Skip to content

: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.

perf(cohorts): implement ledger and decouple consume produce (#68804)

Matheus Batistac1d036b9d245
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index fee16b217d9e..387b46e6a8ef 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2173,15 +2173,19 @@ dependencies = [
"common-liveness",
"common-types",
"envconfig",
+ "futures",
"lifecycle",
"metrics",
"metrics-exporter-prometheus",
+ "proptest",
"rand 0.8.5",
"rdkafka",
"serde",
"serde_json",
"sqlx",
+ "thiserror 2.0.18",
"tokio",
+ "tokio-util",
"tracing",
"tracing-subscriber",
"uuid",
diff --git a/rust/cohort-event-shuffler/Cargo.toml b/rust/cohort-event-shuffler/Cargo.toml
index 651060d744e7..a4a8461843e1 100644
--- a/rust/cohort-event-shuffler/Cargo.toml
+++ b/rust/cohort-event-shuffler/Cargo.toml
@@ -16,6 +16,7 @@ common-kafka = { path = "../common/kafka" }
common-liveness = { path = "../common/liveness" }
common-types = { path = "../common/types" }
envconfig = { workspace = true }
+futures = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
@@ -24,7 +25,12 @@ rdkafka = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
uuid = { workspace = true }
+
+[dev-dependencies]
+proptest = "1"
+tokio-util = { workspace = true }
diff --git a/rust/cohort-event-shuffler/src/config.rs b/rust/cohort-event-shuffler/src/config.rs
index 63e0ceae12e9..74f256e3f993 100644
--- a/rust/cohort-event-shuffler/src/config.rs
+++ b/rust/cohort-event-shuffler/src/config.rs
@@ -7,6 +7,8 @@ use common_kafka::config::{ConsumerConfig, KafkaConfig};
use common_types::cohort::TeamAllowlist;
use envconfig::Envconfig;
+use crate::consumer::ShufflerSettings;
+
const POOL_NAME: &str = "posthog_cohort";
#[derive(Envconfig, Clone, Debug)]
@@ -80,11 +82,36 @@ pub struct Config {
#[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]
pub team_allowlist: TeamAllowlist,
- #[envconfig(default = "1000")]
- pub recv_batch_size: usize,
+ /// Cap on unresolved forwards; intake pauses here while acks and commits keep draining. Sized
+ /// so this count cap — not librdkafka's `kafka_producer_queue_mib` byte queue — is the binding
+ /// backpressure limit: at the 64 MiB queue default it stays under the byte budget for forwards
+ /// up to ~16 KiB serialized, so a slow-ack burst pauses intake cleanly instead of spilling into
+ /// the churnier `QueueFull` retry path. Larger-event bursts still fall back to that path. Keep
+ /// the two knobs in step (`max_inflight_forwards × avg_forward_bytes ≲ kafka_producer_queue_mib`)
+ /// so the in-flight gate stays the one that actually governs. Steady state sits in the low
+ /// hundreds, far below this ceiling.
+ #[envconfig(default = "4000")]
+ pub max_inflight_forwards: usize,
+
+ /// Also bounds the crash-replay window: interval × consume rate events per pod, deduped
+ /// downstream via `source_partition`/`source_offset`.
+ #[envconfig(default = "5000")]
+ pub commit_interval_ms: u64,
+
+ /// Base of the capped-exponential backoff when the producer queue is full.
+ #[envconfig(default = "100")]
+ pub queue_full_backoff_ms: u64,
- #[envconfig(default = "500")]
- pub recv_batch_timeout_ms: u64,
+ /// WarpStream-recommended linger.
+ #[envconfig(default = "100")]
+ pub kafka_producer_linger_ms: u32,
+
+ /// OOM guard: librdkafka's buffer must stay far below the 1Gi pod limit.
+ #[envconfig(default = "64")]
+ pub kafka_producer_queue_mib: u32,
+
+ #[envconfig(default = "100000")]
+ pub kafka_producer_queue_messages: u32,
}
impl Config {
@@ -92,8 +119,12 @@ impl Config {
format!("{}:{}", self.bind_host, self.bind_port)
}
- pub fn recv_batch_timeout(&self) -> Duration {
- Duration::from_millis(self.recv_batch_timeout_ms)
+ pub fn shuffler_settings(&self) -> ShufflerSettings {
+ ShufflerSettings {
+ max_inflight_forwards: self.max_inflight_forwards,
+ commit_interval: Duration::from_millis(self.commit_interval_ms),
+ queue_full_backoff: Duration::from_millis(self.queue_full_backoff_ms),
+ }
}
pub fn team_index_refresh_interval(&self) -> Duration {
@@ -128,12 +159,18 @@ impl Config {
kafka_client_id: self.kafka_client_id.clone(),
kafka_compression_codec: self.kafka_compression_codec.clone(),
kafka_producer_partitioner: Some(self.kafka_producer_partitioner.clone()),
- kafka_producer_linger_ms: 20,
- kafka_producer_queue_mib: 400,
- kafka_producer_queue_messages: 10_000_000,
+ kafka_producer_linger_ms: self.kafka_producer_linger_ms,
+ kafka_producer_queue_mib: self.kafka_producer_queue_mib,
+ kafka_producer_queue_messages: self.kafka_producer_queue_messages,
kafka_message_timeout_ms: 20_000,
kafka_producer_batch_size: None,
kafka_producer_batch_num_messages: None,
+ // Idempotence stays off: librdkafka retries can reorder, but the pipeline is
+ // at-least-once and the downstream processor dedups on `source_partition`/
+ // `source_offset`, so per-partition produce ordering is never relied on. A deliberate
+ // steady-state tradeoff, not a temporary shortcut — enabling it
+ // (enable.idempotence=true) would cap max.in.flight.requests.per.connection at 5 and
+ // throttle the pipeline for an ordering guarantee nothing downstream needs.
kafka_producer_enable_idempotence: None,
kafka_producer_max_in_flight_requests_per_connection: None,
kafka_producer_topic_metadata_refresh_interval_ms: None,
@@ -142,8 +179,11 @@ impl Config {
}
}
- /// Auto-commit is disabled: the loop stores offsets manually only after envelopes are ack'd,
- /// then commits per batch (at-least-once ordering).
+ /// Auto-commit is disabled: the pipeline commits explicit per-partition next-offsets computed
+ /// by its [`crate::ledger::Ledger`] (at-least-once; only ack-covered offsets are committed).
+ /// Load-bearing: `recv_with` still auto-STORES offsets for empty payloads, so enabling
+ /// auto-commit would commit those stores past unacked forwards and silently break
+ /// at-least-once. A unit test pins the flag.
pub fn build_consumer_config(&self) -> ConsumerConfig {
ConsumerConfig {
kafka_consumer_group: self.kafka_consumer_group.clone(),
@@ -191,8 +231,12 @@ mod tests {
team_index_refresh_secs: 300,
team_index_refresh_jitter_secs: 60,
team_allowlist: TeamAllowlist::All,
- recv_batch_size: 1000,
- recv_batch_timeout_ms: 500,
+ max_inflight_forwards: 10_000,
+ commit_interval_ms: 5000,
+ queue_full_backoff_ms: 100,
+ kafka_producer_linger_ms: 100,
+ kafka_producer_queue_mib: 64,
+ kafka_producer_queue_messages: 100_000,
}
}
diff --git a/rust/cohort-event-shuffler/src/consumer.rs b/rust/cohort-event-shuffler/src/consumer.rs
index 2a21fe7389fd..56e177b7d7f5 100644
--- a/rust/cohort-event-shuffler/src/consumer.rs
+++ b/rust/cohort-event-shuffler/src/consumer.rs
@@ -1,26 +1,62 @@
-//! Consume → filter → re-key → produce loop for `clickhouse_events_json`.
+//! Pipelined consume → filter → re-key → produce loop for `clickhouse_events_json`.
//!
//! Drops events with no `person_id`, skips teams with no realtime cohorts, then re-keys the
//! survivors by `(team_id, person_id)` to match the Node CDP precalculated-filters gating.
+//!
+//! Consume, produce-ack, and offset-commit are decoupled: the single owner task enqueues
+//! survivors without awaiting delivery, resolves acks as they arrive, and periodically commits
+//! the [`Ledger`]'s per-partition watermarks through `spawn_blocking`, so WarpStream's
+//! ~250–500ms produce acks never throttle consumption.
+use std::future::Future;
+use std::pin::Pin;
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, Instant};
-use anyhow::{Context, Result};
use common_kafka::kafka_consumer::{Offset, RecvErr, SingleTopicConsumer};
use common_types::ClickHouseEvent;
+use futures::stream::FuturesUnordered;
+use futures::StreamExt;
use lifecycle::Handle;
-use metrics::counter;
+use metrics::{counter, gauge, histogram};
+use rdkafka::error::KafkaError;
use serde::{de::IgnoredAny, Deserialize};
+use tokio::task::JoinError;
use tracing::{debug, error, info, warn};
use crate::event::CohortStreamEvent;
use crate::filter_team_index::TeamIndex;
+use crate::ledger::{
+ DeliveryOutcome, Ledger, NextOffset, Observation, Resolution, SourceOffset, SourcePartition,
+};
use crate::observability::metrics::{
- EVENTS_CONSUMED, EVENTS_DROPPED_NO_PERSON_ID, EVENTS_FORWARDED, EVENTS_SKIPPED_TEAM_GATE,
- PRODUCE_ERRORS,
+ COMMITS, COMMIT_ERRORS, EVENTS_ABANDONED, EVENTS_CONSUMED, EVENTS_DROPPED_NO_PERSON_ID,
+ EVENTS_FORWARDED, EVENTS_SKIPPED_TEAM_GATE, EVENTS_UNPARSEABLE, FORWARDS_ENQUEUED,
+ FORWARDS_INFLIGHT, LEDGER_PARTITIONS, PRODUCE_ACK_SECONDS, PRODUCE_ERRORS, PRODUCE_QUEUE_FULL,
+ UNCOMMITTED_EVENTS,
};
-use crate::producer::CohortStreamProducer;
+use crate::producer::{CohortStreamProducer, EnqueueError};
+
+/// Bounds the idle select wait so every loop iteration (and thus the liveness heartbeat) happens
+/// at least this often on a quiet topic.
+const RECV_TIMEOUT: Duration = Duration::from_millis(500);
+const QUEUE_FULL_BACKOFF_CAP: Duration = Duration::from_secs(2);
+/// Intake pause after a kafka-level recv error, so a persistently erroring consumer doesn't
+/// hot-loop.
+const RECV_ERROR_BACKOFF: Duration = Duration::from_secs(1);
+/// No successful commit for this many intervals while committable work exists ⇒ stop
+/// heartbeating so the stall detector restarts the pod.
+const COMMIT_STALENESS_FACTOR: u32 = 3;
+/// Every step of the shutdown drain shares this one budget, sized inside the consumer's 15s
+/// graceful window with slack for process-exit overhead.
+const SHUTDOWN_DRAIN_BUDGET: Duration = Duration::from_secs(14);
+/// librdkafka-internal bound on the shutdown flush; the shared budget applies on top.
+const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
+/// Floor of the shared budget held back for the final Sync commit — the step that turns drained
+/// work into committed progress must not be starved by a slow flush or ack drain. The commit may
+/// run for longer (up to the full budget) if earlier steps finish early; this only reserves the
+/// minimum.
+const SHUTDOWN_COMMIT_RESERVE: Duration = Duration::from_secs(4);
/// Only the fields the team gate needs. Every undeclared field (notably the large
/// `properties` / `person_properties` / `groupN_properties` JSON-string blobs) is skipped by
@@ -54,7 +90,7 @@ fn classify_gate(gate: &GateFields, team_index: &TeamIndex) -> GateOutcome {
}
/// `event` is boxed to keep the enum small: `Forward` is the only large variant and is built only
-/// for survivors, so the drop/skip majority filling the batch `Vec` stays cheap to move.
+/// for survivors.
#[derive(Debug)]
enum Decoded {
Forward {
@@ -63,27 +99,105 @@ enum Decoded {
},
DropNoPersonId,
SkipTeamGate,
+ /// Serde failure at either phase — counted and settled, never an `Err`. Infallibility matters:
+ /// `recv_with` auto-stores offsets on decode errors, and a stored poison-pill offset could be
+ /// committed past unacked forwards by an auto-commit path. With this variant the decode-error
+ /// auto-store is unreachable; only the empty-payload branch still auto-stores, and stored
+ /// offsets stay inert because auto-commit is off (see `Config::build_consumer_config`). The
+ /// ledger owns every observed offset.
+ Unparseable,
}
/// Cheap gate parse for every event; a full `ClickHouseEvent` parse only for survivors, over the
/// same bytes so forwarded envelopes are byte-identical to a single-parse path.
-fn decode_gated(payload: &[u8], team_index: &TeamIndex) -> Result<Decoded, serde_json::Error> {
- let gate: GateFields = serde_json::from_slice(payload)?;
+fn decode_gated(payload: &[u8], team_index: &TeamIndex) -> Decoded {
+ let Ok(gate) = serde_json::from_slice::<GateFields>(payload) else {
+ return Decoded::Unparseable;
+ };
match classify_gate(&gate, team_index) {
- GateOutcome::DropNoPersonId => Ok(Decoded::DropNoPersonId),
- GateOutcome::SkipTeamGate => Ok(Decoded::SkipTeamGate),
+ GateOutcome::DropNoPersonId => Decoded::DropNoPersonId,
+ GateOutcome::SkipTeamGate => Decoded::SkipTeamGate,
GateOutcome::Forward => {
- let mut event: ClickHouseEvent = serde_json::from_slice(payload)?;
+ let Ok(mut event) = serde_json::from_slice::<ClickHouseEvent>(payload) else {
+ return Decoded::Unparseable;
+ };
let Some(person_id) = event.person_id.take() else {
// Unreachable: the gate saw a present non-null person_id, and a non-string one would
// have failed the full parse above. Fail safe instead of panicking.
warn!("gate-forwarded event had no person_id after full parse; dropping");
- return Ok(Decoded::DropNoPersonId);
+ return Decoded::DropNoPersonId;
};
- Ok(Decoded::Forward {
+ Decoded::Forward {
event: Box::new(event),
person_id,
- })
+ }
+ }
+ }
+}
+
+/// Resolved delivery of one forwarded event, carried back to the pipeline task by an
+/// [`AckFuture`].
+struct DeliveryAck {
+ partition: SourcePartition,
+ offset: SourceOffset,
+ sent_at: Instant,
+ result: Result<(), KafkaError>,
+}
+
+type AckFuture = Pin<Box<dyn Future<Output = DeliveryAck> + Send>>;
+type CommitResult = Result<Result<(), KafkaError>, JoinError>;
+type CommitFuture =
+ Pin<Box<dyn Future<Output = (Vec<(SourcePartition, NextOffset)>, CommitResult)> + Send>>;
+
+#[derive(Debug, Clone, Copy)]
+pub struct ShufflerSettings {
+ pub max_inflight_forwards: usize,
+ pub commit_interval: Duration,
+ pub queue_full_backoff: Duration,
+}
+
+/// A gate survivor whose enqueue hit `QueueFull`, parked until the producer queue drains. Its
+/// offset is not observed by the ledger until the enqueue lands, so a crash while parked simply
+/// replays it.
+struct PendingForward {
+ event: CohortStreamEvent,
+ partition: SourcePartition,
+ offset: SourceOffset,
+}
+
+/// Whether the recv arm may consume. Pausing is a hard ordering gate — a parked survivor must
+/// reach the producer before any newer event for the same `(team, person)` — but only intake
+/// stops: acks, commits, shutdown, and the liveness heartbeat keep flowing because the loop
+/// itself never sleeps.
+enum Intake {
+ Open,
+ /// `QueueFull`: re-enqueue the parked forward at `resume_at`, doubling `backoff` (capped)
+ /// on each further failure. Boxed to keep the always-carried `Open` variant word-sized.
+ RetryForward {
+ forward: Box<PendingForward>,
+ resume_at: tokio::time::Instant,
+ backoff: Duration,
+ },
+ /// Transient kafka-level recv error; resume consuming at `resume_at`. Named for its trigger
+ /// (the recv error) to distinguish it from [`Intake::RetryForward`], which carries its own
+ /// `backoff`.
+ RecvBackoff {
+ resume_at: tokio::time::Instant,
+ },
+}
+
+impl Intake {
+ fn is_open(&self) -> bool {
+ matches!(self, Intake::Open)
+ }
+
+ /// Only meaningful when paused; the select arm awaiting this is guarded on `!is_open()`.
+ fn resume_at(&self) -> tokio::time::Instant {
+ match self {
+ Intake::Open => tokio::time::Instant::now(),
+ Intake::RetryForward { resume_at, .. } | Intake::RecvBackoff { resume_at } => {
+ *resume_at
+ }
}
}
}
@@ -93,8 +207,7 @@ pub struct EventShuffler {
producer: CohortStreamProducer,
team_index: Arc<TeamIndex>,
handle: Handle,
- batch_size: usize,
- batch_timeout: Duration,
+ settings: ShufflerSettings,
}
impl EventShuffler {
@@ -103,170 +216,401 @@ impl EventShuffler {
producer: CohortStreamProducer,
team_index: Arc<TeamIndex>,
handle: Handle,
- batch_size: usize,
- batch_timeout: Duration,
+ settings: ShufflerSettings,
) -> Self {
Self {
consumer,
producer,
team_index,
handle,
- batch_size,
- batch_timeout,
+ settings,
}
}
- /// A successful batch (even an empty poll) heartbeats liveness, so an idle topic stays healthy
- /// and only a wedged loop or a persistent produce failure trips the stall detector.
+ /// The single pipeline task: owns the consumer, producer, [`Ledger`], [`Intake`] gate,
+ /// pending ack futures, and the one-slot commit task. Backpressure is the recv guard — at
+ /// the in-flight cap or while intake is paused the recv arm is disabled but acks and commits
+ /// keep draining, and every `DeliveryFuture` resolves within `message.timeout.ms` regardless
+ /// of broker state, so the loop cannot deadlock and never stops heartbeating on its own.
pub async fn process(self) {
let _guard = self.handle.process_scope();
- info!("shuffler consume loop starting");
+ info!("shuffler pipeline starting");
+
+ let mut ledger = Ledger::default();
+ let mut pending_acks: FuturesUnordered<AckFuture> = FuturesUnordered::new();
+ let mut pending_commit: FuturesUnordered<CommitFuture> = FuturesUnordered::new();
+ let mut intake = Intake::Open;
+ let mut commit_in_flight = false;
+ let mut commit_tick = tokio::time::interval(self.settings.commit_interval);
+ commit_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ let staleness_threshold = self.settings.commit_interval * COMMIT_STALENESS_FACTOR;
+ let mut last_commit_ok = Instant::now();
loop {
tokio::select! {
+ biased;
+
_ = self.handle.shutdown_recv() => {
- info!("shutdown signal received, stopping consume loop");
+ info!("shutdown signal received, stopping intake");
break;
}
- result = self.process_batch() => match result {
- Ok(_) => self.handle.report_healthy(),
- Err(err) => {
- error!(error = %err, "batch processing failed; backing off");
- tokio::time::sleep(Duration::from_secs(1)).await;
+
+ Some(ack) = pending_acks.next() => {
+ record_delivery(&mut ledger, ack);
+ }
+
+ Some((offsets, result)) = pending_commit.next() => {
+ commit_in_flight = false;
+ if apply_commit_result(&mut ledger, offsets, result) {
+ last_commit_ok = Instant::now();
+ }
+ }
+
+ _ = commit_tick.tick(), if !commit_in_flight => {
+ if let Some(commit) = self.start_commit(&mut ledger) {
+ pending_commit.push(commit);
+ commit_in_flight = true;
+ }
+ }
+
+ _ = tokio::time::sleep_until(intake.resume_at()), if !intake.is_open() => {
+ intake = match std::mem::replace(&mut intake, Intake::Open) {
+ Intake::RetryForward { forward, backoff, .. } => {
+ self.try_enqueue(forward, backoff, &mut ledger, &mut pending_acks)
+ }
+ Intake::Open | Intake::RecvBackoff { .. } => Intake::Open,
+ };
+ }
+
+ // Fail-closed until the team index loads once: don't consume — and advance
+ // offsets past — events while the gate would forward nothing.
+ recv = tokio::time::timeout(
+ RECV_TIMEOUT,
+ self.consumer.recv_with(|payload| Ok(decode_gated(payload, &self.team_index))),
+ ), if intake.is_open()
+ && ledger.in_flight() < self.settings.max_inflight_forwards
+ && self.team_index.is_loaded() =>
+ {
+ match recv {
+ Ok(Ok((decoded, offset))) => {
+ intake = self.intake(&mut ledger, &mut pending_acks, decoded, &offset);
+ }
+ Ok(Err(err)) => match err {
+ // Auto-stored by recv_with, but inert: this loop never commits
+ // stored offsets, only explicit ledger watermarks. Worst case at a
+ // partition tail: commit stays one message short → one-message
+ // replay on restart.
+ RecvErr::Empty => debug!("skipped message with empty payload"),
+ RecvErr::Serde(e) => {
+ warn!(error = %e, "unreachable: infallible decode reported serde error");
+ }
+ RecvErr::Kafka(e) => {
+ warn!(error = %e, "kafka recv error; pausing intake");
+ intake = Intake::RecvBackoff {
+ resume_at: tokio::time::Instant::now() + RECV_ERROR_BACKOFF,
+ };
+ }
+ },
+ Err(_elapsed) => {} // idle poll; heartbeat below keeps liveness fresh
}
- },
+ }
+ }
+
+ // Heartbeat gated by commit freshness: a wedged committer with committable work must
+ // trip the stall detector, but an idle topic (nothing to commit) stays healthy.
+ let commit_is_stale = last_commit_ok.elapsed() > staleness_threshold;
+ if should_heartbeat(commit_is_stale, ledger.has_committable()) {
+ self.handle.report_healthy();
}
}
- info!("shuffler consume loop stopped");
+ self.drain_and_commit(ledger, pending_acks, pending_commit, intake)
+ .await;
+ info!("shuffler pipeline stopped");
}
- async fn process_batch(&self) -> Result<usize> {
- // Fail-closed until the team index loads once: don't consume — and advance offsets past —
- // events while the gate would forward nothing.
- if !self.team_index.is_loaded() {
- tokio::time::sleep(Duration::from_millis(200)).await;
- return Ok(0);
- }
-
- let results = self.recv_gated_batch().await;
- if results.is_empty() {
- return Ok(0);
- }
+ fn intake(
+ &self,
+ ledger: &mut Ledger,
+ pending_acks: &mut FuturesUnordered<AckFuture>,
+ decoded: Decoded,
+ offset: &Offset,
+ ) -> Intake {
+ counter!(EVENTS_CONSUMED).increment(1);
+ let partition = SourcePartition(offset.partition());
+ let source_offset = SourceOffset(offset.get_value());
+
+ let (event, person_id) = match decoded {
+ Decoded::Forward { event, person_id } => (event, person_id),
+ Decoded::DropNoPersonId => {
+ counter!(EVENTS_DROPPED_NO_PERSON_ID).increment(1);
+ ledger.observe(partition, source_offset, Observation::Settled);
+ return Intake::Open;
+ }
+ Decoded::SkipTeamGate => {
+ counter!(EVENTS_SKIPPED_TEAM_GATE).increment(1);
+ ledger.observe(partition, source_offset, Observation::Settled);
+ return Intake::Open;
+ }
+ Decoded::Unparseable => {
+ counter!(EVENTS_UNPARSEABLE).increment(1);
+ ledger.observe(partition, source_offset, Observation::Settled);
+ return Intake::Open;
+ }
+ };
- let mut consumed = 0u64;
- let mut dropped = 0u64;
- let mut skipped = 0u64;
- let mut forwardable = Vec::new();
- let mut offsets = Vec::with_capacity(results.len());
-
- for result in results {
- let (decoded, offset) = match result {
- Ok(pair) => pair,
- Err(err) => {
- // Poison pills are already offset-stored by the consumer; just log.
- log_recv_error(&err);
- continue;
- }
- };
+ let forward = Box::new(PendingForward {
+ event: CohortStreamEvent::from_clickhouse(
+ *event,
+ person_id,
+ partition.0,
+ source_offset.0,
+ ),
+ partition,
+ offset: source_offset,
+ });
+ self.try_enqueue(
+ forward,
+ self.settings.queue_full_backoff,
+ ledger,
+ pending_acks,
+ )
+ }
- consumed += 1;
- let source_partition = offset.partition();
- let source_offset = offset.get_value();
-
- match decoded {
- Decoded::Forward { event, person_id } => {
- forwardable.push(CohortStreamEvent::from_clickhouse(
- *event,
- person_id,
- source_partition,
- source_offset,
- ))
+ /// One non-blocking enqueue attempt. `QueueFull` parks the forward for a timer-arm retry
+ /// after `backoff`: the queue drains independently via librdkafka's delivery thread, and
+ /// `message.timeout.ms` bounds how long it can stay full even with a dead broker.
+ fn try_enqueue(
+ &self,
+ forward: Box<PendingForward>,
+ backoff: Duration,
+ ledger: &mut Ledger,
+ pending_acks: &mut FuturesUnordered<AckFuture>,
+ ) -> Intake {
+ match self.producer.enqueue(&forward.event) {
+ Ok(delivery) => {
+ counter!(FORWARDS_ENQUEUED).increment(1);
+ let PendingForward {
+ partition, offset, ..
+ } = *forward;
+ ledger.observe(partition, offset, Observation::InFlight);
+ let sent_at = Instant::now();
+ pending_acks.push(Box::pin(async move {
+ let result = match delivery.await {
+ Ok(Ok(_)) => Ok(()),
+ Ok(Err((err, _message))) => Err(err),
+ Err(_canceled) => Err(KafkaError::Canceled),
+ };
+ DeliveryAck {
+ partition,
+ offset,
+ sent_at,
+ result,
+ }
+ }));
+ Intake::Open
+ }
+ Err(EnqueueError::QueueFull) => {
+ counter!(PRODUCE_QUEUE_FULL).increment(1);
+ Intake::RetryForward {
+ resume_at: tokio::time::Instant::now() + backoff,
+ backoff: (backoff * 2).min(QUEUE_FULL_BACKOFF_CAP),
+ forward,
}
- Decoded::DropNoPersonId => dropped += 1,
- Decoded::SkipTeamGate => skipped += 1,
}
+ Err(EnqueueError::Fatal(err)) => {
+ counter!(PRODUCE_ERRORS).increment(1);
+ counter!(EVENTS_ABANDONED).increment(1);
+ warn!(error = %err, "fatal enqueue error; abandoning event");
+ ledger.observe(forward.partition, forward.offset, Observation::Settled);
+ Intake::Open
+ }
+ }
+ }
- offsets.push(offset);
+ /// Plans a commit from the current assignment snapshot and spawns the blocking Sync commit
+ /// into the single in-flight slot. Emits the ledger gauges even when there is nothing to
+ /// commit.
+ fn start_commit(&self, ledger: &mut Ledger) -> Option<CommitFuture> {
+ let assigned = match self.consumer.assigned_partitions() {
+ Ok(partitions) => partitions.into_iter().map(SourcePartition).collect(),
+ Err(err) => {
+ warn!(error = %err, "failed to snapshot partition assignment; skipping commit tick");
+ return None;
+ }
+ };
+ let plan = ledger.commit_plan(&assigned);
+ if !plan.pruned.is_empty() {
+ debug!(pruned = ?plan.pruned, "pruned revoked partitions from ledger");
}
- counter!(EVENTS_CONSUMED).increment(consumed);
- if dropped > 0 {
- counter!(EVENTS_DROPPED_NO_PERSON_ID).increment(dropped);
+ let stats = ledger.stats();
+ gauge!(FORWARDS_INFLIGHT).set(stats.in_flight as f64);
+ gauge!(UNCOMMITTED_EVENTS).set(stats.uncommitted_events as f64);
+ gauge!(LEDGER_PARTITIONS).set(stats.partitions as f64);
+
+ if plan.offsets.is_empty() {
+ return None;
}
- if skipped > 0 {
- counter!(EVENTS_SKIPPED_TEAM_GATE).increment(skipped);
+ let raw: Vec<(i32, i64)> = plan.offsets.iter().map(|&(p, n)| (p.0, n.0)).collect();
+ let consumer = self.consumer.clone();
+ let task = tokio::task::spawn_blocking(move || consumer.commit_partition_offsets(&raw));
+ Some(Box::pin(async move { (plan.offsets, task.await) }))
+ }
+
+ /// Sequential shutdown: settle the in-flight commit, flush the producer, drain remaining
+ /// acks, then one final Sync commit. Every step runs under one shared
+ /// [`SHUTDOWN_DRAIN_BUDGET`] deadline with the final commit's slice reserved, so the drain
+ /// provably fits the 15s graceful window. Anything unresolved at a deadline simply replays
+ /// under the new consumer (at-least-once).
+ async fn drain_and_commit(
+ &self,
+ mut ledger: Ledger,
+ mut pending_acks: FuturesUnordered<AckFuture>,
+ mut pending_commit: FuturesUnordered<CommitFuture>,
+ intake: Intake,
+ ) {
+ let deadline = tokio::time::Instant::now() + SHUTDOWN_DRAIN_BUDGET;
+ let pre_commit_deadline = deadline - SHUTDOWN_COMMIT_RESERVE;
+
+ // Settle the in-flight commit first so the final plan is a real delta.
+ if !pending_commit.is_empty() {
+ match tokio::time::timeout_at(pre_commit_deadline, pending_commit.next()).await {
+ Ok(Some((offsets, result))) => {
+ apply_commit_result(&mut ledger, offsets, result);
+ }
+ Ok(None) => {}
+ Err(_) => warn!("in-flight commit did not settle before shutdown deadline"),
+ }
}
- // At-least-once: produce and await acks BEFORE storing source offsets, and bail without
- // committing on any produce failure. A transient produce failure that recovers gets
- // committed over by a later batch, dropping those events — accepted tradeoff; the downstream
- // processor dedups replays via source_offset/source_partition.
- let forward_count = forwardable.len();
- if forward_count > 0 {
- let produce_results = self.producer.forward(forwardable).await;
- let errors = produce_results.iter().filter(|r| r.is_err()).count();
- if errors > 0 {
- counter!(PRODUCE_ERRORS).increment(errors as u64);
- let first_error = produce_results
- .iter()
- .find_map(|r| r.as_ref().err())
- .map(ToString::to_string)
- .unwrap_or_default();
- anyhow::bail!(
- "{errors}/{forward_count} produces to cohort_stream_events failed: {first_error}"
+ // A forward parked on QueueFull gets one last attempt; if the queue is still full its
+ // offset was never observed, so the commit stops short of it and the new owner replays.
+ if let Intake::RetryForward {
+ forward, backoff, ..
+ } = intake
+ {
+ if let Intake::RetryForward { forward, .. } =
+ self.try_enqueue(forward, backoff, &mut ledger, &mut pending_acks)
+ {
+ warn!(
+ partition = forward.partition.0,
+ offset = forward.offset.0,
+ "producer queue still full at shutdown; parked forward will replay"
);
}
- counter!(EVENTS_FORWARDED).increment(forward_count as u64);
}
- for offset in offsets {
- if let Err(err) = offset.store() {
- warn!(error = %err, "failed to store consumer offset");
- }
+ let producer = self.producer.clone();
+ let flush = tokio::task::spawn_blocking(move || producer.flush(SHUTDOWN_FLUSH_TIMEOUT));
+ match tokio::time::timeout_at(pre_commit_deadline, flush).await {
+ Ok(Ok(Ok(()))) => {}
+ Ok(Ok(Err(err))) => warn!(error = %err, "producer flush failed during shutdown"),
+ Ok(Err(err)) => error!(error = %err, "producer flush task panicked"),
+ Err(_) => warn!("producer flush exceeded the shutdown budget"),
}
- self.consumer
- .commit()
- .context("committing consumer offsets after forwarding batch")?;
- Ok(consumed as usize)
- }
+ while !pending_acks.is_empty() {
+ match tokio::time::timeout_at(pre_commit_deadline, pending_acks.next()).await {
+ Ok(Some(ack)) => {
+ record_delivery(&mut ledger, ack);
+ }
+ Ok(None) => break,
+ Err(_) => {
+ warn!(
+ unresolved = pending_acks.len(),
+ "ack drain deadline reached; unresolved forwards will replay"
+ );
+ break;
+ }
+ }
+ }
- /// Local mirror of [`SingleTopicConsumer::json_recv_batch`] that decodes via [`decode_gated`]
- /// instead of a blanket full parse.
- async fn recv_gated_batch(&self) -> Vec<Result<(Decoded, Offset), RecvErr>> {
- let team_index: &TeamIndex = &self.team_index;
- let mut results = Vec::with_capacity(self.batch_size);
-
- tokio::select! {
- _ = tokio::time::sleep(self.batch_timeout) => {}
- _ = async {
- while results.len() < self.batch_size {
- let result = self
- .consumer
- .recv_with(|payload| decode_gated(payload, team_index))
- .await;
- let was_err = result.is_err();
- results.push(result);
- if was_err {
- break; // an error may be kafka-level, not just a bad payload
- }
+ if let Some(commit) = self.start_commit(&mut ledger) {
+ match tokio::time::timeout_at(deadline, commit).await {
+ Ok((offsets, result)) => {
+ apply_commit_result(&mut ledger, offsets, result);
}
- } => {}
+ Err(_) => warn!("final offset commit timed out; committed work will replay"),
+ }
}
+ }
+}
- results
+fn record_delivery(ledger: &mut Ledger, ack: DeliveryAck) {
+ let DeliveryAck {
+ partition,
+ offset,
+ sent_at,
+ result,
+ } = ack;
+ let outcome = match &result {
+ Ok(()) => {
+ counter!(EVENTS_FORWARDED).increment(1);
+ DeliveryOutcome::Acked
+ }
+ Err(err) => {
+ counter!(PRODUCE_ERRORS).increment(1);
+ counter!(EVENTS_ABANDONED).increment(1);
+ // Counter-visible rather than log-visible: a broker outage abandons at consume rate.
+ debug!(
+ error = %err,
+ partition = partition.0,
+ offset = offset.0,
+ "delivery failed after librdkafka retries; abandoning event"
+ );
+ DeliveryOutcome::Abandoned
+ }
+ };
+ let label = match outcome {
+ DeliveryOutcome::Acked => "acked",
+ DeliveryOutcome::Abandoned => "abandoned",
+ };
+ histogram!(PRODUCE_ACK_SECONDS, "outcome" => label).record(sent_at.elapsed().as_secs_f64());
+
+ if ledger.resolve(partition, offset, outcome) == Resolution::Untracked {
+ debug!(
+ partition = partition.0,
+ offset = offset.0,
+ "straggler delivery for a pruned partition"
+ );
}
}
-fn log_recv_error(err: &RecvErr) {
- match err {
- RecvErr::Empty => debug!("skipped message with empty payload"),
- RecvErr::Serde(e) => debug!(error = %e, "skipped undeserializable event"),
- RecvErr::Kafka(e) => warn!(error = %e, "kafka recv error during batch"),
+/// Returns true when the broker confirmed the commit (and the ledger was updated). Failed
+/// commits are only counted: the unconfirmed delta is re-emitted at the next tick.
+fn apply_commit_result(
+ ledger: &mut Ledger,
+ offsets: Vec<(SourcePartition, NextOffset)>,
+ result: CommitResult,
+) -> bool {
+ match result {
+ Ok(Ok(())) => {
+ ledger.confirm_committed(&offsets);
+ counter!(COMMITS).increment(1);
+ true
+ }
+ Ok(Err(err)) => {
+ counter!(COMMIT_ERRORS).increment(1);
+ warn!(error = %err, "offset commit failed; retrying next tick");
+ false
+ }
+ Err(err) => {
+ counter!(COMMIT_ERRORS).increment(1);
+ error!(error = %err, "offset commit task panicked");
+ false
+ }
}
}
+/// Liveness gate for the pipeline loop. Stale-and-committable is the only state that withholds the
+/// heartbeat — a committer wedged for [`COMMIT_STALENESS_FACTOR`] intervals while committable work
+/// waits must trip the stall detector. An idle topic (nothing committable) stays healthy even when
+/// the last commit is old, and any fresh commit clears the staleness.
+fn should_heartbeat(commit_stale: bool, has_committable: bool) -> bool {
+ !commit_stale || !has_committable
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -281,6 +625,18 @@ mod tests {
GateFields { team_id, person_id }
}
+ #[test]
+ fn heartbeat_withheld_only_when_stale_and_committable() {
+ // The single false case: a wedged committer with work waiting must stop heartbeating so
+ // the stall detector restarts the pod.
+ assert!(!should_heartbeat(true, true));
+ // Stale but nothing to commit = idle topic, stays healthy.
+ assert!(should_heartbeat(true, false));
+ // Fresh commits keep the pod healthy regardless of pending work.
+ assert!(should_heartbeat(false, true));
+ assert!(should_heartbeat(false, false));
+ }
+
#[test]
fn classify_gate_covers_every_gate_outcome() {
let cases = [
@@ -337,17 +693,29 @@ mod tests {
#[test]
fn dropped_event_never_materializes_blobs() {
// A JSON-object `properties` fails the full parse (the field is a stringified blob): outside
- // the index the gate ignores the blob and skips; inside it the survivor parse rejects it.
+ // the index the gate ignores the blob and skips; inside it the survivor parse rejects it as
+ // unparseable.
let mut value: Value =
serde_json::to_value(sample_clickhouse_event(99, Some("p"))).unwrap();
value["properties"] = json!({ "a": [1, 2, 3] });
let payload = serde_json::to_vec(&value).unwrap();
assert!(matches!(
- decode_gated(&payload, &index_with(&[2])).unwrap(),
+ decode_gated(&payload, &index_with(&[2])),
Decoded::SkipTeamGate
));
- assert!(decode_gated(&payload, &index_with(&[99])).is_err());
+ assert!(matches!(
+ decode_gated(&payload, &index_with(&[99])),
+ Decoded::Unparseable
+ ));
+ }
+
+ #[test]
+ fn garbage_payload_is_unparseable_not_an_error() {
+ assert!(matches!(
+ decode_gated(b"not json at all", &index_with(&[2])),
+ Decoded::Unparseable
+ ));
}
#[test]
@@ -359,7 +727,7 @@ mod tests {
let payload = serde_json::to_vec(&value).unwrap();
assert!(matches!(
- decode_gated(&payload, &index_with(&[2])).unwrap(),
+ decode_gated(&payload, &index_with(&[2])),
Decoded::SkipTeamGate
));
}
@@ -369,8 +737,7 @@ mod tests {
let index = index_with(&[2]);
let base: Value =
serde_json::to_value(sample_clickhouse_event(2, Some("ignored"))).unwrap();
- let decode =
- |value: Value| decode_gated(&serde_json::to_vec(&value).unwrap(), &index).unwrap();
+ let decode = |value: Value| decode_gated(&serde_json::to_vec(&value).unwrap(), &index);
// Absent: drop (person check runs before the team gate).
let mut absent = base.clone();
@@ -411,7 +778,7 @@ mod tests {
#[test]
fn survivor_fully_materializes_the_forward_envelope() {
let payload = serde_json::to_vec(&sample_clickhouse_event(2, Some("p"))).unwrap();
- match decode_gated(&payload, &index_with(&[2])).unwrap() {
+ match decode_gated(&payload, &index_with(&[2])) {
Decoded::Forward { event, person_id } => {
assert_eq!(person_id, "p");
assert_eq!(event.team_id, 2);
diff --git a/rust/cohort-event-shuffler/src/ledger.rs b/rust/cohort-event-shuffler/src/ledger.rs
new file mode 100644
index 000000000000..5e5b8ef21165
--- /dev/null
+++ b/rust/cohort-event-shuffler/src/ledger.rs
@@ -0,0 +1,596 @@
+//! Pure per-partition offset ledger for the pipelined consume → produce → commit loop.
+//!
+//! Encodes the at-least-once commit rule: a source offset is committable only when every
+//! forwarded event at or below it has resolved (acked or abandoned). No Kafka, no I/O, no
+//! locks — owned (`&mut`) by the single pipeline task.
+//!
+//! # Watermark rule (per partition)
+//!
+//! `committable = in_flight.is_empty() ? high_watermark + 1 : min(in_flight)`. Settled events
+//! only lift `high_watermark`. Gaps (offsets never observed, e.g. transaction markers) are
+//! covered when the next observed message lifts the watermark past them.
+//!
+//! # Rebalance stance (eager, no `ConsumerContext` — a deliberate, accepted scope)
+//!
+//! Explicit-TPL commits are fenced by group generation, not per-partition ownership, so a stale
+//! commit for a revoked partition can succeed. Defenses, all in [`Ledger::commit_plan`]:
+//! (1) partitions absent from the current assignment snapshot are pruned; (2) delta suppression —
+//! only committable > confirmed-committed is emitted; (3) commit values derive only from
+//! self-consumed + resolved positions.
+//!
+//! Two residual races remain, both accepted because the pipeline is at-least-once and the
+//! downstream processor dedups on `source_partition`/`source_offset`:
+//!
+//! - Revoke lands between snapshot and commit: the stale value ≤ what this pod actually consumed
+//! **and acked**, so a new owner resuming there skips only events this pod already forwarded —
+//! at-least-once holds; worst case is bounded duplicates.
+//! - Same partition revoked and reassigned to *this* pod with no intervening [`Ledger::commit_plan`]
+//! prune: the surviving `PartitionLedger` re-observes a replayed offset while its first forward is
+//! still in flight, and because `in_flight` is a set the two forwards collapse to one entry. The
+//! watermark can then advance after only one resolves, so an offset abandoned on *both* attempts
+//! is committed over without ever delivering — a single-offset loss, not a duplicate. Narrow (needs
+//! a same-pod reassign plus a double abandon) and out of scope to close without a `ConsumerContext`
+//! revoke hook; called out here so the guarantee doesn't read as duplicates-only.
+
+use std::collections::{BTreeMap, BTreeSet};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct SourcePartition(pub i32);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct SourceOffset(pub i64);
+
+/// The offset Kafka resumes from (last-fully-done + 1). This is what gets committed — the
+/// newtype prevents ever confusing "message offset" with "commit value".
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct NextOffset(pub i64);
+
+/// How a consumed message enters the ledger: the rule "only forwards block the watermark".
+#[derive(Debug, Clone, Copy)]
+pub enum Observation {
+ /// Done when seen: dropped (no person_id), skipped (team gate), or unparseable.
+ Settled,
+ /// Enqueued to the producer; blocks the commit watermark until resolved.
+ InFlight,
+}
+
+/// Why an in-flight forward stopped blocking the watermark. Both advance it: `Abandoned` is the
+/// drop-on-produce-failure policy, encoded in the type.
+#[derive(Debug, Clone, Copy)]
+pub enum DeliveryOutcome {
+ Acked,
+ Abandoned,
+}
+
+/// [`Ledger::resolve`] result: `Untracked` = straggler ack for a pruned (revoked) partition —
+/// dropped.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Resolution {
+ Resolved,
+ Untracked,
+}
+
+#[derive(Debug)]
+struct PartitionLedger {
+ /// First offset this pod observed; stats baseline before the first confirmed commit.
+ base: NextOffset,
+ /// Highest observed offset, monotonic.
+ high_watermark: SourceOffset,
+ /// Unresolved forwards; the smallest blocks the commit watermark.
+ in_flight: BTreeSet<SourceOffset>,
+ /// Last broker-confirmed commit, monotonic.
+ committed: Option<NextOffset>,
+}
+
+impl PartitionLedger {
+ fn new(first: SourceOffset) -> Self {
+ Self {
+ base: NextOffset(first.0),
+ high_watermark: first,
+ in_flight: BTreeSet::new(),
+ committed: None,
+ }
+ }
+
+ fn committable(&self) -> NextOffset {
+ match self.in_flight.first() {
+ Some(oldest) => NextOffset(oldest.0),
+ None => NextOffset(self.high_watermark.0 + 1),
+ }
+ }
+
+ fn has_committable(&self) -> bool {
+ self.committed
+ .is_none_or(|committed| self.committable() > committed)
+ }
+
+ /// Observed-but-unconfirmed span; gap offsets inside it inflate the count slightly.
+ fn uncommitted(&self) -> u64 {
+ let done_through = self.committed.unwrap_or(self.base);
+ (self.high_watermark.0 + 1)
+ .saturating_sub(done_through.0)
+ .max(0) as u64
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct Ledger {
+ partitions: BTreeMap<SourcePartition, PartitionLedger>,
+ /// Denormalized Σ in_flight so the intake backpressure guard is O(1).
+ total_in_flight: usize,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CommitPlan {
+ pub offsets: Vec<(SourcePartition, NextOffset)>,
+ pub pruned: Vec<SourcePartition>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct LedgerStats {
+ pub partitions: usize,
+ pub in_flight: usize,
+ pub uncommitted_events: u64,
+}
+
+impl Ledger {
+ pub fn observe(
+ &mut self,
+ partition: SourcePartition,
+ offset: SourceOffset,
+ observation: Observation,
+ ) {
+ let ledger = self
+ .partitions
+ .entry(partition)
+ .or_insert_with(|| PartitionLedger::new(offset));
+ ledger.high_watermark = ledger.high_watermark.max(offset);
+ if let Observation::InFlight = observation {
+ if ledger.in_flight.insert(offset) {
+ self.total_in_flight += 1;
+ }
+ }
+ }
+
+ /// `_outcome` is deliberately unused for advancement — see [`DeliveryOutcome`].
+ pub fn resolve(
+ &mut self,
+ partition: SourcePartition,
+ offset: SourceOffset,
+ _outcome: DeliveryOutcome,
+ ) -> Resolution {
+ let removed = self
+ .partitions
+ .get_mut(&partition)
+ .is_some_and(|ledger| ledger.in_flight.remove(&offset));
+ if removed {
+ self.total_in_flight -= 1;
+ Resolution::Resolved
+ } else {
+ Resolution::Untracked
+ }
+ }
+
+ /// Prunes partitions not in `assigned`, then returns offsets where committable > committed
+ /// (delta suppression). Does NOT mark committed — see [`Ledger::confirm_committed`].
+ pub fn commit_plan(&mut self, assigned: &BTreeSet<SourcePartition>) -> CommitPlan {
+ let pruned: Vec<SourcePartition> = self
+ .partitions
+ .keys()
+ .filter(|partition| !assigned.contains(partition))
+ .copied()
+ .collect();
+ for partition in &pruned {
+ if let Some(removed) = self.partitions.remove(partition) {
+ self.total_in_flight -= removed.in_flight.len();
+ }
+ }
+
+ let offsets = self
+ .partitions
+ .iter()
+ .filter(|(_, ledger)| ledger.has_committable())
+ .map(|(&partition, ledger)| (partition, ledger.committable()))
+ .collect();
+ CommitPlan { offsets, pruned }
+ }
+
+ /// Only after the broker commit succeeded; failed commits are retried next tick because the
+ /// unconfirmed delta keeps being emitted by [`Ledger::commit_plan`].
+ pub fn confirm_committed(&mut self, offsets: &[(SourcePartition, NextOffset)]) {
+ for &(partition, next) in offsets {
+ if let Some(ledger) = self.partitions.get_mut(&partition) {
+ ledger.committed = Some(ledger.committed.map_or(next, |current| current.max(next)));
+ }
+ }
+ }
+
+ /// Backpressure input for the intake guard.
+ pub fn in_flight(&self) -> usize {
+ self.total_in_flight
+ }
+
+ /// True when a commit tick would emit something — the liveness gate's "committable work
+ /// exists" input. Read-only: unlike [`Ledger::commit_plan`], never prunes.
+ pub fn has_committable(&self) -> bool {
+ self.partitions
+ .values()
+ .any(PartitionLedger::has_committable)
+ }
+
+ pub fn stats(&self) -> LedgerStats {
+ LedgerStats {
+ partitions: self.partitions.len(),
+ in_flight: self.total_in_flight,
+ uncommitted_events: self
+ .partitions
+ .values()
+ .map(PartitionLedger::uncommitted)
+ .sum(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use proptest::prelude::*;
+
+ const P0: SourcePartition = SourcePartition(0);
+
+ fn assigned(partitions: &[i32]) -> BTreeSet<SourcePartition> {
+ partitions.iter().copied().map(SourcePartition).collect()
+ }
+
+ fn plan_offsets(ledger: &mut Ledger, partitions: &[i32]) -> Vec<(i32, i64)> {
+ ledger
+ .commit_plan(&assigned(partitions))
+ .offsets
+ .into_iter()
+ .map(|(p, n)| (p.0, n.0))
+ .collect()
+ }
+
+ #[test]
+ fn empty_ledger_emits_nothing() {
+ let mut ledger = Ledger::default();
+ assert_eq!(
+ ledger.commit_plan(&assigned(&[0, 1])),
+ CommitPlan {
+ offsets: vec![],
+ pruned: vec![],
+ }
+ );
+ assert!(!ledger.has_committable());
+ assert_eq!(
+ ledger.stats(),
+ LedgerStats {
+ partitions: 0,
+ in_flight: 0,
+ uncommitted_events: 0,
+ }
+ );
+ }
+
+ #[test]
+ fn settled_events_commit_past_gaps() {
+ let mut ledger = Ledger::default();
+ for offset in [0, 2, 5] {
+ ledger.observe(P0, SourceOffset(offset), Observation::Settled);
+ }
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 6)]);
+ }
+
+ #[test]
+ fn oldest_in_flight_blocks_the_watermark() {
+ let mut ledger = Ledger::default();
+ ledger.observe(P0, SourceOffset(0), Observation::Settled);
+ ledger.observe(P0, SourceOffset(1), Observation::InFlight);
+ ledger.observe(P0, SourceOffset(2), Observation::Settled);
+ ledger.observe(P0, SourceOffset(3), Observation::InFlight);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 1)]);
+
+ // Out-of-order resolution: the newest ack alone does not unblock the oldest.
+ ledger.resolve(P0, SourceOffset(3), DeliveryOutcome::Acked);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 1)]);
+ ledger.resolve(P0, SourceOffset(1), DeliveryOutcome::Acked);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 4)]);
+ }
+
+ #[test]
+ fn unconfirmed_commit_is_reemitted_and_confirmed_commit_is_suppressed() {
+ let mut ledger = Ledger::default();
+ ledger.observe(P0, SourceOffset(0), Observation::Settled);
+
+ // Failed broker commit = no confirm: the same plan comes back next tick.
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 1)]);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 1)]);
+
+ ledger.confirm_committed(&[(P0, NextOffset(1))]);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![]);
+ assert!(!ledger.has_committable());
+
+ ledger.observe(P0, SourceOffset(1), Observation::Settled);
+ assert!(ledger.has_committable());
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 2)]);
+ }
+
+ #[test]
+ fn pruned_partition_is_forgotten_and_its_straggler_ack_is_untracked() {
+ let mut ledger = Ledger::default();
+ ledger.observe(P0, SourceOffset(7), Observation::InFlight);
+ ledger.observe(SourcePartition(1), SourceOffset(3), Observation::Settled);
+
+ let plan = ledger.commit_plan(&assigned(&[1]));
+ assert_eq!(plan.pruned, vec![P0]);
+ assert_eq!(plan.offsets, vec![(SourcePartition(1), NextOffset(4))]);
+ assert_eq!(ledger.in_flight(), 0);
+ assert_eq!(
+ ledger.resolve(P0, SourceOffset(7), DeliveryOutcome::Acked),
+ Resolution::Untracked
+ );
+ }
+
+ #[test]
+ fn confirm_and_watermark_are_monotonic() {
+ let mut ledger = Ledger::default();
+ ledger.observe(P0, SourceOffset(5), Observation::Settled);
+ // A re-observed lower offset (post-rebalance replay without a prune in between) must not
+ // regress the watermark.
+ ledger.observe(P0, SourceOffset(2), Observation::Settled);
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![(0, 6)]);
+
+ ledger.confirm_committed(&[(P0, NextOffset(6))]);
+ ledger.confirm_committed(&[(P0, NextOffset(4))]); // late/duplicate confirm
+ assert_eq!(plan_offsets(&mut ledger, &[0]), vec![]);
+ }
+
+ // --- model-based property tests ----------------------------------------------------------
+
+ const PARTITIONS: i32 = 3;
+
+ #[derive(Debug, Clone)]
+ enum Op {
+ Observe {
+ partition: i32,
+ gap: u8,
+ in_flight: bool,
+ },
+ ResolveNth {
+ partition: i32,
+ nth: u8,
+ },
+ Commit {
+ assigned_mask: u8,
+ confirm: bool,
+ },
+ }
+
+ fn op_strategy() -> impl Strategy<Value = Op> {
+ prop_oneof![
+ 5 => (0..PARTITIONS, 0u8..3, any::<bool>())
+ .prop_map(|(partition, gap, in_flight)| Op::Observe { partition, gap, in_flight }),
+ 3 => (0..PARTITIONS, any::<u8>())
+ .prop_map(|(partition, nth)| Op::ResolveNth { partition, nth }),
+ 2 => (0u8..(1 << PARTITIONS), any::<bool>())
+ .prop_map(|(assigned_mask, confirm)| Op::Commit { assigned_mask, confirm }),
+ ]
+ }
+
+ /// Naive reference: every observed offset with its resolution state, brute-forced plans.
+ #[derive(Debug, Default)]
+ struct ModelPartition {
+ first_observed: i64,
+ observed_max: i64,
+ unresolved: BTreeSet<i64>,
+ committed: Option<i64>,
+ }
+
+ impl ModelPartition {
+ fn committable(&self) -> i64 {
+ self.unresolved
+ .first()
+ .copied()
+ .unwrap_or(self.observed_max + 1)
+ }
+ }
+
+ #[derive(Debug, Default)]
+ struct Model {
+ partitions: BTreeMap<i32, ModelPartition>,
+ next_offset: BTreeMap<i32, i64>,
+ }
+
+ impl Model {
+ fn plan(&mut self, assigned_mask: u8) -> (Vec<(i32, i64)>, Vec<i32>) {
+ let pruned: Vec<i32> = self
+ .partitions
+ .keys()
+ .filter(|p| assigned_mask & (1 << **p) == 0)
+ .copied()
+ .collect();
+ for p in &pruned {
+ self.partitions.remove(p);
+ }
+ let offsets = self
+ .partitions
+ .iter()
+ .filter(|(_, part)| part.committed.is_none_or(|c| part.committable() > c))
+ .map(|(&p, part)| (p, part.committable()))
+ .collect();
+ (offsets, pruned)
+ }
+ }
+
+ fn apply(ledger: &mut Ledger, model: &mut Model, op: Op) -> Result<(), TestCaseError> {
+ match op {
+ Op::Observe {
+ partition,
+ gap,
+ in_flight,
+ } => {
+ let next = model.next_offset.entry(partition).or_insert(0);
+ let offset = *next + i64::from(gap);
+ *next = offset + 1;
+
+ let part = model
+ .partitions
+ .entry(partition)
+ .or_insert_with(|| ModelPartition {
+ first_observed: offset,
+ observed_max: offset,
+ ..ModelPartition::default()
+ });
+ part.observed_max = part.observed_max.max(offset);
+ let observation = if in_flight {
+ part.unresolved.insert(offset);
+ Observation::InFlight
+ } else {
+ Observation::Settled
+ };
+ ledger.observe(
+ SourcePartition(partition),
+ SourceOffset(offset),
+ observation,
+ );
+ }
+ Op::ResolveNth { partition, nth } => {
+ let Some(part) = model.partitions.get_mut(&partition) else {
+ return Ok(());
+ };
+ if part.unresolved.is_empty() {
+ return Ok(());
+ }
+ let offset = *part
+ .unresolved
+ .iter()
+ .nth(usize::from(nth) % part.unresolved.len())
+ .unwrap();
+ part.unresolved.remove(&offset);
+ let resolution = ledger.resolve(
+ SourcePartition(partition),
+ SourceOffset(offset),
+ DeliveryOutcome::Acked,
+ );
+ prop_assert_eq!(resolution, Resolution::Resolved);
+ }
+ Op::Commit {
+ assigned_mask,
+ confirm,
+ } => {
+ let assigned: BTreeSet<SourcePartition> = (0..PARTITIONS)
+ .filter(|p| assigned_mask & (1 << p) != 0)
+ .map(SourcePartition)
+ .collect();
+ let plan = ledger.commit_plan(&assigned);
+ let (model_offsets, model_pruned) = model.plan(assigned_mask);
+
+ // Equivalence with the naive model (subsumes the watermark rule).
+ let plan_raw: Vec<(i32, i64)> =
+ plan.offsets.iter().map(|&(p, n)| (p.0, n.0)).collect();
+ let pruned_raw: Vec<i32> = plan.pruned.iter().map(|p| p.0).collect();
+ prop_assert_eq!(&plan_raw, &model_offsets);
+ prop_assert_eq!(pruned_raw, model_pruned);
+
+ for &(partition, next) in &plan_raw {
+ let part = &model.partitions[&partition];
+ // P5: pruned/unassigned partitions never emitted.
+ prop_assert!(assigned_mask & (1 << partition) != 0);
+ // P2: safety — never commit past an unresolved forward.
+ if let Some(&oldest) = part.unresolved.first() {
+ prop_assert!(next <= oldest);
+ }
+ // P3: all-resolved ⇒ committable = high_watermark + 1.
+ if part.unresolved.is_empty() {
+ prop_assert_eq!(next, part.observed_max + 1);
+ }
+ // P1: emitted values strictly exceed the confirmed commit.
+ if let Some(committed) = part.committed {
+ prop_assert!(next > committed);
+ }
+ }
+
+ if confirm {
+ ledger.confirm_committed(&plan.offsets);
+ for (partition, next) in plan_raw {
+ model.partitions.get_mut(&partition).unwrap().committed = Some(next);
+ }
+ }
+ }
+ }
+
+ // Denormalized counter and stats stay consistent with the model.
+ let model_in_flight: usize = model.partitions.values().map(|p| p.unresolved.len()).sum();
+ prop_assert_eq!(ledger.in_flight(), model_in_flight);
+ let model_uncommitted: u64 = model
+ .partitions
+ .values()
+ .map(|p| (p.observed_max + 1 - p.committed.unwrap_or(p.first_observed)).max(0) as u64)
+ .sum();
+ prop_assert_eq!(
+ ledger.stats(),
+ LedgerStats {
+ partitions: model.partitions.len(),
+ in_flight: model_in_flight,
+ uncommitted_events: model_uncommitted,
+ }
+ );
+ Ok(())
+ }
+
+ proptest! {
+ #[test]
+ fn ledger_matches_reference_model(ops in proptest::collection::vec(op_strategy(), 1..200)) {
+ let mut ledger = Ledger::default();
+ let mut model = Model::default();
+ for op in ops {
+ apply(&mut ledger, &mut model, op)?;
+ }
+ }
+
+ /// P4: `Abandoned` advances the watermark exactly like `Acked`.
+ #[test]
+ fn abandoned_is_equivalent_to_acked(ops in proptest::collection::vec(op_strategy(), 1..100)) {
+ let mut acked = Ledger::default();
+ let mut abandoned = Ledger::default();
+ let all = (0..PARTITIONS).map(SourcePartition).collect::<BTreeSet<_>>();
+ let mut next_offset: BTreeMap<i32, i64> = BTreeMap::new();
+ let mut unresolved: BTreeMap<i32, BTreeSet<i64>> = BTreeMap::new();
+
+ for op in ops {
+ match op {
+ Op::Observe { partition, gap, in_flight } => {
+ let next = next_offset.entry(partition).or_insert(0);
+ let offset = *next + i64::from(gap);
+ *next = offset + 1;
+ let observation = if in_flight {
+ unresolved.entry(partition).or_default().insert(offset);
+ Observation::InFlight
+ } else {
+ Observation::Settled
+ };
+ acked.observe(SourcePartition(partition), SourceOffset(offset), observation);
+ abandoned.observe(SourcePartition(partition), SourceOffset(offset), observation);
+ }
+ Op::ResolveNth { partition, nth } => {
+ let Some(pending) = unresolved.get_mut(&partition) else { continue };
+ if pending.is_empty() { continue }
+ let offset = *pending.iter().nth(usize::from(nth) % pending.len()).unwrap();
+ pending.remove(&offset);
+ acked.resolve(SourcePartition(partition), SourceOffset(offset), DeliveryOutcome::Acked);
+ abandoned.resolve(SourcePartition(partition), SourceOffset(offset), DeliveryOutcome::Abandoned);
+ }
+ Op::Commit { confirm, .. } => {
+ let plan_a = acked.commit_plan(&all);
+ let plan_b = abandoned.commit_plan(&all);
+ prop_assert_eq!(&plan_a, &plan_b);
+ if confirm {
+ acked.confirm_committed(&plan_a.offsets);
+ abandoned.confirm_committed(&plan_b.offsets);
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/rust/cohort-event-shuffler/src/lib.rs b/rust/cohort-event-shuffler/src/lib.rs
index d736a07121cf..22d572d67d88 100644
--- a/rust/cohort-event-shuffler/src/lib.rs
+++ b/rust/cohort-event-shuffler/src/lib.rs
@@ -9,5 +9,6 @@ pub mod config;
pub mod consumer;
pub mod event;
pub mod filter_team_index;
+pub mod ledger;
pub mod observability;
pub mod producer;
diff --git a/rust/cohort-event-shuffler/src/main.rs b/rust/cohort-event-shuffler/src/main.rs
index 0c9052d9ecd9..085fe825153a 100644
--- a/rust/cohort-event-shuffler/src/main.rs
+++ b/rust/cohort-event-shuffler/src/main.rs
@@ -44,8 +44,9 @@ async fn async_main(config: Config) -> Result<()> {
let metrics_handle =
manager.register("metrics", ComponentOptions::new().is_observability(true));
- // The consumer owns the liveness deadline: no successful batch within deadline × stall_threshold
- // trips coordinated shutdown.
+ // The consumer owns the liveness deadline: a wedged pipeline iteration — or a stalled
+ // committer with committable work — stops heartbeats, and deadline × stall_threshold trips
+ // coordinated shutdown.
let consumer_handle = manager.register(
"consumer",
ComponentOptions::new()
@@ -112,8 +113,7 @@ async fn async_main(config: Config) -> Result<()> {
producer,
team_index,
consumer_handle,
- config.recv_batch_size,
- config.recv_batch_timeout(),
+ config.shuffler_settings(),
);
tokio::spawn(async move {
shuffler.process().await;
@@ -147,7 +147,8 @@ fn log_startup(config: &Config) {
consumer_group = %config.kafka_consumer_group,
partitioner = %config.kafka_producer_partitioner,
offset_reset = %config.kafka_consumer_offset_reset,
- recv_batch_size = config.recv_batch_size,
+ max_inflight_forwards = config.max_inflight_forwards,
+ commit_interval_ms = config.commit_interval_ms,
team_index_refresh_secs = config.team_index_refresh_secs,
team_allowlist = ?config.team_allowlist,
"starting cohort-event-shuffler",
diff --git a/rust/cohort-event-shuffler/src/observability/metrics.rs b/rust/cohort-event-shuffler/src/observability/metrics.rs
index db6c1ce5473a..784c030c4ec1 100644
--- a/rust/cohort-event-shuffler/src/observability/metrics.rs
+++ b/rust/cohort-event-shuffler/src/observability/metrics.rs
@@ -2,15 +2,35 @@
use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
-/// Every message that passed the gate parse, forwarded or not. The gate ignores most fields, so a
-/// skipped event that is invalid only on an ignored field (e.g. missing `person_mode`) still counts.
+// All labels are static — never per-partition (512-cardinality trap on the input topic).
+
+/// Every message the pipeline received with a payload, forwardable or not (including
+/// unparseable ones).
pub const EVENTS_CONSUMED: &str = "shuffler_events_consumed_total";
+/// Increments on delivery ack: the event made it out.
pub const EVENTS_FORWARDED: &str = "shuffler_events_forwarded_total";
pub const EVENTS_DROPPED_NO_PERSON_ID: &str = "shuffler_events_dropped_no_person_id_total";
pub const EVENTS_SKIPPED_TEAM_GATE: &str = "shuffler_events_skipped_team_gate_total";
+/// Serde failure at either gate or survivor parse; the event settles and is committed over.
+pub const EVENTS_UNPARSEABLE: &str = "shuffler_events_unparseable_total";
+/// Delivery failures + fatal enqueue errors.
pub const PRODUCE_ERRORS: &str = "shuffler_produce_errors_total";
pub const ACTIVE_TEAMS: &str = "shuffler_active_teams";
+pub const FORWARDS_ENQUEUED: &str = "shuffler_forwards_enqueued_total";
+/// Gauge, sampled at each commit tick.
+pub const FORWARDS_INFLIGHT: &str = "shuffler_forwards_inflight";
+/// Histogram, enqueue → delivery resolution; label `outcome` = `"acked"` | `"abandoned"`.
+pub const PRODUCE_ACK_SECONDS: &str = "shuffler_produce_ack_seconds";
+/// Forwards whose delivery failed after librdkafka's internal retries; dropped and committed over.
+pub const EVENTS_ABANDONED: &str = "shuffler_events_abandoned_total";
+pub const PRODUCE_QUEUE_FULL: &str = "shuffler_produce_queue_full_total";
+pub const COMMITS: &str = "shuffler_commits_total";
+pub const COMMIT_ERRORS: &str = "shuffler_commit_errors_total";
+/// Gauge: observed-but-unconfirmed events across partitions ≈ the crash-replay window.
+pub const UNCOMMITTED_EVENTS: &str = "shuffler_uncommitted_events";
+pub const LEDGER_PARTITIONS: &str = "shuffler_ledger_partitions";
+
/// # Panics
/// Panics if a global metrics recorder has already been installed.
pub fn install_recorder() -> PrometheusHandle {
diff --git a/rust/cohort-event-shuffler/src/producer.rs b/rust/cohort-event-shuffler/src/producer.rs
index fc6b7befa7cb..f7a590552b79 100644
--- a/rust/cohort-event-shuffler/src/producer.rs
+++ b/rust/cohort-event-shuffler/src/producer.rs
@@ -1,19 +1,20 @@
//! Kafka producer for `cohort_stream_events`. The `murmur2_random` partitioner is pinned in
-//! [`crate::config`]; this module only supplies the [`partition_key`].
+//! [`crate::config`]; this module only supplies the key via [`CohortStreamEvent::partition_key`].
+
+use std::time::Duration;
use anyhow::{Context, Result};
use common_kafka::config::KafkaConfig;
-use common_kafka::kafka_producer::{
- create_kafka_producer, send_keyed_iter_to_kafka_with_headers, KafkaContext, KafkaProduceError,
-};
+use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};
use common_liveness::SyncLivenessReporter;
-use rdkafka::producer::FutureProducer;
+use rdkafka::error::{KafkaError, RDKafkaErrorCode};
+use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};
-use crate::event::{partition_key, CohortStreamEvent};
+use crate::event::CohortStreamEvent;
-/// A producer stall blocks the consumer's `forward().await`, which stops the consumer (owner of
-/// the liveness deadline) from heartbeating and trips the stall detector. So the producer reports
-/// always-healthy rather than feeding its stats into the consumer's health and masking that stall.
+/// Liveness is owned by the pipeline loop's commit-freshness gate: a wedged producer stops
+/// acks, which stops commits, which withholds the consumer heartbeat. The stats callback
+/// therefore reports nothing rather than double-owning the signal.
#[derive(Clone, Copy)]
struct AlwaysHealthy;
@@ -22,6 +23,27 @@ impl SyncLivenessReporter for AlwaysHealthy {
fn report_unhealthy(&self) {}
}
+/// Enqueue failure, split by retriability: `QueueFull` means librdkafka's local buffer is at
+/// capacity and the same event can be retried after a backoff; anything else is fatal for this
+/// event (abandon and move on).
+#[derive(Debug, thiserror::Error)]
+pub enum EnqueueError {
+ #[error("producer queue full")]
+ QueueFull,
+ #[error("fatal enqueue error: {0}")]
+ Fatal(KafkaError),
+}
+
+impl From<KafkaError> for EnqueueError {
+ fn from(err: KafkaError) -> Self {
+ match err {
+ KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => Self::QueueFull,
+ other => Self::Fatal(other),
+ }
+ }
+}
+
+#[derive(Clone)]
pub struct CohortStreamProducer {
producer: FutureProducer<KafkaContext>,
topic: String,
@@ -35,19 +57,43 @@ impl CohortStreamProducer {
Ok(Self { producer, topic })
}
- /// Produces and awaits all acks. Results are returned in input order so the caller can gate
- /// offset commits on full success.
- pub async fn forward(
- &self,
- events: Vec<CohortStreamEvent>,
- ) -> Vec<Result<(), KafkaProduceError>> {
- send_keyed_iter_to_kafka_with_headers(
- &self.producer,
- &self.topic,
- |event: &CohortStreamEvent| Some(partition_key(event.team_id, &event.person_id)),
- |_| None,
- events,
- )
- .await
+ /// Hands the event to librdkafka without awaiting delivery; the returned future resolves on
+ /// broker ack. rdkafka copies the payload, so nothing is borrowed after this returns.
+ pub fn enqueue(&self, event: &CohortStreamEvent) -> Result<DeliveryFuture, EnqueueError> {
+ let payload =
+ serde_json::to_vec(event).expect("CohortStreamEvent serialization cannot fail");
+ let key = event.partition_key();
+ let record = FutureRecord::to(&self.topic).key(&key).payload(&payload);
+ self.producer
+ .send_result(record)
+ .map_err(|(err, _)| err.into())
+ }
+
+ /// Blocking: waits for outstanding deliveries; call from `spawn_blocking`.
+ pub fn flush(&self, timeout: Duration) -> Result<(), KafkaError> {
+ self.producer.flush(timeout)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn enqueue_error_splits_queue_full_from_fatal() {
+ assert!(matches!(
+ EnqueueError::from(KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull)),
+ EnqueueError::QueueFull
+ ));
+ assert!(matches!(
+ EnqueueError::from(KafkaError::MessageProduction(
+ RDKafkaErrorCode::MessageSizeTooLarge
+ )),
+ EnqueueError::Fatal(_)
+ ));
+ assert!(matches!(
+ EnqueueError::from(KafkaError::Canceled),
+ EnqueueError::Fatal(_)
+ ));
}
}
diff --git a/rust/cohort-event-shuffler/tests/integration.rs b/rust/cohort-event-shuffler/tests/integration.rs
index 3baf7984ac75..aa538b9a55aa 100644
--- a/rust/cohort-event-shuffler/tests/integration.rs
+++ b/rust/cohort-event-shuffler/tests/integration.rs
@@ -1,6 +1,7 @@
//! End-to-end shuffler test against an in-process rdkafka `MockCluster` (no external broker or DB).
//! Asserts that only forwardable events land, that each `(team_id, person_id)` lands on a single
-//! partition, and that the envelope payload maps every field.
+//! partition, that the envelope payload maps every field, and that the async commit path settles
+//! every input offset — including an unparseable poison pill — without over-forwarding.
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -16,7 +17,8 @@ use common_types::{ClickHouseEvent, PersonMode};
use lifecycle::{ComponentOptions, Manager};
use rdkafka::consumer::{Consumer, StreamConsumer};
use rdkafka::producer::{FutureProducer, FutureRecord};
-use rdkafka::{ClientConfig, Message};
+use rdkafka::{ClientConfig, Message, TopicPartitionList};
+use tokio_util::sync::CancellationToken;
use uuid::Uuid;
const INPUT_TOPIC: &str = "clickhouse_events_json";
@@ -53,8 +55,12 @@ fn test_config(bootstrap: &str) -> Config {
team_index_refresh_secs: 300,
team_index_refresh_jitter_secs: 0,
team_allowlist: TeamAllowlist::All,
- recv_batch_size: 100,
- recv_batch_timeout_ms: 200,
+ max_inflight_forwards: 4000, // matches the production default
+ commit_interval_ms: 200,
+ queue_full_backoff_ms: 100,
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 64,
+ kafka_producer_queue_messages: 100_000,
}
}
@@ -134,6 +140,43 @@ async fn collect_output(
collected
}
+/// Polls the shuffler group's committed offset for input partition 0 until it reaches
+/// `expected` (the next-offset past everything produced), proving the async ledger commit
+/// settled forwards, drops, skips, and the poison pill. The prober never subscribes, so it
+/// fetches offsets without joining (and rebalancing) the shuffler's group.
+async fn wait_for_committed_offset(bootstrap: &str, group: &str, expected: i64) {
+ let prober: StreamConsumer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap)
+ .set("group.id", group)
+ .set("enable.auto.commit", "false")
+ .create()
+ .expect("failed to create committed-offset prober");
+ let mut tpl = TopicPartitionList::new();
+ tpl.add_partition(INPUT_TOPIC, 0);
+
+ let deadline = Instant::now() + Duration::from_secs(30);
+ loop {
+ if let Ok(committed) = prober.committed_offsets(tpl.clone(), Duration::from_secs(5)) {
+ if let Some(elem) = committed.elements_for_topic(INPUT_TOPIC).first() {
+ if let rdkafka::Offset::Offset(value) = elem.offset() {
+ assert!(
+ value <= expected,
+ "committed offset {value} ran past the produced input {expected}"
+ );
+ if value == expected {
+ return;
+ }
+ }
+ }
+ }
+ assert!(
+ Instant::now() < deadline,
+ "timed out waiting for committed offset {expected}"
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+}
+
#[tokio::test]
async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
let (cluster, input_producer): (_, FutureProducer<_>) =
@@ -200,6 +243,9 @@ async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
},
];
+ // A poison pill mid-stream: unparseable, must settle and be committed over, never forwarded.
+ const GARBAGE_AFTER_INDEX: usize = 3;
+ let mut total_input_messages = 0i64;
let mut uuid_by_index = Vec::new();
for (index, spec) in inputs.iter().enumerate() {
let uuid = Uuid::from_u128(0xC0_0000 + index as u128);
@@ -212,6 +258,21 @@ async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
.await
.expect("input produce canceled")
.expect("input produce failed");
+ total_input_messages += 1;
+
+ if index == GARBAGE_AFTER_INDEX {
+ input_producer
+ .send_result(
+ FutureRecord::to(INPUT_TOPIC)
+ .key("garbage")
+ .payload("this is not json"),
+ )
+ .expect("enqueue garbage")
+ .await
+ .expect("garbage produce canceled")
+ .expect("garbage produce failed");
+ total_input_messages += 1;
+ }
}
let expected_forwardable: usize = inputs.iter().filter(|s| s.forwardable).count();
@@ -237,8 +298,7 @@ async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
producer,
team_index,
handle,
- config.recv_batch_size,
- config.recv_batch_timeout(),
+ config.shuffler_settings(),
);
tokio::spawn(async move { shuffler.process().await });
@@ -311,4 +371,240 @@ async fn shuffler_forwards_only_gated_events_with_stable_partitioning() {
first.source_offset, 0,
"first produced event has input offset 0"
);
+
+ // Commit progression: every input offset — settled drops/skips, acked forwards, and the
+ // poison pill — ends up covered by an explicit ledger commit.
+ wait_for_committed_offset(&bootstrap, "shuffler-itest", total_input_messages).await;
+}
+
+/// Graceful shutdown must commit through the drain path, not the periodic tick. With
+/// `commit_interval_ms` set to an hour the periodic committer cannot cover the input before
+/// shutdown, so the only way the committed offset reaches the full input count is
+/// `EventShuffler::drain_and_commit` running its final Sync commit after the shutdown signal. That
+/// path (producer flush, ack drain, final commit) runs on every pod rotation and is otherwise
+/// unexercised; a regression there would silently replay up to `commit_interval` of events per deploy.
+#[tokio::test]
+async fn shuffler_commits_via_drain_on_graceful_shutdown() {
+ let (cluster, input_producer): (_, FutureProducer<_>) =
+ common_kafka::test::create_mock_kafka().await;
+ cluster
+ .create_topic(INPUT_TOPIC, 1, 1)
+ .expect("create input topic");
+ cluster
+ .create_topic(OUTPUT_TOPIC, OUTPUT_PARTITIONS, 1)
+ .expect("create output topic");
+ let bootstrap = cluster.bootstrap_servers();
+ let mut config = test_config(&bootstrap);
+ // An hour out: the periodic tick can't fire during the test, so only the drain's final commit
+ // can carry the committed offset to the full input count.
+ config.commit_interval_ms = 3_600_000;
+
+ let team_index = Arc::new(TeamIndex::from_teams([2, 7]));
+
+ // Forward, drop, skip, then forward last: seeing every forward in the output proves intake
+ // consumed the whole input (including the poison pill) before we trigger shutdown.
+ let inputs = [
+ InputSpec {
+ team_id: 2,
+ person_id: Some("pA"),
+ event: "$pageview",
+ forwardable: true,
+ },
+ InputSpec {
+ team_id: 2,
+ person_id: None,
+ event: "$pageview",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 99,
+ person_id: Some("pX"),
+ event: "$pageview",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 7,
+ person_id: Some("pB"),
+ event: "$pageview",
+ forwardable: true,
+ },
+ ];
+ const GARBAGE_AFTER_INDEX: usize = 2;
+
+ let mut total_input_messages = 0i64;
+ for (index, spec) in inputs.iter().enumerate() {
+ let uuid = Uuid::from_u128(0xD0_0000 + index as u128);
+ let payload = serde_json::to_string(&clickhouse_event(uuid, spec)).unwrap();
+ let key = uuid.to_string();
+ input_producer
+ .send_result(FutureRecord::to(INPUT_TOPIC).key(&key).payload(&payload))
+ .expect("enqueue input")
+ .await
+ .expect("input produce canceled")
+ .expect("input produce failed");
+ total_input_messages += 1;
+
+ if index == GARBAGE_AFTER_INDEX {
+ input_producer
+ .send_result(
+ FutureRecord::to(INPUT_TOPIC)
+ .key("garbage")
+ .payload("this is not json"),
+ )
+ .expect("enqueue garbage")
+ .await
+ .expect("garbage produce canceled")
+ .expect("garbage produce failed");
+ total_input_messages += 1;
+ }
+ }
+
+ let expected_forwardable = inputs.iter().filter(|s| s.forwardable).count();
+
+ let shutdown = CancellationToken::new();
+ let mut manager = Manager::builder("shuffler-drain-itest")
+ .with_trap_signals(false)
+ .with_shutdown_token(shutdown.clone())
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let _monitor = manager.monitor_background();
+
+ let consumer =
+ SingleTopicConsumer::new(config.build_kafka_config(), config.build_consumer_config())
+ .expect("create shuffler consumer");
+ let producer =
+ CohortStreamProducer::new(&config.build_kafka_config(), OUTPUT_TOPIC.to_string())
+ .await
+ .expect("create shuffler producer");
+ let shuffler = EventShuffler::new(
+ consumer,
+ producer,
+ team_index,
+ handle,
+ config.shuffler_settings(),
+ );
+ let task = tokio::spawn(async move { shuffler.process().await });
+
+ let output = collect_output(&bootstrap, expected_forwardable, Duration::from_secs(40)).await;
+ assert_eq!(
+ output.len(),
+ expected_forwardable,
+ "forwards must flow before shutdown so the ledger has observed every offset",
+ );
+
+ // Nothing has committed the input yet (periodic tick is an hour out); the drain must.
+ shutdown.cancel();
+ wait_for_committed_offset(&bootstrap, "shuffler-itest", total_input_messages).await;
+
+ task.await.expect("shuffler task panicked");
+}
+
+/// The `QueueFull` → `Intake::RetryForward` path keeps the pipeline non-blocking under producer
+/// backpressure, but the other tests leave the producer queue at 100k messages so an enqueue never
+/// fails and it never runs. Here the queue holds a single message, so every forward after the first
+/// trips `QueueFull`, parks in `RetryForward`, and is re-enqueued by the timer arm. The pipeline
+/// must still deliver every forward and commit the full input: a parked forward that got dropped
+/// would miss the output, and one observed in the ledger before its enqueue landed would let the
+/// commit run past an undelivered offset.
+#[tokio::test]
+async fn shuffler_retries_forwards_parked_on_queue_full() {
+ let (cluster, input_producer): (_, FutureProducer<_>) =
+ common_kafka::test::create_mock_kafka().await;
+ cluster
+ .create_topic(INPUT_TOPIC, 1, 1)
+ .expect("create input topic");
+ cluster
+ .create_topic(OUTPUT_TOPIC, OUTPUT_PARTITIONS, 1)
+ .expect("create output topic");
+ let bootstrap = cluster.bootstrap_servers();
+ let mut config = test_config(&bootstrap);
+ // One-message producer queue: a second concurrent enqueue fails with QueueFull, forcing the
+ // whole burst through the RetryForward path.
+ config.kafka_producer_queue_messages = 1;
+
+ let team_index = Arc::new(TeamIndex::from_teams([2, 7]));
+
+ // A drop and a skip, then a burst of forwards (all re-keyed to one partition), so both settled
+ // and acked offsets are committed under queue pressure.
+ let mut inputs = vec![
+ InputSpec {
+ team_id: 2,
+ person_id: None,
+ event: "$pageview",
+ forwardable: false,
+ },
+ InputSpec {
+ team_id: 99,
+ person_id: Some("pX"),
+ event: "$pageview",
+ forwardable: false,
+ },
+ ];
+ for _ in 0..10 {
+ inputs.push(InputSpec {
+ team_id: 2,
+ person_id: Some("pA"),
+ event: "$pageview",
+ forwardable: true,
+ });
+ }
+
+ let mut total_input_messages = 0i64;
+ let mut forwardable_uuids: std::collections::HashSet<String> = std::collections::HashSet::new();
+ for (index, spec) in inputs.iter().enumerate() {
+ let uuid = Uuid::from_u128(0xE0_0000 + index as u128);
+ if spec.forwardable {
+ forwardable_uuids.insert(uuid.to_string());
+ }
+ let payload = serde_json::to_string(&clickhouse_event(uuid, spec)).unwrap();
+ let key = uuid.to_string();
+ input_producer
+ .send_result(FutureRecord::to(INPUT_TOPIC).key(&key).payload(&payload))
+ .expect("enqueue input")
+ .await
+ .expect("input produce canceled")
+ .expect("input produce failed");
+ total_input_messages += 1;
+ }
+
+ let expected_forwardable = forwardable_uuids.len();
+
+ let mut manager = Manager::builder("shuffler-queuefull-itest")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let _monitor = manager.monitor_background();
+
+ let consumer =
+ SingleTopicConsumer::new(config.build_kafka_config(), config.build_consumer_config())
+ .expect("create shuffler consumer");
+ let producer =
+ CohortStreamProducer::new(&config.build_kafka_config(), OUTPUT_TOPIC.to_string())
+ .await
+ .expect("create shuffler producer");
+ let shuffler = EventShuffler::new(
+ consumer,
+ producer,
+ team_index,
+ handle,
+ config.shuffler_settings(),
+ );
+ tokio::spawn(async move { shuffler.process().await });
+
+ let output = collect_output(&bootstrap, expected_forwardable, Duration::from_secs(40)).await;
+ let output_uuids: std::collections::HashSet<String> =
+ output.iter().map(|(_, e)| e.uuid.clone()).collect();
+ assert_eq!(
+ output_uuids, forwardable_uuids,
+ "every forward must reach the output topic despite QueueFull backpressure",
+ );
+
+ // Commit must still advance past the whole burst (settled drop/skip + acked forwards).
+ wait_for_committed_offset(&bootstrap, "shuffler-itest", total_input_messages).await;
}
diff --git a/rust/common/kafka/src/kafka_consumer.rs b/rust/common/kafka/src/kafka_consumer.rs
index 5993cd4f848f..e231a6d00aa0 100644
--- a/rust/common/kafka/src/kafka_consumer.rs
+++ b/rust/common/kafka/src/kafka_consumer.rs
@@ -10,7 +10,7 @@ use lz4::Decoder;
use rdkafka::{
consumer::{CommitMode, Consumer, ConsumerGroupMetadata, StreamConsumer},
error::KafkaError,
- ClientConfig, Message,
+ ClientConfig, Message, TopicPartitionList,
};
use serde::de::DeserializeOwned;
use tracing::warn;
@@ -217,6 +217,33 @@ impl SingleTopicConsumer {
pub fn commit(&self) -> Result<(), KafkaError> {
self.inner.consumer.commit_consumer_state(CommitMode::Sync)
}
+
+ /// Synchronously commit explicit next-offsets for this consumer's topic, bypassing stored
+ /// offsets. Each pair is `(partition, next_offset)` where `next_offset` is the offset
+ /// consumption should resume from (last fully processed + 1), per Kafka commit semantics.
+ pub fn commit_partition_offsets(&self, offsets: &[(i32, i64)]) -> Result<(), KafkaError> {
+ let mut tpl = TopicPartitionList::with_capacity(offsets.len());
+ for &(partition, next_offset) in offsets {
+ tpl.add_partition_offset(
+ &self.inner.topic,
+ partition,
+ rdkafka::Offset::Offset(next_offset),
+ )?;
+ }
+ self.inner.consumer.commit(&tpl, CommitMode::Sync)
+ }
+
+ /// Currently assigned partitions of this consumer's topic (local call, no broker round-trip).
+ pub fn assigned_partitions(&self) -> Result<Vec<i32>, KafkaError> {
+ Ok(self
+ .inner
+ .consumer
+ .assignment()?
+ .elements_for_topic(&self.inner.topic)
+ .iter()
+ .map(|elem| elem.partition())
+ .collect())
+ }
}
fn maybe_decompress_lz4_payload<'a>(payload: &'a [u8], topic: &str) -> Cow<'a, [u8]> {
@@ -349,11 +376,17 @@ impl fmt::Debug for Offset {
#[cfg(test)]
mod tests {
use std::io::Write;
+ use std::time::Duration;
+ use envconfig::Envconfig;
use lz4::EncoderBuilder;
+ use rdkafka::consumer::Consumer;
+ use rdkafka::producer::FutureRecord;
use serde_json::{json, Value};
+ use super::SingleTopicConsumer;
use super::{decompress_lz4_payload, maybe_decompress_lz4_payload, Lz4PayloadError};
+ use crate::config::ConsumerConfig;
fn decode_json_payload(payload: &[u8], topic: &str) -> Result<Value, serde_json::Error> {
let payload = maybe_decompress_lz4_payload(payload, topic);
@@ -405,4 +438,55 @@ mod tests {
result.unwrap();
compressed
}
+
+ #[tokio::test]
+ async fn commits_explicit_partition_offsets_and_reports_assignment() {
+ const TOPIC: &str = "explicit-commit-topic";
+ let (cluster, producer) = crate::test::create_mock_kafka().await;
+ cluster.create_topic(TOPIC, 1, 1).expect("create topic");
+
+ let mut kafka_config = crate::config::KafkaConfig::init_from_env().unwrap();
+ kafka_config.kafka_hosts = cluster.bootstrap_servers();
+ let consumer_config = ConsumerConfig {
+ kafka_consumer_group: "explicit-commit-group".to_string(),
+ kafka_consumer_topic: TOPIC.to_string(),
+ kafka_consumer_offset_reset: "earliest".to_string(),
+ kafka_consumer_auto_commit: false,
+ kafka_consumer_auto_commit_interval_ms: 5000,
+ kafka_consumer_fetch_wait_max_ms: None,
+ kafka_consumer_fetch_min_bytes: None,
+ kafka_consumer_fetch_max_bytes: None,
+ kafka_consumer_max_partition_fetch_bytes: None,
+ kafka_consumer_group_instance_id: None,
+ kafka_consumer_partition_strategy: None,
+ kafka_consumer_socket_send_buffer_bytes: None,
+ kafka_consumer_socket_receive_buffer_bytes: None,
+ kafka_consumer_metadata_refresh_interval_ms: None,
+ };
+ let consumer = SingleTopicConsumer::new(kafka_config, consumer_config).unwrap();
+
+ producer
+ .send_result(FutureRecord::to(TOPIC).key("k").payload(r#"{"a":1}"#))
+ .expect("enqueue")
+ .await
+ .expect("produce canceled")
+ .expect("produce failed");
+
+ let (_, offset) = consumer.json_recv::<Value>().await.expect("recv");
+ assert_eq!((offset.partition(), offset.get_value()), (0, 0));
+
+ assert_eq!(consumer.assigned_partitions().unwrap(), vec![0]);
+ consumer
+ .commit_partition_offsets(&[(0, 1)])
+ .expect("explicit commit");
+
+ let committed = consumer
+ .inner
+ .consumer
+ .committed(Duration::from_secs(5))
+ .expect("fetch committed");
+ let elems = committed.elements_for_topic(TOPIC);
+ assert_eq!(elems.len(), 1);
+ assert_eq!(elems[0].offset(), rdkafka::Offset::Offset(1));
+ }
}