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(propvals): part 4: kafka I/O and worker loop (#59430)

Andy Zhao77ea38528142
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 912a4eae387e..07866fff2746 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7336,17 +7336,22 @@ dependencies = [
name = "property-vals-rs"
version = "0.1.0"
dependencies = [
+ "async-trait",
"axum 0.7.9",
"common-alloc",
"common-continuous-profiling",
"common-kafka",
+ "common-liveness",
"envconfig",
"lifecycle",
+ "metrics",
"proptest",
+ "rdkafka",
"serde",
"serde_json",
"serve-metrics",
"siphasher 1.0.2",
+ "thiserror 2.0.18",
"tokio",
"tracing",
"tracing-subscriber",
diff --git a/rust/common/kafka/src/kafka_consumer.rs b/rust/common/kafka/src/kafka_consumer.rs
index 652ab9e18c99..3b7d89e84733 100644
--- a/rust/common/kafka/src/kafka_consumer.rs
+++ b/rust/common/kafka/src/kafka_consumer.rs
@@ -4,7 +4,7 @@ use std::{
};
use rdkafka::{
- consumer::{Consumer, ConsumerGroupMetadata, StreamConsumer},
+ consumer::{CommitMode, Consumer, ConsumerGroupMetadata, StreamConsumer},
error::KafkaError,
ClientConfig, Message,
};
@@ -189,6 +189,10 @@ impl SingleTopicConsumer {
.group_metadata()
.expect("It is impossible to construct a stream consumer without a group id")
}
+
+ pub fn commit(&self) -> Result<(), KafkaError> {
+ self.inner.consumer.commit_consumer_state(CommitMode::Sync)
+ }
}
pub struct Offset {
diff --git a/rust/property-vals-rs/Cargo.toml b/rust/property-vals-rs/Cargo.toml
index 2afaa669b492..ea04c82ae246 100644
--- a/rust/property-vals-rs/Cargo.toml
+++ b/rust/property-vals-rs/Cargo.toml
@@ -5,16 +5,21 @@ edition = "2021"
publish = false
[dependencies]
+async-trait = { workspace = true }
axum = { workspace = true }
common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
common-kafka = { path = "../common/kafka" }
+common-liveness = { path = "../common/liveness" }
envconfig = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
+metrics = { workspace = true }
+rdkafka = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serve-metrics = { path = "../common/serve_metrics" }
siphasher = { workspace = true }
+thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index 489dc2718b31..3f7985b0872a 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -26,11 +26,8 @@ pub struct Config {
#[envconfig(default = "500000")]
pub max_buffered_tuples: usize,
- #[envconfig(default = "property-vals-rs-local-events")]
- pub kafka_transactional_id: String,
-
#[envconfig(default = "60")]
- pub kafka_transaction_timeout_secs: u64,
+ pub kafka_produce_timeout_secs: u64,
#[envconfig(default = "clickhouse_groups")]
pub groups_kafka_consumer_topic: String,
@@ -38,9 +35,6 @@ pub struct Config {
#[envconfig(default = "clickhouse-property-vals-rs-groups")]
pub groups_kafka_consumer_group: String,
- #[envconfig(default = "property-vals-rs-local-groups")]
- pub groups_kafka_transactional_id: String,
-
#[envconfig(default = "")]
pub allowed_teams: TeamList,
@@ -79,13 +73,14 @@ impl FromStr for TeamList {
impl Config {
pub fn init_with_defaults() -> Result<Self, envconfig::Error> {
- // auto_commit=false because offsets are committed by the
- // transactional producer via send_offsets_to_transaction; auto-commit
- // would break the exactly-once guarantee.
+ // auto_commit=true: background timer ships stored offsets to the
+ // broker every ~5s. We manually advance the stored offset only after
+ // a successful produce (see worker.rs::flush), so the broker never
+ // sees an offset for input we haven't actually written out.
ConsumerConfig::set_defaults(
"clickhouse-property-vals-rs",
"clickhouse_events_json",
- false,
+ true,
);
Config::init_from_env()
}
diff --git a/rust/property-vals-rs/src/lib.rs b/rust/property-vals-rs/src/lib.rs
index 385521254ef6..c5c02a3cfe23 100644
--- a/rust/property-vals-rs/src/lib.rs
+++ b/rust/property-vals-rs/src/lib.rs
@@ -1,4 +1,7 @@
pub mod aggregator;
pub mod config;
pub mod fan_out;
+pub mod metrics_consts;
+pub mod producer;
pub mod types;
+pub mod worker;
diff --git a/rust/property-vals-rs/src/main.rs b/rust/property-vals-rs/src/main.rs
index ed353b8572fe..2ddca8193f21 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -1,8 +1,16 @@
+use std::sync::Arc;
use std::time::Duration;
use axum::{response::IntoResponse, routing::get, Router};
+use common_kafka::kafka_consumer::SingleTopicConsumer;
use lifecycle::{ComponentOptions, Manager};
-use property_vals_rs::config::Config;
+use property_vals_rs::{
+ config::Config,
+ fan_out::{fan_out, fan_out_group},
+ producer::AggregatedProducer,
+ types::{Event, GroupIdentify},
+ worker::worker_loop,
+};
use serve_metrics::setup_metrics_routes;
use tokio::net::TcpListener;
use tracing::level_filters::LevelFilter;
@@ -44,12 +52,90 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_global_shutdown_timeout(Duration::from_secs(60))
.build();
+ let events_handle = manager.register(
+ "events-worker",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(30))
+ .with_liveness_deadline(Duration::from_secs(60))
+ .with_stall_threshold(3),
+ );
+ let groups_handle = manager.register(
+ "groups-worker",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(30))
+ .with_liveness_deadline(Duration::from_secs(60))
+ .with_stall_threshold(3),
+ );
+
let metrics_handle =
manager.register("metrics", ComponentOptions::new().is_observability(true));
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
+ info!(
+ events_topic = %config.consumer.kafka_consumer_topic,
+ events_consumer_group = %config.consumer.kafka_consumer_group,
+ groups_topic = %config.groups_kafka_consumer_topic,
+ groups_consumer_group = %config.groups_kafka_consumer_group,
+ output_topic = %config.output_topic,
+ flush_interval_secs = config.flush_interval_secs,
+ "config loaded"
+ );
+
+ let produce_timeout = Duration::from_secs(config.kafka_produce_timeout_secs);
+
+ let events_consumer = SingleTopicConsumer::new(config.kafka.clone(), config.consumer.clone())?;
+ let events_producer = AggregatedProducer::new(
+ &config.kafka,
+ events_handle.clone(),
+ config.output_topic.clone(),
+ produce_timeout,
+ )
+ .await?;
+
+ let mut groups_consumer_config = config.consumer.clone();
+ groups_consumer_config.kafka_consumer_topic = config.groups_kafka_consumer_topic.clone();
+ groups_consumer_config.kafka_consumer_group = config.groups_kafka_consumer_group.clone();
+ let groups_consumer = SingleTopicConsumer::new(config.kafka.clone(), groups_consumer_config)?;
+ let groups_producer = AggregatedProducer::new(
+ &config.kafka,
+ groups_handle.clone(),
+ config.output_topic.clone(),
+ produce_timeout,
+ )
+ .await?;
+
+ info!(
+ "Subscribed to topic: {}",
+ config.consumer.kafka_consumer_topic
+ );
+ info!(
+ "Subscribed to topic: {}",
+ config.groups_kafka_consumer_topic
+ );
+
+ let shared_config = Arc::new(config.clone());
+
+ let guard = manager.monitor_background();
+
+ tokio::spawn(worker_loop::<Event, _, _>(
+ shared_config.clone(),
+ events_consumer,
+ events_producer,
+ events_handle.clone(),
+ fan_out,
+ ));
+ tokio::spawn(worker_loop::<GroupIdentify, _, _>(
+ shared_config.clone(),
+ groups_consumer,
+ groups_producer,
+ groups_handle.clone(),
+ fan_out_group,
+ ));
+ drop(events_handle);
+ drop(groups_handle);
+
let app = Router::new()
.route("/", get(index))
.route(
@@ -82,6 +168,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.await?;
metrics_handle.work_completed();
+ guard.wait().await?;
+
info!("property-vals-rs stopped");
Ok(())
}
diff --git a/rust/property-vals-rs/src/metrics_consts.rs b/rust/property-vals-rs/src/metrics_consts.rs
new file mode 100644
index 000000000000..8a1817335856
--- /dev/null
+++ b/rust/property-vals-rs/src/metrics_consts.rs
@@ -0,0 +1,11 @@
+pub const EVENTS_RECEIVED: &str = "property_vals_rs_events_received_total";
+pub const EVENTS_FILTERED: &str = "property_vals_rs_events_filtered_total";
+pub const TUPLES_AGGREGATED: &str = "property_vals_rs_tuples_aggregated_total";
+pub const FLUSH_TUPLES: &str = "property_vals_rs_flush_tuples";
+pub const FLUSH_TOTAL: &str = "property_vals_rs_flushes_total";
+pub const FLUSH_REASON_TIMER: &str = "timer";
+pub const FLUSH_REASON_BACKPRESSURE: &str = "backpressure";
+pub const FLUSH_REASON_SHUTDOWN: &str = "shutdown";
+pub const PRODUCER_FLUSH_FAILED: &str = "property_vals_rs_producer_flush_failed_total";
+pub const OFFSET_STORE_FAILED: &str = "property_vals_rs_offset_store_failed_total";
+pub const KAFKA_RECV_ERRORS: &str = "property_vals_rs_kafka_recv_errors_total";
diff --git a/rust/property-vals-rs/src/producer.rs b/rust/property-vals-rs/src/producer.rs
new file mode 100644
index 000000000000..48672fd537ed
--- /dev/null
+++ b/rust/property-vals-rs/src/producer.rs
@@ -0,0 +1,112 @@
+use std::time::Duration;
+
+use async_trait::async_trait;
+use common_kafka::config::KafkaConfig;
+use common_kafka::kafka_producer::{
+ create_kafka_producer, send_keyed_iter_to_kafka, KafkaContext, KafkaProduceError,
+};
+use rdkafka::error::KafkaError;
+use rdkafka::producer::FutureProducer;
+use thiserror::Error;
+use tracing::warn;
+
+use crate::types::{PropertyType, TupleKey};
+
+#[derive(serde::Serialize)]
+struct Outgoing<'a> {
+ team_id: i64,
+ property_type: PropertyType,
+ property_key: &'a str,
+ property_value: &'a str,
+ property_count: u64,
+}
+
+#[derive(Debug, Error)]
+pub enum ProduceError {
+ #[error("kafka produce timed out after {0:?}")]
+ Timeout(Duration),
+ #[error("{failed}/{total} records failed delivery")]
+ PartialFailure { failed: usize, total: usize },
+}
+
+/// Produce the aggregated tuples to the output topic. At-least-once: each
+/// produce stands on its own and the caller stores the input consumer offsets
+/// only after this returns Ok. On failure the caller does not advance the
+/// stored offsets, so the next pod resumes from before these inputs and
+/// re-produces them; duplicates are absorbed by the storage table's existing
+/// aggregation semantics.
+#[async_trait]
+pub trait Producer: Send {
+ async fn produce(&self, items: Vec<(TupleKey, u64)>) -> Result<(), ProduceError>;
+}
+
+pub struct AggregatedProducer {
+ inner: FutureProducer<KafkaContext>,
+ output_topic: String,
+ produce_timeout: Duration,
+}
+
+impl AggregatedProducer {
+ pub async fn new<L>(
+ kafka_config: &KafkaConfig,
+ liveness: L,
+ output_topic: String,
+ produce_timeout: Duration,
+ ) -> Result<Self, KafkaError>
+ where
+ L: common_liveness::SyncLivenessReporter + Clone + 'static,
+ {
+ let inner = create_kafka_producer(kafka_config, liveness).await?;
+ Ok(Self {
+ inner,
+ output_topic,
+ produce_timeout,
+ })
+ }
+}
+
+#[async_trait]
+impl Producer for AggregatedProducer {
+ async fn produce(&self, items: Vec<(TupleKey, u64)>) -> Result<(), ProduceError> {
+ if items.is_empty() {
+ return Ok(());
+ }
+ let total = items.len();
+
+ let messages: Vec<Outgoing> = items
+ .iter()
+ .map(|(tuple, count)| Outgoing {
+ team_id: tuple.team_id,
+ property_type: tuple.property_type,
+ property_key: &tuple.property_key,
+ property_value: &tuple.property_value,
+ property_count: *count,
+ })
+ .collect();
+
+ let send_fut = send_keyed_iter_to_kafka(
+ &self.inner,
+ &self.output_topic,
+ |m| Some(m.team_id.to_string()),
+ messages,
+ );
+
+ let results = match tokio::time::timeout(self.produce_timeout, send_fut).await {
+ Ok(r) => r,
+ Err(_) => {
+ warn!("kafka produce timed out after {:?}", self.produce_timeout);
+ return Err(ProduceError::Timeout(self.produce_timeout));
+ }
+ };
+
+ let failed = results
+ .iter()
+ .filter(|r| matches!(r, Err(KafkaProduceError::KafkaProduceError { .. })))
+ .count();
+ if failed > 0 {
+ return Err(ProduceError::PartialFailure { failed, total });
+ }
+
+ Ok(())
+ }
+}
diff --git a/rust/property-vals-rs/src/worker.rs b/rust/property-vals-rs/src/worker.rs
new file mode 100644
index 000000000000..5537714643ee
--- /dev/null
+++ b/rust/property-vals-rs/src/worker.rs
@@ -0,0 +1,394 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use common_kafka::kafka_consumer::{Offset, RecvErr, SingleTopicConsumer};
+use tracing::{error, info, warn};
+
+use crate::aggregator::Aggregator;
+use crate::config::Config;
+use crate::metrics_consts::*;
+use crate::producer::Producer;
+use crate::types::{IngestableEvent, TupleKey};
+
+/// One worker loop. Each pod runs one worker per input topic.
+///
+/// At-least-once: on each flush we produce non-transactionally, then on
+/// success advance the consumer's stored offsets. Background auto-commit
+/// (configured in init_with_defaults) flushes the stored offsets to the
+/// broker every 5s. On graceful shutdown we drain one final flush and
+/// force a synchronous commit so the next pod resumes from exactly here.
+pub async fn worker_loop<E, P, F>(
+ config: Arc<Config>,
+ consumer: SingleTopicConsumer,
+ producer: P,
+ handle: lifecycle::Handle,
+ fan_out_fn: F,
+) where
+ E: IngestableEvent,
+ P: Producer,
+ F: Fn(&E) -> Vec<TupleKey>,
+{
+ let _guard = handle.process_scope();
+
+ let mut aggregator = Aggregator::new();
+ // One Offset handle per partition: the latest message we've consumed.
+ // On successful flush we call .store() on each, which advances the
+ // consumer's stored offset; auto-commit ships it to the broker.
+ let mut pending_offsets: HashMap<i32, Offset> = HashMap::new();
+
+ let mut flush_timer = tokio::time::interval(Duration::from_secs(config.flush_interval_secs));
+ flush_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ flush_timer.reset();
+
+ loop {
+ tokio::select! {
+ _ = handle.shutdown_recv() => {
+ info!("worker received shutdown; draining final flush");
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_SHUTDOWN).await;
+ if let Err(e) = consumer.commit() {
+ warn!(error = %e, "kafka sync commit at shutdown failed; falling back to broker auto-commit");
+ }
+ return;
+ }
+ _ = flush_timer.tick() => {
+ handle.report_healthy();
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_TIMER).await;
+ }
+ recv = consumer.json_recv::<E>() => {
+ handle.report_healthy();
+ match recv {
+ Ok((event, offset)) => {
+ metrics::counter!(EVENTS_RECEIVED).increment(1);
+
+ if config.should_process(event.team_id()) {
+ let tuples = fan_out_fn(&event);
+ metrics::counter!(TUPLES_AGGREGATED).increment(tuples.len() as u64);
+ for t in tuples {
+ aggregator.add(t, 1);
+ }
+ } else {
+ metrics::counter!(EVENTS_FILTERED).increment(1);
+ }
+
+ pending_offsets.insert(offset.partition(), offset);
+
+ if aggregator.len() >= config.max_buffered_tuples {
+ flush(
+ &mut aggregator,
+ &mut pending_offsets,
+ &producer,
+ FLUSH_REASON_BACKPRESSURE,
+ ).await;
+ }
+ }
+ Err(RecvErr::Empty) | Err(RecvErr::Serde(_)) => {
+ // SingleTopicConsumer auto-stores poison-pill offsets.
+ }
+ Err(RecvErr::Kafka(e)) => {
+ metrics::counter!(KAFKA_RECV_ERRORS).increment(1);
+ warn!(error = %e, "kafka recv error");
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Produce the aggregated counts to the output topic, then advance the
+/// consumer's stored offsets so they get auto-committed. On produce failure,
+/// the snapshot is merged back into the aggregator and offsets are left
+/// untouched so the next flush retries the same input range.
+pub(crate) async fn flush<P: Producer>(
+ aggregator: &mut Aggregator,
+ pending_offsets: &mut HashMap<i32, Offset>,
+ producer: &P,
+ reason: &'static str,
+) {
+ if aggregator.is_empty() && pending_offsets.is_empty() {
+ return;
+ }
+
+ let snapshot: Vec<(TupleKey, u64)> = aggregator.drain().into_iter().collect();
+
+ metrics::counter!(FLUSH_TOTAL, "reason" => reason).increment(1);
+ metrics::histogram!(FLUSH_TUPLES).record(snapshot.len() as f64);
+
+ if let Err(e) = producer.produce(snapshot.clone()).await {
+ metrics::counter!(PRODUCER_FLUSH_FAILED).increment(1);
+ error!(error = %e, "produce failed; restoring counts, retrying next flush");
+ for (tuple, count) in snapshot {
+ aggregator.add(tuple, count);
+ }
+ return;
+ }
+
+ // Produce succeeded; advance the stored offset for each partition we
+ // consumed from. Background auto-commit will ship these to the broker
+ // within ~5s; shutdown forces a sync commit.
+ for (_partition, offset) in pending_offsets.drain() {
+ if let Err(e) = offset.store() {
+ metrics::counter!(OFFSET_STORE_FAILED).increment(1);
+ warn!(error = %e, "failed to store offset; auto-commit will be a no-op for this partition until the next successful flush");
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::aggregator::Aggregator;
+ use crate::producer::ProduceError;
+ use crate::types::{PropertyType, TupleKey};
+ use proptest::prelude::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Mutex;
+
+ /// Mock producer that records each call and can be configured to fail on
+ /// specific call indices.
+ struct MockProducer {
+ calls: AtomicUsize,
+ fail_on: Mutex<Vec<usize>>,
+ seen_items: Mutex<Vec<Vec<(TupleKey, u64)>>>,
+ }
+
+ impl MockProducer {
+ fn new() -> Self {
+ Self {
+ calls: AtomicUsize::new(0),
+ fail_on: Mutex::new(Vec::new()),
+ seen_items: Mutex::new(Vec::new()),
+ }
+ }
+ fn fail_on(self, call_index: usize) -> Self {
+ self.fail_on.lock().unwrap().push(call_index);
+ self
+ }
+ fn call_count(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+ fn last_items(&self) -> Vec<(TupleKey, u64)> {
+ self.seen_items
+ .lock()
+ .unwrap()
+ .last()
+ .cloned()
+ .unwrap_or_default()
+ }
+ fn successful_batches(&self) -> Vec<Vec<(TupleKey, u64)>> {
+ let items = self.seen_items.lock().unwrap();
+ let fail = self.fail_on.lock().unwrap();
+ items
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| !fail.contains(&(i + 1)))
+ .map(|(_, batch)| batch.clone())
+ .collect()
+ }
+ }
+
+ #[async_trait::async_trait]
+ impl Producer for MockProducer {
+ async fn produce(&self, items: Vec<(TupleKey, u64)>) -> Result<(), ProduceError> {
+ let n = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
+ self.seen_items.lock().unwrap().push(items.clone());
+ if self.fail_on.lock().unwrap().contains(&n) {
+ let total = items.len().max(1);
+ return Err(ProduceError::PartialFailure {
+ failed: total,
+ total,
+ });
+ }
+ Ok(())
+ }
+ }
+
+ fn tuple(team: i64, key: &str, value: &str) -> TupleKey {
+ TupleKey {
+ team_id: team,
+ property_type: PropertyType::Event,
+ property_key: key.to_string(),
+ property_value: value.to_string(),
+ }
+ }
+
+ fn populate(agg: &mut Aggregator, count: u64) {
+ for i in 0..count {
+ agg.add(tuple(2, "k", &format!("v{i}")), 1);
+ }
+ }
+
+ #[tokio::test]
+ async fn successful_flush_drains_aggregator() {
+ let mut agg = Aggregator::new();
+ populate(&mut agg, 5);
+
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new();
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+
+ assert!(agg.is_empty());
+ assert_eq!(producer.call_count(), 1);
+ assert_eq!(producer.last_items().len(), 5);
+ }
+
+ #[tokio::test]
+ async fn failed_flush_restores_counts() {
+ let mut agg = Aggregator::new();
+ populate(&mut agg, 3);
+
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new().fail_on(1);
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+
+ assert_eq!(
+ agg.len(),
+ 3,
+ "aggregator must restore drained counts on produce failure"
+ );
+ }
+
+ #[tokio::test]
+ async fn failed_then_successful_flush_eventually_clears_state() {
+ let mut agg = Aggregator::new();
+ populate(&mut agg, 4);
+
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new().fail_on(1);
+
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+ assert!(!agg.is_empty());
+
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+ assert!(agg.is_empty());
+ assert_eq!(producer.call_count(), 2);
+ }
+
+ #[tokio::test]
+ async fn empty_aggregator_empty_offsets_is_noop() {
+ let mut agg = Aggregator::new();
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new();
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+ assert_eq!(producer.call_count(), 0);
+ }
+
+ #[tokio::test]
+ async fn restored_counts_merge_with_new_counts_in_next_window() {
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "k1", "v1"), 1);
+
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new().fail_on(1);
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+
+ agg.add(tuple(2, "k1", "v1"), 1);
+
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+
+ let batch = producer.last_items();
+ assert_eq!(batch.len(), 1);
+ assert_eq!(batch[0].1, 2);
+ }
+
+ #[tokio::test]
+ async fn repeated_failure_holds_all_state_indefinitely() {
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "k1", "v1"), 1);
+
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new().fail_on(1).fail_on(2).fail_on(3);
+
+ for _ in 0..3 {
+ flush(&mut agg, &mut pending, &producer, FLUSH_REASON_TIMER).await;
+ }
+
+ assert_eq!(agg.len(), 1);
+ assert_eq!(producer.call_count(), 3);
+ }
+
+ fn arb_property_type() -> impl Strategy<Value = PropertyType> {
+ prop_oneof![
+ Just(PropertyType::Event),
+ Just(PropertyType::Person),
+ (0u8..=4).prop_map(PropertyType::Group),
+ ]
+ }
+
+ prop_compose! {
+ fn arb_tuple()(
+ team_id in -3i64..=3,
+ property_type in arb_property_type(),
+ property_key in "[a-c]{1,2}",
+ property_value in "[x-z]{1,2}",
+ ) -> TupleKey {
+ TupleKey { team_id, property_type, property_key, property_value }
+ }
+ }
+
+ #[derive(Debug, Clone)]
+ enum WorkerOp {
+ Add(TupleKey, u64),
+ Flush,
+ }
+
+ fn arb_worker_op() -> impl Strategy<Value = WorkerOp> {
+ prop_oneof![
+ // 4:1 weighting so the aggregator actually accumulates between flushes
+ // instead of every other op being an immediate drain.
+ 4 => (arb_tuple(), 1u64..100).prop_map(|(t, n)| WorkerOp::Add(t, n)),
+ 1 => Just(WorkerOp::Flush),
+ ]
+ }
+
+ proptest! {
+ #[test]
+ fn flush_conserves_counts(
+ ops in prop::collection::vec(arb_worker_op(), 0..60),
+ fail_indices in prop::collection::vec(1usize..30, 0..15),
+ ) {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+
+ let mut agg = Aggregator::new();
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let mut producer = MockProducer::new();
+ for idx in &fail_indices {
+ producer = producer.fail_on(*idx);
+ }
+
+ let mut recorded: HashMap<TupleKey, u64> = HashMap::new();
+
+ for op in &ops {
+ match op {
+ WorkerOp::Add(t, n) => {
+ agg.add(t.clone(), *n);
+ *recorded.entry(t.clone()).or_insert(0) += *n;
+ }
+ WorkerOp::Flush => {
+ runtime.block_on(flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ ));
+ }
+ }
+ }
+
+ let mut accounted: HashMap<TupleKey, u64> = HashMap::new();
+ for (t, n) in agg.drain() {
+ *accounted.entry(t).or_insert(0) += n;
+ }
+ for batch in producer.successful_batches() {
+ for (t, n) in batch {
+ *accounted.entry(t).or_insert(0) += n;
+ }
+ }
+
+ prop_assert_eq!(recorded, accounted);
+ }
+ }
+}