:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion-consumer): remove capped polling and poll granularity (#126665)
Paweł Ledwoń8ac60fc5a9f9
diff --git a/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts b/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.tsindex 43c7b5713bf1..6124e1957881 100644--- a/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts+++ b/nodejs/tests/service-e2e/personhog-kafka-parity.serial.test.ts@@ -706,7 +706,10 @@ async function startRustIngestionConsumer(KAFKA_CONSUMER_AUTO_OFFSET_RESET: 'earliest',CONSUMER_BATCH_SIZE: '10',CONSUMER_BATCH_TIMEOUT_MS: '1000',- CONSUMER_MAX_BACKGROUND_TASKS: '1',+ CONSUMER_PARTITION_BUDGET_EVENTS: '10000',+ CONSUMER_PARTITION_BUDGET_BYTES: '268435456',+ CONSUMER_IN_FLIGHT_EVENTS: '100000',+ CONSUMER_IN_FLIGHT_BYTES: '1073741824',INGESTION_WORKER_CONCURRENT_BATCHES: '1',WORKER_ADDRESSES: workerUrl,INGESTION_WORKER_GRPC_PORT_OFFSET: GRPC_PORT_OFFSET.toString(),diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.tsindex a8705e18800c..c0f0ca0dcbbf 100644--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts@@ -501,7 +501,10 @@ function startRustIngestionConsumer(KAFKA_CONSUMER_AUTO_OFFSET_RESET: 'earliest',CONSUMER_BATCH_SIZE: RUST_BATCH_SIZE.toString(),CONSUMER_BATCH_TIMEOUT_MS: '1000',- CONSUMER_MAX_BACKGROUND_TASKS: '1',+ CONSUMER_PARTITION_BUDGET_EVENTS: '10000',+ CONSUMER_PARTITION_BUDGET_BYTES: '268435456',+ CONSUMER_IN_FLIGHT_EVENTS: '100000',+ CONSUMER_IN_FLIGHT_BYTES: '1073741824',INGESTION_WORKER_CONCURRENT_BATCHES: '1',// A request packs every ready key up to the target, so a poll would// go to one worker whole; a small target spreads it over both.diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex a1223b3d3ffa..2f026553b0d6 100644--- a/rust/ingestion-consumer/README.md+++ b/rust/ingestion-consumer/README.md@@ -11,7 +11,7 @@ Each guarantee has a violation counter that must stay flat and a denominator tha| Guarantee | Violations (must stay 0) | Denominator / supporting || --- | --- | --- |-| Commits are contiguous and monotonic per partition, each the ledger frontier one past the accepted prefix, and cover only completed offsets | `kafka_consumer_ledger_errors_total{stage,kind}` (a redelivered or out-of-window offset), `kafka_consumer_ledger_gap_offsets_total{topic,partition}` (offsets a frontier walked over without delivery), `ingestion_consumer_commit_violations_total{kind=empty\|uncredited}` | `ingestion_consumer_committed_offset{topic,partition}`, `kafka_consumer_ledger_uncommitted_offsets{topic,partition}` |+| Commits are contiguous and monotonic per partition, each the ledger frontier one past the accepted prefix, and cover only completed offsets | `kafka_consumer_ledger_errors_total{stage,kind}` (a redelivered or out-of-window offset), `kafka_consumer_ledger_gap_offsets_total{topic,partition}` (offsets a frontier walked over without delivery) | `ingestion_consumer_committed_offset{topic,partition}`, `kafka_consumer_ledger_uncommitted_offsets{topic,partition}` || Async commits land on the broker | `kminion_kafka_consumer_group_topic_partition_lag{group_id}` growing while `ingestion_consumer_messages_processed_total` holds its rate | `ingestion_consumer_committed_offset{topic,partition}` (the offset last handed to the client), `ingestion_consumer_offset_commits_total` || Per-key sends are in offset order, never re-sent after ACK (keyed messages only) | `ingestion_consumer_key_order_violations_total{kind=intra_group_disorder\|resend_after_ack}` | `ingestion_consumer_key_replays_total` (legal at-least-once retries), `ingestion_consumer_key_sentinel_keys`, `ingestion_consumer_key_sentinel_unkeyed_total` (skipped null-key messages) || Messages enter the worker pipeline in per-key offset order (end to end) | `ingestion_api_out_of_order_messages_total` (worker-side) | `ingestion_api_replayed_messages_total`, `ingestion_api_order_sentinel_keys` |@@ -37,13 +37,9 @@ Each frontier the consumer takes goes to the commit pacer (`commit_pacer.rs`), aThe pacer holds no I/O: the consumer commits what it is given.A partition that leaves the assignment drops its pending frontier with its ledger, so a later commit cannot commit under another owner.-`CONSUMER_COMPLETION_GRANULARITY` selects the unit that settles against the ledger; each unit is one implementation of `Settlement` in `src/settlement/`, and the consumer loop is the same for both.-`poll` (the default) settles a whole poll once every one of its groups is accepted, oldest poll first, and commits its frontiers at once.-`group` settles each group's offsets as its completion arrives, in any order, so a stalled key holds back only its own partition's commit.-At `group` granularity the pacer keeps the latest frontier per partition and hands them out at most once per `CONSUMER_COMMIT_INTERVAL_MS` (default 500 ms).+The settlement in `src/settlement/` settles each group's offsets as its completion arrives, in any order, so a stalled key holds back only its own partition's commit.+The pacer keeps the latest frontier per partition and hands them out at most once per `CONSUMER_COMMIT_INTERVAL_MS` (default 500 ms).The consumer asks the pacer on each completion wake, at the top of each loop turn, and on the completion wait's one-second heartbeat, and commits everything pending on exit.-Under the capped polling strategy, admission is per poll at both granularities: `CONSUMER_MAX_BACKGROUND_TASKS` caps in-flight polls, and a slot frees when its whole poll is covered, oldest first, so a stalled key still holds its poll's slot. See [Polling](#polling).-At `poll` granularity, `ingestion_consumer_commits_skipped_total{reason}` counts polls that settle with no frontier: `rejected` means the ledger dropped every slice (expected around a rebalance) and `no_frontier` means an earlier batch is still incomplete at the front of every window the batch settled.The settlement publishes the uncommitted gauges, because it holds both places a partition's charge can be: the ledger's window and the pacer.`kafka_consumer_ledger_uncommitted_offsets{topic,partition}` gauges the offsets each partition has polled and no commit has covered yet, including those taken for a commit the pacer still holds; `kafka_consumer_ledger_uncommitted_events` and `kafka_consumer_ledger_uncommitted_bytes` gauge the charge those offsets carry, where bytes is the payload plus key plus headers of each message.The ledger emits its own counters, so any consumer built on the crate reports the same series.@@ -53,34 +49,30 @@ The ledger emits its own counters, so any consumer built on the crate reports th## Partition budget`CONSUMER_PARTITION_BUDGET_EVENTS` and `CONSUMER_PARTITION_BUDGET_BYTES` bound each partition's replay exposure: the events and bytes the settlement reports as uncommitted for it.-A budget needs `CONSUMER_COMPLETION_GRANULARITY=group`. At `poll` a stalled partition holds back the commits of every partition in its poll, so their budgets would fill and pause together. The consumer ignores a budget at `poll` and logs a warning, so switching a lane back to `poll` rolls it back without unsetting the budget.+Both are required: the consumer does not start without them.When either axis reaches its limit after a poll, the consumer pauses that partition's fetch through the Kafka client; when a commit brings both axes back under `CONSUMER_PARTITION_BUDGET_LOW_WATERMARK` (a fraction of the budget, default 0.8), it resumes.The hysteresis matters because a pause purges the partition's fetched messages from librdkafka's queue and a resume refetches them.-A pause stops only the partition's fetch: the consumer keeps polling, so rebalance callbacks still run and `max.poll.interval.ms` stays satisfied, except while the capped polling strategy's cap is full or the continuous strategy is at its in-flight limit.+A pause stops only the partition's fetch: the consumer keeps polling, so rebalance callbacks still run and `max.poll.interval.ms` stays satisfied, except while the consumer is at its in-flight limit.A revoked partition is forgotten. librdkafka keeps a partition's pause across a revoke and a reassignment, so the consumer resumes every partition it is assigned, and the partition starts with a fresh ledger.-Both limits default to `0`, which sets no budget; the admission cap (`CONSUMER_MAX_BACKGROUND_TASKS`) then governs alone.The budget is a fixed amount per partition, not a share of a pod-wide amount, so a rebalance changes how many partitions a pod holds, not how much each may expose.`ingestion_consumer_budget_paused_partitions` gauges how many partitions are paused and `ingestion_consumer_budget_pauses_total{topic,partition}` counts pauses; read them against `ingestion_lag_ms`.## Polling-The consumer loop is the only caller of `recv()`. It waits on Kafka, completions, the commit tick, the shutdown signal, and the poll's batch timeout, and hands each event to the selected implementation of the `PollingStrategy` trait in `src/polling/`.-The strategy returns steps, and the consumer carries them out: charge and submit a poll, submit a commit and resume its partitions, stop, or fail.+The consumer loop is the only caller of `recv()`. It waits on Kafka, completions, the commit tick, the shutdown signal, and the poll's batch timeout, and hands each event to the polling strategy in `src/polling/`.+The strategy returns steps, and the consumer carries them out: charge and submit a poll, submit a commit and resume its partitions, or stop.A poll is submitted when it reaches the batch size or the byte bound, or when `CONSUMER_BATCH_TIMEOUT_MS` passes after its first message.The rebalance callbacks run inside `recv()`, on the loop's task. After every wake the loop hands the partitions they revoked to the strategy, before the event that woke it.The strategy then removes those partitions' messages from the poll in progress and from its in-flight state: the batcher purges them, or Kafka delivers them again from the last commit.So a message the loop adds to a poll always belongs to the current assignment, and the poll is charged under the partition's current ledger generation.-`CONSUMER_POLLING_STRATEGY` selects what bounds admission.-`capped` (the default) admits up to `CONSUMER_MAX_BACKGROUND_TASKS` polls, and frees a slot only when the oldest poll is covered, so a stalled key holds back fetching for every partition.--`continuous` admits polls without waiting on any of them.+The consumer admits polls without waiting on any of them.The partition budget bounds each partition's replay exposure, and the in-flight limit bounds the whole pod: `CONSUMER_IN_FLIGHT_EVENTS` and `CONSUMER_IN_FLIGHT_BYTES` count the uncommitted charge of every partition, as the partition budget counts it.The limit is approximate: it stops reading, and the poll in progress still completes, so the uncommitted charge can pass the limit by one poll. One poll holds at most `CONSUMER_BATCH_SIZE` events and `CONSUMER_BATCH_SIZE_KB` plus one message; with the byte bound off, its bytes are bounded only by the batch size times the largest message.Room frees when a commit hands out offsets, as it does for the partition budget, not when a completion arrives.At the limit the loop stops reading Kafka until a commit frees room, and rebalance callbacks wait with it, so size the limit above the budget times the partitions a pod holds.-`continuous` needs `CONSUMER_COMPLETION_GRANULARITY=group`, a partition budget, and an in-flight limit, and the budget and the limit each need both their events and bytes settings. A message with no key, value or headers charges zero bytes, so a byte-only limit admits any number of them. Without all three the consumer logs a warning and runs `capped`, so switching a lane back to `poll` rolls back both.+The budget and the limit each need both their events and bytes settings, or the consumer does not start. A message with no key, value or headers charges zero bytes, so a byte-only limit admits any number of them.`ingestion_consumer_in_flight_limit_reached_total` counts each time the loop stops reading at the limit; the `kafka_consumer_ledger_uncommitted_*` gauges show each partition's share.## Batcherdiff --git a/rust/ingestion-consumer/src/commit_pacer.rs b/rust/ingestion-consumer/src/commit_pacer.rsindex 8712e075ce32..ae83adb84c21 100644--- a/rust/ingestion-consumer/src/commit_pacer.rs+++ b/rust/ingestion-consumer/src/commit_pacer.rs@@ -23,10 +23,6 @@ struct PendingFrontier {}impl CommitPacer {- pub fn immediate() -> Self {- Self::every(Duration::ZERO)- }-pub fn every(interval: Duration) -> Self {Self {interval,@@ -125,7 +121,7 @@ mod tests {#[test]fn a_pending_frontier_is_due_on_the_next_take() {- let mut pacer = CommitPacer::immediate();+ let mut pacer = CommitPacer::every(Duration::ZERO);pacer.advance_frontier(&tp(0), taken(0, 10));let offsets = pacer.take_due(Instant::now()).expect("due");@@ -138,7 +134,7 @@ mod tests {#[test]fn the_latest_frontier_per_partition_is_what_goes_out() {- let mut pacer = CommitPacer::immediate();+ let mut pacer = CommitPacer::every(Duration::ZERO);pacer.advance_frontier(&tp(0), taken(0, 10));pacer.advance_frontier(&tp(1), taken(0, 20));pacer.advance_frontier(&tp(0), taken(10, 12));@@ -152,7 +148,7 @@ mod tests {#[test]fn a_forgotten_partition_is_not_committed() {- let mut pacer = CommitPacer::immediate();+ let mut pacer = CommitPacer::every(Duration::ZERO);pacer.advance_frontier(&tp(0), taken(0, 10));pacer.advance_frontier(&tp(1), taken(0, 20));diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 1008455f097c..40051f022d43 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -1,5 +1,4 @@use std::num::{NonZeroU32, NonZeroU64, NonZeroUsize};-use std::str::FromStr;use std::time::{Duration, Instant};use common_continuous_profiling::ContinuousProfilingConfig;@@ -19,48 +18,6 @@ use crate::partition_budget::BudgetLimits;use crate::routing::{Router, RoutingStrategy};use common_kafka_consumer::config::ConsumerConfigBuilder;-#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]-pub enum CompletionGranularity {- #[default]- Poll,- Group,-}--impl FromStr for CompletionGranularity {- type Err = String;-- fn from_str(value: &str) -> Result<Self, Self::Err> {- match value.trim().to_lowercase().as_str() {- "poll" => Ok(Self::Poll),- "group" => Ok(Self::Group),- other => Err(format!(- "unknown consumer completion granularity '{other}' (expected 'poll' or 'group')"- )),- }- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]-pub enum Polling {- #[default]- Capped,- Continuous,-}--impl FromStr for Polling {- type Err = String;-- fn from_str(value: &str) -> Result<Self, Self::Err> {- match value.trim().to_lowercase().as_str() {- "capped" => Ok(Self::Capped),- "continuous" => Ok(Self::Continuous),- other => Err(format!(- "unknown consumer polling strategy '{other}' (expected 'capped' or 'continuous')"- )),- }- }-}-/// Configuration for the ingestion consumer. Env var names and defaults match/// the Node.js ingestion consumer, so both read the same ConfigMap./// `KAFKA_CONSUMER_*` vars also apply as rdkafka overrides; see@@ -260,28 +217,16 @@ pub struct Config {#[envconfig(from = "INGESTION_GOVERNOR_STEP_INTERVAL_MS", default = "1000")]pub governor_step_interval_ms: u64,- /// Maximum polls in flight under the capped polling strategy; continuous- /// polling does not read it. Same name as the Node.js setting.- #[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]- pub consumer_max_background_tasks: usize,-- /// `poll` or `group`; see [`CompletionGranularity`].- #[envconfig(from = "CONSUMER_COMPLETION_GRANULARITY", default = "poll")]- pub consumer_completion_granularity: CompletionGranularity,-- /// Minimum spacing between offset commits at `group` granularity- /// (milliseconds). Not read at `poll` granularity.+ /// Minimum spacing between offset commits (milliseconds).#[envconfig(from = "CONSUMER_COMMIT_INTERVAL_MS", default = "500")]pub consumer_commit_interval_ms: u64,- /// Uncommitted events at which a partition's fetch pauses. `0` (default)- /// sets no event limit. Not read at `poll` granularity.+ /// Uncommitted events at which a partition's fetch pauses. Required.#[envconfig(from = "CONSUMER_PARTITION_BUDGET_EVENTS", default = "0")]pub consumer_partition_budget_events: u64,/// Uncommitted key-plus-value-plus-header bytes at which a partition's- /// fetch pauses. `0` (default) sets no byte limit. Not read at `poll`- /// granularity.+ /// fetch pauses. Required.#[envconfig(from = "CONSUMER_PARTITION_BUDGET_BYTES", default = "0")]pub consumer_partition_budget_bytes: u64,@@ -290,23 +235,15 @@ pub struct Config {#[envconfig(from = "CONSUMER_PARTITION_BUDGET_LOW_WATERMARK", default = "0.8")]pub consumer_partition_budget_low_watermark: f64,- /// `capped` or `continuous`. `continuous` runs only with `group`- /// granularity, a partition budget, and an in-flight limit; without all- /// three the consumer runs `capped`.- #[envconfig(from = "CONSUMER_POLLING_STRATEGY", default = "capped")]- pub consumer_polling_strategy: Polling,-- /// Uncommitted events across all partitions at which the continuous- /// strategy stops reading from Kafka. The poll in progress still- /// completes, so the total can pass it by `CONSUMER_BATCH_SIZE`. `0`- /// (default) sets no event limit.+ /// Uncommitted events across all partitions at which the consumer stops+ /// reading from Kafka. The poll in progress still completes, so the total+ /// can pass it by `CONSUMER_BATCH_SIZE`. Required.#[envconfig(from = "CONSUMER_IN_FLIGHT_EVENTS", default = "0")]pub consumer_in_flight_events: u64,/// Uncommitted key-plus-value-plus-header bytes across all partitions at- /// which the continuous strategy stops reading from Kafka. The poll in- /// progress still completes, so the total can pass it by one poll. `0`- /// (default) sets no byte limit.+ /// which the consumer stops reading from Kafka. The poll in progress+ /// still completes, so the total can pass it by one poll. Required.#[envconfig(from = "CONSUMER_IN_FLIGHT_BYTES", default = "0")]pub consumer_in_flight_bytes: u64,@@ -618,19 +555,36 @@ impl Config {})}+ // Each limit needs both axes, because one axis alone leaves the other+ // unbounded: a message with no key, value or headers charges zero bytes.+pub fn partition_budget(&self) -> Result<BudgetLimits, String> {- BudgetLimits::new(+ let budget = BudgetLimits::new(NonZeroU64::new(self.consumer_partition_budget_events),NonZeroU64::new(self.consumer_partition_budget_bytes),self.consumer_partition_budget_low_watermark,- )+ )?;+ if !budget.sets_both_axes() {+ return Err(+ "CONSUMER_PARTITION_BUDGET_EVENTS and CONSUMER_PARTITION_BUDGET_BYTES must both be set"+ .to_string(),+ );+ }+ Ok(budget)}- pub fn in_flight_limit(&self) -> ChargeLimit {- ChargeLimit::new(+ pub fn in_flight_limit(&self) -> Result<ChargeLimit, String> {+ let limit = ChargeLimit::new(NonZeroU64::new(self.consumer_in_flight_events),NonZeroU64::new(self.consumer_in_flight_bytes),- )+ );+ if !limit.sets_both_axes() {+ return Err(+ "CONSUMER_IN_FLIGHT_EVENTS and CONSUMER_IN_FLIGHT_BYTES must both be set"+ .to_string(),+ );+ }+ Ok(limit)}const MIN_REQUEST_SOFT_BUDGET_MS: u64 = 100;@@ -761,6 +715,7 @@ impl Config {#[cfg(test)]mod tests {use std::collections::HashMap;+ use std::str::FromStr;use rstest::rstest;@@ -824,21 +779,34 @@ mod tests {assert!(config(vars).request_budget().is_err());}+ struct LimitsCase {+ vars: &'static [(&'static str, &'static str)],+ expected_valid: bool,+ }+#[rstest]- #[case::unset(&[], false)]- #[case::events_only(&[("CONSUMER_PARTITION_BUDGET_EVENTS", "5000")], true)]- #[case::bytes_only(&[("CONSUMER_PARTITION_BUDGET_BYTES", "1048576")], true)]- fn a_valid_partition_budget_is_read(#[case] vars: &[(&str, &str)], #[case] is_set: bool) {- assert_eq!(config(vars).partition_budget().unwrap().is_set(), is_set);+ #[case::both_axes(LimitsCase { vars: &[("CONSUMER_PARTITION_BUDGET_EVENTS", "5000"), ("CONSUMER_PARTITION_BUDGET_BYTES", "1048576")], expected_valid: true })]+ #[case::unset(LimitsCase { vars: &[], expected_valid: false })]+ #[case::events_only(LimitsCase { vars: &[("CONSUMER_PARTITION_BUDGET_EVENTS", "5000")], expected_valid: false })]+ #[case::bytes_only(LimitsCase { vars: &[("CONSUMER_PARTITION_BUDGET_BYTES", "1048576")], expected_valid: false })]+ #[case::an_invalid_watermark(LimitsCase { vars: &[("CONSUMER_PARTITION_BUDGET_EVENTS", "5000"), ("CONSUMER_PARTITION_BUDGET_BYTES", "1048576"), ("CONSUMER_PARTITION_BUDGET_LOW_WATERMARK", "1.2")], expected_valid: false })]+ fn the_partition_budget_needs_both_axes(#[case] case: LimitsCase) {+ assert_eq!(+ config(case.vars).partition_budget().is_ok(),+ case.expected_valid+ );}- #[test]- fn a_partition_budget_with_an_invalid_watermark_is_rejected() {- let vars = &[- ("CONSUMER_PARTITION_BUDGET_EVENTS", "5000"),- ("CONSUMER_PARTITION_BUDGET_LOW_WATERMARK", "1.2"),- ];- assert!(config(vars).partition_budget().is_err());+ #[rstest]+ #[case::both_axes(LimitsCase { vars: &[("CONSUMER_IN_FLIGHT_EVENTS", "30000"), ("CONSUMER_IN_FLIGHT_BYTES", "52428800")], expected_valid: true })]+ #[case::unset(LimitsCase { vars: &[], expected_valid: false })]+ #[case::events_only(LimitsCase { vars: &[("CONSUMER_IN_FLIGHT_EVENTS", "30000")], expected_valid: false })]+ #[case::bytes_only(LimitsCase { vars: &[("CONSUMER_IN_FLIGHT_BYTES", "52428800")], expected_valid: false })]+ fn the_in_flight_limit_needs_both_axes(#[case] case: LimitsCase) {+ assert_eq!(+ config(case.vars).in_flight_limit().is_ok(),+ case.expected_valid+ );}#[rstest]@@ -900,17 +868,4 @@ mod tests {assert_eq!(Adaptation::from_str("off"), Ok(Adaptation::Off));assert!(Adaptation::from_str("true").is_err());}-- #[test]- fn completion_granularity_parses_known_values() {- assert_eq!(- CompletionGranularity::from_str(" POLL "),- Ok(CompletionGranularity::Poll)- );- assert_eq!(- CompletionGranularity::from_str("group"),- Ok(CompletionGranularity::Group)- );- assert!(CompletionGranularity::from_str("batch").is_err());- }}diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex e58084713362..b1af291221db 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -1,6 +1,6 @@use std::collections::HashMap;use std::sync::{Arc, Mutex};-use std::time::{Duration, Instant};+use std::time::Duration;use common_kafka_consumer::{AssignmentEpoch, GroupCompletion, Offset, Partition, TopicOffsetLedger, TopicPartition,@@ -17,23 +17,22 @@ use tracing::{error, info, warn};use crate::batcher::{make_batch_id, Batcher, BatcherObserver, BatcherOutputs, Revoker};use crate::charge_limit::ChargeLimit;-use crate::config::{CompletionGranularity, Config, Polling};+use crate::config::Config;use crate::debug_recorder::{record_if, CommitOffset, DebugEventKind, DebugRecorder};use crate::discovery::DiscoveryMode;use crate::grpc_transport::GrpcTransport;use crate::ledger_rejection::{report_rejection, RejectedSlice};use crate::partition_budget::BudgetLimits;use crate::polling::{- self, debug_partition_offsets, debug_partition_spans, BatchStats, CappedPolling,- CollectedBatch, ContinuousPolling, InFlightPoll, PartitionDeliveries, Parts, PollLimits,- PollingStrategy, Selected, Step,+ debug_partition_offsets, debug_partition_spans, BatchStats, CollectedBatch, ContinuousPolling,+ InFlightPoll, PartitionDeliveries, Parts, PollLimits, PollingStrategy, Step,};use crate::rebalance::{partition_error, PartitionHook, RebalanceContext};-use crate::settlement::{self, Commit, Settlement};+use crate::settlement::{Commit, GroupSettlement, Settlement};fn revoke_hook(revoker: Revoker,- settlement: Arc<dyn Settlement>,+ settlement: Arc<GroupSettlement>,revoked_partitions: Arc<Mutex<Vec<TopicPartition>>>,) -> PartitionHook {Box::new(move |partitions| {@@ -51,7 +50,7 @@ fn revoke_hook(}fn assign_hook(- settlement: Arc<dyn Settlement>,+ settlement: Arc<GroupSettlement>,assignment_epoch: AssignmentEpoch,revoked_partitions: Arc<Mutex<Vec<TopicPartition>>>,) -> PartitionHook {@@ -69,7 +68,7 @@ fn assign_hook(fn wire_rebalance_hooks(context: &RebalanceContext,revoker: Revoker,- settlement: &Arc<dyn Settlement>,+ settlement: &Arc<GroupSettlement>,assignment_epoch: AssignmentEpoch,) -> Arc<Mutex<Vec<TopicPartition>>> {let revoked_partitions = Arc::new(Mutex::new(Vec::new()));@@ -86,15 +85,14 @@ fn wire_rebalance_hooks(revoked_partitions}-fn commit_tick(granularity: CompletionGranularity, commit_interval: Duration) -> Duration {+fn commit_tick(commit_interval: Duration) -> Duration {const HEALTH_TICK: Duration = Duration::from_secs(1);// A commit can resume a partition, so a tick longer than the commit// interval delays the resume.- match granularity {- CompletionGranularity::Group if !commit_interval.is_zero() => {- commit_interval.min(HEALTH_TICK)- }- _ => HEALTH_TICK,+ if commit_interval.is_zero() {+ HEALTH_TICK+ } else {+ commit_interval.min(HEALTH_TICK)}}@@ -105,13 +103,9 @@ pub struct IngestionConsumerOptions {/// See `Config::consumer_batch_size_kb`.pub batch_size_bytes: usize,pub batch_timeout: Duration,- /// The capped strategy's admission cap, in polls.- pub max_in_flight_batches: usize,- pub polling: Polling,pub in_flight_limit: ChargeLimit,pub group_id: String,pub debug_recorder: Option<Arc<DebugRecorder>>,- pub completion_granularity: CompletionGranularity,pub commit_interval: Duration,pub ledger: Arc<TopicOffsetLedger>,pub partition_budget: BudgetLimits,@@ -119,7 +113,7 @@ pub struct IngestionConsumerOptions {/// The main consumer loop: reads from Kafka, demuxes each poll into groups,/// submits them to the [`Batcher`], and commits offsets once the batcher's-/// completions cover a poll or a group.+/// completions cover a group.pub struct IngestionConsumer {consumer: Arc<StreamConsumer<RebalanceContext>>,batcher: Batcher,@@ -130,7 +124,7 @@ pub struct IngestionConsumer {batch_size: usize,batch_size_bytes: usize,batch_timeout: Duration,- polling: Selected,+ in_flight_limit: ChargeLimit,commit_tick: Duration,handle: Handle,group_id: String,@@ -139,7 +133,7 @@ pub struct IngestionConsumer {/// Partitions revoked since the loop last looked, fed by the rebalance/// callback.revoked_partitions: Arc<Mutex<Vec<TopicPartition>>>,- settlement: Arc<dyn Settlement>,+ settlement: Arc<GroupSettlement>,}impl IngestionConsumer {@@ -155,19 +149,11 @@ impl IngestionConsumer {handle: Handle,) -> Self {let topic_offset_ledger = options.ledger;- let polling = polling::select(- options.polling,- options.completion_granularity,- &options.partition_budget,- options.in_flight_limit,- options.max_in_flight_batches,- );- let settlement = settlement::for_granularity(- options.completion_granularity,+ let settlement: Arc<GroupSettlement> = Arc::new(GroupSettlement::new(Arc::clone(&topic_offset_ledger),options.commit_interval,options.partition_budget,- );+ ));let revoked_partitions = wire_rebalance_hooks(consumer.context(),batcher.revoker(),@@ -188,8 +174,8 @@ impl IngestionConsumer {batch_size: options.batch_size,batch_size_bytes: options.batch_size_bytes,batch_timeout: options.batch_timeout,- polling,- commit_tick: commit_tick(options.completion_granularity, options.commit_interval),+ in_flight_limit: options.in_flight_limit,+ commit_tick: commit_tick(options.commit_interval),handle,group_id: options.group_id,}@@ -228,19 +214,15 @@ impl IngestionConsumer {let partition_budget = config.partition_budget().map_err(|err| anyhow::anyhow!("invalid partition budget: {err}"))?;- let polling = polling::select(- config.consumer_polling_strategy,- config.consumer_completion_granularity,- &partition_budget,- config.in_flight_limit(),- config.consumer_max_background_tasks,- );- let settlement = settlement::for_granularity(- config.consumer_completion_granularity,+ let in_flight_limit = config+ .in_flight_limit()+ .map_err(|err| anyhow::anyhow!("invalid in-flight limit: {err}"))?;+ let commit_interval = Duration::from_millis(config.consumer_commit_interval_ms);+ let settlement: Arc<GroupSettlement> = Arc::new(GroupSettlement::new(Arc::clone(&topic_offset_ledger),- Duration::from_millis(config.consumer_commit_interval_ms),+ commit_interval,partition_budget,- );+ ));let context = RebalanceContext::new();let revoked_partitions = wire_rebalance_hooks(&context,@@ -259,8 +241,7 @@ impl IngestionConsumer {workers = worker_urls.len(),batch_size = config.consumer_batch_size,batch_size_kb = config.consumer_batch_size_kb,- completion_granularity = ?config.consumer_completion_granularity,- polling = ?polling,+ in_flight_limit = ?in_flight_limit,"Kafka consumer subscribed");@@ -277,11 +258,8 @@ impl IngestionConsumer {batch_size: config.consumer_batch_size,batch_size_bytes: config.consumer_batch_size_kb.saturating_mul(1024),batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),- polling,- commit_tick: commit_tick(- config.consumer_completion_granularity,- Duration::from_millis(config.consumer_commit_interval_ms),- ),+ in_flight_limit,+ commit_tick: commit_tick(commit_interval),handle,group_id: config.ingestion_consumer_group_id.clone(),})@@ -326,20 +304,9 @@ impl IngestionConsumer {},settlement: Arc::clone(&self.settlement),group_id: self.group_id.clone(),- debug_recorder: self.debug_recorder.clone(),};- match self.polling {- Selected::Capped {- max_in_flight_polls,- } => {- let poller = CappedPolling::new(parts, max_in_flight_polls);- self.run(poller, completions, errors).await;- }- Selected::Continuous { in_flight } => {- let poller = ContinuousPolling::new(parts, in_flight);- self.run(poller, completions, errors).await;- }- }+ let poller = ContinuousPolling::new(parts, self.in_flight_limit);+ self.run(poller, completions, errors).await;if let Err(err) = self.commit_all() {warn!(error = %err, "Could not submit pending frontiers on exit");}@@ -440,7 +407,6 @@ impl IngestionConsumer {}Step::Commit(commit) => self.commit(commit).map_err(Stopped::Commit),Step::Stop => Err(Stopped::Drained),- Step::Fail(err) => Err(Stopped::Batch(err)),}}@@ -557,14 +523,8 @@ impl IngestionConsumer {);Ok(InFlightPoll {- poll_id,- assignment_epoch,partitions,uncommitted,- message_count: message_count as u32,- covered: 0,- accepted: 0,- dispatched_at: Instant::now(),})}@@ -727,17 +687,15 @@ mod tests {use crate::settlement::{GroupSettlement, Pause};#[rstest::rstest]- #[case::group_below_a_second(CompletionGranularity::Group, 200, 200)]- #[case::group_above_a_second(CompletionGranularity::Group, 5_000, 1_000)]- #[case::group_immediate(CompletionGranularity::Group, 0, 1_000)]- #[case::poll(CompletionGranularity::Poll, 200, 1_000)]+ #[case::below_a_second(200, 200)]+ #[case::above_a_second(5_000, 1_000)]+ #[case::immediate(0, 1_000)]fn the_commit_tick_follows_the_commit_interval(- #[case] granularity: CompletionGranularity,#[case] commit_interval_ms: u64,#[case] expected_ms: u64,) {assert_eq!(- commit_tick(granularity, Duration::from_millis(commit_interval_ms)),+ commit_tick(Duration::from_millis(commit_interval_ms)),Duration::from_millis(expected_ms));}@@ -745,7 +703,7 @@ mod tests {#[test]fn an_assignment_without_a_revoke_drops_the_partitions_pending_frontier() {let ledger = Arc::new(TopicOffsetLedger::new());- let settlement: Arc<dyn Settlement> = Arc::new(GroupSettlement::new(+ let settlement: Arc<GroupSettlement> = Arc::new(GroupSettlement::new(Arc::clone(&ledger),Duration::from_secs(3600),BudgetLimits::new(NonZeroU64::new(1), None, 0.5).expect("valid limits"),diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 60a68ebc2775..c036f04e4977 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -53,6 +53,9 @@ fn main() -> Result<()> {config.partition_budget().map_err(|err| anyhow::anyhow!("invalid partition budget: {err}"))?;+ config+ .in_flight_limit()+ .map_err(|err| anyhow::anyhow!("invalid in-flight limit: {err}"))?;let runtime = tokio::runtime::Builder::new_multi_thread().enable_all()diff --git a/rust/ingestion-consumer/src/polling/capped.rs b/rust/ingestion-consumer/src/polling/capped.rsdeleted file mode 100644index 313ab5fa0226..000000000000--- a/rust/ingestion-consumer/src/polling/capped.rs+++ /dev/null@@ -1,545 +0,0 @@-use std::collections::{HashMap, VecDeque};-use std::sync::Arc;--use common_kafka_consumer::{GroupCompletion, Offset, TopicPartition};-use metrics::{counter, gauge};-use rdkafka::message::Message;-use tokio::time::Instant;-use tracing::warn;--use super::poll::{debug_partition_offsets, InFlightPoll, PartitionDeliveries};-use super::{report_revoked, Collector, Parts, PollingStrategy, Step};-use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder};-use crate::settlement::Settlement;--/// Admits up to `max_in_flight_polls` polls, and frees a slot only when the-/// oldest poll is covered.-pub(crate) struct CappedPolling {- collector: Collector,- settlement: Arc<dyn Settlement>,- max_in_flight_polls: usize,- in_flight_polls: VecDeque<InFlightPoll>,- accepting_new_batches: bool,- commit_due: bool,- group_id: String,- debug_recorder: Option<Arc<DebugRecorder>>,-}--impl CappedPolling {- pub(crate) fn new(parts: Parts, max_in_flight_polls: usize) -> Self {- Self {- collector: Collector::new(parts.limits),- settlement: parts.settlement,- max_in_flight_polls: max_in_flight_polls.max(1),- in_flight_polls: VecDeque::new(),- accepting_new_batches: true,- commit_due: false,- group_id: parts.group_id,- debug_recorder: parts.debug_recorder,- }- }-}--impl PollingStrategy for CappedPolling {- fn reading(&mut self) -> bool {- self.accepting_new_batches && self.in_flight_polls.len() < self.max_in_flight_polls- }-- fn deadline(&self) -> Option<Instant> {- self.collector.deadline()- }-- fn received<M: Message>(&mut self, message: &M, now: Instant) {- self.collector.add(message, now);- }-- fn completed(&mut self, completion: &GroupCompletion) -> anyhow::Result<()> {- let settlement = &*self.settlement;- apply_completion(- &mut self.in_flight_polls,- completion,- |tp, generation, run| settlement.settle_run(tp, generation, run).map(drop),- )?;- self.commit_due = true;- Ok(())- }-- fn ticked(&mut self) {- self.commit_due = true;- }-- fn revoked(&mut self, topic_partitions: &[TopicPartition]) {- let building = self.collector.remove_partitions(topic_partitions) as u64;- let in_flight = strip_revoked_partitions(&mut self.in_flight_polls, topic_partitions);- self.report_in_flight();- report_revoked(building + in_flight);- }-- fn shutdown(&mut self) {- self.accepting_new_batches = false;- self.collector.discard();- }-- fn submitted(&mut self, poll: InFlightPoll) {- self.in_flight_polls.push_back(poll);- self.report_in_flight();- }-- fn next_step(&mut self, now: Instant) -> Option<Step> {- while self- .in_flight_polls- .front()- .is_some_and(InFlightPoll::is_complete)- {- if let Err(err) = self.retire_oldest_poll() {- return Some(Step::Fail(err));- }- self.commit_due = true;- }- if std::mem::take(&mut self.commit_due) {- if let Some(commit) = self.settlement.take_due(now.into_std()) {- return Some(Step::Commit(commit));- }- }- if let Some(collected) = self.collector.take_ready(now) {- return Some(Step::Submit(collected));- }- (!self.accepting_new_batches && self.in_flight_polls.is_empty()).then_some(Step::Stop)- }-}--impl CappedPolling {- fn retire_oldest_poll(&mut self) -> anyhow::Result<()> {- let poll = pop_committable(&mut self.in_flight_polls)?;- self.report_in_flight();- self.settlement.settle_poll(&poll.charged_slices())?;- emit_latest_processed_timestamp_metrics(&poll.partitions, &self.group_id);- record_if(&self.debug_recorder, || DebugEventKind::PollCompleted {- batch_id: poll.poll_id.clone(),- accepted: poll.accepted,- duration_ms: poll.dispatched_at.elapsed().as_millis() as u64,- partitions: debug_partition_offsets(&poll.partitions),- });- counter!("ingestion_consumer_messages_processed_total").increment(poll.accepted as u64);- counter!("ingestion_consumer_batches_processed_total").increment(1);- Ok(())- }-- fn report_in_flight(&self) {- gauge!("ingestion_consumer_in_flight_batches").set(self.in_flight_polls.len() as f64);- }-}--/// Keeps the other partitions' slices: a dropped slice never settles, and-/// its partition's commits stop at that hole.-fn strip_revoked_partitions(- in_flight_polls: &mut VecDeque<InFlightPoll>,- revoked: &[TopicPartition],-) -> u64 {- let mut stripped: u64 = 0;- for poll in in_flight_polls.iter_mut() {- let mut removed_delivered = 0u32;- let mut removed_covered = 0u32;- let mut removed_accepted = 0u32;- poll.partitions.retain(|topic_partition, deliveries| {- if revoked.contains(topic_partition) {- removed_delivered += deliveries.delivered;- removed_covered += deliveries.covered;- removed_accepted += deliveries.accepted;- false- } else {- true- }- });- if removed_delivered > 0 {- stripped += u64::from(removed_delivered);- poll.message_count = poll.message_count.saturating_sub(removed_delivered);- poll.covered = poll.covered.saturating_sub(removed_covered);- poll.accepted = poll.accepted.saturating_sub(removed_accepted);- }- }- in_flight_polls.retain(|poll| poll.message_count > 0);- stripped-}--/// A key-table run can merge several polls into one send, so a completion-/// can span polls. Within one epoch, spans are disjoint per partition, so an-/// offset matches at most one poll.-fn apply_completion(- in_flight: &mut VecDeque<InFlightPoll>,- completion: &GroupCompletion,- mut settle: impl FnMut(&TopicPartition, u64, &[Offset]) -> anyhow::Result<()>,-) -> anyhow::Result<()> {- let fully_accepted = completion.accepted as usize == completion.offsets.len();- let mut accepted = completion.accepted;- let mut unmatched: u64 = 0;- let mut remaining = completion.offsets.as_slice();- 'runs: while let Some(first) = remaining.first() {- for poll in in_flight- .iter_mut()- .filter(|poll| poll.assignment_epoch == completion.assignment_epoch)- {- for (topic_partition, deliveries) in poll.partitions.iter_mut() {- let span = deliveries.span;- if topic_partition.partition != completion.partition.0- || first.0 < span.first- || span.last < first.0- {- continue;- }- let run_len = remaining- .iter()- .take_while(|offset| span.first <= offset.0 && offset.0 <= span.last)- .count();- let (run, rest) = remaining.split_at(run_len);- let run_accepted = accepted.min(run_len as u32);- accepted -= run_accepted;- poll.covered += run_len as u32;- poll.accepted += run_accepted;- deliveries.covered += run_len as u32;- deliveries.accepted += run_accepted;- let settleable = deliveries.credit_run(run);- if fully_accepted && !settleable.is_empty() {- settle(topic_partition, deliveries.generation, &settleable)?;- }- remaining = rest;- continue 'runs;- }- }- unmatched += 1;- remaining = &remaining[1..];- }- if unmatched > 0 {- counter!("ingestion_consumer_stale_group_completions_total").increment(1);- warn!(- partition = %completion.partition,- unmatched,- epoch = completion.assignment_epoch,- "Discarding completion offsets that match no in-flight poll"- );- }- Ok(())-}--fn pop_committable(in_flight: &mut VecDeque<InFlightPoll>) -> anyhow::Result<InFlightPoll> {- let poll = in_flight.pop_front().expect("front is present");- if poll.accepted < poll.message_count {- anyhow::bail!(- "accepted {}/{} messages — not committing offsets",- poll.accepted,- poll.message_count- );- }- if let Some((topic_partition, offset)) = poll.uncredited_charge() {- counter!("ingestion_consumer_commit_violations_total", "kind" => "uncredited").increment(1);- anyhow::bail!(- "offset {} of {}/{} has no completion — not committing offsets",- offset.0,- topic_partition.topic,- topic_partition.partition- );- }- Ok(poll)-}--fn emit_latest_processed_timestamp_metrics(- partitions: &HashMap<TopicPartition, PartitionDeliveries>,- group_id: &str,-) {- // Same name as the Node.js consumer's gauge, so one dashboard reads both.- for (topic_partition, partition) in partitions {- gauge!(- "latest_processed_timestamp_ms",- "topic" => topic_partition.topic.clone(),- "partition" => topic_partition.partition.to_string(),- "groupId" => group_id.to_string()- )- .set(partition.latest_kafka_ts as f64);- }-}--#[cfg(test)]-mod tests {- use std::collections::HashSet;- use std::time::{Duration, Instant};-- use common_kafka_consumer::{Charge, Offset as MessageOffset, Partition, TopicOffsetLedger};-- use super::super::harness::{p, Harness};- use super::*;- use crate::order_sentinel::OffsetSpan;- use crate::partition_budget::BudgetLimits;- use crate::settlement::{charge_offsets, GroupSettlement};-- fn poll(epoch: u64, partition: i32, first: i64, last: i64, count: u32) -> InFlightPoll {- let mut partitions = HashMap::new();- partitions.insert(- TopicPartition::new("test", partition),- PartitionDeliveries {- span: OffsetSpan { first, last },- generation: 0,- payload_bytes: 0,- charges: (first..=last)- .map(|offset| (MessageOffset(offset), Charge::ZERO))- .collect(),- latest_kafka_ts: 0,- max_lag_ms: None,- delivered: count,- covered: 0,- accepted: 0,- credited: HashSet::default(),- },- );- InFlightPoll {- poll_id: format!("poll-{epoch}-{partition}-{first}"),- assignment_epoch: epoch,- partitions,- uncommitted: HashMap::new(),- message_count: count,- covered: 0,- accepted: 0,- dispatched_at: Instant::now(),- }- }-- fn completion(epoch: u64, partition: i32, offsets: &[i64], accepted: u32) -> GroupCompletion {- GroupCompletion {- partition: Partition(partition),- assignment_epoch: epoch,- generation: 0,- offsets: offsets.iter().map(|o| MessageOffset(*o)).collect(),- accepted,- }- }-- fn credit(in_flight: &mut VecDeque<InFlightPoll>, completion: GroupCompletion) {- apply_completion(in_flight, &completion, |_, _, _| Ok(())).unwrap();- }-- #[test]- fn an_accepted_completion_settles_one_run_per_poll() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);- in_flight[1]- .partitions- .get_mut(&TopicPartition::new("test", 0))- .unwrap()- .generation = 1;- let mut runs = Vec::new();-- apply_completion(- &mut in_flight,- &completion(1, 0, &[2, 3, 4, 5], 4),- |topic_partition, generation, offsets| {- runs.push((topic_partition.partition, generation, offsets.to_vec()));- Ok(())- },- )- .unwrap();-- assert_eq!(- runs,- vec![- (0, 0, vec![MessageOffset(2), MessageOffset(3)]),- (0, 1, vec![MessageOffset(4), MessageOffset(5)]),- ],- "each run carries its own poll's generation"- );- }-- #[test]- fn a_completion_spanning_two_polls_commits_once_the_prefix_is_whole() {- let ledger = Arc::new(TopicOffsetLedger::new());- let settlement =- GroupSettlement::new(Arc::clone(&ledger), Duration::ZERO, BudgetLimits::unset());- let partition = TopicPartition::new("test", 0);- charge_offsets(&ledger, &partition, 0, &[0, 1, 2, 3, 4, 5, 6, 7]);- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);- let mut settle = |topic_partition: &TopicPartition, generation: u64, offsets: &[Offset]| {- settlement- .settle_run(topic_partition, generation, offsets)- .map(drop)- };-- apply_completion(- &mut in_flight,- &completion(1, 0, &[2, 3, 4, 5], 4),- &mut settle,- )- .unwrap();- assert!(- settlement.take_due(Instant::now()).is_none(),- "offsets 0 and 1 are still in flight"- );-- apply_completion(- &mut in_flight,- &completion(1, 0, &[0, 1, 6, 7], 4),- &mut settle,- )- .unwrap();- assert_eq!(- settlement- .take_due(Instant::now())- .map(|commit| commit.offsets),- Some(HashMap::from([(partition, MessageOffset(8))]))- );- }-- #[test]- fn a_short_accepted_completion_settles_nothing() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4)]);- let mut runs = 0;-- apply_completion(&mut in_flight, &completion(1, 0, &[0, 1], 1), |_, _, _| {- runs += 1;- Ok(())- })- .unwrap();-- assert_eq!(runs, 0, "the ledger must not commit past a dropped message");- assert_eq!(in_flight[0].covered, 2);- assert_eq!(in_flight[0].accepted, 1);- }-- #[test]- fn apply_completion_spanning_two_polls_credits_each() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);-- credit(&mut in_flight, completion(1, 0, &[2, 3, 4, 5], 4));-- assert_eq!(in_flight[0].covered, 2);- assert_eq!(in_flight[0].accepted, 2);- assert_eq!(in_flight[1].covered, 2);- assert_eq!(in_flight[1].accepted, 2);- }-- #[test]- fn apply_completion_under_report_shorts_the_tail_poll() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);-- credit(&mut in_flight, completion(1, 0, &[2, 3, 4, 5], 3));-- assert_eq!(in_flight[0].accepted, 2, "leading offsets are accepted");- assert_eq!(- in_flight[1].accepted, 1,- "the tail poll fails its accepted check"- );- assert_eq!(in_flight[1].covered, 2);- }-- #[test]- fn a_complete_poll_with_a_charged_offset_no_completion_covered_is_not_committable() {- let mut in_flight = VecDeque::from([poll(1, 0, 10, 12, 3)]);-- credit(&mut in_flight, completion(1, 0, &[10, 12, 12], 3));-- assert!(in_flight[0].is_complete());- let error = pop_committable(&mut in_flight)- .err()- .expect("offset 11 has no completion");- assert!(error.to_string().contains("offset 11 "), "{error}");- }-- #[test]- fn a_poll_whose_deliveries_span_an_offset_gap_commits() {- let mut gapped = poll(1, 0, 0, 0, 2);- let deliveries = gapped- .partitions- .get_mut(&TopicPartition::new("test", 0))- .unwrap();- deliveries.span.last = i64::MAX;- deliveries- .charges- .push((MessageOffset(i64::MAX), Charge::ZERO));- let mut in_flight = VecDeque::from([gapped]);-- credit(&mut in_flight, completion(1, 0, &[0, i64::MAX], 2));-- assert!(in_flight[0].is_complete());- assert!(pop_committable(&mut in_flight).is_ok());- }-- #[test]- fn strip_revoked_partitions_keeps_the_other_partitions_slices() {- let mut two = poll(1, 0, 0, 1, 4);- two.partitions.insert(- TopicPartition::new("test", 1),- PartitionDeliveries {- span: OffsetSpan {- first: 10,- last: 11,- },- generation: 0,- payload_bytes: 0,- charges: Vec::new(),- latest_kafka_ts: 0,- max_lag_ms: None,- delivered: 2,- covered: 0,- accepted: 0,- credited: HashSet::default(),- },- );- two.partitions- .get_mut(&TopicPartition::new("test", 0))- .unwrap()- .delivered = 2;- let mut in_flight = VecDeque::from([two]);- credit(&mut in_flight, completion(1, 1, &[10], 1));-- let stripped = strip_revoked_partitions(&mut in_flight, &[TopicPartition::new("test", 1)]);-- assert_eq!(stripped, 2);- assert_eq!(in_flight[0].message_count, 2);- assert_eq!(in_flight[0].covered, 0, "the revoked slice's credit goes");- assert!(!in_flight[0].is_complete());-- credit(&mut in_flight, completion(1, 1, &[11], 1));- assert_eq!(in_flight[0].covered, 0);- credit(&mut in_flight, completion(1, 0, &[0, 1], 2));- assert!(in_flight[0].is_complete());- assert_eq!(in_flight[0].accepted, 2);- assert!(pop_committable(&mut in_flight).is_ok());- }-- #[test]- fn strip_revoked_partitions_removes_an_emptied_poll() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 2, 0, 3, 4)]);-- let stripped = strip_revoked_partitions(&mut in_flight, &[TopicPartition::new("test", 0)]);-- assert_eq!(stripped, 4);- assert_eq!(in_flight.len(), 1);- assert_eq!(in_flight[0].message_count, 4);- }-- #[test]- fn apply_completion_requires_a_matching_epoch() {- let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(2, 0, 0, 3, 4)]);-- credit(&mut in_flight, completion(2, 0, &[0, 1, 2, 3], 4));-- assert_eq!(in_flight[0].covered, 0);- assert_eq!(in_flight[1].covered, 4);- }-- fn capped(max_in_flight_polls: usize) -> Harness<CappedPolling> {- Harness::new(|parts| CappedPolling::new(parts, max_in_flight_polls))- }-- #[test]- fn the_capped_strategy_stops_reading_at_its_cap_until_the_oldest_poll_is_covered() {- let mut harness = capped(1);- assert!(harness.poller.reading());-- harness.receive(0, &[0, 1]);- assert!(harness.step().is_none(), "the poll is still collecting");- harness.after_the_batch_timeout();- harness.submit();- assert!(!harness.poller.reading());-- harness.complete(0, &[0, 1]);- assert_eq!(harness.commit(), HashMap::from([(p(0), Offset(2))]));- assert!(harness.poller.reading());- }-}diff --git a/rust/ingestion-consumer/src/polling/continuous.rs b/rust/ingestion-consumer/src/polling/continuous.rsindex 9358598ab6fa..edb7d7ad1be2 100644--- a/rust/ingestion-consumer/src/polling/continuous.rs+++ b/rust/ingestion-consumer/src/polling/continuous.rs@@ -9,13 +9,13 @@ use tokio::time::Instant;use super::poll::InFlightPoll;use super::{report_revoked, Collector, Parts, PollingStrategy, Step};use crate::charge_limit::ChargeLimit;-use crate::settlement::{Commit, RunOutcome, Settlement};+use crate::settlement::{Commit, GroupSettlement, RunOutcome, Settlement};/// Nothing waits on a submitted poll: the partition budget and the in-flight/// limit bound admission.pub(crate) struct ContinuousPolling {collector: Collector,- settlement: Arc<dyn Settlement>,+ settlement: Arc<GroupSettlement>,uncommitted: UncommittedCharges,processed: ProcessedTimestamps,limits: ChargeLimit,diff --git a/rust/ingestion-consumer/src/polling/harness.rs b/rust/ingestion-consumer/src/polling/harness.rsindex 51cd6401c958..bd4e7bee210d 100644--- a/rust/ingestion-consumer/src/polling/harness.rs+++ b/rust/ingestion-consumer/src/polling/harness.rs@@ -16,7 +16,7 @@ pub(super) const BATCH_TIMEOUT: Duration = Duration::from_millis(500);pub(super) struct Harness<P> {pub(super) poller: P,- pub(super) settlement: Arc<dyn Settlement>,+ pub(super) settlement: Arc<GroupSettlement>,pub(super) ledger: Arc<TopicOffsetLedger>,pub(super) now: Instant,}@@ -24,7 +24,7 @@ pub(super) struct Harness<P> {impl<P: PollingStrategy> Harness<P> {pub(super) fn new(make: impl FnOnce(Parts) -> P) -> Self {let ledger = Arc::new(TopicOffsetLedger::new());- let settlement: Arc<dyn Settlement> = Arc::new(GroupSettlement::new(+ let settlement: Arc<GroupSettlement> = Arc::new(GroupSettlement::new(Arc::clone(&ledger),Duration::ZERO,BudgetLimits::unset(),@@ -37,7 +37,6 @@ impl<P: PollingStrategy> Harness<P> {},settlement: Arc::clone(&settlement),group_id: "test".to_string(),- debug_recorder: None,});Self {poller,@@ -66,11 +65,7 @@ impl<P: PollingStrategy> Harness<P> {let Some(Step::Submit(collected)) = self.step() else {panic!("expected a poll to submit");};- let CollectedBatch {- accumulator,- mut partitions,- ..- } = collected;+ let CollectedBatch { mut partitions, .. } = collected;let mut uncommitted = HashMap::new();for (topic_partition, deliveries) in &mut partitions {deliveries.generation = self.ledger.generation(topic_partition);@@ -90,14 +85,8 @@ impl<P: PollingStrategy> Harness<P> {}).collect();self.poller.submitted(InFlightPoll {- poll_id: "poll".to_string(),- assignment_epoch: 1,partitions,uncommitted,- message_count: accumulator.message_count() as u32,- covered: 0,- accepted: 0,- dispatched_at: std::time::Instant::now(),});spans}diff --git a/rust/ingestion-consumer/src/polling/mod.rs b/rust/ingestion-consumer/src/polling/mod.rsindex c0f5efbf1c73..feb998cd9979 100644--- a/rust/ingestion-consumer/src/polling/mod.rs+++ b/rust/ingestion-consumer/src/polling/mod.rs@@ -2,7 +2,6 @@//! consumer owns the Kafka client and the batcher outputs, hands each event to//! the polling strategy, and carries out the [`Step`]s the strategy returns.-mod capped;mod collector;mod continuous;#[cfg(test)]@@ -15,15 +14,10 @@ use common_kafka_consumer::{GroupCompletion, TopicPartition};use metrics::counter;use rdkafka::message::Message;use tokio::time::Instant;-use tracing::{info, warn};+use tracing::info;-use crate::charge_limit::ChargeLimit;-use crate::config::{CompletionGranularity, Polling};-use crate::debug_recorder::DebugRecorder;-use crate::partition_budget::BudgetLimits;-use crate::settlement::{Commit, Settlement};+use crate::settlement::{Commit, GroupSettlement};-pub(crate) use capped::CappedPolling;use collector::Collector;pub(crate) use collector::PollLimits;pub(crate) use continuous::ContinuousPolling;@@ -40,14 +34,12 @@ pub(crate) enum Step {Commit(Commit),/// Shutdown drained the in-flight work.Stop,- Fail(anyhow::Error),}pub(crate) struct Parts {pub(crate) limits: PollLimits,- pub(crate) settlement: Arc<dyn Settlement>,+ pub(crate) settlement: Arc<GroupSettlement>,pub(crate) group_id: String,- pub(crate) debug_recorder: Option<Arc<DebugRecorder>>,}pub(crate) trait PollingStrategy {@@ -81,117 +73,3 @@ fn report_revoked(stripped: u64) {info!(stripped, "Removed revoked partitions' messages");}}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(crate) enum Selected {- Capped { max_in_flight_polls: usize },- Continuous { in_flight: ChargeLimit },-}--/// Continuous polling needs `group` granularity, because at `poll` only a-/// retired poll settles, and continuous polling retires no poll. It needs a-/// partition budget and an in-flight limit, because it has no in-flight poll-/// cap. Each needs both axes, because one axis alone leaves the other-/// unbounded: a message with no key, value or headers charges zero bytes.-/// Without all three the capped strategy runs, so a lane rolled back to `poll` needs no-/// second setting changed.-pub(crate) fn select(- polling: Polling,- granularity: CompletionGranularity,- budget: &BudgetLimits,- in_flight: ChargeLimit,- max_in_flight_polls: usize,-) -> Selected {- let capped = Selected::Capped {- max_in_flight_polls,- };- if polling == Polling::Capped {- return capped;- }- let missing: Vec<&str> = [- (- granularity != CompletionGranularity::Group,- "CONSUMER_COMPLETION_GRANULARITY=group",- ),- (- !budget.sets_both_axes(),- "a partition budget on events and bytes",- ),- (- !in_flight.sets_both_axes(),- "an in-flight limit on events and bytes",- ),- ]- .into_iter()- .filter_map(|(missing, requirement)| missing.then_some(requirement))- .collect();- if missing.is_empty() {- return Selected::Continuous { in_flight };- }- warn!(- missing = missing.join(", "),- "Running the capped polling strategy: continuous polling needs all its requirements"- );- capped-}--#[cfg(test)]-mod tests {- use std::num::NonZeroU64;-- use super::*;-- #[derive(Clone, Copy)]- enum Axes {- Neither,- Events,- Bytes,- Both,- }-- impl Axes {- fn limits(self) -> (Option<NonZeroU64>, Option<NonZeroU64>) {- let (events, bytes) = match self {- Axes::Neither => (0, 0),- Axes::Events => (100, 0),- Axes::Bytes => (0, 100_000),- Axes::Both => (100, 100_000),- };- (NonZeroU64::new(events), NonZeroU64::new(bytes))- }- }-- struct SelectCase {- granularity: CompletionGranularity,- budget: Axes,- in_flight: Axes,- expected_continuous: bool,- }-- #[rstest::rstest]- #[case::all_requirements(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Both, in_flight: Axes::Both, expected_continuous: true })]- #[case::poll_granularity(SelectCase { granularity: CompletionGranularity::Poll, budget: Axes::Both, in_flight: Axes::Both, expected_continuous: false })]- #[case::no_budget(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Neither, in_flight: Axes::Both, expected_continuous: false })]- #[case::event_only_budget(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Events, in_flight: Axes::Both, expected_continuous: false })]- #[case::byte_only_budget(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Bytes, in_flight: Axes::Both, expected_continuous: false })]- #[case::no_in_flight_limit(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Both, in_flight: Axes::Neither, expected_continuous: false })]- #[case::event_only_in_flight_limit(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Both, in_flight: Axes::Events, expected_continuous: false })]- #[case::byte_only_in_flight_limit(SelectCase { granularity: CompletionGranularity::Group, budget: Axes::Both, in_flight: Axes::Bytes, expected_continuous: false })]- fn continuous_polling_runs_only_with_all_its_requirements(#[case] case: SelectCase) {- let (events, bytes) = case.budget.limits();- let budget = BudgetLimits::new(events, bytes, 0.8).unwrap();- let (events, bytes) = case.in_flight.limits();- let in_flight = ChargeLimit::new(events, bytes);-- let selected = select(Polling::Continuous, case.granularity, &budget, in_flight, 4);-- let expected = if case.expected_continuous {- Selected::Continuous { in_flight }- } else {- Selected::Capped {- max_in_flight_polls: 4,- }- };- assert_eq!(selected, expected);- }-}diff --git a/rust/ingestion-consumer/src/polling/poll.rs b/rust/ingestion-consumer/src/polling/poll.rsindex e3ddb8c8cf76..0373a1ac2f31 100644--- a/rust/ingestion-consumer/src/polling/poll.rs+++ b/rust/ingestion-consumer/src/polling/poll.rs@@ -1,11 +1,9 @@-use std::collections::{HashMap, HashSet};-use std::time::Instant;+use std::collections::HashMap;use common_kafka_consumer::{Charge, Offset, TopicPartition};use crate::debug_recorder::{PartitionOffset, PartitionOffsets};use crate::order_sentinel::OffsetSpan;-use crate::settlement::ChargedSlice;use crate::types::Accumulator;#[derive(Default)]@@ -37,14 +35,7 @@ pub(crate) struct PartitionDeliveries {/// Max Kafka message timestamp (ms).pub(crate) latest_kafka_ts: i64,pub(crate) max_lag_ms: Option<i64>,- /// Messages the poll delivered, covered, and accepted from this- /// partition, so a revoked partition can leave the poll exactly.pub(crate) delivered: u32,- pub(crate) covered: u32,- pub(crate) accepted: u32,- /// The offsets that completions covered. Keyed by offset, not by position- /// in `span`, because `span` can have gaps.- pub(crate) credited: HashSet<i64, ahash::RandomState>,}impl PartitionDeliveries {@@ -57,36 +48,9 @@ impl PartitionDeliveries {latest_kafka_ts: delivery.kafka_ts,max_lag_ms: delivery.lag_ms,delivered: 1,- covered: 0,- accepted: 0,- credited: HashSet::default(),}}- /// Credit a completion's run and return the offsets to settle: those- /// charged that no earlier completion credited.- pub(crate) fn credit_run(&mut self, run: &[Offset]) -> Vec<Offset> {- let Self {- credited, charges, ..- } = self;- run.iter()- .copied()- .filter(|offset| {- credited.insert(offset.0)- && charges- .binary_search_by_key(&offset.0, |(charged, _)| charged.0)- .is_ok()- })- .collect()- }-- pub(crate) fn uncredited_charge(&self) -> Option<Offset> {- self.charges- .iter()- .map(|(offset, _)| *offset)- .find(|offset| !self.credited.contains(&offset.0))- }-pub(crate) fn record(&mut self, delivery: &Delivery) {self.span.extend(delivery.offset);self.delivered += 1;@@ -107,48 +71,8 @@ pub(crate) struct CollectedBatch {}pub(crate) struct InFlightPoll {- /// For logs and debug events only.- pub(crate) poll_id: String,- /// The epoch the batcher stamped on this poll's completions.- pub(crate) assignment_epoch: u64,pub(crate) partitions: HashMap<TopicPartition, PartitionDeliveries>,pub(crate) uncommitted: HashMap<TopicPartition, Charge>,- pub(crate) message_count: u32,- /// Messages covered by completions so far, accepted or not.- pub(crate) covered: u32,- /// Worker-accepted messages so far.- pub(crate) accepted: u32,- pub(crate) dispatched_at: Instant,-}--impl InFlightPoll {- pub(crate) fn is_complete(&self) -> bool {- self.covered >= self.message_count- }-- /// A charged offset that no completion covered. A complete poll can still- /// have one, because `covered` also counts an offset that is credited twice.- pub(crate) fn uncredited_charge(&self) -> Option<(&TopicPartition, Offset)> {- self.partitions- .iter()- .find_map(|(topic_partition, deliveries)| {- deliveries- .uncredited_charge()- .map(|offset| (topic_partition, offset))- })- }-- pub(crate) fn charged_slices(&self) -> Vec<ChargedSlice<'_>> {- self.partitions- .iter()- .map(|(topic_partition, deliveries)| ChargedSlice {- topic_partition,- generation: deliveries.generation,- span: deliveries.span,- charges: &deliveries.charges,- })- .collect()- }}/// Per-partition max offset + observed lag for the debug UI's batch events.diff --git a/rust/ingestion-consumer/src/settlement/group.rs b/rust/ingestion-consumer/src/settlement/group.rsindex 8543ed7329aa..4e8a0c7112a5 100644--- a/rust/ingestion-consumer/src/settlement/group.rs+++ b/rust/ingestion-consumer/src/settlement/group.rs@@ -4,8 +4,7 @@ use std::time::{Duration, Instant};use common_kafka_consumer::{Charge, Offset, Rejection, TopicOffsetLedger, TopicPartition};use super::{- Accounting, Admission, Charged, ChargedSlice, Commit, PartitionBudget, RunOutcome, Settlement,- Uncommitted,+ Accounting, Admission, Charged, Commit, PartitionBudget, RunOutcome, Settlement, Uncommitted,};use crate::commit_pacer::CommitPacer;use crate::ledger_rejection::{report_rejection, RejectedSlice};@@ -74,10 +73,6 @@ impl<A: Accounting + 'static, D: Admission + 'static> Settlement for GroupSettleOk(RunOutcome::Settled)}- fn settle_poll(&self, _slices: &[ChargedSlice<'_>]) -> anyhow::Result<()> {- Ok(())- }-fn take_due(&self, now: Instant) -> Option<Commit> {let handed_out = self.accounting.take_due(now)?;let resume = self.admission.handed_out(&handed_out);@@ -260,26 +255,6 @@ mod tests {);}- #[test]- fn a_retired_poll_settles_nothing() {- let (settlement, accounting, _) = settlement();- let charges = [(Offset(10), Charge::ZERO)];-- settlement- .settle_poll(&[ChargedSlice {- topic_partition: &p(0),- generation: 0,- span: OffsetSpan {- first: 10,- last: 10,- },- charges: &charges,- }])- .unwrap();-- assert!(accounting.settles_seen().is_empty());- }-#[test]fn a_revoke_reaches_both_the_accounting_and_the_admission() {let (settlement, accounting, admission) = settlement();diff --git a/rust/ingestion-consumer/src/settlement/mod.rs b/rust/ingestion-consumer/src/settlement/mod.rsindex 65b3328fc3bd..bb4fc2eea8a7 100644--- a/rust/ingestion-consumer/src/settlement/mod.rs+++ b/rust/ingestion-consumer/src/settlement/mod.rs@@ -1,36 +1,23 @@-//! When accepted offsets reach the ledger and the commit pacer: per poll or per group.+//! When accepted offsets reach the ledger and the commit pacer: per group.mod budget;#[cfg(test)]mod fakes;mod group;-mod poll;mod uncommitted;use std::collections::HashMap;-use std::sync::Arc;-use std::time::{Duration, Instant};+use std::time::Instant;-use common_kafka_consumer::{Charge, Held, Offset, Rejection, TopicOffsetLedger, TopicPartition};+use common_kafka_consumer::{Charge, Held, Offset, Rejection, TopicPartition};-use tracing::warn;--use crate::config::CompletionGranularity;-use crate::order_sentinel::OffsetSpan;-use crate::partition_budget::BudgetLimits;+#[cfg(test)]+use common_kafka_consumer::TopicOffsetLedger;use budget::PartitionBudget;pub(crate) use group::GroupSettlement;-pub(crate) use poll::PollSettlement;use uncommitted::Uncommitted;-pub(crate) struct ChargedSlice<'a> {- pub(crate) topic_partition: &'a TopicPartition,- pub(crate) generation: u64,- pub(crate) span: OffsetSpan,- pub(crate) charges: &'a [(Offset, Charge)],-}-pub(crate) trait Settlement: Send + Sync {fn charge(&self,@@ -47,9 +34,6 @@ pub(crate) trait Settlement: Send + Sync {offsets: &[Offset],) -> anyhow::Result<RunOutcome>;- /// The oldest poll retired with every message accepted.- fn settle_poll(&self, slices: &[ChargedSlice<'_>]) -> anyhow::Result<()>;-fn take_due(&self, now: Instant) -> Option<Commit>;fn take_all(&self) -> Option<Commit>;@@ -126,27 +110,6 @@ impl Commit {}}-pub(crate) fn for_granularity(- granularity: CompletionGranularity,- ledger: Arc<TopicOffsetLedger>,- commit_interval: Duration,- limits: BudgetLimits,-) -> Arc<dyn Settlement> {- match granularity {- CompletionGranularity::Poll => {- if limits.is_set() {- warn!(- "Ignoring the partition budget: it needs CONSUMER_COMPLETION_GRANULARITY=group"- );- }- Arc::new(PollSettlement::new(ledger))- }- CompletionGranularity::Group => {- Arc::new(GroupSettlement::new(ledger, commit_interval, limits))- }- }-}-#[cfg(test)]pub(crate) fn charge_offsets(ledger: &TopicOffsetLedger,diff --git a/rust/ingestion-consumer/src/settlement/poll.rs b/rust/ingestion-consumer/src/settlement/poll.rsdeleted file mode 100644index b73483988361..000000000000--- a/rust/ingestion-consumer/src/settlement/poll.rs+++ /dev/null@@ -1,431 +0,0 @@-use std::sync::Arc;-use std::time::Instant;--use common_kafka_consumer::{Charge, Offset, Rejection, TopicOffsetLedger, TopicPartition};-use metrics::counter;-use tracing::warn;--use super::{Accounting, Charged, ChargedSlice, Commit, RunOutcome, Settlement, Uncommitted};-use crate::commit_pacer::CommitPacer;-use crate::ledger_rejection::{report_rejection, RejectedSlice};--pub(crate) struct PollSettlement<A: Accounting = Uncommitted> {- uncommitted: A,-}--impl PollSettlement {- pub(crate) fn new(ledger: Arc<TopicOffsetLedger>) -> Self {- Self {- uncommitted: Uncommitted::new(ledger, CommitPacer::immediate()),- }- }-}--impl<A: Accounting + 'static> Settlement for PollSettlement<A> {- fn charge(- &self,- topic_partition: &TopicPartition,- generation: u64,- charges: &[(Offset, Charge)],- ) -> Result<Charged, Rejection> {- self.uncommitted- .charge(topic_partition, generation, charges)- .map(|uncommitted| Charged {- uncommitted: uncommitted.charge,- pause: None,- })- }-- fn settle_run(- &self,- _topic_partition: &TopicPartition,- _generation: u64,- _offsets: &[Offset],- ) -> anyhow::Result<RunOutcome> {- Ok(RunOutcome::Settled)- }-- fn settle_poll(&self, slices: &[ChargedSlice<'_>]) -> anyhow::Result<()> {- if slices.is_empty() {- // Unreachable: a batch always holds a message. Counted so that "no- // empty commits" is measured, not assumed.- counter!("ingestion_consumer_commit_violations_total", "kind" => "empty").increment(1);- warn!("Poll settled with no partitions");- return Ok(());- }-- if let Some(no_frontier) = settle_slices(&self.uncommitted, slices)? {- let reason = no_frontier.reason();- counter!("ingestion_consumer_commits_skipped_total", "reason" => reason).increment(1);- warn!(reason, "Poll handed over no frontier; nothing to commit");- }- Ok(())- }-- fn take_due(&self, now: Instant) -> Option<Commit> {- let handed_out = self.uncommitted.take_due(now)?;- Some(Commit::new(handed_out, Vec::new()))- }-- fn take_all(&self) -> Option<Commit> {- let handed_out = self.uncommitted.take_all()?;- Some(Commit::new(handed_out, Vec::new()))- }-- fn forget_partitions(&self, topic_partitions: &[TopicPartition]) {- self.uncommitted.forget_partitions(topic_partitions);- }-}--enum NoFrontier {- EveryPartitionRejected,- BehindAnEarlierPoll,-}--impl NoFrontier {- fn reason(self) -> &'static str {- match self {- Self::EveryPartitionRejected => "rejected",- Self::BehindAnEarlierPoll => "no_frontier",- }- }-}--fn settle_slices(- uncommitted: &impl Accounting,- slices: &[ChargedSlice<'_>],-) -> anyhow::Result<Option<NoFrontier>> {- let mut settled = false;- let mut handed_over = false;- for slice in slices {- let frontier = match uncommitted.settled(- slice.topic_partition,- slice.generation,- slice.charges.iter().map(|(offset, _)| *offset),- ) {- Ok(frontier) => frontier,- Err(rejection) => {- report_rejection(- "settle",- slice.topic_partition,- rejection,- RejectedSlice::settled(&slice.span),- )?;- continue;- }- };- settled = true;- handed_over |= frontier.is_some();- }- Ok(match (handed_over, settled) {- (true, _) => None,- (false, true) => Some(NoFrontier::BehindAnEarlierPoll),- (false, false) => Some(NoFrontier::EveryPartitionRejected),- })-}--#[cfg(test)]-mod tests {- use std::collections::HashMap;-- use common_kafka_consumer::{Held, LedgerError};- use metrics_util::debugging::{DebugValue, DebuggingRecorder};-- use super::super::fakes::{FakeAccounting, Settled};- use super::super::HandedOut;- use super::*;- use crate::order_sentinel::OffsetSpan;-- fn p(partition: i32) -> TopicPartition {- TopicPartition::new("events", partition)- }-- fn settlement() -> (PollSettlement<FakeAccounting>, FakeAccounting) {- let accounting = FakeAccounting::default();- let settlement = PollSettlement {- uncommitted: accounting.clone(),- };- (settlement, accounting)- }-- struct Slice {- topic_partition: TopicPartition,- charges: Vec<(Offset, Charge)>,- }-- impl Slice {- fn of(partition: i32, offsets: &[i64]) -> Self {- Self {- topic_partition: p(partition),- charges: offsets- .iter()- .map(|&offset| (Offset(offset), Charge::ZERO))- .collect(),- }- }-- fn charged(&self) -> ChargedSlice<'_> {- ChargedSlice {- topic_partition: &self.topic_partition,- generation: 2,- span: OffsetSpan {- first: self.charges[0].0 .0,- last: self.charges[self.charges.len() - 1].0 .0,- },- charges: &self.charges,- }- }- }-- fn stale() -> Rejection {- Rejection::Stale {- stamp: 0,- generation: 1,- }- }-- fn settle_poll_counting_skips(- settlement: &PollSettlement<FakeAccounting>,- slices: &[Slice],- ) -> (anyhow::Result<()>, Vec<String>) {- let recorder = DebuggingRecorder::new();- let snapshotter = recorder.snapshotter();- let charged: Vec<ChargedSlice<'_>> = slices.iter().map(Slice::charged).collect();- let result = metrics::with_local_recorder(&recorder, || settlement.settle_poll(&charged));- let skipped = snapshotter- .snapshot()- .into_vec()- .into_iter()- .filter(|(key, _, _, value)| {- key.key().name() == "ingestion_consumer_commits_skipped_total"- && matches!(value, DebugValue::Counter(count) if *count > 0)- })- .filter_map(|(key, _, _, _)| {- key.key()- .labels()- .find(|label| label.key() == "reason")- .map(|label| label.value().to_string())- })- .collect();- (result, skipped)- }-- #[test]- fn a_retired_poll_settles_each_slice_under_its_generation() {- let (settlement, accounting) = settlement();-- settle_poll_counting_skips(&settlement, &[Slice::of(0, &[10, 11]), Slice::of(1, &[20])])- .0- .unwrap();-- assert_eq!(- accounting.settles_seen(),- vec![- Settled {- topic_partition: p(0),- generation: 2,- offsets: vec![Offset(10), Offset(11)],- },- Settled {- topic_partition: p(1),- generation: 2,- offsets: vec![Offset(20)],- },- ]- );- }-- struct RetiredPoll {- settles: Vec<Result<Option<Offset>, Rejection>>,- expected_skip: Option<&'static str>,- }-- #[rstest::rstest]- #[case::a_frontier(RetiredPoll { settles: vec![Ok(Some(Offset(12)))], expected_skip: None })]- #[case::behind_an_earlier_poll(RetiredPoll { settles: vec![Ok(None)], expected_skip: Some("no_frontier") })]- #[case::every_slice_stale(RetiredPoll { settles: vec![Err(stale())], expected_skip: Some("rejected") })]- #[case::one_stale_one_frontier(RetiredPoll { settles: vec![Err(stale()), Ok(Some(Offset(21)))], expected_skip: None })]- #[case::one_stale_one_behind(RetiredPoll { settles: vec![Err(stale()), Ok(None)], expected_skip: Some("no_frontier") })]- fn a_retired_poll_that_hands_over_no_frontier_counts_why(#[case] poll: RetiredPoll) {- let (settlement, accounting) = settlement();- let slices: Vec<Slice> = (0..poll.settles.len() as i32)- .map(|partition| Slice::of(partition, &[10]))- .collect();- for result in poll.settles {- accounting.settle_returns(result);- }-- let (result, skipped) = settle_poll_counting_skips(&settlement, &slices);-- result.unwrap();- assert_eq!(- skipped,- poll.expected_skip- .into_iter()- .map(String::from)- .collect::<Vec<_>>()- );- }-- #[test]- fn a_violating_slice_fails_the_poll_and_stops_settling() {- let (settlement, accounting) = settlement();- accounting.settle_returns(Err(Rejection::Violation {- error: LedgerError::CompletedTwice { offset: Offset(10) },- stamp: 2,- generation: 2,- held: Held::default(),- }));-- let (result, _) =- settle_poll_counting_skips(&settlement, &[Slice::of(0, &[10]), Slice::of(1, &[20])]);-- assert!(result.is_err());- assert_eq!(accounting.settles_seen().len(), 1);- }-- #[test]- fn a_run_settles_nothing_before_its_poll_retires() {- let (settlement, accounting) = settlement();-- settlement.settle_run(&p(0), 2, &[Offset(10)]).unwrap();-- assert!(accounting.settles_seen().is_empty());- }-- #[test]- fn a_charge_never_pauses() {- let (settlement, accounting) = settlement();- accounting.charge_returns(Ok(Held {- offsets: usize::MAX,- charge: Charge {- events: u64::MAX,- bytes: u64::MAX,- },- }));-- assert_eq!(- settlement- .charge(&p(0), 2, &[])- .map(|charged| charged.pause),- Ok(None)- );- }-- #[test]- fn a_hand_out_commits_without_resuming() {- let (settlement, accounting) = settlement();- accounting.take_hands_out(HashMap::from([(- p(0),- HandedOut {- offset: Offset(12),- remaining: Held::default(),- },- )]));-- let commit = settlement.take_due(Instant::now()).expect("handed out");-- assert_eq!(commit.offsets, HashMap::from([(p(0), Offset(12))]));- assert!(commit.resume.is_empty());- }-}--#[cfg(test)]-mod integration_tests {- use std::collections::HashMap;-- use common_kafka_consumer::Charge;-- use super::*;- use crate::order_sentinel::OffsetSpan;-- fn settlement() -> (Arc<TopicOffsetLedger>, PollSettlement) {- let ledger = Arc::new(TopicOffsetLedger::new());- let settlement = PollSettlement::new(Arc::clone(&ledger));- (ledger, settlement)- }-- struct Charged {- topic_partition: TopicPartition,- generation: u64,- span: OffsetSpan,- charges: Vec<(Offset, Charge)>,- }-- impl Charged {- fn slice(&self) -> ChargedSlice<'_> {- ChargedSlice {- topic_partition: &self.topic_partition,- generation: self.generation,- span: self.span,- charges: &self.charges,- }- }- }-- fn charged(ledger: &TopicOffsetLedger, partition: i32, first: i64, last: i64) -> Charged {- let topic_partition = TopicPartition::new("test", partition);- let generation = ledger.generation(&topic_partition);- let charges: Vec<(Offset, Charge)> = (first..=last)- .map(|offset| (Offset(offset), Charge::ZERO))- .collect();- ledger- .charge(&topic_partition, generation, charges.iter().copied())- .expect("charge");- Charged {- topic_partition,- generation,- span: OffsetSpan { first, last },- charges,- }- }-- #[test]- fn a_retired_poll_makes_each_partitions_frontier_due() {- let (ledger, settlement) = settlement();- let p0 = charged(&ledger, 0, 10, 11);- let p1 = charged(&ledger, 1, 20, 21);-- settlement.settle_poll(&[p0.slice(), p1.slice()]).unwrap();-- assert_eq!(- settlement- .take_due(Instant::now())- .map(|commit| commit.offsets),- Some(HashMap::from([- (p0.topic_partition, Offset(12)),- (p1.topic_partition, Offset(22)),- ]))- );- }-- #[test]- fn a_poll_behind_an_earlier_one_becomes_due_when_the_earlier_retires() {- let (ledger, settlement) = settlement();- let older = charged(&ledger, 0, 10, 11);- let newer = charged(&ledger, 0, 12, 13);-- settlement.settle_poll(&[newer.slice()]).unwrap();- assert!(settlement.take_due(Instant::now()).is_none());-- settlement.settle_poll(&[older.slice()]).unwrap();- assert_eq!(- settlement- .take_due(Instant::now())- .map(|commit| commit.offsets),- Some(HashMap::from([(older.topic_partition, Offset(14))]))- );- }-- #[test]- fn a_stale_poll_makes_nothing_due() {- let (ledger, settlement) = settlement();- let poll = charged(&ledger, 0, 10, 11);- // The partition left and came back while the poll was in flight.- ledger.forget_partitions([("test", 0)]);-- settlement.settle_poll(&[poll.slice()]).unwrap();-- assert!(settlement.take_due(Instant::now()).is_none());- }-}diff --git a/rust/ingestion-consumer/src/settlement/uncommitted.rs b/rust/ingestion-consumer/src/settlement/uncommitted.rsindex b1cf6bb87897..4e96ebfef9c6 100644--- a/rust/ingestion-consumer/src/settlement/uncommitted.rs+++ b/rust/ingestion-consumer/src/settlement/uncommitted.rs@@ -126,6 +126,8 @@ fn publish(topic_partition: &TopicPartition, uncommitted: Held) {#[cfg(test)]mod tests {+ use std::time::Duration;+use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};use super::*;@@ -150,7 +152,10 @@ mod tests {}fn uncommitted() -> Uncommitted {- Uncommitted::new(Arc::new(TopicOffsetLedger::new()), CommitPacer::immediate())+ Uncommitted::new(+ Arc::new(TopicOffsetLedger::new()),+ CommitPacer::every(Duration::ZERO),+ )}fn published(snapshotter: &Snapshotter, topic_partition: &TopicPartition) -> Held {diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex caffb54f2680..76b67c5285d4 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -32,7 +32,6 @@ use ingestion_consumer::batcher::state_machine::RequestBudget;use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;use ingestion_consumer::batcher::BatcherObserver;use ingestion_consumer::charge_limit::ChargeLimit;-use ingestion_consumer::config::{CompletionGranularity, Polling};use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};use ingestion_consumer::debug_recorder::{DebugEventKind, DebugRecorder};use ingestion_consumer::discovery::reconcile_membership;@@ -586,13 +585,10 @@ struct Harness {group_id: String,pub ledger: Arc<TopicOffsetLedger>,debug_recorder: Arc<DebugRecorder>,- max_in_flight: usize,deferred_flush_timeout: Duration,pack_targets: PackTargets,budget: Option<RequestBudget>,- completion_granularity: CompletionGranularity,partition_budget: BudgetLimits,- polling: Polling,in_flight_limit: ChargeLimit,}@@ -666,7 +662,6 @@ impl Harness {topic: &str,partitions: i32,worker_count: usize,- max_in_flight: usize,deferred_flush_timeout: Duration,registry_config: WorkerRegistryConfig,) -> Self {@@ -674,17 +669,14 @@ impl Harness {topic,partitions,worker_count,- max_in_flight,deferred_flush_timeout,registry_config,0,ComponentOptions::new(),common::PRODUCTION_PACK_TARGETS,None,- CompletionGranularity::Poll,COMMIT_INTERVAL,BudgetLimits::unset(),- Polling::Capped,ChargeLimit::unset(),).await@@ -696,10 +688,6 @@ impl Harness {topic,partitions,1,- // A poll can end after one message, so later polls must reach the- // packer while the first waits for its run. Every poll under a- // held request also stays in flight, and a full cap stops polling.- 512,Duration::from_secs(60),fast_registry_config(),0,@@ -715,21 +703,17 @@ impl Harness {soft_budget: Duration::from_millis(500),attempts: BUDGET_ATTEMPTS,}),- CompletionGranularity::Poll,COMMIT_INTERVAL,BudgetLimits::unset(),- Polling::Capped,ChargeLimit::unset(),).await}- #[allow(clippy::too_many_arguments)]async fn start_with_pack_targets(topic: &str,partitions: i32,worker_count: usize,- max_in_flight: usize,deferred_flush_timeout: Duration,registry_config: WorkerRegistryConfig,pack_targets: PackTargets,@@ -738,17 +722,14 @@ impl Harness {topic,partitions,worker_count,- max_in_flight,deferred_flush_timeout,registry_config,0,ComponentOptions::new(),pack_targets,None,- CompletionGranularity::Poll,COMMIT_INTERVAL,BudgetLimits::unset(),- Polling::Capped,ChargeLimit::unset(),).await@@ -765,7 +746,6 @@ impl Harness {topic,1,worker_count,- 1,deferred_flush_timeout,fast_registry_config(),0,@@ -774,105 +754,50 @@ impl Harness {.with_stall_threshold(stall_threshold),common::ONE_MESSAGE_PER_REQUEST,None,- CompletionGranularity::Poll,COMMIT_INTERVAL,BudgetLimits::unset(),- Polling::Capped,ChargeLimit::unset(),).await}- async fn start_polling(- topic: &str,- partitions: i32,- worker_count: usize,- max_in_flight: usize,- batch_size_bytes: usize,- polling: Polling,- ) -> Self {- let (granularity, partition_budget, in_flight_limit) = match polling {- Polling::Capped => (- CompletionGranularity::Poll,- BudgetLimits::unset(),- ChargeLimit::unset(),- ),- Polling::Continuous => (- CompletionGranularity::Group,- BudgetLimits::new(- NonZeroU64::new(10_000),- NonZeroU64::new(UNBOUNDED_BYTES),- 0.8,- )- .expect("a valid budget"),- ChargeLimit::new(NonZeroU64::new(100_000), NonZeroU64::new(UNBOUNDED_BYTES)),- ),- };+ async fn start_byte_capped(topic: &str, batch_size_bytes: usize) -> Self {Self::start_inner(topic,- partitions,- worker_count,- max_in_flight,+ 1,+ 1,Duration::from_secs(60),fast_registry_config(),batch_size_bytes,ComponentOptions::new(),common::PRODUCTION_PACK_TARGETS,None,- granularity,- COMMIT_INTERVAL,- partition_budget,- polling,- in_flight_limit,- )- .await- }-- async fn start_byte_capped(topic: &str, batch_size_bytes: usize, polling: Polling) -> Self {- Self::start_polling(topic, 1, 1, 1, batch_size_bytes, polling).await- }-- async fn start_group_granularity(- pack_targets: PackTargets,- topic: &str,- partitions: i32,- worker_count: usize,- max_in_flight: usize,- ) -> Self {- Self::start_group_granularity_committing_every(- pack_targets,- topic,- partitions,- worker_count,- max_in_flight,COMMIT_INTERVAL,+ BudgetLimits::unset(),+ ChargeLimit::unset(),).await}- async fn start_group_granularity_committing_every(+ async fn start_committing_every(pack_targets: PackTargets,topic: &str,partitions: i32,worker_count: usize,- max_in_flight: usize,commit_interval: Duration,) -> Self {Self::start_inner(topic,partitions,worker_count,- max_in_flight,Duration::from_secs(60),fast_registry_config(),0,ComponentOptions::new(),pack_targets,None,- CompletionGranularity::Group,commit_interval,BudgetLimits::unset(),- Polling::Capped,ChargeLimit::unset(),).await@@ -884,37 +809,19 @@ impl Harness {partitions: i32,worker_count: usize,partition_budget: BudgetLimits,- polling: Polling,) -> Self {- let (max_in_flight, in_flight_limit) = match polling {- Polling::Capped => (8, ChargeLimit::unset()),- // One poll slot: the continuous loop must not wait on any poll.- Polling::Continuous => (- 1,- ChargeLimit::new(NonZeroU64::new(1_000), NonZeroU64::new(UNBOUNDED_BYTES)),- ),- };- Self::start_inner(+ Self::start_with_limits(+ pack_targets,topic,partitions,worker_count,- max_in_flight,- Duration::from_secs(60),- fast_registry_config(),- 0,- ComponentOptions::new(),- pack_targets,- None,- CompletionGranularity::Group,- COMMIT_INTERVAL,partition_budget,- polling,- in_flight_limit,+ ChargeLimit::new(NonZeroU64::new(1_000), NonZeroU64::new(UNBOUNDED_BYTES)),).await}- async fn start_continuous(+ async fn start_with_limits(pack_targets: PackTargets,topic: &str,partitions: i32,@@ -926,17 +833,14 @@ impl Harness {topic,partitions,worker_count,- 1,Duration::from_secs(60),fast_registry_config(),0,ComponentOptions::new(),pack_targets,None,- CompletionGranularity::Group,COMMIT_INTERVAL,partition_budget,- Polling::Continuous,in_flight_limit,).await@@ -954,17 +858,14 @@ impl Harness {topic,partitions,worker_count,- 8,Duration::from_secs(60),fast_registry_config(),0,ComponentOptions::new(),pack_targets,None,- CompletionGranularity::Group,commit_interval,partition_budget,- Polling::Capped,ChargeLimit::unset(),).await@@ -975,17 +876,14 @@ impl Harness {topic: &str,partitions: i32,worker_count: usize,- max_in_flight: usize,deferred_flush_timeout: Duration,registry_config: WorkerRegistryConfig,batch_size_bytes: usize,component_options: ComponentOptions,pack_targets: PackTargets,budget: Option<RequestBudget>,- completion_granularity: CompletionGranularity,commit_interval: Duration,partition_budget: BudgetLimits,- polling: Polling,in_flight_limit: ChargeLimit,) -> Self {create_topic(topic, partitions).await;@@ -1037,14 +935,11 @@ impl Harness {batch_size: 50,batch_size_bytes,batch_timeout: Duration::from_millis(100),- max_in_flight_batches: max_in_flight,group_id: "e2e-test".to_string(),debug_recorder: Some(Arc::clone(&debug_recorder)),- completion_granularity,commit_interval,ledger: Arc::clone(&ledger),partition_budget,- polling,in_flight_limit,},handle,@@ -1074,13 +969,10 @@ impl Harness {group_id,ledger,debug_recorder,- max_in_flight,deferred_flush_timeout,pack_targets,budget,- completion_granularity,partition_budget,- polling,in_flight_limit,}}@@ -1144,14 +1036,11 @@ impl Harness {batch_size: 50,batch_size_bytes: 0,batch_timeout: Duration::from_millis(100),- max_in_flight_batches: self.max_in_flight,group_id: "e2e-test".to_string(),debug_recorder: None,- completion_granularity: self.completion_granularity,commit_interval: COMMIT_INTERVAL,ledger: Arc::clone(&self.ledger),partition_budget: self.partition_budget,- polling: self.polling,in_flight_limit: self.in_flight_limit,},handle,@@ -1233,14 +1122,11 @@ impl Harness {batch_size: 50,batch_size_bytes: 0,batch_timeout: Duration::from_millis(100),- max_in_flight_batches: self.max_in_flight,group_id: "e2e-test".to_string(),debug_recorder: None,- completion_granularity: self.completion_granularity,commit_interval: COMMIT_INTERVAL,ledger: Arc::new(TopicOffsetLedger::new()),partition_budget: self.partition_budget,- polling: self.polling,in_flight_limit: self.in_flight_limit,},handle,@@ -1338,7 +1224,6 @@ async fn messages_per_distinct_id_arrive_in_order(#[case] pack_targets: PackTarg&topic,3,2,- 1,Duration::from_secs(60),fast_registry_config(),pack_targets,@@ -1606,13 +1491,10 @@ async fn a_message_that_never_fits_the_budget_lands_without_one() {harness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn byte_bound_caps_batches_below_the_count_bound(#[case] polling: Polling) {+async fn byte_bound_caps_batches_below_the_count_bound() {let topic = format!("e2e-bytecap-{}", Uuid::new_v4());- let harness = Harness::start_byte_capped(&topic, 4096, polling).await;+ let harness = Harness::start_byte_capped(&topic, 4096).await;let producer = make_producer();let payload = vec![b'x'; 2048];@@ -1645,13 +1527,10 @@ async fn byte_bound_caps_batches_below_the_count_bound(#[case] polling: Polling)harness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn message_larger_than_byte_bound_is_still_delivered(#[case] polling: Polling) {+async fn message_larger_than_byte_bound_is_still_delivered() {let topic = format!("e2e-bytecap-oversize-{}", Uuid::new_v4());- let harness = Harness::start_byte_capped(&topic, 4096, polling).await;+ let harness = Harness::start_byte_capped(&topic, 4096).await;let producer = make_producer();produce_raw(@@ -1682,7 +1561,6 @@ async fn failing_worker_triggers_rerouting() {&topic,2,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -1732,7 +1610,6 @@ async fn failed_sends_degrade_passive_health() {&topic,1,1,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -1761,7 +1638,6 @@ async fn draining_worker_takes_no_new_work_and_reroutes_in_order() {&topic,2,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -1846,7 +1722,6 @@ async fn send_failure_mid_flight_replays_to_survivor_in_order() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -1903,7 +1778,6 @@ async fn partial_send_failure_replays_only_the_failed_subbatch() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),one_key_of_four_per_request,@@ -1915,7 +1789,6 @@ async fn partial_send_failure_replays_only_the_failed_subbatch() {guards.push(Some(w.block().await));}- // One poll must carry both keys; at max_in_flight=1 a one-key poll would block the second.let records: Vec<(&str, usize)> = (0..4usize).flat_map(|seq| [("user-1", seq), ("user-2", seq)]).collect();@@ -2221,7 +2094,6 @@ async fn multi_key_send_failure_replays_every_key_in_order(#[case] pack_targets:&topic,3,2,- 1,Duration::from_secs(60),fast_registry_config(),pack_targets,@@ -2284,7 +2156,6 @@ async fn flush_target_failure_re_defers_then_replays_in_order() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -2366,7 +2237,6 @@ async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -2410,7 +2280,7 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work() {drain_timeout: Duration::from_millis(400),..fast_registry_config()};- let harness = Harness::start(&topic, 1, 2, 2, Duration::from_secs(60), registry_config).await;+ let harness = Harness::start(&topic, 1, 2, Duration::from_secs(60), registry_config).await;let producer = make_producer();let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();@@ -2485,7 +2355,6 @@ async fn consumer_crash_before_commit_redelivers_without_loss() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -2529,8 +2398,23 @@ async fn consumer_crash_before_commit_redelivers_without_loss() {harness.stop().await;}-async fn assert_commits_track_the_ledger_frontier(mut harness: Harness) {- let topic = harness.topic.clone();+#[tokio::test]+async fn the_committed_offset_is_the_ledger_frontier() {+ let topic = format!("e2e-ledger-commit-{}", Uuid::new_v4());+ let mut harness = Harness::start_with_limits(+ common::PRODUCTION_PACK_TARGETS,+ &topic,+ 1,+ 1,+ BudgetLimits::new(+ NonZeroU64::new(1_000),+ NonZeroU64::new(UNBOUNDED_BYTES),+ 0.8,+ )+ .expect("a valid budget"),+ ChargeLimit::new(NonZeroU64::new(1_000), NonZeroU64::new(UNBOUNDED_BYTES)),+ )+ .await;let producer = make_producer();for seq in 0..10usize {@@ -2567,41 +2451,14 @@ async fn assert_commits_track_the_ledger_frontier(mut harness: Harness) {}#[tokio::test]-async fn the_committed_offset_is_the_ledger_frontier() {- let topic = format!("e2e-ledger-commit-{}", Uuid::new_v4());- assert_commits_track_the_ledger_frontier(- Harness::start(- &topic,- 1,- 1,- 1,- Duration::from_secs(60),- fast_registry_config(),- )- .await,- )- .await;-}--#[tokio::test]-async fn group_granularity_commits_the_ledger_frontier() {- let topic = format!("e2e-group-commit-{}", Uuid::new_v4());- assert_commits_track_the_ledger_frontier(- Harness::start_group_granularity(common::PRODUCTION_PACK_TARGETS, &topic, 1, 1, 1).await,- )- .await;-}--#[tokio::test]-async fn group_granularity_keeps_a_held_frontier_uncommitted_until_the_stop_commits_it() {+async fn a_held_frontier_stays_uncommitted_until_the_stop_commits_it() {let metrics = metrics();let topic = format!("e2e-group-stop-commit-{}", Uuid::new_v4());- let harness = Harness::start_group_granularity_committing_every(+ let harness = Harness::start_committing_every(common::PRODUCTION_PACK_TARGETS,&topic,1,1,- 1,Duration::from_secs(3600),).await;@@ -2725,11 +2582,18 @@ fn accepted_partition(harness: &Harness, idx: usize) -> i32 {}#[tokio::test]-async fn group_granularity_commits_a_partition_while_another_stalls() {+async fn a_partition_commits_while_another_stalls() {let topic = format!("e2e-group-stall-{}", Uuid::new_v4());// One message per request, or the packer puts both keys on one worker.- let harness =- Harness::start_group_granularity(common::ONE_MESSAGE_PER_REQUEST, &topic, 2, 2, 2).await;+ let harness = Harness::start_with_pack_targets(+ &topic,+ 2,+ 2,+ Duration::from_secs(60),+ fast_registry_config(),+ common::ONE_MESSAGE_PER_REQUEST,+ )+ .await;let mut guards = stall_two_partitions_on_two_workers(&harness, &topic).await;guards[0] = None;@@ -2765,23 +2629,14 @@ async fn group_granularity_commits_a_partition_while_another_stalls() {harness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn a_partition_at_its_budget_pauses_until_a_commit_frees_it(#[case] polling: Polling) {+async fn a_partition_at_its_budget_pauses_until_a_commit_frees_it() {let topic = format!("e2e-partition-budget-{}", Uuid::new_v4());let budget = BudgetLimits::new(NonZeroU64::new(5), NonZeroU64::new(UNBOUNDED_BYTES), 0.5).expect("a valid budget");- let harness = Harness::start_with_partition_budget(- common::PRODUCTION_PACK_TARGETS,- &topic,- 1,- 1,- budget,- polling,- )- .await;+ let harness =+ Harness::start_with_partition_budget(common::PRODUCTION_PACK_TARGETS, &topic, 1, 1, budget)+ .await;let p0 = TopicPartition::new(&topic, 0);let guard = harness.workers[0].block().await;let producer = make_producer();@@ -2815,24 +2670,15 @@ async fn a_partition_at_its_budget_pauses_until_a_commit_frees_it(#[case] pollinharness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn a_partition_at_its_budget_does_not_pause_another(#[case] polling: Polling) {+async fn a_partition_at_its_budget_does_not_pause_another() {let topic = format!("e2e-partition-budget-two-{}", Uuid::new_v4());let budget = BudgetLimits::new(NonZeroU64::new(5), NonZeroU64::new(UNBOUNDED_BYTES), 0.5).expect("a valid budget");// One message per request, or the packer puts both keys on one worker.- let harness = Harness::start_with_partition_budget(- common::ONE_MESSAGE_PER_REQUEST,- &topic,- 2,- 2,- budget,- polling,- )- .await;+ let harness =+ Harness::start_with_partition_budget(common::ONE_MESSAGE_PER_REQUEST, &topic, 2, 2, budget)+ .await;let mut guards = stall_two_partitions_on_two_workers(&harness, &topic).await;guards[0] = None;@@ -2876,32 +2722,10 @@ async fn a_partition_at_its_budget_does_not_pause_another(#[case] polling: Polliharness.stop().await;}-#[tokio::test]-async fn continuous_polling_commits_the_ledger_frontier() {- let topic = format!("e2e-continuous-commit-{}", Uuid::new_v4());- assert_commits_track_the_ledger_frontier(- Harness::start_continuous(- common::PRODUCTION_PACK_TARGETS,- &topic,- 1,- 1,- BudgetLimits::new(- NonZeroU64::new(1_000),- NonZeroU64::new(UNBOUNDED_BYTES),- 0.8,- )- .expect("a valid budget"),- ChargeLimit::new(NonZeroU64::new(1_000), NonZeroU64::new(UNBOUNDED_BYTES)),- )- .await,- )- .await;-}-#[tokio::test]async fn the_in_flight_limit_stops_reading_until_a_commit_frees_room() {let topic = format!("e2e-in-flight-limit-{}", Uuid::new_v4());- let harness = Harness::start_continuous(+ let harness = Harness::start_with_limits(common::PRODUCTION_PACK_TARGETS,&topic,1,@@ -2951,7 +2775,7 @@ async fn the_in_flight_limit_stops_reading_until_a_commit_frees_room() {async fn a_ready_backlog_does_not_keep_the_batcher_from_running() {const BACKLOG: usize = 2_000;let topic = format!("e2e-continuous-backlog-{}", Uuid::new_v4());- let harness = Harness::start_continuous(+ let harness = Harness::start_with_limits(common::PRODUCTION_PACK_TARGETS,&topic,1,@@ -3079,7 +2903,6 @@ async fn lost_ack_after_processing_replays_without_loss() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -3130,15 +2953,8 @@ async fn lost_ack_after_processing_replays_without_loss() {#[tokio::test]async fn poison_batch_fails_safely_without_committing() {let topic = format!("e2e-poison-{}", Uuid::new_v4());- let mut harness = Harness::start(- &topic,- 1,- 2,- 1,- Duration::from_secs(2),- fast_registry_config(),- )- .await;+ let mut harness =+ Harness::start(&topic, 1, 2, Duration::from_secs(2), fast_registry_config()).await;let producer = make_producer();for w in &harness.workers {@@ -3165,15 +2981,8 @@ async fn poison_batch_fails_safely_without_committing() {#[tokio::test]async fn partial_acceptance_fails_the_batch_without_commit() {let topic = format!("e2e-partial-accept-{}", Uuid::new_v4());- let mut harness = Harness::start(- &topic,- 1,- 2,- 1,- Duration::from_secs(2),- fast_registry_config(),- )- .await;+ let mut harness =+ Harness::start(&topic, 1, 2, Duration::from_secs(2), fast_registry_config()).await;let producer = make_producer();for w in &harness.workers {@@ -3204,7 +3013,6 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {&topic,1,2,- 2,Duration::from_secs(60),fast_registry_config(),)@@ -3272,7 +3080,6 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(&topic,2,2,- 3,Duration::from_secs(60),fast_registry_config(),pack_targets,@@ -3337,7 +3144,6 @@ async fn headerless_messages_survive_send_failure_replay() {&topic,1,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -3405,7 +3211,6 @@ async fn non_utf8_payload_is_delivered_not_lost() {&topic,1,1,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -3448,7 +3253,6 @@ async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {&topic,2,2,- 2,Duration::from_secs(60),fast_registry_config(),)@@ -3509,13 +3313,17 @@ async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {harness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn second_consumer_joining_the_group_preserves_all_messages(#[case] polling: Polling) {+async fn second_consumer_joining_the_group_preserves_all_messages() {let topic = format!("e2e-two-consumers-{}", Uuid::new_v4());- let harness = Harness::start_polling(&topic, 2, 2, 1, 0, polling).await;+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;let producer = make_producer();// Hold an uncommitted batch while the first consumer owns both partitions.@@ -3562,14 +3370,17 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] pollinharness.stop().await;}-#[rstest]-#[case::capped(Polling::Capped)]-#[case::continuous(Polling::Continuous)]#[tokio::test]-async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] polling: Polling) {+async fn partition_lost_and_regained_keeps_the_consumer_alive() {let topic = format!("e2e-regain-{}", Uuid::new_v4());- // 128 in-flight polls keep the consumer polling under held batches.- let harness = Harness::start_polling(&topic, 2, 2, 128, 0, polling).await;+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;let producer = make_producer();let partitions = [TopicPartition::new(topic.clone(), 0),@@ -3699,14 +3510,11 @@ async fn fenced_static_member_exits_on_fatal_error() {batch_size: 50,batch_size_bytes: 0,batch_timeout: Duration::from_millis(100),- max_in_flight_batches: 1,group_id: "e2e-test".to_string(),debug_recorder: None,- completion_granularity: CompletionGranularity::Poll,commit_interval: Duration::ZERO,ledger: Arc::new(TopicOffsetLedger::new()),partition_budget: BudgetLimits::unset(),- polling: Polling::Capped,in_flight_limit: ChargeLimit::unset(),},handle,@@ -3805,8 +3613,8 @@ fn spawn_churn(})}-async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool) {- let topic = format!("e2e-churn-{churn:?}-mif{max_in_flight}-{}", Uuid::new_v4());+async fn run_churn_suite(churn: Churn, strict_order: bool) {+ let topic = format!("e2e-churn-{churn:?}-{}", Uuid::new_v4());let dids = 8usize;let per_did = 60usize;let total = dids * per_did;@@ -3816,7 +3624,6 @@ async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool)&topic,partitions,4,- max_in_flight,Duration::from_secs(60),fast_registry_config(),)@@ -3889,38 +3696,26 @@ async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool)}#[tokio::test]-async fn churn_drain_preserves_order_at_max_in_flight_2() {- run_churn_suite(Churn::Drain, 2, true).await;-}--#[tokio::test]-async fn churn_drain_preserves_order_at_max_in_flight_3() {- run_churn_suite(Churn::Drain, 3, true).await;+async fn churn_drain_preserves_order() {+ run_churn_suite(Churn::Drain, true).await;}#[tokio::test]-async fn churn_send_failures_are_exactly_once_at_max_in_flight_3() {- run_churn_suite(Churn::Fail, 3, false).await;+async fn churn_send_failures_are_exactly_once() {+ run_churn_suite(Churn::Fail, false).await;}#[tokio::test]-async fn churn_mixed_drain_and_failures_are_exactly_once_at_max_in_flight_3() {- run_churn_suite(Churn::Mixed, 3, false).await;+async fn churn_mixed_drain_and_failures_are_exactly_once() {+ run_churn_suite(Churn::Mixed, false).await;}#[tokio::test]async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {let topic = format!("e2e-flap-{}", Uuid::new_v4());// Short flush timeout so the bound is observable quickly; concurrency > 1.- let mut harness = Harness::start(- &topic,- 1,- 2,- 2,- Duration::from_secs(2),- fast_registry_config(),- )- .await;+ let mut harness =+ Harness::start(&topic, 1, 2, Duration::from_secs(2), fast_registry_config()).await;let producer = make_producer();let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();@@ -3968,7 +3763,6 @@ async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {&topic,2,2,- 1,Duration::from_secs(60),fast_registry_config(),)@@ -4017,7 +3811,6 @@ async fn same_key_across_partitions_completes_and_commits() {&topic,2,1,- 1,Duration::from_secs(60),fast_registry_config(),)