Skip to content

Bound the MQTT revoke wait and fail closed on verification timeout - #15085

Merged
ArnabChatterjee20k merged 12 commits into
mainfrom
fix/mqtt-revoke-bounded-fail-closed
Nov 2, 2026
Merged

ArnabChatterjee20k merged 12 commits into
mainfrom
fix/mqtt-revoke-bounded-fail-closed

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Issue / Description

The MQTT broker's mqtt pub/sub subscriber dispatches every event of a worker — revokes, unsubscribes, deliveries — from one coroutine. A revoke runs its verification in a child coroutine, but the subscriber then waited on that child with no timeout. The verification reads the project database, and a read on a silently-dead (half-open) connection never returns and never errors, so one stuck check parked the subscriber forever: no deliveries, no revokes, no logs, no recovery. The realtime service was taken down by this exact mechanism; MQTT shared the gap. A sibling PR applies the same fix philosophy to app/realtime.php.

Tracking: appwrite-labs/cloud#7102

Solution

  • The subscriber's wait on a revoke verification is bounded by _APP_MQTT_PERMISSION_TIMEOUT (seconds, default 5, documented in app/config/variables.php), read once at worker start.
  • Past the timeout the broker fails closed: Handler::expel() disconnects the user's connections with NOT_AUTHORIZED — the same disconnect a verified revoke uses. Fail closed is safe here because clients reconnect and CONNECT re-authenticates them with fresh credentials, so a legitimate user is restored within one reconnect while an unverifiable one is excluded rather than left connected on unverified access.
  • Handler::unsubscribe() re-checks membership against the same project database inline, so it gets the same treatment: a child coroutine, the same bounded wait, and Handler::drop() removing the subscription unverified on timeout (a user still subscribed can simply re-SUBSCRIBE).
  • A verification that finishes after the timeout path already acted is tolerated: revoke() and unsubscribe() now mutate only connections still tracked as the same object, so a late check never closes a connection reusing the fd of one expel() removed.
  • If the coroutine limit stops the check from starting, the broker fails closed the same way (expel() / drop()) instead of running the check inline, where it could block on the same dead read.
  • Each revoke and unsubscribe event is recorded on one span (mqtt.revoke / mqtt.unsubscribe) that covers the whole event, fail-closed paths included, so production gets one structured, queryable line per event. Attributes: project.id, user.id, mqtt.is_broker, mqtt.topic (unsubscribe only), mqtt.verification (verified, timed_out, coroutine_limit or failed) and the count (mqtt.disconnected / mqtt.unsubscribed). timed_out and coroutine_limit spans carry a RuntimeException describing the failure, so they are recorded at error level and the span sampler keeps them even with trace filters set. A check that threw is set as the span error. The child coroutine sends its count or exception back through the channel instead of opening its own span. There is no separate Console logging for these paths.
  • The dispatcher moves from inline closures in app/mqtt.php into a new class, Appwrite\Mqtt\Event\Handler (src/Appwrite/Mqtt/Event/Handler.php). It handles the broker's internal events (revoke, unsubscribe and deliver) that arrive on the mqtt pub/sub channel. It takes Server, the connection handler (imported as Broker), Mqtt and the timeout. Its handle() method is the phpredis callback app/mqtt.php passes to subscribe(), and private revoke(), unsubscribe() and deliver() methods hold the per-action logic. No change to the CONNECT authentication model or AUTH handling, and delivery logic is unchanged.

Tests

  • tests/unit/Mqtt/Event/HandlerTest.php (a unit test of Appwrite\Mqtt\Event\Handler, each test in its own process) reproduces the poisoning (red → green): an authorizer that parks on a channel nothing pushes — a faithful stand-in for a half-open TCP read — a revoke event for a user with tracked connections, then a delivery event, both through one subscriber coroutine. On the old code the delivery is never processed (verified failing, bounded, before the fix); on the fixed code the user is disconnected NOT_AUTHORIZED within the timeout, the delivery goes through, and when the stuck read finally returns the late check closes nothing twice. A second test pins the normal path: a fast check revokes exactly the unauthorized user and delivery continues; a third covers the stuck unsubscribe membership check (subscription dropped, connection kept, delivery unaffected, late check leaves the rest alone). Two more fill the coroutine table so go() really fails and assert both paths fail closed without running a check. A recording span exporter checks that each of these paths records the right mqtt.verification, count and level.
  • tests/unit/Mqtt/RevokeTest.php / UnsubscribeTest.php cover expel() and drop() directly, plus the late-finish guards (an expel landing mid-check causes no double disconnect and no fd teardown).

Run: docker compose exec appwrite test tests/unit/Mqtt/

Benchmarks

  • Before: one hung revoke or unsubscribe verification stalls all MQTT fan-out on the worker indefinitely (observed as a full delivery outage until restart).
  • After: the affected user is disconnected within _APP_MQTT_PERMISSION_TIMEOUT (5s default) and delivery is unaffected; the full Mqtt unit suite (88 tests) runs in ~1s.

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 2 commits October 29, 2026 14:47
expel() disconnects a user's connections and drop() removes a live
subscription without re-checking against the database: the paths the
broker takes when a revoke or unsubscribe verification cannot complete.
revoke() and unsubscribe() now touch only connections still tracked, so
a check that finishes after the fail-closed path already acted never
tears down a connection reusing the same fd.

Co-Authored-By: Claude Fable 5 <[email protected]>
The 'mqtt' pub/sub subscriber waited forever on the revoke child
coroutine, so a verification stuck on a half-open database read parked
the subscriber: no deliveries, no revokes, no recovery. The wait is now
bounded by _APP_MQTT_PERMISSION_TIMEOUT (default 5s); past it the broker
fails closed — the user's connections are closed unverified and CONNECT
re-authenticates them on reconnect. The unsubscribe membership re-check
reads the same database inline, so it gets the same child coroutine and
bound, dropping the subscription unverified on timeout.

The dispatcher moves to app/init/mqtt/subscriber.php so the regression
test can drive it: a revoke whose check never returns must not starve a
following delivery.

Co-Authored-By: Claude Fable 5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 1 nitpick below.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Fail-closed expel/drop skip the tracked() fd-reuse guard (Handler.php:554) — The new timeout paths call $handler->expel(...) and $handler->drop(...) (app/init/mqtt/subscriber.php:63, app/init/mqtt/subscriber.php:109), and both iterate a connectionsOf() snapshot touching each fd without the $this->tracked() re-check that the sibling paths apply (revoke() at Handler.php:531, unsubscribe() at Handler.php:597), where the comment states the guard exists so a reused fd is never torn down.

The change extracts the MQTT event subscriber into a reusable bootstrap file and adds a bounded, coroutine-isolated permission check that expels or drops connections when verification does not complete within a configurable timeout. Unit tests cover revocation, unsubscribe, and subscriber behavior using process-isolated Swoole runs with fakes.

Files Change
app/init/mqtt/subscriber.php, app/mqtt.php Extracts subscriber construction into an init file wired via onWorkerStart, wrapping the permission check in a timeout that fails closed.
src/Appwrite/Mqtt/Handler.php Adds expel()/drop() revocation paths plus tracked() connection bookkeeping for disconnect semantics.
app/config/variables.php Introduces _APP_MQTT_PERMISSION_TIMEOUT with a 0.1 minimum and default value.
.github/ci/e2e.json Maps the new app/init/mqtt/ paths to the relevant e2e lanes.
tests/unit/Mqtt/* Adds RevokeTest, UnsubscribeTest, SubscriberTest and Fakes/Accounts, Fakes/MutedStderr covering the new paths in separate processes.

Reviewed commit: 10c87b2

@ghost

ghost commented Oct 29, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This pull request routes MQTT pub/sub events through a dedicated handler and bounds revoke and unsubscribe verification, failing closed when checks time out or cannot start. It adds broker-side connection and subscription cleanup guards, structured event spans, and coverage for stalled, normal, saturated, late-completion, and callback-error paths. It also updates MQTT configuration documentation and the CI path map.

Latest changes: The newest commits align MQTT database handles and the verification wait with the API database timeout, and catch unexpected event callback exceptions so they are recorded without escaping into phpredis.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 12
File Change
.github/ci/e2e.json Adds MQTT startup and initialization paths to the E2E CI path map.
app/config/variables.php Updates MQTT configuration documentation.
app/mqtt.php Wires the event handler and configures MQTT database and verification timeouts.
src/Appwrite/Mqtt/Event/Handler.php Dispatches MQTT events with bounded verification, fail-closed handling, spans, and an exception guard.
src/Appwrite/Mqtt/Handler.php Adds connection and subscription cleanup paths with guards for late verification.
tests/unit/Mqtt/Event/HandlerTest.php Covers event dispatch under stalled, normal, saturated, late, and callback-error conditions.
tests/unit/Mqtt/Fakes/Accounts.php Adds controllable authorization state for MQTT tests.
tests/unit/Mqtt/Fakes/RecordingCounter.php Adds a counter fake that records metric additions.
tests/unit/Mqtt/Fakes/RecordingExporter.php Adds a span exporter fake for assertions on recorded events.
tests/unit/Mqtt/Fakes/UnavailableTelemetry.php Adds a telemetry fake that throws when recording dropped-message metrics.
tests/unit/Mqtt/RevokeTest.php Tests revoke and expel behavior, including late verification completion.
tests/unit/Mqtt/UnsubscribeTest.php Tests membership-checked unsubscribe and fail-closed subscription dropping.

Reviewed the commits since 533a3d2 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread app/init/mqtt/subscriber.php Resolved
Comment thread tests/unit/Mqtt/Event/HandlerTest.php Resolved
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mqtt-revoke-bounded-fail-closed (after).

Metric Before After Change
🚀 Requests/sec 185.5 184.11 ⚪ -0.7%
⏱️ Latency P50 93.16 ms 94.45 ms ⚪ +1.4%
⏱️ Latency P95 219.4 ms 217.17 ms ⚪ -1%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 94.45 217.17 11,400 184.11 -2.23
Account 172.32 328.75 600 10.42 -6.2
TablesDB 91.81 169.65 6,200 103.18 -11.38
Storage 87.57 203.26 3,000 51.39 +7.7
Functions 128.19 257.39 1,600 28.32 +15.08

Top API waits (after)

API request Max wait (ms)
functions.create 504.09
account.prefs.update 409.92
account.name.update 397.49
storage.buckets.create 391.29
functions.variables.update 387.63

ArnabChatterjee20k and others added 2 commits October 29, 2026 15:05
When go() could not start a child, revoke and unsubscribe ran their
database check inline, so a half-open read could still park the
subscriber. At the limit the broker now expels or drops unverified,
as on timeout, and logs one error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apply the same tracked() check revoke() and unsubscribe() use, so the
fail-closed paths only touch connections still in the index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Reply to the tenki-reviewer nitpick:

🟢 Fail-closed expel/drop skip the tracked() fd-reuse guard (Handler.php:554)

Applied in 6c263d2. expel() and drop() now check tracked() before touching each connection, the same way revoke() and unsubscribe() do, and return how many connections they actually acted on. The Mqtt unit suite passes (90 tests).

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

Comment thread app/init/mqtt/subscriber.php Outdated
@@ -0,0 +1,154 @@
<?php

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should have it as a class Subscriber if required in the src/Appwrite/Mqtt along side the Handler.php cause that makes more sense.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in afb177a. The dispatcher is now Appwrite\Mqtt\Subscriber in src/Appwrite/Mqtt/Subscriber.php, next to Handler. It is the broker's subscriber to the internal mqtt pub/sub channel. The constructor takes Server, Handler, Mqtt and the $timeout, and the public receive($redis, $channel, $payload) method is the phpredis callback, so app/mqtt.php passes $subscriber->receive(...) to subscribe(). The private revoke(), unsubscribe() and deliver() methods keep the same logic: bounded wait, fail-closed expel()/drop(), coroutine-limit fail-closed, spans and logs. app/init/mqtt/subscriber.php is deleted, and SubscriberTest now constructs the class directly with its assertions unchanged (90 tests pass).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed in f6a2591. The class is now Appwrite\Mqtt\Event\Handler in src/Appwrite/Mqtt/Event/Handler.php. It imports the connection handler as Broker, and its entry method is handle(). app/mqtt.php passes $eventHandler->handle(...) to subscribe(). The test moved to tests/unit/Mqtt/Event/HandlerTest.php with its assertions unchanged (still 90 tests, 401 assertions). I also trimmed the comments this PR added, here and in Mqtt/Handler.php, to one line each; the fail-closed reasoning is in the PR body.

The broker's subscriber to the internal 'mqtt' pub/sub channel becomes
a class beside Handler instead of a closure factory in app/init. Its
receive() method is the phpredis callback; revoke, unsubscribe and
deliver keep their logic unchanged, including the bounded wait and the
fail-closed paths. SubscriberTest now constructs the class directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

ArnabChatterjee20k and others added 2 commits October 29, 2026 15:35
It handles the broker's internal events; "Subscriber" only described
how it is wired in. The entry method is handle(), the connection
handler is imported as Broker, and the test moves to
tests/unit/Mqtt/Event/HandlerTest.php with its assertions unchanged.
Comments added by this change are trimmed to one line each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
One mqtt.revoke / mqtt.unsubscribe span now covers the whole event,
including the fail-closed paths, instead of a span only inside the
child coroutine plus Console lines. The child sends its count or
throwable back through the channel. The span carries project.id,
user.id, mqtt.is_broker, mqtt.topic (unsubscribe), the count
(mqtt.disconnected / mqtt.unsubscribed) and mqtt.verification:
verified, timed_out, coroutine_limit or failed. Timed-out and
coroutine-limit spans finish at error level; a thrown check is set as
the span error. The Console logging for these paths is removed, and
with nothing left writing to STDERR the MutedStderr fake goes too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

Fail-closed outcomes are now recorded on spans instead of Console lines (a44b195).

Each revoke and unsubscribe event gets one span (mqtt.revoke / mqtt.unsubscribe) that covers the whole event, including the fail-closed paths. The child coroutine no longer opens its own span. It sends its count, or the exception it threw, back through the channel, and the parent records it.

Attributes:

  • project.id, user.id, mqtt.is_broker, and mqtt.topic (unsubscribe only)
  • mqtt.verification: verified, timed_out, coroutine_limit or failed
  • mqtt.disconnected (revoke) / mqtt.unsubscribed (unsubscribe): the count from whichever path ran

timed_out and coroutine_limit finish the span at Level::Error, using Span::finish(Level). failed calls setError() with the exception the check threw. The Console::error lines for these paths are gone, including the two "Failed to revoke/unsubscribe MQTT connections" lines that predate this PR, because the span already records that error. tests/unit/Mqtt/Event/HandlerTest.php now captures spans with a recording exporter and checks mqtt.verification, the count and the level on the stuck, coroutine-limit and fast paths.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Event/Handler.php Resolved
A timed_out or coroutine_limit span set only the error level, so the
span sampler's trace filters could drop it. It now carries a
RuntimeException describing the failure (a check that could not
complete is a genuine failure), which keeps it exported and sets the
error level through finish(). mqtt.verification is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
});

// An inline check could block on the same dead read.
$outcome = $started === false ? null : $result->pop($this->timeout);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is solving the clog with the help of a timeout

ArnabChatterjee20k and others added 2 commits November 2, 2026 14:34
fix(mqtt): never let an exception reach the subscribe loop; wait the API database timeout
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 02aacf6 into main Nov 2, 2026
69 checks passed
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