Skip to content

Async spike - #4

Closed
blacktrs wants to merge 18 commits into
mainfrom
async-spike
Closed

blacktrs wants to merge 18 commits into
mainfrom
async-spike

Conversation

@blacktrs

@blacktrs blacktrs commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Async and non-blocking I/O is already working on this branch.

Tested with a simple HTTP server (TechEmpower style bench)
I am able to achieve ~150k RPS at this point. There are a few more steps that could be done to improve the results

blacktrs added 18 commits July 23, 2026 17:49
…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.
…ree)

emitClosure retained captures via rcRetainByType, which only handles concrete
obj/array/string and no-ops a CELL/UNKNOWN value. So a closure capturing an rc
value read off a `mixed`/bare array or returned as `T|false` — e.g. a stream
resource — copied the pointer WITHOUT a refcount. When the enclosing scope then
dropped its reference (a loop reassigning the variable, or scope exit), the value
was freed and the closure held a dangling pointer → use-after-free.

Surfaced by the async spike: a fiber-per-connection HTTP server crashed under
concurrency (EXC_BAD_ACCESS in flockfile) because each connection fiber captured
a socket the accept loop had already freed. Single-connection worked; concurrency
(the fiber runs after the loop reassigned the var) reliably hit it.

Fix: a CELL/UNKNOWN capture gets a TAG-checked retain (__mir_cell_retain) — it
retains the underlying obj/array/string/resource and no-ops a scalar. Concrete
types keep the existing rcRetainByType path. Regression: closure_capture_cell_rc.
No regressions (closure/resource/fiber/generator/oop/socket). Promote to main.
…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.
…hurn leak

A fiber's 8MB guard-page stack was mmap'd on start and munmap'd only in the
DEFERRED __destruct — so a scheduler churning short-lived fibers (one per
connection) never reclaimed them promptly: 16k connections held ~413MB and the
mmap+mprotect+munmap syscalls cost ~3.5µs per fiber.

Two changes (general — any fiber-heavy program benefits):
  - Fiber-stack FREE-LIST (EmitLlvmFiber): __mir_fiber_stack_alloc reuses a pooled
    stack (guard page already set) instead of mmap; _free pools instead of munmap
    (cap 128, overflow → munmap). Single-threaded, no lock.
  - \Fiber::reclaim(): frees a TERMINATED fiber's stack+ctx immediately (pooling
    them), instead of waiting for __destruct. Idempotent — __destruct's guards
    skip the nulled fields; getReturn() still works (value is a field, not stack).
    A scheduler calls it on completion.

Result: spawn+run+destroy 4.99µs → 1.28µs (3.7x); 16k-connection churn RSS
413MB → 36MB (bounded). Fiber AOT 8/8, no regressions.
…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.
Dispatched in parseStatement; lowered to define("NAME", <expr>) so the existing
const-registration pre-pass (LowerFromAst) resolves a later bareword at compile
time, matching php's compile-time top-level const. One name per statement. Test
top_level_const; no parser regressions (const/class/define/oop). Promote to main.
…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.
@blacktrs blacktrs changed the title Async spike [#5] Async spike Jul 25, 2026
@blacktrs blacktrs changed the title [#5] Async spike Async spike Jul 25, 2026
@blacktrs

Copy link
Copy Markdown
Contributor Author

Superseded by #6. The spike's poc/async/src/ tree is gone: the runtime now ships as prelude/async.php (demand-gated), the demos live in examples/async/ and the guide in docs/async.md. #6 also carries the three general compiler fixes the spike's crashes turned out to be — chiefly an FFI C-int return that was not sign-extended, which is what made every https://-inside-async() read crash.

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