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.

chore(cohorts): decouple heartbeat (#67940)

Matheus Batista90ee16d68e9d
diff --git a/SESSION.md b/SESSION.md
new file mode 100644
index 000000000000..077d92bb5a4f
--- /dev/null
+++ b/SESSION.md
@@ -0,0 +1,4 @@
+# SESSION — deferred issues (PR #67940, decouple heartbeat)
+
+- **`run_pauser_loop` executes blocking librdkafka FFI on a tokio worker thread.** The 3-thread runtime is already saturated by sync RocksDB reads (gate report §3); a wedged `pause()`/`resume()` call parks one of three threads. It no longer gates the heartbeat (that runs on the consume loop), but under thread starvation the re-assertion could lag. Optional hardening: `spawn_blocking` inside the pauser loop, or a dedicated single-thread runtime for the pauser.
+- **`EventDispatcher::dispatch` (blocking) has zero production callers** — ~30 test call sites in `consumers/events.rs` + 1 in `tests/sweep_worker.rs`. Follow-up (per haacked, explicitly deferred out of #67940): migrate tests to `dispatch_events_nonblocking` and delete `dispatch` so there's a single dispatch path to maintain.
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index a295bc398f2b..b14ae5f3f0d7 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -35,12 +35,15 @@ use crate::observability::metrics::{
COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED, COHORT_STREAM_WORKERS_SPAWNED,
DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL, DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL,
DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL, MERGE_HELD_OFFSET_GAUGE,
- MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL, PARTITIONS_REVOKED_TOTAL,
- PARTITION_STATE_DELETED_TOTAL, REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,
+ MERGE_PENDING_TRANSFERS_GAUGE, PARTITIONS_ASSIGNED_TOTAL, PARTITIONS_PAUSED,
+ PARTITIONS_REVOKED_TOTAL, PARTITION_STATE_DELETED_TOTAL, PENDING_HELD_EVENTS,
+ REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,
};
+use crate::partitions::backpressure::Backpressure;
use crate::partitions::offset_tracker::OffsetTracker;
+use crate::partitions::pause::{ConsumerPauser, PartitionPauser};
use crate::partitions::rebalance::{CohortConsumerContext, ConsumerCommandReceiver};
-use crate::partitions::router::PartitionRouter;
+use crate::partitions::router::{PartitionRouter, SendOutcome};
use crate::partitions::shuffle_message::ShuffleMessage;
use crate::producer::MembershipSink;
use crate::store::durability::OffsetManifest;
@@ -194,7 +197,8 @@ impl EventDispatcher {
&self.store
}
- /// Route a consumed batch to per-partition workers, lazily spawning on first delivery.
+ /// Blocking events dispatch, retained for tests; the consume loop uses
+ /// [`dispatch_events_nonblocking`](Self::dispatch_events_nonblocking).
///
/// The dispatch ceiling is raised before routing so a `RouteError` leaves the offset
/// uncommittable and Kafka replays it. Events for unowned partitions are dropped before any
@@ -221,6 +225,116 @@ impl EventDispatcher {
counter!(COHORT_STREAM_EVENTS_DISPATCHED).increment(stats.dispatched);
}
+ /// Non-blocking events dispatch: `try_send`s each non-held partition's sub-batch and raises the
+ /// dispatch ceiling only for what lands. Events for a partition in `held` (already paused behind an
+ /// older holdover) skip the send and are returned to queue behind it. Returns the un-dispatched
+ /// events per partition for the caller to hold and pause.
+ pub fn dispatch_events_nonblocking(
+ &self,
+ batch: Vec<ConsumedEvent>,
+ held: &HashSet<i32>,
+ ) -> HashMap<i32, Vec<ShuffleMessage>> {
+ if self.draining.load(Ordering::SeqCst) {
+ if !batch.is_empty() {
+ counter!(COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED).increment(batch.len() as u64);
+ debug!(
+ dropped = batch.len(),
+ "dispatch after shutdown began; dropping batch for replay"
+ );
+ }
+ return HashMap::new();
+ }
+
+ let mut full: HashMap<i32, Vec<ShuffleMessage>> = HashMap::new();
+ let mut fresh: Vec<(i32, ShuffleMessage)> = Vec::with_capacity(batch.len());
+ let mut not_owned = 0u64;
+ for consumed in batch {
+ let partition = consumed.partition;
+ if !self.owned.contains(&partition) {
+ not_owned += 1;
+ continue;
+ }
+ self.ensure_worker(partition);
+ let message = ShuffleMessage::Event {
+ event: Box::new(consumed.event),
+ cse_offset: consumed.offset,
+ };
+ // A paused partition can still deliver a few already-fetched stragglers; queue them behind
+ // the holdover rather than racing them ahead of older offsets.
+ if held.contains(&partition) {
+ full.entry(partition).or_default().push(message);
+ } else {
+ fresh.push((partition, message));
+ }
+ }
+ counter!(COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED).increment(not_owned);
+
+ self.route_and_fold(fresh, &mut full);
+ full
+ }
+
+ /// Retry-send held sub-batches, raising the ceiling for any that flush. Returns the partitions
+ /// still full (retained holdover) to keep paused; a flushed or worker-gone one is absent, so the
+ /// caller resumes it.
+ pub fn redispatch_held(
+ &self,
+ held: Vec<(i32, Vec<ShuffleMessage>)>,
+ ) -> HashMap<i32, Vec<ShuffleMessage>> {
+ // Each partition's Vec stays contiguous, so the regrouped route keeps offset order.
+ let mut messages: Vec<(i32, ShuffleMessage)> = Vec::new();
+ for (partition, batch) in held {
+ for message in batch {
+ messages.push((partition, message));
+ }
+ }
+ let mut still_full = HashMap::new();
+ self.route_and_fold(messages, &mut still_full);
+ still_full
+ }
+
+ /// `try_send` events and fold the outcomes: raise the ceiling for what landed, collect a full
+ /// channel's un-sent sub-batch into `full`, and count a missing/closed worker as a route error.
+ /// Folds for both the fresh dispatch and the [`redispatch_held`](Self::redispatch_held) retry.
+ fn route_and_fold(
+ &self,
+ messages: Vec<(i32, ShuffleMessage)>,
+ full: &mut HashMap<i32, Vec<ShuffleMessage>>,
+ ) {
+ let mut dispatched = 0u64;
+ let mut route_errors = 0u64;
+ for (partition, outcome) in self.router.try_route_batch(messages) {
+ match outcome {
+ SendOutcome::Sent { max_offset, count } => {
+ // Ceiling raised after `try_send`, so a worker could mark this batch processed first
+ // and trip a spurious `CappedAheadOfDispatch`. Harmless (marks are monotonic and
+ // commits derive from `processed`, so the next dispatch corrects it) and near
+ // unreachable (per-event work is ~hundreds of reads; this mark is microseconds off).
+ // Marking before the send would wrongly raise the ceiling for `Full`/dropped
+ // sub-batches. `None` carries no offset, so it leaves the ceiling untouched.
+ if let Some(max_offset) = max_offset {
+ self.tracker.mark_dispatched(partition, max_offset + 1);
+ }
+ dispatched += count as u64;
+ }
+ SendOutcome::Full(returned) => {
+ full.entry(partition).or_default().extend(returned);
+ }
+ SendOutcome::NoWorker | SendOutcome::ChannelClosed => route_errors += 1,
+ }
+ }
+ if dispatched > 0 {
+ counter!(COHORT_STREAM_EVENTS_DISPATCHED).increment(dispatched);
+ }
+ if route_errors > 0 {
+ counter!(COHORT_STREAM_ROUTE_ERRORS).increment(route_errors);
+ }
+ }
+
+ /// Snapshot of the partitions currently owned, for the backpressure prune/reconcile pass.
+ pub fn owned_set(&self) -> HashSet<i32> {
+ self.owned.iter().map(|entry| *entry).collect()
+ }
+
/// Route a consumed `person_merge_events` batch to per-partition workers, ceiling on the merge
/// tracker. Spawns workers (unlike sweep) because merges are durable external input.
pub async fn dispatch_merges(&self, batch: Vec<ConsumedMerge>) {
@@ -779,6 +893,8 @@ pub struct CohortStreamEventsConsumer {
topic: String,
dispatcher: Arc<EventDispatcher>,
handle: Handle,
+ /// Pauses/resumes events partitions to express downstream backpressure as lag.
+ pauser: Arc<dyn PartitionPauser>,
recv_batch_size: usize,
recv_batch_timeout: Duration,
offset_commit_interval: Duration,
@@ -805,11 +921,15 @@ impl CohortStreamEventsConsumer {
consumer_command_rx: ConsumerCommandReceiver,
restore_manifest: Option<OffsetManifest>,
) -> Self {
+ let consumer = Arc::new(consumer);
+ let pauser: Arc<dyn PartitionPauser> =
+ Arc::new(ConsumerPauser::new(consumer.clone(), topic.clone()));
Self {
- consumer: Arc::new(consumer),
+ consumer,
topic,
dispatcher,
handle,
+ pauser,
recv_batch_size,
recv_batch_timeout,
offset_commit_interval,
@@ -823,7 +943,7 @@ impl CohortStreamEventsConsumer {
///
/// Offset commit runs on its own interval task so a CPU-saturated consume loop or worker backlog
/// can't block offset advancement; it shares the shutdown signal and is awaited before the final
- /// synchronous commit. Liveness is reported inline from `handle_outcome`.
+ /// synchronous commit. Liveness is reported inline from the non-blocking backpressure cycle.
pub async fn process(self) {
let _guard = self.handle.process_scope();
info!(topic = %self.topic, "cohort_stream_events consume loop starting");
@@ -836,11 +956,22 @@ impl CohortStreamEventsConsumer {
self.handle.clone(),
));
+ // Apply pause/resume off the consume loop: librdkafka's are synchronous, un-timed FFI, so a
+ // wedged client must never delay the heartbeat. The loop hands over the paused *target* (the
+ // held-partition set); the pauser task owns re-asserting it.
+ let (pause_tx, pause_rx) = tokio::sync::mpsc::unbounded_channel::<HashSet<i32>>();
+ let pauser_task = tokio::spawn(run_pauser_loop(self.pauser.clone(), pause_rx));
+
// One-shot guards; each pre-marked done when its gate is off, keeping the non-durable path unchanged.
let mut boot_sweep_done = !self.dispatcher.durable_restore_enabled();
let mut eager_redrive_done = !self.dispatcher.durable_restore_enabled();
let mut restore_seek_done = self.restore_manifest.is_none();
let mut prev_assignment: Option<HashSet<i32>> = None;
+ // Untouched until boot recovery completes below, so nothing pauses during boot.
+ let mut backpressure = Backpressure::new();
+ // Last paused target sent to the pauser task: lets us send only while backpressure is active
+ // (plus the cycle it clears) and stay silent otherwise.
+ let mut prev_paused_target: HashSet<i32> = HashSet::new();
loop {
tokio::select! {
@@ -872,7 +1003,13 @@ impl CohortStreamEventsConsumer {
restore_seek_done = self.run_restore_seek();
continue;
}
- self.handle_outcome(outcome).await;
+ self.dispatch_with_backpressure(
+ outcome,
+ &mut backpressure,
+ &mut prev_paused_target,
+ &pause_tx,
+ )
+ .await;
}
}
}
@@ -881,6 +1018,11 @@ impl CohortStreamEventsConsumer {
if let Err(err) = commit_task.await {
warn!(error = %err, "offset-commit task did not exit cleanly");
}
+ // Drop the sender so the pauser task drains and exits.
+ drop(pause_tx);
+ if let Err(err) = pauser_task.await {
+ warn!(error = %err, "pauser task did not exit cleanly");
+ }
let tracker = self.dispatcher.shutdown().await;
let offsets = self.dispatcher.owned_committable_offsets();
@@ -975,7 +1117,16 @@ impl CohortStreamEventsConsumer {
}
}
- async fn handle_outcome(&self, outcome: ConsumeOutcome) {
+ /// One steady-state cycle: prune revoked holdover, retry-flush held partitions, dispatch the polled
+ /// batch, reconcile the paused set and hand its deltas to the pauser task. Every step is
+ /// non-blocking, so the heartbeat below fires each iteration regardless of downstream drain.
+ async fn dispatch_with_backpressure(
+ &self,
+ outcome: ConsumeOutcome,
+ backpressure: &mut Backpressure,
+ prev_paused_target: &mut HashSet<i32>,
+ pause_tx: &tokio::sync::mpsc::UnboundedSender<HashSet<i32>>,
+ ) {
histogram!(COHORT_STREAM_CONSUME_BATCH_SIZE).record(outcome.events.len() as f64);
if !outcome.events.is_empty() {
counter!(COHORT_STREAM_EVENTS_CONSUMED).increment(outcome.events.len() as u64);
@@ -987,7 +1138,31 @@ impl CohortStreamEventsConsumer {
counter!(COHORT_STREAM_EMPTY_PAYLOAD).increment(outcome.empty_payloads);
}
- self.dispatcher.dispatch(outcome.events).await;
+ let owned = self.dispatcher.owned_set();
+ backpressure.prune_revoked(&owned);
+ // Retry-flush held partitions before dispatching new events, so a newer offset never leapfrogs
+ // an older held one on the same partition.
+ let still_full = self.dispatcher.redispatch_held(backpressure.take_held());
+ backpressure.absorb(still_full);
+ let full = self
+ .dispatcher
+ .dispatch_events_nonblocking(outcome.events, &backpressure.held_partitions());
+ backpressure.absorb(full);
+
+ // Hand the pauser task the paused target (the still-held partitions); it re-asserts pause
+ // idempotently, so no librdkafka call can delay the heartbeat below. Send every cycle the
+ // target is non-empty (re-asserting heals a swallowed pause error or a rebalance-reset toppar),
+ // plus the one cycle it clears (to resume); stay silent otherwise.
+ let target = backpressure.held_partitions();
+ if !target.is_empty() || !prev_paused_target.is_empty() {
+ if pause_tx.send(target.clone()).is_err() {
+ // The receiver is gone only at shutdown, where an unapplied target is moot.
+ debug!("pauser task has exited; skipping a pause/resume update");
+ }
+ *prev_paused_target = target;
+ }
+ gauge!(PARTITIONS_PAUSED).set(backpressure.held_partition_count() as f64);
+ gauge!(PENDING_HELD_EVENTS).set(backpressure.held_event_count() as f64);
if outcome.transport_error {
tokio::time::sleep(RECV_ERROR_BACKOFF).await;
@@ -1160,6 +1335,24 @@ async fn run_commit_loop(
}
}
+/// Applies the paused-partition target off the consume loop, so blocking librdkafka `pause`/`resume`
+/// never delays the heartbeat. Re-asserts the full target every update — idempotent in librdkafka — so
+/// a swallowed pause error or a rebalance-reset toppar self-heals. `applied` tracks only which
+/// partitions to resume (those that left the target). Exits when the sender is dropped.
+async fn run_pauser_loop(
+ pauser: Arc<dyn PartitionPauser>,
+ mut rx: tokio::sync::mpsc::UnboundedReceiver<HashSet<i32>>,
+) {
+ let mut applied: HashSet<i32> = HashSet::new();
+ while let Some(target) = rx.recv().await {
+ let to_pause: Vec<i32> = target.iter().copied().collect();
+ let to_resume: Vec<i32> = applied.difference(&target).copied().collect();
+ pauser.pause(&to_pause);
+ pauser.resume(&to_resume);
+ applied = target;
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1173,6 +1366,7 @@ mod tests {
MergeStateTransfer, PendingTransfer, PersonMergeEvent, Tombstone, TransferLeaf,
MERGE_EVENT_SCHEMA_VERSION,
};
+ use crate::partitions::offset_tracker::MarkOutcome;
use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
use crate::producer::{
CaptureSink, CaptureStreamEventSink, CaptureTransferSink, MembershipStatus,
@@ -1189,6 +1383,74 @@ mod tests {
const BEHAVIORAL_HASH: [u8; 16] = *b"0123456789abcdef";
const BASE_TS: &str = "2026-05-26 12:34:56.789000";
+ /// Broker-free [`PartitionPauser`] recording every pause/resume call, to exercise the pauser task
+ /// without a Kafka client.
+ #[derive(Default)]
+ struct RecordingPauser {
+ paused: std::sync::Mutex<Vec<Vec<i32>>>,
+ resumed: std::sync::Mutex<Vec<Vec<i32>>>,
+ }
+
+ impl RecordingPauser {
+ /// The non-empty pause calls, in order (the pauser also issues empty no-ops each idle cycle).
+ fn nonempty_pauses(&self) -> Vec<Vec<i32>> {
+ Self::nonempty(&self.paused)
+ }
+
+ fn nonempty_resumes(&self) -> Vec<Vec<i32>> {
+ Self::nonempty(&self.resumed)
+ }
+
+ fn nonempty(calls: &std::sync::Mutex<Vec<Vec<i32>>>) -> Vec<Vec<i32>> {
+ calls
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|call| !call.is_empty())
+ .cloned()
+ .collect()
+ }
+ }
+
+ impl PartitionPauser for RecordingPauser {
+ fn pause(&self, partitions: &[i32]) {
+ self.paused.lock().unwrap().push(partitions.to_vec());
+ }
+
+ fn resume(&self, partitions: &[i32]) {
+ self.resumed.lock().unwrap().push(partitions.to_vec());
+ }
+ }
+
+ #[tokio::test]
+ async fn pauser_loop_reasserts_the_full_target_each_cycle_and_resumes_on_drop() {
+ let pauser = Arc::new(RecordingPauser::default());
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<HashSet<i32>>();
+ let task = tokio::spawn(run_pauser_loop(pauser.clone(), rx));
+
+ // Stable target over two cycles: re-paused each time. That idempotent re-assertion is what
+ // heals a swallowed pause error or a rebalance-reset toppar.
+ tx.send(HashSet::from([5])).unwrap();
+ tx.send(HashSet::from([5])).unwrap();
+ // Partition 5 drains and 7 becomes held: 5 leaves the target (resumed), 7 is paused.
+ tx.send(HashSet::from([7])).unwrap();
+ // Target clears: 7 is resumed.
+ tx.send(HashSet::new()).unwrap();
+ drop(tx);
+ task.await.unwrap();
+
+ assert_eq!(
+ pauser.nonempty_pauses(),
+ vec![vec![5], vec![5], vec![7]],
+ "the full target is re-paused every cycle it is non-empty",
+ );
+ assert_eq!(
+ pauser.nonempty_resumes(),
+ vec![vec![5], vec![7]],
+ "a partition is resumed only once it leaves the target",
+ );
+ }
+
#[test]
fn deserializes_a_full_shuffler_envelope() {
let value = json!({
@@ -1788,6 +2050,122 @@ mod tests {
let _tracker = dispatcher.shutdown().await;
}
+ /// A dispatcher whose router uses `buffer` channel slots and no real worker, so a pre-filled
+ /// channel exercises the `try_send`-full path.
+ fn dispatcher_with_buffer(
+ store: &CohortStore,
+ catalog: Arc<CatalogHandle>,
+ buffer: usize,
+ ) -> EventDispatcher {
+ let sink: Arc<dyn MembershipSink> = Arc::new(CaptureSink::new());
+ EventDispatcher::new(
+ PartitionRouter::new(buffer),
+ Arc::new(OffsetTracker::new()),
+ store.clone(),
+ catalog,
+ sink,
+ MergeWorkerDeps::capture(),
+ )
+ }
+
+ fn held_offsets(messages: &[ShuffleMessage]) -> Vec<i64> {
+ messages
+ .iter()
+ .filter_map(ShuffleMessage::event_offset)
+ .collect()
+ }
+
+ #[tokio::test]
+ async fn nonblocking_dispatch_holds_a_full_channel_and_advances_the_offset_only_after_flush() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with_buffer(&store, behavioral_catalog(), 1);
+ dispatcher.assign_partition(0);
+ // Hold the receiver so nothing drains; ensure_worker reuses the registered channel and spawns
+ // no worker, leaving this rx the only consumer.
+ let mut rx = dispatcher.router.add_partition(0).unwrap();
+ let no_held = HashSet::new();
+
+ // Batch A fills the one slot and raises the ceiling to 105.
+ assert!(dispatcher
+ .dispatch_events_nonblocking(vec![consumed(person(1), 0, 104)], &no_held)
+ .is_empty());
+ // Batch B finds the channel full: held verbatim, ceiling unchanged.
+ let mut full =
+ dispatcher.dispatch_events_nonblocking(vec![consumed(person(2), 0, 105)], &no_held);
+ let held = full.remove(&0).expect("partition 0 was held");
+ assert_eq!(held_offsets(&held), vec![105]);
+ assert!(
+ dispatcher.workers.is_empty(),
+ "no worker drained the channel"
+ );
+
+ // The hole at 105 can't be committed past: a worker marking beyond the ceiling clamps to it.
+ assert_eq!(
+ dispatcher.tracker().mark_processed(0, 106),
+ MarkOutcome::CappedAheadOfDispatch,
+ );
+ assert_eq!(
+ dispatcher.tracker().committable_offsets().get(&0),
+ Some(&105),
+ "committable pinned at the sent ceiling while 105 is held",
+ );
+
+ // Drain A; the retry-flush now sends B and the ceiling advances past it.
+ let _a = rx.recv().await.unwrap();
+ assert!(
+ dispatcher.redispatch_held(vec![(0, held)]).is_empty(),
+ "the holdover flushed once the channel had room",
+ );
+ assert_eq!(
+ dispatcher.tracker().mark_processed(0, 106),
+ MarkOutcome::WithinDispatch,
+ );
+ assert_eq!(
+ dispatcher.tracker().committable_offsets().get(&0),
+ Some(&106)
+ );
+ }
+
+ #[tokio::test]
+ async fn nonblocking_dispatch_defers_events_for_a_held_partition_even_with_room() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with_buffer(&store, behavioral_catalog(), 16);
+ dispatcher.assign_partition(0);
+ let mut rx = dispatcher.router.add_partition(0).unwrap();
+
+ // Partition 0 is already held: its fresh events queue behind the holdover rather than racing
+ // onto the channel, even with room.
+ let held: HashSet<i32> = [0].into_iter().collect();
+ let mut full =
+ dispatcher.dispatch_events_nonblocking(vec![consumed(person(1), 0, 200)], &held);
+
+ assert_eq!(held_offsets(&full.remove(&0).unwrap()), vec![200]);
+ assert!(rx.try_recv().is_err(), "nothing was sent to the channel");
+ assert!(
+ !dispatcher.tracker().committable_offsets().contains_key(&0),
+ "a deferred event never raised the ceiling",
+ );
+ }
+
+ #[tokio::test]
+ async fn nonblocking_dispatch_returns_promptly_when_the_channel_is_saturated() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with_buffer(&store, behavioral_catalog(), 1);
+ dispatcher.assign_partition(0);
+ let _rx = dispatcher.router.add_partition(0).unwrap();
+ let no_held = HashSet::new();
+
+ dispatcher.dispatch_events_nonblocking(vec![consumed(person(1), 0, 0)], &no_held);
+ // The second dispatch onto the saturated channel returns the holdover synchronously instead of
+ // awaiting a drain.
+ let full =
+ dispatcher.dispatch_events_nonblocking(vec![consumed(person(2), 0, 1)], &no_held);
+ assert!(
+ full.contains_key(&0),
+ "the saturated partition's events are held, never blocked on",
+ );
+ }
+
#[tokio::test]
async fn revoke_partition_drains_produces_evicts_and_deletes_state() {
let (_dir, store) = temp_store();
diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rs
index 38e0d85e6a37..e9cea42be5a8 100644
--- a/rust/cohort-stream-processor/src/consumers/merges.rs
+++ b/rust/cohort-stream-processor/src/consumers/merges.rs
@@ -265,6 +265,10 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
counter!(R::DESERIALIZE_ERRORS_TOTAL).increment(outcome.deserialize_errors);
}
+ // Follower keeps the blocking dispatch on purpose: merges/transfers/cascades are low-volume, so
+ // a full channel here can await a drain without risking the heartbeat — unlike the events
+ // consumer's non-blocking, partition-pausing path (`EventDispatcher::dispatch_events_nonblocking`).
+ // Port that path here if any of these topics ever approaches events-topic volume.
R::dispatch(&self.dispatcher, outcome.messages).await;
if outcome.transport_error {
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 6a648bf21c03..9798861e3ab9 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -202,6 +202,16 @@ pub const PARTITIONS_ACTIVE: &str = "partitions_active";
pub const PARTITION_ROUTE_DROPPED_TOTAL: &str = "partition_route_dropped_total";
/// Sub-batches queued in a partition worker's channel, labelled by `partition` (gauge).
pub const PARTITION_CHANNEL_DEPTH: &str = "partition_channel_depth";
+/// Events held back because a partition worker's channel was full, labelled by `partition` (counter).
+/// Backpressure, not loss: the partition is paused and its events redispatch once the channel drains.
+/// Re-counted on every retry of a still-full holdover, so it is a pressure rate, not a distinct-event
+/// count.
+pub const PARTITION_CHANNEL_FULL_TOTAL: &str = "partition_channel_full_total";
+/// Partitions currently paused on the events consumer to shed downstream backpressure (gauge).
+pub const PARTITIONS_PAUSED: &str = "partitions_paused";
+/// Events currently held across all paused partitions, awaiting redispatch (gauge). Bounded — a
+/// paused partition stops fetching — so a climbing value flags a stuck worker.
+pub const PENDING_HELD_EVENTS: &str = "pending_held_events";
/// Non-empty rebalance callbacks, labelled by `event_type` (`assign`|`revoke`) (counter).
pub const REBALANCES_TOTAL: &str = "rebalances_total";
@@ -555,6 +565,13 @@ mod tests {
assert_eq!(TOKIO_BLOCKING_QUEUE_DEPTH, "tokio_blocking_queue_depth");
}
+ #[test]
+ fn partition_backpressure_metric_names_are_stable() {
+ assert_eq!(PARTITION_CHANNEL_FULL_TOTAL, "partition_channel_full_total");
+ assert_eq!(PARTITIONS_PAUSED, "partitions_paused");
+ assert_eq!(PENDING_HELD_EVENTS, "pending_held_events");
+ }
+
#[test]
fn stage2_orphan_gc_metric_names_are_stable() {
assert_eq!(
diff --git a/rust/cohort-stream-processor/src/partitions/backpressure.rs b/rust/cohort-stream-processor/src/partitions/backpressure.rs
new file mode 100644
index 000000000000..0aafeee606e4
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/backpressure.rs
@@ -0,0 +1,169 @@
+//! The events consume loop's per-partition holdover of un-dispatched events, kept broker-free so its
+//! transitions are unit-testable in isolation.
+//!
+//! A partition holds a non-empty entry in [`pending`](Backpressure::pending) **iff** its events could
+//! not be dispatched, so [`held_partitions`](Backpressure::held_partitions) (`pending.keys()`) is
+//! exactly the paused target. Applying and re-asserting that target on the consumer is owned by the
+//! pauser task (`run_pauser_loop`), not this struct.
+
+use std::collections::{HashMap, HashSet};
+
+use crate::partitions::shuffle_message::ShuffleMessage;
+
+/// Held events per held partition for the events consume loop. Never keeps an empty holdover, so
+/// `pending.keys()` is exactly the paused target.
+#[derive(Debug, Default)]
+pub struct Backpressure {
+ /// Un-dispatched events per held partition, coalesced in offset order.
+ pending: HashMap<i32, Vec<ShuffleMessage>>,
+}
+
+impl Backpressure {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Drop the holdover for partitions no longer owned. Their offsets replay on the next owner, and
+ /// the pauser task resumes them once they leave the held target.
+ pub fn prune_revoked(&mut self, owned: &HashSet<i32>) {
+ self.pending
+ .retain(|partition, _| owned.contains(partition));
+ }
+
+ /// Take the whole holdover for a retry-flush, emptying `pending`; the caller re-[`absorb`](Self::absorb)s
+ /// whatever stays full.
+ pub fn take_held(&mut self) -> Vec<(i32, Vec<ShuffleMessage>)> {
+ std::mem::take(&mut self.pending).into_iter().collect()
+ }
+
+ /// Partitions with an outstanding holdover: the paused target, and the set fresh events must queue
+ /// behind rather than leapfrog.
+ pub fn held_partitions(&self) -> HashSet<i32> {
+ self.pending.keys().copied().collect()
+ }
+
+ /// Append un-dispatched events to their partition's holdover in offset order. Empty batches are
+ /// skipped, so a present entry always means a non-empty holdover.
+ pub fn absorb(&mut self, full: HashMap<i32, Vec<ShuffleMessage>>) {
+ for (partition, mut messages) in full {
+ if messages.is_empty() {
+ continue;
+ }
+ self.pending
+ .entry(partition)
+ .or_default()
+ .append(&mut messages);
+ }
+ }
+
+ /// Partitions currently held (== the paused target size). Feeds the `partitions_paused` gauge.
+ pub fn held_partition_count(&self) -> usize {
+ self.pending.len()
+ }
+
+ /// Total events held across all held partitions. Feeds the `pending_held_events` gauge.
+ pub fn held_event_count(&self) -> usize {
+ self.pending.values().map(Vec::len).sum()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::consumers::events::CohortStreamEvent;
+
+ fn event(cse_offset: i64) -> ShuffleMessage {
+ ShuffleMessage::Event {
+ event: Box::new(CohortStreamEvent {
+ team_id: 1,
+ person_id: "p".to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: None,
+ person_properties: None,
+ elements_chain: None,
+ source_offset: cse_offset,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ }),
+ cse_offset,
+ }
+ }
+
+ fn offsets(messages: &[ShuffleMessage]) -> Vec<i64> {
+ messages
+ .iter()
+ .filter_map(ShuffleMessage::event_offset)
+ .collect()
+ }
+
+ #[test]
+ fn a_newly_full_partition_becomes_the_held_target() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([(5, vec![event(10)])]));
+
+ assert_eq!(bp.held_partitions(), HashSet::from([5]));
+ assert_eq!(bp.held_partition_count(), 1);
+ }
+
+ #[test]
+ fn a_flushed_partition_leaves_the_held_target() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([(5, vec![event(10)])]));
+
+ // Next iteration: the holdover flushed (nothing re-absorbed), so the partition drops out of
+ // the held target and the pauser task resumes it.
+ let _held = bp.take_held();
+
+ assert!(bp.held_partitions().is_empty());
+ assert_eq!(bp.held_partition_count(), 0);
+ }
+
+ #[test]
+ fn a_still_full_partition_stays_in_the_held_target() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([(5, vec![event(10)])]));
+
+ // Retry-flush leaves it full: re-absorbed verbatim, still held.
+ let held = bp.take_held();
+ bp.absorb(held.into_iter().collect());
+
+ assert_eq!(bp.held_partitions(), HashSet::from([5]));
+ }
+
+ #[test]
+ fn a_revoked_partition_is_pruned_from_the_held_target() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([(5, vec![event(10)]), (6, vec![event(20)])]));
+
+ // Only partition 6 is still owned: 5's holdover is dropped for replay on its next owner.
+ bp.prune_revoked(&HashSet::from([6]));
+
+ assert_eq!(bp.held_partitions(), HashSet::from([6]));
+ assert_eq!(bp.held_partition_count(), 1);
+ }
+
+ #[test]
+ fn absorb_coalesces_fresh_events_after_the_existing_holdover_in_offset_order() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([(5, vec![event(10), event(11)])]));
+ // A straggler that arrived after the pause queues behind the older held offsets.
+ bp.absorb(HashMap::from([(5, vec![event(12)])]));
+
+ let held: HashMap<i32, Vec<ShuffleMessage>> = bp.take_held().into_iter().collect();
+ assert_eq!(offsets(&held[&5]), vec![10, 11, 12]);
+ }
+
+ #[test]
+ fn held_event_count_sums_across_partitions() {
+ let mut bp = Backpressure::new();
+ bp.absorb(HashMap::from([
+ (5, vec![event(10), event(11)]),
+ (6, vec![event(20)]),
+ ]));
+ assert_eq!(bp.held_event_count(), 3);
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index a3393c951731..1c9d2e9b7498 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -5,21 +5,25 @@
//! long-lived worker that owns the `Receiver` from [`router::PartitionRouter::add_partition`] and
//! runs the Stage 1 loop lives in [`crate::workers`].
+pub mod backpressure;
pub mod follower;
pub mod offset_tracker;
pub mod partitioner;
+pub mod pause;
pub mod rebalance;
pub mod router;
pub mod shuffle_message;
+pub use backpressure::Backpressure;
pub use follower::{Follower, FollowerSet, PartitionMirror};
pub use offset_tracker::{MarkOutcome, OffsetTracker};
pub use partitioner::{
merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,
};
+pub use pause::{ConsumerPauser, PartitionPauser};
pub use rebalance::{
run_rebalance_worker, CohortConsumerContext, ConsumerCommand, ConsumerCommandReceiver,
ConsumerCommandSender, RebalanceEvent, RebalanceEventReceiver,
};
-pub use router::{PartitionRouter, RouteError};
+pub use router::{PartitionRouter, RouteError, SendOutcome};
pub use shuffle_message::ShuffleMessage;
diff --git a/rust/cohort-stream-processor/src/partitions/pause.rs b/rust/cohort-stream-processor/src/partitions/pause.rs
new file mode 100644
index 000000000000..1c60f0834412
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/pause.rs
@@ -0,0 +1,67 @@
+//! Per-partition Kafka pause/resume for the events consumer, so a full worker channel surfaces as lag
+//! on that partition alone. Trait-based for broker-free tests; the prod impl [`ConsumerPauser`] warns
+//! and skips on error — a missed pause only grows the holdover, a missed resume only defers a drain.
+
+use std::sync::Arc;
+
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::TopicPartitionList;
+use tracing::warn;
+
+use crate::partitions::rebalance::CohortConsumerContext;
+
+/// Pause/resume Kafka fetching for specific partitions of the events topic.
+pub trait PartitionPauser: Send + Sync {
+ fn pause(&self, partitions: &[i32]);
+ fn resume(&self, partitions: &[i32]);
+}
+
+/// Production [`PartitionPauser`]: drives `pause`/`resume` on the events `StreamConsumer`.
+pub struct ConsumerPauser {
+ consumer: Arc<StreamConsumer<CohortConsumerContext>>,
+ topic: String,
+}
+
+impl ConsumerPauser {
+ pub fn new(consumer: Arc<StreamConsumer<CohortConsumerContext>>, topic: String) -> Self {
+ Self { consumer, topic }
+ }
+
+ fn tpl(&self, partitions: &[i32]) -> TopicPartitionList {
+ let mut tpl = TopicPartitionList::new();
+ for &partition in partitions {
+ tpl.add_partition(&self.topic, partition);
+ }
+ tpl
+ }
+}
+
+impl PartitionPauser for ConsumerPauser {
+ fn pause(&self, partitions: &[i32]) {
+ if partitions.is_empty() {
+ return;
+ }
+ if let Err(err) = self.consumer.pause(&self.tpl(partitions)) {
+ warn!(
+ topic = %self.topic,
+ ?partitions,
+ error = %err,
+ "failed to pause partitions; the holdover grows until the next attempt",
+ );
+ }
+ }
+
+ fn resume(&self, partitions: &[i32]) {
+ if partitions.is_empty() {
+ return;
+ }
+ if let Err(err) = self.consumer.resume(&self.tpl(partitions)) {
+ warn!(
+ topic = %self.topic,
+ ?partitions,
+ error = %err,
+ "failed to resume partitions; surfaces as lag until the next attempt",
+ );
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/partitions/router.rs b/rust/cohort-stream-processor/src/partitions/router.rs
index 0c7ed22c6ed6..f7ecbc67da86 100644
--- a/rust/cohort-stream-processor/src/partitions/router.rs
+++ b/rust/cohort-stream-processor/src/partitions/router.rs
@@ -14,11 +14,13 @@ use futures::future::join_all;
use metrics::{counter, gauge};
use thiserror::Error;
use tokio::sync::mpsc;
+use tokio::sync::mpsc::error::TrySendError;
use tracing::warn;
use super::shuffle_message::ShuffleMessage;
use crate::observability::metrics::{
- PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_ROUTE_DROPPED_TOTAL,
+ PARTITIONS_ACTIVE, PARTITION_CHANNEL_DEPTH, PARTITION_CHANNEL_FULL_TOTAL,
+ PARTITION_ROUTE_DROPPED_TOTAL,
};
const REASON_NO_WORKER: &str = "no_worker";
@@ -37,6 +39,24 @@ pub enum RouteError {
ChannelClosed { partition: i32, dropped: usize },
}
+/// Per-partition result of [`try_route_batch`](PartitionRouter::try_route_batch). `Full` is
+/// backpressure — the events are returned to be held and retried — not a drop.
+#[derive(Debug)]
+pub enum SendOutcome {
+ /// Delivered. `max_offset` is the highest event offset (raises the dispatch ceiling), or `None` if
+ /// the batch carries no events; `count` is the number delivered.
+ Sent {
+ max_offset: Option<i64>,
+ count: usize,
+ },
+ /// Channel full: carries the un-sent sub-batch to hold, pause, and redispatch. No drop recorded.
+ Full(Vec<ShuffleMessage>),
+ /// No worker registered (never assigned, or revoked): dropped and recorded; Kafka replays.
+ NoWorker,
+ /// Worker channel closed (worker exited): dropped and recorded; Kafka replays.
+ ChannelClosed,
+}
+
/// Routes per-partition sub-batches to long-lived per-partition worker channels.
pub struct PartitionRouter {
senders: DashMap<i32, mpsc::Sender<Vec<ShuffleMessage>>>,
@@ -163,6 +183,51 @@ impl PartitionRouter {
}
}
+ /// Non-blocking sibling of [`route_batch`](Self::route_batch): group by partition and `try_send`
+ /// each sub-batch, returning the per-partition [`SendOutcome`] instead of awaiting a drain.
+ pub fn try_route_batch(
+ &self,
+ messages: Vec<(i32, ShuffleMessage)>,
+ ) -> HashMap<i32, SendOutcome> {
+ if messages.is_empty() {
+ return HashMap::new();
+ }
+ let mut by_partition: HashMap<i32, Vec<ShuffleMessage>> = HashMap::new();
+ for (partition, message) in messages {
+ by_partition.entry(partition).or_default().push(message);
+ }
+ by_partition
+ .into_iter()
+ .map(|(partition, batch)| (partition, self.try_send_to_partition(partition, batch)))
+ .collect()
+ }
+
+ fn try_send_to_partition(&self, partition: i32, batch: Vec<ShuffleMessage>) -> SendOutcome {
+ let Some(sender) = self.sender_for(partition) else {
+ self.record_drop(partition, batch.len(), REASON_NO_WORKER);
+ return SendOutcome::NoWorker;
+ };
+ let count = batch.len();
+ // `None` for an event-less batch — carried through, not defaulted to 0, so a future non-Event
+ // caller can't fabricate a ceiling (`route_and_fold` only marks when `Some`).
+ let max_offset = batch.iter().filter_map(ShuffleMessage::event_offset).max();
+ match sender.try_send(batch) {
+ Ok(()) => {
+ self.emit_channel_depth(partition, &sender);
+ SendOutcome::Sent { max_offset, count }
+ }
+ Err(TrySendError::Full(returned)) => {
+ counter!(PARTITION_CHANNEL_FULL_TOTAL, "partition" => partition.to_string())
+ .increment(returned.len() as u64);
+ SendOutcome::Full(returned)
+ }
+ Err(TrySendError::Closed(returned)) => {
+ self.record_drop(partition, returned.len(), REASON_CHANNEL_CLOSED);
+ SendOutcome::ChannelClosed
+ }
+ }
+ }
+
pub fn partition_count(&self) -> usize {
self.senders.len()
}
@@ -417,6 +482,100 @@ mod tests {
assert_eq!(tags(&rx_new.recv().await.unwrap()), vec![7]);
}
+ /// An event whose `cse_offset` matches its `source_offset` tag, so [`tags`] and `max_offset`
+ /// assertions line up.
+ fn event_off(cse_offset: i64) -> ShuffleMessage {
+ match event(cse_offset) {
+ ShuffleMessage::Event { event, .. } => ShuffleMessage::Event { event, cse_offset },
+ other => other,
+ }
+ }
+
+ #[tokio::test]
+ async fn try_route_batch_delivers_and_reports_the_max_offset_and_count() {
+ let router = PartitionRouter::new(16);
+ let mut rx5 = router.add_partition(5).unwrap();
+ let mut rx6 = router.add_partition(6).unwrap();
+
+ let mut outcomes = router.try_route_batch(vec![
+ (5, event_off(1)),
+ (6, event_off(2)),
+ (5, event_off(3)),
+ ]);
+
+ match outcomes.remove(&5) {
+ Some(SendOutcome::Sent { max_offset, count }) => {
+ assert_eq!((max_offset, count), (Some(3), 2));
+ }
+ other => panic!("expected Sent for 5, got {other:?}"),
+ }
+ match outcomes.remove(&6) {
+ Some(SendOutcome::Sent { max_offset, count }) => {
+ assert_eq!((max_offset, count), (Some(2), 1));
+ }
+ other => panic!("expected Sent for 6, got {other:?}"),
+ }
+ assert_eq!(tags(&rx5.try_recv().unwrap()), vec![1, 3]);
+ assert_eq!(tags(&rx6.try_recv().unwrap()), vec![2]);
+ }
+
+ #[tokio::test]
+ async fn try_route_batch_returns_the_batch_on_full_without_recording_a_drop() {
+ let router = PartitionRouter::new(1);
+ let mut rx = router.add_partition(1).unwrap();
+
+ // Saturate the slot, then the next try hands the batch back untouched.
+ assert!(matches!(
+ router.try_route_batch(vec![(1, event_off(100))]).remove(&1),
+ Some(SendOutcome::Sent { .. }),
+ ));
+
+ match router.try_route_batch(vec![(1, event_off(7))]).remove(&1) {
+ Some(SendOutcome::Full(returned)) => assert_eq!(tags(&returned), vec![7]),
+ other => panic!("expected Full, got {other:?}"),
+ }
+ assert_eq!(tags(&rx.try_recv().unwrap()), vec![100]);
+ assert!(rx.try_recv().is_err());
+ }
+
+ #[tokio::test]
+ async fn try_route_batch_reports_no_worker_and_channel_closed() {
+ let router = PartitionRouter::new(16);
+ assert!(matches!(
+ router.try_route_batch(vec![(9, event_off(1))]).remove(&9),
+ Some(SendOutcome::NoWorker),
+ ));
+
+ let rx = router.add_partition(3).unwrap();
+ drop(rx);
+ assert!(matches!(
+ router.try_route_batch(vec![(3, event_off(1))]).remove(&3),
+ Some(SendOutcome::ChannelClosed),
+ ));
+ }
+
+ #[tokio::test]
+ async fn try_route_batch_isolates_a_full_partition_from_a_free_one() {
+ let router = PartitionRouter::new(1);
+ let mut rx2 = router.add_partition(2).unwrap();
+ let _rx1 = router.add_partition(1).unwrap();
+ router.try_route_batch(vec![(1, event_off(100))]);
+
+ let mut outcomes = router.try_route_batch(vec![(1, event_off(1)), (2, event_off(2))]);
+ assert!(matches!(outcomes.remove(&1), Some(SendOutcome::Full(_))));
+ assert!(matches!(
+ outcomes.remove(&2),
+ Some(SendOutcome::Sent { .. })
+ ));
+ assert_eq!(tags(&rx2.try_recv().unwrap()), vec![2]);
+ }
+
+ #[tokio::test]
+ async fn try_route_batch_is_empty_for_an_empty_batch() {
+ let router = PartitionRouter::new(16);
+ assert!(router.try_route_batch(vec![]).is_empty());
+ }
+
#[tokio::test]
async fn has_partition_tracks_registration_not_channel_liveness() {
let router = PartitionRouter::new(16);
diff --git a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
index 82feebcbc28d..de9f8778d685 100644
--- a/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
+++ b/rust/cohort-stream-processor/src/partitions/shuffle_message.rs
@@ -49,6 +49,21 @@ pub enum ShuffleMessage {
},
}
+impl ShuffleMessage {
+ /// The offset an [`Event`](Self::Event) carries; `None` for the maintenance variants.
+ pub fn event_offset(&self) -> Option<i64> {
+ match self {
+ ShuffleMessage::Event { cse_offset, .. } => Some(*cse_offset),
+ ShuffleMessage::Sweep { .. }
+ | ShuffleMessage::Merge { .. }
+ | ShuffleMessage::Transfer { .. }
+ | ShuffleMessage::Cascade { .. }
+ | ShuffleMessage::RedrivePendingTransfers
+ | ShuffleMessage::MergeCfGc { .. } => None,
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;