Skip to content

fix(binding-mqtt): answer an unroutable filter with a per-filter suback failure - #3191

Merged
jfallows merged 4 commits into
fix/3175-mqtt-v5-failure-publish-acksfrom
fix/3177-mqtt-per-filter-suback-failure
Nov 13, 2026
Merged

jfallows merged 4 commits into
fix/3175-mqtt-v5-failure-publish-acksfrom
fix/3177-mqtt-per-filter-suback-failure

Conversation

@jfallows

Copy link
Copy Markdown
Contributor

Description

A SUBSCRIBE containing a filter that no route accepts, or that no route authorizes for the client, closed the connection (DISCONNECT 0x83 on MQTT 5, a bare close on MQTT 3.1.1), and an unauthorized filter was reported as 0x83, never 0x87. The filter was written to the session state before it was resolved. An UNSUBSCRIBE for a filter that matched no route threw a NullPointerException in sendUnsuback, and a mixed UNSUBSCRIBE answered fewer reason codes than filters.

What changed (design as posted on #3177):

  • Decision point. The mqtt server decides per filter, in onDecodeSubscribeV4/V5, before anything is written to the session state, using the same route resolution openSubscribeStreams uses. A new MqttBindingConfig.resolveSubscribeReasonCode returns 0x87 when a route matches the topic but its guard does not authorize the client, otherwise 0x83. MQTT 3.1.1 maps either to 0x80 through the existing SUBACK_FAILURE_CODE_V4.
  • Carried on the existing field. The code travels on Subscription.reasonCode, which openSubscribeStreams already encodes into the SUBACK and already uses to drop failed filters from the subscribe streams. A failed filter is added to session.unAckedSubscriptions (so its SUBACK position is kept) and is skipped when the session state is built, so it is never written to the session state, never reaches Kafka, and cannot reappear on resume.
  • Mixed SUBSCRIBE. When the session replies with the state, the SUBACK list is rebuilt in the original order from the packet's unAckedSubscriptions entries: echoed filters take their echoed code, failed ones keep theirs.
  • All filters fail. No state is written (nothing would trigger a reply); the SUBACK is encoded directly and the connection stays open.
  • Resume. A stored filter that no longer routes is skipped on the implicit resubscribe instead of closing the connection at CONNECT. The stored state is not pruned.
  • UNSUBSCRIBE. A filter that resolves to no route, or has no subscribe stream, gets 0x11 and no stream flush instead of the NPE. The ordered filter list of the packet is kept in a packet-id keyed map (unsubscribePacketFilters, mirroring session.deferredUnsubscribes) so the v5 UNSUBACK carries one code per filter, in order. A failed filter in unAckedSubscriptions no longer defers an UNSUBSCRIBE.
  • Unchanged. Malformed filters and unsupported wildcard, shared and subscription-identifier requests keep their DISCONNECT codes. No IDL change (MqttTopicFilter.reasonCode already exists). No mqtt-kafka production change: its session factory echoes the state it stores, and a failed filter never reaches it.

Fixes #3177

This PR is based on #3190's branch (fix/3175-mqtt-v5-failure-publish-acks), the top of the stack develop <- #3176 <- #3179 <- #3186 <- #3190. It will be retargeted after the PRs below it merge.

Statements checked against the OASIS text

I read the full MQTT 5.0 and 3.1.1 OASIS Standard pages myself (downloaded, converted to text, read with grep and sed) and checked the clause texts below. The same reading is posted on #3177.

  • SUBACK carries one code per filter, in order. v5 [MQTT-3.8.4-6] and [MQTT-3.9.3-1]; v3.1.1 [MQTT-3.8.4-5] and [MQTT-3.9.3-1].
  • The code may indicate failure. v5 [MQTT-3.8.4-7] ("This Reason Code MUST either show the maximum QoS that was granted for that Subscription or indicate that the subscription failed"); v3.1.1 [MQTT-3.8.4-5]. In v3.1.1 the allowed return codes are 0x00, 0x01, 0x02 and 0x80, and any other code is reserved [MQTT-3.9.3-2].
  • A multi-filter SUBSCRIBE is a combined response. v5 [MQTT-3.8.4-5], v3.1.1 [MQTT-3.8.4-4]: it is handled "as if it had received a sequence of multiple SUBSCRIBE packets, except that it combines their responses into a single SUBACK".
  • A SUBACK is still required when all filters fail. v5 and v3.1.1 [MQTT-3.8.4-1] ("MUST respond with a SUBACK packet") have no exception.
  • A failed subscription is not a protocol error. v5 4.13.2: "Acknowledgment packets PUBACK, PUBREC, PUBREL, PUBCOMP, SUBACK, UNSUBACK with a Reason Code of 0x80 or greater indicate that the received packet, identified by a Packet Identifier, was in error. There are no consequences for other Sessions or other Packets flowing on the same Session." Closing is required for Malformed Packet and Protocol Errors [MQTT-4.13.1-1] and for CONNACK/DISCONNECT with 0x80 or more [MQTT-4.13.2-1]. v3.1.1 4.8 requires closing only for a protocol violation [MQTT-4.8.0-1] or a Transient Error [MQTT-4.8.0-2].
  • The unsupported-feature disconnects stay. v5 4.13.1 lists 0x9E, 0xA1 and 0xA2 among the Protocol Error codes, and 3.2.2.3.11 says a wildcard SUBSCRIBE to a server that does not support wildcards "is a Protocol Error. The Server uses DISCONNECT with Reason Code 0xA2".
  • UNSUBACK. v5 [MQTT-3.10.4-4], [MQTT-3.10.4-5] ("Even where no Topic Subscriptions are deleted, the Server MUST respond with an UNSUBACK"), [MQTT-3.10.4-6]; one reason code per filter in order [MQTT-3.11.3-1] from Table 3-9 [MQTT-3.11.3-2]; 0x11 is "No matching Topic Filter is being used by the Client". v3.1.1 UNSUBACK has no payload (Remaining Length 2), so the mixed-case fix applies to v5 only and the v4 UNSUBACK scripts carry no per-filter codes.
  • No ordering constraint on a direct SUBACK. The ordering clauses are within one packet ([MQTT-3.9.3-1], [MQTT-3.11.3-1]) and v5 4.6 ([MQTT-4.6.0-1] to [MQTT-4.6.0-6], PUBLISH/PUBACK/PUBREC/PUBREL order). Nothing orders a SUBACK relative to other acknowledgements.
  • Session state for a failed filter is my reading, not a MUST. v5 4.1 says the Server's Session State includes "The Clients subscriptions, including any Subscription Identifiers", and [MQTT-3.8.4-7] says the failed code indicates "that the subscription failed". I read a failed filter as not being a subscription, so it is left out of the state. No clause says "MUST NOT store a failed subscription".

Scripts rewritten, with the reason

subscribe.unroutable and subscribe.invalid.topic.guarded.identity.param (network v5 and v4, application) encoded DISCONNECT 0x83 (v5) and a bare close (v3.1.1) for an unroutable filter. The decision recorded on #3171 and #3177 is that the SUBACK form is the intended behavior: the "MUST respond" clauses ([MQTT-3.8.4-1], v5 [MQTT-3.8.4-6] and [MQTT-3.8.4-7], v3.1.1 [MQTT-3.8.4-5]) and 4.13.2 were not reconciled by the specification, and the issue chose the acknowledgement form, which 4.13.2 describes as having "no consequences for other ... Packets flowing on the same Session". They are rewritten in their own commit so a reviewer can see exactly what changed: they now expect SUBACK 0x83 (0x80 on v4) followed by a normal DISCONNECT. The IT methods are renamed to match.

Beyond a mechanical merge

Rebasing onto #3190 had one real conflict, in the MqttServer constructor: #3186 removed the unAckedReceivedQos1PacketIds and unAckedReceivedQos2PacketIds initializers next to where I add unsubscribePacketFilters. I kept only my initializer. The three IT files where both sides appended methods at the end of the class were resolved by taking the base file and re-appending my methods. Nothing else was changed.

Test evidence

Test-first: the first commits hold the scripts and ITs only. Against the unchanged production code (those commits on top of #3190's head, 9c85f3088), the new and rewritten server ITs failed, for v5 and v4:

  • shouldSubscribeTopicFiltersUnroutableMixed, shouldSubscribeTopicFiltersUnroutableAll, shouldSubscribeTopicFilterUnauthorized, shouldSubscribeUnroutable, shouldSubscribeInvalidTopicGuardedIdentityParam: the connection was closed instead of a SUBACK being sent.
  • shouldUnsubscribeTopicFilterUnroutable: NullPointerException: Cannot read field "id" because "resolved" is null.
  • shouldUnsubscribeTopicFiltersMixedSubscribedAndNot (v5): the UNSUBACK had one reason code where two were expected. The v4 variant passes on unchanged code because a v3.1.1 UNSUBACK has no payload; it is a no-regression check and not a failing-first test.
  • shouldSessionSubscribeUnroutableResume: the CONNECT was closed with no CONNACK.

The spec peer-to-peer ITs passed, so the scripts agree with each other. No other test in those classes failed.

After the fix, each module run with clean verify, checkstyle and license checks on, build cache skipped (-Dmaven.build.cache.skipCache=true), upstream modules installed with -am:

  • specs/binding-mqtt.spec: 518 ITs, 0 failures, 2 skipped (+ 78 unit and schema tests, 4 skipped)
  • specs/binding-mqtt-kafka.spec: 260 ITs, 0 failures (+ 27 unit tests)
  • runtime/binding-mqtt: 419 ITs, 0 failures, 6 skipped (+ 44 unit tests)
  • runtime/binding-mqtt-kafka: 148 ITs, 0 failures (+ 10 unit tests)

MqttKafkaSubscribeProxyIT.shouldReceiveServerSentRetainedReset did not fail in this run.

New scenarios, each with network v5 and v4 scripts (except where noted) and an application script pair: subscribe.topic.filters.unroutable.mixed, subscribe.topic.filters.unroutable.all, subscribe.topic.filter.unauthorized (guard roles config, v5 0x87, v4 0x80), unsubscribe.topic.filter.unroutable, unsubscribe.topic.filters.mixed.subscribed.and.not, session.subscribe.unroutable.resume (the v4 application script is ...resume.session.expiry.never).

Not delivered

  • No mqtt-kafka production change or script. Its session factory echoes the stored state and a failed filter never reaches it, so there is nothing new to pin there. Both mqtt-kafka modules are verified above only as dependents.
  • A reason code set by the application peer in the echoed session state (the existing *.non.successful scripts) still leaves that filter in the session state. Nothing sets such a code today.
  • sendUnsuback still takes the reason code of the last stream when a filter appears on several QoS streams.

Follow-ups

  1. 0x8F "Topic Filter invalid" for a filter no route allows this client. MQTT 5.0 Table 3-8 defines it as "The Topic Filter is correctly formed but is not allowed for this Client", and Table 3-9 (UNSUBACK) uses the same words. The other candidates read: 0x83 "The SUBSCRIBE is valid but the Server does not accept it", and 0x87 "The Client is not authorized to make this subscription". This PR uses 0x87 when a route matches the topic but its guard rejects the client, and 0x83 when no route matches, as decided on mqtt: an unroutable or unauthorized filter should get a per-filter SUBACK failure code, not close the connection #3177. Both readings are defensible from the table text; 0x8F is the closest wording for "no route allows this client" and is left for a decision.
  2. mqtt-kafka route mismatch. MqttKafkaBindingConfig.resolveAll keeps the routes that match any filter of a SUBSCRIBE, against a route table separate from the mqtt binding's. If no route matches, MqttKafkaSubscribeFactory rejects the stream, and the server answers DISCONNECT 0x83 (onSubscribeReset). If only some filters match, the unmatched ones are granted in the SUBACK but never delivered. Originating a per-filter code from mqtt-kafka means setting reasonCode in the state that the session factory persists in the compacted sessions topic.
  3. Decide what the application peer should do with a failed filter it reports in the session state (see Not delivered), and whether sendUnsuback should combine the codes of several streams.

Generated by Claude Code

…uback failure

An unroutable or unauthorized filter in a SUBSCRIBE should get a failure
code in its SUBACK position and leave the connection open, and an
UNSUBSCRIBE for a filter that is unroutable or was never subscribed
should get an UNSUBACK entry per filter (0x11 on MQTT 5).

Network and application scripts for v5 and v4: mixed granted and
unroutable filters, all filters unroutable, an unauthorized filter,
UNSUBSCRIBE for an unroutable filter, and a mixed UNSUBSCRIBE.

Against the unchanged binding the new server ITs fail: the SUBSCRIBE
closes the connection instead of answering, and the UNSUBSCRIBE throws a
NullPointerException on the unresolved route.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SiHVoVWUEF6tRdct6rasgP
…k form

subscribe.unroutable and subscribe.invalid.topic.guarded.identity.param
(network v5 and v4, application) encoded DISCONNECT 0x83 on v5 and a
bare close on v4 for a filter that cannot be routed. The decision
recorded on #3171 and #3177 is the SUBACK form: the filter gets a
failure code in its SUBACK position and the connection stays open
(MQTT 5.0 [MQTT-3.8.4-1], [MQTT-3.8.4-6], [MQTT-3.8.4-7], section 3.9.3;
MQTT 3.1.1 [MQTT-3.8.4-1], [MQTT-3.8.4-5], return code 0x80).

The scripts now expect SUBACK 0x83 (0x80 on v4) followed by a normal
DISCONNECT, and the application side no longer sees the filter in the
session state. The IT methods are renamed to match the scenarios.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SiHVoVWUEF6tRdct6rasgP
…le stored filter

A resumed session whose stored state still holds a filter that no longer
routes should connect with the session present, skip that filter, and
resubscribe only the routable ones. Against the unchanged binding the
CONNECT is answered with a close instead of a CONNACK.

Network v5 and v4, application scripts for session expiry unset (v5) and
session expiry never (v4).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SiHVoVWUEF6tRdct6rasgP
…ck failure

A filter that cannot be routed, or that no route authorizes for the
client, now gets a failure code in its SUBACK position (0x87 not
authorized, 0x83 otherwise; 0x80 on MQTT 3.1.1) and the connection stays
open. The other filters of the SUBSCRIBE are granted as usual.

The failure is decided per filter before the session state is written,
so a failed filter is never written to the session state or subscribed.
A SUBSCRIBE whose filters all fail is answered directly. A resumed
session skips a stored filter that no longer routes instead of closing
the connection.

An UNSUBSCRIBE for a filter that matches no route or was never
subscribed now gets its UNSUBACK entry (0x11 on MQTT 5) instead of a
NullPointerException, and a mixed UNSUBSCRIBE gets one reason code per
filter in order.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SiHVoVWUEF6tRdct6rasgP

Copy link
Copy Markdown
Contributor Author

CI: testing (mqtt.kafka.proxy) failed once on this head and passed on re-run

Run 43347949420, head 3fd498c50e96bf07d8dae84e67950593e1b886fa. Attempt 1 failed in testing (mqtt.kafka.proxy) (job 131635472986) and so did the aggregate Examples job. I re-ran the failed jobs once on the same head. Attempt 2 passed: testing (mqtt.kafka.proxy) (job 131638822749) and Examples are both green.

I read this as a timing race in the example's own examples/mqtt.kafka.proxy/.github/test.sh, not a regression from this PR. This PR does not touch that script, and I am leaving it alone here.

What the failed attempt showed (job log, plus the zilla and kafka container logs from the uploaded artifact mqtt.kafka.proxy_logs.tgz):

  • test.sh starts mosquitto_sub on topic zilla in the background, runs sleep 1, then publishes Hello Zilla!. In attempt 1 the subscriber's output was empty (RESULT=0, OUTPUT= against EXPECTED=Hello Zilla!), with no error on the publish.
  • The Kafka log shows the topic partitions being created slowly, after the test had started at 02:02:27: mqtt-messages-0 at 02:02:19.8, mqtt-devices-0 at :23.3, mqtt-retained-0 at :26.7, mqtt-sessions-0 at :29.8, about 3 s apart. The first probe publish was refused for about 4 s (Connection Refused at 02:02:31) and succeeded on the retry at 02:02:33.9. The kafka-init container reports healthy at 02:02:17, so the test does not wait for topic creation.
  • The runner was slow in that job: restoring the shared example image cache took 29 s (10 s in the passing feat(binding-mqtt): answer a failed mqtt 5 publish with a failure PUBACK or PUBREC #3190 run) and loading the example images 18 s (13 s).
  • The zilla container log has no exception and no error line, only the engine start and three BINDING_MQTT_CLIENT_CONNECTED events.

What the passing attempt showed: Execute Test took 9 s (02:10:22 to 02:10:31). The first probe was refused once here too (0.5 s, Connection Refused at 02:10:23, reachable at 02:10:26), the subscriber printed Hello Zilla!, and RESULT=0. The same job also passed on #3190's head 9c85f3088 (run 43347949502, job 131635478521, 9 s).

Why this PR is not the cause, as far as I can tell: the example's mqtt binding has no guard and a single route with no when (its binding-level exit becomes that route), so its SUBSCRIBE resolves and is granted; the integration tests that use the same route shape get grants and deliver messages. The SUBACK is sent before the Kafka fetch for the subscription is positioned, and test.sh leaves only sleep 1 before it publishes, so on a slow broker the message can be published before the subscription is live.

What I could not prove:

  • I could not reproduce the failure locally. The build environment's Maven allowlist blocks several third-party artifacts (jackson-databind, testcontainers, maven-resolver-impl, jose4j, commons-lang3), so binding-kafka, the launcher modules and the Docker image cannot be built there.
  • One failure and one pass on the same head show it is not deterministic. They do not show which timing detail decided the outcome.

The sleep 1 race in test.sh is a separate follow-up and is not part of this PR.


Generated by Claude Code

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.

mqtt: an unroutable or unauthorized filter should get a per-filter SUBACK failure code, not close the connection

2 participants