From 09389f934f9c668ca71f42c47a0f6375796f7956 Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Mon, 23 Nov 2026 15:24:05 -0800 Subject: [PATCH] M7, ports part 3: the Stream consumer Java V5's tests of the Stream consumer that had no Rust counterpart, ported (PLAN.md, M7; tests/PORTING.md follows in its own PR): a cumulative ack made while disconnected going first on the next subscription, members splitting the segments, a member back under its name taking the same keys again, keys keeping their order across an empty segment and as a member joins mid-traffic, a segment moving once what was taken from it is acknowledged, a member joining after another left, a consumer at latest, a missing topic created or not found, a refused lookup, a broker without scalable topics, and following the controller the layout names across brokers. Only test code changes. follows_the_controller_while_a_producer_holds_the_layout_watch is the same controller failover with a producer of the topic on the client. It fails, so it is ignored with the reason: registering again takes the controller from the layout watch the producer holds, which names the old one. A fix follows in its own PR. --- .../apache-pulsar-protocol/tests/consumer.rs | 22 ++ .../tests/stream_consumer.rs | 236 +++++++++++++++++- crates/apache-pulsar/src/stream_tests.rs | 132 +++++++++- 3 files changed, 387 insertions(+), 3 deletions(-) diff --git a/crates/apache-pulsar-protocol/tests/consumer.rs b/crates/apache-pulsar-protocol/tests/consumer.rs index 18c8987..e5e65fe 100644 --- a/crates/apache-pulsar-protocol/tests/consumer.rs +++ b/crates/apache-pulsar-protocol/tests/consumer.rs @@ -577,6 +577,28 @@ fn a_new_registration_takes_the_same_cumulative_ack_again() { assert_eq!(cumulative_acks(&t.actions()), [(5, vec![])]); } +/// Java's `V5CumulativeAckTest.testRetryingAnAckIssuedWhileDisconnectedAdvancesTheCursor`: a cumulative ack made once +/// the connection is lost waits for the next subscription, and goes out on it first, before the permits that let the +/// broker deliver again what it covers. Made again, it adds nothing. +#[test] +fn a_cumulative_ack_made_while_disconnected_goes_first_on_the_next_subscription() { + let mut t = Test::subscribed(ConsumerOptions { ack_group_time: Duration::ZERO, ..exclusive() }); + t.deliver(1, single(5)); + t.take(1); + t.consumer.on_disconnected(1, t.now); + t.consumer.acknowledge_cumulative(&id(5, -1, 0), t.now); + assert!(t.actions().is_empty(), "no subscription to send it on"); + t.advance(Duration::from_millis(200)); + assert_eq!(t.actions(), [Action::Connect { generation: 2 }]); + t.consumer.on_subscribed(2, 8); + let actions = t.actions(); + assert_eq!(cumulative_acks(&actions[..1]), [(5, vec![])]); + assert_eq!(commands(&actions)[0].ack.consumer_id, 8, "on the new subscription"); + assert_eq!(actions[1..], [Action::Send(Box::new(permits(8, 4)))]); + t.consumer.acknowledge_cumulative(&id(5, -1, 0), t.now); + assert!(t.actions().is_empty()); +} + #[test] fn a_cumulative_ack_made_while_subscribing_goes_first() { let mut t = Test::new(exclusive()); diff --git a/crates/apache-pulsar-testkit/tests/stream_consumer.rs b/crates/apache-pulsar-testkit/tests/stream_consumer.rs index 91d6ef2..8eb3ae7 100644 --- a/crates/apache-pulsar-testkit/tests/stream_consumer.rs +++ b/crates/apache-pulsar-testkit/tests/stream_consumer.rs @@ -17,9 +17,11 @@ //! The Stream consumer against the simulated cluster and its controller. Ported scenarios from Java's //! `V5StreamConsumerBasicTest`, `V5StreamConsumerDagReplayTest`, `V5StreamConsumerOrderingTest`, -//! `V5StreamConsumerAutoReconnectTest`, `V5StreamConsumerAckWatermarkTest` and the Stream consumer's case of +//! `V5StreamConsumerAutoReconnectTest`, `V5StreamConsumerAckWatermarkTest` and `V5EntryBucketDispatchTest`, the +//! Stream consumer's cases of `V5MultipleConsumersTest`, `V5MultiBrokerScalableTopicTest` (on one broker) and //! `ScalableTopicLegacySegmentTest`, and members that share segments. +use std::collections::{BTreeMap, BTreeSet}; use std::time::Duration; use apache_pulsar_protocol::consumer::ConsumerOptions; @@ -262,6 +264,43 @@ fn an_empty_segment_does_not_let_its_children_ahead_of_its_parent() { assert_eq!(assigned, [lower, upper, high]); } +/// Java's `V5StreamConsumerOrderingTest.testPerKeyOrderAcrossAnEmptySegment` as Java runs it: the member subscribes +/// before the publishes and the splits, so the splits' children get the subscription at their start, and the empty +/// child is drained as it seals, while the root still has backlog. Its children wait for the root all the same, and +/// each key keeps its order. In `an_empty_segment_does_not_let_its_children_ahead_of_its_parent` the empty child has +/// no subscription until it is assigned, so only this test fails with a controller that checks a segment's parent and +/// not the ancestors beyond it. +#[test] +fn keys_keep_their_order_across_an_empty_segment() { + let mut h = StreamHarness::new(world(1), TOPIC); + let solo = h.join("solo", options()); + let mut sent: BTreeMap> = BTreeMap::new(); + for k in 0..16 { + let (key, value) = (format!("key-{k}"), format!("key-{k}-gen0")); + publish(&mut h.world, 0, &key, &value); + sent.entry(key).or_default().push(value); + } + let (low, high) = h.world.split(TOPIC, 0); + let (lower, upper) = h.world.split(TOPIC, low); + let grandchildren = [(lower, 0, 0x3fff), (upper, 0x4000, 0x7fff), (high, 0x8000, 0xffff)]; + for k in 0..16 { + let (key, value) = (format!("key-{k}"), format!("key-{k}-gen2")); + publish(&mut h.world, route(&key, &grandchildren), &key, &value); + sent.entry(key).or_default().push(value); + } + assert!([lower, upper, high].iter().all(|&s| h.world.backlog(TOPIC, s, SUB) > 0)); + // The empty child is drained, but its children wait for the root, as its sibling does: only the root is assignable. + assert_eq!(h.world.assigned(TOPIC, SUB, "solo"), [(0, false)]); + let first = h.take(solo); + assert_eq!(first.len(), 16); + assert!([low, lower, upper, high].iter().all(|&s| h.world.consumer_count(TOPIC, s, SUB) == 0)); + h.ack(solo, &first[15].id); + let assigned: Vec = h.world.assigned(TOPIC, SUB, "solo").into_iter().map(|(s, _)| s).collect(); + assert_eq!(assigned, [lower, upper, high]); + let second = h.take(solo); + assert_eq!(by_key(&[first, second].concat()), sent); +} + /// Java's `testSealedBacklogNotRedeliveredAfterFirstConsumerDrains`. #[test] fn a_new_member_gets_nothing_acknowledged_again() { @@ -341,6 +380,74 @@ fn past_the_grace_period_the_group_rebalances() { assert_eq!(h.members[bob].consumer.segments().count(), 1); } +/// Publishes `count` messages, keyed `k-0`, `k-1`, … and valued `{batch}-0`, `{batch}-1`, …, each to the segment its +/// key goes to. Each member then takes what it has, and acknowledges the last of it. Checks that each message goes to +/// one of them, once, and that each gets some. Returns what each took. +fn take_a_batch(h: &mut StreamHarness, members: [usize; 2], batch: &str, count: usize) -> [Vec; 2] { + let mut sent: Vec = (0..count).map(|i| format!("{batch}-{i}")).collect(); + for (i, value) in sent.iter().enumerate() { + let key = format!("k-{i}"); + let segment = h.world.route(TOPIC, &key); + publish(&mut h.world, segment, &key, value); + } + let taken = members.map(|member| { + let taken = h.take(member); + if let Some(last) = taken.last() { + h.ack(member, &last.id); + } + taken + }); + assert!(taken.iter().all(|got| !got.is_empty()), "each member gets some"); + let mut got: Vec = taken.iter().flat_map(|got| values(got)).collect(); + got.sort(); + sent.sort(); + assert_eq!(got, sent, "each message once"); + taken +} + +/// Java's `V5MultipleConsumersTest.testStreamConsumersSplitSegmentsAcrossConsumers`, and on one broker +/// `V5MultiBrokerScalableTopicTest.testStreamConsumerControllerCoordinationAcrossBrokers`: two members split four +/// segments, each takes the messages of its own, and each message goes to one of them, once. +#[test] +fn members_split_the_segments_and_each_message_goes_to_one() { + let mut h = StreamHarness::new(world(4), TOPIC); + let alice = h.join("alice", options()); + let bob = h.join("bob", options()); + h.advance(Duration::from_millis(200)); + assert_eq!(h.members[bob].subscribed, Some(Ok(()))); + let taken = take_a_batch(&mut h, [alice, bob], "v", 100); + for (member, got) in [alice, bob].into_iter().zip(&taken) { + let segments: Vec = h.members[member].consumer.segments().collect(); + assert_eq!(segments.len(), 2); + assert!(got.iter().all(|m| segments.contains(&(m.id.segment_id as u64))), "from its own segments"); + } + assert!((0..4).all(|segment| h.world.backlog(TOPIC, segment, SUB) == 0)); +} + +/// Java's `V5MultipleConsumersTest.testStreamConsumerReconnectWithinGraceKeepsAssignment`: a member that closes leaves +/// the group at once, and the other takes its segments. Back under its name, it gets the same ones again, since the +/// controller orders the members by name: each member takes the same keys as before. +#[test] +fn a_member_back_under_its_name_takes_the_same_keys_again() { + let mut h = StreamHarness::new(world(4), TOPIC); + let alice = h.join("alice", options()); + let bob = h.join("bob", options()); + h.advance(Duration::from_millis(200)); + let segments = |h: &StreamHarness, member: usize| h.members[member].consumer.segments().collect::>(); + let before = (segments(&h, alice), segments(&h, bob)); + let keys = |got: &[ReceivedMessage]| got.iter().map(|m| m.key.clone().unwrap()).collect::>(); + let first = take_a_batch(&mut h, [alice, bob], "first", 80).map(|got| keys(&got)); + h.close(alice); + assert!(h.members[alice].closed); + assert_eq!(segments(&h, bob), [0, 1, 2, 3], "Bob takes Alice's segments"); + let alice = h.join("alice", options()); + h.advance(Duration::from_millis(200)); + assert_eq!(h.members[alice].subscribed, Some(Ok(()))); + assert_eq!((segments(&h, alice), segments(&h, bob)), before); + let second = take_a_batch(&mut h, [alice, bob], "second", 80).map(|got| keys(&got)); + assert_eq!(second, first); +} + /// Java's `V5StreamConsumerAckWatermarkTest`: once the broker rewinds the subscription and delivers everything again, /// the application's ack of a position it acknowledged before goes out again. #[test] @@ -376,7 +483,9 @@ fn by_key(messages: &[ReceivedMessage]) -> std::collections::BTreeMap> = BTreeMap::new(); + for i in 0..40 { + let (key, value) = (format!("k{}", i % 10), format!("again-{i}")); + publish(&mut h.world, 0, &key, &value); + sent.entry(key).or_default().push(value); + } + let (got_alice, got_carol) = (h.take(alice), h.take(carol)); + assert!(!got_alice.is_empty() && !got_carol.is_empty()); + let mut got = by_key(&got_alice); + for (key, values) in by_key(&got_carol) { + assert!(got.insert(key, values).is_none(), "a key goes to one member"); + } + assert_eq!(got, sent); + h.ack(alice, &got_alice.last().unwrap().id); + h.ack(carol, &got_carol.last().unwrap().id); + assert_eq!(h.world.backlog(TOPIC, 0, SUB), 0); +} + +/// Java's `V5EntryBucketDispatchTest.testConsumerJoiningMidTrafficPreservesPerKeyOrder`: a second member joins while +/// the first takes keyed traffic, acknowledging as it goes. The first member's Exclusive consumer gives nothing more, +/// while the traffic goes on, until the member acknowledged what it took; then the two share the segment by bucket. +/// For each key, what the first member took, then what the second took, is what was sent. +#[test] +fn a_member_joining_mid_traffic_keeps_each_key_in_order() { + let mut world = world(1); + world.set_buckets(TOPIC, 0, 4); + let mut h = StreamHarness::new(world, TOPIC); + let alice = h.join("alice", options()); + let mut sent: BTreeMap> = BTreeMap::new(); + let mut round = |h: &mut StreamHarness, i: usize| { + for k in 0..16 { + let (key, value) = (format!("key-{k}"), format!("key-{k}-{i}")); + publish(&mut h.world, 0, &key, &value); + sent.entry(key).or_default().push(value); + } + }; + let mut got_alice = Vec::new(); + for i in 0..13 { + round(&mut h, i); + let taken = h.take(alice); + h.ack(alice, &taken.last().unwrap().id); + got_alice.extend(taken); + } + // Bob joins while Alice holds the round she took, and the next one comes. + round(&mut h, 13); + got_alice.extend(h.take(alice)); + let bob = h.join("bob", options()); + round(&mut h, 14); + h.advance(Duration::from_millis(200)); + assert!(h.take(alice).is_empty(), "Alice's Exclusive consumer drains"); + assert_eq!(h.members[bob].subscribed, None); + h.ack(alice, &got_alice.last().unwrap().id); + h.advance(Duration::from_millis(500)); + assert_eq!(h.members[bob].subscribed, Some(Ok(()))); + let mut got_bob = Vec::new(); + for i in 15..40 { + round(&mut h, i); + for (member, got) in [(alice, &mut got_alice), (bob, &mut got_bob)] { + let taken = h.take(member); + if let Some(last) = taken.last() { + h.ack(member, &last.id); + } + got.extend(taken); + } + } + assert_eq!(h.world.backlog(TOPIC, 0, SUB), 0); + assert!(!got_bob.is_empty()); + let mut got = by_key(&got_alice); + for (key, values) in by_key(&got_bob) { + got.entry(key).or_default().extend(values); + } + assert_eq!(got, sent); +} + +/// Java's `V5EntryBucketDispatchTest.testSegmentReleaseWithPendingAcksHandsOffCleanly`: a member holds what it took +/// from two segments when a second member joins and gets one of them. The first member's consumer of that segment +/// gives nothing more, and closes once the member's late cumulative ack reaches it; only then does the second attach. +/// Nothing comes twice, and each key has the first member's messages, then the second's. +#[test] +fn a_segment_moves_once_what_was_taken_from_it_is_acknowledged() { + let mut h = StreamHarness::new(world(2), TOPIC); + let alice = h.join("alice", options()); + let mut sent: BTreeMap> = BTreeMap::new(); + let mut round = |h: &mut StreamHarness, i: usize| { + for k in 0..16 { + let (key, value) = (format!("key-{k}"), format!("key-{k}-{i}")); + let segment = h.world.route(TOPIC, &key); + publish(&mut h.world, segment, &key, &value); + sent.entry(key).or_default().push(value); + } + }; + for i in 0..10 { + round(&mut h, i); + } + let held = h.take(alice); + let last = held.last().unwrap().id.clone(); + assert_eq!((held.len(), last.positions.len()), (160, 2), "from both segments"); + let bob = h.join("bob", options()); + assert_eq!(h.world.assigned(TOPIC, SUB, "bob"), [(1, false)]); + // Alice lets go of segment 1, but her consumer stays while she holds its messages: Bob waits. + h.advance(Duration::from_millis(200)); + assert_eq!(h.members[alice].consumer.segments().collect::>(), [0]); + assert_eq!((h.world.consumer_count(TOPIC, 1, SUB), h.members[bob].subscribed.clone()), (1, None)); + h.ack(alice, &last); + assert_eq!(h.world.backlog(TOPIC, 1, SUB), 0, "the ack reached the consumer let go of"); + h.advance(Duration::from_millis(500)); + assert_eq!(h.members[bob].subscribed, Some(Ok(()))); + for i in 10..20 { + round(&mut h, i); + } + let (got_alice, got_bob) = (h.take(alice), h.take(bob)); + assert!(!got_bob.is_empty() && got_bob.iter().all(|m| m.id.segment_id == 1)); + let mut got = by_key(&[held, got_alice].concat()); + for (key, values) in by_key(&got_bob) { + got.entry(key).or_default().extend(values); + } + assert_eq!(got, sent); } /// With fewer buckets than members, the members left over get nothing, until one leaves. diff --git a/crates/apache-pulsar/src/stream_tests.rs b/crates/apache-pulsar/src/stream_tests.rs index dd07eb9..e00e3d1 100644 --- a/crates/apache-pulsar/src/stream_tests.rs +++ b/crates/apache-pulsar/src/stream_tests.rs @@ -27,8 +27,9 @@ use std::time::Duration; use apache_pulsar_protocol::hash::KeyHash; use apache_pulsar_protocol::lookup::HostPort; use apache_pulsar_protocol::proto::base_command::Type; -use apache_pulsar_protocol::proto::{MessageMetadata, ServerError}; +use apache_pulsar_protocol::proto::{FeatureFlags, MessageMetadata, ServerError}; use apache_pulsar_testkit::LookupAnswer; +use apache_pulsar_testkit::scalable::World; use bytes::Bytes; use futures_util::future::Either; use futures_util::{FutureExt, StreamExt}; @@ -129,6 +130,31 @@ fn a_consumer_without_a_name_gets_one() { }); } +/// A consumer subscribing at the latest position gets none of the messages stored before, and the ones stored after. +/// Java's `V5SubscriptionInitialPositionTest.testStreamConsumerLatestSkipsPriorMessages`. +#[test] +fn a_consumer_at_latest_skips_what_was_stored_before() { + run(async { + let server = WorldServer::start(world(1)).await; + let client = local_client(&server).await; + for i in 0..5 { + publish(&server, 0, "k", &format!("pre-{i}")); + } + let consumer = client + .new_stream_consumer(Schema::string()) + .topic(TOPIC) + .subscription_name(SUB) + .subscription_initial_position(SubscriptionInitialPosition::Latest) + .subscribe() + .await + .unwrap(); + assert_eq!(backlog(&server, 0), 0, "the subscription starts after what was stored"); + publish(&server, 0, "k", "post"); + assert_eq!(consumer.receive().await.unwrap().value().unwrap(), "post"); + client.close().await.unwrap(); + }); +} + #[test] fn receives_with_a_timeout_and_in_batches() { run(async { @@ -231,6 +257,53 @@ fn finds_the_controller_the_layout_names_or_any_broker_behind_a_proxy() { }); } +/// The controller the layout names, on another broker than the service URL's, registers the consumer. Once that +/// broker drops its connections, the consumer registers with the controller the layout names then, on a third one. +/// Java's `V5MultiBrokerControllerFailoverTest`, without its split, and the driver's half of +/// `ClientSegmentLayoutTest.testControllerBrokerUrlPropagated`. +#[test] +fn follows_the_controller_the_layout_names_across_brokers() { + run(controller_failover(false)); +} + +/// The same with a producer of the topic on the client, as in Java's +/// `V5MultiBrokerControllerFailoverTest.testStreamConsumerFollowsControllerLeaderShutdown`: it holds the loop's layout +/// watch, which the consumer's registrations share. +#[test] +#[ignore = "bug: registering again takes the controller from the layout watch the producer holds, naming the old one"] +fn follows_the_controller_while_a_producer_holds_the_layout_watch() { + run(controller_failover(true)); +} + +/// A consumer registered with the controller the layout names on `leader`; the controller moves to `follower`, and +/// `leader` drops its connections: the consumer registers with `follower`, and keeps receiving. With `producer`, a +/// producer of the topic on the same client holds the loop's layout watch all along. +async fn controller_failover(producer: bool) { + let server = WorldServer::start(world(1)).await; + // Brokers that serve only the topic's controller. + let leader = WorldServer::start(world(1)).await; + let follower = WorldServer::start(world(1)).await; + server.with(|w| w.controller.url = Some(leader.url())); + let client = local_client(&server).await; + let _producer = + if producer { Some(client.new_producer(Schema::string()).topic(TOPIC).create().await.unwrap()) } else { None }; + let consumer = consumer(&client, "solo").await; + let registered = || [&server, &leader, &follower].map(|broker| broker.received(Type::SCALABLE_TOPIC_SUBSCRIBE)); + assert_eq!(registered(), [0, 1, 0]); + // The controller moves to the follower, and the leader's broker drops its connections. + server.with(|w| w.controller.url = Some(follower.url())); + leader.with(|w| { + for conn in w.open_connections() { + w.kill(conn); + } + }); + wait_until("it registers again", || registered().iter().sum::() == 2).await; + assert_eq!(registered(), [0, 1, 1]); + publish(&server, 0, "k", "after"); + assert_eq!(consumer.receive().await.unwrap().value().unwrap(), "after"); + client.close().await.unwrap(); +} + /// A refused registration fails the subscribe with the controller's error; a builder missing what it needs fails /// before anything is sent. #[test] @@ -252,6 +325,63 @@ fn a_refused_registration_or_a_bad_builder_fails_the_subscribe() { }); } +/// The broker refuses the lookup of the topic, made before its layout: the subscribe fails with the broker's error. +/// Java's `V5AuthErrorTest.testLookupNotAuthorized`, for a Stream consumer. +#[test] +fn a_refused_lookup_fails_the_subscribe() { + run(async { + let server = WorldServer::start(world(1)).await; + server.with(|w| { + w.lookup = LookupAnswer::Fail { error: ServerError::AuthorizationError, message: "not you".into() } + }); + let client = local_client(&server).await; + let subscribe = client.new_stream_consumer(Schema::bytes()).topic(TOPIC).subscription_name(SUB).subscribe(); + let error = subscribe.await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::Authorization, "{error}"); + assert_eq!(server.received(Type::SCALABLE_TOPIC_LOOKUP), 0); + client.close().await.unwrap(); + }); +} + +/// A missing topic is not found while the broker may not create it; else the subscribe creates it, with one segment, +/// which the consumer reads. Java's `V5ScalableTopicAutoCreateTest.testStreamConsumerAutoCreatesScalableTopic`, and +/// the Stream consumer's part of `V5ScalableTopicAutoCreateTest.testNoAutoCreateWhenNamespaceDisallows`. +#[test] +fn a_missing_topic_is_created_or_not_found() { + run(async { + let mut world = World::default(); + world.auto_create = false; + let server = WorldServer::start(world).await; + let client = local_client(&server).await; + let subscribe = client.new_stream_consumer(Schema::string()).topic(TOPIC).subscription_name(SUB).subscribe(); + let error = subscribe.await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::NotFound, "{error}"); + assert_eq!(server.received(Type::SCALABLE_TOPIC_SUBSCRIBE), 0); + server.with(|w| w.auto_create = true); + let consumer = consumer(&client, "first").await; + assert_eq!(server.world.borrow().assigned(TOPIC, SUB, "first"), [(0, false)]); + publish(&server, 0, "k", "a"); + assert_eq!(consumer.receive().await.unwrap().value().unwrap(), "a"); + client.close().await.unwrap(); + }); +} + +/// A broker without scalable topics fails the subscribe, and is sent nothing scalable (C15). +#[test] +fn a_broker_without_scalable_topics_is_refused() { + run(async { + let mut world = world(1); + world.features = FeatureFlags { supports_scalable_topics: Some(false), ..Default::default() }; + let server = WorldServer::start(world).await; + let client = local_client(&server).await; + let subscribe = client.new_stream_consumer(Schema::bytes()).topic(TOPIC).subscription_name(SUB).subscribe(); + let error = subscribe.await.unwrap_err(); + assert_eq!(error.kind(), ErrorKind::UnsupportedBroker, "{error}"); + assert_eq!(server.received(Type::SCALABLE_TOPIC_LOOKUP) + server.received(Type::SCALABLE_TOPIC_SUBSCRIBE), 0); + client.close().await.unwrap(); + }); +} + /// After a connection loss the consumer registers again, and its segments subscribe again. #[test] fn a_lost_connection_registers_again() {