Skip to content

fix(mqtt): stop a truncated replay from pinning the replay cursor - #14410

Merged
ArnabChatterjee20k merged 5 commits into
mainfrom
fix/mqtt-replay-cursor
Oct 13, 2026
Merged

ArnabChatterjee20k merged 5 commits into
mainfrom
fix/mqtt-replay-cursor

Conversation

@abnegate

Copy link
Copy Markdown
Member

Summary

Offline replay could leave a device's replay cursor stuck forever, so messages it had already received live were replayed again on every reconnect.

@ArnabChatterjee20k could you review?

Root cause

Handler::replayBacklog resumed and persisted the stored cursor $from, but only replayed the last _APP_MQTT_REPLAY_DEPTH messages. Connection::acknowledge() only advances across a contiguous run of acknowledgements, so the skipped sequences between $from and the replayed window were never acknowledged and pinned the cursor at $from. Every reconnect replayed the same window, and live deliveries acknowledged above the gap never moved the persisted cursor.

Repro (device testing)

Found running the Android device scenarios plus new edge cases on Android emulators (native Android and React Native SDKs) against a real Appwrite main instance (Messaging API → Appwrite push provider → MQTT broker).

  1. Take a device offline (or kill the app) while more than 5 pushes are sent to its user, so the next reconnect replays a truncated window.
  2. Reconnect, then with the app open send 3 more pushes; each reaches the callback.
  3. Force-stop and relaunch the app: the 3 live messages (and older ones, up to the replay depth) are delivered again, on every restart.

Observed: the user topic's ledger tail was 159 while the stored cursor stayed at 142, on both SDKs.

Fix

  • Anchor the cursor just below the oldest replayable message: the ledger lookup is sequence > max($from, $tail - $maxDepth), newest first with a descending $sequence tie-break (so the (topic, sequence) index serves it as a backward range scan), limited to the depth and replayed oldest first. There is no upper bound, so a message committed while the SUBSCRIBE runs is still replayed.
  • New monotonic Connection::raise() moves the cursor up to that floor without undoing acknowledgements that arrived while the lookup yielded.
  • The single save at the end persists max(floor, in-memory cursor) for every granted topic, so PUBACK progress made during the replay is never overwritten.
  • New Connection::cursor() getter.

Tests

  • tests/unit/Mqtt/ReplayCursorTest.php (new, with Fakes/FieldCache mirroring Redis Envelope TTL semantics and Fakes/InterleavingDatabase to interleave acks and inserts deterministically): truncated replay, pruned ledger, insert during subscribe, depth-bounded lookup, acks during replay or lookup, topics with nothing to replay. 7 fail on main.
  • packages/mqtt/tests/ConnectionTest.php: cursor() and raise().
  • E2E testReplayIsBoundedByMaxDepth is now strict: reconnecting must eventually replay nothing (bounded assertEventually, no sleeps). It fails on main.

Notes / follow-ups

  • Pre-existing: Server::dispatch records the subscription only after onSubscribe returns, so a message committed between the ledger read and that record is neither replayed nor delivered live in that session (it is replayed on the next reconnect).
  • Pre-existing: Cache lowercases fields, so mixed-case topic names miss their stored cursor and start from the tail.
  • Messages beyond _APP_MQTT_REPLAY_DEPTH are still dropped silently by design; the client gets no signal that it missed any.

🤖 Generated with Claude Code

abnegate and others added 2 commits October 13, 2026 19:12
replayBacklog resumed the connection at the persisted cursor and persisted
that same value, but replayed only the newest $maxDepth messages. PUBACKs
advance the cursor only across a contiguous run, so the sequences skipped
by the truncation (or pruned from the ledger) left a gap the cursor could
never cross: every reconnect replayed the same window again, including
messages already delivered live (seen on a device as ledger tail 159 with
the cursor stuck at 142).

The replay now resumes at the persisted cursor, reads the newest $maxDepth
ledger rows above max(cursor, tail - $maxDepth) (descending, then reversed
to deliver oldest first) and raises the cursor to just below the oldest
replayed row, or to the tail when nothing is left to read. The depth lower
bound and a descending $sequence tie-break let the (topic, sequence) index
serve the lookup as a backward range scan over at most $maxDepth rows:
without the bound the range covers the whole backlog, and without the
tie-break utopia-php/database appends an ascending $sequence order that
the index cannot serve, so the database read and filesorted every row
(200k rows for LIMIT 50 on MariaDB).

The window has no upper bound at the topic document's tail: that document
is read before the ledger query yields, and the subscription is only
recorded after onSubscribe returns, so a message committed in between
reaches the client only through the replay. A message committed after the
ledger read and before the subscription is recorded is still missed until
the next reconnect; that window predates this change.

Connection::raise() sets the cursor to max(current, floor), drops acked
sequences at or below it and folds the contiguous acked run above it, so
a PUBACK processed while the ledger query yielded is kept instead of being
overwritten by a second resume().

Every granted topic, including one with nothing to replay, now persists
the higher of its floor and the connection's cursor in the single
saveMany after the loop, so the write no longer undoes cursor progress
that onPuback saved during the subscribe.

FieldCache mirrors the Redis adapter's Envelope semantics (null values are
a miss, an empty save is rejected) and InterleavingDatabase runs a
callback before a chosen find and records each find's queries, so the
unit tests can interleave commits and acknowledgements with the ledger
query deterministically and assert the lookup stays index-bounded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The depth test only checked that capped-out messages were not re-delivered,
which passed while the cursor stayed pinned and the replayed window came
back on every reconnect. It now reconnects until the backlog is empty,
proving the acknowledgements of a truncated replay advance the persisted
cursor, and still asserts no capped-out message ever reappears.

Each reconnect attempt disconnects in a finally block so a missing SUBACK
does not leak the socket across retries.

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

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 resume() lowers a cursor a PUBACK already raised — Handler.php:396

This PR makes MQTT QoS 1 delivery resilient across reconnects: acknowledged messages are tracked so replay resumes from a persisted per-topic cursor instead of re-delivering the full backlog.

Files Change
packages/mqtt/src/Connection.php Adds per-topic cursor tracking with resume()/raise()/fold() bookkeeping over packet-id acks, plus cursor() accessors.
src/Appwrite/Mqtt/Handler.php Persists per-topic replay cursors via a field cache, computes replay floors from the push ledger, and drives replayBacklog on subscribe/reconnect.
packages/mqtt/tests/ConnectionTest.php Unit coverage for raise/fold and cursor semantics on the connection.
tests/unit/Mqtt/ReplayCursorTest.php + tests/unit/Mqtt/Fakes/* Unit tests for cursor replay with interleaving-database and field-cache fakes.
tests/e2e/Services/Mqtt/MqttServerTest.php E2E coverage of server-side replay behavior.

Reviewed commit: c921c2b

@ghost

ghost commented Oct 13, 2026 •

Copy link
Copy Markdown

🟡 Tier B · Needs changes before merging

The previously reported cursor rewind during a replayable resubscription remains unresolved.

This PR bounds MQTT offline replay to the newest configured depth, advances the cursor below the replay window, and persists the higher of that floor and acknowledgement progress. It adds connection cursor APIs, replay interleaving coverage, and a stricter E2E assertion. The PHPStan baseline is updated for the MQTT tests.

Latest changes: The latest commit marks no-backlog QoS 1 topics as seeded and monotonically raises their cursor, with a regression test for a live acknowledgement interleaved with the cursor read.

Verdict New comments Fixed Still open
💬 Commented 0 0 1

Note

Not approving while a bug finding is open: Preserve cursors established by live deliveries too

Fix with agent prompt
### Issue 1
src/Appwrite/Mqtt/Handler.php:390-391
**Preserve cursors established by live deliveries too**

`resumed()` is false when the connection first tracked this topic through a live wildcard subscription, even though `track()` has already established an in-memory cursor. If a PUBACK advances that cursor while this cache read yields, the stale `$from` is passed to `resume()`, replaying already acknowledged messages and potentially persisting the lower cursor. Preserve any existing connection cursor here, not only one seeded by an earlier replay.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 8
File Change
packages/mqtt/phpstan-baseline.neon Removes obsolete nullable-offset warnings for MQTT connection tests.
packages/mqtt/src/Connection.php Adds cursor inspection and monotonic cursor raising, and marks raised topics as seeded.
packages/mqtt/tests/ConnectionTest.php Tests the connection cursor and raise APIs and acknowledgement behavior.
src/Appwrite/Mqtt/Handler.php Replays a depth-bounded ledger window, anchors and persists its cursor floor, and preserves concurrent acknowledgement progress.
tests/e2e/Services/Mqtt/MqttServerTest.php Requires reconnects to eventually stop replaying acknowledged messages.
tests/unit/Mqtt/Fakes/FieldCache.php Adds Redis-like field TTL behavior and a hook for interleaving cache reads with acknowledgements.
tests/unit/Mqtt/Fakes/InterleavingDatabase.php Adds deterministic interleaving of ledger reads with acknowledgements and inserts.
tests/unit/Mqtt/ReplayCursorTest.php Covers bounded and truncated replay, pruning, concurrent progress, empty replay, and the new no-backlog resubscription case.
⏳ Still open from earlier reviews · 1

Reviewed the commits since baff066 · 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 A · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • 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.

@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 MQTT QoS 1 replay-cursor persistence in Handler with packet-id raise/fold bookkeeping in the mqtt package; one medium-severity cursor-regression issue found.

Key findings

  • 🟡 resume() lowers a cursor a PUBACK already raised — Handler.php:396

Comment thread src/Appwrite/Mqtt/Handler.php Resolved
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mqtt-replay-cursor (after).

Metric Before After Change
🚀 Requests/sec 210.87 221.41 ⚪ +5%
⏱️ Latency P50 81.36 ms 79.52 ms ⚪ -2.3%
⏱️ Latency P95 190.4 ms 179.09 ms 🟢 -5.9%
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 79.52 179.09 13,680 221.41 -11.31
Account 141.38 270.1 720 12.35 -18.93
TablesDB 75.71 131.8 7,440 122.85 -17.17
Storage 76.78 163.87 3,600 61.33 +5.42
Functions 114.19 217.18 1,920 33.45 -28.58

Top API waits (after)

API request Max wait (ms)
functions.create 438.4
account.name.update 401.41
functions.variables.create 374.17
functions.variables.update 360.22
account.prefs.update 351.34

abnegate and others added 2 commits October 13, 2026 21:13
The package runs phpstan at max level over its tests, and the new cursor and
raise() tests added offset accesses on acknowledge()'s nullable result beyond
the baseline's fixed count, failing the Packages / mqtt check. A helper that
fails the test on an untracked packet narrows the type, so the baseline entries
for those offsets can go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A PUBACK processed while replayBacklog or onPuback waited on the cursor cache
could be undone by the staler value that read returned. On a re-SUBSCRIBE,
resume() lowered the connection's cursor to the cached snapshot and the final
save persisted it; in onPuback, a coroutine resuming after a later PUBACK saved
its older cursor over the newer one. Either replays acknowledged messages on
the next reconnect.

Never seed a topic below the cursor this connection already resumed from a
persisted value (a cursor anchored by a first live delivery is not trusted, as
it would skip an offline backlog), and persist the connection's latest cursor
after the read in onPuback.

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 A · See the inline comments. Summary

Comment thread src/Appwrite/Mqtt/Handler.php Resolved

@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

src/Appwrite/Mqtt/Handler.php:390-391

Preserve cursors established by live deliveries too

resumed() is false when the connection first tracked this topic through a live wildcard subscription, even though track() has already established an in-memory cursor. If a PUBACK advances that cursor while this cache read yields, the stale $from is passed to resume(), replaying already acknowledged messages and potentially persisting the lower cursor. Preserve any existing connection cursor here, not only one seeded by an earlier replay.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Mqtt/Handler.php
Line: 390-391

Comment:
**Preserve cursors established by live deliveries too**

`resumed()` is false when the connection first tracked this topic through a live wildcard subscription, even though `track()` has already established an in-memory cursor. If a PUBACK advances that cursor while this cache read yields, the stale `$from` is passed to `resume()`, replaying already acknowledged messages and potentially persisting the lower cursor. Preserve any existing connection cursor here, not only one seeded by an earlier replay.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · concurrency · Reply if this doesn't apply.

…subscribe

A topic with nothing to replay on its first SUBSCRIBE never had its cursor
seeded, so the resumed guard stayed off and a later SUBSCRIBE could rewind live
acknowledgements made while it read the cursor cache. Raising the cursor to the
stored value there never lowers progress and, with no backlog below it, cannot
skip any message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ArnabChatterjee20k
ArnabChatterjee20k merged commit 8092bd3 into main Oct 13, 2026
68 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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.

2 participants