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.

feat(personhog): parallelize writer into per-partition lanes (#76693)

José Sequeira5e4a453e86c8
diff --git a/rust/personhog-writer/src/buffer.rs b/rust/personhog-writer/src/buffer.rs
index 871e3e19dcd1..53c0c5020863 100644
--- a/rust/personhog-writer/src/buffer.rs
+++ b/rust/personhog-writer/src/buffer.rs
@@ -1,7 +1,7 @@
use std::collections::hash_map::Entry;
use std::collections::HashMap;
-use metrics::{counter, gauge};
+use metrics::counter;
use personhog_proto::personhog::types::v1::Person;
/// In-memory dedup buffer keyed by (team_id, person_id).
@@ -45,8 +45,6 @@ impl PersonBuffer {
e.insert(person);
}
}
-
- gauge!("personhog_writer_buffer_size").set(self.entries.len() as f64);
}
pub fn len(&self) -> usize {
@@ -70,7 +68,6 @@ impl PersonBuffer {
pub fn drain(&mut self) -> (Vec<Person>, HashMap<i32, i64>) {
let persons: Vec<Person> = self.entries.drain().map(|(_, p)| p).collect();
let offsets = std::mem::take(&mut self.offsets);
- gauge!("personhog_writer_buffer_size").set(0.0);
(persons, offsets)
}
}
diff --git a/rust/personhog-writer/src/config.rs b/rust/personhog-writer/src/config.rs
index 8a83c1b63953..666d8eff8c2b 100644
--- a/rust/personhog-writer/src/config.rs
+++ b/rust/personhog-writer/src/config.rs
@@ -35,8 +35,10 @@ pub struct Config {
#[envconfig(default = "30000")]
pub flush_interval_ms: u64,
- /// Flush when the buffer reaches this many entries. Sized to produce
- /// multi-chunk batches that exercise the parallel chunk path.
+ /// Flush when a lane's buffer reaches this many entries. Sized to produce
+ /// multi-chunk batches that exercise the parallel chunk path. Clamped to
+ /// half the per-lane capacity (`buffer_capacity / writer_lanes`) so the
+ /// nonblocking size flush always fires before a lane's hard cap.
#[envconfig(default = "10000")]
pub flush_buffer_size: usize,
@@ -57,11 +59,18 @@ pub struct Config {
#[envconfig(default = "16")]
pub row_fallback_concurrency: usize,
- /// Channel capacity between consumer and writer tasks.
+ /// Channel capacity between the consumer and each writer lane.
/// Higher values allow more buffered batches but use more memory.
- #[envconfig(default = "8")]
+ #[envconfig(default = "2")]
pub flush_channel_capacity: usize,
+ /// Number of parallel writer lanes. Partitions map to lanes by
+ /// `partition % writer_lanes`, and each lane flushes and commits its
+ /// own partitions independently, so PG writes overlap across lanes.
+ /// 1 preserves the original single-writer pipeline.
+ #[envconfig(default = "1")]
+ pub writer_lanes: usize,
+
// ── Service ──────────────────────────────────────────────────
#[envconfig(default = "9103")]
pub metrics_port: u16,
diff --git a/rust/personhog-writer/src/consumer.rs b/rust/personhog-writer/src/consumer.rs
index 697d56a2c18e..feee6a9d0b28 100644
--- a/rust/personhog-writer/src/consumer.rs
+++ b/rust/personhog-writer/src/consumer.rs
@@ -22,36 +22,71 @@ pub struct FlushBatch {
pub oldest_message_ts_ms: Option<i64>,
}
-/// Reads from Kafka, decodes Person protos, buffers with dedup, and
-/// sends batches to the writer task for PG upsert + offset commit.
-pub struct ConsumerTask {
- consumer: Arc<PersonConsumer>,
+/// One writer lane: a dedup buffer plus the channel to its writer task.
+/// Partitions map to lanes by `partition % lanes`, so a partition's
+/// messages always flow through the same lane — Kafka's cumulative
+/// per-partition commits stay safe because each lane commits only the
+/// partitions it owns, in order.
+struct Lane {
buffer: PersonBuffer,
flush_tx: mpsc::Sender<FlushBatch>,
+ /// Oldest message timestamp currently buffered in this lane.
+ oldest_message_ts_ms: Option<i64>,
+}
+
+/// Reads from Kafka, decodes Person protos, buffers with dedup per lane,
+/// and sends batches to the lane writer tasks for PG upsert + offset commit.
+pub struct ConsumerTask {
+ consumer: Arc<PersonConsumer>,
+ lanes: Vec<Lane>,
flush_interval: Duration,
flush_buffer_size: usize,
handle: Handle,
- /// Oldest message timestamp in the current buffer (millis since epoch).
- oldest_message_ts_ms: Option<i64>,
}
impl ConsumerTask {
+ /// `lane_txs` carries one sender per writer lane; each lane gets its own
+ /// dedup buffer of `per_lane_capacity` entries. A single-element vec
+ /// reproduces the single-writer pipeline.
pub fn new(
consumer: Arc<PersonConsumer>,
- buffer: PersonBuffer,
- flush_tx: mpsc::Sender<FlushBatch>,
+ lane_txs: Vec<mpsc::Sender<FlushBatch>>,
+ per_lane_capacity: usize,
flush_interval: Duration,
flush_buffer_size: usize,
handle: Handle,
) -> Self {
+ assert!(!lane_txs.is_empty(), "at least one writer lane is required");
+ // The nonblocking size flush must fire while the lane still has
+ // headroom below its hard cap; otherwise every flush degrades to the
+ // blocking backpressure path and one busy writer stalls consumption
+ // for all lanes again.
+ let max_flush_size = (per_lane_capacity / 2).max(1);
+ let flush_buffer_size = if flush_buffer_size > max_flush_size {
+ warn!(
+ configured = flush_buffer_size,
+ clamped = max_flush_size,
+ per_lane_capacity,
+ "flush_buffer_size clamped to half the per-lane capacity"
+ );
+ max_flush_size
+ } else {
+ flush_buffer_size
+ };
+ let lanes = lane_txs
+ .into_iter()
+ .map(|flush_tx| Lane {
+ buffer: PersonBuffer::new(per_lane_capacity),
+ flush_tx,
+ oldest_message_ts_ms: None,
+ })
+ .collect();
Self {
consumer,
- buffer,
- flush_tx,
+ lanes,
flush_interval,
flush_buffer_size,
handle,
- oldest_message_ts_ms: None,
}
}
@@ -59,14 +94,14 @@ impl ConsumerTask {
let _guard = self.handle.process_scope();
let mut flush_timer = tokio::time::interval(self.flush_interval);
- info!("Consumer task starting");
+ info!(lanes = self.lanes.len(), "Consumer task starting");
loop {
- // Backpressure: flush immediately when buffer is full
- if self.buffer.is_full() {
+ // Backpressure: flush a full lane immediately
+ if let Some(idx) = self.lanes.iter().position(|l| l.buffer.is_full()) {
counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "backpressure")
.increment(1);
- self.send_flush().await;
+ self.send_flush(idx).await;
continue;
}
@@ -74,18 +109,24 @@ impl ConsumerTask {
biased;
_ = self.handle.shutdown_recv() => {
- info!("Shutdown signal, flushing remaining buffer");
- counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "shutdown")
- .increment(1);
- self.send_flush().await;
+ info!("Shutdown signal, flushing remaining buffers");
+ for idx in 0..self.lanes.len() {
+ if !self.lanes[idx].buffer.is_empty() {
+ counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "shutdown")
+ .increment(1);
+ self.send_flush(idx).await;
+ }
+ }
break;
}
_ = flush_timer.tick() => {
- if !self.buffer.is_empty() {
- counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "timer")
- .increment(1);
- self.send_flush().await;
+ for idx in 0..self.lanes.len() {
+ if !self.lanes[idx].buffer.is_empty() {
+ counter!("personhog_writer_flushes_by_trigger_total", "trigger" => "timer")
+ .increment(1);
+ self.send_flush(idx).await;
+ }
}
}
@@ -94,42 +135,43 @@ impl ConsumerTask {
Ok(borrowed_msg) => {
let partition = borrowed_msg.partition();
let offset = borrowed_msg.offset();
-
- gauge!(
- "personhog_writer_partition_offset",
- "partition" => partition.to_string()
- )
- .set(offset as f64);
-
- // Track the oldest message timestamp for e2e latency
- if let Some(ts_ms) = borrowed_msg.timestamp().to_millis() {
- match self.oldest_message_ts_ms {
- Some(existing) if ts_ms < existing => {
- self.oldest_message_ts_ms = Some(ts_ms);
- }
- None => {
- self.oldest_message_ts_ms = Some(ts_ms);
- }
- _ => {}
- }
- }
+ let ts_ms = borrowed_msg.timestamp().to_millis();
if let Some(payload) = borrowed_msg.payload() {
match Person::decode(payload) {
Ok(person) => {
counter!("personhog_writer_messages_consumed_total")
.increment(1);
- self.buffer.insert(person, partition, offset);
- gauge!("personhog_writer_buffer_size")
- .set(self.buffer.len() as f64);
+ let idx = (partition as usize) % self.lanes.len();
+ let lane = &mut self.lanes[idx];
+
+ if let Some(ts_ms) = ts_ms {
+ match lane.oldest_message_ts_ms {
+ Some(existing) if ts_ms < existing => {
+ lane.oldest_message_ts_ms = Some(ts_ms);
+ }
+ None => {
+ lane.oldest_message_ts_ms = Some(ts_ms);
+ }
+ _ => {}
+ }
+ }
+
+ lane.buffer.insert(person, partition, offset);
- if self.buffer.len() >= self.flush_buffer_size {
+ // Size-triggered flushes never block the
+ // consume loop: if this lane's writer is
+ // still busy, keep buffering and reading —
+ // other lanes' writers stay fed. The lane's
+ // hard capacity above is the real limit.
+ if lane.buffer.len() >= self.flush_buffer_size
+ && self.try_send_flush(idx)
+ {
counter!(
"personhog_writer_flushes_by_trigger_total",
"trigger" => "size"
)
.increment(1);
- self.send_flush().await;
}
}
Err(e) => {
@@ -155,29 +197,75 @@ impl ConsumerTask {
info!("Consumer task stopped");
}
- /// Drain the buffer and send to the writer task. The bounded channel
- /// provides backpressure -- if the writer is busy, this blocks.
- async fn send_flush(&mut self) {
- let (persons, offsets) = self.buffer.drain();
- gauge!("personhog_writer_buffer_size").set(self.buffer.len() as f64);
+ /// Drain a lane's buffer into a batch. Offset and buffer-size gauges
+ /// are recorded here, per flush — updating them per message is too
+ /// expensive for the consume loop (dynamic-label registry lookups).
+ fn take_batch(&mut self, idx: usize) -> Option<FlushBatch> {
+ let lane = &mut self.lanes[idx];
+ let (persons, offsets) = lane.buffer.drain();
+ let oldest_message_ts_ms = lane.oldest_message_ts_ms.take();
if persons.is_empty() {
- return;
+ return None;
+ }
+
+ for (partition, offset) in &offsets {
+ gauge!(
+ "personhog_writer_partition_offset",
+ "partition" => partition.to_string()
+ )
+ .set(*offset as f64);
}
+ let total: usize = self.lanes.iter().map(|l| l.buffer.len()).sum();
+ gauge!("personhog_writer_buffer_size").set(total as f64);
- let count = persons.len();
- let batch = FlushBatch {
+ Some(FlushBatch {
persons,
offsets,
- oldest_message_ts_ms: self.oldest_message_ts_ms.take(),
+ oldest_message_ts_ms,
+ })
+ }
+
+ /// Drain a lane's buffer and send to its writer task, waiting until the
+ /// writer accepts it. Used on the timer, shutdown, and hard-capacity
+ /// paths, where blocking the consume loop is intended backpressure.
+ async fn send_flush(&mut self, idx: usize) {
+ let Some(batch) = self.take_batch(idx) else {
+ return;
};
+ let count = batch.persons.len();
let start = std::time::Instant::now();
- if self.flush_tx.send(batch).await.is_err() {
- error!(rows = count, "writer task gone, dropping batch");
+ if self.lanes[idx].flush_tx.send(batch).await.is_err() {
+ error!(rows = count, lane = idx, "writer task gone, dropping batch");
self.handle
- .signal_failure("Writer task channel closed".to_string());
+ .signal_failure(format!("Writer task channel closed (lane {idx})"));
}
histogram!("personhog_writer_channel_send_duration_ms")
.record(start.elapsed().as_secs_f64() * 1000.0);
}
+
+ /// Flush a lane only if its writer channel has capacity right now.
+ /// Returns whether a batch was handed off. Never awaits, so a busy
+ /// writer on one lane can't stall consumption for the others.
+ fn try_send_flush(&mut self, idx: usize) -> bool {
+ let tx = self.lanes[idx].flush_tx.clone();
+ // Bound to a local first: the permit borrows `tx`, so a tail-expression
+ // match would outlive it.
+ let flushed = match tx.try_reserve() {
+ Ok(permit) => {
+ if let Some(batch) = self.take_batch(idx) {
+ permit.send(batch);
+ }
+ true
+ }
+ Err(mpsc::error::TrySendError::Full(())) => false,
+ Err(mpsc::error::TrySendError::Closed(())) => {
+ error!(lane = idx, "writer task gone, cannot flush");
+ self.handle
+ .signal_failure(format!("Writer task channel closed (lane {idx})"));
+ true
+ }
+ };
+ flushed
+ }
}
diff --git a/rust/personhog-writer/src/main.rs b/rust/personhog-writer/src/main.rs
index 7443deefdb80..1335a80ecbb5 100644
--- a/rust/personhog-writer/src/main.rs
+++ b/rust/personhog-writer/src/main.rs
@@ -13,7 +13,6 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
-use personhog_writer::buffer::PersonBuffer;
use personhog_writer::config::Config;
use personhog_writer::consumer::ConsumerTask;
use personhog_writer::kafka::PersonConsumer;
@@ -47,6 +46,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing::info!("Flush interval: {}ms", config.flush_interval_ms);
tracing::info!("Flush buffer size: {}", config.flush_buffer_size);
tracing::info!("Buffer capacity: {}", config.buffer_capacity);
+ tracing::info!("Writer lanes: {}", config.writer_lanes);
tracing::info!("Metrics port: {}", config.metrics_port);
let mut manager = Manager::builder("personhog-writer")
@@ -59,12 +59,20 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_graceful_shutdown(Duration::from_secs(15))
.with_liveness_deadline(Duration::from_secs(30)),
);
- let writer_handle = manager.register(
- "writer",
- ComponentOptions::new()
- .with_graceful_shutdown(Duration::from_secs(15))
- .with_liveness_deadline(Duration::from_secs(30)),
- );
+ // All components must be registered before monitor_background() starts,
+ // so writer lane handles are created up front.
+ let lanes = config.writer_lanes.max(1);
+ let mut writer_handles = Vec::with_capacity(lanes);
+ for lane in 0..lanes {
+ writer_handles.push(
+ manager.register(
+ &format!("writer-{lane}"),
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(15))
+ .with_liveness_deadline(Duration::from_secs(30)),
+ ),
+ );
+ }
let metrics_handle = manager.register(
"metrics-server",
ComponentOptions::new().is_observability(true),
@@ -138,8 +146,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
- let (flush_tx, flush_rx) = mpsc::channel(config.flush_channel_capacity);
-
// Kafka consumer
let kafka_consumer = Arc::new(PersonConsumer::from_config(
&config.kafka,
@@ -149,26 +155,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?);
tracing::info!("Subscribed to Kafka topic: {}", config.kafka_topic);
- // Writer task
- let pg_store = PgStore::new(pool, config.pg_target_table.clone());
- let store = PersonWriteStore::new(
- pg_store,
- personhog_writer::store::StoreConfig {
- chunk_size: config.upsert_batch_size,
- row_fallback_concurrency: config.row_fallback_concurrency,
- },
- );
- let writer_task = WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
-
- tokio::spawn(async move {
- writer_task.run().await;
- });
+ // Writer lanes: each lane gets its own channel, store, and task, and
+ // commits offsets only for the partitions routed to it.
+ let mut lane_txs = Vec::with_capacity(lanes);
+ for writer_handle in writer_handles {
+ let (flush_tx, flush_rx) = mpsc::channel(config.flush_channel_capacity);
+ let store = PersonWriteStore::new(
+ PgStore::new(pool.clone(), config.pg_target_table.clone()),
+ personhog_writer::store::StoreConfig {
+ chunk_size: config.upsert_batch_size,
+ row_fallback_concurrency: config.row_fallback_concurrency,
+ },
+ );
+ let writer_task =
+ WriterTask::new(Arc::clone(&kafka_consumer), store, flush_rx, writer_handle);
+ tokio::spawn(async move {
+ writer_task.run().await;
+ });
+ lane_txs.push(flush_tx);
+ }
// Consumer task
let consumer_task = ConsumerTask::new(
kafka_consumer,
- PersonBuffer::new(config.buffer_capacity),
- flush_tx,
+ lane_txs,
+ (config.buffer_capacity / lanes).max(1),
config.flush_interval(),
config.flush_buffer_size,
consumer_handle,
diff --git a/rust/personhog-writer/tests/common/mod.rs b/rust/personhog-writer/tests/common/mod.rs
index e0823d3e56bc..59649fed44ee 100644
--- a/rust/personhog-writer/tests/common/mod.rs
+++ b/rust/personhog-writer/tests/common/mod.rs
@@ -32,10 +32,20 @@ pub fn test_store_config() -> StoreConfig {
pub async fn create_mock_kafka() -> (
MockCluster<'static, DefaultProducerContext>,
FutureProducer<KafkaContext>,
+) {
+ create_mock_kafka_with_partitions(1).await
+}
+
+/// Create a mock Kafka cluster with a multi-partition personhog_updates topic.
+pub async fn create_mock_kafka_with_partitions(
+ partitions: i32,
+) -> (
+ MockCluster<'static, DefaultProducerContext>,
+ FutureProducer<KafkaContext>,
) {
let (cluster, producer) = common_kafka::test::create_mock_kafka().await;
cluster
- .create_topic(TOPIC, 1, 1)
+ .create_topic(TOPIC, partitions, 1)
.expect("failed to create mock topic");
(cluster, producer)
}
diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rs
index c58a196476ba..dcddc4b4f638 100644
--- a/rust/personhog-writer/tests/integration.rs
+++ b/rust/personhog-writer/tests/integration.rs
@@ -9,7 +9,6 @@ use common::{
KAFKA_BOOTSTRAP, TARGET_TABLE, TOPIC,
};
use personhog_proto::personhog::types::v1::Person;
-use personhog_writer::buffer::PersonBuffer;
use personhog_writer::consumer::{ConsumerTask, FlushBatch};
use personhog_writer::kafka::PersonConsumer;
use personhog_writer::pg::PgStore;
@@ -243,8 +242,8 @@ async fn consumer_flushes_on_buffer_size_threshold() {
// Start consumer with flush_buffer_size=3 (flushes at exactly 3 and 6)
let consumer_task = ConsumerTask::new(
kafka_consumer,
- PersonBuffer::new(100),
- flush_tx,
+ vec![flush_tx],
+ 100,
Duration::from_secs(60), // long timer so only size triggers flush
3, // flush at 3 messages
consumer_handle,
@@ -338,8 +337,8 @@ async fn consumer_flushes_on_timer() {
// Start consumer with high size threshold but short timer (500ms)
let consumer_task = ConsumerTask::new(
kafka_consumer,
- PersonBuffer::new(100),
- flush_tx,
+ vec![flush_tx],
+ 100,
Duration::from_millis(500), // short timer triggers flush
1000, // high threshold so only timer triggers
consumer_handle,
@@ -434,8 +433,8 @@ async fn consumer_deduplicates_multiple_updates_for_same_person() {
// Start consumer with high size threshold, short timer
let consumer_task = ConsumerTask::new(
kafka_consumer,
- PersonBuffer::new(100),
- flush_tx,
+ vec![flush_tx],
+ 100,
Duration::from_millis(500),
1000,
consumer_handle,
@@ -479,6 +478,130 @@ async fn consumer_deduplicates_multiple_updates_for_same_person() {
cleanup_team(&pool, team_id).await;
}
+// ============================================================
+// Consumer: multi-lane routing, lane-local dedup, independent flush
+// ============================================================
+
+/// With two lanes over a two-partition topic, each lane must receive only
+/// its own partition's persons and offsets (routing + disjoint commits),
+/// dedup within its own buffer, and flush on size without draining the
+/// other lane. Asserted on the lane channels directly — the consumer's
+/// public output — so no writer or PG is involved.
+#[tokio::test]
+async fn multi_lane_consumer_routes_partitions_and_flushes_independently() {
+ let (mock_cluster, producer) = common::create_mock_kafka_with_partitions(2).await;
+ let team_id: i64 = 99_060;
+
+ let (tx0, mut rx0) = mpsc::channel::<FlushBatch>(2);
+ let (tx1, mut rx1) = mpsc::channel::<FlushBatch>(2);
+
+ let client_config = ClientConfig::new()
+ .set("bootstrap.servers", mock_cluster.bootstrap_servers())
+ .set("group.id", "test-multi-lane")
+ .set("auto.offset.reset", "earliest")
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .clone();
+ let kafka_consumer = Arc::new(PersonConsumer::new(&client_config, TOPIC.to_string()).unwrap());
+
+ let mut manager = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .build();
+ let consumer_handle = manager.register(
+ "consumer",
+ lifecycle::ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(5)),
+ );
+ let _monitor = manager.monitor_background();
+
+ // Partition 0: person 1 twice (dedup) plus persons 2 and 3 — four
+ // messages but three unique persons, hitting the size threshold of 3.
+ // Partition 1: person 4 only, staying below the threshold.
+ let mut to_produce = vec![
+ (0, make_person(team_id, 1, 1)),
+ (0, make_person(team_id, 1, 2)),
+ (0, make_person(team_id, 2, 1)),
+ (0, make_person(team_id, 3, 1)),
+ (1, make_person(team_id, 4, 1)),
+ ];
+ for (partition, person) in to_produce.drain(..) {
+ let payload = person.encode_to_vec();
+ let key = format!("{}:{}", team_id, person.id);
+ let record = FutureRecord::to(TOPIC)
+ .partition(partition)
+ .key(&key)
+ .payload(&payload);
+ producer
+ .send_result(record)
+ .unwrap()
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ let consumer_task = ConsumerTask::new(
+ kafka_consumer,
+ vec![tx0, tx1],
+ 100,
+ Duration::from_secs(60), // long timer so only size triggers flush
+ 3,
+ consumer_handle,
+ );
+ tokio::spawn(async move { consumer_task.run().await });
+
+ // Lane 0 flushes on size with only partition 0's persons and offsets,
+ // person 1 deduped to its latest version.
+ let batch0 = tokio::time::timeout(Duration::from_secs(15), rx0.recv())
+ .await
+ .expect("lane 0 should flush on size")
+ .expect("lane 0 channel should be open");
+ assert_eq!(batch0.offsets.keys().copied().collect::<Vec<_>>(), vec![0]);
+ assert_eq!(batch0.offsets[&0], 3); // four messages, offsets 0..=3
+ let mut persons0 = batch0.persons;
+ persons0.sort_by_key(|p| p.id);
+ assert_eq!(
+ persons0.iter().map(|p| p.id).collect::<Vec<_>>(),
+ vec![1, 2, 3]
+ );
+ assert_eq!(persons0[0].version, 2, "dedup must keep the latest version");
+
+ // Lane 1 is below its size threshold and the timer is far away, so a
+ // lane-0 flush must not have drained it.
+ assert!(
+ tokio::time::timeout(Duration::from_millis(500), rx1.recv())
+ .await
+ .is_err(),
+ "lane 1 must not flush before reaching its own threshold"
+ );
+
+ // Two more persons on partition 1 push lane 1 to its threshold; its
+ // batch carries only partition 1's persons and offsets.
+ for id in [5, 6] {
+ let person = make_person(team_id, id, 1);
+ let payload = person.encode_to_vec();
+ let key = format!("{team_id}:{id}");
+ let record = FutureRecord::to(TOPIC)
+ .partition(1)
+ .key(&key)
+ .payload(&payload);
+ producer
+ .send_result(record)
+ .unwrap()
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ let batch1 = tokio::time::timeout(Duration::from_secs(15), rx1.recv())
+ .await
+ .expect("lane 1 should flush on size")
+ .expect("lane 1 channel should be open");
+ assert_eq!(batch1.offsets.keys().copied().collect::<Vec<_>>(), vec![1]);
+ assert_eq!(batch1.offsets[&1], 2); // three messages, offsets 0..=2
+ let mut ids1: Vec<i64> = batch1.persons.iter().map(|p| p.id).collect();
+ ids1.sort_unstable();
+ assert_eq!(ids1, vec![4, 5, 6]);
+}
+
// ============================================================
// Writer task: signals completion through channel
// ============================================================
@@ -937,8 +1060,8 @@ async fn e2e_produce_to_kafka_and_verify_pg_write() {
let consumer_task = ConsumerTask::new(
kafka_consumer,
- PersonBuffer::new(50000),
- flush_tx,
+ vec![flush_tx],
+ 50000,
Duration::from_millis(500), // fast flush for test
1, // flush after every message
consumer_handle,