Repository navigation
fix(mqtt): drop expired messages from offline replay - #14412
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]>
A topic's expiry only shaped the replay cursor's cache TTL and was never applied to the age of ledger messages, so a device that reconnected after the expiry still received the message. With a 20 s provider expiry, a push sent while a device was offline was delivered when it reconnected 60 s later. User topics (users/<id>) carry no expiry of their own, so the provider's expiry never reached them at all. Replay now resolves an effective expiry per topic: the topic's own when set, otherwise the lowest expiry across the project's enabled Appwrite providers, read once per subscribe and only when a topic without one has a backlog. Zero disables offline replay and skips the ledger lookup. Expiry is a prefix cut over the replay window, not a per-row filter. The ledger lookup is unchanged (the sequence-bounded (topic, sequence) range scan, newest first, at most the replay depth), and the handler keeps the newest run of rows written within the expiry, stopping at the first expired one. $createdAt is stamped by each publishing host's clock, so it is not monotonic in sequence: under skew an expired row can sit between fresh ones. Filtering it out alone would replay the older fresh rows around a hole that no PUBACK can fill, pinning the persisted cursor below it and growing the connection's acked set. Cutting at the newest expired row keeps the replayed run contiguous, so the existing floor logic still raises the cursor past everything left out. The cutoff reads an injected clock, so the unit tests drive ledger timestamps, the cache and the handler from one value instead of mixing wall time with a fake clock. The cursor lifetime is decoupled from expiry: cursors are read and written, on replay and on PUBACK, with APP_PUSH_LEDGER_RETENTION (7 days, the ledger pruning window). PUBACK previously saved with TTL 0, a plain HMSET with no EXPIRE on Redis, so a cursor key recreated by an acknowledgement after expiry never expired. A cursor older than an hour was also discarded on reconnect and on PUBACK, which skipped the backlog or let a late acknowledgement lower it. Behaviour change: a topic with no expiry anywhere now replays back to the 7-day ledger window instead of an effective 1 hour, matching the documented "no expiry". The replay fixture moves to a shared ReplayTestCase, whose topics.expiry now defaults to null as in the real schema. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 7-day push ledger window was spelled out separately in the topic and Appwrite provider expiry validators and in the Deletes worker's ledger pruning, while the MQTT cursor TTL now depends on it too. If one copy changed alone, expiries could exceed what the ledger keeps, or cursors could expire before their messages. Use APP_PUSH_LEDGER_RETENTION in all of them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A topic with a null expiry now takes its offline retention from the project's enabled Appwrite providers at replay time, so the old wording (and the Update comment's "no expiry") misdescribed what null does. State the inheritance, the lowest-provider rule and the 7-day fallback on the topic create/update params, the Topic model and the collection schema, and say on the provider expiry param which topics it applies to. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reproduces the device report end to end: a users/<id> topic has a null expiry, so its offline replay must honour the Appwrite provider's expiry. Expiry 0 makes the assertion independent of the clock (nothing may replay whatever the age), and raising it to 3600 is the positive control that replay still works once the provider retains messages. Each push must reach SENT: if the expired push FAILED, nothing would be replayed for a reason unrelated to expiry and the expiry-0 step would pass vacuously. publishToUser now returns the terminal status so the test can assert it. The test runs in a fresh project because the provider expiry is the minimum across every enabled Appwrite provider in the project; setting it to 0 in the shared project would also suppress replay for the other session tests whose topics inherit it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Review complete. 🟡 2 medium 💬 Inline comments (2)
This PR introduces bounded, cursor-based QoS-1 replay for offline MQTT subscribers, controlled by a new
Two medium findings remain around non-atomic cursor persistence and replay racing a concurrently advanced cursor; no high or critical issues. Note: one scanner lane (correctness group 1) exhausted its step budget before publishing, though its interim analysis reported no findings, so that subset was covered by the sweep and holistic passes instead. Reviewed commit: 2493ffb |
🔵 Tier A · Mergeable after minor fixes
This pull request applies topic expiry and inherited provider expiry to MQTT offline replay, cuts expired and truncated ledger prefixes, and aligns replay cursors with the seven-day ledger-retention window. It adds topic bindings to replay cursors, preserves acknowledgement progress, and seeds cursors when no backlog is available. It also updates expiry documentation and adds unit and E2E coverage for expiry, cursor behavior, and replay convergence. Latest changes: The latest commit binds a cursor written after a cache-field miss to the current topic sequence and adds a regression test for that case.
Note Not approving while a bug finding is open: Treat unbound cursors as stale Fix with agent prompt### Issue 1
src/Appwrite/Mqtt/Handler.php:392
**Treat unbound cursors as stale**
Cursors written before this change have no `topic` field, and `onPuback()` can also write `topic: null` when no cache entry exists. This fallback treats either as belonging to the current topic, so if the old topic was recreated and its tail has caught up to the saved cursor, its new messages are still skipped; treating a missing binding as stale avoids that lost replay (at the cost of a one-time duplicate for legacy cursors).
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 20
⏳ 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 a QoS-1 offline replay cursor with per-provider expiry to the MQTT server, plus messaging API and e2e/unit test updates.
Key findings
- 🟡 Replay can regress a concurrently advanced PUBACK cursor — Handler.php:393
- 🟡 onPuback cursor persist is a non-atomic read-modify-write — Handler.php:307
✨ 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]>
…e name Cursor fields are keyed by topic name and outlive a deleted topic. A topic recreated under that name restarts its sequence, so the old cursor sits above the new tail and suppressed offline replay until the new sequence caught up or the cursor expired, which this branch stretches from an hour to the 7-day ledger window. A topic's sequence only grows, so a cursor above the tail can only be stale: replay from the start of the new topic instead. 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]>
# Conflicts: # src/Appwrite/Mqtt/Handler.php
Comparing a stored cursor with the tail only catches a stale one while the recreated topic is still below it. Once the new topic reaches the old cursor's sequence, replay resumed from that cursor and silently skipped the new topic's first messages. Topic IDs can repeat (users/<id> topics are derived from the name), so the cursor now also stores the topic document's internal sequence, and one written for another topic replays the new topic from its start. Cursors stored before this change carry no topic and keep resuming as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| $from = (int) ($stored['sequence'] ?? $tail); | ||
| // A cursor bound to another topic of the same name, or above this topic's tail (a topic's sequence | ||
| // only grows), was left by an earlier topic: all of this topic's ledger is new to the device. | ||
| if ($stored !== null && (($stored['topic'] ?? $topicSequence) !== $topicSequence || $from > $tail)) { |
There was a problem hiding this comment.
Treat unbound cursors as stale
Cursors written before this change have no topic field, and onPuback() can also write topic: null when no cache entry exists. This fallback treats either as belonging to the current topic, so if the old topic was recreated and its tail has caught up to the saved cursor, its new messages are still skipped; treating a missing binding as stale avoids that lost replay (at the cost of a one-time duplicate for legacy cursors).
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Mqtt/Handler.php
Line: 392
Comment:
**Treat unbound cursors as stale**
Cursors written before this change have no `topic` field, and `onPuback()` can also write `topic: null` when no cache entry exists. This fallback treats either as belonging to the current topic, so if the old topic was recreated and its tail has caught up to the saved cursor, its new messages are still skipped; treating a missing binding as stale avoids that lost replay (at the cost of a one-time duplicate for legacy cursors).
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
There was a problem hiding this comment.
Keeping this open for a maintainer decision rather than changing it. Treating unbound cursors as stale trades a rare permanent skip (a topic deleted and recreated while an unbound cursor for its name is alive, and whose new tail has passed it) for duplicates that are not rare: every device reconnecting after the deploy would replay up to _APP_MQTT_REPLAY_DEPTH messages per topic it already received, which users see as repeated notifications. On the onPuback point: it writes an unbound entry only when no entry exists, i.e. the bound one expired after 7 days on a live connection, or the topic was only ever received through a wildcard subscription (which never replays). Those cursors were written for the current topic, so they carry the same rare risk as legacy ones, not a new one. @ArnabChatterjee20k happy to flip it to stale if you'd rather take the one-time duplicates.
🤖 Addressed by Claude Code
There was a problem hiding this comment.
The duplicate cost is real, but it doesn’t rule out the data-loss case. With an unbound cursor at 5, a same-name topic recreated with a tail of 5 is treated as the original topic at this fallback. The backlog query only fetches sequences above that cursor, so the new topic’s messages 1–5 are skipped (query). This is reachable: deleting a topic is supported, and a recreated topic’s sequence starts at 0 (delete, default).
Also, the new PUBACK path can write topic: null after a cache miss (lines 307–310), so this is not limited to legacy cursors at deploy time. I’d keep the finding open: the one-time duplicate tradeoff is real, but the unbound cursor still permits silent permanent skips.
There was a problem hiding this comment.
The PUBACK part is fixed in ae40fa3: on a cache miss onPuback now looks the topic up and binds the cursor (at most once per topic per connection), so every cursor written from now on is bound. Regression: testAcknowledgementAfterACursorCacheMissBindsTheCursorToItsTopic. What remains is only cursors stored before this change, which age out within the 7-day cursor TTL. Whether to treat those as stale (a one-time duplicate burst for every device on deploy) is left to @ArnabChatterjee20k; leaving the thread open for that call.
🤖 Addressed by Claude Code
There was a problem hiding this comment.
The PUBACK fix is valid, and the regression test covers that path. The legacy-cursor case remains: when topic is missing, this fallback treats the cursor as belonging to the current topic. If a topic is deleted and recreated, its sequence starts at 0; if its new tail reaches the old cursor before that cursor expires, the tail <= from branch skips replay, and the cursor is then persisted bound to the recreated topic (topic deletion, sequence default).
The seven-day limit bounds how long this can happen, but does not prevent a reconnect during that window from permanently skipping the new topic’s messages. The duplicate cost of treating unbound cursors as stale is real; it doesn’t eliminate this failure. Please address the legacy-cursor window, whether by treating unbound cursors as stale or another safe discriminator. I’m keeping the finding open.
…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]>
onPuback carried the topic binding over from the stored entry, so after a cache miss (an entry expired on a long-lived connection, or a topic first acked through a wildcard subscription) it wrote an unbound cursor, which replay trusts as belonging to whatever topic later has that name. Look the topic up on a miss, at most once per topic per connection, so every cursor written from now on is bound; only cursors stored before the binding existed stay unbound. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Offline replay now honours message expiry, so a device that comes back after a message has expired no longer receives it.
@ArnabChatterjee20k could you review?
Root cause
Provider and topic
expiry("message retention in seconds for offline delivery") only set the replay cursor's cache TTL. It was never applied to the age of ledger rows, so any message still in the ledger was replayed whatever its age. Auto-provisionedusers/<id>topics also never picked up the provider's expiry.Repro (device testing)
On Android emulators (native Android and React Native SDKs) against a real Appwrite main instance:
PATCH /v1/messaging/providers/appwrite/{providerId}with{"expiry": 20}.Fix
expiry, otherwise the lowest non-nullexpiryamong the project's enabled Appwrite providers (looked up at replay time, at most once per SUBSCRIBE), otherwise none.users/<id>topics have a null expiry, so they inherit the provider's, and later provider updates apply.APP_PUSH_LEDGER_RETENTION(7 days, matching the validator cap and the ledger pruning in Deletes) for reads and writes. PUBACK writes used TTL 0 before, so a key recreated after expiry never expired.Behaviour changes
push:cursor:<project>:<user>:<client>) now live up to 7 days after their last write instead of about 1 hour, so Redis holds more of them. Each PUBACK that moves the cursor costsHMGET+HMSET+EXPIRE. Rolling back needs no migration.Tests
tests/unit/Mqtt/ReplayExpiryTest.php(new) and the TTL tests inReplayCursorTest: 13 fail on the fix(mqtt): stop a truncated replay from pinning the replay cursor #14410 base, including the device repro (testProviderExpiryAppliesToUserTopic), the skew hole (testExpiredMessageBetweenFreshOnesCutsTheWindow), a cursor older than an hour resuming, and PUBACK reading and writing with the cursor TTL.testProviderExpiryAppliesToUserTopic: fresh project, expiry 0 then 3600, deterministic with no time waits. Fails on the fix(mqtt): stop a truncated replay from pinning the replay cursor #14410 base.Notes
src/Appwrite/Mqtt/Handler.php; whichever merges second needs a small rebase.🤖 Generated with Claude Code