Runtime Hooks

RUNTIME_HOOKS makes blocking PHP builtins suspend the current fiber instead of holding the worker thread. Code you cannot edit (a framework, a database client, an HTTP library) then lets the worker run other requests while it waits. It is off by default and enabled by category.

Hooks act inside worker-mode request fibers and oxphp_async() task fibers. Everywhere else (traditional, Framework and SPA routing, the CLI) the builtins behave natively, argument validation errors included.

How it works

Category What suspends the fiber
sleep sleep() and usleep(), the way oxphp_sleep() and oxphp_usleep() do
streams A blocking read on a tcp:// socket stream, and stream_select(). That covers fsockopen(), stream_socket_client(), the HTTP stream wrappers, mysqlnd (PDO_MySQL, mysqli) and phpredis
net Connects, TLS handshakes and reads, writes that wait for buffer room, and reads on sockets that are not TCP. Needs streams and works on Linux only
curl Everything curl_exec() waits for, and the wait inside curl_multi_select(). Needs neither streams nor net, and works on Linux only. See cURL Under Runtime Hooks

None of them needs a change to the client's code.

The net category

With net listed, these waits below PHP streams suspend the fiber as well:

  • connecting through stream_socket_client(), fsockopen() and every client built on PHP streams (mysqlnd, so PDO_MySQL and mysqli, and phpredis among them);
  • the TLS handshake, and reads on ssl:// and tls:// streams once crypto is active;
  • writes that have to wait for room in the send buffer;
  • stream reads on unix://, udp:// and udg:// sockets, on stream_socket_pair() streams, and on the streams socket_export_stream() makes from sockets that are not TCP.

net does not cover waits inside libpq (pgsql, pdo_pgsql) or libmemcached, DNS resolution, stream_socket_recvfrom(), writes on a plain stream with an infinite timeout (default_socket_timeout=-1), or persistent connects. Where the streams hook does not suspend has the details.

Configuration

Variable Default Description
RUNTIME_HOOKS (off) 1, true or all enables every category. A comma-separated list enables some of them (RUNTIME_HOOKS=sleep,streams)

1, true and all include every category, so they also turn on any category a later release adds. Name the categories you want (RUNTIME_HOOKS=sleep) if an upgrade should not change what is hooked.

Migration from 0.15.0

1, true and all now include the new curl category. cURL transfers start suspending on upgrade, and /config and oxphp_server_info()['runtime_hooks'] report ["sleep","streams","net","curl"], so a check that compares the list to ["sleep","streams","net"] stops matching. To keep 0.15.0's behavior, set RUNTIME_HOOKS=sleep,streams,net. Read Sharing a handle between fibers if requests share an HTTP client.

Enabling streams or net patches PHP's and OpenSSL's socket stream tables in memory at startup, then restores the memory protection. On a platform where the original protection cannot be determined, the memory stays writable: a small loss of hardening, which the server log reports.

Before you turn it on

A request can now be suspended inside code you did not write, so check these first:

  • Other requests run during a hooked wait. They see the container, singletons and static properties as they are at that moment. A worker runs its first request alone for a while, which covers a container built lazily in that request, but per-request state kept in a shared service breaks. See Hooked waits and shared application state.
  • A shared database or Redis connection is safe with PDO, mysqli and phpredis, and gains nothing. Its queries run one after another; the gain is on connections a fiber opens for itself. Predis and hand-written protocols are guarded only one reply at a time, so give them a connection per request. See Sharing one connection between fibers.
  • Closing a shared connection ends the requests parked on it with a 500. Dropping the last reference to a PDO handle closes it, so a reconnect helper that reassigns a shared handle does this. See Closing a shared connection.
  • Calls on a shared cURL handle take turns, and one that cannot get the handle throws OxPHP\Async\AsyncException. See Sharing a handle between fibers.
  • Fibers your code starts are not hooked. Waits inside new Fiber, AMPHP or Revolt hold the worker thread. See Fibers your application starts.
  • A misspelled category is not an error. Check what the server installed, as below.

Checking that hooks are active

The server reports the categories it installed, as a parsed set. On the internal server:

Installed hook categories
$ curl -s localhost:9090/config | jq .runtime_hooks [ "sleep", "streams", "net", "curl" ]

From PHP, when the internal server is not reachable or not enabled:

php
<?php echo json_encode(oxphp_server_info()['runtime_hooks']); // ["sleep","streams","net","curl"]

How to read the list:

  • RUNTIME_HOOKS=all, 1 and sleep, streams, net, curl all report ["sleep","streams","net","curl"].
  • An empty list means no hook is installed: the variable is unset, set to 0, names only unknown categories, or is itself misspelled.
  • A mix installs the known names: RUNTIME_HOOKS=sleep,bogus reports ["sleep"]. Each unknown name gets a line in the server log at startup, oxphp: RUNTIME_HOOKS lists an unknown category "bogus", which enables nothing; …, and is named nowhere else.

Check after every change to the setting. Otherwise a misspelling shows up only as latency.

Installed is not the same as in effect

The list says which builtins were replaced at startup, whatever the routing mode. A traditional-mode server reports ["sleep","streams","net","curl"] and behaves natively throughout, because it has no fibers to suspend. A php CLI process reports ["sleep","streams"]: net and curl cannot work inside the CLI binary.

streams is reported even when its socket-read part fails to install, on a platform where the stream ops table cannot be made writable. stream_select() stays hooked then, and the only sign is the log line oxphp: socket stream hooks unavailable (…); socket reads stay blocking.

The startup lines on this page follow PHP's error logging. With error_log unset (the default) they reach the server log as warn, and LOG_LEVEL=error hides them.

When net or curl stays off

net and curl are reported only when they are in place, so a name missing from the list after you asked for it is the answer.

  • net listed without streams stays off, with the log line oxphp: RUNTIME_HOOKS lists net without streams; ….
  • On a platform other than Linux, or where the server cannot intercept PHP's poll(), net stays off with a line starting oxphp: net hooks unavailable and ending connects and TLS waits stay blocking.
  • With OpenSSL loaded as a shared extension (extension=openssl), the TLS waits (the handshake, and reads and writes once crypto is active) keep the thread. net is still reported, and connects and the other reads still suspend. The official images build OpenSSL into PHP, where these waits suspend.
  • Without ext/curl, curl is left out with no log line.
  • curl stays off on a platform other than Linux, with libcurl linked into PHP instead of loaded as a shared library, or where the server cannot intercept libcurl's poll(). The last is the case for ext/curl loaded as a shared extension (extension=curl) under PHP 8.4 on glibc. The log line starts oxphp: curl hooks unavailable and ends cURL transfers stay blocking.

Where hooks do not suspend

Where the sleep hooks do not suspend

Where a fiber switch is refused, the hooked sleep() and usleep() call the native builtin, which waits on the worker thread and returns what it returns. A sleep() cut short by a signal there returns the seconds it did not sleep. A hooked sleep() that suspends returns 0. The argument check is the hook's own in both cases: it rejects anything above 4294967295, which the native builtin accepts and truncates.

Switching is refused wherever leaving the current frame would be unsafe. This list is not exhaustive:

  • inside a declare(ticks) handler and inside pcntl's signal dispatch;
  • while a request's input is being built: before the script runs, and in worker mode inside request_parse_body();
  • inside a FILTER_CALLBACK reached from filter_input_array() given a per-field definitions array (see the note under $_GET);
  • inside array_multisort(), in the code it runs while comparing (a __toString(), an error handler, a destructor);
  • in the cleanup after a request has come apart (a fatal error, a timeout, or a write to a client that has left): the destructors it runs, a decorator's after(), a stream filter's onClose(), and an output handler that a fatal error's message passes through. A new Fiber started there still runs;
  • in the destructors of what a request left in a superglobal or in the closure of an oxphp_async() task it never awaited, which run after its session is written.

The ordinary end of a request is not on the list: its shutdown functions and the destructors of its variables suspend as usual. oxphp_sleep() and oxphp_usleep() wait on the thread in the same places, so switching to them does not help.

Cancelling an oxphp_async() task during a hooked sleep unwinds it with OxPHP\Async\AsyncException.

Fibers your application starts

A fiber started inside a request by new Fiber, or by a scheduler such as AMPHP or Revolt, runs on a context OxPHP cannot resume. The hooks stand aside there: a sleep, a socket read or a stream_select() inside it takes the native path and holds the worker thread. Size that share of the load as if the hooks were off.

The request's own fiber is not affected. In worker mode it is a real Fiber that OxPHP drives (Fiber::getCurrent() inside a request returns it), so the hooks apply to it, and libraries that only need to tell concurrent requests apart work. It is also why Revolt refuses to run its event loop inside a worker-mode request.

Where the streams hook does not suspend

streams covers a blocking read on a PHP socket stream and the wait in stream_select(), and net adds the waits listed above. Check how your client waits before counting on them. For these, nothing changes:

  • ext/curl. curl_exec() and curl_multi_* work below PHP streams, so they wait on the thread unless the curl category is listed.
  • socket_select() and stream_socket_accept(). ext/sockets' socket_select() and the wait inside stream_socket_accept() are not hooked. stream_select() is.
  • Other sockets and TLS under streams alone. Reads on unix://, udp:// and udg:// streams, socket pairs, non-TCP streams from socket_export_stream(), and ssl:///tls:// streams once crypto is active need net. A TCP socket passed to socket_export_stream() gives a tcp:// stream, which streams covers. stream_socket_recvfrom() holds the thread until a datagram arrives, even with net.
  • Some connects. ftp_connect() and socket_connect() connect outside the stream layer and are never covered. Persistent connects hold the thread even with net: pfsockopen(), STREAM_CLIENT_PERSISTENT, PDO_MySQL with PDO::ATTR_PERSISTENT, mysqli with the p: host prefix, and phpredis's pconnect(). That costs only the connect, which a persistent connection makes once; its queries suspend as usual.
  • DNS resolution. A host name is resolved on the worker thread before the connect starts, so a slow resolver holds it.
  • Clients with a network library of their own. pgsql and pdo_pgsql (libpq) and the memcached extension (libmemcached) connect and wait inside that library, which no category sees.
  • MySQL through localhost. The MySQL client reads localhost as "use the unix socket", which streams does not cover. Write 127.0.0.1 in the DSN, or list net. This applies to PDO_MySQL and mysqli, and is easy to miss because everything still works, just without the gain.
  • Writes under streams alone. Only reads suspend, so a write that fills the socket buffer blocks as it does without the hook. That costs little, since the time goes into waiting for the reply. With net, a write that waits for room suspends, except on a plain (non-TLS) stream with an infinite timeout (default_socket_timeout=-1); a TLS stream with an infinite timeout does suspend.

Within that scope socket timeouts behave natively. stream_set_timeout() and default_socket_timeout apply, a timed-out read reports timed_out through stream_get_meta_data(), and socket_import_stream() and similar keep working. The deadline is checked once per scheduler tick, so it can fire up to a tick late: at best 100 µs in worker mode and 50 µs in the async pool, longer under load. At the default 60-second timeout this is not observable.

stream_select() keeps PHP's own results: the return count, the arrays rewritten down to the ready streams, the warnings and the argument errors. The call runs unhooked when its arrays hold a read stream with data already buffered, a stream with no descriptor, an element that is not a live stream, a descriptor the kernel cannot watch (a regular file), or a descriptor at or above FD_SETSIZE (1024). PHP's own select() refuses that last one with or without the hook, and a busy worker can hold more than 1024 open descriptors.

A connection that several fibers share is covered in Shared Connections Under Runtime Hooks.

Cost

Measured per socket round trip: about 3 to 5 µs on a worker with nothing else parked, 5 to 6 µs with 64 fibers parked on descriptors, and 7 to 11 µs with 200. The cost tracks how many descriptors became ready, not how many are waiting.

A wide stream_select() costs more, because each descriptor it names is registered before the wait and removed after it: roughly 0.65 µs per descriptor. Measured on calls that return at once, so that only the overhead remains:

Descriptors Hooked Unhooked
1 about 6 µs about 5 µs
64 about 56 µs about 9 µs
200 130 to 150 µs 16 to 21 µs

That is a fixed cost per call. A stream_select() that waits a millisecond makes even the 200-descriptor figure about a tenth of the call, and gets the worker thread back for the whole wait. Clients that wait on one connection (mysqlnd, phpredis, the HTTP stream wrappers) pay around a microsecond. Leave streams off for two shapes: a call over many descriptors that almost never waits, and a request that is itself the event loop, where the thread has nothing else to run anyway.

Best practices

  • In code you write, use oxphp_sleep() and oxphp_usleep(). They suspend the fiber in worker mode with no setting, and oxphp_sleep() takes fractional seconds (oxphp_sleep(0.25)), which native sleep() cannot. Relying on RUNTIME_HOOKS there ties your handlers' behavior to a deployment setting.
  • Enable RUNTIME_HOOKS=sleep for code you cannot edit, such as a framework or vendor library that calls sleep() or usleep(). A hooked sleep() still takes an int, returns 0 when it suspends, and returns what the builtin returns when it falls back.
  • Neither of them suspends in the places listed under Where hooks do not suspend.

Prompts for your agent

These prompts assume an agent with the OxPHP documentation MCP server connected. The agent reads the pages it needs itself.

prompt
Check whether my application is safe to run under OxPHP with `RUNTIME_HOOKS=all`. Read the `features/runtime-hooks`, `features/runtime-hooks-shared-state` and `features/runtime-hooks-curl` pages through the OxPHP documentation MCP server. Go through this repository's database, Redis and HTTP clients and its worker bootstrap, tell me what each hook category would make cooperative here and what could break, with a fix for each. If a category should stay off, give me the `RUNTIME_HOOKS` value to set instead and tell me how to confirm the server picked it up.

See also

Found a mistake? Report it