Repository navigation
fix(mqtt): stop a truncated replay from pinning the replay cursor - #14410
Conversation
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]>
|
Review complete. 🟡 1 medium 💬 Inline comments (1)
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.
Reviewed commit: c921c2b |
🟡 Tier B · Needs changes before merging
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.
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
⏳ Still open from earlier reviews · 1
Reviewed the commits since |
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
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
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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
left a comment
There was a problem hiding this comment.
🔵 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]>
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::replayBacklogresumed and persisted the stored cursor$from, but only replayed the last_APP_MQTT_REPLAY_DEPTHmessages.Connection::acknowledge()only advances across a contiguous run of acknowledgements, so the skipped sequences between$fromand 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).
Observed: the user topic's ledger tail was 159 while the stored cursor stayed at 142, on both SDKs.
Fix
sequence > max($from, $tail - $maxDepth), newest first with a descending$sequencetie-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.Connection::raise()moves the cursor up to that floor without undoing acknowledgements that arrived while the lookup yielded.max(floor, in-memory cursor)for every granted topic, so PUBACK progress made during the replay is never overwritten.Connection::cursor()getter.Tests
tests/unit/Mqtt/ReplayCursorTest.php(new, withFakes/FieldCachemirroring RedisEnvelopeTTL semantics andFakes/InterleavingDatabaseto 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()andraise().testReplayIsBoundedByMaxDepthis now strict: reconnecting must eventually replay nothing (boundedassertEventually, no sleeps). It fails on main.Notes / follow-ups
Server::dispatchrecords the subscription only afteronSubscribereturns, 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).Cachelowercases fields, so mixed-case topic names miss their stored cursor and start from the tail._APP_MQTT_REPLAY_DEPTHare still dropped silently by design; the client gets no signal that it missed any.🤖 Generated with Claude Code