fiber-interop

Scope

The identity of the operation code belongs to, an HTTP request or a job, preserved across fibers and generators.

Scope is what lets an application or framework keep services per request, per user or per job while fibers interleave. Run each request in (new Scope)->run(...) and anything keyed by Scope::getCurrent() (a WeakMap of services, a container's Lifetime::Scoped, locale, timezone) is per request, with per-scope superglobals, without a separate worker mode. Library authors never touch it. Every fiber-interop runtime provides a global \Scope: the extension natively, else the polyfill (fiber_interop\scope\IS_POLYFILL says which). phasync keeps it switched itself; the other adapters do it in the adapter.

Scope is proposed for PHP core in the Scope RFC (draft). Today it is available as a native extension, fiber-interop/ext-scope, with a userland polyfill, fiber-interop/scope, for installs without the extension. The polyfill and the extension expose the same class; code written against one runs on the other.

Install

composer require fiber-interop/scope

Composer uses the extension when it is loaded and the polyfill otherwise.

Polyfill (fiber-interop/scope)

Scope identifies the logical operation (an HTTP request, a queued job, a transaction) that code belongs to, and keeps that identity across fibers and generators. It is the class from the PHP RFC: Scope. This package gives you that class on PHP 8.1+: the native extension fiber-interop/ext-scope (also bundled in ext-phasync) when available, otherwise a userland polyfill. See the RFC and the extension for the API, the rules and the cost.

$scope = new Scope();
$scope->run(function () {
    Scope::getCurrent();          // $scope
});
Scope::getCurrent();              // Scope::getRootScope()

Install

composer require fiber-interop/scope

Native or polyfill

The loader (src/loader.php, autoloaded by Composer) picks one at load time:

  1. A Scope class already exists (ext-scope loaded via php.ini or -d extension=, or a future PHP with Scope in core): it is used, and fiber_interop\scope\IS_POLYFILL is false.
  2. Opted in, on the CLI, with pcntl_exec available and a binary of ext-scope for the running PHP build: PHP re-executes itself with -d extension=<binary>. Opt in with the environment variable FIBER_INTEROP_SCOPE_EXT=1, or "extra": {"fiber-interop/scope": {"ext": true}} in the root composer.json. The binary is FIBER_INTEROP_SCOPE_SO, else ext/scope-<8.x>-<nts|zts>-<arch>-<glibc|musl|darwin>.so in this package. The package ships no binaries: build ext-scope, or place one there when you package an application. FIBER_INTEROP_SCOPE_REEXEC=1 is set in the child so it never re-executes twice; if the binary fails to load, the child falls back to the polyfill.
  3. Otherwise the polyfill in src/Scope.php is declared and IS_POLYFILL is true.

Polyfill gaps

The polyfill keeps a stack of run() scopes per fiber (a WeakMap keyed by the fiber) plus one for {main}. {main} outside any run() sees the root scope. A fiber with no run() of its own sees the scope most recently made current, by run() entry or exit or by fiber_interop\scope\activate(); so a fiber started and driven inside a request's run() keeps the request's scope without anyone's cooperation. As the RFC says, a fiber runs in the scope it is started in, not the one it is constructed in, and new Fiber($scope->bind($fn)) runs in $scope whoever starts it. It cannot add Generator::getScope(), and has two gaps the extension closes:

Execution key provider (polyfill only)

By default the polyfill keys its stacks on Fiber::getCurrent() (null = {main}). Runtimes whose execution unit is not a Fiber (Swoole coroutines, for instance, all see Fiber::getCurrent() === null) would otherwise share the {main} stack. For them:

function fiber_interop\scope\set_execution_key_provider(?callable $provider): void

$provider() returns ?object, the object identifying the current execution unit; null means {main} (falls back to Fiber::getCurrent()). The polyfill uses $provider() ?? Fiber::getCurrent() as the WeakMap key, so a unit's stack is dropped when its object is released (Swoole: Swoole\Coroutine::getContext(), which dies with the coroutine). null restores the default.

It is a function, not a Scope method, because the polyfill class has exactly the native class's public API. Under the native extension it is a no-op that records nothing: the extension cannot see coroutine switches that are not fiber switches, so Swoole users should use the polyfill.

Per-scope superglobals (polyfill)

$_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST and $_SERVER are per scope:

The live superglobals belong to the active scope. Switching is done by one function:

function fiber_interop\scope\activate(): void

It compares the scope it last activated with Scope::getCurrent(). If they are the same it returns: one comparison, no work. Otherwise it stores the six live values into the previously active scope's record and loads the current scope's. Scope::run() calls it on entry and on exit, so run() restores the previous scope's globals when it returns. Records live in a WeakMap keyed by the Scope object and die with it; the root's record is held strongly.

The invariant: the active scope equals the current scope whenever user code runs. run() keeps it within one execution unit; the event loop keeps it across switches. Adapters call activate() whenever the loop hands control to user code: at task start, after a resume, before a queued callback, and after run() returns to {main}. Calling it on every transfer is cheap, since a swap only happens on a real change of scope. Coverage therefore depends on the adapter; see the scope-state column of the conformance table.

Under the native extension activate() exists and does nothing: per-scope superglobals are engine-level in the extension (RFC secondary vote A).

Per-scope default timezone and locale (polyfill)

Secondary vote B: date_default_timezone_get()/set() and, when ext/intl is loaded, Locale::getDefault()/setDefault() follow the scope. The root has today's values, a new scope starts from ini (date.timezone, falling back to UTC; intl.default_locale as configured at startup, else ICU's default; Locale::setDefault() writes that ini entry, so the polyfill reads the startup value with ini_restore() once) rather than its creator's, and a change inside a scope affects only that scope.

Polyfill limitation. Userland cannot intercept date_default_timezone_set() or Locale::setDefault() (the extension does, at engine level). The polyfill reconciles at switch points instead: when a scope is left, the live timezone and locale are read into that scope's record; when a scope is entered (run() entry/exit, or activate() when it really swaps) its values are applied, but only if they differ from the live ones. A change made and read within one scope with no switch in between is naturally correct, and other scopes see their own values after the next switch. Code that changes the timezone from a fiber switch the loop does not report through activate() can leak the value to a sibling until the next switch. Locale::getDefault() is ignored unless ext/intl is loaded before the first Scope is created.

Cost: one date_default_timezone_get() (plus Locale::getDefault() with intl) and a string comparison per real switch, roughly 0.1-0.3 µs.

Sessions (extension only)

The session follows the scope only with the extension (ext-scope or ext-phasync). ext/session's state (session id, status, save handler, the open session) cannot be swapped from userland, and session_status() cannot be set, so the polyfill does not fake it: one PHP session is process-wide. The only thing it does is swap $_SESSION between scopes at switches where session_status() is PHP_SESSION_NONE: a new scope has no $_SESSION. While a session is active, $_SESSION is left alone and shared by all scopes.

Scope::bind()

$scope->bind($closure) returns a closure that runs $closure in $scope whoever calls it (fn(...$args) => $scope->run($closure, ...$args)), restoring the previous scope on return or throw; $closure is unchanged and keeps its own $this and class scope. Polyfill limit: by-reference parameters are not preserved (the extension's bind() keeps the closure's signature).

For runtime authors: generation() (polyfill only, @internal)

function fiber_interop\scope\generation(): int

A counter that strictly increases whenever the polyfill's active scope may have changed: on every Scope::run() entry and exit (including exit by exception, and including a run() that returns to the scope it left) and whenever activate() swaps scopes. It exists because a userland loop must know each coroutine's current scope at every suspend: the coroutine can change it with $scope->run(). Loops read generation() at resume and at suspend, and call Scope::getCurrent() only when it moved. It is not part of the Scope RFC and is declared only when IS_POLYFILL is true: under ext-scope the engine keeps each fiber's scope across its suspensions, so loops need not track it there.

Extension only: Scope::__run_without()

ext-scope has one method outside the RFC, Scope::__run_without(), for event loops that run in a scope of their own (see the extension's README). The polyfill does not declare it: a loop on the polyfill keeps scope state with activate() instead, and checks method_exists(Scope::class, '__run_without') before using it.

Polyfill rules

A project that declares its own global Scope class cannot install this package.

Release 0.6.0

0.6.0 is 0.5.0 with the version number of the extension it pairs with: from here on this package and ext-scope are released together under the same version, so "scope 0.6" means both. No code change.

Release 0.5.0

0.5.0 follows RFC 0.10: a fiber runs in the scope current where start() is called, and constructing it captures nothing. The polyfill never tied a fiber to its construction scope, so the change is in the tests, the documentation and the extension it is tested against (ext-scope 0.6.0, which also removes Fiber::getScope()). new Fiber($scope->bind($fn)) gives a fiber a fixed scope.

Release 0.4.0

0.4.0 follows RFC 0.9: a new scope starts with empty superglobals and ini timezone/locale, and Scope::bind() is added. Sessions are extension-only (above).

Release 0.3.0

0.3.0 is the "Scope spec level": the RFC draft plus secondary votes A (per-scope superglobals) and B (per-scope default timezone and locale, above). Version 0.3 adds vote B to the polyfill.

Tests

composer install
vendor/bin/phpunit                                        # polyfill
php -d extension=../ext-scope/modules/scope.so vendor/bin/phpunit   # native

License

MIT

Extension (fiber-interop/ext-scope)

The Scope class from the PHP RFC: Scope, as an extension for PHP 8.2 and later. A userland polyfill with the same class is fiber-interop/scope.

A Scope identifies the logical operation running code belongs to, such as an HTTP request, a queued job or a transaction, and keeps that identity across fibers and generators. Service containers can key request-scoped services by it, and libraries can keep per-operation state without depending on a particular event loop.

final class Scope
{
    public function __construct() {}
    public function run(callable $callback, mixed ...$args): mixed {}
    public function bind(Closure $closure): Closure {}
    public static function getCurrent(): Scope {}
    public static function getRootScope(): Scope {}
}

Generator::getScope(): Scope;   // added by the extension
$scope = new Scope();
$scope->run(function () {
    Scope::getCurrent();          // $scope
    $fiber = new Fiber(function () {
        Scope::getCurrent();      // $scope: a fiber runs in the scope it is started in
    });
    $fiber->start();
});
Scope::getCurrent();              // Scope::getRootScope()

$fiber = new Fiber($scope->bind($work));   // runs in $scope, whoever starts it

The root scope is one object for the whole request (process, on the CLI). It is current in {main} outside any run(), in fibers started there and in generators created there, so getCurrent() and Generator::getScope() never return null. "Am I inside an operation" is Scope::getCurrent() !== Scope::getRootScope(). To start something that belongs to no request from inside one: Scope::getRootScope()->run(fn() => /* start the service */).

Release 0.6.0

0.6.0 implements the fiber rule of the Scope RFC 0.10: every stack frame gets its scope when it is created, and $fiber->start() is an ordinary call, so a fiber's first frame gets the scope current where start() is called. Constructing a fiber creates no frame and captures nothing. Once started, a fiber keeps its scope (and any run() active in it) while it is suspended, whoever resumes it, as before. new Fiber($scope->bind($fn)) gives a fiber a fixed scope, whoever starts it. A fiber that has finished no longer keeps the scope it ran in alive.

Fiber::getScope() is removed; Generator::getScope() stays, and generators are unchanged. Code that constructs a fiber inside $scope->run() and starts it outside, expecting it to run in $scope, must bind its closure or start it inside run().

Release 0.5.0

0.5.0 adds Scope::__run_without(), which is not part of the RFC: an event loop running in a scope of its own keeps that scope out of the state switching (see below). Switching is cheaper: the superglobals are moved between the symbol table and the scopes without being compared (copy-on-write makes the entry hold the outgoing scope's current array), the per-fiber bookkeeping skips its hash table when a fiber goes back to the scope it came from, and a missing $_SESSION costs no lookup. A fiber resumed from the root into another scope went from about 83 ns to about 66 ns of extra cost per switch (PHP 8.5, php -n). Fixes:

Release 0.4.4

0.4.4 implements the session locking rule of the Scope RFC 0.9.3: a session whose save handler locks it is open in one scope of a process at a time, and session_start() throws a RuntimeException when the session id is open in another scope, instead of blocking the whole process on a lock only that scope can release (see the session section below).

Release 0.4.3

0.4.3 builds and works on thread-safe (ZTS) PHP, where it previously did not compile. The session and the locale follow the scope there too, and new tests run scopes in several threads at once with the parallel extension; CI builds ZTS as well as NTS for PHP 8.2 to 8.5. It also fixes unset($_GET) (or any of the six) inside a scope, which removed the superglobal from every scope instead of only that one. Switching is cheaper: a superglobal that both scopes leave empty is not moved, the session is not moved when neither scope has one, and the C-side copies of the request arrays are updated without feeding the cycle collector. A fiber resumed from the root into another scope went from about 322 ns to about 260 ns (PHP 8.5, opcache on, JIT off); within one scope nothing changed.

Release 0.4.2

0.4.2 makes the session settings request-wide, as the RFC specifies: session_name(), session_set_cookie_params(), session_cache_limiter() and ini_set() of session.* change them for every scope, and a new scope's save handler is the current session.save_handler. Only the session itself (its id, status, save handler state and $_SESSION) is per scope. Switching scopes is also faster: a generator step that crosses scopes went from about 530 ns to about 230 ns (PHP 8.5, opcache on, JIT off), and steps within one scope cost what they did.

Release 0.4.1

0.4.1 fixes a crash in generators whose finally block ends with a yield, when an exception or a return enters the block (found by running php-src's tests with the extension loaded: Zend, standard, session, date, intl, reflection and SPL now fail the same tests with and without it). The extension also allocates no object until the first Scope is created, so object ids (#1, spl_object_id()) are the same as without it in code that never uses one. And it fixes the session's end when a scope is destroyed: it now runs in the destructor phase, so user save handlers run safely, also when the scope is collected as a cycle or is still alive at request shutdown (this fixes a use-after-free when ending the session released the last reference to the scope). Scope reports its state to the cycle collector, and $_SESSION is per scope like the other superglobals.

Release 0.4.0

0.4.0 implements the Scope RFC 0.9:

Code that relied on a new scope inheriting its creator's superglobals, timezone or locale must now seed the scope.

Release 0.3.1

0.3.1 removes the per-call cost of loading the extension: generators now switch scope through calls compiled into generator bodies only, instead of an fcall observer that put every function call on PHP's observed path (#3). Same spec level as 0.3.0.

Release 0.3.0

0.3.0 is the "Scope spec level": the RFC draft plus both secondary votes. It contains the Scope class (getRootScope(), getCurrent(), run()), Fiber::getScope() and Generator::getScope(), per-scope request superglobals (vote A, ini scope.superglobals), per-scope default timezone and locale (vote B, ini scope.locale_timezone), and PIE metadata (composer.json, config.m4). The polyfill fiber-interop/scope 0.3.0 implements the same level.

Install

Rules

The RFC has the full motivation, the rules and prior art in other languages.

Request superglobals (secondary vote A)

$_GET, $_POST, $_COOKIE, $_FILES, $_REQUEST and $_SERVER follow the scope:

When the current scope changes (run() entering or leaving, a fiber switch, a generator resuming or yielding) the six arrays are moved between the scope's storage and the live EG(symbol_table) entries, which is where compiled $_GET accesses read and write, and PG(http_globals)[TRACK_VARS_*] is re-pointed at the same array for C code such as filter_input(). The cost of a switch is six symbol-table lookups and pointer moves; no array is copied. With auto_globals_jit (the default), $_SERVER and $_REQUEST are built only when a compiled file first uses them. The first scope creation, and every switch, makes the engine build them first, so a file compiled later inside a scope can't have its build overwrite the scope's array. Before the first Scope, the lazy build is unchanged.

scope.superglobals (default 1, PHP_INI_SYSTEM) turns this off, so the vote can be shown independently of the base proposal: with 0, all scopes share the SAPI's arrays (and the session, see below).

Session

When ext/session is loaded (it is an optional dependency), its request state follows the scope too:

scope.session (default 1, PHP_INI_SYSTEM) turns only this off; it is also off when scope.superglobals=0.

Default locale and timezone (secondary vote B)

date_default_timezone_get()/set() (ext/date) and Locale::getDefault()/setDefault() (ext/intl, only when intl is loaded) follow the scope with the same rules as the superglobals: the root scope's values are today's (from ini and the SAPI), a new scope starts with the ini values (date.timezone, or its fallback when unset; intl.default_locale, or ICU's default at request start when unset), not with its creator's, a change inside a scope affects only that scope, and code outside any scope sees no change. Fibers and generators of a scope share its values.

How it is done, and what a switch costs:

scope.locale_timezone (default 1, PHP_INI_SYSTEM) turns this off independently of scope.superglobals: with 0, all scopes share one timezone and one locale.

bind()

$scope->bind($closure) returns a new closure that runs $closure with $scope current, exactly as run() would, whoever calls it and from whichever scope: the previous scope is restored when it returns or throws, and calls nest. Generators created and fibers started inside such a call belong to $scope, so new Fiber($scope->bind($fn)) is a fiber that runs in $scope whoever starts it. $closure itself is unchanged and still runs in its caller's scope. Binding a closure that bind() returned replaces its scope rather than nesting: $a->bind($b->bind($fn)) runs $fn in $a.

The returned closure is a native wrapper that uses $closure's own parameter info, so it keeps its signature (by-reference parameters, defaults, variadics, return type, named arguments) and its $this and class scope; it is not a variadic fn(...$a) => $scope->run($closure, ...$a), which would lose by-reference parameters. Reflection reports it as an internal function with $closure's parameters; default values of its parameters are not visible to Reflection, and it does not return by reference.

Per-scope state (prototype)

A follow-up to the RFC plans an internal API with two layers, so that extensions can give implicit state one copy per scope without changing anything for code outside scopes. This extension implements both, each with one user that is off by default.

Slots are for new code: an extension allocates a slot at startup, and scope_slot() returns the current scope's copy of its state, created on first use. Outside any scope it returns the copy of the root scope, so extension code never handles a missing scope; Scope::getRootScope() is that root scope's object, and getRootScope()->run() makes the root's state current. A change of scope updates a pointer. The demonstration user is a per-scope counter:

scope.slot_demo = 1    ; adds scope_demo_counter(): int

Swapped globals are a bridge for state that stays in an extension's globals: the globals always hold the current scope's copy, and are swapped when execution moves between scopes, so code that reads them directly keeps working. The demonstration user is json_last_error():

scope.isolate_json_errors = 1

With it, json_last_error() and json_last_error_msg() are per scope: a new scope starts with no error, the fibers of one scope share it, and requests no longer see each other's last error. Code outside any scope sees the global, as without the extension. This prototype is built for NTS only; on ZTS builds the setting has no effect. Swapping costs roughly 25–55 ns per switch between fibers of different scopes; switches within one scope cost a pointer comparison.

Event loops: Scope::__run_without() (not part of the RFC)

public static function Scope::__run_without(callable $callback, mixed ...$args): mixed;

An event loop resumes a fiber of one request, gets control back, and resumes the next: every round trip switches the state of the loop's scope in and out. A loop that runs in a scope of its own can skip that. While $callback runs, switching to the calling scope does not apply its superglobals, session, locale and timezone: the state of the scope that ran before it stays live. Loop → fiber in A → loop → fiber in A then switches no state, and loop → A → loop → B switches once instead of twice. Scope::getCurrent() still returns the loop's scope, and fibers and generators keep theirs; only the state is not applied. When $callback returns or throws, the loop's state is applied again. A scope whose state is live when it is destroyed gives it back first.

$loopScope = new Scope();
$loopScope->run(fn() => Scope::__run_without(fn() => $loop->run()));

The cost is a rule for the loop: code running in its scope sees, and writes to, whichever scope's state is live. Timer and stream callbacks that run in the loop's own frame must not use the superglobals, the session or the default timezone. It throws from the root scope (code outside any scope must keep its own state) and when it is already running. The engine implementation proposed by the RFC switches scopes with a few pointer stores, so this has no counterpart there. Measured with a loop resuming fibers that each run in a scope (PHP 8.5, php -n):

Loop in its own scope With __run_without()
Fibers of one scope ~40 ns per switch ~0 ns
Fibers of two scopes, alternating ~44 ns per switch ~14 ns

Build

phpize
./configure --enable-scope
make
make test
php -d extension=modules/scope.so your-script.php

Cost

An extension can't add fields to the engine's fiber and generator objects, so this one keeps each started fiber's and each generator's scope in a WeakMap. It follows fiber switches with the engine's fiber observer. For generators it compiles scope switches into generator bodies only (a zend_extension op_array handler, registered by the extension itself): the body switches to the generator's scope when it starts, after each yield and at each catch and finally, and back to the resumer's scope before each yield, yield from and return. An exception escaping the body is handled where the generator is resumed (the Generator methods, its iterator for foreach, its destructor). Every other function compiles exactly as without the extension, and there is no function call observer, so ordinary calls cost nothing extra and the JIT stays on. Measured on PHP 8.5 (x86-64, php -n):

Without With
Function call ~25 ns ~25 ns
Generator step (valid(), current(), next()) ~67 ns ~98 ns
Generator step (foreach) ~37 ns ~70 ns
Fiber resume and suspend ~108 ns ~163 ns

An implementation in the engine stores the scope in the fiber or generator itself, which makes switching it a pointer assignment.

On PHP 8.2, a cycle that runs through a scope's WeakMap state back to a fiber of that scope isn't collected: the cycle collector learned to see through WeakMap entries in PHP 8.3.

License

MIT