Skip to content

fix(mqtt): never let an exception reach the subscribe loop; wait the API database timeout - #15170

Merged
ArnabChatterjee20k merged 3 commits into
fix/mqtt-revoke-bounded-fail-closedfrom
fix/mqtt-subscriber-boundary
Nov 2, 2026
Merged

ArnabChatterjee20k merged 3 commits into
fix/mqtt-revoke-bounded-fail-closedfrom
fix/mqtt-subscriber-boundary

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Issue / Description

Stacked on #15085. Part of appwrite-labs/cloud#7177 (Finding 8).

The MQTT broker has the same two problems the realtime server had (fixed for realtime in #15166 and #15169).

1. An exception can reach the phpredis subscribe() loop.

  • Event\Handler::handle() is passed straight to $pubsub->subscribe(['mqtt'], ...). revoke() and unsubscribe() contain their own failures, but handle() itself and deliver() do not: the broker->deliver() call, the messagesDropped counter and the span calls can all throw.
  • With an exception pending, PHP 8.5's zend_call_function() returns SUCCESS without running the callback, and phpredis only stops on a non-SUCCESS return.
  • The broker would then keep reading and dropping every revoke, unsubscribe and delivery, silently and until restart. That is the FRA realtime freeze from adds user name in subscriber response model #7177.

2. The permission wait and the database timeout were unrelated.

Solution

  • Event\Handler::handle() runs everything inside a try. A failure is counted on mqtt.messages.failed with its action and reported as an mqtt.event span carrying the error. Reporting is guarded too, so nothing escapes to phpredis.
  • The wait is now APP_DATABASE_TIMEOUT_MILLISECONDS_API / 1000 (15 s), the time an API request gives a query. _APP_MQTT_PERMISSION_TIMEOUT (added in Bound the MQTT revoke wait and fail closed on verification timeout #15085) is removed.
  • getConsoleDB() and getProjectDB() in app/mqtt.php set APP_DATABASE_TIMEOUT_MILLISECONDS_API, so a check's query is killed when the wait ends.

Trade-off: the wait bounds the whole check, which can run several queries. A hung check can now hold the subscriber for up to 15 s instead of 5 s before it fails closed. A slow-but-healthy database that pushes a multi-query check past 15 s also fails closed: connections or subscriptions drop and are re-authorized on reconnect. _APP_MQTT_PERMISSION_TIMEOUT only exists in the unmerged #15085, so no deployment sets it.

Cloud needs the same database-handle change in its own app/mqtt.php; that is a separate PR.

Tests

  • New Mqtt\Event\HandlerTest::testNeverThrowsWhenAnEventFails delivers to a topic with no subscribers while the drop counter throws (UnavailableTelemetry fake).
    • Before the fix, RuntimeException: telemetry unavailable escapes handle() from deliver() (Handler.php:163 → :35), and the isolated test process dies (red).
    • After the fix, handle() returns, counts [1, ['action' => 'deliver']] on mqtt.messages.failed, and records one mqtt.event span with the error (green).
  • tests/unit/Mqtt and tests/unit/Docker: 117 tests pass.
  • Pint and PHPStan pass on the changed files.

🤖 Generated with Claude Code

@luxor-code-review

luxor-code-review Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (1)

  • 🟡 Verification timeout loses tuning and conflates query vs total budget — mqtt.php:258
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Leaked mqtt.deliver span when delivery throws · Handler.php:174–187 · unchanged line

// src/Appwrite/Mqtt/Event/Handler.php
174	        $span = Span::init('mqtt.deliver');
175	        $span->set('project.id', $projectId);
176	        $span->set('mqtt.topic', $topic);
177	        $span->set('mqtt.qos', $qos);
178	        $span->set('mqtt.is_broker', true);
179	
180	        $delivered = $this->broker->deliver($this->server, $projectId, $topic, $message, $qos, $sequence, $publishedAt);
181	
182	        $span->set('mqtt.subscribers', $delivered);
183	        if ($delivered === 0) {
184	            $this->mqtt->messagesDropped->add(1, ['reason' => 'no_subscriber']);
185	        }

deliver() is the only event handler without try/finally around its span: the mqtt.deliver span opened at line 174 is finished only after $this->broker->deliver(...) succeeds (src/Appwrite/Mqtt/Event/Handler.php:187), unlike revoke() and unsubscribe() which finish in a finally. If the delivery throws (socket fan-out can), the new catch guard in handle() swallows the error and the span is never finished. Failed deliveries lose their delivery span — latency and per-topic attributes are absent exactly when debugging matters, and the fallback mqtt.event span starts as a child of the never-closed parent, misattributing the failure.


This PR extracts MQTT broker event handling into src/Appwrite/Mqtt/Event/Handler.php, wrapping deliver/revoke/unsubscribe actions with fail-closed permission checks, per-action spans, and counter metrics that swallow telemetry errors so broker callbacks stay alive. app/mqtt.php is simplified to wire the handler with a verification timeout derived from the API database timeout, and _APP_MQTT_PERMISSION_TIMEOUT is dropped from the variables catalog. Unit tests cover handler behavior using fakes for the counter and telemetry services.

Files Change
src/Appwrite/Mqtt/Event/Handler.php New handler class centralizing MQTT event dispatch with spans, metrics, and fail-closed permission verification.
app/mqtt.php Wires the handler into the broker runtime; verification timeout now derived from APP_DATABASE_TIMEOUT_MILLISECONDS_API / 1000.
app/config/variables.php Removes the _APP_MQTT_PERMISSION_TIMEOUT env var from the catalog.
tests/unit/Mqtt/* Unit tests and fakes (RecordingCounter, UnavailableTelemetry) covering handler paths and telemetry-failure resilience.
tests/unit/Mqtt/Event/HandlerTest.php Handler unit suite asserting dispatch, fail-closed, and telemetry behavior.

Reviewed commit: 14f3604

@ghost

ghost commented Nov 2, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental change only clarifies the timeout comment and introduces no behavior change.

The MQTT event callback catches failures across dispatch and reports them through failure telemetry and an error span. Broker database handles and permission-verification waits use the API database timeout, replacing the MQTT-specific permission timeout; unit coverage exercises a delivery failure caused by unavailable telemetry.

Latest changes: The newest commit clarifies that the permission wait is intended to cover at least one API-timeout-bounded query, rather than the full verification check.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 6
File Change
app/config/variables.php Removes the MQTT-specific permission timeout setting.
app/mqtt.php Applies the API database timeout to broker database handles and permission-verification waits; clarifies the wait's intended bound.
src/Appwrite/Mqtt/Event/Handler.php Guards event dispatch and reports caught failures through telemetry and tracing.
tests/unit/Mqtt/Event/HandlerTest.php Covers safe handling and failure reporting when delivery telemetry throws.
tests/unit/Mqtt/Fakes/RecordingCounter.php Adds a counter fake that records metric updates for assertions.
tests/unit/Mqtt/Fakes/UnavailableTelemetry.php Adds telemetry whose dropped-message counter throws.

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

@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

@luxor-code-review luxor-code-review Bot 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.

Adds a dedicated MQTT event-handler class with fail-closed permission verification, telemetry instrumentation, and unit tests, replacing inline logic in app/mqtt.php.

Key findings

  • 🟡 Leaked mqtt.deliver span when delivery throws — Handler.php:174
  • 🟡 Verification timeout loses tuning and conflates query vs total budget — mqtt.php:258

Comment thread app/mqtt.php Resolved
@github-actions

github-actions Bot commented Nov 2, 2026

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.

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

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

Metric Before After Change
🚀 Requests/sec 206.86 217.54 🟢 +5.2%
⏱️ Latency P50 84.52 ms 80.32 ms ⚪ -5%
⏱️ Latency P95 188.59 ms 183.64 ms ⚪ -2.6%
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 80.32 183.64 13,680 217.54 -4.95
Account 151.65 289.48 720 12.08 +25.05
TablesDB 78.69 145.36 7,440 120.55 -7.58
Storage 70.65 163.46 3,600 60.18 -29.85
Functions 111.38 211.5 1,920 32.84 +3.94

Top API waits (after)

API request Max wait (ms)
account.name.update 436.09
functions.create 434.68
account.prefs.update 400.54
storage.buckets.create 368.59
functions.variables.update 359.34

@ArnabChatterjee20k
ArnabChatterjee20k merged commit 25e9d68 into fix/mqtt-revoke-bounded-fail-closed Nov 2, 2026
67 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