: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): resend only the unfinished part of a request (#115960)
José Sequeirad2576332b520
diff --git a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.tsindex fa29480e3b6d..c9d57314ca63 100644--- a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts+++ b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts@@ -309,8 +309,8 @@ export type SubBatchAck = Message<'ingestion.worker.v1.SubBatchAck'> & {/*** Messages with work left when the budget ran out. Set only on PARTIAL,* never empty. Every other message is done, as on OK. The listed messages- * need not be the last of their routing key, because a worker may process- * one key's messages in independent groups.+ * are the last of their distinct id, not of their routing key: a message+ * is done only once every earlier message of its distinct id is done.** @generated from field: repeated ingestion.worker.v1.MessageRef unfinished = 5;*/diff --git a/proto/ingestion/worker/v1/worker.proto b/proto/ingestion/worker/v1/worker.protoindex 66e00289877b..0caed14e3a62 100644--- a/proto/ingestion/worker/v1/worker.proto+++ b/proto/ingestion/worker/v1/worker.proto@@ -130,7 +130,7 @@ message SubBatchAck {string error = 4;// Messages with work left when the budget ran out. Set only on PARTIAL,// never empty. Every other message is done, as on OK. The listed messages- // need not be the last of their routing key, because a worker may process- // one key's messages in independent groups.+ // are the last of their distinct id, not of their routing key: a message+ // is done only once every earlier message of its distinct id is done.repeated MessageRef unfinished = 5;}diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex 49bf86c88f93..b168fe3ff2c8 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, monotonic, non-empty per partition | `ingestion_consumer_commit_violations_total{kind=gap\|out_of_order\|overlap\|empty}` | `ingestion_consumer_commits_checked_total`, `ingestion_consumer_committed_offset{topic,partition}` |+| Commits are contiguous, monotonic, non-empty per partition, and cover only completed offsets | `ingestion_consumer_commit_violations_total{kind=gap\|out_of_order\|overlap\|empty\|uncredited}` | `ingestion_consumer_commits_checked_total`, `ingestion_consumer_committed_offset{topic,partition}` || Async commits actually succeed | `ingestion_consumer_commit_confirmation_lag{topic,partition}` persistently > 0 | `ingestion_consumer_broker_committed_offset{topic,partition}`, `ingestion_consumer_last_successful_commit_timestamp_seconds`, `ingestion_consumer_commit_monitor_errors_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` |@@ -23,7 +23,8 @@ Alerts should gate on `ingestion_consumer_offset_commits_total > 0` — an idleBoth sides default to enabled and have kill switches: `CONSUMER_ORDER_SENTINEL_ENABLED` here, `INGESTION_API_FEED_ORDER_SENTINEL_ENABLED` (plus `INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS`) on the worker.The rebalance metrics from the consumer context stay on regardless, and the `consumer_id`/`replay` request fields are always stamped so either side can be toggled independently.The worker-side check lives in `nodejs/src/ingestion/api/feed-order-sentinel.ts`, fed by the `consumer_id` (process incarnation) and `replay` fields the transport stamps on every sub-batch.-It measures the invariant at its end point: the worker's grouping stage processes each key strictly in feed order, so "fed in offset order per key" is "processed in order per key".+It measures the invariant at its end point: the worker groups each key's messages by distinct id and processes each group in feed order, so "fed in offset order per key" is "processed in order per distinct id".+A partial ack keeps that, because the worker leaves only the last messages of a distinct id unfinished and the consumer resends them in order.Rebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.Null-key messages (e.g. overflow rerouting) are excluded from both checks: the producer deliberately forfeits per-key order for them, and the consumer routes each one individually rather than pinning it, so there is no invariant to check on either side.@@ -56,6 +57,8 @@ Under `key_table`:- The packer builds a request only for a free worker slot, from ready keys up to a target size. Keys stay unclaimed until then, so a key's run keeps growing while every slot is busy, up to the run cap. A key's backlog past the run cap leaves in consecutive requests, one in flight at a time. The run cap is the target unless `INGESTION_RUN_CAP_*` sets it apart. A request never mixes assignment epochs or fresh and replayed messages.- A request is placed on a worker when it is sent, against the load at that moment. Each worker takes at most `INGESTION_WORKER_CONCURRENT_BATCHES` requests at a time.- A failed send returns its messages to the front of their keys' queues. They retry through the packer as replay after the retry delay.+- A partial ack completes the messages the worker finished. Its unfinished messages return to the front of their keys' queues and go out again at once as replay. They need not be the last messages of their key.+- A key resends without a budget once `INGESTION_REQUEST_BUDGET_ATTEMPTS` settles have left its messages unfinished since it last finished a run, or at once when its request finished nothing, because a budgeted retry would wait out the same budget again. So a message that never fits the budget still finishes. A failed request neither counts nor resets the count. The resend rides in a request that holds only such keys, ahead of budgeted replays.- A revoke drops the pending messages of the revoked partitions, because the new owner replays them.- Pending work with nothing in flight and nothing accepted for `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` fails the consumer, which restarts and replays.@@ -65,7 +68,9 @@ Under `key_table`:| `INGESTION_PACK_TARGET_BYTES` | `0` | Send a request to a free slot once this many key-plus-value bytes are ready. Unless a run cap is set, it also caps one key's run. `0` disables the byte target and the cap, and needs an event target. || `INGESTION_RUN_CAP_EVENTS` | `0` | The most events one key's run holds, which is the most of its backlog a key sends per round trip. With both run caps at `0`, the pack targets cap runs. When either is set, the run caps replace them, and a `0` cap leaves that dimension uncapped. || `INGESTION_RUN_CAP_BYTES` | `0` | One key's run stops growing once it holds this many key-plus-value bytes. Works with `INGESTION_RUN_CAP_EVENTS`. |-| `INGESTION_PACK_LATENCY_BUDGET_MS` | `0` | Once a slot is free, wait this long for ready events below the target to reach it. `0` waits for nothing: each free slot gets what is ready, packed up to the target. Replays never wait, because they already waited out a retry delay. |+| `INGESTION_PACK_LATENCY_BUDGET_MS` | `0` | Once a slot is free, wait this long for ready events below the target to reach it. `0` waits for nothing: each free slot gets what is ready, packed up to the target. Replays never wait, because they already waited out a retry delay or a worker's time budget. |+| `INGESTION_REQUEST_SOFT_BUDGET_MS` | `0` | How long a worker may spend on one request before it stops starting work and acks what finished as partial. The rest goes out again at once. `0` sends no budget. A request split into several frames goes without one. Startup fails if it is below `100` or above `2147483647`, if it is set under `pin_stash`, if it times `INGESTION_WORKER_CONCURRENT_BATCHES` reaches `INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS`, or if it plus `INGESTION_PACK_LATENCY_BUDGET_MS` reaches `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`. |+| `INGESTION_REQUEST_BUDGET_ATTEMPTS` | `3` | How many budgeted attempts may leave a key's messages unfinished, since the key last finished a run, before it resends without a budget. At least 1, or startup fails. Only read when `INGESTION_REQUEST_SOFT_BUDGET_MS` is set. || `INGESTION_PARKED_RETRY_INTERVAL_MS` | `200` | The delay before a failed send retries, and how often a request with no routable worker tries again. |Metrics:@@ -73,6 +78,8 @@ Metrics:- `ingestion_consumer_request_events` and `ingestion_consumer_request_bytes` record each request as sent. They show whether requests reach the pack target.- `ingestion_consumer_request_queue_wait_seconds{kind=fresh|replay}` records how long a request's oldest message waited, including the pack budget.- `ingestion_consumer_batcher_packed_requests_total{reason=target|deadline|replay|shutdown}` counts why the packer built each request: at the target, at the budget deadline, as a replay, or at shutdown.+- `ingestion_consumer_request_budget_partials_total` counts partial acks, and `ingestion_consumer_request_budget_unfinished_messages_total` counts the messages they left unfinished.+- `ingestion_consumer_request_budget_escalations_total` counts keys that resend without a budget, after their budgeted attempts or after a partial ack that finished nothing. A steady rate means the budget is too tight for the lane, or that the workers are saturated: a frame that waits out its budget for a pipeline slot comes back as a partial ack with nothing finished, and the worker counts it in `ingestion_api_grpc_admission_expired_total`.- The `ingestion_consumer_batcher_*` gauges report keys, queued messages and bytes, claimed and waiting keys, unplaced work, and in-flight requests.## Debug APIdiff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.mdindex 00e70dfda785..8f6742d142a3 100644--- a/rust/ingestion-consumer/docs/driver-model-plan.md+++ b/rust/ingestion-consumer/docs/driver-model-plan.md@@ -430,25 +430,27 @@ Exit criterion: partial acks resolve and their remainders redeliver in order, ze### 14. Add partial settlement and the request time budget (implement)-**Task:** Teach the transport the `PARTIAL` ack and the scheduler a partial settlement. Ship with no budget set: absent means unlimited, today's behavior.+**Task:** Teach the transport the `PARTIAL` ack and the batcher state machine a partial settlement. Ship with no budget set: absent means unlimited, today's behavior.**Goal:** Partial redelivery exists as one settlement arm, not a new path.-- The stream runner parses `PARTIAL` and resolves the send with the `unfinished` message list, instead of fencing it as busy.-- The scheduler's partial arm is the failure arm plus completions: complete every message not in `unfinished` as group completions, return the unfinished messages to the front of their keys' queues in offset order, and keep the key blocked until the redelivery settles.-- Send the remainder with `replay` set. The worker's feed-order sentinel saw its offsets in the first send, so an unmarked redelivery counts as a key-order violation.-- The prototype against the old machinery ([#91480](https://github.com/PostHog/posthog/pull/91480)) showed the cost of doing this earlier: concurrent polls and per-batch accounting push partial handling through the deferral paths. Behind the key table it is one `on_settled` arm.-- Stamp `soft_budget_ms` on each request from config. Unset sends no budget.+- The transport parses `PARTIAL` and resolves the send with the accepted count and the `unfinished` messages, named by partition and offset, instead of fencing it as busy. An ack that does not match the request fails the stream.+- `BatcherStateMachine::on_request_partial` completes exactly the accepted set and returns each key's unfinished messages to the front of its queue, sent again at once as replay. The unfinished messages need not be the last of their key, because the worker groups by distinct id inside one Kafka key.+- The order sentinel's ACK mark stops below a run's lowest unfinished offset, so the resend is legal. The consumer refuses to commit a poll offset that no completion covered (`commit_violations_total{kind="uncredited"}`).+- A key resends without a budget once `INGESTION_REQUEST_BUDGET_ATTEMPTS` settles left its messages unfinished since it last finished a run, or at once when its request finished nothing, so a message that never fits the budget still lands. That request carries only such keys and goes ahead of budgeted replays.+- The prototype against the old machinery ([#91480](https://github.com/PostHog/posthog/pull/91480)) showed the cost of doing this earlier: concurrent polls and per-batch accounting push partial handling through the deferral paths. Behind the key table it is one settlement arm.+- Stamp `soft_budget_ms` from config on each key-table request that fits one frame. Unset sends no budget, and `pin_stash` rejects one.**Interfaces:**-- Modify the ack handling in `grpc_transport.rs`: parse `PARTIAL`; resolve with the unfinished partitions and offsets.-- Modify the settlement types and `KeyTableScheduler::on_settled`: add the partial arm.-- Modify `Config`: add the soft budget per request, default unset.+- Modify the ack handling in `grpc_transport.rs`: parse `PARTIAL`; resolve with the accepted count and the unfinished messages.+- Modify `BatcherStateMachine` and `KeyQueues`: add the partial arm and the per-key escalation count.+- Modify `Config`: add `INGESTION_REQUEST_SOFT_BUDGET_MS` (default unset) and `INGESTION_REQUEST_BUDGET_ATTEMPTS` (default 3), bounded at startup against the ack and stall timeouts.**Metrics:**- Add `ingestion_consumer_request_budget_partials_total` (counter) and `ingestion_consumer_request_budget_unfinished_messages_total` (counter). The names match the wire: a `PARTIAL` ack with an `unfinished` message list.+- Add `ingestion_consumer_request_budget_escalations_total` (counter), one per key that resends without a budget. A charts warning alert fires on a sustained rate per lane.### 15. Set the request time budgets (switchover)@@ -457,7 +459,7 @@ Exit criterion: partial acks resolve and their remainders redeliver in order, ze**Goal:** A slow request costs a partial redelivery, not a fenced stream and a full replay.- A charts values PR sets the budget lane by lane. The generous stage is the cycle's verify.-- Watch the partial and unfinished counters, the key-order sentinel, and stream teardowns.+- Watch the partial, unfinished and escalation counters, the key-order sentinel, and stream teardowns.- Rollback is unsetting the values.**Interfaces:**diff --git a/rust/ingestion-consumer/src/batcher/driver.rs b/rust/ingestion-consumer/src/batcher/driver.rsindex 59aa61ce1b46..09d929d58657 100644--- a/rust/ingestion-consumer/src/batcher/driver.rs+++ b/rust/ingestion-consumer/src/batcher/driver.rs@@ -18,9 +18,9 @@ use super::key_queues::KeyRun;use super::state_machine::{BatcherStateMachine, Effects, FailureCause, SendRequest};use super::worker_pool::WorkerPoolSource;use super::{make_batch_id, BatcherOutputs};-use crate::grpc_transport::GrpcTransport;+use crate::grpc_transport::{GrpcTransport, SendOptions};use crate::order_sentinel::{KeyOrderSentinel, SendKind, SentinelBatch};-use crate::transport::SendError;+use crate::transport::{SendError, SendOutcome};use crate::types::{Accumulator, SerializedKafkaMessage};use crate::worker_registry::WorkerId;@@ -57,8 +57,8 @@ pub(super) trait RequestSender: Send + Sync + 'static {&self,worker: &WorkerId,messages: Vec<SerializedKafkaMessage>,- replay: bool,- ) -> BoxFuture<'static, Result<u32, SendError>>;+ options: SendOptions,+ ) -> BoxFuture<'static, Result<SendOutcome, SendError>>;}pub(super) trait Workers: Send + 'static {@@ -79,9 +79,9 @@ impl RequestSender for GrpcTransport {&self,worker: &WorkerId,messages: Vec<SerializedKafkaMessage>,- replay: bool,- ) -> BoxFuture<'static, Result<u32, SendError>> {- self.begin_send(worker, &make_batch_id(), messages, replay)+ options: SendOptions,+ ) -> BoxFuture<'static, Result<SendOutcome, SendError>> {+ self.begin_send_with(worker, &make_batch_id(), messages, options).wait().boxed()}@@ -104,7 +104,7 @@ impl Workers for WorkerPoolSource {}}-type Response = BoxFuture<'static, (RequestId, Result<u32, SendError>)>;+type Response = BoxFuture<'static, (RequestId, Result<SendOutcome, SendError>)>;struct BatcherTask<S, W> {inputs: mpsc::UnboundedReceiver<Input>,@@ -120,7 +120,7 @@ struct BatcherTask<S, W> {enum Event {Input(Input),- Response(RequestId, Result<u32, SendError>),+ Response(RequestId, Result<SendOutcome, SendError>),Wakeup,}@@ -261,9 +261,22 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {state.on_partitions_revoked(now, &partitions)}Event::Input(Input::Shutdown) => state.on_shutdown(now, &self.workers.candidates()),- Event::Response(request, Ok(accepted)) => {+ Event::Response(request, Ok(SendOutcome::Accepted(accepted))) => {state.on_request_succeeded(now, &self.workers.candidates(), request, accepted)}+ Event::Response(+ request,+ Ok(SendOutcome::Partial {+ accepted,+ unfinished,+ }),+ ) => state.on_request_partial(+ now,+ &self.workers.candidates(),+ request,+ accepted,+ unfinished,+ ),Event::Response(request, Err(failure)) => {// Backpressure is transient, not a worker fault.let cause = if failure.error.is_backpressure() {@@ -366,7 +379,11 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {sentinel.note_sent(&run.routing_key, &run.messages, kind);messages.extend(run.messages);}- let response = self.sender.send(&send.worker, messages, send.class.replay);+ let options = SendOptions {+ replay: send.class.replay,+ soft_budget: send.soft_budget,+ };+ let response = self.sender.send(&send.worker, messages, options);let request = send.request;self.responses.push(async move { (request, response.await) }.boxed());@@ -382,7 +399,7 @@ async fn sleep_until(wakeup: Option<Instant>) {#[cfg(test)]mod tests {- use std::num::NonZeroUsize;+ use std::num::{NonZeroU32, NonZeroUsize};use std::time::Duration;use tokio::sync::oneshot;@@ -390,6 +407,7 @@ mod tests {use super::*;use crate::batcher::packer::{PackTargets, Packer};use crate::batcher::retry_policy::RetryPolicy;+ use crate::batcher::state_machine::RequestBudget;use crate::batcher::test_support::{message, offsets};use crate::batcher::worker_assigner::WorkerAssigner;use crate::routing::{Router, RoutingStrategy};@@ -404,8 +422,9 @@ mod tests {worker: WorkerId,offsets: Vec<i64>,replay: bool,+ soft_budget: Option<Duration>,fence_released: Option<bool>,- reply: oneshot::Sender<Result<u32, SendError>>,+ reply: oneshot::Sender<Result<SendOutcome, SendError>>,}struct FakeSender {@@ -423,8 +442,8 @@ mod tests {&self,worker: &WorkerId,messages: Vec<SerializedKafkaMessage>,- replay: bool,- ) -> BoxFuture<'static, Result<u32, SendError>> {+ options: SendOptions,+ ) -> BoxFuture<'static, Result<SendOutcome, SendError>> {let fence_released = self.fence.lock()@@ -435,7 +454,8 @@ mod tests {self.sent.lock().unwrap().push(Sent {worker: worker.clone(),offsets: offsets(&messages),- replay,+ replay: options.replay,+ soft_budget: options.soft_budget,fence_released,reply,});@@ -480,6 +500,14 @@ mod tests {impl Harness {fn new(workers: &[&str], max_requests_per_worker: usize) -> Self {+ Self::budgeted(workers, max_requests_per_worker, None)+ }++ fn budgeted(+ workers: &[&str],+ max_requests_per_worker: usize,+ budget: Option<RequestBudget>,+ ) -> Self {let assigner =WorkerAssigner::new(Router::new(RoutingStrategy::P2c), max_requests_per_worker).expect("valid request cap");@@ -497,7 +525,8 @@ mod tests {STALL,tokio::time::Instant::now().into_std(),)- .expect("valid stall timeout");+ .expect("valid stall timeout")+ .with_request_budget(budget);let fake_workers = FakeWorkers::default();fake_workers.set_candidates(workers);let sender = Arc::new(FakeSender {@@ -592,13 +621,53 @@ mod tests {assert!(!sent[0].replay);let send = sent.into_iter().next().unwrap();- send.reply.send(Ok(1)).unwrap();+ send.reply.send(Ok(SendOutcome::Accepted(1))).unwrap();settle().await;assert_eq!(h.completed_offsets(), vec![1]);assert_eq!(h.workers.outcomes(), vec![(WorkerId::from("w"), false)]);assert_eq!(h.workers.idle(), vec![WorkerId::from("w")]);}+ #[tokio::test(start_paused = true)]+ async fn a_partial_response_resends_its_unfinished_messages_at_once_as_replay() {+ let budget = Duration::from_millis(250);+ let mut h = Harness::budgeted(+ &["w"],+ 4,+ Some(RequestBudget {+ soft_budget: budget,+ attempts: NonZeroU32::new(3).expect("nonzero attempts"),+ }),+ );+ h.submit(vec![run("a", &[1])]);+ settle().await;+ let send = h.take_sent().pop().unwrap();+ assert_eq!(send.soft_budget, Some(budget));++ send.reply+ .send(Ok(SendOutcome::Partial {+ accepted: 0,+ unfinished: vec![message("a", 0, 1)],+ }))+ .unwrap();+ settle().await;+ assert!(h.completed_offsets().is_empty());+ assert_eq!(h.workers.outcomes(), vec![(WorkerId::from("w"), false)]);+ let resend = h.take_sent();+ assert_eq!(resend.len(), 1, "the resend waits for no retry delay");+ assert!(resend[0].replay);+ assert_eq!(resend[0].offsets, vec![1]);+ assert_eq!(+ resend[0].soft_budget, None,+ "a request that finished nothing resends without a budget"+ );++ let resend = resend.into_iter().next().unwrap();+ resend.reply.send(Ok(SendOutcome::Accepted(1))).unwrap();+ settle().await;+ assert_eq!(h.completed_offsets(), vec![1]);+ }+#[tokio::test(start_paused = true)]async fn a_busy_send_replays_after_the_busy_delay() {let h = Harness::new(&["w"], 4);@@ -669,7 +738,7 @@ mod tests {settle().await;let send = h.take_sent().pop().unwrap();- send.reply.send(Ok(1)).unwrap();+ send.reply.send(Ok(SendOutcome::Accepted(1))).unwrap();h.driver.revoke_sender().purge_revoked(&[("events".to_string(), 0)]);@@ -720,13 +789,13 @@ mod tests {let accepted = |send: &Sent| send.offsets.len() as u32;let first = sent.remove(0);let count = accepted(&first);- first.reply.send(Ok(count)).unwrap();+ first.reply.send(Ok(SendOutcome::Accepted(count))).unwrap();settle().await;assert!(!load.busy_workers.lock().unwrap().is_empty());let last = sent.remove(0);let count = accepted(&last);- last.reply.send(Ok(count)).unwrap();+ last.reply.send(Ok(SendOutcome::Accepted(count))).unwrap();settle().await;assert!(load.busy_workers.lock().unwrap().is_empty());assert_eq!(load.in_flight_messages.load(Ordering::Relaxed), 0);@@ -738,7 +807,7 @@ mod tests {h.submit(vec![run("a", &[1])]);settle().await;let send = h.take_sent().pop().unwrap();- send.reply.send(Ok(2)).unwrap();+ send.reply.send(Ok(SendOutcome::Accepted(2))).unwrap();settle().await;assert!(h.outputs.errors.try_recv().is_ok());}diff --git a/rust/ingestion-consumer/src/batcher/in_flight.rs b/rust/ingestion-consumer/src/batcher/in_flight.rsindex 2917f4daeb1f..9a4ab233fcd5 100644--- a/rust/ingestion-consumer/src/batcher/in_flight.rs+++ b/rust/ingestion-consumer/src/batcher/in_flight.rs@@ -29,11 +29,35 @@ impl SentMessage {}}+/// The partition the key's order watermark tracks.+fn first_keyed_partition(messages: &[SentMessage]) -> Option<i32> {+ messages+ .iter()+ .find(|message| message.keyed)+ .map(|message| message.partition)+}+pub struct SentRun {pub routing_key: Arc<str>,pub messages: Vec<SentMessage>,}+impl SentRun {+ pub fn first_keyed_partition(&self) -> Option<i32> {+ first_keyed_partition(&self.messages)+ }+}++/// One run's share of a partial ack.+pub struct PartialRun {+ pub routing_key: Arc<str>,+ /// Taken from the whole run, because the first keyed message may itself+ /// be unfinished.+ pub first_keyed_partition: Option<i32>,+ pub accepted: Vec<SentMessage>,+ pub unfinished: Vec<SerializedKafkaMessage>,+}+pub struct InFlightRequest {pub worker: WorkerId,pub class: RequestClass,@@ -118,16 +142,67 @@ impl InFlightRequest {}).collect())}++ /// The transport hands back the unfinished messages in send order. They+ /// need not be the last messages of a run, because a worker may process+ /// one key's messages in independent groups.+ pub fn partially_accepted(+ self,+ accepted_count: u32,+ unfinished: Vec<SerializedKafkaMessage>,+ ) -> Result<Vec<PartialRun>, String> {+ if unfinished.is_empty() || accepted_count as usize + unfinished.len() != self.message_count+ {+ return Err(format!(+ "partial ack accepted {accepted_count} and left {} of {} messages unfinished",+ unfinished.len(),+ self.message_count+ ));+ }+ let mut unfinished = unfinished.into_iter().peekable();+ let partial_runs = self+ .runs+ .into_iter()+ .map(|run| {+ let mut partial_run = PartialRun {+ routing_key: run.routing_key,+ first_keyed_partition: first_keyed_partition(&run.messages),+ accepted: Vec::new(),+ unfinished: Vec::new(),+ };+ for sent in run.messages {+ let next = unfinished.next_if(|message| {+ message.partition == sent.partition && message.offset == sent.offset+ });+ match next {+ Some(message) => partial_run.unfinished.push(message),+ None => partial_run.accepted.push(sent),+ }+ }+ partial_run+ })+ .collect();+ if let Some(message) = unfinished.next() {+ return Err(format!(+ "partial ack lists {}:{} as unfinished, which the request does not carry at that point",+ message.partition, message.offset+ ));+ }+ Ok(partial_runs)+ }}#[cfg(test)]mod tests {+ use rstest::rstest;+use super::*;use crate::batcher::test_support::{message, offsets};const FRESH: RequestClass = RequestClass {assignment_epoch: 0,replay: false,+ unbudgeted: false,};fn run(key: &str, offsets: &[i64]) -> KeyRun {@@ -171,4 +246,56 @@ mod tests {fn a_hand_back_missing_messages_is_an_error() {assert!(request().hand_back(vec![message("a", 0, 1)]).is_err());}++ #[test]+ fn a_partial_sorts_each_run_into_accepted_and_unfinished_in_send_order() {+ let partial_runs = request()+ .partially_accepted(2, vec![message("a", 0, 2), message("b", 0, 10)])+ .expect("matches the request");+ let shapes: Vec<_> = partial_runs+ .iter()+ .map(|run| {+ (+ &*run.routing_key,+ run.accepted+ .iter()+ .map(|sent| sent.offset)+ .collect::<Vec<i64>>(),+ offsets(&run.unfinished),+ )+ })+ .collect();+ assert_eq!(+ shapes,+ vec![("a", vec![1, 3], vec![2]), ("b", vec![], vec![10])]+ );+ }++ #[test]+ fn a_partial_matches_a_message_the_request_carries_twice_by_occurrence() {+ let mut requests = InFlightRequests::new();+ let id = requests.register(WorkerId::from("w"), FRESH, &[run("a", &[1, 2, 1])]);+ let request = requests.take(id).expect("registered");+ let partial_runs = request+ .partially_accepted(2, vec![message("a", 0, 1)])+ .expect("matches the request");+ let run = &partial_runs[0];+ let accepted: Vec<i64> = run.accepted.iter().map(|sent| sent.offset).collect();+ assert_eq!((accepted, offsets(&run.unfinished)), (vec![2, 1], vec![1]));+ }++ #[rstest]+ #[case::empty(4, vec![])]+ #[case::not_in_the_request(3, vec![message("a", 0, 7)])]+ #[case::duplicate(2, vec![message("a", 0, 2), message("a", 0, 2)])]+ #[case::out_of_send_order(2, vec![message("a", 0, 3), message("a", 0, 2)])]+ #[case::count_mismatch(1, vec![message("a", 0, 2)])]+ fn a_partial_that_does_not_match_the_request_is_an_error(+ #[case] accepted_count: u32,+ #[case] unfinished: Vec<SerializedKafkaMessage>,+ ) {+ assert!(request()+ .partially_accepted(accepted_count, unfinished)+ .is_err());+ }}diff --git a/rust/ingestion-consumer/src/batcher/key_queues.rs b/rust/ingestion-consumer/src/batcher/key_queues.rsindex 412481a40ca1..e317fc7686ec 100644--- a/rust/ingestion-consumer/src/batcher/key_queues.rs+++ b/rust/ingestion-consumer/src/batcher/key_queues.rs@@ -2,7 +2,7 @@//! out, and its later messages wait until that run settles.use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};-use std::num::NonZeroUsize;+use std::num::{NonZeroU32, NonZeroUsize};use std::sync::Arc;use std::time::Instant;@@ -103,6 +103,26 @@ pub struct UnclaimedSettle {pub routing_key: String,}+pub enum Settlement {+ Done,+ Unfinished(Vec<SerializedKafkaMessage>),+ /// The request finished nothing, so a budgeted retry would wait out the+ /// same budget again. The key resends without one at once.+ Bounced(Vec<SerializedKafkaMessage>),+ Failed {+ messages: Vec<SerializedKafkaMessage>,+ retry_at: Instant,+ },+}++#[derive(Debug, Default, PartialEq, Eq)]+pub struct Settled {+ pub evicted: bool,+ /// The key's run went out with a budget and its resend goes without one.+ /// True on one settle per escalation, so a counter of it counts keys.+ pub escalated: bool,+}+struct Segment {class: RequestClass,queued_at: Instant,@@ -121,6 +141,7 @@ impl Segment {struct Claim {assignment_epoch: u64,+ unbudgeted: bool,/// Requeued messages of these partitions drop; the new owner replays them.revoked: Vec<(String, i32)>,}@@ -130,6 +151,10 @@ struct KeyState {segments: VecDeque<Segment>,claim: Option<Claim>,retry_at: Option<Instant>,+ /// Settles that left messages unfinished since the key last finished a+ /// run; a bounce counts as all of them. A failure leaves it, because a+ /// failed request says nothing about the budget.+ unfinished_attempts: u32,}impl KeyState {@@ -185,6 +210,7 @@ impl KeyState {let segment = self.segments.pop_front().expect("a ready key has messages");self.claim = Some(Claim {assignment_epoch: segment.class.assignment_epoch,+ unbudgeted: segment.class.unbudgeted,revoked: Vec::new(),});segment@@ -247,8 +273,10 @@ impl ReadySizes {}}-fn send_order(class: &RequestClass) -> (bool, u64) {- (!class.replay, class.assignment_epoch)+/// An unbudgeted replay goes ahead of a budgeted one of its epoch, because+/// it is the request that surely finishes its messages.+fn send_order(class: &RequestClass) -> (bool, u64, bool) {+ (!class.replay, class.assignment_epoch, !class.unbudgeted)}#[derive(Default)]@@ -260,6 +288,7 @@ pub struct KeyQueues {waiting_keys: BTreeSet<(Instant, Arc<str>)>,ready_sizes: ReadySizes,run_cap: RunCap,+ budget_attempts: Option<NonZeroU32>,queued_messages: usize,queued_bytes: usize,claimed_keys: usize,@@ -273,6 +302,13 @@ impl KeyQueues {}}+ pub fn with_budget_attempts(self, budget_attempts: Option<NonZeroU32>) -> Self {+ Self {+ budget_attempts,+ ..self+ }+ }+pub fn key_count(&self) -> usize {self.keys.len()}@@ -321,6 +357,7 @@ impl KeyQueues {let class = RequestClass {assignment_epoch,replay: false,+ unbudgeted: false,};let state = match self.keys.get_mut(&*routing_key) {Some(state) => state,@@ -413,10 +450,9 @@ impl KeyQueues {pub fn settle(&mut self,routing_key: &Arc<str>,- mut requeued: Vec<SerializedKafkaMessage>,- retry_at: Option<Instant>,+ settlement: Settlement,now: Instant,- ) -> Result<bool, UnclaimedSettle> {+ ) -> Result<Settled, UnclaimedSettle> {let unclaimed = || UnclaimedSettle {routing_key: routing_key.to_string(),};@@ -428,6 +464,28 @@ impl KeyQueues {};self.claimed_keys = self.claimed_keys.saturating_sub(1);+ let (mut requeued, retry_at) = match settlement {+ Settlement::Done => {+ state.unfinished_attempts = 0;+ (Vec::new(), None)+ }+ Settlement::Unfinished(messages) => {+ state.unfinished_attempts = state.unfinished_attempts.saturating_add(1);+ (messages, None)+ }+ Settlement::Bounced(messages) => {+ if let Some(attempts) = self.budget_attempts {+ state.unfinished_attempts = state.unfinished_attempts.max(attempts.get());+ }+ (messages, None)+ }+ Settlement::Failed { messages, retry_at } => (messages, Some(retry_at)),+ };+ let unbudgeted = self+ .budget_attempts+ .is_some_and(|attempts| state.unfinished_attempts >= attempts.get());+ let mut settled = Settled::default();+if !claim.revoked.is_empty() {requeued.retain(|message| {!claim.revoked.iter().any(|(topic, partition)| {@@ -436,6 +494,7 @@ impl KeyQueues {});}if !requeued.is_empty() {+ settled.escalated = unbudgeted && !claim.unbudgeted;let bytes = payload_bytes(&requeued);self.queued_messages += requeued.len();self.queued_bytes += bytes;@@ -445,6 +504,7 @@ impl KeyQueues {class: RequestClass {assignment_epoch: claim.assignment_epoch,replay: true,+ unbudgeted,},queued_at: now,bytes,@@ -459,12 +519,13 @@ impl KeyQueues {self.ready_sizes.replace(None, state.ready_size());if state.is_idle() {self.keys.remove(&**routing_key);- return Ok(true);+ settled.evicted = true;+ return Ok(settled);}if state.is_ready() {self.ready_keys.push_back(Arc::clone(routing_key));}- Ok(false)+ Ok(settled)}pub fn purge(&mut self, revoked: &[(String, i32)]) -> Vec<Arc<str>> {@@ -546,7 +607,11 @@ impl KeyQueues {self.push(Arc::clone(&routing_key), assignment_epoch, messages, now);self.ready_keys.retain(|key| *key != routing_key);let sent = self.claim(Arc::clone(&routing_key));- self.settle(&routing_key, sent.run.messages, None, now)+ let settlement = Settlement::Failed {+ messages: sent.run.messages,+ retry_at: now,+ };+ self.settle(&routing_key, settlement, now).expect("a claimed key");}}@@ -557,6 +622,8 @@ mod tests {use common_kafka_consumer::{GroupMessage, Partition};+ use rstest::rstest;+use super::*;use crate::batcher::test_support::{message, offsets};@@ -567,8 +634,18 @@ mod tests {const FRESH: RequestClass = RequestClass {assignment_epoch: 0,replay: false,+ unbudgeted: false,};+ const EVICTED: Settled = Settled {+ evicted: true,+ escalated: false,+ };++ fn failure(messages: Vec<SerializedKafkaMessage>, retry_at: Instant) -> Settlement {+ Settlement::Failed { messages, retry_at }+ }+fn take_all(queues: &mut KeyQueues, now: Instant) -> Vec<ReadyRun> {queues.promote_due(now);let mut runs = Vec::new();@@ -611,12 +688,15 @@ mod tests {"one run per key is out");- assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(false));+ assert_eq!(+ queues.settle(&key("a"), Settlement::Done, now),+ Ok(Settled::default())+ );assert_eq!(claimed(&take_all(&mut queues, now)),vec![("a", vec![2, 3], false)]);- assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(true));+ assert_eq!(queues.settle(&key("a"), Settlement::Done, now), Ok(EVICTED));assert_eq!(queues.key_count(), 0);}@@ -656,8 +736,8 @@ mod tests {let requeued = vec![message("a", 0, 2)];assert_eq!(- queues.settle(&key("a"), requeued, Some(retry_at), now),- Ok(false)+ queues.settle(&key("a"), failure(requeued, retry_at), now),+ Ok(Settled::default()));assert!(take_all(&mut queues, now).is_empty(),@@ -670,7 +750,7 @@ mod tests {vec![("a", vec![2], true)]);queues- .settle(&key("a"), Vec::new(), None, retry_at)+ .settle(&key("a"), Settlement::Done, retry_at).expect("claimed");assert_eq!(claimed(&take_all(&mut queues, retry_at)),@@ -711,7 +791,7 @@ mod tests {let requeued = vec![message("a", 0, 1), message("a", 1, 7)];queues- .settle(&key("a"), requeued, None, now)+ .settle(&key("a"), failure(requeued, now), now).expect("claimed");assert_eq!(claimed(&take_all(&mut queues, now)),@@ -729,7 +809,7 @@ mod tests {queues.push(key("a"), 0, vec![message("a", 1, 7)], now);let retry_at = now + Duration::from_millis(100);queues- .settle(&key("a"), vec![message("a", 0, 1)], Some(retry_at), now)+ .settle(&key("a"), failure(vec![message("a", 0, 1)], retry_at), now).expect("claimed");queues.purge(&[("events".to_string(), 0)]);@@ -746,7 +826,7 @@ mod tests {let mut queues = KeyQueues::default();queues.push(key("a"), 0, vec![message("a", 0, 1)], now);assert!(queues- .settle(&key("a"), vec![message("a", 0, 1)], None, now)+ .settle(&key("a"), failure(vec![message("a", 0, 1)], now), now).is_err());assert_eq!(queues.queued_messages(), 1);}@@ -808,7 +888,7 @@ mod tests {let requeued = vec![message("a", 0, 1), message("a", 1, 2)];let requeued_bytes = payload_bytes(&requeued);queues- .settle(&key("a"), requeued, None, now)+ .settle(&key("a"), failure(requeued, now), now).expect("claimed");assert_eq!(queues.queued_bytes(), requeued_bytes);@@ -825,7 +905,7 @@ mod tests {take_all(&mut queues, now);queues.push(key("a"), 0, vec![message("a", 0, 3)], now);queues- .settle(&key("a"), failed(), None, now)+ .settle(&key("a"), failure(failed(), now), now).expect("claimed");assert_eq!(claimed(&take_all(&mut queues, now)),@@ -834,7 +914,7 @@ mod tests {queues.push(key("a"), 0, vec![message("a", 0, 4)], now);queues- .settle(&key("a"), failed(), None, now)+ .settle(&key("a"), failure(failed(), now), now).expect("claimed");assert_eq!(queues.queued_messages(), 4);assert_eq!(@@ -842,17 +922,69 @@ mod tests {vec![("a", vec![1, 2], true)]);queues- .settle(&key("a"), Vec::new(), None, now)+ .settle(&key("a"), Settlement::Done, now).expect("claimed");assert_eq!(claimed(&take_all(&mut queues, now)),vec![("a", vec![3, 4], false)]);- assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(true));+ assert_eq!(queues.settle(&key("a"), Settlement::Done, now), Ok(EVICTED));assert_eq!(queues.queued_messages(), 0);assert_eq!(queues.queued_bytes(), 0);}+ #[derive(Clone, Copy)]+ enum SettleKind {+ Unfinished,+ Bounced,+ Failed,+ }++ #[rstest]+ #[case::attempts_used_up(+ &[+ SettleKind::Unfinished,+ SettleKind::Failed,+ SettleKind::Unfinished,+ SettleKind::Failed,+ SettleKind::Unfinished,+ ],+ &[false, false, true, false, false],+ "a failure neither counts as an attempt nor resets the count"+ )]+ #[case::bounced(+ &[SettleKind::Bounced, SettleKind::Failed, SettleKind::Unfinished],+ &[true, false, false],+ "a bounce uses up the attempts at once, and a failure keeps the escalation"+ )]+ fn a_key_reports_its_escalation_once(+ #[case] settles: &[SettleKind],+ #[case] expected: &[bool],+ #[case] reason: &str,+ ) {+ let now = Instant::now();+ let mut queues = KeyQueues::default().with_budget_attempts(NonZeroU32::new(2));+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);++ let escalated: Vec<bool> = settles+ .iter()+ .map(|kind| {+ take_all(&mut queues, now);+ let messages = vec![message("a", 0, 1)];+ let settlement = match kind {+ SettleKind::Unfinished => Settlement::Unfinished(messages),+ SettleKind::Bounced => Settlement::Bounced(messages),+ SettleKind::Failed => failure(messages, now),+ };+ queues+ .settle(&key("a"), settlement, now)+ .expect("claimed")+ .escalated+ })+ .collect();+ assert_eq!(escalated, expected, "{reason}");+ }+#[test]fn a_key_evicted_by_a_purge_and_pushed_again_is_claimed_once() {let now = Instant::now();@@ -902,7 +1034,7 @@ mod tests {queues.push(key("a"), 0, spanning(), now);take_all(&mut queues, now);queues- .settle(&key("a"), spanning(), Some(retry_at), now)+ .settle(&key("a"), failure(spanning(), retry_at), now).expect("claimed");queues.purge(&[("events".to_string(), 0)]);@@ -920,6 +1052,7 @@ mod tests {let epoch = |assignment_epoch| RequestClass {assignment_epoch,replay: false,+ unbudgeted: false,};let mut queues = KeyQueues::default();queues.push(key("a"), 1, vec![message("a", 0, 1)], now);@@ -935,7 +1068,7 @@ mod tests {assert!(!queues.has_ready(), "a's epoch-2 run waits for its claim");queues- .settle(&key("a"), Vec::new(), None, now)+ .settle(&key("a"), Settlement::Done, now).expect("claimed");assert_eq!(queues.ready_sizes(), &[(epoch(2), size(1))]);}@@ -951,6 +1084,7 @@ mod tests {let older_epoch = RequestClass {assignment_epoch: 1,replay: false,+ unbudgeted: false,};assert_eq!(claimed(&queues.take_runs(older_epoch, |_| false)),@@ -980,7 +1114,7 @@ mod tests {vec![("a", expected, false)]);queues- .settle(&key("a"), Vec::new(), None, now)+ .settle(&key("a"), Settlement::Done, now).expect("claimed");}}diff --git a/rust/ingestion-consumer/src/batcher/mod.rs b/rust/ingestion-consumer/src/batcher/mod.rsindex 282e8ff4b220..c0b7a68cbbe9 100644--- a/rust/ingestion-consumer/src/batcher/mod.rs+++ b/rust/ingestion-consumer/src/batcher/mod.rs@@ -44,7 +44,7 @@ use self::worker_pool::WorkerPoolSource;use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch, Submission};use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};use crate::order_sentinel::KeyOrderSentinel;-use crate::transport::SendError;+use crate::transport::{SendError, SendOutcome};use crate::types::Accumulator;use crate::types::SerializedKafkaMessage;use crate::worker_registry::WorkerId;@@ -482,7 +482,13 @@ async fn await_settled(} = sub_batch;match pending.wait().await {- Ok(accepted) => {+ // The dispatcher sends no budget, and the transport refuses a partial+ // ack for an unbudgeted sub-batch.+ Ok(SendOutcome::Partial { .. }) => {+ inner.report_error("partial ack for a pin_stash send".to_string());+ 0+ }+ Ok(SendOutcome::Accepted(accepted)) => {// Advance ACK high-water marks before the settle, which// may evict the keys' sentinel state.inner.dispatcher.on_sub_batch_acked(&key_offsets);diff --git a/rust/ingestion-consumer/src/batcher/packer.rs b/rust/ingestion-consumer/src/batcher/packer.rsindex 6e85d1e3f893..4711387f70dd 100644--- a/rust/ingestion-consumer/src/batcher/packer.rs+++ b/rust/ingestion-consumer/src/batcher/packer.rs@@ -91,7 +91,8 @@ impl Packer {/// hold. A class at the target goes out at once. Ready messages below/// the target wait for the latency budget, counted from the first action/// that finds a free slot for them, or go out at once when `draining`.- /// Replays go out at once, because they already waited out a retry delay.+ /// Replays go out at once, because they already waited out a retry delay+ /// or a worker's time budget./// Classes go in `KeyQueues::ready_sizes` order, and a later class goes/// ahead only while every earlier one waits below the target.pub fn pack(diff --git a/rust/ingestion-consumer/src/batcher/request.rs b/rust/ingestion-consumer/src/batcher/request.rsindex c2aa0912b361..d779d7c6aab7 100644--- a/rust/ingestion-consumer/src/batcher/request.rs+++ b/rust/ingestion-consumer/src/batcher/request.rs@@ -9,6 +9,7 @@ use super::key_queues::{KeyRun, ReadyRun};pub struct RequestClass {pub assignment_epoch: u64,pub replay: bool,+ pub unbudgeted: bool,}#[derive(Debug)]diff --git a/rust/ingestion-consumer/src/batcher/state_machine.rs b/rust/ingestion-consumer/src/batcher/state_machine.rsindex 789388621a60..f30db0cb9970 100644--- a/rust/ingestion-consumer/src/batcher/state_machine.rs+++ b/rust/ingestion-consumer/src/batcher/state_machine.rs@@ -14,18 +14,20 @@//! instead of growing lag.use std::collections::HashMap;+use std::num::NonZeroU32;use std::sync::Arc;use std::time::{Duration, Instant};use common_kafka_consumer::{GroupCompletion, Offset, Partition};-use metrics::{gauge, histogram};+use metrics::{counter, gauge, histogram};-use super::in_flight::{InFlightRequest, InFlightRequests, RequestId, SentRun};-use super::key_queues::{KeyQueues, KeyRun};+use super::in_flight::{InFlightRequest, InFlightRequests, RequestId, SentMessage};+use super::key_queues::{KeyQueues, KeyRun, Settlement};use super::packer::Packer;use super::request::{Request, RequestClass};use super::retry_policy::{RetryPolicy, RetryReason};use super::worker_assigner::WorkerAssigner;+use crate::order_sentinel::ack_mark;use crate::types::SerializedKafkaMessage;use crate::worker_registry::WorkerId;@@ -35,11 +37,22 @@ pub enum FailureCause {Busy,}+/// The worker's soft time budget for every request. A key resends without it+/// once `attempts` settles left its messages unfinished since it last finished+/// a run, or at once when its request finished nothing, so a message that+/// never fits the budget still finishes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct RequestBudget {+ pub soft_budget: Duration,+ pub attempts: NonZeroU32,+}+#[derive(Debug)]pub struct SendRequest {pub request: RequestId,pub worker: WorkerId,pub class: RequestClass,+ pub soft_budget: Option<Duration>,pub runs: Vec<KeyRun>,}@@ -108,9 +121,24 @@ impl BatcherStateMachine {retry,stall_timeout,last_progress: now,+ soft_budget: None,}))}+ /// `None` sends no budget.+ pub fn with_request_budget(self, budget: Option<RequestBudget>) -> Self {+ match self {+ BatcherStateMachine::Running(active) => BatcherStateMachine::Running(ActiveState {+ soft_budget: budget.map(|budget| budget.soft_budget),+ keys: active+ .keys+ .with_budget_attempts(budget.map(|budget| budget.attempts)),+ ..active+ }),+ other => other,+ }+ }+pub fn on_groups(self,now: Instant,@@ -142,9 +170,24 @@ impl BatcherStateMachine {})}- /// A worker accepts a whole request or none of it. The failed request's- /// messages go back to the front of their keys' queues and are sent again- /// as replay after the retry delay.+ /// The worker finished every message except `unfinished`. Those go back to+ /// the front of their keys' queues and are sent again at once as replay,+ /// without a budget when the worker finished nothing.+ pub fn on_request_partial(+ self,+ now: Instant,+ workers: &[WorkerId],+ request: RequestId,+ accepted: u32,+ unfinished: Vec<SerializedKafkaMessage>,+ ) -> (Self, Effects) {+ self.act(|active, draining| {+ active.on_request_partial(now, workers, draining, request, accepted, unfinished)+ })+ }++ /// The failed request's messages go back to the front of their keys'+ /// queues and are sent again as replay after the retry delay.pub fn on_request_failed(self,now: Instant,@@ -261,6 +304,7 @@ pub struct ActiveState {retry: RetryPolicy,stall_timeout: Duration,last_progress: Instant,+ soft_budget: Option<Duration>,}impl ActiveState {@@ -322,10 +366,68 @@ impl ActiveState {}let assignment_epoch = sent.class.assignment_epoch;let runs = sent.accepted();- effects.completions = completions(assignment_epoch, &runs);- effects.key_acks = key_acks(&runs);+ effects.completions =+ completions(assignment_epoch, runs.iter().flat_map(|run| &run.messages));+ effects.key_acks = key_acks(runs.iter().map(|run| {+ (+ &run.routing_key,+ run.first_keyed_partition(),+ run.messages.as_slice(),+ &[][..],+ )+ }));for run in runs {- self.settle_key(&run.routing_key, Vec::new(), None, now, &mut effects)?;+ self.settle_key(&run.routing_key, Settlement::Done, now, &mut effects)?;+ }+ self.advance(now, workers, draining, &mut effects)?;+ Ok(effects)+ }++ fn on_request_partial(+ &mut self,+ now: Instant,+ workers: &[WorkerId],+ draining: bool,+ request: RequestId,+ accepted: u32,+ unfinished: Vec<SerializedKafkaMessage>,+ ) -> Result<Effects, String> {+ let mut effects = Effects::default();+ let sent = self.take_request(request, &mut effects)?;+ effects.worker_outcomes.push(WorkerOutcome {+ worker: sent.worker.clone(),+ fault: false,+ });+ if accepted > 0 {+ self.last_progress = now;+ }+ let assignment_epoch = sent.class.assignment_epoch;+ let unfinished_count = unfinished.len();+ let partial_runs = sent.partially_accepted(accepted, unfinished)?;+ counter!("ingestion_consumer_request_budget_partials_total").increment(1);+ counter!("ingestion_consumer_request_budget_unfinished_messages_total")+ .increment(unfinished_count as u64);+ effects.completions = completions(+ assignment_epoch,+ partial_runs.iter().flat_map(|run| &run.accepted),+ );+ effects.key_acks = key_acks(partial_runs.iter().map(|run| {+ (+ &run.routing_key,+ run.first_keyed_partition,+ run.accepted.as_slice(),+ run.unfinished.as_slice(),+ )+ }));+ for run in partial_runs {+ let settlement = if run.unfinished.is_empty() {+ Settlement::Done+ } else if accepted == 0 {+ Settlement::Bounced(run.unfinished)+ } else {+ Settlement::Unfinished(run.unfinished)+ };+ self.settle_key(&run.routing_key, settlement, now, &mut effects)?;}self.advance(now, workers, draining, &mut effects)?;Ok(effects)@@ -355,13 +457,11 @@ impl ActiveState {},);for run in runs {- self.settle_key(- &run.routing_key,- run.messages,- Some(retry_at),- now,- &mut effects,- )?;+ let settlement = Settlement::Failed {+ messages: run.messages,+ retry_at,+ };+ self.settle_key(&run.routing_key, settlement, now, &mut effects)?;}self.advance(now, workers, draining, &mut effects)?;Ok(effects)@@ -401,16 +501,18 @@ impl ActiveState {fn settle_key(&mut self,routing_key: &Arc<str>,- requeued: Vec<SerializedKafkaMessage>,- retry_at: Option<Instant>,+ settlement: Settlement,now: Instant,effects: &mut Effects,) -> Result<(), String> {- let evicted = self+ let settled = self.keys- .settle(routing_key, requeued, retry_at, now)+ .settle(routing_key, settlement, now).map_err(|err| err.to_string())?;- if evicted {+ if settled.escalated {+ counter!("ingestion_consumer_request_budget_escalations_total").increment(1);+ }+ if settled.evicted {effects.evicted_keys.push(Arc::clone(routing_key));}Ok(())@@ -474,6 +576,7 @@ impl ActiveState {request: id,worker,class: request.class,+ soft_budget: self.soft_budget.filter(|_| !request.class.unbudgeted),runs: request.runs,});}@@ -518,15 +621,16 @@ impl ActiveState {}}-fn completions(assignment_epoch: u64, runs: &[SentRun]) -> Vec<GroupCompletion> {+fn completions<'a>(+ assignment_epoch: u64,+ messages: impl IntoIterator<Item = &'a SentMessage>,+) -> Vec<GroupCompletion> {let mut by_partition: HashMap<i32, Vec<Offset>> = HashMap::new();- for run in runs {- for message in &run.messages {- by_partition- .entry(message.partition)- .or_default()- .push(Offset(message.offset));- }+ for message in messages {+ by_partition+ .entry(message.partition)+ .or_default()+ .push(Offset(message.offset));}let mut completions: Vec<GroupCompletion> = by_partition.into_iter()@@ -541,22 +645,34 @@ fn completions(assignment_epoch: u64, runs: &[SentRun]) -> Vec<GroupCompletion>completions}-fn key_acks(runs: &[SentRun]) -> Vec<KeyAck> {- runs.iter()- .filter_map(|run| {- let max_offset = run- .messages- .iter()- // An unkeyed message lives on an arbitrary partition under a- // synthetic key, so it does not advance an ACK high-water mark.- .filter(|message| message.keyed)- .map(|message| message.offset)- .max()?;- Some(KeyAck {- routing_key: Arc::clone(&run.routing_key),- max_offset,- })- })+fn key_acks<'a>(+ runs: impl IntoIterator<+ Item = (+ &'a Arc<str>,+ Option<i32>,+ &'a [SentMessage],+ &'a [SerializedKafkaMessage],+ ),+ >,+) -> Vec<KeyAck> {+ runs.into_iter()+ .filter_map(+ |(routing_key, first_keyed_partition, accepted, unfinished)| {+ let max_offset = ack_mark(+ first_keyed_partition?,+ accepted+ .iter()+ .map(|message| (message.partition, message.offset, message.keyed)),+ unfinished+ .iter()+ .map(|message| (message.partition, message.offset)),+ )?;+ Some(KeyAck {+ routing_key: Arc::clone(routing_key),+ max_offset,+ })+ },+ ).collect()}@@ -565,16 +681,20 @@ mod tests {use std::collections::VecDeque;use std::num::NonZeroUsize;+ use rstest::rstest;+use super::*;use crate::batcher::key_queues::RunCap;use crate::batcher::packer::PackTargets;use crate::batcher::test_support::{message, offsets};+ use crate::order_sentinel::{KeyOrderSentinel, KeyOrderViolation, SendKind};use crate::routing::{Router, RoutingStrategy};const FAULT_DELAY: Duration = Duration::from_millis(200);const BUSY_DELAY: Duration = Duration::from_millis(20);const NO_WORKER_DELAY: Duration = Duration::from_millis(100);const STALL: Duration = Duration::from_secs(60);+ const BUDGET: Duration = Duration::from_millis(250);/// Distinct delays, so a wakeup time shows which retry reason applied.fn retry_policy() -> RetryPolicy {@@ -613,6 +733,13 @@ mod tests {.expect("valid stall timeout")}+ fn budgeted_batcher(events: usize, attempts: u32, now: Instant) -> BatcherStateMachine {+ packing_batcher(events, Duration::ZERO, 4, now).with_request_budget(Some(RequestBudget {+ soft_budget: BUDGET,+ attempts: NonZeroU32::new(attempts).expect("nonzero attempts"),+ }))+ }+fn pool(workers: &[&str]) -> Vec<WorkerId> {workers.iter().map(|w| WorkerId::from(*w)).collect()}@@ -634,6 +761,30 @@ mod tests {.collect()}+ /// Applies the effects in the order the driver does, so the sentinel judges+ /// the sends against the ACK marks of the same action.+ fn apply_to_sentinel(sentinel: &KeyOrderSentinel, effects: &Effects) -> Vec<KeyOrderViolation> {+ let mut batch = sentinel.batch();+ for ack in &effects.key_acks {+ batch.note_acked(&ack.routing_key, ack.max_offset);+ }+ for key in &effects.evicted_keys {+ batch.evict(key);+ }+ let mut violations = Vec::new();+ for send in &effects.sends {+ let kind = if send.class.replay {+ SendKind::Resend+ } else {+ SendKind::Fresh+ };+ for run in &send.runs {+ violations.extend(batch.note_sent(&run.routing_key, &run.messages, kind));+ }+ }+ violations+ }+fn sent_messages(send: &SendRequest) -> Vec<SerializedKafkaMessage> {send.runs.iter()@@ -1272,7 +1423,7 @@ mod tests {}#[test]- fn every_offset_completes_exactly_once_across_failures_retries_and_packing() {+ fn every_offset_completes_exactly_once_across_failures_partials_retries_and_packing() {let now = Instant::now();let retry_at = now + FAULT_DELAY;let workers = pool(&["w1", "w2"]);@@ -1319,7 +1470,13 @@ mod tests {vec![("a", vec![1, 2]), ("b", vec![3])]);let replay = effects.sends[0].request;- let (batcher, effects) = batcher.on_request_succeeded(retry_at, &workers, replay, 3);+ let (batcher, effects) =+ batcher.on_request_partial(retry_at, &workers, replay, 2, vec![message("a", 0, 1)]);+ record(&effects);+ assert!(effects.sends[0].class.replay);+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1])]);+ let resend = effects.sends[0].request;+ let (batcher, effects) = batcher.on_request_succeeded(retry_at, &workers, resend, 1);record(&effects);assert_eq!(shape(&effects.sends[0]), vec![("a", vec![7])]);let last = effects.sends[0].request;@@ -1346,7 +1503,8 @@ mod tests {}#[test]- fn an_accepted_request_completes_each_partition_and_acks_only_keyed_messages() {+ fn an_accepted_request_completes_each_partition_and_acks_keyed_messages_on_the_first_partition()+ {let now = Instant::now();let workers = pool(&["w"]);let batcher = packing_batcher(2, Duration::ZERO, 4, now);@@ -1375,7 +1533,7 @@ mod tests {effects.key_acks,vec![KeyAck {routing_key: "a".into(),- max_offset: 2+ max_offset: 1}]);@@ -1384,6 +1542,31 @@ mod tests {assert!(effects.key_acks.is_empty());}+ #[test]+ fn a_partial_leaving_a_keys_first_partition_unfinished_resends_it_without_a_violation() {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let sentinel = KeyOrderSentinel::new();+ let run = KeyRun {+ routing_key: "a".into(),+ messages: vec![message("a", 0, 10), message("a", 1, 100)],+ };+ let (batcher, effects) =+ packing_batcher(2, Duration::ZERO, 4, now).on_groups(now, &workers, 0, vec![run]);+ assert!(apply_to_sentinel(&sentinel, &effects).is_empty());+ let request = effects.sends[0].request;++ let (_, effects) =+ batcher.on_request_partial(now, &workers, request, 1, vec![message("a", 0, 10)]);+ assert_eq!(effects.completions[0].offsets, vec![Offset(100)]);+ assert!(+ effects.key_acks.is_empty(),+ "partition 1's offset is no mark for partition 0"+ );+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![10])]);+ assert!(apply_to_sentinel(&sentinel, &effects).is_empty());+ }+#[test]fn a_failed_run_spanning_a_revoked_partition_replays_only_the_kept_partition_in_order() {let now = Instant::now();@@ -1468,6 +1651,233 @@ mod tests {assert!(effects.completions.is_empty());}+ /// Key `a` holds offsets 1 to 3 and key `b` offset 4. The ack for `a`+ /// stops below its lowest unfinished offset, and a key with nothing+ /// finished gets no ack.+ #[rstest]+ #[case::a_middle_message_of_a_shared_key(&[2], &[1, 3, 4], Some(1))]+ #[case::the_tail_of_a_key(&[2, 3], &[1, 4], Some(1))]+ #[case::a_whole_key(&[1, 2, 3], &[4], None)]+ fn a_partial_completes_the_accepted_offsets_and_requeues_the_unfinished_ones_at_the_front(+ #[case] unfinished: &[i64],+ #[case] completed: &[i64],+ #[case] ack_for_a: Option<i64>,+ ) {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let sentinel = KeyOrderSentinel::new();+ let (batcher, effects) = packing_batcher(4, Duration::ZERO, 4, now).on_groups(+ now,+ &workers,+ 0,+ vec![run("a", &[1, 2, 3]), run("b", &[4])],+ );+ assert_eq!(+ shape(&effects.sends[0]),+ vec![("a", vec![1, 2, 3]), ("b", vec![4])]+ );+ assert!(apply_to_sentinel(&sentinel, &effects).is_empty());+ let request = effects.sends[0].request;+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[5])]);+ assert!(effects.sends.is_empty(), "a's run is in flight");++ let accepted = 4 - unfinished.len() as u32;+ let unfinished_messages = unfinished+ .iter()+ .map(|&offset| message("a", 0, offset))+ .collect();+ let (batcher, effects) =+ batcher.on_request_partial(now, &workers, request, accepted, unfinished_messages);+ assert_eq!(+ effects.completions[0].offsets,+ completed+ .iter()+ .map(|&offset| Offset(offset))+ .collect::<Vec<_>>()+ );+ let mut expected_acks = Vec::new();+ if let Some(max_offset) = ack_for_a {+ expected_acks.push(KeyAck {+ routing_key: "a".into(),+ max_offset,+ });+ }+ expected_acks.push(KeyAck {+ routing_key: "b".into(),+ max_offset: 4,+ });+ assert_eq!(effects.key_acks, expected_acks);+ assert_eq!(effects.evicted_keys, vec![Arc::<str>::from("b")]);+ assert_eq!(+ effects.sends.len(),+ 1,+ "a's fresh message waits for the replay"+ );+ assert!(effects.sends[0].class.replay);+ assert_eq!(shape(&effects.sends[0]), vec![("a", unfinished.to_vec())]);+ let violations = apply_to_sentinel(&sentinel, &effects);+ assert!(+ violations.is_empty(),+ "the ACK mark stops before the unfinished message, so its resend is legal: \+ {violations:?}"+ );+ let replay = effects.sends[0].request;++ let (_, effects) =+ batcher.on_request_succeeded(now, &workers, replay, unfinished.len() as u32);+ assert_eq!(+ effects.completions[0].offsets,+ unfinished+ .iter()+ .map(|&offset| Offset(offset))+ .collect::<Vec<_>>()+ );+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![5])]);+ let violations = apply_to_sentinel(&sentinel, &effects);+ assert!(+ violations.is_empty(),+ "the fresh send after the resend is legal: {violations:?}"+ );+ }++ #[test]+ fn a_partial_that_does_not_match_the_request_fails_the_state_machine() {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);+ let request = effects.sends[0].request;++ let (batcher, effects) =+ batcher.on_request_partial(now, &workers, request, 0, vec![message("a", 0, 2)]);+ assert!(matches!(batcher, BatcherStateMachine::Failed));+ assert!(effects.fatal.is_some());+ }++ #[test]+ fn partials_that_accept_nothing_do_not_hold_off_the_watchdog() {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);+ let request = effects.sends[0].request;++ let (batcher, effects) = batcher.on_request_partial(+ now + STALL / 2,+ &workers,+ request,+ 0,+ vec![message("a", 0, 1)],+ );+ assert!(effects.fatal.is_none());+ let resend = effects.sends[0].request;+ let (batcher, effects) =+ batcher.on_request_partial(now + STALL, &workers, resend, 0, vec![message("a", 0, 1)]);+ assert!(matches!(batcher, BatcherStateMachine::Failed));+ assert!(effects.fatal.is_some());+ }++ #[test]+ fn a_key_that_keeps_running_out_of_budget_resends_alone_without_one() {+ let now = Instant::now();+ let retry_at = now + FAULT_DELAY;+ let workers = pool(&["w"]);+ let (batcher, effects) =+ budgeted_batcher(4, 2, now).on_groups(now, &workers, 0, vec![run("a", &[1, 2, 3])]);+ let first = effects.sends[0].request;+ let (batcher, effects) = batcher.on_request_partial(+ now,+ &workers,+ first,+ 1,+ vec![message("a", 0, 2), message("a", 0, 3)],+ );+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![2, 3])]);+ assert_eq!(effects.sends[0].soft_budget, Some(BUDGET));+ let second = effects.sends[0].request;+ let (batcher, effects) =+ batcher.on_request_partial(now, &workers, second, 1, vec![message("a", 0, 3)]);+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![3])]);+ assert_eq!(effects.sends[0].soft_budget, None);+ assert!(effects.sends[0].class.unbudgeted);+ let escalated = effects.sends[0].request;++ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("b", &[4])]);+ let budgeted = effects.sends[0].request;+ let (batcher, _) = batcher.on_request_failed(+ now,+ &workers,+ escalated,+ FailureCause::Fault,+ vec![message("a", 0, 3)],+ );+ let (batcher, _) = batcher.on_request_failed(+ now,+ &workers,+ budgeted,+ FailureCause::Fault,+ vec![message("b", 0, 4)],+ );++ let (_, effects) = batcher.on_wakeup(retry_at, &workers);+ let sends: Vec<_> = effects+ .sends+ .iter()+ .map(|send| (shape(send), send.soft_budget))+ .collect();+ assert_eq!(+ sends,+ vec![+ (vec![("a", vec![3])], None),+ (vec![("b", vec![4])], Some(BUDGET)),+ ],+ "a failure keeps the escalation, the escalated replay goes first, and a budgeted \+ replay never rides along"+ );+ }++ #[test]+ fn a_partial_that_finished_nothing_resends_without_a_budget_at_once() {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let (batcher, effects) =+ budgeted_batcher(4, 3, now).on_groups(now, &workers, 0, vec![run("a", &[1, 2])]);+ let request = effects.sends[0].request;++ let (_, effects) = batcher.on_request_partial(+ now,+ &workers,+ request,+ 0,+ vec![message("a", 0, 1), message("a", 0, 2)],+ );+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1, 2])]);+ assert_eq!(effects.sends[0].soft_budget, None);+ assert!(effects.sends[0].class.unbudgeted);+ }++ #[test]+ fn a_finished_run_resets_the_escalation_count() {+ let now = Instant::now();+ let workers = pool(&["w"]);+ let (batcher, effects) =+ budgeted_batcher(4, 2, now).on_groups(now, &workers, 0, vec![run("a", &[1, 2])]);+ let first = effects.sends[0].request;+ let (batcher, _) = batcher.on_groups(now, &workers, 0, vec![run("a", &[3, 4])]);+ let (batcher, effects) =+ batcher.on_request_partial(now, &workers, first, 1, vec![message("a", 0, 2)]);+ let resend = effects.sends[0].request;+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, resend, 1);+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![3, 4])]);+ let next = effects.sends[0].request;++ let (_, effects) =+ batcher.on_request_partial(now, &workers, next, 1, vec![message("a", 0, 4)]);+ assert_eq!(+ effects.sends[0].soft_budget,+ Some(BUDGET),+ "the earlier unfinished attempt no longer counts"+ );+ }+#[test]fn a_failure_handing_back_extra_messages_fails_the_state_machine() {let now = Instant::now();diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex d95a5e6f8345..c993b084872b 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -1,4 +1,4 @@-use std::num::NonZeroUsize;+use std::num::{NonZeroU32, NonZeroUsize};use std::time::{Duration, Instant};use common_continuous_profiling::ContinuousProfilingConfig;@@ -9,7 +9,7 @@ use tracing::info;use crate::batcher::key_queues::RunCap;use crate::batcher::packer::{PackTargets, Packer};use crate::batcher::retry_policy::RetryPolicy;-use crate::batcher::state_machine::BatcherStateMachine;+use crate::batcher::state_machine::{BatcherStateMachine, RequestBudget};use crate::batcher::worker_assigner::WorkerAssigner;use crate::discovery::DiscoveryMode;use crate::routing::{Router, RoutingStrategy};@@ -213,6 +213,20 @@ pub struct Config {#[envconfig(from = "INGESTION_PACK_LATENCY_BUDGET_MS", default = "0")]pub pack_latency_budget_ms: u64,+ /// How long a worker may spend on one key-table request before it stops+ /// starting work and acks what finished as partial (milliseconds). `0`+ /// (default) sends no budget, otherwise at least 100. Needs+ /// `INGESTION_SCHEDULER=key_table`. See `request_budget` for the bounds+ /// against the ack and stall timeouts.+ #[envconfig(from = "INGESTION_REQUEST_SOFT_BUDGET_MS", default = "0")]+ pub request_soft_budget_ms: u64,++ /// How many budgeted attempts may leave a key's messages unfinished, since+ /// the key last finished a run, before it resends without a budget. At+ /// least 1. Only read when `INGESTION_REQUEST_SOFT_BUDGET_MS` is set.+ #[envconfig(from = "INGESTION_REQUEST_BUDGET_ATTEMPTS", default = "3")]+ pub request_budget_attempts: u32,+/// Maximum Kafka batches to process concurrently. Matches the Node.js/// CONSUMER_MAX_BACKGROUND_TASKS setting used by the Kafka consumer wrapper.#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]@@ -467,13 +481,74 @@ impl Config {self.ingestion_worker_concurrent_batches,)?;let retry = RetryPolicy::uniform(Duration::from_millis(self.parked_retry_interval_ms))?;- BatcherStateMachine::new(+ Ok(BatcherStateMachine::new(packer,assigner,retry,Duration::from_millis(self.consumer_deferred_flush_timeout_ms),Instant::now(),- )+ )?+ .with_request_budget(self.request_budget()?))+ }++ const MIN_REQUEST_SOFT_BUDGET_MS: u64 = 100;++ pub fn request_budget(&self) -> Result<Option<RequestBudget>, String> {+ let budget_ms = self.request_soft_budget_ms;+ if budget_ms == 0 {+ return Ok(None);+ }+ // pin_stash keeps several requests per key in flight, so a partial+ // ack's resend could overtake a newer request for the same key.+ if self.scheduler != SchedulerKind::KeyTable {+ return Err(+ "INGESTION_REQUEST_SOFT_BUDGET_MS needs INGESTION_SCHEDULER=key_table".to_string(),+ );+ }+ // Below this the worker's fixed work per frame outlasts the budget, so+ // nearly every request comes back partial with nothing finished.+ if budget_ms < Self::MIN_REQUEST_SOFT_BUDGET_MS {+ return Err(format!(+ "INGESTION_REQUEST_SOFT_BUDGET_MS must be at least {}",+ Self::MIN_REQUEST_SOFT_BUDGET_MS+ ));+ }+ // The worker treats a longer budget as unlimited.+ if budget_ms > i32::MAX as u64 {+ return Err(format!(+ "INGESTION_REQUEST_SOFT_BUDGET_MS must be at most {}",+ i32::MAX+ ));+ }+ // The worker starts a frame's budget when it reads the frame, and a+ // full worker reads the next frame only once the previous one has a+ // slot, so the last frame in flight can ack a budget per frame late.+ let in_flight = self.ingestion_worker_concurrent_batches.max(1) as u64;+ if budget_ms.saturating_mul(in_flight) >= self.ingestion_worker_stream_ack_timeout_ms {+ return Err(+ "INGESTION_REQUEST_SOFT_BUDGET_MS times INGESTION_WORKER_CONCURRENT_BATCHES must \+ be below INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS"+ .to_string(),+ );+ }+ let attempts = NonZeroU32::new(self.request_budget_attempts)+ .ok_or("INGESTION_REQUEST_BUDGET_ATTEMPTS must be at least 1")?;+ // A partial ack that finished nothing does not count as progress, so+ // it must come back before the stall watchdog fires. Its resend goes+ // without a budget, so no second one follows for the same key.+ if budget_ms.saturating_add(self.pack_latency_budget_ms)+ >= self.consumer_deferred_flush_timeout_ms+ {+ return Err(+ "INGESTION_REQUEST_SOFT_BUDGET_MS plus INGESTION_PACK_LATENCY_BUDGET_MS must be \+ below CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS"+ .to_string(),+ );+ }+ Ok(Some(RequestBudget {+ soft_budget: Duration::from_millis(budget_ms),+ attempts,+ }))}pub fn worker_urls(&self) -> Vec<String> {@@ -551,3 +626,88 @@ impl Config {builder.build()}}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use rstest::rstest;++ use super::*;++ fn config(vars: &[(&str, &str)]) -> Config {+ let vars: HashMap<String, String> = vars+ .iter()+ .map(|(key, value)| (key.to_string(), value.to_string()))+ .collect();+ Config::init_from_hashmap(&vars).expect("valid config")+ }++ #[rstest]+ #[case::unset(&[], None)]+ #[case::under_key_table(+ &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "250")],+ Some((250, 3))+ )]+ #[case::at_the_floor(+ &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "100")],+ Some((100, 3))+ )]+ #[case::just_below_the_ack_and_stall_timeouts(+ &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "59999")],+ Some((59999, 3))+ )]+ #[case::just_below_the_stall_timeout_with_the_pack_latency(+ &[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "49999"),+ ("INGESTION_PACK_LATENCY_BUDGET_MS", "10000"),+ ],+ Some((49999, 3))+ )]+ fn a_valid_request_budget_is_read(+ #[case] vars: &[(&str, &str)],+ #[case] expected: Option<(u64, u32)>,+ ) {+ let expected = expected.map(|(budget_ms, attempts)| RequestBudget {+ soft_budget: Duration::from_millis(budget_ms),+ attempts: NonZeroU32::new(attempts).expect("nonzero attempts"),+ });+ assert_eq!(config(vars).request_budget(), Ok(expected));+ }++ #[rstest]+ #[case::under_pin_stash(&[+ ("INGESTION_SCHEDULER", "pin_stash"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "250"),+ ])]+ #[case::below_the_floor(&[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "99"),+ ])]+ #[case::longer_than_the_worker_honors(&[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "2147483648"),+ ("INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS", "4294967296"),+ ("CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS", "4294967296"),+ ])]+ #[case::at_the_ack_timeout_across_every_frame_in_flight(&[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "15000"),+ ("INGESTION_WORKER_CONCURRENT_BATCHES", "4"),+ ])]+ #[case::at_the_stall_timeout_with_the_pack_latency(&[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "50000"),+ ("INGESTION_PACK_LATENCY_BUDGET_MS", "10000"),+ ("INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS", "120000"),+ ])]+ #[case::with_no_budgeted_attempt(&[+ ("INGESTION_SCHEDULER", "key_table"),+ ("INGESTION_REQUEST_SOFT_BUDGET_MS", "250"),+ ("INGESTION_REQUEST_BUDGET_ATTEMPTS", "0"),+ ])]+ fn an_invalid_request_budget_is_rejected(#[case] vars: &[(&str, &str)]) {+ assert!(config(vars).request_budget().is_err());+ }+}diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex d98448a71572..d400cd1d6b6f 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -1,4 +1,4 @@-use std::collections::{HashMap, VecDeque};+use std::collections::{HashMap, HashSet, VecDeque};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};@@ -76,6 +76,9 @@ struct PartitionDeliveries {delivered: u32,covered: u32,accepted: u32,+ /// The offsets a completion covered. Keyed by offset rather than by+ /// position in `span`, because a poll can span an offset gap.+ credited: HashSet<i64, ahash::RandomState>,}impl PartitionDeliveries {@@ -90,9 +93,21 @@ impl PartitionDeliveries {delivered: 1,covered: 0,accepted: 0,+ credited: HashSet::default(),}}+ fn credit(&mut self, offset: i64) {+ self.credited.insert(offset);+ }++ fn uncredited_charge(&self) -> Option<Offset> {+ self.charges+ .iter()+ .map(|(offset, _)| *offset)+ .find(|offset| !self.credited.contains(&offset.0))+ }+/// Record one more delivery. `generation` is consulted only when/// `generations_version` moved since the last stamp. A moved generation/// means the partition was revoked and regained inside this batch: the@@ -165,6 +180,18 @@ impl InFlightPoll {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 one offset credited twice fills `covered` as well.+ fn uncredited_charge(&self) -> Option<(&TopicPartition, Offset)> {+ self.partitions+ .iter()+ .find_map(|(topic_partition, deliveries)| {+ deliveries+ .uncredited_charge()+ .map(|offset| (topic_partition, offset))+ })+ }}/// A partition revocation stamped with the ledger generation started by the@@ -271,6 +298,7 @@ fn apply_completion(in_flight: &mut VecDeque<InFlightPoll>, completion: GroupCompoll.accepted += u32::from(is_accepted);deliveries.covered += 1;deliveries.accepted += u32::from(is_accepted);+ deliveries.credit(offset.0);continue 'offsets;}}@@ -288,6 +316,29 @@ fn apply_completion(in_flight: &mut VecDeque<InFlightPoll>, completion: GroupCom}}+/// Pops the front poll for its commit. A complete poll commits only when+/// workers accepted all of it and a completion covered every charged offset.+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)+}+/// Options for constructing an [`IngestionConsumer`] from pre-built parts./// Used in integration tests where the Kafka consumer is created externally.pub struct IngestionConsumerOptions {@@ -659,14 +710,7 @@ impl IngestionConsumer {}}- let poll = in_flight_polls.pop_front().expect("front is present");- if poll.accepted < poll.message_count {- return Err(Failure::Batch(anyhow::anyhow!(- "accepted {}/{} messages — not committing offsets",- poll.accepted,- poll.message_count- )));- }+ let poll = pop_committable(in_flight_polls).map_err(Failure::Batch)?;self.settle_poll(&poll.partitions);if let Some(offsets) = self.commit_sentinel.take_due() {@@ -1154,12 +1198,15 @@ mod tests {span: OffsetSpan { first, last },generation: 0,generations_version_seen: 0,- charges: Vec::new(),+ 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 {@@ -1225,6 +1272,40 @@ mod tests {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)]);++ apply_completion(&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() {+ // A compacted or transactional topic skips offsets, so a span can far+ // exceed the poll's message count.+ 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]);++ apply_completion(&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() {// A cooperative rebalance revokes one partition of a two-partition@@ -1246,6 +1327,7 @@ mod tests {delivered: 2,covered: 0,accepted: 0,+ credited: HashSet::default(),},);two.partitions@@ -1276,6 +1358,7 @@ mod tests {apply_completion(&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]@@ -1365,7 +1448,8 @@ mod tests {apply_completion(&mut in_flight, completion(1, 0, &[10, 10], 2));assert!(in_flight[0].is_complete());- let reassigned = in_flight.pop_front().unwrap();+ let reassigned = pop_committable(&mut in_flight)+ .expect("an offset credited twice still counts as credited");let retained = reassigned.partitions.get(&topic_partition).unwrap();ledger.settle(@@ -1448,6 +1532,7 @@ mod tests {delivered: (last - first + 1) as u32,covered: 0,accepted: 0,+ credited: HashSet::default(),};ledger.charge(diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rsindex c96b59e47ee0..97392fb2fa46 100644--- a/rust/ingestion-consumer/src/grpc_transport.rs+++ b/rust/ingestion-consumer/src/grpc_transport.rs@@ -15,6 +15,10 @@//! already released its keys and left the older messages to replay after//! the newer ones.//!+//! **A partial ack is not a failure.** It resolves in the same order as OK+//! and hands back the messages the worker's time budget cut off. An ack that+//! does not match its sub-batch fences the stream as a fault.+//!//! **Failure fences the whole worker stream.** A nack, stream break, or connect//! failure resolves every queued and un-acked item, in enqueue order, with a//! [`SendError`] carrying the messages back — the callers' existing@@ -34,7 +38,7 @@//! `max_in_flight_batches`, whose batches cannot complete until their sends//! resolve.-use std::collections::VecDeque;+use std::collections::{HashMap, VecDeque};use std::sync::Arc;use std::time::Duration;@@ -43,7 +47,7 @@ use dashmap::DashMap;use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_client::WorkerIngestClient;use ingestion_worker_proto::ingestion::worker::v1::{ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,- KafkaMessage, StreamHello, SubBatch, SubBatchStatus,+ KafkaMessage, MessageRef, StreamHello, SubBatch, SubBatchAck, SubBatchStatus,};use metrics::{counter, gauge, histogram};use prost::Message;@@ -53,14 +57,15 @@ use tracing::{error, info, warn};use crate::readiness;use crate::transport::{- split_by_size, FenceGuard, SendError, TransportError, DEFAULT_MAX_BODY_BYTES,+ split_by_size, FenceGuard, SendError, SendOutcome, TransportError, DEFAULT_MAX_BODY_BYTES,};use crate::types::SerializedKafkaMessage;-/// An acked chunk: the worker's accepted count, with the messages handed-/// back so a split send can reassemble the whole sub-batch on failure.+/// An acked chunk: the worker's answer, with the messages handed back so a+/// split send can reassemble the whole sub-batch on failure.struct Accepted {accepted: u32,+ unfinished: Vec<MessageRef>,messages: Vec<SerializedKafkaMessage>,}@@ -75,12 +80,16 @@ pub struct PendingWorkerStreamSend {impl PendingWorkerStreamSend {/// All-or-nothing: `Ok` only when every- /// chunk was accepted; on any failure the `SendError` carries back the- /// full original message set, in order, so the caller defers all of it.- /// Already-accepted chunks then replay, which is ordinary at-least-once.- pub async fn wait(self) -> Result<u32, SendError> {+ /// chunk was acked, fully or partially; on any failure the `SendError`+ /// carries back the full original message set, in order, so the caller+ /// defers all of it. Already-accepted chunks then replay, which is+ /// ordinary at-least-once.+ pub async fn wait(self) -> Result<SendOutcome, SendError> {let mut accepted_total = 0u32;let mut messages: Vec<SerializedKafkaMessage> = Vec::new();+ // A partition revoked and regained inside one poll delivers an offset+ // twice, so unfinished references are counted, not deduplicated.+ let mut unfinished: HashMap<(i32, i64), usize> = HashMap::new();let mut failure: Option<SendError> = None;for rx in self.chunks {let reply = match rx.await {@@ -98,6 +107,11 @@ impl PendingWorkerStreamSend {match reply {Ok(accepted) => {accepted_total += accepted.accepted;+ for message in &accepted.unfinished {+ *unfinished+ .entry((message.partition, message.offset))+ .or_default() += 1;+ }messages.extend(accepted.messages);}Err(mut err) => {@@ -116,7 +130,24 @@ impl PendingWorkerStreamSend {}}match failure {- None => Ok(accepted_total),+ None if unfinished.is_empty() => Ok(SendOutcome::Accepted(accepted_total)),+ // Callers match unfinished messages to what they sent in send+ // order, so walk the sent messages, not the worker's list.+ None => Ok(SendOutcome::Partial {+ accepted: accepted_total,+ unfinished: messages+ .into_iter()+ .filter(|message| {+ match unfinished.get_mut(&(message.partition, message.offset)) {+ Some(left) if *left > 0 => {+ *left -= 1;+ true+ }+ _ => false,+ }+ })+ .collect(),+ }),Some(mut err) => {err.messages = messages;Err(err)@@ -125,10 +156,20 @@ impl PendingWorkerStreamSend {}}+/// How one send rides the stream.+#[derive(Clone, Copy, Debug, Default)]+pub struct SendOptions {+ pub replay: bool,+ /// The worker's soft time budget. `None` sends no budget.+ pub soft_budget: Option<Duration>,+}+struct WorkerStreamItem {batch_id: String,messages: Vec<SerializedKafkaMessage>,replay: bool,+ /// `0` means no budget.+ soft_budget_ms: u64,reply: oneshot::Sender<StreamReply>,}@@ -227,6 +268,20 @@ impl GrpcTransport {batch_id: &str,messages: Vec<SerializedKafkaMessage>,replay: bool,+ ) -> PendingWorkerStreamSend {+ let options = SendOptions {+ replay,+ soft_budget: None,+ };+ self.begin_send_with(worker_url, batch_id, messages, options)+ }++ pub fn begin_send_with(+ &self,+ worker_url: &str,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ options: SendOptions,) -> PendingWorkerStreamSend {let chunks = split_by_size(messages, self.max_body_bytes);if chunks.len() > 1 {@@ -236,6 +291,16 @@ impl GrpcTransport {).increment((chunks.len() - 1) as u64);}+ // The worker runs each frame as its own batch, so in a split send a+ // key's later message could finish while an earlier one is left+ // unfinished.+ let soft_budget_ms = match options.soft_budget {+ Some(budget) if chunks.len() == 1 && !budget.is_zero() => {+ u64::try_from(budget.as_millis()).unwrap_or(u64::MAX).max(1)+ }+ _ => 0,+ };+ let replay = options.replay;let stream = self.worker_stream_for(worker_url);let receivers = chunks.into_iter()@@ -245,6 +310,7 @@ impl GrpcTransport {batch_id: batch_id.to_string(),messages,replay,+ soft_budget_ms,reply,};if let Err(send_err) = stream.tx.send(item) {@@ -322,9 +388,14 @@ struct LedgerEntry {deadline: tokio::time::Instant,/// When the sub-batch went on the wire, for the send-to-ack latency histogram.sent_at: std::time::Instant,- /// The worker's accepted count once acked. The entry stays in the ledger- /// until every earlier entry is acked too, so a fence still reaches it.- acked: Option<u32>,+ /// The worker's answer once acked. The entry stays in the ledger until+ /// every earlier entry is acked too, so a fence still reaches it.+ acked: Option<Ack>,+}++struct Ack {+ accepted: u32,+ unfinished: Vec<MessageRef>,}/// An open stream: the request sender and the worker's ack stream.@@ -548,7 +619,7 @@ impl WorkerStreamRunner {messages: item.messages.iter().map(to_proto_message).collect(),replay: item.replay,assignment_epoch: self.assignment_epoch.current(),- soft_budget_ms: 0,+ soft_budget_ms: item.soft_budget_ms,})),};// tonic gzips the frame after this point, so only the raw size is observable here.@@ -670,7 +741,8 @@ impl WorkerStreamRunner {);return Err(self.fence(None, ledger, queue, "sub-batch nacked"));}- if response.status != SubBatchStatus::Ok as i32 {+ let partial = response.status == SubBatchStatus::Partial as i32;+ if response.status != SubBatchStatus::Ok as i32 && !partial {// BUSY, or any status this consumer predates: transient// backpressure, not a fault. Fence in order (the ordered stream// cannot retry one sub-batch in place) but as retriable, so the@@ -684,19 +756,32 @@ impl WorkerStreamRunner {return Err(self.fence_with(true, None, ledger, queue, "worker busy"));}let was_full = ledger.len() >= self.max_unacked;- let Some(entry) = ledger- .iter_mut()- .find(|e| e.seq == response.seq && e.acked.is_none())+ let Some(index) = ledger+ .iter()+ .position(|e| e.seq == response.seq && e.acked.is_none())else {warn!(worker = %self.worker_url, seq = response.seq, "Ack for unknown seq — fencing worker stream");return Err(self.fence(None, ledger, queue, "unknown ack seq"));};- entry.acked = Some(response.accepted);+ if let Some(reason) = ack_shape_error(&ledger[index].item, &response) {+ warn!(+ worker = %self.worker_url,+ seq = response.seq,+ reason,+ "Malformed ack — fencing worker stream"+ );+ return Err(self.fence(None, ledger, queue, reason));+ }+ let entry = &mut ledger[index];+ entry.acked = Some(Ack {+ accepted: response.accepted,+ unfinished: response.unfinished,+ });self.record_send_duration(entry);counter!("ingestion_consumer_transport_requests_total","worker" => self.worker_url.clone(),- "status" => "ok"+ "status" => if partial { "partial" } else { "ok" }).increment(1);// Resolve only the acked prefix: a later ack waits for every earlier@@ -704,11 +789,18 @@ impl WorkerStreamRunner {// release its keys first.while ledger.front().is_some_and(|e| e.acked.is_some()) {let entry = ledger.pop_front().expect("front is present");- let accepted = entry.acked.expect("front is acked");+ let Ack {+ accepted,+ unfinished,+ } = entry.acked.expect("front is acked");let WorkerStreamItem {reply, messages, ..} = entry.item;- let _ = reply.send(Ok(Accepted { accepted, messages }));+ let _ = reply.send(Ok(Accepted {+ accepted,+ unfinished,+ messages,+ }));}if was_full && ledger.len() < self.max_unacked && !queue.is_empty() {counter!(@@ -853,6 +945,42 @@ enum StreamEnd {Idle,}+/// A worker bug that misreports what it processed would lose or double+/// complete messages, so an ack that does not match its sub-batch fences the+/// stream as a fault.+fn ack_shape_error(item: &WorkerStreamItem, ack: &SubBatchAck) -> Option<&'static str> {+ if ack.status != SubBatchStatus::Partial as i32 {+ return (!ack.unfinished.is_empty()).then_some("unfinished on a non-partial ack");+ }+ if item.soft_budget_ms == 0 {+ return Some("partial ack for an unbudgeted sub-batch");+ }+ if ack.unfinished.is_empty() {+ return Some("partial ack with no unfinished entries");+ }+ if ack.accepted as usize + ack.unfinished.len() != item.messages.len() {+ return Some("partial ack does not account for every message");+ }+ // A partition revoked and regained inside one poll delivers an offset+ // twice, so a sub-batch may carry one coordinate more than once.+ let mut carried: HashMap<(i32, i64), usize> = HashMap::with_capacity(item.messages.len());+ for message in &item.messages {+ *carried+ .entry((message.partition, message.offset))+ .or_default() += 1;+ }+ for message in &ack.unfinished {+ match carried.get_mut(&(message.partition, message.offset)) {+ Some(left) if *left > 0 => *left -= 1,+ Some(_) => {+ return Some("partial ack lists a message more often than the sub-batch carried it")+ }+ None => return Some("partial ack lists a message the sub-batch did not carry"),+ }+ }+ None+}+fn to_proto_message(message: &SerializedKafkaMessage) -> KafkaMessage {KafkaMessage {topic: message.topic.to_string(),diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex f89c7835d8d4..bedd0413cffc 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -45,6 +45,9 @@ fn main() -> Result<()> {let config = Config::init_from_env().context("Failed to load configuration from environment variables")?;+ config+ .request_budget()+ .map_err(|err| anyhow::anyhow!("invalid request budget: {err}"))?;let runtime = tokio::runtime::Builder::new_multi_thread().enable_all()diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rsindex 88143e8af2e8..bb5e78fdb244 100644--- a/rust/ingestion-consumer/src/order_sentinel.rs+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -376,6 +376,36 @@ impl Drop for SentinelBatch<'_> {}}+/// The `max_offset` to pass to [`SentinelBatch::note_acked`] for one key's+/// accepted messages, given as `(partition, offset, keyed)` in send order,+/// while `unfinished`, as `(partition, offset)` in send order, go out again.+/// `partition` is the run's first keyed partition, which `note_sent` tracks.+/// `None` when nothing may be ACKed.+pub fn ack_mark(+ partition: i32,+ accepted: impl IntoIterator<Item = (i32, i64, bool)>,+ unfinished: impl IntoIterator<Item = (i32, i64)>,+) -> Option<i64> {+ // A resent message must stay above the mark. A partition revoked and+ // regained inside one poll sends an offset twice, so send order is not+ // offset order and the lowest unfinished offset bounds the mark.+ let resend_from = unfinished+ .into_iter()+ .filter(|&(unfinished_partition, _)| unfinished_partition == partition)+ .map(|(_, offset)| offset)+ .min()+ .unwrap_or(i64::MAX);+ accepted+ .into_iter()+ // An unkeyed message lives on an arbitrary partition under a synthetic+ // key, so it does not advance the mark.+ .filter(|&(message_partition, offset, keyed)| {+ keyed && message_partition == partition && offset < resend_from+ })+ .map(|(_, offset, _)| offset)+ .max()+}+/// The consumer's rdkafka context: observes async commit results (a/// fire-and-forget `CommitMode::Async` failure is otherwise invisible until/// restart-time redelivery), forgets revoked partitions around rebalances, and@@ -638,6 +668,39 @@ mod tests {assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);}+ #[test]+ fn a_partial_acks_mark_keeps_the_resend_of_its_unfinished_message_legal() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.batch().note_sent(+ "t:a",+ &[msg_at(0, 1), msg_at(0, 2), msg_at(0, 3)],+ SendKind::Fresh,+ );+ let mark = ack_mark(+ 0,+ [(0, 1, true), (0, 3, true), (1, 9, false)],+ [(1, 8), (0, 2)],+ );+ assert_eq!(mark, Some(1));+ sentinel.batch().note_acked("t:a", mark.expect("a mark"));+ assert!(sentinel+ .batch()+ .note_sent("t:a", &[msg_at(0, 2)], SendKind::Resend)+ .is_empty());+ }++ #[test]+ fn a_redelivered_offset_keeps_the_ack_mark_below_every_unfinished_message() {+ // The run sent offset 1, 2, then 1 again, and the worker accepted the+ // first copy only, so the unfinished list runs 2 then 1.+ assert_eq!(ack_mark(0, [(0, 1, true)], [(0, 2), (0, 1)]), None);+ }++ #[test]+ fn a_run_whose_tracked_partition_is_wholly_unfinished_acks_nothing() {+ assert_eq!(ack_mark(0, [(1, 100, true)], [(0, 10)]), None);+ }+#[test]fn older_messages_after_acked_newer_ones_are_a_violation() {// The exact race the deferral machinery exists to prevent: a key'sdiff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 4d3d0f203dcc..c46b1118fd24 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -50,6 +50,18 @@ pub(crate) fn split_by_size(chunks}+/// How a send settled once the worker took it.+#[derive(Debug)]+pub enum SendOutcome {+ Accepted(u32),+ /// The worker finished every message except `unfinished`, which come back+ /// in send order.+ Partial {+ accepted: u32,+ unfinished: Vec<SerializedKafkaMessage>,+ },+}+/// Failure from a worker stream send, carrying back the sub-batch's messages/// so the caller can defer/replay them (the worker may have died mid-send and/// the messages were never accepted).diff --git a/rust/ingestion-consumer/tests/common/mod.rs b/rust/ingestion-consumer/tests/common/mod.rsindex 5e36a33074ff..d332180e8bdf 100644--- a/rust/ingestion-consumer/tests/common/mod.rs+++ b/rust/ingestion-consumer/tests/common/mod.rs@@ -8,7 +8,7 @@ use std::time::{Duration, Instant};use ingestion_consumer::batcher::packer::{PackTargets, Packer};use ingestion_consumer::batcher::retry_policy::RetryPolicy;-use ingestion_consumer::batcher::state_machine::BatcherStateMachine;+use ingestion_consumer::batcher::state_machine::{BatcherStateMachine, RequestBudget};use ingestion_consumer::batcher::worker_assigner::WorkerAssigner;use ingestion_consumer::batcher::{Batcher, BatcherOutputs};use ingestion_consumer::dispatcher::Dispatcher;@@ -29,6 +29,7 @@ pub const ONE_MESSAGE_PER_REQUEST: PackTargets = PackTargets {latency_budget: Duration::ZERO,};+#[allow(clippy::too_many_arguments)]pub fn batcher(kind: SchedulerKind,dispatcher: &Arc<Dispatcher>,@@ -37,9 +38,11 @@ pub fn batcher(stall_timeout: Duration,retry_delay: Duration,pack_targets: PackTargets,+ budget: Option<RequestBudget>,) -> (Batcher, BatcherOutputs) {match kind {SchedulerKind::PinStash => {+ debug_assert!(budget.is_none(), "pin_stash sends no budget");Batcher::new(Arc::clone(dispatcher), transport, handle, stall_timeout)}SchedulerKind::KeyTable => packing_key_table_batcher(@@ -48,6 +51,7 @@ pub fn batcher(stall_timeout,retry_delay,pack_targets,+ budget,),}}@@ -64,6 +68,7 @@ pub fn key_table_batcher(stall_timeout,retry_delay,ONE_MESSAGE_PER_REQUEST,+ None,)}@@ -73,6 +78,7 @@ fn packing_key_table_batcher(stall_timeout: Duration,retry_delay: Duration,pack_targets: PackTargets,+ budget: Option<RequestBudget>,) -> (Batcher, BatcherOutputs) {let pool_source = dispatcher.worker_pool_source();let assigner =@@ -86,6 +92,7 @@ fn packing_key_table_batcher(stall_timeout,Instant::now(),)- .expect("valid stall timeout");+ .expect("valid stall timeout")+ .with_request_budget(budget);Batcher::with_state_machine(state_machine, pool_source, transport)}diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 6e2bacb0bed5..ce56aec8d517 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -6,7 +6,7 @@mod common;use std::collections::{HashMap, HashSet};-use std::num::NonZeroUsize;+use std::num::{NonZeroU32, NonZeroUsize};use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -30,6 +30,7 @@ use uuid::Uuid;use common_kafka_consumer::{TopicOffsetLedger, TopicPartition};use ingestion_consumer::batcher::packer::PackTargets;+use ingestion_consumer::batcher::state_machine::RequestBudget;use ingestion_consumer::batcher::BatcherObserver;use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};use ingestion_consumer::discovery::reconcile_membership;@@ -47,10 +48,11 @@ use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{};use ingestion_worker_proto::ingestion::worker::v1::{ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,- StreamReady, SubBatchAck, SubBatchStatus,+ MessageRef, StreamReady, SubBatchAck, SubBatchStatus,};const KAFKA_BROKERS: &str = "localhost:9092";+const BUDGET_ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).expect("nonzero attempts");// ── Kafka helpers ──────────────────────────────────────────────────────────@@ -120,12 +122,47 @@ async fn produce_in_one_transaction(partition: i32,token: &str,records: &[(&str, usize)],+) {+ let records = records+ .iter()+ .map(|&(distinct_id, seq)| (format!("{token}:{distinct_id}"), distinct_id, seq))+ .collect::<Vec<_>>();+ let records: Vec<(i32, &str, &str, usize)> = records+ .iter()+ .map(|(key, distinct_id, seq)| (partition, key.as_str(), *distinct_id, *seq))+ .collect();+ produce_keyed_in_one_transaction(topic, token, &records).await;+}++/// Visitors A and B take turns behind one Kafka key, as cookieless visitors+/// behind one `token:ip` key do.+fn alternating_visitors(+ partition: i32,+ key: &str,+ first_seq: usize,+) -> [(i32, &str, &str, usize); 4] {+ [+ (partition, key, "visitor-a", first_seq),+ (partition, key, "visitor-b", first_seq + 1),+ (partition, key, "visitor-a", first_seq + 2),+ (partition, key, "visitor-b", first_seq + 3),+ ]+}++/// Like `produce_in_one_transaction`, with each record given as+/// `(partition, key, distinct_id, seq)`.+async fn produce_keyed_in_one_transaction(+ topic: &str,+ token: &str,+ records: &[(i32, &str, &str, usize)],) {let topic = topic.to_string();let token = token.to_string();- let records: Vec<(String, usize)> = records+ let records: Vec<(i32, String, String, usize)> = records.iter()- .map(|&(distinct_id, seq)| (distinct_id.to_string(), seq))+ .map(|&(partition, key, distinct_id, seq)| {+ (partition, key.to_string(), distinct_id.to_string(), seq)+ }).collect();// The transaction calls block, so keep them off the test's runtime thread,// which also serves the fake workers.@@ -141,8 +178,7 @@ async fn produce_in_one_transaction(.init_transactions(timeout).expect("init transactions");producer.begin_transaction().expect("begin transaction");- for (distinct_id, seq) in &records {- let key = format!("{token}:{distinct_id}");+ for (partition, key, distinct_id, seq) in &records {let value = format!(r#"{{"seq":{seq}}}"#);let headers = OwnedHeaders::new().insert(Header {@@ -156,9 +192,9 @@ async fn produce_in_one_transaction(producer.send(BaseRecord::to(&topic)- .key(&key)+ .key(key.as_str()).payload(&value)- .partition(partition)+ .partition(*partition).headers(headers),).map_err(|(err, _)| err)@@ -201,7 +237,7 @@ struct FakeWorker {pub url: String,/// (distinct_id, seq) pairs in arrival order.pub received: Arc<Mutex<Vec<(String, usize)>>>,- /// Message count of each accepted sub-batch, in arrival order. With a+ /// Message count of each acked sub-batch, in arrival order. With a/// single worker and partition a sub-batch is the whole Kafka batch, which/// is what lets the batching-bound tests read batch sizes from here.pub batch_sizes: Arc<Mutex<Vec<usize>>>,@@ -218,6 +254,15 @@ struct FakeWorker {/// When true, every sub-batch is nacked without/// ingesting anything — a poison batch this worker will never accept.pub reject_4xx: Arc<AtomicBool>,+ /// When set to `(distinct_id, frames)`, the next `frames` sub-batches with+ /// a soft budget that carry this distinct_id leave all of that id's+ /// messages unfinished. They are not recorded, and the ack is PARTIAL.+ pub leave_unfinished: Arc<Mutex<Option<(String, usize)>>>,+ /// (distinct_id, seq) pairs that arrived in a sub-batch marked as replay.+ pub replayed: Arc<Mutex<Vec<(String, usize)>>>,+ /// When true, a replay sub-batch is dropped without an ack, as a worker+ /// stuck on it would leave it.+ pub hold_replays: Arc<AtomicBool>,/// When set, the next sub-batch is ingested in full but reports one/// message fewer than sent — a partial-acceptance contract violation.pub underreport_once: Arc<AtomicBool>,@@ -256,6 +301,9 @@ impl FakeWorker {let ack_lost_once = Arc::new(AtomicBool::new(false));let reject_4xx = Arc::new(AtomicBool::new(false));let underreport_once = Arc::new(AtomicBool::new(false));+ let leave_unfinished = Arc::new(Mutex::new(None));+ let replayed = Arc::new(Mutex::new(Vec::new()));+ let hold_replays = Arc::new(AtomicBool::new(false));let arrived = Arc::new(AtomicUsize::new(0));let gate = Arc::new(tokio::sync::Mutex::new(()));@@ -301,6 +349,9 @@ impl FakeWorker {ack_lost_once: Arc::clone(&ack_lost_once),reject_4xx: Arc::clone(&reject_4xx),underreport_once: Arc::clone(&underreport_once),+ leave_unfinished: Arc::clone(&leave_unfinished),+ replayed: Arc::clone(&replayed),+ hold_replays: Arc::clone(&hold_replays),arrived: Arc::clone(&arrived),gate: Arc::clone(&gate),delivery_log,@@ -328,6 +379,9 @@ impl FakeWorker {ack_lost_once,reject_4xx,underreport_once,+ leave_unfinished,+ replayed,+ hold_replays,arrived,gate,_task: task,@@ -338,7 +392,7 @@ impl FakeWorker {self.received.lock().unwrap().len()}- /// Message count of each accepted sub-batch, in arrival order.+ /// Message count of each acked sub-batch, in arrival order.fn batch_sizes(&self) -> Vec<usize> {self.batch_sizes.lock().unwrap().clone()}@@ -375,6 +429,9 @@ struct FakeWorkerGrpc {ack_lost_once: Arc<AtomicBool>,reject_4xx: Arc<AtomicBool>,underreport_once: Arc<AtomicBool>,+ leave_unfinished: Arc<Mutex<Option<(String, usize)>>>,+ replayed: Arc<Mutex<Vec<(String, usize)>>>,+ hold_replays: Arc<AtomicBool>,arrived: Arc<AtomicUsize>,gate: Arc<tokio::sync::Mutex<()>>,delivery_log: Option<DeliveryLog>,@@ -399,6 +456,9 @@ impl WorkerIngestService for FakeWorkerGrpc {let ack_lost_once = Arc::clone(&self.ack_lost_once);let reject_4xx = Arc::clone(&self.reject_4xx);let underreport_once = Arc::clone(&self.underreport_once);+ let leave_unfinished = Arc::clone(&self.leave_unfinished);+ let replayed = Arc::clone(&self.replayed);+ let hold_replays = Arc::clone(&self.hold_replays);let arrived = Arc::clone(&self.arrived);let gate = Arc::clone(&self.gate);let delivery_log = self.delivery_log.clone();@@ -439,6 +499,9 @@ impl WorkerIngestService for FakeWorkerGrpc {nack(&tx, sub_batch.seq, "poison batch");return;}+ if sub_batch.replay && hold_replays.load(Ordering::SeqCst) {+ continue;+ }let entries: Vec<(String, usize)> = sub_batch.messages.iter()@@ -453,10 +516,55 @@ impl WorkerIngestService for FakeWorkerGrpc {(did, seq)}).collect();- received.lock().unwrap().extend(entries.iter().cloned());+ let unfinished_id = if sub_batch.soft_budget_ms > 0 {+ leave_unfinished+ .lock()+ .unwrap()+ .as_ref()+ .map(|(id, _)| id.clone())+ } else {+ None+ };+ let mut done = Vec::new();+ let mut unfinished = Vec::new();+ for (message, entry) in sub_batch.messages.iter().zip(entries) {+ if unfinished_id.as_deref() == Some(entry.0.as_str()) {+ unfinished.push(MessageRef {+ partition: message.partition,+ offset: message.offset,+ });+ } else {+ done.push(entry);+ }+ }+ if sub_batch.replay {+ replayed.lock().unwrap().extend(done.iter().cloned());+ }+ received.lock().unwrap().extend(done.iter().cloned());batch_sizes.lock().unwrap().push(sub_batch.messages.len());if let Some(log) = &delivery_log {- log.lock().unwrap().extend(entries);+ log.lock().unwrap().extend(done.iter().cloned());+ }+ if !unfinished.is_empty() {+ let mut frames_left = leave_unfinished.lock().unwrap();+ let used_up = frames_left.as_mut().is_some_and(|(_, frames)| {+ *frames -= 1;+ *frames == 0+ });+ if used_up {+ *frames_left = None;+ }+ drop(frames_left);+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq: sub_batch.seq,+ status: SubBatchStatus::Partial as i32,+ accepted: done.len() as u32,+ error: String::new(),+ unfinished,+ })),+ }));+ continue;}// Work done and recorded, but the ACK is lost: fail the stream// so the consumer fences and replays.@@ -508,6 +616,7 @@ struct Harness {max_in_flight: usize,deferred_flush_timeout: Duration,pack_targets: PackTargets,+ budget: Option<RequestBudget>,}/// Build a Kafka consumer subscribed to `topic` in `group_id`, configured like@@ -607,6 +716,38 @@ impl Harness {0,ComponentOptions::new(),common::PRODUCTION_PACK_TARGETS,+ None,+ )+ .await+ }++ /// One key-table consumer with one worker, sending a soft budget on every+ /// request except an escalated key's resend.+ async fn start_budgeted(topic: &str, partitions: i32) -> Self {+ Self::start_inner(+ SchedulerKind::KeyTable,+ 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,+ ComponentOptions::new(),+ // A request waits for four events per partition, which one+ // `alternating_visitors` call per partition fills.+ PackTargets {+ events: NonZeroUsize::new(4 * partitions as usize),+ bytes: None,+ latency_budget: Duration::from_secs(5),+ },+ Some(RequestBudget {+ soft_budget: Duration::from_millis(500),+ attempts: BUDGET_ATTEMPTS,+ }),).await}@@ -633,6 +774,7 @@ impl Harness {0,ComponentOptions::new(),pack_targets,+ None,).await}@@ -658,6 +800,7 @@ impl Harness {.with_liveness_deadline(liveness_deadline).with_stall_threshold(stall_threshold),common::ONE_MESSAGE_PER_REQUEST,+ None,).await}@@ -677,6 +820,7 @@ impl Harness {batch_size_bytes,ComponentOptions::new(),common::PRODUCTION_PACK_TARGETS,+ None,).await}@@ -693,6 +837,7 @@ impl Harness {batch_size_bytes: usize,component_options: ComponentOptions,pack_targets: PackTargets,+ budget: Option<RequestBudget>,) -> Self {create_topic(topic, partitions).await;@@ -735,6 +880,7 @@ impl Harness {deferred_flush_timeout,Duration::from_millis(200),pack_targets,+ budget,);let consumer = IngestionConsumer::from_parts(kafka_consumer,@@ -780,6 +926,7 @@ impl Harness {max_in_flight,deferred_flush_timeout,pack_targets,+ budget,}}@@ -824,6 +971,7 @@ impl Harness {self.deferred_flush_timeout,Duration::from_millis(200),self.pack_targets,+ self.budget,);let consumer = IngestionConsumer::from_parts(kafka_consumer,@@ -905,6 +1053,71 @@ impl Harness {let _ = tokio::time::timeout(Duration::from_secs(3), task).await;}}++ /// A second consumer in the same group, configured like the first, with+ /// its own routing stack and the same worker pool, as a second pod would be.+ async fn join_second_consumer(&self) -> SecondConsumer {+ let worker_urls: Vec<String> = self.workers.iter().map(|w| w.url.clone()).collect();+ let registry = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));+ let probe = CancellationToken::new();+ Arc::clone(®istry).start_probing(probe.clone());+ let dispatcher = Arc::new(Dispatcher::with_strategy(+ Arc::clone(®istry),+ RoutingStrategy::default(),+ ));+ let transport = Arc::new(test_transport());+ let mut manager = Manager::builder("e2e-c2").with_trap_signals(false).build();+ let handle = manager.register("consumer", ComponentOptions::new());+ let shutdown = handle.shutdown_token();+ let (batcher, outputs) = common::batcher(+ self.scheduler,+ &dispatcher,+ Arc::clone(&transport),+ handle.clone(),+ self.deferred_flush_timeout,+ Duration::from_millis(200),+ self.pack_targets,+ self.budget,+ );+ let consumer = IngestionConsumer::from_parts(+ make_kafka_consumer(&self.topic, &self.group_id, None),+ batcher,+ outputs,+ transport,+ worker_urls,+ IngestionConsumerOptions {+ 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,+ },+ handle,+ );+ let task = tokio::spawn(async move { consumer.process().await });+ SecondConsumer {+ shutdown,+ probe,+ task,+ _manager: manager,+ }+ }+}++struct SecondConsumer {+ shutdown: CancellationToken,+ probe: CancellationToken,+ task: tokio::task::JoinHandle<()>,+ _manager: Manager,+}++impl SecondConsumer {+ async fn stop(self) {+ self.shutdown.cancel();+ let _ = tokio::time::timeout(Duration::from_secs(5), self.task).await;+ self.probe.cancel();+ }}fn fast_registry_config() -> WorkerRegistryConfig {@@ -1014,6 +1227,262 @@ async fn messages_per_distinct_id_arrive_in_order(harness.stop().await;}+/// A partial ack redelivers only the messages the worker left unfinished. One+/// Kafka key carries two distinct ids, as a cookieless `token:ip` key does, and+/// the worker leaves one distinct id's messages unfinished while it finishes+/// the other's, so the unfinished messages are not the last of their key.+#[tokio::test]+async fn a_partial_ack_redelivers_only_the_unfinished_messages() {+ let topic = format!("e2e-partial-{}", Uuid::new_v4());+ let harness = Harness::start_budgeted(&topic, 1).await;+ *harness.workers[0].leave_unfinished.lock().unwrap() = Some(("visitor-a".to_string(), 1));++ produce_keyed_in_one_transaction(+ &topic,+ "tok",+ &alternating_visitors(0, "tok:203.0.113.7", 0),+ )+ .await;+ // A commit means every resend settled, so a late duplicate is in the log.+ wait_until(Duration::from_secs(15), "the offsets commit", || {+ harness+ .committed_offset(0)+ .is_some_and(|offset| offset >= 4)+ })+ .await;++ let worker = &harness.workers[0];+ assert_eq!(+ worker.batch_sizes()[0],+ 4,+ "all four messages ride one request: sizes {:?}",+ worker.batch_sizes()+ );+ assert_eq!(worker.seqs_for("visitor-a"), vec![0, 2]);+ assert_eq!(worker.seqs_for("visitor-b"), vec![1, 3]);+ assert_eq!(+ *worker.replayed.lock().unwrap(),+ vec![("visitor-a".to_string(), 0), ("visitor-a".to_string(), 2)],+ "only the unfinished messages are redelivered, marked as replay"+ );++ harness.stop().await;+}++/// A consumer crash after a partial ack, while its resend is unacked, loses+/// none of the unfinished messages. The partial ack completed the poll's other+/// messages, so a commit past an unfinished offset would skip it on restart.+#[tokio::test]+async fn a_crash_before_a_partial_acks_resend_loses_nothing() {+ let topic = format!("e2e-partial-crash-{}", Uuid::new_v4());+ let mut harness = Harness::start_budgeted(&topic, 1).await;+ *harness.workers[0].leave_unfinished.lock().unwrap() = Some(("visitor-a".to_string(), 1));+ // The resend never settles, so it is still in flight at the crash.+ harness.workers[0]+ .hold_replays+ .store(true, Ordering::SeqCst);++ produce_keyed_in_one_transaction(+ &topic,+ "tok",+ &alternating_visitors(0, "tok:203.0.113.7", 0),+ )+ .await;+ wait_until(+ Duration::from_secs(15),+ "the resend to reach the worker",+ || harness.workers[0].arrived_count() >= 2,+ )+ .await;+ assert!(+ harness.workers[0].seqs_for("visitor-a").is_empty(),+ "visitor A's messages are unfinished"+ );++ // The consumer commits asynchronously, so a wrong commit can land after+ // the crash and go unseen by the restart.+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert_eq!(+ harness.committed_offset(0),+ None,+ "nothing commits while an unfinished message waits for its resend"+ );++ harness.crash_consumer();+ harness.restart_consumer(fast_registry_config()).await;++ wait_until(+ Duration::from_secs(30),+ "the offsets to commit after the restart",+ || {+ harness+ .committed_offset(0)+ .is_some_and(|offset| offset >= 4)+ },+ )+ .await;+ assert_eq!(+ harness.workers[0].seqs_for("visitor-a"),+ vec![0, 2],+ "the restarted consumer delivers the unfinished messages"+ );++ harness.stop().await;+}++/// A partial ack that arrives after its partition was revoked resends nothing.+/// The new owner replays the partition from its committed offset, so a resend+/// by the old owner would deliver the unfinished messages twice.+#[tokio::test]+async fn a_partial_ack_after_a_revoke_resends_nothing() {+ let topic = format!("e2e-partial-revoke-{}", Uuid::new_v4());+ let harness = Harness::start_budgeted(&topic, 2).await;+ *harness.workers[0].leave_unfinished.lock().unwrap() = Some(("visitor-a".to_string(), 1));+ let partitions = [+ TopicPartition::new(topic.clone(), 0),+ TopicPartition::new(topic.clone(), 1),+ ];+ let records: Vec<_> = alternating_visitors(0, "tok:203.0.113.7", 0)+ .into_iter()+ .chain(alternating_visitors(1, "tok:203.0.113.8", 10))+ .collect();++ // The consumer stops polling Kafka after an empty poll while a poll is in+ // flight, and only a polling consumer takes part in a rebalance, so a+ // trickle keeps it polling. A cold producer's first send can miss the+ // first 100 ms poll window, so the producer connects first.+ let producer = make_producer();+ producer+ .client()+ .fetch_metadata(Some(&topic), Duration::from_secs(5))+ .expect("trickle producer metadata");++ // Hold the first request in flight across the rebalance. The worker stream+ // keeps one request unacked, so the trickle's requests wait behind it.+ let gate = harness.workers[0].block().await;+ produce_keyed_in_one_transaction(&topic, "tok", &records).await;+ let trickling = Arc::new(AtomicBool::new(true));+ let trickle = tokio::spawn({+ let trickling = Arc::clone(&trickling);+ let topic = topic.clone();+ async move {+ let mut seq = 1000usize;+ while trickling.load(Ordering::SeqCst) {+ produce(&producer, &topic, 0, "tok", "trickle", seq).await;+ seq += 1;+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ }+ });+ wait_until(+ Duration::from_secs(15),+ "a request to reach the worker",+ || harness.workers[0].arrived_count() > 0,+ )+ .await;+ let generations: Vec<u64> = partitions+ .iter()+ .map(|partition| harness.ledger.generation(partition))+ .collect();++ let second = harness.join_second_consumer().await;++ // An eager rebalance revokes both of the first consumer's partitions. The+ // held request fences at the transport's 10 s ack timeout and comes back+ // as a replay, so the rebalance must land first.+ wait_until(+ Duration::from_secs(8),+ "the rebalance to revoke both partitions",+ || {+ partitions+ .iter()+ .zip(&generations)+ .all(|(partition, before)| harness.ledger.generation(partition) > *before)+ },+ )+ .await;+ trickling.store(false, Ordering::SeqCst);+ trickle.await.expect("trickle task");+ drop(gate);++ wait_until(+ Duration::from_secs(30),+ "every message to be delivered",+ || {+ let delivered: HashSet<(String, usize)> = harness+ .delivery_log+ .lock()+ .unwrap()+ .iter()+ .cloned()+ .collect();+ records+ .iter()+ .all(|(_, _, visitor, seq)| delivered.contains(&(visitor.to_string(), *seq)))+ },+ )+ .await;+ // The new owner delivers everything on its own, so the old owner may not+ // have settled the partial ack yet. A wrong resend would be in flight.+ wait_until(+ Duration::from_secs(15),+ "the old owner to settle the partial ack",+ || harness.observer.total_in_flight() == 0,+ )+ .await;+ assert!(+ harness.workers[0]+ .leave_unfinished+ .lock()+ .unwrap()+ .is_none(),+ "the held request was acked as partial"+ );+ assert_eq!(+ *harness.workers[0].replayed.lock().unwrap(),+ Vec::<(String, usize)>::new(),+ "the old owner resends nothing for a revoked partition"+ );++ second.stop().await;+ harness.stop().await;+}++/// A message that never fits the budget still lands. Its budgeted resend+/// finishes nothing, so the next goes out without a budget, and the partition+/// commits.+#[tokio::test]+async fn a_message_that_never_fits_the_budget_lands_without_one() {+ let topic = format!("e2e-partial-escalate-{}", Uuid::new_v4());+ let harness = Harness::start_budgeted(&topic, 1).await;+ *harness.workers[0].leave_unfinished.lock().unwrap() =+ Some(("visitor-a".to_string(), usize::MAX));++ produce_keyed_in_one_transaction(+ &topic,+ "tok",+ &alternating_visitors(0, "tok:203.0.113.7", 0),+ )+ .await;+ wait_until(Duration::from_secs(15), "the offsets commit", || {+ harness+ .committed_offset(0)+ .is_some_and(|offset| offset >= 4)+ })+ .await;++ let worker = &harness.workers[0];+ assert_eq!(worker.seqs_for("visitor-a"), vec![0, 2]);+ assert_eq!(worker.seqs_for("visitor-b"), vec![1, 3]);+ assert_eq!(+ worker.batch_sizes(),+ vec![4, 2, 2],+ "visitor A goes out once more with a budget, then once without"+ );++ harness.stop().await;+}+/// The byte bound ends collection before the count bound when payloads are/// large, so batch memory tracks bytes rather than event count.///@@ -2827,46 +3296,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind:}).await;- // A second consumer joins the same group with its own routing stack but- // the same worker pool.- let worker_urls: Vec<String> = harness.workers.iter().map(|w| w.url.clone()).collect();- let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));- let probe2 = CancellationToken::new();- Arc::clone(®istry2).start_probing(probe2.clone());- let dispatcher2 = Arc::new(Dispatcher::with_strategy(- Arc::clone(®istry2),- RoutingStrategy::default(),- ));- let transport2 = Arc::new(test_transport());- let mut manager2 = Manager::builder("e2e-c2").with_trap_signals(false).build();- let handle2 = manager2.register("consumer", ComponentOptions::new());- let shutdown2 = handle2.shutdown_token();- let (batcher, outputs) = common::batcher(- kind,- &dispatcher2,- Arc::clone(&transport2),- handle2.clone(),- Duration::from_secs(60),- Duration::from_millis(200),- common::PRODUCTION_PACK_TARGETS,- );- let consumer2 = IngestionConsumer::from_parts(- make_kafka_consumer(&topic, &harness.group_id, None),- batcher,- outputs,- transport2,- worker_urls,- IngestionConsumerOptions {- 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,- },- handle2,- );- let task2 = tokio::spawn(async move { consumer2.process().await });+ let second = harness.join_second_consumer().await;// Release the held batch so the first consumer resumes polling and the// rebalance can complete, then keep traffic flowing on both partitions.@@ -2893,9 +3323,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind:).await;- shutdown2.cancel();- let _ = tokio::time::timeout(Duration::from_secs(3), task2).await;- probe2.cancel();+ second.stop().await;harness.stop().await;}@@ -2950,46 +3378,7 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche.collect();// A second consumer joins and takes a partition away.- let worker_urls: Vec<String> = harness.workers.iter().map(|w| w.url.clone()).collect();- let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));- let probe2 = CancellationToken::new();- Arc::clone(®istry2).start_probing(probe2.clone());- let dispatcher2 = Arc::new(Dispatcher::with_strategy(- Arc::clone(®istry2),- RoutingStrategy::default(),- ));- let transport2 = Arc::new(test_transport());- let mut manager2 = Manager::builder("e2e-regain-c2")- .with_trap_signals(false)- .build();- let handle2 = manager2.register("consumer", ComponentOptions::new());- let shutdown2 = handle2.shutdown_token();- let (batcher, outputs) = common::batcher(- kind,- &dispatcher2,- Arc::clone(&transport2),- handle2.clone(),- Duration::from_secs(60),- Duration::from_millis(200),- common::PRODUCTION_PACK_TARGETS,- );- let consumer2 = IngestionConsumer::from_parts(- make_kafka_consumer(&topic, &harness.group_id, None),- batcher,- outputs,- transport2,- worker_urls,- IngestionConsumerOptions {- 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,- },- handle2,- );- let task2 = tokio::spawn(async move { consumer2.process().await });+ let second = harness.join_second_consumer().await;// The first consumer polls only while its polls return messages, and// only a polling consumer takes part in a rebalance: a trickle holds it@@ -3038,9 +3427,7 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche// The second consumer leaves; its partition returns to the first under a// new generation and must consume as a fresh assignment.- shutdown2.cancel();- let _ = tokio::time::timeout(Duration::from_secs(5), task2).await;- probe2.cancel();+ second.stop().await;for seq in 10..15usize {produce(&producer, &topic, 0, "tok", "user-1", seq).await;@@ -3100,6 +3487,7 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)Duration::from_secs(60),Duration::from_millis(200),common::PRODUCTION_PACK_TARGETS,+ None,);let consumer = IngestionConsumer::from_parts(make_kafka_consumer(&topic, &group, Some("pod-1")),diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rsindex 904eb731450c..6b4627e1bc8e 100644--- a/rust/ingestion-consumer/tests/grpc_transport_test.rs+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs@@ -16,9 +16,9 @@ use std::time::Duration;use common::key_table_batcher;use common_kafka_consumer::Partition;use ingestion_consumer::dispatcher::Dispatcher;-use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};+use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport, SendOptions};use ingestion_consumer::routing::RoutingStrategy;-use ingestion_consumer::transport::TransportError;+use ingestion_consumer::transport::{SendOutcome, TransportError};use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{@@ -26,8 +26,9 @@ use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{};use ingestion_worker_proto::ingestion::worker::v1::{ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,- StreamReady, SubBatch, SubBatchAck, SubBatchStatus,+ MessageRef, StreamReady, SubBatch, SubBatchAck, SubBatchStatus,};+use rstest::rstest;use tokio::sync::{mpsc, oneshot, Mutex};use tokio_stream::wrappers::UnboundedReceiverStream;use tokio_stream::StreamExt;@@ -50,10 +51,10 @@ enum AckMode {}/// Manual mode: the test drives the worker's acks through this.-#[derive(Clone, Copy)]enum ManualAck {Ok { seq: u64, accepted: u32 },Nack(u64),+ Ack(SubBatchAck),}type ManualAcks = Arc<Mutex<Option<mpsc::UnboundedReceiver<ManualAck>>>>;@@ -107,6 +108,7 @@ impl WorkerIngest for MockWorker {error: "poisoned".to_string(),unfinished: vec![],},+ ManualAck::Ack(ack) => ack,};let _ = tx.send(Ok(IngestStreamResponse {msg: Some(ingest_stream_response::Msg::Ack(ack)),@@ -277,8 +279,11 @@ async fn sub_batches_reach_the_worker_in_enqueue_order() {.map(|i| transport.begin_send(&url, &format!("batch-{i}"), vec![msg("d1", i)], false)).collect();for (i, p) in pending.into_iter().enumerate() {- let accepted = p.wait().await.expect("send should succeed");- assert_eq!(accepted, 1, "sub-batch {i}");+ let outcome = p.wait().await.expect("send should succeed");+ assert!(+ matches!(outcome, SendOutcome::Accepted(1)),+ "sub-batch {i}: {outcome:?}"+ );}let received = mock.received.lock().await;@@ -324,8 +329,14 @@ async fn out_of_order_acks_resolve_the_right_sends() {accepted: 2,}).unwrap();- assert_eq!(first.wait().await.expect("first ack"), 2);- assert_eq!(second.await.unwrap().expect("second ack"), 1);+ assert!(matches!(+ first.wait().await.expect("first ack"),+ SendOutcome::Accepted(2)+ ));+ assert!(matches!(+ second.await.unwrap().expect("second ack"),+ SendOutcome::Accepted(1)+ ));}async fn wait_for_received(mock: &MockHandle, count: usize) {@@ -339,8 +350,237 @@ async fn wait_for_received(mock: &MockHandle, count: usize) {}}+const BUDGET: Duration = Duration::from_millis(250);++fn partial_ack(seq: u64, accepted: u32, unfinished: &[i64]) -> SubBatchAck {+ SubBatchAck {+ seq,+ status: SubBatchStatus::Partial as i32,+ accepted,+ error: String::new(),+ unfinished: unfinished+ .iter()+ .map(|&offset| MessageRef {+ partition: 0,+ offset,+ })+ .collect(),+ }+}++#[tokio::test]+async fn a_partial_ack_resolves_the_send_without_fencing_the_stream() {+ let (ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);+ let budgeted = SendOptions {+ replay: false,+ soft_budget: Some(BUDGET),+ };++ let pending = transport.begin_send_with(+ &url,+ "batch-1",+ vec![msg("d1", 1), msg("d2", 2), msg("d1", 3)],+ budgeted,+ );+ wait_for_received(&mock, 1).await;+ // The worker lists its unfinished messages in its own order.+ ack_tx+ .send(ManualAck::Ack(partial_ack(1, 1, &[3, 1])))+ .unwrap();+ match pending+ .wait()+ .await+ .expect("a partial ack is not a failure")+ {+ SendOutcome::Partial {+ accepted,+ unfinished,+ } => {+ assert_eq!(accepted, 1);+ let offsets: Vec<i64> = unfinished.iter().map(|message| message.offset).collect();+ assert_eq!(+ offsets,+ vec![1, 3],+ "unfinished messages come back in send order"+ );+ }+ other => panic!("expected a partial outcome, got {other:?}"),+ }++ let next = transport.begin_send(&url, "batch-2", vec![msg("d1", 4)], false);+ wait_for_received(&mock, 2).await;+ ack_tx+ .send(ManualAck::Ok {+ seq: 2,+ accepted: 1,+ })+ .unwrap();+ assert!(matches!(+ next.wait().await.expect("the stream stays up"),+ SendOutcome::Accepted(1)+ ));+ assert_eq!(mock.hellos.lock().await.len(), 1, "no reconnect");+}++#[rstest]+#[case::both_copies_unfinished(partial_ack(1, 0, &[1, 1]), vec![1, 1])]+#[case::one_copy_unfinished(partial_ack(1, 1, &[1]), vec![1])]+#[tokio::test]+async fn a_partial_ack_counts_a_message_the_sub_batch_carries_twice(+ #[case] ack: SubBatchAck,+ #[case] expected_unfinished: Vec<i64>,+) {+ let (ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);+ let budgeted = SendOptions {+ replay: false,+ soft_budget: Some(BUDGET),+ };++ let pending =+ transport.begin_send_with(&url, "batch-1", vec![msg("d1", 1), msg("d1", 1)], budgeted);+ wait_for_received(&mock, 1).await;+ ack_tx.send(ManualAck::Ack(ack)).unwrap();++ match pending+ .wait()+ .await+ .expect("a partial ack is not a failure")+ {+ SendOutcome::Partial {+ accepted,+ unfinished,+ } => {+ let offsets: Vec<i64> = unfinished.iter().map(|message| message.offset).collect();+ assert_eq!(offsets, expected_unfinished);+ assert_eq!(+ accepted as usize + offsets.len(),+ 2,+ "each copy is either accepted or unfinished"+ );+ }+ other => panic!("expected a partial outcome, got {other:?}"),+ }+}++#[rstest]+#[case::partial_without_a_budget(None, partial_ack(1, 1, &[1]))]+#[case::partial_with_no_unfinished_messages(Some(BUDGET), partial_ack(1, 2, &[]))]+#[case::partial_listing_a_message_not_sent(Some(BUDGET), partial_ack(1, 1, &[9]))]+#[case::partial_listing_the_offset_on_another_partition(+ Some(BUDGET),+ SubBatchAck { unfinished: vec![MessageRef { partition: 1, offset: 1 }], ..partial_ack(1, 1, &[]) }+)]+#[case::partial_listing_a_message_more_often_than_carried(Some(BUDGET), partial_ack(1, 0, &[1, 1]))]+#[case::partial_missing_a_message(Some(BUDGET), partial_ack(1, 0, &[1]))]+#[case::unfinished_messages_on_an_ok_ack(+ Some(BUDGET),+ SubBatchAck { status: SubBatchStatus::Ok as i32, ..partial_ack(1, 2, &[1]) }+)]#[tokio::test]-async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked() {+async fn a_malformed_ack_fences_the_stream_as_a_fault(+ #[case] soft_budget: Option<Duration>,+ #[case] ack: SubBatchAck,+) {+ let (ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);+ let options = SendOptions {+ replay: false,+ soft_budget,+ };+ let pending =+ transport.begin_send_with(&url, "batch-1", vec![msg("d1", 1), msg("d1", 2)], options);+ wait_for_received(&mock, 1).await;++ ack_tx.send(ManualAck::Ack(ack)).unwrap();+ let error = pending+ .wait()+ .await+ .expect_err("a malformed ack fails the send");+ assert!(+ matches!(error.error, TransportError::WorkerStreamFailed(_)),+ "{:?}",+ error.error+ );+ assert_eq!(+ error.messages.len(),+ 2,+ "every message comes back for a retry"+ );+}++#[rstest]+#[case::a_single_frame_carries_the_budget(1_000, Some(BUDGET), vec![250])]+#[case::a_split_send_carries_no_budget(200, Some(BUDGET), vec![0, 0, 0])]+#[case::no_budget_carries_none(1_000, None, vec![0])]+#[case::a_zero_budget_carries_none(1_000, Some(Duration::ZERO), vec![0])]+#[case::a_sub_millisecond_budget_rounds_up(1_000, Some(Duration::from_micros(500)), vec![1])]+#[tokio::test]+async fn a_budget_rides_only_a_single_frame_send(+ #[case] max_body_bytes: usize,+ #[case] soft_budget: Option<Duration>,+ #[case] frame_budgets: Vec<u64>,+) {+ let mock = start_mock(AckMode::Immediate, None).await;+ let mut transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 4,+ Duration::from_secs(30),+ );+ transport.set_max_body_bytes(max_body_bytes);+ let url = worker_url(mock.addr);+ let options = SendOptions {+ replay: false,+ soft_budget,+ };++ transport+ .begin_send_with(+ &url,+ "batch-1",+ vec![msg("d1", 1), msg("d1", 2), msg("d1", 3)],+ options,+ )+ .wait()+ .await+ .expect("the worker accepts every frame");++ let budgets: Vec<u64> = mock+ .received+ .lock()+ .await+ .iter()+ .map(|sub_batch| sub_batch.soft_budget_ms)+ .collect();+ assert_eq!(budgets, frame_budgets);+}++#[rstest]+#[case::ok(ManualAck::Ok { seq: 2, accepted: 2 })]+#[case::partial(ManualAck::Ack(partial_ack(2, 1, &[3])))]+#[tokio::test]+async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked(+ #[case] second_ack: ManualAck,+) {// Regression: with more than one un-acked sub-batch, the worker may ack// seq 2 before seq 1. If seq 2 resolved on its own ack, its caller would// release its keys and never replay it, while seq 1's later failure@@ -354,17 +594,17 @@ async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked() {Duration::from_secs(30),);let url = worker_url(mock.addr);+ let budgeted = SendOptions {+ replay: false,+ soft_budget: Some(BUDGET),+ };let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);- let second = transport.begin_send(&url, "batch-2", vec![msg("d1", 2)], false);+ let second =+ transport.begin_send_with(&url, "batch-2", vec![msg("d1", 2), msg("d1", 3)], budgeted);wait_for_received(&mock, 2).await;- ack_tx- .send(ManualAck::Ok {- seq: 2,- accepted: 1,- })- .unwrap();+ ack_tx.send(second_ack).unwrap();let second = tokio::spawn(second.wait());tokio::time::sleep(Duration::from_millis(200)).await;assert!(!second.is_finished(), "seq 2 must wait for seq 1");@@ -380,10 +620,12 @@ async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked() {.await.unwrap().expect_err("an acked send behind a failure must fence with it");- assert_eq!(- second_err.messages[0].offset, 2,- "messages come back for deferral"- );+ let offsets: Vec<i64> = second_err+ .messages+ .iter()+ .map(|message| message.offset)+ .collect();+ assert_eq!(offsets, vec![2, 3], "every message comes back for deferral");}#[tokio::test]@@ -461,8 +703,11 @@ async fn an_oversized_sub_batch_rides_the_stream_as_ordered_chunks() {vec![msg("d1", 1), msg("d1", 2), msg("d1", 3)],false,);- let accepted = pending.wait().await.expect("all chunks accepted");- assert_eq!(accepted, 3, "accepted counts sum across chunks");+ let outcome = pending.wait().await.expect("all chunks accepted");+ assert!(+ matches!(outcome, SendOutcome::Accepted(3)),+ "accepted counts sum across chunks: {outcome:?}"+ );let received = mock.received.lock().await;let frames: Vec<(u64, &str, Vec<i64>)> = received