From 517e18f185b4babf0a38b99a54894d6b6f0ce96f Mon Sep 17 00:00:00 2001 From: Matteo Merli Date: Mon, 23 Nov 2026 10:48:11 -0800 Subject: [PATCH] =?UTF-8?q?M7:=20the=20conformance=20suite,=20and=20the=20?= =?UTF-8?q?C1=E2=80=93C15=20checklist?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spec's test guidance (conformance §5) as a named suite, as docs/8-quality.md §2.2 plans it: routing vectors, a split or merge during active produce and consume, a broker failover, cumulative ack across segments, and checkpoint round trips across a layout change. tests/conformance/README.md describes each case for any SDK, and lists, for each of C1–C15, the tests that show this client meets it. The cases against a 5.0.1 broker are integration trials named conformance::. Four existing tests moved into the suite's table rather than being written again; the vector cases are the protocol crate's tests. New cases: the same key to the same segment from Rust's and Java's producers on a layout of uneven ranges (RoutingTool.java); a split and a merge under load, with a Queue and a Stream consumer reading; a failover by namespace unload and one by killing and restarting the broker, with a producer and the three consumers active; a Stream consumer's cumulative ack settling what came before it on every segment, a sealed one included, and nothing after. The broker restart runs once the other trials are done, one at a time, in a second libtest-mimic run: Env::restart_broker kills the broker container and starts it again. --- .../tests/integration/RoutingTool.java | 44 ++ .../tests/integration/conformance.rs | 503 ++++++++++++++++++ crates/apache-pulsar/tests/integration/env.rs | 30 +- .../apache-pulsar/tests/integration/main.rs | 46 +- tests/conformance/README.md | 352 ++++++++++++ 5 files changed, 946 insertions(+), 29 deletions(-) create mode 100644 crates/apache-pulsar/tests/integration/RoutingTool.java create mode 100644 crates/apache-pulsar/tests/integration/conformance.rs create mode 100644 tests/conformance/README.md diff --git a/crates/apache-pulsar/tests/integration/RoutingTool.java b/crates/apache-pulsar/tests/integration/RoutingTool.java new file mode 100644 index 0000000..6e9f910 --- /dev/null +++ b/crates/apache-pulsar/tests/integration/RoutingTool.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.apache.pulsar.client.api.v5.MessageId; +import org.apache.pulsar.client.api.v5.Producer; +import org.apache.pulsar.client.api.v5.PulsarClient; +import org.apache.pulsar.client.api.v5.schema.Schema; + +/** + * Publishes a message for each key with the Java client's V5 producer, for the Rust client's integration tests, in the + * broker container, as the admin: {@code RoutingTool ...}. Prints, for each key, + * {@code routed }, the message id as the V5 client prints it, which names the segment the producer routed + * the key to. + */ +public final class RoutingTool { + public static void main(String[] args) throws Exception { + try (PulsarClient client = PulsarClient.builder() + .serviceUrl("pulsar://localhost:6650") + .authentication("org.apache.pulsar.client.impl.auth.AuthenticationToken", "file:///it/admin.token") + .build(); + Producer producer = client.newProducer(Schema.string()).topic(args[0]).create()) { + for (int i = 1; i < args.length; i++) { + MessageId id = producer.newMessage().key(args[i]).value("java-" + args[i]).send(); + System.out.println("routed " + args[i] + " " + id); + } + } + } +} diff --git a/crates/apache-pulsar/tests/integration/conformance.rs b/crates/apache-pulsar/tests/integration/conformance.rs new file mode 100644 index 0000000..c6d2a89 --- /dev/null +++ b/crates/apache-pulsar/tests/integration/conformance.rs @@ -0,0 +1,503 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The conformance suite against a real broker (docs/8-quality.md §2.2), from the spec's test guidance +//! (*conformance* §5). `tests/conformance/README.md` describes each case for any SDK, under the id its trial is named +//! after here: `conformance::`, so that `cargo test -p apache-pulsar --test integration conformance::` runs the +//! suite. Cases that an earlier test already covers name that test rather than repeat it. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use apache_pulsar::{Checkpoint, Message, Schema, SubscriptionInitialPosition, local}; +use apache_pulsar_protocol::hash::KeyHash; +use futures_util::stream::FuturesOrdered; +use futures_util::{FutureExt, StreamExt}; + +use super::{ + Env, a_checkpoint_round_trips_with_java_across_layout_changes, a_partitioned_topic_routes_like_v4, + a_split_during_consumption_loses_no_message, env, keys_keep_their_order_across_a_split, proxy_client, run, stats, + stream_backlog, stream_consumer, token_client, unique, wait_for, +}; + +/// The cases that run beside the other tests. +pub(super) const TESTS: &[(&str, fn(&Env))] = &[ + ("conformance::routing_across_clients", routing_across_clients), + ("conformance::legacy_routing", a_partitioned_topic_routes_like_v4), + ("conformance::split_during_produce", keys_keep_their_order_across_a_split), + ("conformance::split_during_consume", a_split_during_consumption_loses_no_message), + ("conformance::split_and_merge_under_load", split_and_merge_under_load), + ("conformance::failover_by_unload", failover_by_unload), + ("conformance::cumulative_ack_across_segments", cumulative_ack_across_segments), + ( + "conformance::checkpoint_round_trip_across_layout_changes", + a_checkpoint_round_trips_with_java_across_layout_changes, + ), +]; + +/// The cases that take the broker down: they run once the others are done, one at a time. +pub(super) const EXCLUSIVE: &[(&str, fn(&Env))] = + &[("conformance::failover_by_broker_restart", failover_by_broker_restart)]; + +/// `routing-across-clients`: on a layout of segments of unequal ranges, the Java client and this one send each key to +/// the same segment, the one whose range holds the key's hash. +fn routing_across_clients(env: &Env) { + let name = unique("routing"); + let path = format!("public/default/{name}"); + let topic = format!("topic://{path}"); + // Four segments of a quarter of the ring each, then the second split in two eighths. + env.admin(&["scalable-topics", "create", "-s", "4", &path]); + env.admin(&["scalable-topics", "split-segment", "-s", "1", &path]); + let ranges = active_ranges(env, &path); + assert_eq!(ranges.len(), 5, "the layout: {ranges:?}"); + let keys: Vec = (0..128).map(|i| format!("key-{i}")).collect(); + let rust: BTreeMap = run(async { + let client = token_client(env::BROKER_URL, Some(env.token.clone())).build().await.unwrap(); + let producer = client.new_producer(Schema::string()).topic(&topic).create().await.unwrap(); + let mut routed = BTreeMap::new(); + for key in &keys { + let id = producer.new_message().key(key.clone()).value(format!("rust-{key}")).send().await.unwrap(); + routed.insert(key.clone(), segment_of(&id.to_string())); + } + client.close().await.unwrap(); + routed + }); + let java = env.java_route(&topic, &keys); + for key in &keys { + let hash = KeyHash::of(key.as_bytes()).segment_hash(); + let covering: Vec = + ranges.iter().filter(|(_, (start, end))| (*start..=*end).contains(&hash)).map(|(id, _)| *id).collect(); + assert_eq!(covering.len(), 1, "key {key}, hash {hash:#06x}: segments {covering:?} of {ranges:?}"); + assert_eq!((rust[key], java[key]), (covering[0], covering[0]), "key {key}, hash {hash:#06x}"); + } + let used: BTreeSet = rust.values().copied().collect(); + assert_eq!(used.len(), ranges.len(), "every segment got keys: {used:?}"); +} + +/// The active segments of scalable topic `path`, by id, with the range of hashes each covers. +fn active_ranges(env: &Env, path: &str) -> BTreeMap { + let metadata = stats(env, &["scalable-topics", "get-metadata", path]); + let segments = metadata["segments"].as_object().unwrap_or_else(|| panic!("no segments in {metadata}")); + let field = |segment: &serde_json::Value, name: &str| { + segment[name].as_u64().unwrap_or_else(|| panic!("no {name} in {segment}")) + }; + segments + .values() + .filter(|segment| segment["state"] == "ACTIVE") + .map(|segment| { + let range = &segment["hashRange"]; + let bound = |name| u16::try_from(field(range, name)).unwrap(); + (field(segment, "segmentId"), (bound("start"), bound("end"))) + }) + .collect() +} + +/// The segment a message id, as it prints, names: `segment:ledger:entry:index`, or Java's `MessageIdV5{segment=…`. +fn segment_of(id: &str) -> u64 { + let segment = id.split_once("segment=").map_or(id, |(_, rest)| rest); + segment.split([':', ',']).next().and_then(|s| s.parse().ok()).unwrap_or_else(|| panic!("no segment in {id}")) +} + +/// `split-and-merge-under-load`: a producer sends keyed messages without pause while a segment splits and its children +/// merge again; a Queue and a Stream consumer read meanwhile. No send fails, both consumers get every message once, and +/// the Stream consumer gets each key's messages in the order they were sent. +fn split_and_merge_under_load(env: &Env) { + let name = unique("split-merge"); + let path = format!("public/default/{name}"); + let topic = format!("topic://{path}"); + env.admin(&["scalable-topics", "create", "-s", "2", &path]); + // Keep the layout to the admin's changes. + env.disable_auto_scale(&path); + let keys: Vec = (0..16).map(|i| format!("k{i}")).collect(); + let (changes_done, producing) = (AtomicBool::new(false), AtomicBool::new(true)); + std::thread::scope(|scope| { + let (started, change_now) = std::sync::mpsc::channel(); + let (changes_done, path) = (&changes_done, &path); + scope.spawn(move || { + change_now.recv().unwrap(); + // Segment 0 splits into 2 and 3, which merge into 4. + env.admin(&["scalable-topics", "split-segment", "-s", "0", path]); + env.admin(&["scalable-topics", "merge-segments", "--segment-id-1", "2", "--segment-id-2", "3", path]); + changes_done.store(true, Ordering::Release); + }); + run(async { + let client = token_client(env::BROKER_URL, Some(env.token.clone())).build().await.unwrap(); + let proxied = proxy_client(env).build().await.unwrap(); + let queue = client + .new_queue_consumer(Schema::string()) + .topic(&topic) + .subscription_name("queue") + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .subscribe() + .await + .unwrap(); + let stream = stream_consumer(&proxied, &topic, "ordered").await; + let producer = client.new_producer(Schema::string()).topic(&topic).create().await.unwrap(); + let sent = Mutex::new(BTreeMap::>::new()); + let produce = async { + let mut sends = FuturesOrdered::new(); + let (mut round, mut after) = (0, 0); + // Twenty rounds after the merge, or a bound that only a stuck split or merge reaches. + while after < 20 && round < 3000 { + if round == 5 { + started.send(()).unwrap(); + } + for key in &keys { + let value = format!("{key}-{round:04}"); + sends.push_back(producer.new_message().key(key.clone()).value(value.clone()).send()); + sent.lock().unwrap().entry(key.clone()).or_default().push(value); + } + while sends.len() > 2 * keys.len() { + sends.next().await.unwrap().unwrap(); + } + after += usize::from(changes_done.load(Ordering::Acquire)); + round += 1; + compio::time::sleep(Duration::from_millis(20)).await; + } + while let Some(result) = sends.next().await { + result.unwrap(); + } + producing.store(false, Ordering::Release); + }; + let total = || sent.lock().unwrap().values().map(Vec::len).sum::(); + let read_queue = async { + let mut got = Vec::new(); + while producing.load(Ordering::Acquire) || got.len() < total() { + let Some(message) = queue.receive_timeout(Duration::from_secs(30)).await.unwrap() else { break }; + queue.acknowledge(message.id()).await.unwrap(); + got.push(message); + } + got + }; + let read_stream = async { + let mut got = Vec::new(); + while producing.load(Ordering::Acquire) || got.len() < total() { + let Some(message) = stream.receive_timeout(Duration::from_secs(30)).await.unwrap() else { break }; + stream.acknowledge_cumulative(message.id()).await.unwrap(); + got.push(message); + } + got + }; + let ((), from_queue, from_stream) = futures_util::join!(produce, read_queue, read_stream); + assert!(changes_done.load(Ordering::Acquire), "the split and the merge did not complete"); + let sent = sent.into_inner().unwrap(); + let segments: BTreeSet = from_queue.iter().map(|m| segment_of(&m.id().to_string())).collect(); + assert!( + segments.is_superset(&BTreeSet::from([0, 1, 2, 3, 4])), + "the layout changed under load: {segments:?}" + ); + let mut expected: Vec = sent.values().flatten().cloned().collect(); + expected.sort(); + let mut queued: Vec = from_queue.iter().map(|m| m.value().unwrap()).collect(); + queued.sort(); + assert_eq!(queued, expected, "the Queue consumer gets every message once"); + assert_eq!(per_key(&from_stream), sent, "the Stream consumer gets every key in order"); + client.close().await.unwrap(); + proxied.close().await.unwrap(); + }); + }); +} + +/// The values of `messages` by key, in the order received. +fn per_key(messages: &[Message]) -> BTreeMap> { + let mut keys: BTreeMap> = BTreeMap::new(); + for message in messages { + keys.entry(message.key().unwrap().to_string()).or_default().push(message.value().unwrap()); + } + keys +} + +/// `cumulative-ack-across-segments`: a Stream consumer's cumulative ack of a message settles what came before it on +/// every segment, sealed ones included, and nothing that came after it. +fn cumulative_ack_across_segments(env: &Env) { + let name = unique("cumulative"); + let path = format!("public/default/{name}"); + let topic = format!("topic://{path}"); + env.admin(&["scalable-topics", "create", "-s", "2", &path]); + env.disable_auto_scale(&path); + // Keys of segment 0, which covers the lower half of the ring, and of segment 1, in turn. + let (low, high): (Vec, Vec) = + (0..64).map(|i| format!("k{i}")).partition(|key| KeyHash::of(key.as_bytes()).segment_hash() < 0x8000); + let key = |i: usize| if i.is_multiple_of(2) { &low[i / 2 % 4] } else { &high[i / 2 % 4] }; + run(async { + let client = proxy_client(env).build().await.unwrap(); + let producer = client.new_producer(Schema::string()).topic(&topic).create().await.unwrap(); + let send = async |prefix: &str, i: usize| { + let id = producer.new_message().key(key(i).clone()).value(format!("{prefix}-{i:02}")).send().await; + segment_of(&id.unwrap().to_string()) + }; + let receive = async |consumer: &local::StreamConsumer| { + consumer.receive_timeout(Duration::from_secs(30)).await.unwrap().expect("a message") + }; + let values = |messages: &[Message]| -> BTreeSet { + messages.iter().map(|m| m.value().unwrap()).collect() + }; + + // Two active segments, each message received before the next is sent, so that they come in turn from each: + // the ack of the tenth settles the nine before it, from both segments, and none after it. + let first = stream_consumer(&client, &topic, "first").await; + let mut got = Vec::new(); + for i in 0..20 { + assert_eq!(send("active", i).await, (i % 2) as u64); + got.push(receive(&first).await); + } + first.acknowledge_cumulative(got[9].id()).await.unwrap(); + wait_for(|| stream_backlog(env, &name) == 10, "the ack settles what came before it").await; + first.close().await.unwrap(); + let again = stream_consumer(&client, &topic, "again").await; + let mut rest = Vec::new(); + for _ in 0..10 { + rest.push(receive(&again).await); + } + assert_eq!(values(&rest), values(&got[10..]), "what came after the ack comes again"); + assert!(again.receive_timeout(Duration::from_secs(1)).await.unwrap().is_none(), "and only that"); + again.acknowledge_cumulative(rest.last().unwrap().id()).await.unwrap(); + wait_for(|| stream_backlog(env, &name) == 0, "the last ack settles both segments").await; + + // A sealed segment: segment 0 splits with messages delivered and not acknowledged. Its children's messages wait + // until it is drained, which the ack of a message of segment 1 does. + let mut delivered = Vec::new(); + for i in 0..10 { + send("sealed", i).await; + delivered.push(receive(&again).await); + } + env.admin(&["scalable-topics", "split-segment", "-s", "0", &path]); + for i in 0..10 { + // Segment 1, and the children 2 and 3 of segment 0, in turn. + let segment = send("split", i).await; + assert!( + if i.is_multiple_of(2) { segment == 2 || segment == 3 } else { segment == 1 }, + "message {i}: {segment}" + ); + } + let mut from_one = Vec::new(); + for _ in 0..5 { + from_one.push(receive(&again).await); + } + let segments: BTreeSet = from_one.iter().map(|m| segment_of(&m.id().to_string())).collect(); + assert_eq!(segments, BTreeSet::from([1]), "the children wait for their parent"); + again.acknowledge_cumulative(from_one.last().unwrap().id()).await.unwrap(); + delivered.extend(from_one); + for _ in 0..5 { + let message = receive(&again).await; + assert!([2, 3].contains(&segment_of(&message.id().to_string())), "a child's: {message:?}"); + delivered.push(message); + } + assert_eq!(values(&delivered).len(), 20); + again.acknowledge_cumulative(delivered.last().unwrap().id()).await.unwrap(); + wait_for(|| stream_backlog(env, &name) == 0, "the last ack settles every segment").await; + client.close().await.unwrap(); + }); +} + +/// How a failover case takes the topic away from the clients. +#[derive(Debug, Clone, Copy)] +enum Failover { + /// `pulsar-admin namespaces unload`: the broker closes the topic's producers and consumers, and gives the topic up, + /// as when its ownership moves to another broker. + Unload, + /// The broker is killed and started again: every connection drops, and nothing answers until it is back. + BrokerRestart, +} + +/// `failover-by-unload`. +fn failover_by_unload(env: &Env) { + failover(env, Failover::Unload); +} + +/// `failover-by-broker-restart`. +fn failover_by_broker_restart(env: &Env) { + failover(env, Failover::BrokerRestart); +} + +/// The failover cases: a producer sends without pause while the topic fails over, its sends queued as they are made, +/// and a Queue, a Stream and a Checkpoint consumer receive meanwhile. The producer carries on, with no send failing, +/// and each consumer resumes: it gets every message, the Stream and the Checkpoint consumers each key's in the order +/// sent. Messages may come twice after a failover (at least once), but the first time each comes is in order. +fn failover(env: &Env, failover: Failover) { + // A namespace of its own, to unload. + let namespace = format!("public/{}", unique("failover")); + env.admin(&["namespaces", "create", &namespace]); + let path = format!("{namespace}/orders"); + let topic = format!("topic://{path}"); + env.admin(&["scalable-topics", "create", "-s", "2", &path]); + let (failed_over, producing) = (AtomicBool::new(false), AtomicBool::new(true)); + // The producer's registrations on the two segments, before the unload. + let registered = OnceLock::new(); + std::thread::scope(|scope| { + let (start, fail_over) = std::sync::mpsc::channel(); + let (failed_over, namespace, path, registered) = (&failed_over, &namespace, &path, ®istered); + scope.spawn(move || { + fail_over.recv().unwrap(); + match failover { + Failover::Unload => { + // The keys go to both segments: wait for the producer on each. + let deadline = Instant::now() + Duration::from_secs(30); + let before = loop { + let before = producers(env, path); + if before.len() == 2 || Instant::now() > deadline { + break before; + } + std::thread::sleep(Duration::from_millis(200)); + }; + assert_eq!(before.len(), 2, "the producer on each segment: {before:?}"); + registered.set(before).unwrap(); + env.admin(&["namespaces", "unload", namespace]); + } + Failover::BrokerRestart => env.restart_broker(), + } + failed_over.store(true, Ordering::Release); + }); + run(async { + let client = token_client(env::BROKER_URL, Some(env.token.clone())).build().await.unwrap(); + let proxied = proxy_client(env).build().await.unwrap(); + // No send times out while the broker is away. + let producer = client + .new_producer(Schema::string()) + .topic(&topic) + .send_timeout(Duration::ZERO) + .create() + .await + .unwrap(); + let queue = client + .new_queue_consumer(Schema::string()) + .topic(&topic) + .subscription_name("queue") + .subscription_initial_position(SubscriptionInitialPosition::Earliest) + .subscribe() + .await + .unwrap(); + let stream = stream_consumer(&proxied, &topic, "ordered").await; + let checkpoint = client.new_checkpoint_consumer(Schema::string()).topic(&topic); + let checkpoint = checkpoint.start_position(Checkpoint::earliest()).create().await.unwrap(); + let sent = Mutex::new(BTreeMap::>::new()); + let total = || sent.lock().unwrap().values().map(Vec::len).sum::(); + let produce = async { + let mut sends = FuturesOrdered::new(); + let mut after = 0; + // Twenty messages first, then the failover; a message every 50 ms until it is over, and twenty more. + for i in 0..6000 { + let (key, value) = (format!("k{}", i % 5), format!("m-{i:04}")); + sends.push_back(producer.new_message().key(key.clone()).value(value.clone()).send()); + sent.lock().unwrap().entry(key).or_default().push(value); + // A send's message is queued when its future is first polled: poll the new one, and take the + // ones that completed, without waiting. + while let Some(Some(result)) = sends.next().now_or_never() { + result.expect("a send made across the failover"); + } + if i == 20 { + start.send(()).unwrap(); + } + after += usize::from(failed_over.load(Ordering::Acquire)); + if after == 20 { + break; + } + compio::time::sleep(Duration::from_millis(50)).await; + } + while let Some(result) = sends.next().await { + result.expect("a send made across the failover"); + } + producing.store(false, Ordering::Release); + }; + let deadline = Instant::now() + Duration::from_secs(240); + let reading = |got: &[Message]| { + (producing.load(Ordering::Acquire) || firsts(got) < total()) && Instant::now() < deadline + }; + let wait = Duration::from_secs(1); + let read_queue = async { + let mut got = Vec::new(); + while reading(&got) { + if let Some(message) = queue.receive_timeout(wait).await.unwrap() { + queue.acknowledge(message.id()).await.unwrap(); + got.push(message); + } + } + got + }; + let read_stream = async { + let mut got = Vec::new(); + while reading(&got) { + if let Some(message) = stream.receive_timeout(wait).await.unwrap() { + stream.acknowledge_cumulative(message.id()).await.unwrap(); + got.push(message); + } + } + got + }; + let read_checkpoint = async { + let mut got = Vec::new(); + while reading(&got) { + got.extend(checkpoint.receive_timeout(wait).await.unwrap()); + } + got + }; + let ((), from_queue, from_stream, from_checkpoint) = + futures_util::join!(produce, read_queue, read_stream, read_checkpoint); + assert!(failed_over.load(Ordering::Acquire), "the failover did not complete"); + if let Some(before) = registered.get() { + // The broker did let go of the producer: it is back on both segments, registered again. + let again = producers(env, path); + let since = |producers: &BTreeMap| producers.values().cloned().collect::>(); + assert_eq!(again.len(), 2, "{again:?}"); + assert!(since(before).is_disjoint(&since(&again)), "before {before:?}, after {again:?}"); + } + let sent = sent.into_inner().unwrap(); + let as_sets = |got: &[Message]| -> BTreeMap> { + per_key_first(got).into_iter().map(|(key, values)| (key, values.into_iter().collect())).collect() + }; + let expected: BTreeMap> = + sent.iter().map(|(key, values)| (key.clone(), values.iter().cloned().collect())).collect(); + assert_eq!(as_sets(&from_queue), expected, "the Queue consumer resumes"); + assert_eq!(per_key_first(&from_stream), sent, "the Stream consumer resumes, every key in order"); + assert_eq!(per_key_first(&from_checkpoint), sent, "the Checkpoint consumer resumes, every key in order"); + client.close().await.unwrap(); + proxied.close().await.unwrap(); + }); + }); +} + +/// How many messages of `messages` came for the first time. +fn firsts(messages: &[Message]) -> usize { + messages.iter().map(|m| m.value().unwrap()).collect::>().len() +} + +/// The values of `messages` by key, each the first time it came, in the order received. +fn per_key_first(messages: &[Message]) -> BTreeMap> { + let mut seen = BTreeSet::new(); + let mut keys: BTreeMap> = BTreeMap::new(); + for message in messages { + let value = message.value().unwrap(); + if seen.insert(value.clone()) { + keys.entry(message.key().unwrap().to_string()).or_default().push(value); + } + } + keys +} + +/// The producers of scalable topic `path`, one per segment it writes to, by name, with when each registered: the +/// topic stats' `producers`. +fn producers(env: &Env, path: &str) -> BTreeMap { + let topic = stats(env, &["scalable-topics", "stats", path]); + let producers = topic["producers"].as_array().map_or(&[][..], Vec::as_slice); + let since = |producer: &serde_json::Value| { + let name = producer["producerName"].as_str().expect("a producer's name"); + (name.to_string(), producer["connectedSince"].as_str().expect("when a producer registered").to_string()) + }; + producers.iter().map(since).collect() +} diff --git a/crates/apache-pulsar/tests/integration/env.rs b/crates/apache-pulsar/tests/integration/env.rs index 75b94d2..405aa2d 100644 --- a/crates/apache-pulsar/tests/integration/env.rs +++ b/crates/apache-pulsar/tests/integration/env.rs @@ -22,6 +22,7 @@ //! because the broker advertises them in its lookup answers (`broker.conf`), so only one environment runs on a //! host at a time. +use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::OnceLock; use std::time::Duration; @@ -48,8 +49,9 @@ const JAVA_TOOLS_CLASSPATH: [&str; 4] = [ "com.google.protobuf-protobuf-java-4.36.2.jar", ]; /// The Java test tools, by file name. -const JAVA_TOOLS: [(&str, &[u8]); 2] = [ +const JAVA_TOOLS: [(&str, &[u8]); 3] = [ ("CheckpointTool.java", include_bytes!("CheckpointTool.java")), + ("RoutingTool.java", include_bytes!("RoutingTool.java")), ("SchemaTool.java", include_bytes!("SchemaTool.java")), ]; const NETWORK: &str = "apr-it-net"; @@ -299,6 +301,32 @@ impl Env { self.java(&["SchemaTool", "info", kind, message]) } + /// Publishes a message for each of `keys` to `topic` with the Java client's V5 producer, as the admin, and returns + /// the segment the producer sent each key to. + pub fn java_route(&self, topic: &str, keys: &[String]) -> BTreeMap { + let args: Vec<&str> = ["RoutingTool", topic].into_iter().chain(keys.iter().map(String::as_str)).collect(); + let output = self.java(&args); + let routed = output.lines().filter_map(|line| line.strip_prefix("routed ")).map(|line| { + let (key, id) = line.split_once(' ').expect("a key and a message id"); + let segment = id.split_once("segment=").and_then(|(_, rest)| rest.split(',').next()?.parse().ok()); + (key.to_string(), segment.unwrap_or_else(|| panic!("no segment in {id}"))) + }); + routed.collect() + } + + /// Kills the broker, as a crash would, starts it again, and returns once it serves again. Every client connection + /// drops, the proxy's to the broker included. The broker keeps what it stored; the Java clients running in the + /// background ([`Env::v4_consumer`], [`Env::v4_producer`]) are gone. + pub fn restart_broker(&self) { + self.broker.stop_with_timeout(Some(0)).unwrap(); + self.broker.start().unwrap(); + let deadline = std::time::Instant::now() + STARTUP_TIMEOUT; + while let Err(error) = self.try_admin(&["brokers", "healthcheck"]) { + assert!(std::time::Instant::now() < deadline, "the broker did not come back: {error}"); + std::thread::sleep(Duration::from_millis(500)); + } + } + /// Runs one of the Java test tools in the broker container, with its arguments, and returns what it printed. fn java(&self, args: &[&str]) -> String { self.try_java(args).unwrap_or_else(|error| panic!("{args:?} failed:\n{error}")) diff --git a/crates/apache-pulsar/tests/integration/main.rs b/crates/apache-pulsar/tests/integration/main.rs index 383f90a..e04dab8 100644 --- a/crates/apache-pulsar/tests/integration/main.rs +++ b/crates/apache-pulsar/tests/integration/main.rs @@ -23,6 +23,7 @@ //! the Java client stored is read with the Rust consumer, both Java clients run in the broker container. mod bridge; +mod conformance; mod env; mod schemas; @@ -48,8 +49,6 @@ const TESTS: &[(&str, fn(&Env))] = &[ ("missing_credentials_are_refused", missing_credentials_are_refused), ("a_java_consumer_reads_what_was_produced", a_java_consumer_reads_what_was_produced), ("a_java_consumer_reads_rust_batches", a_java_consumer_reads_rust_batches), - ("keys_keep_their_order_across_a_split", keys_keep_their_order_across_a_split), - ("a_partitioned_topic_routes_like_v4", a_partitioned_topic_routes_like_v4), ("a_short_name_is_a_regular_topic", a_short_name_is_a_regular_topic), ("exclusive_producers_conflict_at_create", exclusive_producers_conflict_at_create), ("exclusive_with_fencing_fences_the_older_producer", exclusive_with_fencing_fences_the_older_producer), @@ -59,7 +58,6 @@ const TESTS: &[(&str, fn(&Env))] = &[ ("a_queue_consumer_reads_compressed_java_batches", a_queue_consumer_reads_compressed_java_batches), ("a_payload_reads_back_with_each_codec", a_payload_reads_back_with_each_codec), ("a_java_consumer_reads_rust_compressed_batches", a_java_consumer_reads_rust_compressed_batches), - ("a_split_during_consumption_loses_no_message", a_split_during_consumption_loses_no_message), ("a_latest_consumer_gets_what_the_children_stored_first", a_latest_consumer_gets_what_the_children_stored_first), ("queue_consumers_share_a_subscription", queue_consumers_share_a_subscription), ("a_negative_ack_brings_a_message_back", a_negative_ack_brings_a_message_back), @@ -83,10 +81,6 @@ const TESTS: &[(&str, fn(&Env))] = &[ ("a_checkpoint_consumer_resumes_across_a_split", a_checkpoint_consumer_resumes_across_a_split), ("a_latest_checkpoint_consumer_reads_a_later_split", a_latest_checkpoint_consumer_reads_a_later_split), ("a_checkpoint_consumer_skips_a_deleted_segment", a_checkpoint_consumer_skips_a_deleted_segment), - ( - "a_checkpoint_round_trips_with_java_across_layout_changes", - a_checkpoint_round_trips_with_java_across_layout_changes, - ), ("checkpoint_group_members_share_the_segments", checkpoint_group_members_share_the_segments), ("a_checkpoint_group_member_reads_the_sealed_backlog", a_checkpoint_group_member_reads_the_sealed_backlog), ]; @@ -95,31 +89,27 @@ fn main() { let args = Arguments::from_args(); // Listing the tests needs no environment. let env = (!args.list).then(|| Arc::new(Env::start())); - let ignored = bridge::IGNORED.iter().map(|test| (test, true)); - let trials = TESTS - .iter() - .chain(bridge::TESTS) - .chain(schemas::TESTS) - .map(|test| (test, false)) - .chain(ignored) - .map(|(&(name, test), ignored)| { - let env = env.clone(); - let trial = Trial::test(name, move || { - test(env.as_deref().expect("the environment is started unless listing")); - Ok(()) - }); - trial.with_ignored_flag(ignored) - }) - .collect(); - let conclusion = libtest_mimic::run(&args, trials); - if conclusion.has_failed() - && let Some(env) = &env - { + let trial = |&(name, test): &(&'static str, fn(&Env)), ignored: bool| { + let env = env.clone(); + let trial = Trial::test(name, move || { + test(env.as_deref().expect("the environment is started unless listing")); + Ok(()) + }); + trial.with_ignored_flag(ignored) + }; + let tests = TESTS.iter().chain(bridge::TESTS).chain(schemas::TESTS).chain(conformance::TESTS); + let trials = tests.map(|test| trial(test, false)).chain(bridge::IGNORED.iter().map(|test| trial(test, true))); + let conclusion = libtest_mimic::run(&args, trials.collect()); + // The tests that take the broker down run once the others are done, one at a time. + let exclusive = conformance::EXCLUSIVE.iter().map(|test| trial(test, false)).collect(); + let then = libtest_mimic::run(&Arguments { test_threads: Some(1), ..args.clone() }, exclusive); + let failed = conclusion.has_failed() || then.has_failed(); + if failed && let Some(env) = &env { env.print_logs(); } // Remove the containers before exiting: `exit` runs no destructors. drop(env); - conclusion.exit(); + std::process::exit(if failed { 101 } else { 0 }); } fn run(f: F) -> F::Output { diff --git a/tests/conformance/README.md b/tests/conformance/README.md new file mode 100644 index 0000000..4e77d3e --- /dev/null +++ b/tests/conformance/README.md @@ -0,0 +1,352 @@ + + +# Conformance + +The Scalable Topics Client Specification (*conformance*) defines what a conformant client is: the required core, +C1–C15 (§2), and the tests that validate interoperability (§5). This directory holds both for this client: + +- **The suite** (§1–§3 below): the cases of *conformance* §5, described for any SDK, each with what this client runs + for it. They need no Rust: another SDK can run the same cases against the same broker and data. +- **The checklist** (§4): each of C1–C15, and the tests that show this client meets it. + +## 1. The environment + +The cases that need a broker run against Apache Pulsar 5.0.1, the first release with scalable topics, from the +`apachepulsar/pulsar:5.0.1` image, in standalone mode. A harness provides: + +- **The broker**, with automatic topic creation on, and the `public/default` namespace. +- **Admin access**, through `pulsar-admin` in the broker's container: `scalable-topics create`, `split-segment`, + `merge-segments`, `get-metadata`, `stats` and `segment-stats`; `namespaces create` and `unload`. `pulsar-admin` + 5.0.1 has no command to turn a topic's automatic splits and merges off, which some cases need: they + `POST {"enabled": false}` to `/admin/v2/scalable////autoScalePolicy`. +- **The reference client**, Java's, version 5.0.1, from the broker's image, with two small programs + ([`RoutingTool`](../../crates/apache-pulsar/tests/integration/RoutingTool.java), + [`CheckpointTool`](../../crates/apache-pulsar/tests/integration/CheckpointTool.java)) for the cases that compare + the SDK under test with it. +- **A way to kill the broker and start it again**: stopping its container with `SIGKILL` and starting it. A case that + does it runs alone, once the others are done. + +A case's topics are its own: it names them with a random suffix, so that cases run side by side and the suite runs +again on the same broker. + +Some cases also use vectors that the Java client generated (`tools/java-vectors`), which need no broker: +[`routing.json`](../../crates/apache-pulsar-protocol/tests/vectors/routing.json), +[`message_id.json`](../../crates/apache-pulsar-protocol/tests/vectors/message_id.json) and +[`checkpoint.json`](../../crates/apache-pulsar-protocol/tests/vectors/checkpoint.json). + +## 2. The cases + +Each case has an id, the requirements it checks, what it does, and when it passes. *This client* names what runs it +here. "Every message" means every message the case sent; "in order" means, for each key, in the order the key's +messages were sent. + +### Routing + +**`routing-vectors`** (C2; no broker). For each key of `routing.json`: the raw and masked 32-bit Murmur3 hashes of +its UTF-8 bytes, the segment hash (the high 16 bits), the entry-bucket hash (the low 16 bits), and the partition a +v4 producer picks among N partitions, for each N listed. *Passes* when the SDK computes every one of them as listed. +*This client:* [`routing_vectors.rs`](../../crates/apache-pulsar-protocol/tests/routing_vectors.rs) +`routing_matches_java`. + +**`routing-across-clients`** (C2). A topic of four segments, the second then split, so that the five active segments +cover ranges of two sizes. The SDK's producer and the reference client's each send one message for each of 128 keys +(`key-0` to `key-127`). *Passes* when, for every key, both messages went to the same segment, the one whose range +holds the key's segment hash in the layout `get-metadata` returns, and every segment got keys. A message's segment is +read from its id: the reference client prints it. *This client:* `conformance::routing_across_clients`. + +**`legacy-routing`** (C2, the migration bridge). A partitioned `persistent://` topic of three partitions. The SDK's +producer sends keyed messages to it. *Passes* when each key's messages are in the partition a v4 producer picks +(`routing.json`'s partition for N = 3), read back with the reference client. *This client:* +`conformance::legacy_routing`. + +### Layout changes during traffic + +**`split-during-produce`** (C1, C3, C4). The SDK's producer sends 16 keys in rounds, with sends in flight, while the +topic's segment splits. *Passes* when no send fails, the topic's messages are stored in more than one segment, and the +reference client reads every key's messages in the order they were sent, the parent's before the children's. *This +client:* `conformance::split_during_produce`. + +**`split-during-consume`** (C1, C8). A Queue consumer receives while the producer sends and the segment splits. +*Passes* when the consumer gets every message once, from more than one segment, and the drained parent keeps no +consumer of the subscription. *This client:* `conformance::split_during_consume`. + +**`split-and-merge-under-load`** (C1, C3, C4, C7, C8). A topic of two segments, its automatic splits and merges off. +A producer sends 16 keys in rounds without pause, with sends in flight, while segment 0 splits into segments 2 and 3, +and those merge into segment 4; a Queue and a Stream consumer receive meanwhile, and acknowledge what they receive. +The producer goes on for 20 rounds after the merge. *Passes* when no send fails, the Queue consumer receives every +message once, from segments 0 to 4, and the Stream consumer receives every message once, in order. *This client:* +`conformance::split_and_merge_under_load`. + +### Failover + +Both cases run the same clients: a producer whose sends never time out, a Queue consumer, a Stream consumer and a +Checkpoint consumer, from the earliest position, on a topic of two segments in a namespace of the case's own. The +producer sends 20 messages over 5 keys, then a message every 50 ms while the topic fails over and 20 more once it is +back. The consumers receive meanwhile, the Queue and Stream consumers acknowledging. A message may come twice after a +failover; what counts is the first time each comes. *Passes* when no send fails, and each consumer receives every +message, the Stream and the Checkpoint consumers each key's in order. + +**`failover-by-unload`** (C14, C7, C8, C9). The namespace is unloaded (`namespaces unload`): the broker closes the +topic's producers and consumers and gives the topic up, as when its ownership moves to another broker. *Passes* as +above, and the topic's stats show the producer registered again on both segments, each with a new `connectedSince`. +*This client:* `conformance::failover_by_unload`. + +**`failover-by-broker-restart`** (C14, C7, C8, C9). The broker is killed, every connection dropping, and started +again. It runs alone. *Passes* as above. *This client:* `conformance::failover_by_broker_restart`. + +### Cumulative acknowledgment + +**`cumulative-ack-across-segments`** (C7). A Stream consumer of a topic of two segments, its automatic splits and +merges off. The keys are chosen by their hash, so that the messages go to the two segments in turn. + +1. 20 messages, each received before the next is sent, so that they come from the two segments in turn. The consumer + acknowledges cumulatively the tenth. *Passes* when the subscription's backlog over the topic is 10, and a consumer + of the subscription created next receives exactly the last 10, and no other. It acknowledges them all. +2. 10 more messages, received in turn as above and not acknowledged. Segment 0 splits; 10 messages go to segment 1 and + to segment 0's children in turn. The children's messages wait for their parent to be drained, so only segment 1's + come. The consumer acknowledges cumulatively the last of them. *Passes* when the children's messages then come, and + the acknowledgment of the last one leaves no backlog. + +*This client:* `conformance::cumulative_ack_across_segments`. + +### Message ids and checkpoints + +**`id-and-checkpoint-vectors`** (C10; no broker). The SDK decodes each message id of `message_id.json` and each +checkpoint of `checkpoint.json`, and encodes them again. *Passes* when the decoded values are those listed, and the +encodings are the listed bytes (compared after decoding where `byte_exact` is false). +*This client:* [`message_id_vectors.rs`](../../crates/apache-pulsar-protocol/tests/message_id_vectors.rs), +[`checkpoint_vectors.rs`](../../crates/apache-pulsar-protocol/tests/checkpoint_vectors.rs). + +**`checkpoint-round-trip-across-layout-changes`** (C9, C10). A topic of one segment, and keyed messages before each +step. The reference client's Checkpoint consumer reads part of the topic from the earliest position and takes a +checkpoint; the segment splits; the SDK's Checkpoint consumer starts from that checkpoint, reads part of what is +left, and takes its own; the two children merge; the reference client starts from the SDK's checkpoint and reads the +rest. *Passes* when, between them, they read every message once, every key in order. *This client:* +`conformance::checkpoint_round_trip_across_layout_changes`. + +## 3. Running the suite here + +The cases against a broker are trials of the integration tests, named `conformance::` with the id's dashes as +underscores. The harness starts the broker, a proxy and the reference client in Docker: + +```bash +cargo test -p apache-pulsar --test integration conformance:: +``` + +The cases with vectors are the protocol crate's tests: + +```bash +cargo test -p apache-pulsar-protocol --test routing_vectors --test message_id_vectors --test checkpoint_vectors +``` + +The Stream consumers go through the proxy: the broker names the controller by an address of its internal listener, +which the host can't reach. + +## 4. The checklist + +Each requirement of *conformance* §2, and the tests that show this client meets it, by layer +([docs/8-quality.md](../../docs/8-quality.md) §2): *vectors* and *unit* tests of the state machines +(`apache-pulsar-protocol`), the *simulated cluster* (`apache-pulsar-testkit`), the *driver*, the client over loopback +sockets (`apache-pulsar`'s own tests), and the *broker*, a 5.0.1 one (the integration tests, the suite's cases among +them). Each list names the tests that check the requirement most directly. + +**C1. Resolve a topic and track its layout through the DAG watch, applying updates by epoch.** +- Unit: [`layout.rs`][p-layout] `a_greater_epoch_or_a_migration_supersedes`, `errors`; [`watch.rs`][d-watch] + `a_malformed_layout_is_refused`, `a_migration_replaces_the_synthetic_layout`. +- Simulated cluster: [`lookup.rs`][tk-lookup] (direct answers, redirects, proxies); [`producer.rs`][tk-producer] + `a_migration_made_while_disconnected_is_followed`; [`queue_consumer.rs`][tk-queue] + `follows_splits_and_merges_without_losing_a_message`. +- Driver: [`producer_tests.rs`][d-producer] `a_repeated_layout_is_ignored`, + `a_watch_reopens_its_session_through_failed_lookups`, `a_watch_outlives_an_error_on_its_session`, + `a_layout_that_never_comes_times_create_out`. +- Broker: `conformance::split_during_produce`, `conformance::split_and_merge_under_load`. + +**C2. Routing: a key by the high 16 bits of its Murmur3 hash to the active segment covering it; keyless round robin; +an all-legacy layout by v4's mod N.** +- Vectors: [`routing_vectors.rs`][p-routing] `routing_matches_java` (`routing-vectors`). +- Unit: [`layout.rs`][p-layout] `routes_keys_by_the_high_half`, `keyless_goes_round_robin_in_range_order`, + `legacy_layout_routes_like_v4_partitions`. +- Simulated cluster: [`producer.rs`][tk-producer] `routes_keys_by_hash_and_keyless_round_robin`, + `a_legacy_topic_routes_like_v4_partitions`, `sends_a_stamped_batch_of_one_per_message` (segment producers created + lazily); [`producer_edges.rs`][tk-producer-edges] `a_key_no_segment_covers_fails_its_send`. +- Broker: `conformance::routing_across_clients`, `conformance::legacy_routing`. + +**C3. Per-key publish order, across splits and merges; asynchronous sends in call order.** +- Simulated cluster: [`producer.rs`][tk-producer] `per_key_order_holds_across_a_split_with_traffic`, + `per_key_order_holds_across_a_merge_with_traffic`, `per_key_order_holds_across_consecutive_splits`, + `a_split_resends_in_flight_messages_before_newer_ones`, `only_the_keys_of_a_retiring_segment_are_held`; + [`producer_batching.rs`][tk-batching] `a_split_routes_the_open_batches_again_in_order`. +- Driver: [`producer_tests.rs`][d-producer] `keys_keep_their_order_across_a_split_during_traffic`, + `pipelining_combinators_keep_send_order`. +- Broker: `conformance::split_during_produce`, `conformance::split_and_merge_under_load`; + [`bridge.rs`][it-bridge] `a_producer_keeps_key_order_across_a_migration`. + +**C4. Transparent segment-gone retry when producing.** +- Simulated cluster: [`producer.rs`][tk-producer] `a_send_refused_by_a_terminated_topic_waits_for_the_layout`, + `a_gone_segment_gets_no_new_producer_and_its_sends_fail_in_the_end`; [`producer_edges.rs`][tk-producer-edges] + `a_message_is_parked_at_most_ten_times`, `a_gone_segment_retires_again_for_new_messages`, + `a_closing_segment_that_turns_out_terminated`, `a_dropped_segment_that_disconnects_parks_its_messages`. +- Broker: `conformance::split_during_produce`, `conformance::split_and_merge_under_load` (sends in flight as segments + seal; none fails). + +**C5. Deduplication by monotonic sequence ids; the last published id exposed.** +- Simulated cluster: [`producer.rs`][tk-producer] + `reconnecting_writes_unacknowledged_messages_again_with_their_sequence_ids`, + `sequence_ids_start_after_the_initial_or_the_brokers_last`, `an_application_sequence_id_is_kept`, + `a_duplicate_is_acknowledged_but_not_stored`; [`producer_batching.rs`][tk-batching] + `a_sequence_id_that_may_be_a_duplicate_goes_alone`. +- Driver: [`producer_tests.rs`][d-producer] `local_producer_sends_flushes_and_closes`, + `every_message_field_reaches_the_wire` (`last_sequence_id`). +- Broker: [`main.rs`][it-main] `batches_pass_the_brokers_deduplication`. + +**C6. The access modes: shared, exclusive, exclusive with fencing, wait for exclusive; exclusive ones claim every +segment at create.** +- Simulated cluster: [`producer.rs`][tk-producer] `exclusive_claims_every_segment_at_create`, + `a_failed_exclusive_create_releases_what_it_claimed`, `exclusive_with_fencing_fences_the_older_producer`, + `wait_for_exclusive_is_created_once_the_holder_leaves`, `a_waiting_producer_that_reconnects_waits_again`, + `a_shared_producer_is_refused_while_an_exclusive_one_holds_the_topic`; [`producer_edges.rs`][tk-producer-edges] + `exclusive_producers_claim_new_segments_from_a_layout`, `an_exclusive_create_follows_a_split_that_lands_meanwhile`. +- Driver: [`producer_tests.rs`][d-producer] `exclusive_conflicts_fail_create`, `exclusive_with_fencing_takes_the_topic`, + `wait_for_exclusive_outlasts_the_operation_timeout`. +- Broker: [`main.rs`][it-main] `exclusive_producers_conflict_at_create`, + `exclusive_with_fencing_fences_the_older_producer`. + +**C7. The Stream consumer: per-key order; a cumulative ack advancing every segment by its position vector; the +broker's cursor; the controller's assignments, rebalances, reconnects and grace period.** +- Unit: [`stream_consumer.rs`][p-stream] (the assignment session: registration, modes, drains, reconnects, close); + [`consumer.rs`][p-consumer] `cumulative_acks_go_out_once_a_group`, + `a_key_shared_consumer_acknowledges_in_the_order_given`. +- Simulated cluster: [`stream_consumer.rs`][tk-stream] `a_cumulative_ack_covers_every_segment`, + `an_ack_covers_what_was_given_before_it`, `an_ack_leaves_what_was_given_after_it`, + `keys_keep_their_order_across_two_splits`, `a_split_while_consuming_keeps_each_key_in_order`, + `members_beyond_the_segments_share_them_by_bucket`, `within_the_grace_period_the_assignment_holds`, + `past_the_grace_period_the_group_rebalances`, `a_member_comes_back_after_a_connection_loss`. +- Driver: [`stream_tests.rs`][d-stream]. +- Broker: `conformance::cumulative_ack_across_segments`, `conformance::split_and_merge_under_load`, the failover cases; + [`main.rs`][it-main] `a_stream_consumer_reads_sealed_backlog_first_in_key_order`, + `stream_consumers_share_a_segment_by_bucket`, `a_closed_stream_consumer_hands_its_segments_over_at_once`. + +**C8. The Queue consumer: parallel delivery; individual and negative acks; every active and sealed segment; acks +routed by segment.** +- Unit: [`consumer.rs`][p-consumer] `acks_go_out_together`, `negative_acks_ask_for_their_entries_again`. +- Simulated cluster: [`queue_consumer.rs`][tk-queue] `receives_from_every_segment_and_acknowledges_on_each`, + `a_consumer_subscribing_again_gets_only_what_was_not_acknowledged`, + `follows_splits_and_merges_without_losing_a_message`, + `a_new_earliest_subscription_replays_the_sealed_parent_and_the_children`, + `a_negative_ack_brings_the_message_back_after_the_delay`, `acks_of_segments_it_does_not_have_are_ignored`. +- Driver: [`consumer_tests.rs`][d-consumer]. +- Broker: `conformance::split_during_consume`, `conformance::split_and_merge_under_load`; [`main.rs`][it-main] + `a_queue_consumer_reads_and_acknowledges_every_segment`, `queue_consumers_share_a_subscription`, + `a_negative_ack_brings_a_message_back`, `batch_index_acks_settle_whole_batches`. + +**C9. The Checkpoint consumer: a position held by the application; an atomic checkpoint across segments, captured and +restored; ungrouped and grouped.** +- Simulated cluster: [`checkpoint_consumer.rs`][tk-checkpoint], [`checkpoint_group.rs`][tk-group]. +- Driver: [`checkpoint_tests.rs`][d-checkpoint]. +- Broker: `conformance::checkpoint_round_trip_across_layout_changes`; [`main.rs`][it-main] + `a_checkpoint_consumer_resumes_across_a_split`, `a_latest_checkpoint_consumer_reads_a_later_split`, + `checkpoint_group_members_share_the_segments`, `a_checkpoint_group_member_reads_the_sealed_backlog`. + +**C10. Opaque, serializable, comparable message ids, and opaque, serializable checkpoints that later versions +restore.** +- Vectors: [`message_id_vectors.rs`][p-ids], [`checkpoint_vectors.rs`][p-checkpoints] (`id-and-checkpoint-vectors`): + the bytes of the Java client, which every later release must read ([docs/8-quality.md](../../docs/8-quality.md) + §3). +- Unit: [`message_id.rs`][d-message-id] `round_trips_and_orders`; [`checkpoint.rs`][d-checkpoint-type] + `round_trips_and_prints`. `MessageId` and `Checkpoint` have no public fields. +- Broker: `conformance::checkpoint_round_trip_across_layout_changes`. + +**C11. A topic-level schema; the broker's compatibility check surfaced as a typed error.** +- Driver: [`schema_tests.rs`][d-schema] `a_topic_has_one_schema_and_its_messages_carry_the_version`, + `a_schema_of_another_type_is_refused`, `a_topic_with_data_and_no_schema_refuses_a_typed_consumer`. +- Broker: [`schemas.rs`][it-schemas] `a_schema_of_another_type_is_refused`, + `the_first_consumer_of_a_new_topic_registers_its_schema`, and Java ⇄ Rust for each schema. + +**C12. Auto-creation honored; a missing topic surfaced as `NotFound`.** +- Driver: [`producer_tests.rs`][d-producer] `a_missing_topic_is_not_found`. +- Broker: [`main.rs`][it-main] `a_missing_topic_is_not_found_without_auto_creation`; most broker tests use topics they + never create, which the broker creates. + +**C13. Typed error categories; asynchronous operations fail through their futures; transient failures retried +inside.** +- Unit and simulated cluster: [`connection.rs`][tk-connection] `which_failures_are_worth_reconnecting_for`, + `refused_connection_is_not_retryable_for_auth_errors`; [`producer.rs`][tk-producer] + `the_send_timeout_fails_late_messages_and_the_producer_carries_on`, `a_forbidden_message_fails_alone`. +- Driver: [`errors.rs`][d-errors]; [`task.rs`][d-producer-task] `send_failures_map_to_kinds`; + [`consumer/task.rs`][d-consumer-task] `subscribe_failures_map_to_kinds`; [`producer_tests.rs`][d-producer] + `invalid_configuration_fails_create`; [`consumer_tests.rs`][d-consumer] `invalid_configuration_fails_subscribe`. + Every operation that can fail returns a `Result`, through its future when it is asynchronous. +- Broker: [`main.rs`][it-main] `missing_credentials_are_refused` (`Authentication`), + `exclusive_producers_conflict_at_create`; [`schemas.rs`][it-schemas] `a_schema_of_another_type_is_refused` + (`IncompatibleSchema`). + +**C14. Long-lived producers and consumers that heal themselves; a graceful, idempotent close; thread safety.** +- Simulated cluster: [`queue_consumer.rs`][tk-queue] `keeps_consuming_and_following_the_layout_after_a_connection_loss`; + [`consumer.rs`][tk-consumer] `an_unload_closes_the_consumer_and_it_comes_back`; [`stream_consumer.rs`][tk-stream] + `a_member_comes_back_after_a_connection_loss`. +- Driver: [`tests.rs`][d-tests] `reconnects_after_the_broker_drops_the_connection`, + `request_in_flight_when_the_connection_drops_is_retried`, `client_is_send_and_sync`, + `thread_safe_client_runs_on_its_loops_from_any_executor`; [`producer_tests.rs`][d-producer] + `a_lost_connection_writes_unacknowledged_messages_again`, `close_completes_the_sends_the_broker_has`, + `local_producer_sends_flushes_and_closes` (closed twice), `thread_safe_producers_spread_over_the_loops`; + [`consumer_tests.rs`][d-consumer] `a_lost_connection_brings_back_what_was_not_acknowledged`, + `a_consumer_the_broker_closes_subscribes_again`, `closing_the_client_closes_its_consumers_and_fails_their_receives`; + [`stream_tests.rs`][d-stream] `a_lost_connection_registers_again`; [`checkpoint_tests.rs`][d-checkpoint] + `a_lost_connection_resumes_after_what_was_received`. +- Broker: `conformance::failover_by_unload`, `conformance::failover_by_broker_restart`. + +**C15. No scalable-topic command to a broker that doesn't advertise them.** +- Unit and simulated cluster: [`connection.rs`][tk-connection] `scalable_commands_need_the_broker_feature`, + `connect_advertises_the_features_the_client_honors`. +- Driver: [`producer_tests.rs`][d-producer] `a_broker_without_scalable_topics_is_refused` + (`UnsupportedBroker`); [`driver.rs`][d-driver] `a_request_the_broker_does_not_support_fails_at_once`. + +[p-layout]: ../../crates/apache-pulsar-protocol/tests/layout.rs +[p-routing]: ../../crates/apache-pulsar-protocol/tests/routing_vectors.rs +[p-stream]: ../../crates/apache-pulsar-protocol/tests/stream_consumer.rs +[p-consumer]: ../../crates/apache-pulsar-protocol/tests/consumer.rs +[p-ids]: ../../crates/apache-pulsar-protocol/tests/message_id_vectors.rs +[p-checkpoints]: ../../crates/apache-pulsar-protocol/tests/checkpoint_vectors.rs +[tk-lookup]: ../../crates/apache-pulsar-testkit/tests/lookup.rs +[tk-connection]: ../../crates/apache-pulsar-testkit/tests/connection.rs +[tk-producer]: ../../crates/apache-pulsar-testkit/tests/producer.rs +[tk-producer-edges]: ../../crates/apache-pulsar-testkit/tests/producer_edges.rs +[tk-batching]: ../../crates/apache-pulsar-testkit/tests/producer_batching.rs +[tk-consumer]: ../../crates/apache-pulsar-testkit/tests/consumer.rs +[tk-queue]: ../../crates/apache-pulsar-testkit/tests/queue_consumer.rs +[tk-stream]: ../../crates/apache-pulsar-testkit/tests/stream_consumer.rs +[tk-checkpoint]: ../../crates/apache-pulsar-testkit/tests/checkpoint_consumer.rs +[tk-group]: ../../crates/apache-pulsar-testkit/tests/checkpoint_group.rs +[d-watch]: ../../crates/apache-pulsar/src/watch.rs +[d-tests]: ../../crates/apache-pulsar/src/tests.rs +[d-driver]: ../../crates/apache-pulsar/src/tests/driver.rs +[d-errors]: ../../crates/apache-pulsar/src/tests/errors.rs +[d-producer]: ../../crates/apache-pulsar/src/producer_tests.rs +[d-producer-task]: ../../crates/apache-pulsar/src/producer/task.rs +[d-consumer]: ../../crates/apache-pulsar/src/consumer_tests.rs +[d-consumer-task]: ../../crates/apache-pulsar/src/consumer/task.rs +[d-stream]: ../../crates/apache-pulsar/src/stream_tests.rs +[d-checkpoint]: ../../crates/apache-pulsar/src/checkpoint_tests.rs +[d-checkpoint-type]: ../../crates/apache-pulsar/src/checkpoint.rs +[d-message-id]: ../../crates/apache-pulsar/src/message_id.rs +[d-schema]: ../../crates/apache-pulsar/src/schema_tests.rs +[it-main]: ../../crates/apache-pulsar/tests/integration/main.rs +[it-bridge]: ../../crates/apache-pulsar/tests/integration/bridge.rs +[it-schemas]: ../../crates/apache-pulsar/tests/integration/schemas.rs