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.

fix(ingestion-consumer): keep the liveness heartbeat going while flushing deferred messages (#88858)

Nick Best1511f7b13fe6
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index e99f5f95e90d..5775753abbf3 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -1,4 +1,5 @@
use std::collections::{HashMap, VecDeque};
+use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -414,19 +415,19 @@ impl IngestionConsumer {
async fn await_processed_batch(&self, batch: InFlightBatch) -> anyhow::Result<ProcessedBatch> {
let batch_id = batch.batch_id;
- let mut handle = batch.handle;
- let mut heartbeat = tokio::time::interval(Duration::from_secs(10));
+ let processed = self.heartbeat_while(batch.handle).await??;
+ info!(batch_id = %batch_id, "Kafka batch processing completed");
+ Ok(processed)
+ }
+
+ async fn heartbeat_while<F: Future>(&self, fut: F) -> F::Output {
+ tokio::pin!(fut);
+ let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
- result = &mut handle => {
- let processed = result??;
- info!(batch_id = %batch_id, "Kafka batch processing completed");
- return Ok(processed);
- }
- _ = heartbeat.tick() => {
- self.handle.report_healthy();
- }
+ output = &mut fut => return output,
+ _ = heartbeat.tick() => self.handle.report_healthy(),
}
}
}
@@ -471,17 +472,20 @@ impl IngestionConsumer {
_ = self.handle.shutdown_recv() => {
anyhow::bail!("shutdown while flushing deferred messages");
}
- _ = tokio::time::sleep(Duration::from_millis(200)) => {}
+ _ = tokio::time::sleep(Duration::from_millis(200)) => {
+ self.handle.report_healthy();
+ }
}
} else {
- accepted_this_round += Self::scatter(
- &self.dispatcher,
- &self.transport,
- batch_id,
- sub_batches,
- true,
- )
- .await?;
+ accepted_this_round += self
+ .heartbeat_while(Self::scatter(
+ &self.dispatcher,
+ &self.transport,
+ batch_id,
+ sub_batches,
+ true,
+ ))
+ .await?;
}
// Eager-path acceptances count as progress too — a batch whose
// remaining groups are all draining through eager chains must
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index 75d5db2a51bd..42500f5bb18d 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -458,6 +458,29 @@ impl Harness {
deferred_flush_timeout,
registry_config,
0,
+ ComponentOptions::new(),
+ )
+ .await
+ }
+
+ async fn start_with_liveness(
+ topic: &str,
+ worker_count: usize,
+ deferred_flush_timeout: Duration,
+ liveness_deadline: Duration,
+ stall_threshold: u32,
+ ) -> Self {
+ Self::start_inner(
+ topic,
+ 1,
+ worker_count,
+ 1,
+ deferred_flush_timeout,
+ fast_registry_config(),
+ 0,
+ ComponentOptions::new()
+ .with_liveness_deadline(liveness_deadline)
+ .with_stall_threshold(stall_threshold),
)
.await
}
@@ -474,6 +497,7 @@ impl Harness {
Duration::from_secs(60),
fast_registry_config(),
batch_size_bytes,
+ ComponentOptions::new(),
)
.await
}
@@ -487,6 +511,7 @@ impl Harness {
deferred_flush_timeout: Duration,
registry_config: WorkerRegistryConfig,
batch_size_bytes: usize,
+ component_options: ComponentOptions,
) -> Self {
create_topic(topic, partitions).await;
@@ -521,9 +546,11 @@ impl Harness {
let mut manager = Manager::builder("e2e-test")
.with_trap_signals(false)
+ .with_health_poll_interval(Duration::from_millis(100))
.build();
- let handle = manager.register("consumer", ComponentOptions::new());
+ let handle = manager.register("consumer", component_options);
let shutdown = handle.shutdown_token();
+ let _monitor = manager.monitor_background();
let group_id = format!("e2e-{}", Uuid::new_v4());
let kafka_consumer = make_kafka_consumer(topic, &group_id, None);
@@ -1150,19 +1177,16 @@ async fn partial_send_failure_replays_only_the_failed_subbatch() {
/// When a send fails and there is no healthy worker to replay to, the deferred
/// work is held (not lost, not dropped) and the flush loop retries until a
-/// worker returns, then drains in order.
+/// worker returns, then drains in order. Waiting for a worker, and waiting on
+/// a slow one once found, both outlast the liveness deadline here: neither is
+/// a stall, so the lifecycle monitor must not shut the consumer down.
#[tokio::test]
async fn deferred_flush_retries_until_a_worker_recovers() {
let topic = format!("e2e-replay-wait-{}", Uuid::new_v4());
- let harness = Harness::start(
- &topic,
- 1,
- 2,
- 1,
- Duration::from_secs(60),
- fast_registry_config(),
- )
- .await;
+ let liveness_deadline = Duration::from_millis(1500);
+ let harness =
+ Harness::start_with_liveness(&topic, 2, Duration::from_secs(60), liveness_deadline, 2)
+ .await;
let producer = make_producer();
// Take worker 1 out of the pool so the batch routes to worker 0.
@@ -1208,16 +1232,34 @@ async fn deferred_flush_retries_until_a_worker_recovers() {
// The deferred work is held steady — the flush loop is backing off, not
// dropping anything — for as long as no worker is available.
let held = harness.dispatcher.stashed_messages();
- tokio::time::sleep(Duration::from_millis(400)).await;
+ tokio::time::sleep(liveness_deadline * 4).await;
assert_eq!(
harness.dispatcher.stashed_messages(),
held,
"deferred work must be held steady while no worker is available"
);
+ assert!(
+ !harness.shutdown.is_cancelled(),
+ "waiting for a worker must keep the liveness heartbeat going"
+ );
- // Recover worker 1 → the flush loop drains the stash to it, then the consumer
- // resumes and delivers the rest. All of user-1 lands on worker 1, in order.
+ // Recover worker 1 while it is blocked → the flush loop sends the stash to
+ // it and waits on the in-flight request past the liveness deadline.
+ let guard1 = harness.workers[1].block().await;
harness.workers[1].healthy.store(true, Ordering::SeqCst);
+ wait_until(Duration::from_secs(10), "replay to reach worker 1", || {
+ harness.workers[1].arrived_count() > 0
+ })
+ .await;
+ tokio::time::sleep(liveness_deadline * 4).await;
+ assert!(
+ !harness.shutdown.is_cancelled(),
+ "waiting on a slow worker must keep the liveness heartbeat going"
+ );
+
+ // Release worker 1 → the stash drains, then the consumer resumes and
+ // delivers the rest. All of user-1 lands on worker 1, in order.
+ drop(guard1);
harness.wait_for(4, Duration::from_secs(15)).await;
assert_eq!(
@@ -1234,6 +1276,186 @@ async fn deferred_flush_retries_until_a_worker_recovers() {
harness.stop().await;
}
+/// With no worker ever coming back, the batch must still fail: the flush
+/// loop's own `deferred_flush_timeout` ends it, not a liveness stall, so the
+/// exit lands at the flush timeout rather than at the (shorter) stall window.
+#[tokio::test]
+async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall() {
+ let topic = format!("e2e-flush-timeout-liveness-{}", Uuid::new_v4());
+ let flush_timeout = Duration::from_secs(4);
+ let liveness_deadline = Duration::from_millis(1500);
+ let mut harness =
+ Harness::start_with_liveness(&topic, 2, flush_timeout, liveness_deadline, 2).await;
+ let producer = make_producer();
+
+ harness.workers[1].healthy.store(false, Ordering::SeqCst);
+ wait_until(
+ Duration::from_secs(10),
+ "worker 1 to leave the pool",
+ || !in_pool(&harness, &harness.workers[1].url),
+ )
+ .await;
+
+ let guard0 = harness.workers[0].block().await;
+ for seq in 0..4usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ }
+ wait_until(Duration::from_secs(10), "batch to reach worker 0", || {
+ harness.workers[0].arrived_count() > 0
+ })
+ .await;
+
+ harness.workers[0].healthy.store(false, Ordering::SeqCst);
+ drop(guard0);
+ wait_until(
+ Duration::from_secs(10),
+ "the failed send to be deferred",
+ || harness.dispatcher.stashed_messages() > 0,
+ )
+ .await;
+ let deferred_at = tokio::time::Instant::now();
+
+ assert!(
+ harness
+ .wait_for_consumer_exit(Duration::from_secs(20))
+ .await,
+ "consumer must fail the batch once nothing lands for a full flush timeout"
+ );
+ let waited = deferred_at.elapsed();
+ assert!(
+ waited >= flush_timeout * 3 / 4,
+ "consumer exited after {waited:?}: a liveness stall, not the {flush_timeout:?} flush timeout"
+ );
+ assert_eq!(
+ harness.workers.iter().map(|w| w.count()).sum::<usize>(),
+ 0,
+ "nothing should be delivered"
+ );
+}
+
+/// A drain that is slow but moving must complete even when it outlasts both the
+/// liveness deadline and the flush timeout: every landing resets the flush
+/// deadline, and the wait in between keeps the heartbeat going. Two keys land
+/// in two flush rounds, the first only after the original deadline has passed.
+#[tokio::test]
+async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout() {
+ let topic = format!("e2e-slow-drain-{}", Uuid::new_v4());
+ let flush_timeout = Duration::from_secs(3);
+ let liveness_deadline = Duration::from_millis(1500);
+ let harness =
+ Harness::start_with_liveness(&topic, 3, flush_timeout, liveness_deadline, 2).await;
+ let producer = make_producer();
+
+ // Workers 1 and 2 out, so both keys route to worker 0 together.
+ for i in [1, 2] {
+ harness.workers[i].healthy.store(false, Ordering::SeqCst);
+ }
+ wait_until(
+ Duration::from_secs(10),
+ "workers 1 and 2 to leave the pool",
+ || {
+ !in_pool(&harness, &harness.workers[1].url)
+ && !in_pool(&harness, &harness.workers[2].url)
+ },
+ )
+ .await;
+
+ let guard0 = harness.workers[0].block().await;
+ for seq in 0..4usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 0, "tok", "user-2", seq).await;
+ }
+ wait_until(Duration::from_secs(10), "batch to reach worker 0", || {
+ harness.workers[0].arrived_count() > 0
+ })
+ .await;
+
+ // Workers 1 and 2 rejoin, blocked, before worker 0 fails, so the flush
+ // sees both and spreads the two keys over them, one request each.
+ let mut guard1 = Some(harness.workers[1].block().await);
+ let guard2 = harness.workers[2].block().await;
+ for i in [1, 2] {
+ harness.workers[i].healthy.store(true, Ordering::SeqCst);
+ }
+ wait_until(
+ Duration::from_secs(10),
+ "workers 1 and 2 to rejoin the pool",
+ || in_pool(&harness, &harness.workers[1].url) && in_pool(&harness, &harness.workers[2].url),
+ )
+ .await;
+ harness.workers[0].healthy.store(false, Ordering::SeqCst);
+ drop(guard0);
+ wait_until(
+ Duration::from_secs(10),
+ "the flush to reach both workers",
+ || harness.workers[1].arrived_count() > 0 && harness.workers[2].arrived_count() > 0,
+ )
+ .await;
+ let flush_started = tokio::time::Instant::now();
+
+ // Worker 2 fails its key now, so that key re-defers into a later round.
+ harness.workers[2].ingest_ok.store(false, Ordering::SeqCst);
+ drop(guard2);
+ wait_until(Duration::from_secs(10), "worker 2 to answer", || {
+ harness.workers[2].arrived_count() == 1 && harness.dispatcher.stashed_messages() > 0
+ })
+ .await;
+ let guard2 = harness.workers[2].block().await;
+ harness.workers[2].ingest_ok.store(true, Ordering::SeqCst);
+
+ // Worker 1 lands its key only after the original flush deadline has passed.
+ tokio::time::sleep(flush_timeout + Duration::from_millis(200)).await;
+ assert!(
+ !harness.shutdown.is_cancelled(),
+ "a slow in-flight send must not trip the liveness stall"
+ );
+ guard1.take();
+ wait_until(
+ Duration::from_secs(10),
+ "the retried key to reach worker 2",
+ || harness.workers[2].arrived_count() == 2,
+ )
+ .await;
+
+ // The second round waits past the liveness deadline again before landing.
+ tokio::time::sleep(liveness_deadline * 3).await;
+ assert!(
+ !harness.shutdown.is_cancelled(),
+ "the second flush round must keep the heartbeat going"
+ );
+ drop(guard2);
+ harness.wait_for(8, Duration::from_secs(15)).await;
+
+ assert!(
+ flush_started.elapsed() > flush_timeout,
+ "the drain must have outlasted the flush timeout for this test to mean anything"
+ );
+ assert!(
+ !harness.shutdown.is_cancelled(),
+ "the consumer must still be running"
+ );
+ let log = harness.delivery_log.lock().unwrap().clone();
+ for user in ["user-1", "user-2"] {
+ let seqs: Vec<usize> = log
+ .iter()
+ .filter(|(did, _)| did == user)
+ .map(|(_, seq)| *seq)
+ .collect();
+ assert_eq!(
+ seqs,
+ vec![0, 1, 2, 3],
+ "{user} must land exactly once, in order; log: {log:?}"
+ );
+ }
+ assert_eq!(
+ harness.workers[0].count(),
+ 0,
+ "failed worker recorded nothing"
+ );
+
+ harness.stop().await;
+}
+
/// A failed multi-key sub-batch replays every key, each in its own Kafka order,
/// once a worker is available.
#[tokio::test]