:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(personhog): drop revoked partitions from the writer buffer (#112448)
José Sequeira3a41bd396fc8
diff --git a/rust/personhog-writer/README.md b/rust/personhog-writer/README.mdindex 9b544b5a82bc..e5c61cfa589f 100644--- a/rust/personhog-writer/README.md+++ b/rust/personhog-writer/README.md@@ -87,7 +87,8 @@ When the writer is slow (PG latency, pool saturation), size-triggered flushes st- **Cooperative-sticky assignment**: during autoscaling, only partitions that need to move are revoked- **Static group membership**: when `KAFKA_CLIENT_ID` is set, the broker holds partition assignments during pod restarts (requires StatefulSet for stable pod names)-- **Manual offset commits**: offsets are committed only after a successful Postgres write+- **Manual offset commits**: offsets are committed only after a successful Postgres write, and only for partitions still assigned to this pod+- **Revocation**: when the broker takes partitions away, their buffered rows are dropped, and a batch already queued for the writer is filtered the same way when the writer picks it up. Their offsets were never committed, so the new owner reads them from the last commit instead of both pods writing the same rows. A batch already executing against Postgres, including its retries, still completes## Metrics@@ -115,6 +116,9 @@ When the writer is slow (PG latency, pool saturation), size-triggered flushes st| `personhog_writer_pg_pool_idle` | gauge | Idle sqlx pool connections (sampled every 5s) || `personhog_writer_offset_commits_total` | counter | Successful offset commits || `personhog_writer_offset_commit_errors_total` | counter | Failed offset commits |+| `personhog_writer_offset_commits_skipped_total{reason}` | counter | Partition offsets left uncommitted because the partition is no longer assigned |+| `personhog_writer_partitions_revoked_total` | counter | Partitions the broker revoked from this pod |+| `personhog_writer_revoked_rows_dropped_total{stage}` | counter | Rows dropped because their partition was revoked (stage: buffer, queued) || `personhog_writer_flush_duration_seconds` | histogram | PG write latency per flush || `personhog_writer_flush_rows` | histogram | Rows per flush || `personhog_writer_channel_send_duration_seconds` | histogram | Time waiting on the writer channel (backpressure indicator) |diff --git a/rust/personhog-writer/src/buffer.rs b/rust/personhog-writer/src/buffer.rsindex 0d879b9f910d..07dd59d55d09 100644--- a/rust/personhog-writer/src/buffer.rs+++ b/rust/personhog-writer/src/buffer.rs@@ -1,21 +1,21 @@use std::collections::hash_map::Entry;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use metrics::counter;use personhog_proto::personhog::types::v1::Person;/// A buffered person plus the partition its latest message arrived on, so/// drains can select whole partitions.-struct Buffered {- person: Person,- partition: i32,+pub struct BufferedPerson {+ pub person: Person,+ pub partition: i32,}/// A partition-complete slice of the buffer, ready to flush. Offsets cover/// exactly the partitions whose entries were drained, so committing them/// can never skip past a person still sitting in the buffer.pub struct DrainedBatch {- pub persons: Vec<Person>,+ pub persons: Vec<BufferedPerson>,/// Max offset seen per drained partition.pub offsets: HashMap<i32, i64>,/// Oldest message timestamp across the drained partitions (millis@@ -26,7 +26,7 @@ pub struct DrainedBatch {/// In-memory dedup buffer keyed by (team_id, person_id)./// Later messages for the same person overwrite earlier ones.pub struct PersonBuffer {- entries: HashMap<(i64, i64), Buffered>,+ entries: HashMap<(i64, i64), BufferedPerson>,/// Max offset seen per partition for offset commits.offsets: HashMap<i32, i64>,/// Oldest message timestamp per partition with buffered entries.@@ -71,11 +71,11 @@ impl PersonBuffer {let key = (person.team_id, person.id);match self.entries.entry(key) {Entry::Occupied(mut e) => {- e.insert(Buffered { person, partition });+ e.insert(BufferedPerson { person, partition });counter!("personhog_writer_messages_deduped_total").increment(1);}Entry::Vacant(e) => {- e.insert(Buffered { person, partition });+ e.insert(BufferedPerson { person, partition });}}}@@ -97,6 +97,18 @@ impl PersonBuffer {self.offsets.get(&partition).copied()}+ pub fn remove_partitions(&mut self, partitions: &[i32]) -> usize {+ let revoked: HashSet<i32> = partitions.iter().copied().collect();+ let before = self.entries.len();+ self.entries+ .retain(|_, buffered| !revoked.contains(&buffered.partition));+ for partition in &revoked {+ self.offsets.remove(partition);+ self.oldest_ts_ms.remove(partition);+ }+ before - self.entries.len()+ }+/// Drain whole partitions — oldest buffered message first — until at/// least `max_rows` persons are collected or the buffer is empty. A/// partition is never split: its max offset is only safe to commit once@@ -131,7 +143,7 @@ impl PersonBuffer {}for key in &keys_by_partition[&partition] {let buffered = self.entries.remove(key).expect("key collected above");- persons.push(buffered.person);+ persons.push(buffered);}if let Some(offset) = self.offsets.remove(&partition) {offsets.insert(partition, offset);@@ -195,7 +207,7 @@ mod tests {assert_eq!(buf.len(), 1);let batch = buf.drain_up_to(usize::MAX).unwrap();- assert_eq!(batch.persons[0].version, 3);+ assert_eq!(batch.persons[0].person.version, 3);}#[test]@@ -237,7 +249,10 @@ mod tests {let batch = buf.drain_up_to(2).unwrap();assert_eq!(batch.persons.len(), 2);- assert!(batch.persons.iter().all(|p| p.id == 1 || p.id == 2));+ assert!(batch+ .persons+ .iter()+ .all(|p| p.person.id == 1 || p.person.id == 2));assert_eq!(batch.offsets.len(), 1);assert_eq!(batch.offsets[&0], 11);assert_eq!(batch.oldest_message_ts_ms, Some(100));@@ -274,8 +289,32 @@ mod tests {buf.insert(make_person(1, 2, 1), 7, 0, Some(100));let batch = buf.drain_up_to(1).unwrap();- assert_eq!(batch.persons[0].id, 2);+ assert_eq!(batch.persons[0].person.id, 2);assert_eq!(batch.offsets.len(), 1);assert_eq!(batch.offsets[&7], 0);}++ #[test]+ fn remove_partitions_drops_rows_offsets_and_timestamps() {+ let mut buf = PersonBuffer::new(100);+ buf.insert(make_person(1, 1, 1), 0, 10, Some(100));+ buf.insert(make_person(1, 2, 1), 1, 20, Some(50));+ buf.insert(make_person(1, 3, 1), 1, 21, Some(60));++ assert_eq!(buf.remove_partitions(&[1]), 2);+ assert_eq!(buf.len(), 1);+ assert_eq!(buf.partition_offset(1), None);++ let batch = buf.drain_up_to(usize::MAX).unwrap();+ assert_eq!(+ batch+ .persons+ .iter()+ .map(|p| p.person.id)+ .collect::<Vec<_>>(),+ vec![1]+ );+ assert_eq!(batch.offsets, HashMap::from([(0, 10)]));+ assert_eq!(batch.oldest_message_ts_ms, Some(100));+ }}diff --git a/rust/personhog-writer/src/consumer.rs b/rust/personhog-writer/src/consumer.rsindex c89f68e1bbf9..c6b765c755db 100644--- a/rust/personhog-writer/src/consumer.rs+++ b/rust/personhog-writer/src/consumer.rs@@ -10,18 +10,39 @@ use rdkafka::message::Message as KafkaMessage;use tokio::sync::mpsc;use tracing::{error, info, warn};-use crate::buffer::PersonBuffer;+use crate::buffer::{BufferedPerson, PersonBuffer};use crate::kafka::PersonConsumer;/// Batch of persons and their Kafka offsets, sent from consumer to writer.pub struct FlushBatch {- pub persons: Vec<Person>,+ pub persons: Vec<BufferedPerson>,pub offsets: HashMap<i32, i64>,/// Timestamp of the oldest Kafka message in this batch (millis since epoch)./// Used to compute end-to-end latency from ingestion to PG commit.pub oldest_message_ts_ms: Option<i64>,}+/// Their offsets were never committed, so the new owner re-reads these rows;+/// writing them here as well would only race that owner.+fn drop_revoked_partitions(consumer: &PersonConsumer, lanes: &mut [Lane]) {+ let revoked = consumer.take_revoked();+ if revoked.is_empty() {+ return;+ }+ let dropped: usize = lanes+ .iter_mut()+ .map(|lane| lane.buffer.remove_partitions(&revoked))+ .sum();+ counter!("personhog_writer_partitions_revoked_total").increment(revoked.len() as u64);+ counter!("personhog_writer_revoked_rows_dropped_total", "stage" => "buffer")+ .increment(dropped as u64);+ info!(+ partitions = revoked.len(),+ rows = dropped,+ "dropped buffered rows for revoked partitions"+ );+}+/// 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@@ -140,6 +161,8 @@ impl ConsumerTask {let offset = borrowed_msg.offset();let ts_ms = borrowed_msg.timestamp().to_millis();+ drop_revoked_partitions(&self.consumer, &mut self.lanes);+if let Some(payload) = borrowed_msg.payload() {match Person::decode(payload) {Ok(person) => {@@ -204,6 +227,7 @@ impl ConsumerTask {/// 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> {+ drop_revoked_partitions(&self.consumer, &mut self.lanes);let lane = &mut self.lanes[idx];let batch = lane.buffer.drain_up_to(self.flush_buffer_size)?;diff --git a/rust/personhog-writer/src/kafka.rs b/rust/personhog-writer/src/kafka.rsindex 7a628b264c64..e6a43f908264 100644--- a/rust/personhog-writer/src/kafka.rs+++ b/rust/personhog-writer/src/kafka.rs@@ -1,17 +1,46 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};use common_kafka::config::KafkaConfig;-use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};+use metrics::counter;+use rdkafka::consumer::{+ BaseConsumer, CommitMode, Consumer, ConsumerContext, Rebalance, StreamConsumer,+};use rdkafka::message::BorrowedMessage;-use rdkafka::{ClientConfig, TopicPartitionList};+use rdkafka::{ClientConfig, ClientContext, TopicPartitionList};// ── Consumer ────────────────────────────────────────────────────+/// Records the partitions each rebalance takes away, so the consume loop can+/// drop their buffered rows before the new owner starts reading them.+struct RebalanceContext {+ revoked: Arc<Mutex<Vec<i32>>>,+ joined: Arc<AtomicBool>,+}++impl ClientContext for RebalanceContext {}++impl ConsumerContext for RebalanceContext {+ fn pre_rebalance(&self, _base_consumer: &BaseConsumer<Self>, rebalance: &Rebalance<'_>) {+ match rebalance {+ Rebalance::Assign(_) => self.joined.store(true, Ordering::SeqCst),+ Rebalance::Revoke(partitions) => {+ let mut revoked = self.revoked.lock().unwrap();+ revoked.extend(partitions.elements().iter().map(|e| e.partition()));+ }+ Rebalance::Error(_) => {}+ }+ }+}+/// Wraps a Kafka StreamConsumer with its topic, providing a clean/// interface for receiving messages and committing offsets.pub struct PersonConsumer {- consumer: StreamConsumer,+ consumer: StreamConsumer<RebalanceContext>,topic: String,+ revoked: Arc<Mutex<Vec<i32>>>,+ joined: Arc<AtomicBool>,}impl PersonConsumer {@@ -69,23 +98,66 @@ impl PersonConsumer {client_config.set("client.rack", &kafka.kafka_client_rack);}- let consumer: StreamConsumer = client_config.create()?;- consumer.subscribe(&[&topic])?;- Ok(Self { consumer, topic })+ Self::new(&client_config, topic)}/// Create from a raw `ClientConfig`. Useful in tests where you control/// the config directly (e.g., mock clusters).pub fn new(config: &ClientConfig, topic: String) -> Result<Self, rdkafka::error::KafkaError> {- let consumer: StreamConsumer = config.create()?;+ let revoked = Arc::new(Mutex::new(Vec::new()));+ let joined = Arc::new(AtomicBool::new(false));+ let consumer: StreamConsumer<RebalanceContext> =+ config.create_with_context(RebalanceContext {+ revoked: Arc::clone(&revoked),+ joined: Arc::clone(&joined),+ })?;consumer.subscribe(&[&topic])?;- Ok(Self { consumer, topic })+ Ok(Self {+ consumer,+ topic,+ revoked,+ joined,+ })}pub async fn recv(&self) -> Result<BorrowedMessage<'_>, rdkafka::error::KafkaError> {self.consumer.recv().await}+ pub fn take_revoked(&self) -> Vec<i32> {+ std::mem::take(&mut *self.revoked.lock().unwrap())+ }++ /// `None` until the first assignment arrives: before that, an empty+ /// assignment means the group is still forming, not that this pod owns+ /// nothing.+ pub fn assigned_partitions(&self) -> Result<Option<HashSet<i32>>, rdkafka::error::KafkaError> {+ if !self.joined.load(Ordering::SeqCst) {+ return Ok(None);+ }+ Ok(Some(+ self.consumer+ .assignment()?+ .elements()+ .iter()+ .map(|e| e.partition())+ .collect(),+ ))+ }++ pub fn positions(&self) -> Result<HashMap<i32, i64>, rdkafka::error::KafkaError> {+ Ok(self+ .consumer+ .position()?+ .elements()+ .iter()+ .filter_map(|e| match e.offset() {+ rdkafka::Offset::Offset(next) => Some((e.partition(), next)),+ _ => None,+ })+ .collect())+ }+pub fn commit_offsets(&self,offsets: &HashMap<i32, i64>,@@ -94,10 +166,25 @@ impl PersonConsumer {return Ok(());}+ // A partition revoked while its batch was in flight belongs to+ // another pod now; committing it here would move that pod's offset.+ let assigned = self.assigned_partitions()?.unwrap_or_default();let mut tpl = TopicPartitionList::new();+ let mut skipped: u64 = 0;for (partition, offset) in offsets {+ if !assigned.contains(partition) {+ skipped += 1;+ continue;+ }tpl.add_partition_offset(&self.topic, *partition, rdkafka::Offset::Offset(offset + 1))?;}+ if skipped > 0 {+ counter!("personhog_writer_offset_commits_skipped_total", "reason" => "unassigned")+ .increment(skipped);+ }+ if tpl.count() == 0 {+ return Ok(());+ }self.consumer.commit(&tpl, CommitMode::Async)?;Ok(())diff --git a/rust/personhog-writer/src/writer.rs b/rust/personhog-writer/src/writer.rsindex b6fb6f748e9c..e479be276157 100644--- a/rust/personhog-writer/src/writer.rs+++ b/rust/personhog-writer/src/writer.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::ops::ControlFlow;use std::sync::Arc;use std::time::Duration;@@ -15,11 +15,14 @@ use crate::consumer::FlushBatch;use crate::kafka::PersonConsumer;use crate::store::{BatchOutcome, PersonDb, PersonWriteStore};-/// The offset-commit surface the writer needs from Kafka. Abstracted so the-/// retry loop is testable without a broker.+/// The offset-commit and assignment surface the writer needs from Kafka.+/// Abstracted so the retry loop is testable without a broker.pub trait OffsetCommitter: Send + Sync {fn commit_offsets(&self, offsets: &HashMap<i32, i64>)-> Result<(), rdkafka::error::KafkaError>;++ /// `None` while the consumer has not joined its group yet.+ fn assigned_partitions(&self) -> Result<Option<HashSet<i32>>, rdkafka::error::KafkaError>;}impl OffsetCommitter for PersonConsumer {@@ -29,6 +32,10 @@ impl OffsetCommitter for PersonConsumer {) -> Result<(), rdkafka::error::KafkaError> {PersonConsumer::commit_offsets(self, offsets)}++ fn assigned_partitions(&self) -> Result<Option<HashSet<i32>>, rdkafka::error::KafkaError> {+ PersonConsumer::assigned_partitions(self)+ }}/// Receives batches from the consumer task, writes to the persistent@@ -129,10 +136,32 @@ impl<D: PersonDb + 'static, C: OffsetCommitter + 'static> WriterTask<D, C> {/// receiving so no later batch can commit offsets past this one.async fn process_batch(&mut self, batch: FlushBatch) -> ControlFlow<()> {let FlushBatch {- persons,- offsets,+ mut persons,+ mut offsets,oldest_message_ts_ms,} = batch;++ // A partition revoked while this batch waited in the channel belongs+ // to another pod now, which re-reads these rows from the last commit.+ match self.consumer.assigned_partitions() {+ Ok(None) => {}+ Ok(Some(assigned)) => {+ let before = persons.len();+ persons.retain(|row| assigned.contains(&row.partition));+ offsets.retain(|partition, _| assigned.contains(partition));+ let dropped = before - persons.len();+ if dropped > 0 {+ counter!("personhog_writer_revoked_rows_dropped_total", "stage" => "queued")+ .increment(dropped as u64);+ info!(rows = dropped, "dropped queued rows for revoked partitions");+ }+ }+ Err(e) => warn!(error = %e, "assignment unavailable, writing the batch unfiltered"),+ }+ if persons.is_empty() {+ return ControlFlow::Continue(());+ }+let total_rows = persons.len();counter!("personhog_writer_flushes_total").increment(1);@@ -142,7 +171,7 @@ impl<D: PersonDb + 'static, C: OffsetCommitter + 'static> WriterTask<D, C> {// committing (skipping would permanently diverge PG from the cache// and changelog), Kafka redelivers after restart, and the alarm// stands until admission's gap is fixed.- let mut remaining: Vec<Person> = persons;+ let mut remaining: Vec<Person> = persons.into_iter().map(|row| row.person).collect();let mut saturation_rounds: u32 = 0;loop {@@ -282,22 +311,26 @@ mod tests {use super::*;use std::collections::VecDeque;+ use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Mutex;use async_trait::async_trait;use lifecycle::{ComponentOptions, Manager};+ use crate::buffer::BufferedPerson;use crate::store::{StoreConfig, WriteError, WriteErrorKind};/// DB whose chunk calls pop scripted outcomes (None = Ok); an empty/// script succeeds.struct ScriptedDb {responses: Mutex<VecDeque<Option<WriteErrorKind>>>,+ rows_written: Arc<AtomicUsize>,}#[async_trait]impl PersonDb for ScriptedDb {- async fn execute_chunk(&self, _chunk: &[Person]) -> Result<(), WriteError> {+ async fn execute_chunk(&self, chunk: &[Person]) -> Result<(), WriteError> {+ self.rows_written.fetch_add(chunk.len(), Ordering::SeqCst);match self.responses.lock().unwrap().pop_front().flatten() {None => Ok(()),Some(kind) => Err(WriteError {@@ -312,9 +345,31 @@ mod tests {}}- #[derive(Default)]struct RecordingCommitter {commits: Mutex<Vec<HashMap<i32, i64>>>,+ assigned: Option<HashSet<i32>>,+ }++ impl RecordingCommitter {+ fn owning(partitions: &[i32]) -> Self {+ Self {+ commits: Mutex::default(),+ assigned: Some(partitions.iter().copied().collect()),+ }+ }++ fn unjoined() -> Self {+ Self {+ commits: Mutex::default(),+ assigned: None,+ }+ }+ }++ impl Default for RecordingCommitter {+ fn default() -> Self {+ Self::owning(&[0])+ }}impl OffsetCommitter for RecordingCommitter {@@ -325,20 +380,34 @@ mod tests {self.commits.lock().unwrap().push(offsets.clone());Ok(())}++ fn assigned_partitions(&self) -> Result<Option<HashSet<i32>>, rdkafka::error::KafkaError> {+ Ok(self.assigned.clone())+ }}- fn scripted_writer(- responses: Vec<Option<WriteErrorKind>>,- ) -> (+ type ScriptedWriter = (WriterTask<ScriptedDb, RecordingCommitter>,Arc<RecordingCommitter>,+ Arc<AtomicUsize>,mpsc::Sender<FlushBatch>,Manager,- ) {- let committer = Arc::new(RecordingCommitter::default());+ );++ fn scripted_writer(responses: Vec<Option<WriteErrorKind>>) -> ScriptedWriter {+ scripted_writer_with(RecordingCommitter::default(), responses)+ }++ fn scripted_writer_with(+ committer: RecordingCommitter,+ responses: Vec<Option<WriteErrorKind>>,+ ) -> ScriptedWriter {+ let committer = Arc::new(committer);+ let rows_written = Arc::new(AtomicUsize::new(0));let store = PersonWriteStore::new(ScriptedDb {responses: Mutex::new(responses.into()),+ rows_written: Arc::clone(&rows_written),},StoreConfig {chunk_size: 100,@@ -350,19 +419,24 @@ mod tests {let mut manager = Manager::builder("test").build();let handle = manager.register("writer", ComponentOptions::new());let writer = WriterTask::new(Arc::clone(&committer), store, rx, handle);- (writer, committer, tx, manager)+ (writer, committer, rows_written, tx, manager)+ }++ fn row(partition: i32, id: i64) -> BufferedPerson {+ BufferedPerson {+ partition,+ person: Person {+ id,+ team_id: 1,+ version: 1,+ ..Default::default()+ },+ }}fn batch(rows: i64) -> FlushBatch {FlushBatch {- persons: (0..rows)- .map(|id| Person {- id,- team_id: 1,- version: 1,- ..Default::default()- })- .collect(),+ persons: (0..rows).map(|id| row(0, id)).collect(),offsets: HashMap::from([(0, rows - 1)]),oldest_message_ts_ms: None,}@@ -373,7 +447,8 @@ mod tests {// More saturation rounds than MAX_CONSECUTIVE_FAILURES, then success:// the batch must complete and commit instead of halting the writer.let sat = Some(WriteErrorKind::Saturation);- let (mut writer, committer, _tx, _manager) = scripted_writer(vec![sat, sat, sat, sat]);+ let (mut writer, committer, _rows, _tx, _manager) =+ scripted_writer(vec![sat, sat, sat, sat]);let flow = writer.process_batch(batch(3)).await;@@ -385,7 +460,7 @@ mod tests {#[tokio::test(start_paused = true)]async fn transient_rounds_still_halt_at_the_strike_limit() {let err = Some(WriteErrorKind::Transient);- let (mut writer, committer, _tx, _manager) = scripted_writer(vec![err, err, err]);+ let (mut writer, committer, _rows, _tx, _manager) = scripted_writer(vec![err, err, err]);let flow = writer.process_batch(batch(3)).await;@@ -393,6 +468,40 @@ mod tests {assert!(committer.commits.lock().unwrap().is_empty());}+ #[tokio::test(start_paused = true)]+ async fn queued_batch_is_filtered_by_the_current_assignment() {+ let both: HashMap<i32, i64> = HashMap::from([(0, 1), (1, 4)]);+ let cases = vec![+ (+ "owns 0",+ RecordingCommitter::owning(&[0]),+ 2,+ vec![HashMap::from([(0, 1)])],+ ),+ (+ "owns both",+ RecordingCommitter::owning(&[0, 1]),+ 3,+ vec![both.clone()],+ ),+ ("not joined", RecordingCommitter::unjoined(), 3, vec![both]),+ ("owns nothing", RecordingCommitter::owning(&[]), 0, vec![]),+ ];+ for (name, committer, rows, commits) in cases {+ let (mut writer, committer, rows_written, _tx, _manager) =+ scripted_writer_with(committer, vec![]);+ let mut queued = batch(2);+ queued.persons.push(row(1, 7));+ queued.offsets.insert(1, 4);++ let flow = writer.process_batch(queued).await;++ assert!(matches!(flow, ControlFlow::Continue(())), "{name}");+ assert_eq!(rows_written.load(Ordering::SeqCst), rows, "{name}");+ assert_eq!(*committer.commits.lock().unwrap(), commits, "{name}");+ }+ }+#[test]fn backoff_doubles_each_failure() {assert_eq!(backoff_duration(1), Duration::from_secs(1));diff --git a/rust/personhog-writer/tests/integration.rs b/rust/personhog-writer/tests/integration.rsindex ba1f942fde76..01808f0e04f7 100644--- a/rust/personhog-writer/tests/integration.rs+++ b/rust/personhog-writer/tests/integration.rs@@ -1,6 +1,6 @@mod common;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::sync::Arc;use std::time::Duration;@@ -10,6 +10,7 @@ use common::{unique_team_id, KAFKA_BOOTSTRAP, TARGET_TABLE, TOPIC,};use personhog_proto::personhog::types::v1::Person;+use personhog_writer::buffer::BufferedPerson;use personhog_writer::consumer::{ConsumerTask, FlushBatch};use personhog_writer::kafka::PersonConsumer;use personhog_writer::pg::PgStore;@@ -18,10 +19,21 @@ use personhog_writer::store::{};use personhog_writer::writer::WriterTask;use prost::Message;+use rdkafka::consumer::{Consumer, StreamConsumer};use rdkafka::producer::FutureRecord;-use rdkafka::ClientConfig;+use rdkafka::{ClientConfig, Offset, TopicPartitionList};use tokio::sync::mpsc;+fn rows(persons: Vec<Person>) -> Vec<BufferedPerson> {+ persons+ .into_iter()+ .map(|person| BufferedPerson {+ partition: 0,+ person,+ })+ .collect()+}+// ============================================================// PG Writer: upsert correctness// ============================================================@@ -714,12 +726,15 @@ async fn multi_lane_consumer_routes_partitions_and_flushes_independently() {assert_eq!(batch0.offsets.keys().copied().collect::<Vec<_>>(), vec![0]);assert_eq!(batch0.offsets[&0], 3); // four messages, offsets 0..=3let mut persons0 = batch0.persons;- persons0.sort_by_key(|p| p.id);+ persons0.sort_by_key(|p| p.person.id);assert_eq!(- persons0.iter().map(|p| p.id).collect::<Vec<_>>(),+ persons0.iter().map(|p| p.person.id).collect::<Vec<_>>(),vec![1, 2, 3]);- assert_eq!(persons0[0].version, 2, "dedup must keep the latest version");+ assert_eq!(+ persons0[0].person.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.@@ -754,7 +769,7 @@ async fn multi_lane_consumer_routes_partitions_and_flushes_independently() {.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();+ let mut ids1: Vec<i64> = batch1.persons.iter().map(|p| p.person.id).collect();ids1.sort_unstable();assert_eq!(ids1, vec![4, 5, 6]);}@@ -831,7 +846,7 @@ async fn capped_drains_commit_only_the_partitions_they_carry() {let partitions_in_batch: std::collections::HashSet<i32> = batch.persons.iter()- .map(|p| if p.id <= 3 { 0 } else { 1 })+ .map(|p| if p.person.id <= 3 { 0 } else { 1 }).collect();let committed: std::collections::HashSet<i32> = batch.offsets.keys().copied().collect();assert_eq!(@@ -853,6 +868,153 @@ async fn capped_drains_commit_only_the_partitions_they_carry() {assert_eq!(max_offset_seen[&1], 2);}+async fn wait_until(limit: Duration, mut ready: impl FnMut() -> bool) -> Result<(), ()> {+ let deadline = tokio::time::Instant::now() + limit;+ while !ready() {+ if tokio::time::Instant::now() >= deadline {+ return Err(());+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ Ok(())+}++fn committed_offset(tpl: &TopicPartitionList, partition: i32) -> Option<i64> {+ tpl.elements()+ .iter()+ .find(|e| e.partition() == partition)+ .and_then(|e| match e.offset() {+ Offset::Offset(offset) => Some(offset),+ _ => None,+ })+}++/// A second member joining revokes one partition from the first, which must+/// flush only the partition it kept and leave the revoked one uncommitted.+#[tokio::test]+async fn revoked_partitions_are_dropped_and_their_offsets_stay_uncommitted() {+ let (mock_cluster, producer) = common::create_mock_kafka_with_partitions(2).await;+ let team_id: i64 = 99_062;++ let member_config = |client_id: &str| {+ ClientConfig::new()+ .set("bootstrap.servers", mock_cluster.bootstrap_servers())+ .set("group.id", "test-revoke")+ .set("client.id", client_id)+ .set("auto.offset.reset", "earliest")+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false")+ .set("partition.assignment.strategy", "cooperative-sticky")+ .set("session.timeout.ms", "6000")+ .set("heartbeat.interval.ms", "1000")+ .clone()+ };++ // Two persons per partition, produced before the first member joins so+ // it reads them as soon as it is assigned. Ids encode the partition.+ for (partition, id) in [(0, 1), (0, 2), (1, 3), (1, 4)] {+ 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(partition)+ .key(&key)+ .payload(&payload);+ producer+ .send_result(record)+ .unwrap()+ .await+ .unwrap()+ .unwrap();+ }++ let first = Arc::new(PersonConsumer::new(&member_config("first"), TOPIC.to_string()).unwrap());+ let (tx, mut rx) = mpsc::channel::<FlushBatch>(4);+ 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 shutdown = consumer_handle.clone();+ let _monitor = manager.monitor_background();++ // A timer far beyond the test and a size threshold above the row count:+ // only the shutdown flush drains the buffer.+ let consumer_task = ConsumerTask::new(+ Arc::clone(&first),+ vec![tx],+ 100,+ Duration::from_secs(600),+ 100,+ consumer_handle,+ );+ tokio::spawn(async move { consumer_task.run().await });++ wait_until(Duration::from_secs(20), || {+ first+ .positions()+ .map(|p| p.get(&0) == Some(&2) && p.get(&1) == Some(&2))+ .unwrap_or(false)+ })+ .await+ .expect("the first member should consume both partitions");++ // The second member joins and keeps polling so the rebalance completes.+ let second: Arc<StreamConsumer> = Arc::new(member_config("second").create().unwrap());+ second.subscribe(&[TOPIC]).unwrap();+ {+ let second = Arc::clone(&second);+ tokio::spawn(async move { while second.recv().await.is_ok() {} });+ }+ wait_until(Duration::from_secs(20), || {+ second.assignment().map(|a| a.count() == 1).unwrap_or(false)+ })+ .await+ .expect("the second member should take one partition");+ let revoked = second.assignment().unwrap().elements()[0].partition();+ let kept = 1 - revoked;++ shutdown.request_shutdown();+ let mut flushed_ids = Vec::new();+ let mut flushed_partitions = HashSet::new();+ while let Ok(Some(batch)) = tokio::time::timeout(Duration::from_secs(10), rx.recv()).await {+ flushed_ids.extend(batch.persons.iter().map(|p| p.person.id));+ flushed_partitions.extend(batch.offsets.keys().copied());+ }+ flushed_ids.sort_unstable();+ let kept_ids = if kept == 0 { vec![1, 2] } else { vec![3, 4] };+ assert_eq!(+ flushed_ids, kept_ids,+ "only the kept partition's rows may flush"+ );+ assert_eq!(flushed_partitions, HashSet::from([kept]));++ first+ .commit_offsets(&HashMap::from([(kept, 1), (revoked, 1)]))+ .unwrap();+ let mut probe = TopicPartitionList::new();+ probe.add_partition(TOPIC, kept);+ probe.add_partition(TOPIC, revoked);+ wait_until(Duration::from_secs(10), || {+ second+ .committed_offsets(probe.clone(), Duration::from_secs(2))+ .map(|c| committed_offset(&c, kept) == Some(2))+ .unwrap_or(false)+ })+ .await+ .expect("the kept partition's commit should land");+ let committed = second+ .committed_offsets(probe.clone(), Duration::from_secs(2))+ .unwrap();+ assert_eq!(+ committed_offset(&committed, revoked),+ None,+ "the revoked partition must stay uncommitted"+ );+}+// ============================================================// Writer task: signals completion through channel// ============================================================@@ -890,7 +1052,7 @@ async fn writer_processes_batch_from_channel() {// Send a batch directly through the channellet person = make_person(team_id as i64, 1, 1);let batch = FlushBatch {- persons: vec![person],+ persons: rows(vec![person]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1002,7 +1164,7 @@ async fn writer_crashes_after_exhausting_transient_retries() {tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {- persons: vec![make_person(99_040, 1, 1)],+ persons: rows(vec![make_person(99_040, 1, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1055,7 +1217,7 @@ async fn writer_recovers_on_transient_retry() {tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {- persons: vec![make_person(99_041, 1, 1)],+ persons: rows(vec![make_person(99_041, 1, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1064,7 +1226,7 @@ async fn writer_recovers_on_transient_retry() {// Send a second batch to verify the writer is still alive after recoverytokio::time::sleep(Duration::from_secs(3)).await;let batch2 = FlushBatch {- persons: vec![make_person(99_041, 2, 1)],+ persons: rows(vec![make_person(99_041, 2, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1112,7 +1274,7 @@ async fn writer_falls_back_to_per_row_on_data_error() {tokio::spawn(async move { writer_task.run().await });let batch = FlushBatch {- persons: vec![make_person(99_042, 1, 1), make_person(99_042, 2, 1)],+ persons: rows(vec![make_person(99_042, 1, 1), make_person(99_042, 2, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1121,7 +1283,7 @@ async fn writer_falls_back_to_per_row_on_data_error() {// Writer should handle the data error via fallback and stay alivetokio::time::sleep(Duration::from_secs(1)).await;let batch2 = FlushBatch {- persons: vec![make_person(99_042, 3, 1)],+ persons: rows(vec![make_person(99_042, 3, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};@@ -1179,12 +1341,12 @@ async fn unapplyable_batch_halts_the_writer_before_any_later_batch() {// A second batch is already buffered behind the poison one — the// regression this guards is the writer pulling and committing it.let poison = FlushBatch {- persons: vec![make_person(99_043, 1, 1)],+ persons: rows(vec![make_person(99_043, 1, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};let buffered = FlushBatch {- persons: vec![make_person(99_043, 2, 1)],+ persons: rows(vec![make_person(99_043, 2, 1)]),offsets: HashMap::new(),oldest_message_ts_ms: None,};