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(property-vals): emit-once seen cache in merger (#60733)

Andy Zhao10b3138a0d19
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5a81a0e97a15..700380679995 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7404,6 +7404,7 @@ dependencies = [
"lifecycle",
"metrics",
"proptest",
+ "quick_cache",
"rdkafka",
"serde",
"serde_json",
diff --git a/rust/property-vals-rs/Cargo.toml b/rust/property-vals-rs/Cargo.toml
index ea04c82ae246..424a4f6fa096 100644
--- a/rust/property-vals-rs/Cargo.toml
+++ b/rust/property-vals-rs/Cargo.toml
@@ -14,6 +14,7 @@ common-liveness = { path = "../common/liveness" }
envconfig = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
+quick_cache = { workspace = true }
rdkafka = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index b374f340bf99..c2ecd4c83b0d 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -38,6 +38,9 @@ pub struct Config {
#[envconfig(default = "0")]
pub max_values_per_key: usize,
+ #[envconfig(default = "0")]
+ pub merger_seen_cache_capacity: usize,
+
#[envconfig(default = "60")]
pub kafka_produce_timeout_secs: u64,
diff --git a/rust/property-vals-rs/src/lib.rs b/rust/property-vals-rs/src/lib.rs
index c5c02a3cfe23..381b2dfacbd6 100644
--- a/rust/property-vals-rs/src/lib.rs
+++ b/rust/property-vals-rs/src/lib.rs
@@ -3,5 +3,6 @@ pub mod config;
pub mod fan_out;
pub mod metrics_consts;
pub mod producer;
+pub mod seen_cache;
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 a5ee9a10e6d4..6e1430fc2f9b 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -9,7 +9,7 @@ use property_vals_rs::{
fan_out::{extract_tuple, fan_out, fan_out_group},
producer::AggregatedProducer,
types::{Event, GroupIdentify, PropertyValueMessage},
- worker::worker_loop,
+ worker::{worker_loop, ReductionConfig},
};
use serve_metrics::setup_metrics_routes;
use tokio::net::TcpListener;
@@ -151,7 +151,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
events_handle.clone(),
move |e: &Event| fan_out(e, &excluded_events),
"events",
- 0,
+ ReductionConfig::default(),
));
tokio::spawn(worker_loop::<GroupIdentify, _, _>(
shared_config.clone(),
@@ -160,7 +160,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
groups_handle.clone(),
move |g: &GroupIdentify| fan_out_group(g, &excluded_groups),
"groups",
- 0,
+ ReductionConfig::default(),
));
tokio::spawn(worker_loop::<PropertyValueMessage, _, _>(
shared_config.clone(),
@@ -169,7 +169,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
merger_handle.clone(),
|m: &PropertyValueMessage| extract_tuple(m),
"merger",
- shared_config.max_values_per_key,
+ ReductionConfig {
+ max_values_per_key: shared_config.max_values_per_key,
+ seen_cache_capacity: shared_config.merger_seen_cache_capacity,
+ },
));
drop(events_handle);
drop(groups_handle);
diff --git a/rust/property-vals-rs/src/metrics_consts.rs b/rust/property-vals-rs/src/metrics_consts.rs
index f7f19e13f315..d6f88a9768ec 100644
--- a/rust/property-vals-rs/src/metrics_consts.rs
+++ b/rust/property-vals-rs/src/metrics_consts.rs
@@ -11,3 +11,6 @@ pub const PRODUCER_FLUSH_FAILED: &str = "property_vals_rs_producer_flush_failed_
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";
pub const TOP_K_DROPPED: &str = "property_vals_rs_top_k_dropped_total";
+pub const SEEN_CACHE_HITS: &str = "property_vals_rs_seen_cache_hits_total";
+pub const SEEN_CACHE_MISSES: &str = "property_vals_rs_seen_cache_misses_total";
+pub const SEEN_CACHE_EVICTED: &str = "property_vals_rs_seen_cache_evicted_total";
diff --git a/rust/property-vals-rs/src/seen_cache.rs b/rust/property-vals-rs/src/seen_cache.rs
new file mode 100644
index 000000000000..78ae4eabf0df
--- /dev/null
+++ b/rust/property-vals-rs/src/seen_cache.rs
@@ -0,0 +1,53 @@
+use quick_cache::{sync, DefaultHashBuilder, Lifecycle, UnitWeighter};
+
+use crate::metrics_consts::{SEEN_CACHE_EVICTED, SEEN_CACHE_HITS, SEEN_CACHE_MISSES};
+use crate::types::TupleKey;
+
+#[derive(Clone)]
+struct EvictingLifecycle {
+ worker: &'static str,
+}
+
+impl Lifecycle<TupleKey, ()> for EvictingLifecycle {
+ type RequestState = ();
+
+ fn begin_request(&self) -> Self::RequestState {}
+
+ fn on_evict(&self, _state: &mut Self::RequestState, _key: TupleKey, _val: ()) {
+ metrics::counter!(SEEN_CACHE_EVICTED, "worker" => self.worker).increment(1);
+ }
+}
+
+type Inner = sync::Cache<TupleKey, (), UnitWeighter, DefaultHashBuilder, EvictingLifecycle>;
+
+pub struct SeenCache {
+ cache: Inner,
+ worker: &'static str,
+}
+
+impl SeenCache {
+ pub fn new(capacity: usize, worker: &'static str) -> Self {
+ let cache = sync::Cache::with(
+ capacity,
+ capacity as u64,
+ UnitWeighter,
+ DefaultHashBuilder::default(),
+ EvictingLifecycle { worker },
+ );
+ Self { cache, worker }
+ }
+
+ pub fn seen(&self, key: &TupleKey) -> bool {
+ if self.cache.get(key).is_some() {
+ metrics::counter!(SEEN_CACHE_HITS, "worker" => self.worker).increment(1);
+ true
+ } else {
+ metrics::counter!(SEEN_CACHE_MISSES, "worker" => self.worker).increment(1);
+ false
+ }
+ }
+
+ pub fn insert(&self, key: &TupleKey) {
+ self.cache.insert(key.clone(), ());
+ }
+}
diff --git a/rust/property-vals-rs/src/worker.rs b/rust/property-vals-rs/src/worker.rs
index 0cdacdb552fc..ca2111f52ccf 100644
--- a/rust/property-vals-rs/src/worker.rs
+++ b/rust/property-vals-rs/src/worker.rs
@@ -9,8 +9,15 @@ use crate::aggregator::Aggregator;
use crate::config::Config;
use crate::metrics_consts::*;
use crate::producer::Producer;
+use crate::seen_cache::SeenCache;
use crate::types::{IngestableEvent, PropertyType, TupleKey};
+#[derive(Clone, Copy, Default)]
+pub struct ReductionConfig {
+ pub max_values_per_key: usize,
+ pub seen_cache_capacity: usize,
+}
+
/// One worker loop. Each pod runs one worker per input topic.
///
/// At-least-once: on each flush we produce non-transactionally, then on
@@ -25,7 +32,7 @@ pub async fn worker_loop<E, P, F>(
handle: lifecycle::Handle,
fan_out_fn: F,
worker: &'static str,
- max_values_per_key: usize,
+ reduction: ReductionConfig,
) where
E: IngestableEvent,
P: Producer,
@@ -34,6 +41,8 @@ pub async fn worker_loop<E, P, F>(
let _guard = handle.process_scope();
let mut aggregator = Aggregator::new();
+ let seen_cache = (reduction.seen_cache_capacity > 0)
+ .then(|| SeenCache::new(reduction.seen_cache_capacity, worker));
// 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.
@@ -47,7 +56,7 @@ pub async fn worker_loop<E, P, F>(
tokio::select! {
_ = handle.shutdown_recv() => {
info!("worker received shutdown; draining final flush");
- flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_SHUTDOWN, worker, max_values_per_key).await;
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_SHUTDOWN, worker, reduction.max_values_per_key, seen_cache.as_ref()).await;
if let Err(e) = consumer.commit() {
warn!(error = %e, "kafka sync commit at shutdown failed; falling back to broker auto-commit");
}
@@ -55,7 +64,7 @@ pub async fn worker_loop<E, P, F>(
}
_ = flush_timer.tick() => {
handle.report_healthy();
- flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_TIMER, worker, max_values_per_key).await;
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_TIMER, worker, reduction.max_values_per_key, seen_cache.as_ref()).await;
}
recv = consumer.json_recv::<E>() => {
handle.report_healthy();
@@ -82,7 +91,8 @@ pub async fn worker_loop<E, P, F>(
&producer,
FLUSH_REASON_BACKPRESSURE,
worker,
- max_values_per_key,
+ reduction.max_values_per_key,
+ seen_cache.as_ref(),
).await;
}
}
@@ -110,6 +120,7 @@ pub(crate) async fn flush<P: Producer>(
reason: &'static str,
worker: &'static str,
max_values_per_key: usize,
+ seen_cache: Option<&SeenCache>,
) {
if aggregator.is_empty() && pending_offsets.is_empty() {
return;
@@ -120,20 +131,35 @@ pub(crate) async fn flush<P: Producer>(
snapshot = cap_top_k(snapshot, max_values_per_key, worker);
}
+ let to_emit: Vec<(TupleKey, u64)> = match seen_cache {
+ Some(cache) => snapshot
+ .into_iter()
+ .filter(|(tuple, _)| !cache.seen(tuple))
+ .collect(),
+ None => snapshot,
+ };
+
metrics::counter!(FLUSH_TOTAL, "reason" => reason, "worker" => worker).increment(1);
- metrics::histogram!(FLUSH_TUPLES, "worker" => worker).record(snapshot.len() as f64);
+ metrics::histogram!(FLUSH_TUPLES, "worker" => worker).record(to_emit.len() as f64);
- for (_, count) in &snapshot {
+ for (_, count) in &to_emit {
metrics::histogram!(FLUSH_TUPLE_COUNT, "worker" => worker).record(*count as f64);
}
- if let Err(e) = producer.produce(snapshot.clone()).await {
- metrics::counter!(PRODUCER_FLUSH_FAILED, "worker" => worker).increment(1);
- error!(error = %e, "produce failed; restoring counts, retrying next flush");
- for (tuple, count) in snapshot {
- aggregator.add(tuple, count);
+ if !to_emit.is_empty() {
+ if let Err(e) = producer.produce(to_emit.clone()).await {
+ metrics::counter!(PRODUCER_FLUSH_FAILED, "worker" => worker).increment(1);
+ error!(error = %e, "produce failed; restoring counts, retrying next flush");
+ for (tuple, count) in to_emit {
+ aggregator.add(tuple, count);
+ }
+ return;
+ }
+ if let Some(cache) = seen_cache {
+ for (tuple, _) in &to_emit {
+ cache.insert(tuple);
+ }
}
- return;
}
// Produce succeeded; advance the stored offset for each partition we
@@ -329,6 +355,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
@@ -351,6 +378,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
@@ -376,6 +404,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
assert!(!agg.is_empty());
@@ -387,6 +416,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
assert!(agg.is_empty());
@@ -405,6 +435,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
assert_eq!(producer.call_count(), 0);
@@ -424,6 +455,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
@@ -436,6 +468,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
@@ -460,6 +493,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
)
.await;
}
@@ -468,6 +502,132 @@ mod tests {
assert_eq!(producer.call_count(), 3);
}
+ #[tokio::test]
+ async fn seen_cache_suppresses_already_emitted_tuples() {
+ let cache = SeenCache::new(1000, "test");
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new();
+
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "k", "v"), 1);
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ assert_eq!(producer.last_items().len(), 1, "first sight is emitted");
+
+ agg.add(tuple(2, "k", "v"), 1);
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ assert_eq!(
+ producer.call_count(),
+ 1,
+ "an already-cached tuple is suppressed, so there is no second produce"
+ );
+ assert!(
+ agg.is_empty(),
+ "suppressed tuples still drain the aggregator"
+ );
+ }
+
+ #[tokio::test]
+ async fn seen_cache_reemits_after_produce_failure() {
+ let cache = SeenCache::new(1000, "test");
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new().fail_on(1);
+
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "k", "v"), 1);
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ assert_eq!(agg.len(), 1, "failed produce restores the tuple for retry");
+
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ assert_eq!(producer.call_count(), 2);
+ assert_eq!(
+ producer.last_items().len(),
+ 1,
+ "a tuple forgotten on produce failure is re-emitted, not lost to the cache"
+ );
+ }
+
+ #[tokio::test]
+ async fn seen_cache_emits_new_values_and_suppresses_repeats() {
+ let cache = SeenCache::new(1000, "test");
+ let mut pending: HashMap<i32, Offset> = HashMap::new();
+ let producer = MockProducer::new();
+
+ let mut agg = Aggregator::new();
+ agg.add(tuple(2, "k", "a"), 1);
+ agg.add(tuple(2, "k", "b"), 1);
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ assert_eq!(
+ producer.last_items().len(),
+ 2,
+ "distinct new tuples all emit"
+ );
+
+ agg.add(tuple(2, "k", "a"), 1); // already seen
+ agg.add(tuple(2, "k", "c"), 1); // new
+ flush(
+ &mut agg,
+ &mut pending,
+ &producer,
+ FLUSH_REASON_TIMER,
+ "test",
+ 0,
+ Some(&cache),
+ )
+ .await;
+ let batch = producer.last_items();
+ assert_eq!(
+ batch.len(),
+ 1,
+ "only the new value emits; the repeat is suppressed"
+ );
+ assert_eq!(batch[0].0.property_value, "c");
+ }
+
fn arb_property_type() -> impl Strategy<Value = PropertyType> {
prop_oneof![
Just(PropertyType::Event),
@@ -536,6 +696,7 @@ mod tests {
FLUSH_REASON_TIMER,
"test",
0,
+ None,
));
}
}