[PHP-DEV] [IDEA] Native async/await syntax on top of Fibers

Hi internals,

I'd like to gauge interest in adding native async/await syntax to PHP,
built on top of the Fiber implementation we've had since 8.1.

Fibers made it possible to write concurrent code without "function
colouring", but in practice everyone still picks a userland library
(Amp, ReactPHP, Revolt) together with its own Promise/Future type, and
the code doesn't say directly what it means. The idea is to give the
engine a small, standard vocabulary for this:

    async function fetch(string $name, float $secs): string {
        await Async\delay($secs);
        return "$name done";
    }

    $a = fetch("a", 0.2); // starts right away, returns Async\Future
    $b = fetch("b", 0.2);
    echo await $a, await $b; // ~0.2s total, not 0.4s

Proposed semantics, in short:

- `async` can be applied to functions, methods, closures and arrow
  functions. Calling one runs its body in a new Fiber and returns an
  Async\Future. The task starts eagerly and runs until it awaits a
  Future that isn't complete yet.

- `await <expr>` inside a task suspends that task. Outside a task (at
  the top level, or in a plain Fiber) it drives a small scheduler until
  the Future completes. It returns the value or rethrows the exception.

- `async` is a contextual keyword: it is only a keyword when followed
  by `function` or `fn`, so existing userland async() functions keep
  working. `await` would become a reserved keyword, though it remains
  usable as a method, constant or property name.

- Tasks still pending at shutdown are destroyed the same way suspended
  Fibers are, so their finally blocks run. Deadlocks throw an Error
  instead of hanging.

- A minimal runtime API: final class Async\Future, Async\async(),
  Async\wait() (the function form of await), Async\delay() and
  Async\suspend().

I have a working prototype. Both constructs are desugared in the
parser into calls to the runtime functions, so there are no new opcodes
and no VM changes:

    [Draft] Experimental async/await syntax on top of Fibers by Eng3bbas · Pull Request #24623 · php/php-src · GitHub

It comes with tests and passes the existing test suite on a debug
build (macOS arm64, NTS). I haven't tried it on Windows or ZTS yet.

Questions I'd especially like feedback on:

1. Is reserving `await` an acceptable BC break? Unqualified functions
   named await() would break; namespaced calls such as
   Amp\Future\await() would not.

2. How should this relate to the True Async RFC? Should syntax like
   this be layered on top of that work rather than proposed separately?

3. What should I/O integration look like? The prototype only supports
   timers and cooperative yielding. Real-world usefulness depends on
   an event-loop or reactor story for streams and sockets.

4. Known rough edges in the desugaring approach: func_get_args() inside
   an async body returns [], stack traces show an extra {closure} frame,
   and reflection reports the return type as Async\Future. Are these
   acceptable, or is a dedicated engine-level implementation preferred?

If there is interest, I'm happy to turn this into a proper RFC.

Thanks,
Abbas Al-Khateeb

Hi Abbas,

Thanks for putting a prototype behind the idea.

I think PHP is already closer to good async than it looks, and that the
best path keeps the property Fibers gave us: no function colouring. Any
function can suspend, and its caller doesn't need to know. That lets
PHP go the way of Go rather than JavaScript: code is written as
ordinary blocking code, and concurrency is chosen at the call site, not
declared on the function.

This runs today, unchanged, on phasync, Revolt, AMPHP, ReactPHP and
Swoole:

    use function fiber\{go, await_all, sleep};

    function fetchAll(array $ms): array
    {
        $tasks = [];
        foreach ($ms as $m) {
            $tasks[] = go(function () use ($m) {
                sleep($m / 1000);
                return "slept $m ms";
            });
        }
        return await_all($tasks);
    }

sleep() is just called, with no await. It suspends the task it runs
in, not the process, and fetchAll() is an ordinary function that its
callers can't tell apart from a blocking one.

The only reason it is fiber\sleep() and not \sleep() is that PHP's own
sleep() has no way to tell the scheduler it is about to block. Give
userland a way to be notified when a fiber would otherwise block, and
plain \sleep(), fread() or PDO::query() behave the same way. At that
point there is nothing left for an await on a function call to do.

Compare Async\delay() in your proposal. Without the await,

    $value = Async\delay($secs);

doesn't wait at all: $value is a Future, and the code carries on at
once. Every function that returns a Future has that trap, and every
caller has to know which functions are which. That is the colouring,
and it spreads: a library that wants to serve both kinds of code ends
up with two versions of each function.

I read your point that everyone still picks a userland library as a
frustration with interoperability, and I share it. A library written
for Amp doesn't run on ReactPHP. But that is solvable without new
syntax. The code above is from fiber-interop, a small common API with
an adapter per event loop:

Most of the remaining pieces exist too. PHP even lets userland make
file I/O transparent: phasync/file-streamwrapper replaces the file://
wrapper, so plain file_get_contents()/fread() code suspends only its
own fiber:

That works because stream wrappers are a userland extension point.
PDO, curl, mysqli and the socket functions have no such point. What the
language lacks is the interface for them: a standard way for an
internal function that would block the whole process to ask the
userland scheduler to suspend the current fiber, and to be resumed when
its I/O is ready. With that, existing code becomes concurrent without
being rewritten, under whichever event loop the application uses.

If PHP gets async and await keywords some day, I think they should
launch and join fibers at the call site, not mark functions and await
futures:

    $fiber = async some_function(1, 2, 3);
    $result = await $fiber;

some_function() stays an ordinary function. Whether it runs
concurrently is the caller's choice, as with Go's "go", so nothing is
coloured.

A request that runs in many fibers also needs to know which request it
belongs to. That is Go's context.Context, and it's what I've just
proposed as the Scope RFC:

Frode Børli