Skip to content

fix: inherit broker ack_policy for router subscribers declared - #3394

Open
ce1ebrimbor wants to merge 19 commits into
ag2ai:mainfrom
ce1ebrimbor:fix/router-ack-policy-inheritance
Open

ce1ebrimbor wants to merge 19 commits into
ag2ai:mainfrom
ce1ebrimbor:fix/router-ack-policy-inheritance

Conversation

@ce1ebrimbor

@ce1ebrimbor ce1ebrimbor commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A subscriber copied ack_policy when it was constructed. include_router only composes the config, so a handler declared on a router before the include kept the built-in default, and Kafka kept auto-commit on.

The subscriber now keeps its config and reads the policy from it: on demand until it starts, then fixed from start() to stop(), so a running consumer, its driver options and the ack middleware always agree. Kafka and Confluent derive enable_auto_commit and the parser's message class from that policy, RabbitMQ derives no_ack.

Fixes #3339

Behaviour changes

  • Router subscribers without their own ack_policy follow the router and broker policy, whatever the declaration order (Kafka, Confluent, RabbitMQ, NATS, MQTT, Redis streams).
  • Kafka (aiokafka): any policy other than ACK_FIRST now needs a group_id, as Confluent already required. Without a group commit() raised IllegalOperation at runtime and no offset was stored. SetupError is raised where the subscriber is declared, or at broker.start() when the policy only arrives with a later include_router.
  • Kafka and Confluent validate the resolved policy, so a broker- or router-level policy counts as much as a subscriber-level one. Confluent used to check the subscriber's own policy only.
  • Kafka and Confluent: a subscriber with max_workers > 1 that inherits a commit policy after it was declared fails at broker.start() with SetupError. On Kafka an explicit policy, or a router included first, still selects the partition-aware subscriber.
  • Kafka: max_workers > 1 with several topics, a pattern or partitions is refused under a broker-level commit policy too. It used to be accepted, and every topic but the first was silently dropped.
  • NATS JetStream push: ACK_FIRST now acknowledges before the handler runs. nats-py's own auto-ack fired after the callback, so msg.nack() inside the handler still took effect; it no longer does.
  • TestBroker refuses at start what the real broker refuses, under TestApp too.
  • Warnings fire where the policy is set, at broker and router level as well: Kafka's REJECT_ON_ERROR hint and MQTT's NACK_ON_ERROR redelivery warning. NATS no longer warns that ACK_FIRST has no effect on a JetStream pull subscriber: it acknowledges before the handler there too.
  • subscriber.ack_policy is now a read-only property.

How it is built

  • The group_id and max_workers rules are one method of the subscriber config, validate_ack_policy(). The factory calls it at declaration, _pre_start() calls it again at start, and every broker runs _validate_subscribers() before it connects.
  • _setup() is the hook for state a subscriber can only derive once its config is composed. Kafka and Confluent set the parser's message class there, and MQTT's parser re-resolution moved into it from start() and TestMQTTBroker.
  • TestKafkaBroker(with_real=True): the fake subscribers created for publishers are pinned to ACK_FIRST. They have no group and would otherwise inherit a broker-level commit policy.

Open question

A running subscriber keeps its policy when its router is included into another broker (review comment). Moving a running router already detaches its subscribers from the first broker's stop(), on main as well, so refusing the move in include_router would be simpler than freezing the policy. This PR keeps the freeze.

Type of change

  • Breaking change (a fix or feature that would disrupt existing functionality)

Checklist

  • I have read and followed the AI Policy
  • My code adheres to the style guidelines of this project (just lint shows no errors)
  • I have conducted a self-review of my own code
  • I have made the necessary changes to the documentation
  • My changes do not generate any new warnings
  • I have added tests to validate the effectiveness of my fix or the functionality of my new feature
  • Both new and existing unit tests pass successfully on my local environment by running just test-coverage
  • I have ensured that static analysis tests are passing by running just static-analysis
  • I have included code examples to illustrate the modifications

AI assistance

  • I understand these changes and can explain them in my own words.
  • I checked the PR description against the actual diff.
  • If I used AI, I reviewed, tested, and validated its generated code or text before submitting.

… include

A subscriber copied ack_policy at construction, so a router subscriber declared before include_router kept the built-in default. The policy is now re-resolved when the subscriber binds (start, schema, TestBroker), and derived state is rebuilt from it.

Kafka and Confluent: the parser ack mode and enable_auto_commit follow the resolved policy. A concurrent subscriber (max_workers > 1) whose resolved policy is not ACK_FIRST now fails at start with SetupError.

Rabbit: no_ack follows the resolved policy when consuming starts.

Tests: one in-memory test covers inheritance and precedence for Kafka, Confluent, Rabbit, NATS, MQTT and Redis. Includes the Kafka and Confluent guard tests and a Kafka batch commit test.
@ce1ebrimbor ce1ebrimbor self-assigned this Nov 23, 2026
@github-actions github-actions Bot added Confluent Issues related to `faststream.confluent` module AioKafka Issues related to `faststream.kafka` module labels Nov 23, 2026
RedisClusterTestcaseConfig inherited the default channel subscriber for the generic ack test. Channel subscribers are always MANUAL, so the three cases failed. Override the ack hooks with a consumer-group stream, as standalone Redis does.

@Lancetnik Lancetnik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 24 in-memory policy cases pass on 3743a637, including both overrides in subscriber > router > broker. Before merging, please address the missing consumer-group checks and the point at which the policy takes effect. The connected Kafka batch test passes even when the driver rejects the commit.

One smaller follow-up concerns warnings. MQTT documents a redelivery warning for NACK_ON_ERROR. A router subscriber that inherits it from the broker gets the behavior silently. Both Kafka backends also skip the REJECT_ON_ERROR warning on inheritance. JetStream Pull's explicit ACK_FIRST warning says the option has no effect, although the callback acknowledges before the handler. Please check these diagnostics against the effective policy. MQTT documentation

Reviewed with Codex using local reproductions on Python 3.11.14. The batch test ran against Kafka, and the RabbitMQ and JetStream callback checks used transport doubles.

Comment thread faststream/kafka/subscriber/usecase.py Resolved
Comment thread faststream/kafka/subscriber/usecase.py Resolved
Comment thread tests/brokers/kafka/test_ack_policy.py Resolved
Comment thread tests/brokers/base/consume.py Resolved
Comment thread tests/brokers/base/consume.py Resolved
ACK, MANUAL, REJECT_ON_ERROR and NACK_ON_ERROR commit offsets and need a consumer group. Kafka accepted group-less subscribers and failed on the first commit: the middleware logged CRITICAL and no offsets were saved. Confluent silently joined faststream-consumer-group. Router subscribers inherit the broker policy after declaration, so both paths were reachable from the inheritance fix.

broker.start() now runs subscriber checks before connect, so a misconfigured subscriber fails without connecting to the broker. TestBroker runs the same checks. The group_id check lives in _pre_start next to the concurrency check.

Tests: the Kafka testcase config gives group-bearing ack params. Guard tests run broker.start() against an unreachable bootstrap; the Confluent guard asserts connect is not awaited. New refusal tests cover the four commit policies, inherited policies, and TestBroker. A connected Kafka test checks that an inherited MANUAL policy advances the committed offset.

Docs: group_id requirement on the Kafka and Confluent ack pages; the Kafka MANUAL example gets a group.
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Nov 23, 2026
Router subscribers declared before include_router copied the built-in default policy in __init__. The copy was refreshed only in _build_fastdepends_model, so the policy read before start, schema or TestBroker was wrong and depended on call order.

ack_policy and auto_ack_disabled are now properties over the subscriber config, and _resolve_ack is gone. start() calls _on_ack_resolved() after _pre_start(); TestBroker calls it before _build_fastdepends_model(). Rabbit no_ack moved into _on_ack_resolved(), which removes its constructor copy that TestBroker consume read.

Test: SubscriberAckPolicyTestcase reads sub.ack_policy after include_router and before start, on every in-memory broker.
MQTT sets nack_is_observable to False, so its NACK case had no assertion of its own, and nothing checked that the handler ran. The case passed when the handler never ran. The handler now sets an event and the test asserts it after publish. Checked by publishing to an unsubscribed queue: the MQTT cases then fail on the new assertion, and without it the four MQTT NACK cases pass.
A JetStream push subscriber chose manual_ack from the policy declared on the subscriber. A declared ACK_FIRST used nats-py auto-ack, which acks after the callback returns, and was rewritten to MANUAL. An inherited ACK_FIRST kept manual_ack=True and was acked by the middleware before the handler. The two forms settled differently, and a nack inside the handler only worked in the first.

Push subscribers now always pass manual_ack=True and keep the declared policy, so the ack middleware settles every policy. ACK_FIRST acks before the handler in both forms, as the acknowledgement guide says.

Breaking: with ACK_FIRST declared on a push subscriber, the ack now precedes the handler, and a nack or reject inside the handler has no effect.

Test: one handler covers both forms and asserts the driver calls are ack, then handler.
The partition-aware mode is selected when the subscriber is declared. A router subscriber declared before include_router that then inherits a commit policy from the broker is refused at broker.start(). The Kafka page now states the restriction and the workaround: set ack_policy on the subscriber, or include the router first.

The Confluent page said the max_workers refusal happens at declaration. It now adds that an inherited policy is refused at broker.start().
A subscriber reads its policy from the composed config until it starts, then keeps a snapshot until it stops. Kafka and Confluent derive enable_auto_commit from the effective policy on read, and RabbitMQ reads no_ack the same way. The values are right as soon as a router is included (ag2ai#3339), and a later include_router no longer changes a consumer that is already running.

The max_workers refusal message now says the policy is inherited from the broker or router.

Tests: the ag2ai#3339 reproduction for both Kafka backends, and a started consumer keeping its policy on every broker. Driver checks for a late-included router: Kafka and Confluent disable auto-commit and read the failed record again, RabbitMQ consumes with no_ack=True. The Kafka batch test now checks the committed offset. A restart-based settlement test covers Kafka, Confluent and RabbitMQ.
@github-actions github-actions Bot added the NATS Issues related to `faststream.nats` module and NATS broker features label Nov 24, 2026
Validation ran in TestBroker._create_ctx, which TestApp skips, so an
in-memory app accepted a configuration production start refuses. It now
runs in the fake start itself.

With with_real=True the real start also validated the publishers' fake
subscribers: they have no group_id and inherited the broker's ack policy,
so a broker-level commit policy failed with SetupError. Fakes are pinned
to ACK_FIRST.
The group_id and max_workers rules lived in the usecase's _pre_start and,
for Confluent, a second time in the factory with other messages. They are
now one method of the config, validate_ack_policy.

The factory calls it on the resolved policy, so a subscriber-level or an
already visible broker-level policy is refused where the subscriber is
declared; start() keeps the check for a router included later. aiokafka
gains the declaration-time check Confluent already had.

enable_auto_commit and the parser's message class are now derived in one
place: the config no longer writes enable_auto_commit and the constructor
no longer picks the message class. RabbitSubscriberConfig.ack_first had
no reader left and is gone.
…ed policy

With max_workers > 1 and a commit policy, the factory picks the
partition-aware subscriber from the resolved policy but validated its
single-topic, pattern and partitions rules against the subscriber's own
policy only. Under a broker-level policy several topics were therefore
accepted and all but the first one silently dropped. The rules now see
the resolved policy.
…uter

_on_ack_resolved was ack-specific, while MQTT already re-derived its
parser in the same two places by overriding start() and TestMQTTBroker's
fake start. The hook is now _setup(), called by start() and by the fake
start, and MQTT's parser re-resolution moves into it.
BrokerUsecase._validate_subscribers promises to run before connect, but
only the Kafka brokers called it. A _pre_start added to another broker's
subscriber would have run after the connection was open and after the
subscribers declared before it had started.
The Redis subscriber stored the same config object a second time under
its own slot. `config` stays readable as before.
Kafka's REJECT_ON_ERROR hint and MQTT's NACK_ON_ERROR redelivery warning
fired only for a subscriber's own policy (MQTT: for whatever policy was
visible at declaration), so a router included later inherited either one
silently. The broker and router constructors now warn as well, pointing
at the line that set the policy. MQTT's subscriber-level warning moves to
the factory, where it points at the registering line instead of at
FastStream.

NATS: drop the warning that ACK_FIRST has no effect on a JetStream pull
subscriber. The middleware acknowledges before the handler there too.
- One in-memory case per broker pins the reported bug; the two override
  rows passed before the fix and fail together with test_config.py.
- test_settlement_reaches_broker passed before the fix and half of its
  instances skipped; it is gone, with its redelivers_to_new_consumer flag.
- The started-subscriber case runs in memory through subscriber.start()
  instead of against every real broker.
- The pre-start read of ack_policy moves to IncludeSubscriberTestcase,
  next to the other options a late include must pass down.
- get_ack_subscriber_params replaces get_cancel_ack_subscriber_kwargs and
  supports_cancel_ack_skip: the two tests that used them now run on NATS,
  Redis and MQTT too instead of skipping.
Kafka now refuses it at declaration like Confluent; only a policy that
arrives with a later include_router waits for broker.start(). The
resolution order names the router level, and the MQTT page says the
NACK_ON_ERROR warning fires at every level.
@github-actions github-actions Bot added Redis Issues related to `faststream.redis` module and Redis features MQTT Issues related to `faststream.mqtt` module labels Nov 24, 2026
@ce1ebrimbor

Copy link
Copy Markdown
Collaborator Author

@Lancetnik The PR took different proportions, thanks for the review !

@Lancetnik Lancetnik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two regressions from the follow-up validation changes, checked with Codex against d78fc429.

if self.ack_first:
return

if not self.group_id:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rejects a Confluent consumer that already has a group through the broker’s public config argument:

broker = KafkaBroker(config={"group.id": "workers"}, ack_policy=AckPolicy.ACK)
broker.subscriber("orders")

On the base revision, a live Kafka run with this configuration committed offset 1 after processing one record. On this revision, declaring the subscriber raises SetupError because self.group_id only sees the subscriber argument. Please validate the effective group using the same precedence as the consumer builder. A regression test should accept the example above and still reject inherited ACK when neither the subscriber nor the broker config supplies a group. Consumer config merge

@ce1ebrimbor ce1ebrimbor Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validation now uses the group the consumer builder would use: group.id from the broker config, else the subscriber's group_id. Your example is accepted
(test_group_from_broker_config_serves_inherited_commit_policy); with no group in either place an inherited commit policy is still refused (test_group_less_inherited_commit_policy_refused_at_declaration).

Comment thread faststream/kafka/subscriber/factory.py Resolved
…ount

- Confluent: `group.id` in the broker's `config` satisfies a commit policy, as it does in the consumer builder.
- A batch subscriber ignores `max_workers`, so the concurrency rules no longer refuse it under a commit policy, whichever comes first: the declaration or the include.
@ce1ebrimbor

Copy link
Copy Markdown
Collaborator Author

@Lancetnik If you have time 🙏

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AioKafka Issues related to `faststream.kafka` module Confluent Issues related to `faststream.confluent` module documentation Improvements or additions to documentation MQTT Issues related to `faststream.mqtt` module NATS Issues related to `faststream.nats` module and NATS broker features Redis Issues related to `faststream.redis` module and Redis features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: broker acknowledgement policy is ignored by pre-registered router subscribers

2 participants