Skip to content

mqtt: re-subscribing to the same filter adds a second subscription instead of replacing the first #3217

Closed

Description

@jfallows

Problem

By reading MqttServerFactory (about lines 3970-3984 and 4128-4142 on a recent develop; not run): a SUBSCRIBE for a filter identical to an existing subscription adds a second entry to the session state instead of replacing the first. The old QoS-level stream keeps the old entry, so a downgrade from QoS 2 to QoS 0 still delivers at QoS 2, and the old Subscription Identifier persists.

Specification statements (to be re-read from the OASIS text)

  • MQTT 5.0 3.8.4 [MQTT-3.8.4-3]: if a Topic Filter is identical to a Non-shared Subscription's Topic Filter for the current Session, the Server MUST replace that existing Subscription with a new Subscription; the new Subscription's options could be different. [MQTT-3.8.4-4]: if Retain Handling is 0, existing retained messages matching the filter MUST be re-sent, but Application Messages MUST NOT be lost due to replacing the Subscription.
  • [MQTT-3.8.4-8]: the QoS of Application Messages sent in response to a Subscription MUST be the minimum of the QoS of the originally published message and the Maximum QoS granted.
  • MQTT 3.1.1 3.8.4 [MQTT-3.8.4-3]: the Server MUST completely replace the existing Subscription.
  • 3.8.2.1.2 (v5): the Subscription Identifier is associated with a subscription created or modified by the SUBSCRIBE; if the property is not specified, the absence of an identifier is stored with the subscription.

Expected

  • A second SUBSCRIBE for an identical Non-shared filter replaces the first: the session state holds one entry, the granted QoS, options and Subscription Identifier (or its absence) are those of the new SUBSCRIBE, and messages are delivered at the new QoS from then on.
  • A change of QoS level does not lose messages in flight to the replacement (the specification forbids that loss) and does not deliver the same message twice because both entries were live.
  • A replacement with Retain Handling 0 re-sends the retained messages as the options say.

Design first

How the replacement flows across the per-QoS-level subscribe streams and the session state is not defined today (a subscription lives on a stream per QoS level). Before any code, post a short design on this issue: what happens to the old stream, to messages in flight, to the stored session state and to the Subscription Identifier when the QoS level changes and when it does not; how the mqtt-kafka subscribe proxy and its consumer group see the change. The pattern to mirror must be an existing implementation in the same modules; if none fits, say so and ask.

Test plan (test-first)

After the design is accepted: scripts for v5 and v4 in specs/binding-mqtt.spec (and specs/binding-mqtt-kafka.spec if the proxy changes): same QoS re-subscribe (one state entry, one delivery), QoS 2 to 0 downgrade (delivered at 0), 0 to 2 upgrade, a Subscription Identifier added, changed and removed by re-subscribe, and Retain Handling 0 resend. The first commit holds the failing scripts; if a case cannot be shown to fail, stop and record the analysis here.

Notes

Found by a clause-by-clause audit of MQTT 3.1.1 and 5.0 conformance, by reading the code. Part of the MQTT conformance work under #512.

Activity

  1. jfallows commented on Nov 13, 2026

    @jfallows
    ContributorAuthor

    Design (step 1, no code yet)

    Checked against develop at 6ee5654. Line numbers have moved from the issue's. Confirmed by reading only; nothing was run, no throwaway script.

    What happens today (read, not run)

    MqttServerFactory:

    • onDecodeSubscribeV4 / onDecodeSubscribeV5 build one Subscription per filter and write the session state as session.subscriptions (all existing entries) followed by the new entries. There is no filter-keyed dedupe, so an identical Non-shared filter yields two state items with the same pattern: the old id/qos/flags and the new ones.
    • MqttSessionStream.onSessionData (connected branch) takes newState entries that are not equals() to the current ones. Subscription.equals includes id, qos, flags and reasonCode, so a changed entry always counts as new. It then calls openSubscribeStreams.
    • openSubscribeStreams groups by qos and, for each level 0..qos, does computeIfAbsent on the route's MqttSubscribeStream and calls doSubscribeBeginOrFlush, which only does this.subscriptions.addAll(...). It never removes the old entry.
    • Result for QoS 2 to 0: level-0 stream holds old(2)+new(0); level-1 and level-2 streams are never touched and keep old(2). The mqtt-kafka proxy still has the QoS 2 filters on those streams, so QoS 2 delivery continues and the old Subscription Identifier is still attached. For same-QoS the level streams hold both entries. A 0 to 2 upgrade leaves the old entry on level 0 beside the new one.
    • MqttSubscribeStream.onSubscribeData encodes using the stream's subscriptions list and drops the DATA (droppedHandler, then doSubscribeComplete, which acks and commits) when that list is empty.

    mqtt-kafka (MqttKafkaSubscribeFactory):

    • MqttSubscribeProxy.onMqttFlush → onFiltersChanged → KafkaMessagesProxy.doKafkaFlush rebuilds the whole fetch filter set and the subscriptionIds/subscriptionFlags lists from the flush's full filter list. The proxy already has "replace" semantics, provided the flush carries one entry per filter.
    • A flush with an empty filter list and no packetId is ignored in onMqttFlush. That is pre-existing UNSUBSCRIBE behaviour and I have not traced its effect.
    • Not traced: how a level stream's merged fetch positions itself against the client's consumer group (groupId = prefix-clientId) when its filters change. Offsets are committed via offsetsPerPacketId and clientHighWaterMarks.

    Proposed behaviour

    State and stream rules, in terms of the filter:

    • Session state: replace by filter string. Remove any existing entry with the same pattern and add the new one, so exactly one entry per filter holds the new qos, flags and id.
    • Subscription Identifier: the new entry carries the id of this SUBSCRIBE. If none was given it carries a generated id (supplySubscriptionId, masked), which encodePublishV5 never emits. So "absence stored" per 3.8.2.1.2 needs no new field, and a removed id disappears with the old entry.
    • Level streams: for each stream of the route, remove the old entry by filter. Then add the new entry on levels 0..newQos, and flush each touched stream with its remaining filters.
      • Same QoS: every stream swaps the entry in place, so there is one delivery and no duplicate.
      • Downgrade: levels above the new QoS lose the entry.
      • Upgrade: levels up to the new QoS gain it.
    • Proxy / consumer group: no new frames. The flush on each touched level stream already replaces the Kafka fetch filters. The consumer group, offset commits and clientHighWaterMarks are untouched.
    • Retain Handling 0: existing retained path, re-sent from SEND_RETAINED_FLAG on the new entry as before. Retain Handling 1 on an existing filter must not re-send.
    • No IDL change expected. MqttSessionState items and MqttSubscribeFlushEx filters already carry id, qos, flags and pattern.

    Pattern to mirror

    The UNSUBSCRIBE path is filter-keyed in exactly the places that need to change:

    • onDecodeUnsubscribe → doSendSessionState (state minus entries whose filter is in the list)
    • onSessionData shrink branch → sendUnsuback
    • MqttSubscribeStream.getSubscriptionByFilter / doSubscribeFlushOrEnd (remove the entry from each level stream, then flush the remaining filters)

    Replacement is "remove by filter, then add" on the same three seams.

    Open question for the orchestrator (needs a decision before "go")

    Messages in flight on a level stream that loses its last entry (the QoS 2 to 0 case). Both specs forbid losing them. The 3.1.1 text reads "the flow of publications MUST NOT be interrupted [MQTT-3.8.4-3]". The 5.0 text reads "Applicaton Messages MUST NOT be lost due to replacing the Subscription" [MQTT-3.8.4-4]. DATA already on its way to a level stream after the flush is dropped by onSubscribeData (empty list) and its offset is committed. Unsubscribe has the same pre-existing behaviour, but a replacement must not lose them.

    I found no existing implementation in these modules that drains a stream whose entries were removed. Ordering the new level-0 fetch against frames already queued on level 2 also depends on the untraced positioning above. Options I see:

    1. Keep the replaced entry live on the old level stream until that stream's already-received DATA has been delivered, then drop it. This needs a drain marker and may need a new signal.
    2. Let the new-level stream re-read from the group's committed offset. This risks duplicates, which a QoS 2 to 0 downgrade is meant to avoid.

    I am not inventing either. I need your call, or a pointer to an existing pattern. If this cannot be shown to fail or be fixed within the rules, I will record the analysis here instead.

    Test plan (after "go")

    Scripts for v5 and v4 in specs/binding-mqtt.spec, each client/server pair plus the spec-level IT and the binding IT, as new methods in existing classes:

    • same-QoS re-subscribe: one state entry, one delivery
    • QoS 2 to 0 downgrade: delivered at 0
    • 0 to 2 upgrade
    • Subscription Identifier added, changed and removed
    • Retain Handling 0 resend

    Add specs/binding-mqtt-kafka.spec scripts only if the proxy changes. The first commit holds only the failing scripts.

    OASIS text

    Read:

    • 3.1.1 mqtt-v3.1.1-os.html: 3.8.4 Response ([MQTT-3.8.4-3], -6).
    • 5.0 mqtt-v5.0-os.html: 3.8.4 SUBSCRIBE Actions ([MQTT-3.8.4-3], -4, -8), 3.8.2.1.2 Subscription Identifier, 3.8.3.1 Subscription Options, and the non-normative text on identifiers being removed when the same Topic Filter is re-subscribed.

    Quotes, shortened:

    • 5.0 [MQTT-3.8.4-3]: "…identical to a Non-shared Subscription" "then it MUST replace that existing Subscription with a new Subscription"
    • 5.0 [MQTT-3.8.4-4]: "If the Retain Handling option is 0, any existing retained messages matching the Topic Filter MUST be re-sent" / "but Applicaton Messages MUST NOT be lost due to replacing the Subscription"
    • 5.0 [MQTT-3.8.4-8]: "The QoS of Application Messages sent in response to a Subscription MUST be the minimum of the QoS" "of the originally published message and the Maximum QoS granted by the Server"
    • 5.0 3.8.2.1.2: "If there is a Subscription Identifier, it is stored with the subscription." / "If this property is not specified, then the absence of a Subscription Identifier is stored with the subscription."
    • 3.1.1 [MQTT-3.8.4-3]: "then it MUST completely replace that existing Subscription with a new Subscription." "…the flow of publications MUST NOT be interrupted"
    • 3.1.1 [MQTT-3.8.4-6]: "The QoS of Payload Messages sent in response to a Subscription MUST be the minimum of the QoS of the originally published message and the maximum QoS granted by the Server."

    Not read: 3.1.1 sections 3.8.3 and 4.x, and 5.0 4.3/4.6, which did not appear in the page chunks returned. The last 6,290 characters of the 5.0 page were also not read. Clause numbers in the 3.1.1 and 5.0 body text differ: 3.1.1 has the flow rule inside -3 and the QoS rule as -6, while 5.0 has no-loss as -4 and the QoS rule as -8.


    Generated by Claude Code

  2. jfallows commented on Nov 14, 2026

    @jfallows
    ContributorAuthor

    Feasibility of delivering in-flight DATA against the replacement subscription: not possible without a new mechanism

    The decision was to deliver DATA already on a level stream that loses its last entry (QoS 2 to 0) against the replacement subscription, at min(published QoS, new granted QoS) [MQTT-3.8.4-8], with no drain marker, no new signal and no re-read from the committed offset. I checked whether the old level stream can encode a frame from an entry it no longer holds. Read only, on develop (6ee5654); nothing was run.

    What the encode path uses (MqttServerFactory):

    • MqttSubscribeStream.onSubscribeData reads the stream's subscriptions list in one place only: the guard payload != null && !subscriptions.isEmpty(). When the list is empty the frame goes to droppedHandler and doSubscribeComplete, which acks and commits the offset.
    • encodePublishV4 / encodePublishV5 take the subscriptions list as a parameter but do not read it. The QoS is the qos argument, which onSubscribeData passes as the stream's own final qos (its level). The Subscription Identifiers come from subscribeDataEx.subscribe().subscriptionIds(), which the mqtt-kafka proxy filled from the old entry at fetch time.
    • After the encode, onSubscribeData branches on the same stream-level qos: qos == 0 || !hasFin replies with a window; otherwise it registers qos1Subscribes / qos2Subscribes and waits for the client's PUBACK or PUBREC.

    What a stream at level 2 would do with an in-flight frame after the downgrade:

    1. It encodes at QoS 2, not at min(published, new granted) = 0, and waits for a PUBREC that a QoS 0 subscription does not expect.
    2. It carries the old Subscription Identifier. The replacement's identifier exists only in the stream's subscriptions entry, which the encode does not read.
    3. Delivering at the lower QoS needs a per-frame QoS below the stream's level and a matching ack branch. The replacement's QoS would have to stay reachable from a stream whose level is above it.
    4. Keeping the replacement entry (qos 0) on the level-2 stream does not work. doSubscribeFlush builds the Kafka fetch filters from the stream's subscriptions, and doKafkaFlush conditions each filter on its maxQos and the stream level. A qos-0 entry on the level-2 stream would still fetch QoS 2-published messages there, while the level-0 stream fetches all messages for that filter. That delivers the same message twice, which the issue also forbids.

    So this needs a field or list separating "entries kept for delivering in-flight frames" from "filters sent to the proxy", per-frame QoS and identifier selection, and a changed ack path. None of that exists in these modules, and the instructions are not to invent one. I am stopping here and writing no scripts or code. Open for the maintainer: (a) accept a new mechanism of that kind, (b) take the no-loss guarantee from the proxy side, or (c) narrow the scope of #3217.

    The replace-by-filter design for the state and the level streams (the UNSUBSCRIBE seams) is unaffected.


    Generated by Claude Code

  3. jfallows commented on Nov 14, 2026

    @jfallows
    ContributorAuthor

    Scope narrowed by the maintainer's decision: #3217 now covers replacing the subscription entries (one session-state entry per filter; the new QoS, options and Subscription Identifier take effect; old level streams stop carrying the old entry; new levels gain it; Retain Handling 0 resend via the existing retained path).

    The "Expected" bullet about not losing messages in flight to the replacement moved to #3230. Frames already received on a level stream that loses its last entry are still dropped, as they are for UNSUBSCRIBE today; the PR for #3217 will state that and will not claim [MQTT-3.8.4-4] / 3.1.1 [MQTT-3.8.4-3] are fully met.


    Generated by Claude Code

  4. self-assigned this
    on Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions