Repository navigation
Fail closed on stuck realtime permission verification instead of stalling delivery - #15086
Conversation
permissionsChanged events were verified inline in the single pub/sub subscriber coroutine, whose coroutine context caches the platform and project database objects. A silently dead (half-open) database connection parked the subscriber forever on a socket read and stalled all realtime delivery. Each branch's database work now runs in a child coroutine with a fresh context, and the subscriber waits at most _APP_REALTIME_PERMISSION_TIMEOUT seconds (default 5). On timeout it fails closed: the affected connections are closed unverified, a reconnect re-authenticates with fresh roles, and delivery moves on. A late-finishing child skips its writes once abandoned. A Throwable in one event now logs and continues instead of unwinding the subscription. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Harness/server.php boots app/realtime.php with fake databases through the overridable getConsoleDB/getProjectDB hooks; the test drives it over real websockets and pub/sub. A user lookup that blocks forever stands in for a half-open database connection: before the fix the follow-up event is never delivered (the subscriber is parked); after it, the unverifiable user's connections are closed within the timeout and delivery continues. Also pins the normal path: a revoked connection receives the revoking event with its old roles, then the unauthorized error, then the close. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Review complete. 🟡 5 medium 💬 Inline comments (4)
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to🟡 Medium — Add // docker-compose.yml
346 - _APP_LIMIT_REALTIME_QUERIESThe new variable is declared in This PR introduces
Reviewed commit: c865c55 |
🟢 Tier S · Ready to mergeRealtime pub/sub processing now uses a dedicated event handler that bounds permission checks, closes affected connections when verification cannot complete, and preserves normal delivery ordering. The change adds configurable timeout settings, telemetry for verification and failed event handling, and generated Compose configuration. Unit coverage exercises handler outcomes, telemetry, and event-span selection. Latest changes: The latest commit changes the span-case data provider from returning an array to yielding its named cases through an Iterator.
📂 Walkthrough · 11
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
A verification that threw was rethrown into the per-event catch, so the event was dropped for everyone and the user's connections stayed open on their old roles. An error leaves the user as unverifiable as a timeout, so both now go through the same fail-closed path ($onFailure), whose log line says which case happened, and the event still fans out. _APP_REALTIME_PERMISSION_TIMEOUT is clamped to at least 0.1 seconds, as a non-positive Channel::pop() timeout waits forever or not at all. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The harness user lookup for `broken` throws. The test asserts the triggering event still reaches other subscribers, the broken user gets it then the 401 and close, and a follow-up event is delivered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
There was a problem hiding this comment.
Expand to see previous review
Adds a configurable timeout for realtime permission revalidation with fail-closed connection handling, plus unit test coverage.
Key findings
- 🟡 Add
_APP_REALTIME_PERMISSION_TIMEOUTto compose env list — docker-compose.yml:346 - 🟡 Verification error path fails open on stale roles — realtime.php:618
- 🟡
assertUnauthorizedClosecannot distinguish close from silence — PermissionsChangedTest.php:222 - 🟡 Project-wide timeout path leaves admin and impersonated connections open — realtime.php:898
- 🟡 Verification paths without a bound: fallback and abandoned child — realtime.php:608
| if ($started === false) { | ||
| Console::warning('Coroutine limit reached, verifying realtime permissions inline'); | ||
|
|
||
| return $verify(); | ||
| } | ||
|
|
||
| $result = $done->pop($permissionTimeout); | ||
| if ($result === false) { | ||
| return $onTimeout(); |
There was a problem hiding this comment.
🟡 bug · medium
Verification paths without a bound: fallback and abandoned child
When go() returns false (coroutine limit reached), $verifyPermissions runs $verify() inline on the subscriber with no timeout at app/realtime.php:611, reintroducing the indefinite firehose stall the timeout was added to prevent — and because getConsoleDB()/getProjectDB() cache per-coroutine (app/realtime.php:128-176), any half-open connection handed out there is stored in the long-lived subscriber's context, stalling all later delivery. On the normal path, a timed-out child coroutine is never terminated: it stays blocked inside $verify() (app/realtime.php:600), leaking one Swoole coroutine and its pooled database connection per stuck user/project with no cap or cleanup. Both paths violate the bounded-wait guarantee the $permissionTimeout was introduced to provide.
📋 Prompt for AI Agents
In app/realtime.php around lines 598-616: (1) replace the inline return $verify(); fallback at line 611 with fail-closed handling — call $onTimeout() (marking $abandoned) after logging a warning, so the subscriber never blocks unbounded and its Coroutine::getContext cache is never used for permission reads; (2) capture the coroutine id returned by go() (line 600) and after the timeout cancel it via Coroutine::cancel($cid) (handling the cancelled exception in the child's catch), or pass a cancellation flag checked between steps, so a coroutine stuck on a never-returning DB read does not accumulate indefinitely.
There was a problem hiding this comment.
@tenki-reviewer Part 1 is valid, fixed in ae69a80: at the coroutine limit $verifyPermissions fails closed (skipped: coroutine limit reached) and never verifies inline, so the subscriber never makes a database read.
Part 2 (cancelling the stranded child) is out of scope for this PR, deliberately. This PR bounds how long the subscriber waits, not the database read itself. Bounding the read (driver/query timeouts) is tracked separately. A stuck child now costs one coroutine plus the dead connection it holds. It cannot stall delivery: if such children pile up to the limit, new events fail closed instead of blocking. The MQTT broker's equivalent change (#15085) takes the same approach and does not cancel. Coroutine::cancel() on a read blocked inside the hooked PDO driver is a separate behavior to validate, and belongs with the read-timeout work. Please re-review.
There was a problem hiding this comment.
Part 1 is confirmed fixed in the diff: $verifyPermissions now calls $onFailure('skipped: coroutine limit reached') when go() returns false, so the subscriber never runs $verify() inline and never makes a database read in the subscriber coroutine's context.
Part 2 (stranded child coroutine accumulation) remains open. The diff shows the timed-out child is never signalled or cancelled after $done->pop($permissionTimeout) returns false — the child continues blocked inside $verify() indefinitely. The $abandoned flag only prevents the child from writing back to connection state, but it does not unblock the coroutine itself. Under sustained DB slowness, one leaked coroutine and one pooled connection accumulate per timed-out event, with no cap or cleanup. The argument that 'new events fail closed at the limit' is correct but circular: the limit is reached faster precisely because old children are not reaped. This part of the original finding is not resolved.
There was a problem hiding this comment.
@tenki-reviewer Agreed that the stuck child is not reaped and that it holds a pool slot. Two points on why reaping it is not in this PR:
- What leaks is the connection the child is stuck on, and that connection is already dead. It cannot serve anyone else, and returning it to the pool would hand the half-open socket to the next caller. One leak needs one dead connection. A burst of events cannot multiply leaks from a single bad connection: each child pops its own connection, and only the dead ones hang. The limit is bounded by Swoole's
max_coroutine(100000 by default), far above any realistic count of dead database connections. - The real fix is a bounded database read. That frees the child and its slot on every path (HTTP, workers, realtime), not just this one, and it is tracked as a separate issue.
Coroutine::cancel()would only cover this call site, and only if the hooked PDO read is in a cancellable wait. We have not validated that, and we cannot exercise it in the harness, whose fake blocks on aChannel(always cancellable). The MQTT broker's matching change (Bound the MQTT revoke wait and fail closed on verification timeout #15085) makes the same choice.
So this PR bounds the subscriber's wait and fails closed, and freeing the read is left to the read-timeout work. Please re-review with that scope.
There was a problem hiding this comment.
Part 1 is confirmed resolved in the diff: the coroutine-limit fallback now calls $onFailure('skipped: coroutine limit reached') instead of $verify() inline.
Part 2 remains open as identified. The $abandoned flag prevents stale writes but does not unblock or reap the stuck child coroutine — it continues holding a pooled connection indefinitely after $done->pop($permissionTimeout) times out. The arguments about bounded pool size and a separate read-timeout fix are noted, but the accumulation of unreleased coroutines and dead connections under sustained DB slowness is a real resource-leak with no in-process ceiling below max_coroutine. The original finding called out both paths; only one is addressed here.
There was a problem hiding this comment.
@tenki-reviewer Correction to my earlier reply: you're right about Part 2, and my argument was wrong.
I claimed only dead connections hang, so one leak needs one dead connection, and that the ceiling is max_coroutine. Both are wrong. A slow database makes every timed-out check hold its pool connection, not only checks on dead sockets. The real ceiling is the per-worker database pool, which holds tens of connections. Once stuck checks drain it, handshakes and other permission checks on that worker starve too.
This PR still stops the subscriber from stalling, but it does not release the stuck check's coroutine or connection. That is now tracked as its own follow-up for both realtime and MQTT (appwrite-labs/cloud#7108): bound the read so the connection is discarded, and/or cap in-flight checks and fail closed at the cap. It will come with a regression test that keeps the pool bounded under N stuck checks.
There was a problem hiding this comment.
The acknowledgement is noted and the follow-up tracking (appwrite-labs/cloud#7108) is a reasonable way to proceed. However, the diff visible here still shows no mechanism to signal, cancel, or reap the stuck child after 'pop($permissionTimeout)' returns false — 'abandoned' only gates writes, the coroutine and its pool connection remain blocked indefinitely. Part 2 of the original finding is not resolved in this diff, so I cannot close the thread until the bounded-read or in-flight-cap work lands.
There was a problem hiding this comment.
Fixed in stacked PR #15094 (base: this branch), commit d9ec7f7. Each worker now caps its in-flight permission checks at half its database pool (max(1, intdiv(console pool size, 2))). A stuck check keeps its slot until its read returns. At the cap, a new check is not started and fails closed at once (realtime.verification = check_limit), so stuck checks can hold at most half the pool instead of draining it.
To be clear about what this does and does not do: the stuck child is bounded, not reaped. It still holds its slot and connection until the read returns, and reaping it comes with the database read timeout, appwrite-labs/cloud#7100. With default settings the per-worker pool is 1, so the cap is 1 and one stuck check already holds the whole pool; the cap only stops it from getting worse. The cap also only applies after a timeout, because the subscriber handles events one at a time.
There was a problem hiding this comment.
The stacked PR (#15094) addresses Part 2 by capping in-flight permission checks, but that diff is not visible in the evidence shown here — only the Handler.php refactor is available for review. In the diff visible here, after 'done->pop($permissionTimeout)' returns false, no signal is sent to the child, no slot is decremented, and no cap is enforced; the coroutine and its pooled connection remain blocked with no ceiling below 'max_coroutine'. The in-flight cap claimed in #15094 is not present in this diff, so I cannot confirm Part 2 is resolved from the evidence available at this tier.
Running the verification inline in the subscriber when go() fails brings back the unbounded hang on a half-open database read, and saturation is most likely exactly when stuck children pile up. Skip verification and close the affected connections instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Admin-mode connections carry an empty top-level userId, so the project-wide fail-closed path skipped them, though the verifier re-checks their team on success. Close them too when verification times out, fails or is skipped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The helper returned on silence as well as on a close, so a dropped close() went unnoticed. It now passes only on a close frame or a dropped socket and fails at the deadline otherwise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without it in the service environment list, a value set in .env never reached the realtime server, which silently used the default. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@tenki-reviewer Re the finding outside the diff ( |
|
Review complete. 🟠 1 high · 🟡 2 medium 💬 Inline comments (3)
This PR rebuilds the realtime connection verification path so that session invalidation and permission changes fail closed: on timeout or error, connections are closed rather than left serving stale roles, and a project-wide sweep re-verifies every subscribed connection after sessions change.
Reviewed commit: 1fd6ce8 |
commit: |
There was a problem hiding this comment.
Adds fail-closed, project-wide realtime re-verification of permissions when sessions are invalidated, with a Swoole coroutine-driven verify flow, new env knobs, compose/docs plumbing, and a real-process E2E harness test.
Key findings
- 🟠 Project-wide session sweep skips impersonated connections — realtime.php:941
- 🟡 Random port picks collide across parallel runs — PermissionsChangedTest.php:68
- 🟡 SIGKILL teardown orphans Swoole worker processes — PermissionsChangedTest.php:49
The port now comes from the kernel and the log from tempnam, so parallel runs share neither. Readiness fails fast if the harness died rather than passing on another listener. The harness leads its own process group and teardown signals the group, so the Swoole manager and worker go with the master instead of outliving the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The reasoning lives in the PR description; the code keeps only what a reader needs at each line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each permissionsChanged verification gets a realtime.permissions span with project.id, user.id (per-user events), realtime.event, the outcome in realtime.verification (verified, timed_out, failed, coroutine_limit) and realtime.closed. Timeouts and the coroutine limit finish at error level; a failure carries its throwable. A failed event records a realtime.event span with the error. These replace the Console lines, which were not structured or queryable. The harness exports spans as JSON, and the tests assert the recorded outcome for the verified, timed-out and failed paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sampler kept only spans carrying a throwable past _APP_TRACE_PROJECT_ID / _APP_TRACE_FUNCTION_ID, so the realtime verification timeout and coroutine-limit spans, which finish at error level without one, could be filtered out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The subscribe closure in app/realtime.php moves, unchanged in behavior, into Appwrite\Realtime\Event\Handler, mirroring Appwrite\Mqtt\Event\Handler: handle() is the phpredis subscribe callback, and private methods carry the plot: arrival telemetry, revalidateUser/revalidateProject with their checks run through verify() (the bounded child-coroutine wait and its span), endDeletedTeams, deliver, the closes, and tail. Dependencies are injected as objects and concrete telemetry instruments; the database getters stay the overridable globals, resolved inside the child coroutine. The reconnect loop stays in app/realtime.php. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Refactor in dbd7233: the pub/sub event handling moved out of the |
A level-only span carries no error, so the sampler drops it whenever the trace filters are set. timed_out now records a DATABASE_TIMEOUT and coroutine_limit a GENERAL_SERVER_ERROR, each with a short fixed message, and finishes at error level by default. That keeps them past the filters without special-casing the shared sampler, so its earlier change is reverted. realtime.verification is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The project-wide sessions.delete sweep skipped every connection without a sessionId, and impersonated connections never carry one: they run on the impersonator's session. After "invalidate all sessions" they kept serving the target user's data on an invalidated session. The sweep now checks impersonated connections whose impersonator belongs to the project, against that impersonator's session, status and impersonator flag, reading each impersonator once per event. Console impersonators hold console sessions and are left alone. The fail-closed path closes the same set. The harness can now open impersonated and session-bearing connections and invalidate a project's sessions, and three tests cover the verified, console-impersonator and timed-out sweeps. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sion-sweep End impersonated realtime connections when a project invalidates its sessions
At the author's request, the process harness and the tests that drove it are not kept in the repository. Their red and green runs are recorded in the pull request description instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
The test harness is removed in 5015e9e ( |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y-on-ingest feat(realtime): telemetry for the pub/sub event handler
…-ingest feat(realtime): report worker uptime gauge
…ed, slow or traced events Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Issue / Description
Tracking: appwrite-labs/cloud#7099
In
app/realtime.php, the pub/sub subscribe callback handlespermissionsChangedevents inline, in the single long-lived subscriber coroutine. That handling reads the platform and project databases throughgetConsoleDB()/getProjectDB(), which cache the database objects in the subscriber's coroutine context.If one of those cached connections goes silently dead (half-open TCP), the next permission lookup blocks forever on a socket read. There is no error and no log — the subscriber coroutine is simply parked, and all realtime delivery stops for every project served by that worker. This caused a full realtime outage in production on 2026-10-28.
The inline design exists for a reason that must be kept: the revocation event itself is delivered with the roles the user held until then, events after it see the new roles, and revoked connections are closed only after that delivery.
Solution
Mirrors the MQTT broker's change in #15085, including its shape: the pub/sub event handling moves out of the
app/realtime.phpsubscribe closure intoAppwrite\Realtime\Event\Handler(src/Appwrite/Realtime/Event/Handler.php), next toAppwrite\Mqtt\Event\Handler.handle()is the phpredis subscribe callback. Private methods carry the plot:revalidateUser()/revalidateProject()run their checks (checkUser()/checkProject()) throughverify(), the bounded child-coroutine wait that records the span, thenendDeletedTeams(),deliver(), the closes, andtail(). Dependencies are injected as objects: the WebSocket server, theRealtimeadapter, the stats table, the tail registry, usage, the concrete telemetry instruments, the unauthorized exception and payload, and the timeout. The database getters (getConsoleDB()/getProjectDB()) stay the existing overridable global functions, so the Cloud edition's overrides keep working. They are called inside the child coroutine, which is what gives each check fresh database objects. The pub/sub reconnect loop stays inapp/realtime.php. Behavior is unchanged by the move: the harness tests bootapp/realtime.phpand pass with every assertion unchanged.The behavior, with a bounded wait:
permissionsChangedbranch's database work and subscription rebuild now runs in a child coroutine viago(). The child gets a fresh coroutine context, so it resolves fresh database objects from the pool instead of reusing the subscriber's cached ones, and hands its$closingresult back through aSwoole\Coroutine\Channel.$channel->pop($timeout). The timeout comes from the new_APP_REALTIME_PERMISSION_TIMEOUTenv var (seconds, default 5, clamped to a minimum of 0.1 because a zero or negativeChannel::pop()timeout waits forever or not at all), documented inapp/config/variables.php.$closingsemantics, same telemetry.userIdandsessionId, the branch's existing filter) and its admin-mode connections, which the verifier re-checks against the project's team. Impersonated connections are not re-checked by the project-wide verifier, so its failure path leaves them alone too. Each gets the same unauthorized payload and close as the existing$closingflow, and the outcome is recorded on the verification span (below). The triggering event still fans out to everyone else. Failing closed is the right degradation because a reconnect re-authenticates with fresh roles — an unverifiable user is excluded rather than served on stale roles.realtime.permissionsspan. It is structured and queryable in production, whereConsoletext lines are not. Attributes:project.id,user.id(per-user events only),realtime.event(the event name),realtime.verification(verified|timed_out|failed|coroutine_limit), andrealtime.closed(how many connections the verification closed).failedcarries the throwable viasetError().timed_outattaches aDATABASE_TIMEOUT("Permission verification timed out after {timeout}s"), andcoroutine_limitattaches aGENERAL_SERVER_ERROR("Permission verification skipped: coroutine limit reached"). So every failure finishes at error level, and the sampler keeps it past_APP_TRACE_PROJECT_ID/_APP_TRACE_FUNCTION_ID, because it keeps every span that carries an error. A per-event span is used becauserealtime.pubsublives for the whole subscription. When handling an event throws, the per-event catch records arealtime.eventspan with the error. It is created only on failure, so normal firehose traffic adds no log volume.go()fails at the coroutine limit, the verification is skipped and the affected connections are closed (logged asskipped: coroutine limit reached). Running it inline in the subscriber would bring back the unbounded hang, and saturation is most likely exactly when stuck children pile up, since a timed-out child stays alive until its read returns.$pubsub->subscribe().Out of scope, deliberately: database-level timeouts, batching of the
sessions.deleteper-connection lookups, MQTT, and liveness metrics.Most of the diff is the subscribe closure moving into the new class; the behavioral change is the bounded wait, fail-closed paths and spans described here.
Tests
The regression tests ran locally against a real Swoole realtime server and a real Redis pub/sub. They booted
app/realtime.phpin its own process, with fake databases injected through its overridablegetConsoleDB()/getProjectDB()hooks, and used real websocket clients. At the author's request the test harness is not part of this PR, so the repository does not gain a process harness. The results below are the captured runs."Before" is the pre-fix code:
main'sapp/realtime.phpfor the first four rows, and this branch ata2a716ed27(before #15089) for the impersonation rows. "After" is this branch at578e93d8c7.timed_outat error level withDATABASE_TIMEOUTattached;realtime.closed = 1realtime.permissionsspan did not exist yetverifiedverified,realtime.closed = 2timed_out,realtime.closed = 1; a guest stays openThe ⚠ on the first test in the green run is a deprecation notice from the vendored
textalk/websocketclient, which PHPUnit pins on whichever test loads it first. It is not a failure. The rest oftests/unit/Realtimepasses (50 tests). The coroutine-limit path was not exercised: the server's own coroutines share the same limit, sogo()cannot be made to fail reliably without breaking the server first.After (green), branch head 578e93d: 6 tests pass
Before (red), main's app/realtime.php: stuck, error and normal-path tests
ANSI colour codes stripped from the server log lines. Nothing else edited.
Before (red), a2a716e (before #15089): impersonation tests
ANSI colour codes stripped from the server log lines. Nothing else edited.
Benchmarks
Behavior of the poisoning scenario (one permission lookup blocked on a half-open connection), measured by the regression test:
_APP_REALTIME_PERMISSION_TIMEOUT(default 5s)realtime.permissionsspan at error level, with project, user, event,realtime.verificationandrealtime.closed🤖 Generated with Claude Code