Repository navigation
Conversation
…eep/nanosleep stdlib Spike answering "is the compiler ready for async?" — YES. A cooperative fiber scheduler multiplexed over the Io\Poll reactor + timers, with a structured- concurrency API (no fire-and-forget). Pure PHP over Fiber + Io\Poll — zero new codegen. Both demos run clean, no compiler bugs surfaced. spike/async/src/: Scheduler (run-queue + reactor + timer engine) · Task (fiber handle, await) · TaskGroup (structured scope, joins children, propagates the first failure) · Context (ambient scope + cooperative cancel) · api (run/spawn/ delay) · io (accept/read/write — blocking-looking, suspend-on-EWOULDBLOCK). smoke.php: spawn/await/delay/TaskGroup → "sum: 42 / group: 12". echo_server.php: async accept/read/write round-trip → "reply: echo:hello". Validates the full pattern on manticore: arrays-of-task-objects, closures+spread into fibers, rc across suspends, the mixed↔object boundary (Task carried as Io\Poll Watcher data), non-blocking streams over the reactor. stdlib: add usleep / time_nanosleep / time_sleep_until (libc usleep + nanosleep; timespec 16B tv_sec@0/tv_nsec@8). Standard PHP functions, generally useful — promote to main separately.
…core, survives 16 concurrent conns
…poll, ~2x rps Profiling the HTTP server showed 62% of wall time in poll(2) INSIDE fread: the stream stdio layer (fread/fwrite) does its own internal poll per call, which blocks the single-threaded cooperative scheduler — one connection's read stalled every other fiber. With our own reactor (Io\Poll = kqueue/epoll) that poll is pure waste. Async\read/write now do raw non-blocking recv/send on the fd (fd = $conn->addr); a <0 return (EWOULDBLOCK) suspends on the reactor and retries — the reactor is the ONLY thing that waits. stream_set_blocking is set ONCE (accept/connect), not per call (was 2 fcntl syscalls/read). New Async\connect() for the client side (a raw stream must be non-blocking or the raw recv blocks the loop — that deadlocked the echo round-trip until connect() set it). Throughput at concurrency ~doubled: 8 conns 27k->52k, 16 conns 31k->59k, 32 conns ->62k req/s single-core. Echo + smoke still correct. Remaining perf roadmap: persistent fd registration (drop kqueue add/remove churn), cached Date (1/s not per-req), per-connection read buffer reuse, multi-process + SO_REUSEPORT (rps x cores).
Also found: a cached-Date via a static local corrupts under concurrent fibers (json empty / rps collapse / hang) — static local (global cell) vs per-fiber arena. Left Date per-request; Date caching needs a fiber-safe holder. Noted.
…etion (no leak) TaskGroup drops a child once it settles (swap+pop; array_splice isn't implemented) so a long-lived root scope doesn't accumulate finished tasks; the scheduler calls Fiber::reclaim() on termination to free+pool the stack now. A 16k-connection churn holds ~36MB instead of ~413MB. joinAll drains-until-empty since children are pruned live.
…ve 60k→64.5k Two remaining single-core wins from the profile (buf-alloc ~4%, kevent-churn ~5-10%): 1. Reused recv scratch buffer (Scheduler::readBuf): Async\read no longer callocs/ frees per read — one grown-on-demand buffer, shared safely (a read copies out to a string before the fiber can suspend, so cooperative reads never overlap holding it). 2. Persistent fd registration: a connection's fd is added to the reactor ONCE (level-triggered Read) and kept for its life — no add/remove kevent per read. waitReadable just re-suspends; the scheduler wakes only tasks that are actually ioWaiting (persistent watcher stays). Safe against a level-triggered busy-loop because a fiber suspends only after recv/send hit EWOULDBLOCK (fd drained), so the watcher won't re-fire until new readiness. Rare write-block arms Write on the same watcher (modifyEvents) then disarms. Async\close drops the watcher before fclose. waitWritable path for back-pressure. Result: keep-alive 60.0k→64.5k req/s single-core; idle CPU 0% (no busy-loop); 16k-connection churn stays 36MB (watchers cleaned via closeConn). smoke/echo/both endpoints correct.
…scaling) __mc_tcp_listen now sets SO_REUSEADDR (rebind past TIME_WAIT, like php — also fixes the earlier "cannot listen" restarts) AND SO_REUSEPORT (Darwin 0x200/Linux 15), so multiple processes bind the same port and the kernel load-balances accepts across their independent queues — no thundering herd, no locks. Async\workers($n): fork $n shared-nothing workers before run(); each runs its own scheduler+reactor and binds the shared port. The http server forks 8 workers. Verified: 8 worker procs, all bind :8080, serve correctly. (Local RPS is client-bound — 8 workers + N php load procs contend for the same 10 cores — so the per-core scaling isn't visible without an off-box or native load client; server side confirmed working.)
…worker macOS SO_REUSEPORT does NOT load-balance across sockets (one worker got all connections — 96% on 1 core). Prefork — bind ONE listener then fork, workers share the fd and pull connections off a shared accept queue — distributes portably (macOS + Linux): server CPU 96%→211% under the same load. (Local RPS/scaling still client-bound: 40 php load procs starve 8 workers on 10 cores; a native/off-box load client is needed to show ×cores. Linux SO_REUSEPORT would also distribute.)
…s scaling Native client (CONNS fibers × REQS keep-alive requests, one process) is far lighter than php clients, so it can actually drive the multi-worker server: 1-worker (php client): 64.5k req/s 8-worker + 1 native client: 121k (~1.9x) 8-worker + 2 native clients: 169k aggregate (~2.6x) Scaling confirmed; the local ceiling is client+server contending for the same 10 cores (off-box clients would push toward ~Nx). ⚠ 4 concurrent clients (200 conns) hung once — a possible high-concurrency issue to investigate.
…eactor read/write treated every recv/send <0 as EWOULDBLOCK and re-suspended, so a ECONNRESET/EPIPE (also -1, no errno binding to distinguish) looped forever: reactor says fd ready -> syscall -1 -> re-arm -> ready -> -1 ... A hang under connection churn. Fix: with a level-triggered reactor, a <=0 AFTER a readiness wake is EOF or a hard error, not would-block -> wait at most once, retry, then treat as closed. Bounded; no spin. Likely cause of the rare 4-client hang.
… gitignore) Rename spike/async -> poc/async. Add README (model, layout, build, wrk numbers vs go/node/bun). Remove accidentally-committed echo_bin/smoke_bin; gitignore poc/async/*_bin. Keep capture.php + spawncost.php as standalone examples.
Async\Channel over the cooperative scheduler: send/recv park via suspendCurrent() and wake() their counterpart; unbuffered = direct handoff rendezvous, buffered = FIFO buffer with sender promotion on drain; close() wakes receivers (null) and senders (throw). Task gains a chanValue carrier. Async\channel() factory. Demo (chan_demo.php): unbuffered sum 15, buffered FIFO abcde, fan-in 60.
Async\select(Channel[]) receives from whichever channel is ready first. Fast path takes from the first ready; slow path parks the waiter on ALL channels and wakes on the first delivery. Soundness under the cooperative scheduler: Channel::wakeReceiver enforces a single atomic claim — a select-waiter parked on several channels is committed to by exactly the FIRST channel to reach it; a losing channel sees selectClaimed and skips it (no double-delivery). removeRecvWaiter deregisters losers (rebuild, not array_splice). Task gains chanOk/selecting/selectClaimed/chanReady. Demo: select sum 10 across two producer channels drained to close.
…+ non-blocking http fd
Spike -> epic. The engine moves out of poc/async/src into a demand-gated prelude tier (Main.php gates on an `Async` mention and forces Fiber + Io\Poll on), and every structural defect the spike carried is fixed: - scope lives on the TASK (Task->owner / Task->scope), not on a scheduler-global stack: a spawn can no longer attach to another fiber's group, and a nested TaskGroup::run is interleaving-safe; - REAL cancellation: cancelTask deregisters the victim from the reactor slot / timer heap and resumes it with Fiber::throw(CancelledException) at its suspend point. A CancelledException is never escalated as a new failure; - awaitAll is FAIL-FAST: it claims every input BEFORE parking (so a sibling that fails while it waits elsewhere is not mistaken for an unhandled failure and escalated behind its back -- a *caught* error used to still kill the program at exit), cancels + joins the rest, and rethrows the first error; - awaitAny parks directly on the inputs instead of spawning N watcher fibers, so a winner orphans nothing; its AggregateError keys are input-indexed like awaitAll's; - Task::await / joinAll loop on STATE instead of assuming one wake == settled; wake() dedupes via Task->queued; - root scope is joined and the loop reports a DeadlockException instead of exiting rc=0 with tasks still parked; - TaskGroup::run cancels + joins children when the BODY throws (no orphans); - per-fd waiter slots (readWaiter/writeWaiter) replace the single watcher payload, so a reader and a writer on one fd both wake; Write is armed only while a writer waits; - the recv scratch buffer moves onto the Task -- one global buffer that grew via free+calloc handed every parked reader a dangling pointer; - timers become a binary min-heap with lazy delete (was two O(n) scans per tick), childSettled is true O(1), the loop snapshots its batch so a self-requeueing task cannot starve the reactor, and ioWaiters counts WAITING TASKS not registered fds; - the Scheduler singleton is torn down when run() returns, so repeated async() calls in one program get a clean engine. fiber: injectEx/pendingEx must be \Throwable-typed, not mixed. A mixed property holds the throwable NaN-boxed, so `throw $cell` reaching a typed `catch (Foo $e)` dereferenced the boxed word as an object header -> SIGSEGV. catch (\Throwable) needs no class-id test, which is why fiber_throw never saw it. poc/async: demos are single files now (no library, no manifest) -- build.sh compiles them. smoke.php covers the new guarantees: fail-fast + sibling cancellation, a throwing scope body, and interleaved nested scopes.
Phase 3 -- the reported symptom was "file_get_contents is blocking even inside
different spawns". Only the response BODY read was async; DNS, connect(2) and
the TLS handshake all ran synchronously in the fiber, and they are most of the
wall time. Under AsyncHook the socket now goes O_NONBLOCK BEFORE connect(2),
EINPROGRESS parks the fiber on writability and SO_ERROR reports the outcome
(__mc_fd_nonblock / __mc_so_error / __mc_await_connect), and SSL_connect is
driven through WANT_READ/WANT_WRITE parks instead of one blocking call
(__mc_tls_drive_connect). Sockets.php gains EINPROGRESS as __mc_sock_const(12).
Two spawned file_get_contents("https://httpbin.io/..."): 0.94s -> 0.49s, i.e.
one RTT instead of two. Sync mode unchanged at 0.94s.
Io.php: SSL_read returning <= 0 with WANT_READ/WANT_WRITE is a partial record,
not end-of-stream. Reporting it as EOF truncated a TLS response at a record
boundary; it now parks and reads the rest (the optimistic-recv retry above is
KIND_SOCKET-only, so TLS had no recovery path at all).
ROOT-CAUSE 1 -- fiber (prelude/fiber.php): injectEx/pendingEx were declared
"mixed", so Fiber::throw()'s throwable was NaN-boxed; a typed
"catch (Foo $e)" then dereferenced the boxed word as an object header and
segfaulted. "catch (Throwable)" needs no class-id test, which is why
fiber_throw never saw it. Both are Throwable-typed now.
Test: fiber_throw_typed_catch (php oracle).
ROOT-CAUSE 2 -- static props (LowerClasses + MemoryAbi::CELL_NULL): a CELL-typed
module global was initialised to raw 0, but a cell carries its type in a NaN tag
and "=== null" compiles to a tag==3 test. So "public static mixed $cb = null;"
read back as int(0) and "$cb === null" was FALSE for a property nobody had
assigned -- an optional-callback guard passed and called through a null pointer.
That is exactly what crashed fclose() (AsyncHook::closer() outside a scheduler)
and with it net_tcp_loopback / http_parse / socket_addr / unix_socket /
stream_timeout. Cell-typed cells now initialise to the boxed null.
Test: static_prop_mixed_null (php oracle).
NOTE 2-gen: the stdlib .o is built by the PREVIOUS binary, so this fix only
reaches Runtime\AsyncHook's own cells on the SECOND bin/build.
tests/aot: async_structured, async_cancel, async_scope (nested scopes, repeated
async(), deadlock detection), async_channel -- manticore-only, hand-written
expected (difftest skips them, php has no Io\Poll).
The runtime had structure but no way to bound work in time, and cancellation was only reachable implicitly (a scope failure). Both are load-bearing for real programs, so they go in now rather than as a later bolt-on. - async() and the new group() RETURN the body's value, so a concurrent block composes like an ordinary call instead of forcing an out-parameter dance. group() is the everyday form of TaskGroup::run(). - timeout(float, callable): a scope with a deadline. On expiry the body AND everything it spawned is cancelled and joined before TimeoutException is thrown -- a timeout that leaves work running is not a timeout. The body runs as a CHILD task, because only a separate task can be cancelled at its suspend point while this fiber still holds the timer. Deadlines nest by TIGHTENING (TaskGroup::deadlineAt walks the chain for the earliest), so a 30s inner scope inside a 2s outer one still dies at 2s. - Task::awaitWithin(float): per-task deadline; cancels and joins the task it gave up on rather than leaving it unobserved. - Scheduler::awaitDeadline(Task, float) is the single primitive under both: park until the task settles or the deadline passes, returning which happened and deciding nothing. - CancellationToken: the READ half of cancellation. The scope IS the source (TaskGroup::cancel()), and a token is a read-only view of it -- so there is no second cancellation mechanism to keep in sync with the scope tree, and isCancelled() walks the same parent chain the scheduler already uses. Pass a token into a helper to let it observe cancellation without granting it the power to cancel. onCancel() hooks releasing a resource the scheduler cannot see; handlers fire once, synchronously, before the children are cancelled. Context gains token()/deadline()/remaining() for the ambient form. - Every park site now calls Scheduler::checkCancel() BEFORE registering, then suspends -- registering and only then throwing would strand a reactor slot or a timer reservation on the way out. Test: async_timeout. Suite: full AOT run green at 656/656 before this change; async subset 5/5 after. Not done: #[Async]. Unlike the rest it cannot be a library -- it needs the compiler to rewrite the function body and to carry a generic Task<T> through inference. Recorded in the README as a post-runtime item.
Design review of the first cut, before merging. The skeleton held up; three
correctness holes did not.
CORRECTNESS
- Cancellation was ONE-SHOT: step() nulled pendingThrow on delivery, so a task
got CancelledException exactly once. The shape real code is written in --
`try { … } catch (\Throwable $e) { log(); }` -- therefore neutralised it
permanently, and the scope could never close. A 0.05s timeout() over a child
that swallowed once and slept again reported its timeout ~10s late, because
timeout() joins after cancelling. Cancellation is now STICKY
(Task->cancelRequested + Task->shield): every resume and every park site
re-raises until the task actually terminates. Cleanup that must itself suspend
goes in the new Async\shield() -- without an escape hatch a cancelled task
could never close a connection.
- TaskGroup::run() SWALLOWED cancellation and leaked the scope pointer. It
caught \Throwable into fail(), which deliberately treats CancelledException as
"not a failure" -- so a task cancelled inside group() returned null and
carried on, i.e. cancellation stopped at every scope boundary. And
`$cur->scope = $group->parent` ran without a finally, so a join interrupted
mid-way left the task pointing at a closed group. Now: scope restored in
finally, Cancelled always rethrown, and a join interrupted by our own
cancellation cancels the group and re-joins SHIELDED so children are still
reaped. Same shielded-join in timeout() and awaitAll().
- cancelTask() released the reactor slot and the timer but not CHANNEL queues.
A cancelled receiver is still PENDING, so wakeReceiver's settled-check let it
through: an unbuffered send handed the value over, returned as if delivered,
and the message died with the task. Symmetrically a cancelled sender's value
was still taken by a later recv. Now Task->chanHost / ->selectChans track the
park, Channel::removeWaiter rebuilds recvQ and the sendQ/sendVal pair in
lockstep, and both claim paths check cancelRequested.
CONTRACTS
- CancelledException extends \Error, not \RuntimeException, so the most common
blanket catch in PHP -- catch (\Exception) -- cannot see it at all. Sticky
delivery covers catch (\Throwable); this covers the rest.
- onCancel handlers are isolated: cancel() is reached from inside the scheduler
loop (settle -> fail -> cancel), so a throwing handler is recorded as the
group's failure rather than unwinding the loop.
- awaitAll() now only cancels tasks OWNED by the caller's scope subtree
(TaskGroup::owns). A task borrowed from an enclosing scope, which someone else
may still be awaiting, is left alone; the ownership contract is documented.
API GAPS
- Async\Semaphore (acquire/release/withPermit) and Async\mapConcurrent(items,
fn, limit) -- "fetch 1000 URLs, 10 at a time" needed a hand-rolled channel.
- select() gained send cases via Async\SelectCase::recv()/::send(), with the
mirror of the existing single-claim rule on the sender side, plus the two
non-blocking forms selectNow() (Go's default:) and selectWithin() (time.After).
- Context::value()/withValue() -- scoped values for request-id propagation,
falling out of the parent-chain walk that was already there.
PHP INSTEAD OF TRANSLITERATED GO
The model is Go's; the spelling should not be.
- select() returned array{int,mixed,bool} because Go has multi-return. It now
returns Async\Selected (index/value/ok/channel/isSend), and the comma-ok
receive is Async\Received (value/ok) from Channel::next().
- Channel implements IteratorAggregate: `foreach ($ch as $v)` replaces
`while (($v = $ch->recv()) !== null)`, which was a Go loop in PHP and could
not carry a legitimate null payload. recv() stays as the terse form.
ChannelIterator is a plain Iterator, not a generator -- each call is an
ordinary frame on the fiber's stack, so parking inside it is just a suspend.
- ChannelClosedException instead of a stringly RuntimeException -- and it
matches the project's own sentinels-become-exceptions direction.
- The raw fd layer (Async\read/write/accept/connect/close) moves to an
@internal section: fread/fwrite/stream_socket_accept already suspend through
the netpoller and are what PHP code should be written against. The functions
stay for the syscall-count benchmarks.
Tests: async_cancel_sticky (sticky, not-an-\Exception, shield, group unwinding),
async_channel_cancel (no message lost either side), async_concurrency
(max-in-flight bound, fail-fast, scoped values), async_channel rewritten for
foreach/next/send-select/selectNow/selectWithin/typed close.
Verified: async 8/8, fiber 9/9, iopoll 2/2; http_transparent 149.8k rps (no
regression); two spawned HTTPS fetches still ~half the sync wall time.
Round 3 phase A. The question was "atomics, maybe a mutex?" -- atomics would be cargo cult here and are deliberately absent: the scheduler is cooperative and single-threaded, so nothing runs between two suspend points and an ordinary read-modify-write is already atomic by construction. That invariant is now stated in the file header and the README, because it is what makes half of the usual synchronisation vocabulary unnecessary here. What is NOT free is a critical section that SUSPENDS in the middle: - Mutex -- non-reentrant (a self-lock is a LogicException, not a hang), FIFO, lock/tryLock/unlock/withLock. The test shows the difference plainly: two tasks writing around a delay produce "aAbB" under the lock and would interleave without it. - Once -- run() memoises the value or the error, so a lazy initialiser that suspends is built exactly once however many tasks race for it. A CANCELLED initialiser resets to fresh: it is not a result, and the next caller must not inherit someone else's cancellation. Ergonomics and outcome collection: - Task::cancel() -- cancelling one task no longer means reaching into Scheduler::instance()->cancelTask(). - Task::join(): Settled -- wait WITHOUT rethrowing. Found while writing the test: "$t->cancel(); $t->await();" raised the task's own CancelledException into a caller that was not being cancelled, which unwound the caller's scope and silently ended the program at rc=0. join() is what you want after cancelling something yourself. - Scheduler::run() now rethrows a CancelledException that reached the top while the root was NOT actually cancelled. Deliberate shutdown sets cancelRequested and still returns normally; a leaked one used to end the program silently. - Settled (ok/value/error) + awaitAllSettled() + mapSettled(): the "fetch a hundred and tell me which failed" shape, keyed by input position, never throwing and never cancelling the survivors. mapSettled wraps each body so no child ever reaches FAILED -- a real failure would trip the group's fail-fast and cancel the siblings, which is the opposite of what was asked. Tests: async_sync, async_settled. async suite 10/10.
…wn on it A server that cannot handle SIGTERM does not ship, so signals go in as a global pcntl-style facility that works with or without the scheduler -- not as a hook bolted onto the loop. THREE TIERS, each with one job: - src/Runtime/Libc.php -- the syscalls: sigemptyset/sigaddset/sigismember, sigprocmask/sigpending/sigwait, signal, kill, fork, waitpid, getpid, getppid, alarm. - src/Runtime/Stdlib/Pcntl.php -- policy, SCALARS ONLY. No callables, no statics holding anything with a refcount, no array built here and handed back out. That is forced: an array built inside the stdlib does not survive being parked in a static and returned to user code (__mc_http_headers_store documents it), and a signal registry holds CALLABLES, which cannot be flattened to a refcount-free scalar the way that workaround does. So pcntl_sigprocmask's old-mask comes back as a BIT SET, not a list. - prelude/pcntl.php -- the registry and the php-facing functions, in a module the user's own program compiles. Demand-gated on the pcntl_*/posix_* names; Async\ forces it on. MECHANISM. A C handler cannot be a PHP closure, so pcntl_signal() never installs one: it BLOCKS the signal -- the default action cannot fire and the kernel keeps it pending -- and records the callback. pcntl_signal_dispatch() reaps with sigpending(2) + sigwait(2), a pair that exists on both hosts (sigtimedwait does not: Darwin lacks it) and returns immediately for a signal that is both blocked and pending. php's own pcntl is likewise deferred, so the observable contract is the same. The one documented divergence: a blocked signal never interrupts a syscall with EINTR. For a cooperative loop that is a feature. CONSTANTS were MEASURED, not recalled: a C probe compiled and run on Darwin arm64, gcc:13 (glibc) and alpine:3.20 (musl). The two Linux libcs agree; Darwin differs on eleven signals AND on the SIG_BLOCK family (1/2/3 vs 0/1/2), which is exactly the kind of thing that is silent on one host if guessed. They resolve in LowerPrelude like FNM_*/SO_*, and Pcntl.php names none of them -- a compile-time host probe reachable from a stdlib path kills the Zend cold seed. ASYNC INTEGRATION. Async\onSignal / Async\shutdownOn / Async\supervise. The dispatch runs in a DAEMON TASK in the root scope, not at the loop level. That was a real design correction: a handler running between tasks has no scope, so spawn() threw "outside async()" and $this->running was null under it. As a task it is ordinary async code -- it can spawn, suspend, and be cancelled with everything else -- and its own delay() bounds latency, so the reactor needs to know nothing about signals. Task->daemon keeps such work from counting towards "is there still work?", or the pump would pin every program open forever. shutdownOn() cancels the ROOT scope and everything else follows from cancellation already being structured: connections raise CancelledException at their suspend point, scopes join their children, shield() covers a final write, and async() returns normally because a root cancellation is a shutdown, not a failure. poc/async/server.php demonstrates the whole shape -- four supervised workers, keep-alive HTTP, SIGTERM to the group, every worker reporting a clean drain and the supervisor exiting. FOUND WHILE BUILDING IT: unset() on a VEC element is a silent no-op. The array runtime notes it as deferred (it needs hole/shift semantics), but nothing warns at the call site, so Supervisor's pid map never shrank and the reap loop spun forever. Worked around with the rebuild pattern used elsewhere in the file, with the reason recorded at the site. Reported separately -- it is a parity gap, not an async one. Tests: pcntl_signal (php oracle, difftest MATCH 1/0) and async_signal (manticore-only). async 11/11, pcntl 1/1, fiber 9/9, socket 14/14, net 3/3 -- after TWO generations, since Libc/LowerPrelude/stdlib all moved together.
…ntl_signal work Layering fix, prompted by the right question: is a signal really part of the async namespace? Mostly it is not. - Process\ (new, in the pcntl tier) takes fork/pid/ppid/workers/supervise. None of that runs a scheduler -- supervise() forks, reaps, restarts and forwards SIGTERM, and Async\supervise() implied a runtime that supervision never has. The process model sits UNDER concurrency, not inside it. - Async\onSignal is gone. The scheduler notices a non-empty pcntl registry and starts the pump itself, so ordinary `pcntl_signal(SIGHUP, ...)` just works inside async() -- one way to register a handler, and it is the standard one. - Async\pid() is gone (it was posix_getpid() under another name), along with the duplicate sys_fork/sys_getpid FFI declarations in async.php. - Async\shutdownOn() stays, and is now the only signal-aware thing in Async\. It earns that by being about SCOPES: it cancels the root scope, and the rest falls out of cancellation already being structured. Two things this shook out: - The lazy pump start has to be checked immediately BEFORE the blocking reactor wait, not at the top of the loop. A worker parked in accept() reaches the top again only once the reactor returns, so an idle one started no pump and never saw its SIGTERM -- in the four-worker demo exactly one worker drained (the one curl had woken) and three hung. Checked before the block, the pump lands in the ready queue and its own delay() then bounds the wait. - The gate cannot use definedFunctions() for this tier any more: it now defines fork/pid/workers/supervise, which are names a program may well own. pcntl_* and posix_* are prefixed and stay gated on the call; Process\ is gated on the qualifier, exactly as Async\ is. Verified: a program defining its own workers() and supervise() compiles and runs untouched. poc/async/server.php, http_server.php, http_transparent.php and async_signal move to Process\; async_signal now registers with plain pcntl_signal to prove the auto-pump. async 11/11, pcntl 1/1 (difftest MATCH), fiber 9/9; the four supervised workers all drain and the supervisor exits.
…sure's implicit return is boxed null Two general repr bugs, both on the dynamic-callable edge — found while wiring a fourth AsyncHook slot whose callback has to report a bool. 1. InferCalls::inferInvoke had no branch for a CELL/UNKNOWN-typed callee, so `$h = Hook::get(); $r = $h(41);` left the invoke untyped and every consumer read the tagged word RAW: int(42) printed as int(-4222124650659798), a bool printed as an int and `=== true` was false, a string decoded as a pointer, is_array() on an array return was false. The uniform closure ABI boxes the callee's return, so the invoke is a cell — the same reasoning the DynProp_ and string-callee branches above it already use. 2. A closure's IMPLICIT return (fall off the end, or a bare `return;`) emitted raw 0, which a by-tag reader decodes as a float — so a void callback's result was not === null. Closures and trampolines now return MemoryAbi::CELL_NULL; every other function keeps the raw 0 its typed caller ignores. Only void hook callbacks existed before, which is why the corpus never saw this. An OBJECT return still rides raw (documented at the fix site): boxing it would have to be matched by an unmask in every typed callee path. Test dyn_callable_return_repr (php oracle). Verified over two build generations; closure/callable/array/generator/fiber/async/oop/object/sort/union/usort/map subsets green.
The INITIALISER half of this landed earlier in the epic (LowerClasses +
MemoryAbi::CELL_NULL); the ASSIGNMENT half never boxed at all, so every store
into a `public static mixed $x` wrote a RAW word while the read side decodes by
tag:
C::$s = 42; var_dump(C::$s); // float(2.08E-322)
C::$s = 'str'; var_dump(C::$s); // float(2.14E-314)
C::$s = null; var_dump(C::$s === null) // false
That last line is why fclose() SIGSEGV'd after any async() run:
AsyncHook::clear() assigns null to each hook slot, the slot then read as
NOT-null, and fclose()'s `$oc !== null` guard called through a null closure.
Only closures had been parked in those slots before, and objects legitimately
ride raw — which is why the corpus never saw it.
StoreStaticProp_ gains a trailing nullable `$declared` (InferTypes overwrites
`$type` with the assigned value's type, and the emitter has no static-prop type
table); LowerExprs passes the declared type it already resolved, NodeClone
propagates it, and emitStoreStaticProp boxes when the slot is cell/unknown and
the value is cell-boxable. Retain still happens on the RAW pointer before the
box; a float is boxed from the double register (via i64 first, box_float read
1.5 as 4.6e18). Arrays/objects stay raw, exactly as an instance cell-property
does — documented at the fix site.
Test static_prop_mixed_store (php oracle). class/oop/object/static/enum/closure
/array/net/socket/fiber subsets green.
…adlines, non-blocking listeners The seam had no BOUNDED wait, so three things were broken under a scheduler: 1. stream_set_timeout() was silently ignored. __mc_wait_read parked forever via the readable hook and dropped $rtimeoutMs, so a peer that accepts and never writes wedged the reading fiber and ['timed_out'] could never become true (the synchronous path has a 60 s floor). Now a bounded park with the same deadline, and expiry records timedOut and returns 0. 2. stream_socket_accept($timeout) fell into the SYNCHRONOUS branch, whose poll(2) blocked the whole scheduler. It now uses the bounded wait against an absolute deadline, so a lost accept race cannot extend it. 3. ⚠ The LISTENER was never O_NONBLOCK. accept(2) on an idle blocking listener blocks the PROCESS — every timer, every other connection and the signal pump with it — and this path attempts an accept before it ever parks. A listener is normally created before async() starts, so the accept site marks it. AsyncHook gains a 4th slot, `waitReadableFor: fn(\Resource, float): bool`, over Scheduler::waitReadableWithin — one park holding BOTH a reactor slot and a heap timer, releasing both on either exit path (cancelTask already drops both, so a cancelled bounded wait leaks neither). Also: A WAKE IS A HINT. The plain-socket recv path reported 0 (= end of stream) on the first EWOULDBLOCK after a wake, and the write path treated it as a hard error and ended the write short. Both now loop — would-block re-parks, only a real errno stops them. Test async_stream_timeout (manticore-only: php has no Io\Poll).
…() exists at all Every retry/backoff loop in third-party code is written with these, and they went straight to libc — one task sleeping froze every other task in the scheduler. A 5th AsyncHook slot (`sleeper: fn(float): void` over Scheduler::sleep, which is already cancellation- and daemon-aware) makes them park instead; with no scheduler they fall back to the libc sleep unchanged. `sleep()` itself was MISSING from the stdlib — it reached clang as an undefined symbol, i.e. any program calling it failed to compile. The scheduler's own idle usleep() runs outside every fiber and AsyncHook::active() requires \Fiber::getCurrent(), so this cannot recurse into the loop it is called from; noted at both ends. Test async_sleep_transparent: three tasks sleeping 60/20/40 ms overlap and complete shortest-first.
…4967295 ★ THE ROOT CAUSE of the intermittent SIGBUS/SIGSEGV on any https:// read inside async(). Bisected to before this session's work (ad943e5 crashes 4/4), which is why the epic's own "network fully async" claim only held for plain sockets. An FFI extern declared `: int` was emitted as `declare i64 @sym(...)`. A C-compiled callee returning -1 does `mov w0, #-1`, which ZEROES x0's upper half, so the wrapper read 0x00000000FFFFFFFF = 4294967295. SSL_read's return is used as a BYTE COUNT: __mc_stream_fill took the "got > 0" path and memmove'd ~4 GB from a bogus pointer. Hand-written libc syscall stubs write the full x0 (their -1 IS sign-extended), which is exactly why only the C libraries were exposed and why every socket test passed. Sync mode never saw it either: a BLOCKING fd makes SSL_read return >0, so -1 only appears once the netpoller sets O_NONBLOCK. Fix at the boundary rather than by caller convention (the file header used to say "callers compare > 0 / === 1, never a raw i64" — __mc_stream_fill legitimately needs the number): a FUNCTION-level `#[CType('int')]` now declares the C RETURN as 32-bit, and emitFfiWrapper sign-extends it. Applied to the 12 OpenSSL binds whose C prototype really returns int; deliberately NOT to the pointer-carrying ones (SSL_CTX_new / TLS_*_method / SSL_new) or SSL_ctrl (returns long), where a sext would truncate. Verified: 6/6 clean runs of three https-in-async shapes that previously crashed 4/5, `got` now reads 864/5 instead of 4294967295, and two spawned fetches to DIFFERENT hosts run 0.17s vs 0.34s sequential. Regression check lives in poc/async/tls_async_smoke.php (network-dependent, so not in the offline suite).
Follow-up to the would-block loops: the errno test was positive-polarity (`errno !== EWOULDBLOCK` → hard error), and errno is not reliably set on every recv(2)/send(2) failure path. A stale or zero errno therefore ended a read at ZERO bytes with the data still in flight: a 32 KB loopback response inside async() read as 0, and a bounded accept reported no connection while one was pending. Now inverted — EWOULDBLOCK / EAGAIN / EINTR / 0 park and retry, and only a recognised hard errno (EPIPE, ECONNRESET, …) stops the transfer. Conservative direction is "wait", not "declare end of stream". Verified with a loopback server that delays 100 ms then writes 32 KB inside a scheduler: 32768 bytes, 6/6 runs, both with and without an accept deadline.
The runtime ships in prelude/async.php as part of the standard distribution, so the demos belong beside the other examples and the guide beside the other docs. `poc/` is gone entirely. poc/async/*.php → examples/async/*.php (11 demos + build.sh + the TLS smoke) poc/async/README.md → docs/async.md Path references updated in .gitignore (the ignored `*_bin` glob), build.sh, server.php, tls_async_smoke.php and the two source comments that pointed at the old tree; every `poc/async/` in the doc became `examples/async/`. build.sh also builds `server` now (it was added after the list was written) and says why tls_async_smoke is excluded. Verified: `bash examples/async/build.sh` — all 11 demos compile.
…hangs anyway
Two ways an async program could still hang forever, and the tooling to see either:
1. `__mc_await_connect` parked on writability with NO deadline, so a connect to a
black-holed address never returned and fsockopen's 5th argument was silently
ignored under a scheduler. `__mc_tls_drive_connect` was worse — its comment
claimed it was "bounded only by the peer", but a peer that completes the TCP
handshake and then goes quiet mid-flight produces neither readiness nor an SSL
error. Both now take an absolute deadline: a 6th hook slot `waitWritableFor`
(the writable twin of the read-side bounded wait), the caller's timeout threaded
through fsockopen / stream_socket_client / __mc_transport_connect /
__mc_tcp_connect / __mc_tls_connect / __mc_tls_handshake, and ETIMEDOUT reported
through __mc_net_errno so the error message matches php's. 0.0 = "unspecified" →
the same 60 s default_socket_timeout floor the read path uses.
ETIMEDOUT is MEASURED: Darwin 60 (cc probe + php's SOCKET_ETIMEDOUT), Linux 110
(asm-generic, glibc and musl agree).
2. There was no way to ask a hung program what it was doing: tasks had no identity,
and DeadlockException said only "all tasks are asleep". Now
`spawn(…)->named('http')` labels a task, and `Async\dump()` returns the whole
engine as text — live/io-parked/timer/ready counts, then one line per live task
with what it parks on (`io-read fd=7 +deadline`, `timer`, `channel`,
`select(2 channels)`), `*` marking the running one, and `daemon` /
`cancel-requested` / `shielded` / `awaited` flags. DeadlockException embeds it, so
the failure now reads `#2 "blocked-receiver" channel` instead of a shrug.
Enumeration uses an intrusive doubly-linked list of live tasks on the Scheduler
(`Task->allNext/allPrev`, O(1) link on spawn and unlink on settle): the scope tree
cannot answer it, because settled children are pruned and a nested group's children
hang off that group rather than the root.
Tests: async_connect_timeout (offline-safe: prints no elapsed times, and RETURNING
at all is what it pins down) · async_diagnostics (asserts the report's shape, not fd
numbers). async 19/19.
Ф8c. `Async\readFile()` was the opt-in fix; plain `fread()` / `file_get_contents()` on a regular file still handed libc one enormous read and stalled every other task for its whole duration. Both now go through `__mc_file_read_yielding()`: a single libc call below 1 MiB or outside a scheduler (byte-for-byte the old behaviour), and 1 MiB pieces with a yield between them above that. Measured, 64 MB page-cache-hot file, 1 ms ticker beside the reader: before worst tick gap 15-25 ms after worst tick gap 5.7-6.7 ms Async\readFile worst tick gap 2.3-2.9 ms The residual ~6 ms is the one thing chunking cannot split: `str_from_buffer()` copying the finished 64 MB into a headered string. `Async\readFile` avoids it by building the result incrementally, which is why it stays the better tool for genuinely large files — now a preference, not a correctness cliff. Sync mode verified unchanged (64 MB in 0.015 s, bytes identical via both paths); fs 7/7 · file 3/3 · read 16/16 · write 4/4 · stream 10/10 · async 19/19, two generations.
…ositive
**Cold seed (`bin/compile`) was broken on this branch** — the gate's
rebuild-stability stage died on it:
compile failed (emit): Manticore\calloc(): Return value must be of type
Ffi\Ptr, none returned (src/Manticore/Main.php:27)
`host_os()`/`host_arch()` reached for the libc `calloc`+`uname` FFI pair, which is
an EMPTY STUB when the compiler itself runs under php. Harmless while nothing in a
compiler pass called them — and that stopped being true the moment the compiler's
own source started demanding fibers: `src/Runtime/AsyncHook.php` mentions `\Fiber`,
so the demand gate turns fibers on for the compiler build, and the fiber preamble
emits arch-branched `module asm`, which needs the host arch. Cold bootstrap has been
dead on this branch since AsyncHook landed; the earlier session recorded the symptom
as a `str_bytes` bootstrap quirk, but this is the real cause.
Both now go through `php_uname()`, the ONE primitive that exists in BOTH worlds:
php's builtin under the seed, the stdlib's uname(2) wrapper natively. It also
deletes the hand-walked utsname stride table (Darwin _SYS_NAMELEN 256 vs glibc/musl
_UTSNAME_LENGTH 65) and, with it, the "never call host_os() from an emitter" rule.
`bin/compile` now returns 0 end to end (3m39s, stdlib included).
**difftest flagged async_stream_timeout as a DIFF.** It skips a case as
manticore-only when php produces NO stdout for it; that test var_dump'd one line
before its first `async()`, so php printed something, failed, and the file looked
like a real divergence. The assertion is folded into the report after the async
block, and the constraint is now written at the top of the file. All five async
cases: 5 PHP-SKIP, 0 DIFF.
Gate run 1 — two failures, both fixed; re-runningFull AOT suite: 682/682 ✅ and the self-host fixpoint itself was clean (IR 1.
2. difftest reported a DIFF on Also in since the PR was opened (Ф8 — "no silent hangs, and something to look at"):
Gate is running again on |
…ded them Ф9a. Writing the TLS-under-async regression test — the one whose absence let the FFI sign-extension bug live — turned up two more real gaps. **1. Server-side `SSL_accept` was not netpoller-aware.** `__mc_tls_accept` called it straight, on a blocking fd, so every client handshake froze the whole loop — and a single-process TLS loopback (server task + client task) DEADLOCKED: the server sat inside SSL_accept waiting for a flight only the parked client could send. That is why the epic's earlier note claimed "a single-process loopback would deadlock"; it was a missing drive loop, not a law of nature. Now `__mc_tls_drive_accept()` mirrors the client-side driver: the accepted fd goes O_NONBLOCK first, each WANT_READ/WANT_WRITE parks on the reactor, and an absolute deadline means a client that opens TCP and never speaks TLS cannot pin a task (slowloris-on-handshake). **2. `__FILE__` and `__DIR__` compiled to the EMPTY STRING.** Every other magic constant was handled; these two fell through. So `require __DIR__ . '/x.php'`, a config path, a fixture path — the way real code finds a sibling file — silently resolved against the filesystem root and `file_exists()` answered false with nothing to explain it. (It is what made my own test hand `false` to `stream_socket_accept()`.) They now fold at PARSE time, where the file identity still exists: lowering only ever sees statements flattened across every file of the build. `Parser::parseSource()` takes the path, `lower_module()` passes `realpath()` of it, and the values are byte-identical to php. Tests: `async_tls_loopback` — a real TLS handshake BOTH ways in one process over the scheduler, 32 KiB across several records read back exactly, plus a third task that completes all its ticks to prove neither handshake stalled the loop (fixture cert: self-signed 127.0.0.1, `tests/aot/fixtures/tls_localhost.pem`, valid to 2046) · `magic_file_dir` — php-oracle, asserting only path-relative facts so it stays machine-independent. Two generations green; async 20/20 · net 3/3 · socket 14/14 · stream 10/10 · ssl 2/2 · magic 5/5.
…accept park Ф9b, the last MUST from the gap review. `Sockets.php` consulted AsyncHook NOWHERE, so the whole socket_* family blocked the LOOP: one `socket_read` stalled every task, and a program mixing ext/sockets with async had a scheduler in name only. The stream layer has been netpoller-aware for a while — this closes the two-tier gap so both socket APIs behave the same way under `async()`. The seam speaks `\Resource` while ext/sockets hands out `\Socket`, so `__mc_sock_park()` carries the fd to the reactor on a throwaway \Resource (the bridge `__mc_await_connect` already used) and detaches it before it dies, or its destructor would close the caller's fd. `__mc_sock_async_prep()` marks the fd O_NONBLOCK once (and `\Socket` gains a `$blocking` flag that socket_set_nonblock/_block keep honest), `__mc_sock_wouldblock()` is the same negative-polarity errno test the stream layer uses — only a RECOGNISED hard errno ends a transfer, an unknown one parks. Each call retries after its wake, because a wake is a hint: accept, socket_read (both the bulk and the byte-at-a-time mode), socket_recv, socket_write, socket_send. Outside a scheduler every one of them is byte-for-byte what it was. Test async_socket_family: a socket_* server task and client task in ONE process exchange ~9.7 KiB exactly while a third task completes all its ticks — accept runs before the client exists, so a blocking call would deadlock rather than merely stall. socket 15/15 · async 21/21 · net 3/3 · stream 10/10, two generations; difftest on the three new cases: 1 MATCH (magic_file_dir), 2 manticore-only skips, 0 DIFF.
… tests
Gate run 2 came back rc=1 with `use of undefined value '@manticore_str_bytes'` while
everything that matters was green — suite 684/684, difftest 0 DIFF, fixpoint
IR-byte-identical, self-host 684/684, MIR golden 108/108. The branch was fine; the
GATE was standing on its own foot.
`bin/compile` rebuilds the CHECKOUT's toolchain as a side effect — bin/manticore and
lib/manticore_stdlib.{o,sig} — even when the binary it is asked for goes to $WORK.
`selfhost_stability.sh` runs it N times and then hands `bin/manticore` to the self
front-end loop, so by then the compiler under test has been replaced N times over. One
imperfect seed build poisons every later stage, and the developer's checkout is left
unable to build itself (mine could not: `bin/build` failed on the stdlib, a user
program failed to link `__mir_var_dump`).
Now the script snapshots bin/manticore + lib/manticore_stdlib.* up front, restores them
from an EXIT trap whatever happens, and drives the self loop from the snapshot — the
binary the gate was actually asked to test. Verified: md5 of bin/manticore identical
before and after a run.
Second half of the same bug: both rebuild loops ran their builder unguarded under
`set -e`, so a failed rebuild killed the script with NO diagnosis — which is why the
gate printed a bare header and exited. Each loop now reports
`zend-buildN: FAIL (bin/compile: …)` / `self-buildN: FAIL (…)` and keeps going.
That reporting immediately paid for itself: it caught a cold-seed break I had just
introduced in Ф9a — `lower_module()` called `\__mc_abs_source_path()` with a leading
backslash, i.e. the GLOBAL namespace, while the helper lives in `namespace Manticore`.
Manticore flattens namespaces so it resolved natively; php does not, so the Zend seed
died with "Call to undefined function". Unqualified now. `bin/compile` is rc=0 again
(3m38s).
Gate run 2 + Ф8/Ф9 updateEverything that measures the code was green: full suite 684/684 · difftest It still exited 1, and the cause was the gate standing on its own foot: Fixed in the tool: snapshot Since the last comment (Ф9)
Gate run 3 is going now on |
…h a real home
Ф10's resolver half. What landed in Ф2 was the minimum that worked: ONE nameserver, A
records only, UDP only, no cache. Each of those is a way for a real deployment to get a
wrong or slow answer.
- **Every nameserver, twice each, 2 s per attempt** (`__mc_dns_nameservers()` returns
them comma-joined — a string, so the value crosses any boundary unharmed). A dead or
slow first entry in resolv.conf no longer fails the whole lookup.
- **TC → retry over TCP** (`__mc_dns_truncated()` + `__mc_dns_exchange_tcp()`, 2-byte
big-endian length framing both ways, per RFC 1035). A host with a large RRset used to
resolve to whatever fragment fit in 512 bytes, or to nothing.
- **AAAA after A**, so an IPv6-only name resolves asynchronously instead of falling back
to the blocking walk. Nothing downstream needed changing: the literal goes back into
`getaddrinfo`, which takes v6 literals as happily as v4.
- **A per-run cache in the SCHEDULER**, reached through two new hook slots
(`dnsGet`/`dnsPut`). This was the open question — a stdlib static cannot own an assoc
(the array-repr trap) — and the scheduler is the right owner anyway: `async()` drops
the singleton on the way out, so no entry survives into the next run to go stale. Two
parallel assocs (ip + expiry, no nesting), record TTL capped at 5 minutes because a
cache we cannot invalidate must not outlive a deployment change.
Verified live: `nameservers` parsed from resolv.conf · second resolve of a host served
from cache · `ipv6.google.com` → a v6 literal · `dns_get_record('google.com', DNS_A)` = 6
records. Offline test `async_dns_resolver` covers the hosts-file step, the TC-bit reader,
and cache hit/miss/expiry/per-run-isolation. async 22/22 · dns 3/3 · net 3/3 ·
socket 15/15 · stream 10/10, two generations.
Signal latency (the other half of Ф10) is documented in docs/async.md instead of
half-built: it needs `EVFILT_SIGNAL` on kqueue and `signalfd` on Linux — two separate
backends with their own measured constants.
tools/docker/run_tests.sh already built from source in a container and ran the suite; --gate adds difftest (php is in the image) and selfhost_fixpoint (fixpoint, self-host suite, MIR golden, rebuild-stability) and fails if any stage does. Stability is parameterised (MC_STABILITY_N, 2x2 by default in a container, 5x5 on the host) because each Linux cold seed is minutes. Rationale, from this session: macOS green says nothing about the epoll path, the Linux socket/errno constants, or a glibc free() — the invalid-free earlier in the epic was tolerated by macOS and aborted on glibc.
… could not assemble)
Found by the FIRST Linux gate run, in its first minute:
<inline asm>:36:29: error: unexpected token in argument list
adrp x3, mc_fiber_trampoline@PAGE
<inline asm>:37:33: error: invalid specifier '@PAGEOFF'
build: clang -c (library) failed for lib/manticore_stdlib.o
Taking the trampoline's address is the one object-format-specific line in the arm64
fcontext asm: Mach-O spells the halves of a PC-relative symbol reference
`@PAGE`/`@PAGEOFF`, ELF spells the low half `:lo12:` and needs no suffix on the high
half. The Mach-O form does not assemble on Linux at all.
It went unnoticed because the fiber preamble is DEMAND-GATED and nothing on Linux used
to demand it — until `src/Runtime/AsyncHook.php` started mentioning `\Fiber`, which makes
every build (the stdlib library included) pull the preamble in, on every target. So the
whole Linux port has been unbuildable since AsyncHook landed, and only a Linux build
could say so. macOS x86_64 was never affected: that variant uses
`leaq sym(%rip), %rax`, which is valid in both formats.
macOS arm64 verified unchanged (@page still emitted there): fiber 9/9 · async 22/22 ·
iopoll 2/2.
…EN await bug with a repro
First Linux gate run: suite 679/688, difftest 1 DIFF + a script crash, fixpoint's
self-host suite failing the same 9 cases. Triage, in three buckets.
**1. Tests that cannot have ONE expected output on every host.** `run.sh` now prefers
`expected/<name>.<os>.out` over `expected/<name>.out` (`darwin`/`linux` from `uname -s`).
`iopoll_kqueue` builds a Kqueue backend that does not exist on Linux — it now catches
`BackendUnavailableException` and says so, with a `.linux.out` to match, instead of dying
with an uncaught fatal the gate read as a regression. (`socket_cmsg` needs the same
treatment: a cmsg header is 16 bytes on Darwin, 24 on Linux, both matching php — left for
the next Linux round, where I can capture its real output.)
**2. difftest crashed exactly when it had nothing to report**: `${#COMPILES[@]}` with
`set -u` on an array that was declared but never assigned →
`COMPILES: unbound variable`. Assigned empty now.
**3. ★ An OPEN runtime bug, with reproducers checked in** (`tests/aot/repro/`, skipped by
the suite since they have no `expected/`): a task that PARKS inside a callee can hand back
the WRONG value through `Task::await()` — a `fread($c, 5)` reader returns the int **5**,
its own length argument, printed as `string(5) "5"` with `strlen() === 1`. The `_noio`
variant needs no sockets: `delay()` inside a callee is enough. Each half of the shape is
clean in isolation (see the memory note for the full ruled-out list); it needs a
suspending callee whose result flows through a `=== false` ternary plus an awaited cell
consumed more than once — which is what ordinary stream code looks like.
`async_shared_stream` is therefore left asserting the order-INDEPENDENT truth
(`both-halves`, since which reader gets which half is not promised) and is RED on macOS
until that bug is fixed — deliberately, rather than pinned to a wrong expected value.
Its Linux timeout (rc=124) may be the same bug or a second one.
`exit;` without parentheses is valid php and reaches lowering as a CONSTANT: "MIR.lower: unknown constant exit". Worked around at the one call site and noted there; the parser/lowering gap itself is filed for later (php also allows `die;`).
…ed it
The return path releases every owned rc local except the one being handed back — but
"the one being handed back" was recognised ONLY for a bare `return $x;`
(`$v->kind === KIND_LOAD_LOCAL`). Any expression that YIELDS a local — a ternary, a
short ternary, `??` — fell through, so the local was released while its value was
returned:
tern.end.2:
%r18 = call i64 @__manticore_box_ptr(ptr %r17) ; return $d
call void @__mir_rc_release_str(ptr %r8) ; ...and free $d
ret i64 %r18
Invisible whenever the caller read the value before anything else allocated, and
visible the moment something did. A closure return was enough, because it boxes:
$fn = function (): string { $d = str_repeat('x', 5); return $d === false ? 'F' : $d; };
$fn(); // string(5) "5" ← bytes of an unrelated allocation
`$x === false ? … : $x` is THE `string|false` idiom, so this sat under every stream read
in the async epic: a task doing `fread($c, 5)` handed back the integer **5** — its own
length argument — through `Task::await()`. Two days of that looked like an async bug
(the value only corrupts once a park makes the caller allocate in between), which is why
the trail started at `async_shared_stream`.
`returnedLocalNames()` now collects every local the returned value may alias — LoadLocal,
both ternary arms (the short form's condition IS its arm), both `??` operands, recursively
— and the cleanup exempts the set. Conservative by design: a name kept here leaks at
worst, a name missed corrupts. The separate "is this a bare borrowed-obj passthrough?"
question keeps its single-name form.
Test return_expr_keeps_local (php oracle): ternary/short-ternary/`??`/nested arms, in a
plain function, in a closure, and through an untyped slot, each with an allocation right
after to reuse a freed block. Two generations green; async 22/22 · array 100/100 ·
string 44/44 · closure 17/17 · return 22/22 · oop 16/16 · socket 15/15 · stream 10/10 ·
dns 3/3 · fiber 9/9. async_shared_stream (deliberately red since the last commit) passes.
…ck as 4294967295
The OpenSSL fix earlier in this branch was half the story. On DARWIN most libc entry
points are hand-written syscall stubs that write the whole x0, so their -1 arrives
sign-extended and the bug is invisible. On LINUX every one of them is an ordinary C
function in glibc: it writes only w0, and an `i64` declare reads the zero-extended
value. Measured in the container, on a non-blocking listener with nothing pending:
accept raw = 4294967295 is negative? NO
connect raw = 4294967295
So `$fd < 0` was FALSE, 4294967295 was treated as a valid fd, and everything downstream
followed: `stream_socket_accept()` reported a connection that did not exist (a loop
counting queued connections found "6" after ONE client), reads on the bogus fd hung, and
the TLS loopback client timed out. That is the whole of the Linux async failure set —
seven tests — and it is why macOS stayed green throughout.
40+ `Runtime\Libc` binds whose C prototype really returns `int` now carry
`#[CType('int')]`: the socket/poll/epoll/fcntl core, close, the stat family, and the
fs/dir calls. The rule is written at the top of Libc.php, including what must NOT get it
— ssize_t (read/write/recv/send/readlink), size_t (strlen/fread/fwrite), long (ftell),
off_t (lseek/truncate) and pointers carried as int (strstr) would be truncated to 32 bits.
Verified on Linux in the container: async_stream_timeout · async_shared_stream ·
async_fd_churn · async_socket_family · async_stream_select · async_tls_loopback ·
async_diagnostics ALL PASS (were 7 failures/hangs). macOS unchanged: socket 15/15 ·
net 3/3 · stream 10/10 · fs 7/7 · async 22/22 · dns 3/3.
Also: socket_cmsg gets a `.linux.out`. CMSG_SPACE grows with the fd count on Darwin, but
a 16-byte cmsghdr plus 8-byte alignment gives the SAME 24 bytes for one fd and two on
Linux — php agrees, so it is a platform fact, not a defect.
The last Linux difftest divergence was `ip2long('1.2.3.04')`. Not our bug: macOS
php 8.5.8 reads the leading-zero octet as decimal and answers int(16909060), while the
SAME php version on Linux answers bool(false). We matched macOS.
I briefly "fixed" it by rejecting leading-zero octets — which made the pair diverge the
other way, on macOS. There is no single right answer to match, so the case is removed
from the test with the reason written next to it. Everything unambiguous about ip2long /
long2ip / inet_pton stays covered.
difftest on dns_inet: 1 MATCH, 0 DIFF. dns 3/3.
Structured concurrency for Manticore, as a pure-PHP library in
prelude/async.php— no newcompiler intrinsics. This branch takes the async spike (#4) to something usable and then fixes
what actually broke when it met real traffic.
What you get
Ordinary stream code suspends the fiber, not the process:
fread/fwrite/fgets,stream_socket_accept,fclose,stream_select,sleep/usleep, and everything layered onthem (
file_get_contents('https://…')included). Scopes, deadlines, cancellation, channels +select,Mutex/Once/Semaphore,mapConcurrent, signals and a supervised multi-processserver. Guide:
docs/async.md. Demos:examples/async/.No atomics anywhere, deliberately: a cooperative single thread makes a read-modify-write atomic
by construction. That invariant is documented in the runtime header.
★ Three general compiler bugs this shook out
Each has a php-oracle regression test — they are not async-specific.
intreturn was not sign-extended (declare i64for a Cint). A C-compiledcallee returning
-1writes onlyw0, so the wrapper read 4294967295 — andSSL_read'sreturn is a byte count, so
__mc_stream_fillmemmove'd ~4 GB. This is why everyhttps://-inside-async()read crashed intermittently. Hand-written libc syscall stubswrite the full
x0, which is why only the C libraries were exposed, and a blocking fd neverreturns
-1, which is why sync mode never saw it. Fixed with a function-level#[CType('int')]→sext i32.$h = Hook::get(); $h(41)read the tagged word raw (
int(42)→int(-4222124650659798); bool/string/array likewise),and a closure's implicit return emitted raw
0instead of a boxed null.C::$s = 42; C::$s === 42wasfalse, and
= nullread back as not null, soAsyncHook::clear()left every hooknon-null and
fclose()afterasync()called through a null closure.Async fixes in this round
stream_set_timeout()was silently ignored under ascheduler (a hung peer wedged the fiber forever) and
stream_socket_accept($timeout)fellinto the synchronous branch whose
poll(2)blocked the whole loop. Also: the listener wasnever
O_NONBLOCK, soaccept(2)on an idle listener blocked the process.EWOULDBLOCKafter awake and the write path called it a hard error. Both loop now, and the errno test is
negative-polarity — only a recognised errno stops a transfer.
/etc/hosts, then an A query overa netpoller-parked UDP exchange, substituted into the existing
getaddrinfowalk, with theblocking walk as fallback. Two fetches to different hosts: 0.34s → 0.17s.
silently overwrote the first — it was never woken and its
fread()returned empty while theother got the data.
sleep/usleep/time_nanosleepsuspend the fiber (andsleep()did not exist in thestdlib at all — it reached clang as an undefined symbol).
stream_select/socket_selectpark the fiber instead of blocking every task for thetimeout.
Async\readFile/writeFile— chunked and yielding. Measured on a 64 MB hot file: onefread(64MB)stalls every other task 15–25 ms, chunk+yield keeps it at ~2 ms, which is theentire benefit a fork+socketpair worker pool would have bought (rejected: it copies every byte
through a socket).
Verification
Two build generations green throughout;
async17/17 ·socket14 ·stream10 ·net3 ·fiber9 ·pcntl1 ·iopoll2 ·array97 ·closure17 ·class36 ·static20.http_transparent149.1k rps, no regression against the pre-change baseline.The full gate (whole suite +
tools/difftest.sh+tools/selfhost_fixpoint.sh) is running asof opening this PR; I'll post the result here.
New cases:
async_stream_timeout,async_sleep_transparent,async_shared_stream,async_fd_churn,async_stream_select,async_file_chunked, plus the php-oracledyn_callable_return_reprandstatic_prop_mixed_store.Known limits, stated plainly
O_NONBLOCKis a no-op for files).
Async\readFileis the mitigation, not a fix.stream_selectunder a scheduler is a polling park, not a reactor registration: one taskholds a single per-fd waiter slot while a select waits on N fds. Nothing hot goes through it.
is_object()on it lies.#[Async]is not done: unlike everything else it cannot be a library.Supersedes #4.