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): cap top-K values per key in merger (#60595)

Andy Zhao187eb205cae4
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index efc33680e39c..b374f340bf99 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -35,6 +35,9 @@ pub struct Config {
#[envconfig(default = "500000")]
pub max_buffered_tuples: usize,
+ #[envconfig(default = "0")]
+ pub max_values_per_key: usize,
+
#[envconfig(default = "60")]
pub kafka_produce_timeout_secs: u64,
diff --git a/rust/property-vals-rs/src/main.rs b/rust/property-vals-rs/src/main.rs
index 47fa8cbeb192..a5ee9a10e6d4 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -151,6 +151,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
events_handle.clone(),
move |e: &Event| fan_out(e, &excluded_events),
"events",
+ 0,
));
tokio::spawn(worker_loop::<GroupIdentify, _, _>(
shared_config.clone(),
@@ -159,6 +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,
));
tokio::spawn(worker_loop::<PropertyValueMessage, _, _>(
shared_config.clone(),
@@ -167,6 +169,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
merger_handle.clone(),
|m: &PropertyValueMessage| extract_tuple(m),
"merger",
+ shared_config.max_values_per_key,
));
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 2b47e2ba6939..f7f19e13f315 100644
--- a/rust/property-vals-rs/src/metrics_consts.rs
+++ b/rust/property-vals-rs/src/metrics_consts.rs
@@ -10,3 +10,4 @@ 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";
+pub const TOP_K_DROPPED: &str = "property_vals_rs_top_k_dropped_total";
diff --git a/rust/property-vals-rs/src/worker.rs b/rust/property-vals-rs/src/worker.rs
index def52be7f46b..0cdacdb552fc 100644
--- a/rust/property-vals-rs/src/worker.rs
+++ b/rust/property-vals-rs/src/worker.rs
@@ -9,7 +9,7 @@ use crate::aggregator::Aggregator;
use crate::config::Config;
use crate::metrics_consts::*;
use crate::producer::Producer;
-use crate::types::{IngestableEvent, TupleKey};
+use crate::types::{IngestableEvent, PropertyType, TupleKey};
/// One worker loop. Each pod runs one worker per input topic.
///
@@ -25,6 +25,7 @@ pub async fn worker_loop<E, P, F>(
handle: lifecycle::Handle,
fan_out_fn: F,
worker: &'static str,
+ max_values_per_key: usize,
) where
E: IngestableEvent,
P: Producer,
@@ -46,7 +47,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).await;
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_SHUTDOWN, worker, max_values_per_key).await;
if let Err(e) = consumer.commit() {
warn!(error = %e, "kafka sync commit at shutdown failed; falling back to broker auto-commit");
}
@@ -54,7 +55,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).await;
+ flush(&mut aggregator, &mut pending_offsets, &producer, FLUSH_REASON_TIMER, worker, max_values_per_key).await;
}
recv = consumer.json_recv::<E>() => {
handle.report_healthy();
@@ -81,6 +82,7 @@ pub async fn worker_loop<E, P, F>(
&producer,
FLUSH_REASON_BACKPRESSURE,
worker,
+ max_values_per_key,
).await;
}
}
@@ -107,12 +109,16 @@ pub(crate) async fn flush<P: Producer>(
producer: &P,
reason: &'static str,
worker: &'static str,
+ max_values_per_key: usize,
) {
if aggregator.is_empty() && pending_offsets.is_empty() {
return;
}
- let snapshot: Vec<(TupleKey, u64)> = aggregator.drain().into_iter().collect();
+ let mut snapshot: Vec<(TupleKey, u64)> = aggregator.drain().into_iter().collect();
+ if max_values_per_key > 0 {
+ snapshot = cap_top_k(snapshot, max_values_per_key, worker);
+ }
metrics::counter!(FLUSH_TOTAL, "reason" => reason, "worker" => worker).increment(1);
metrics::histogram!(FLUSH_TUPLES, "worker" => worker).record(snapshot.len() as f64);
@@ -141,6 +147,37 @@ pub(crate) async fn flush<P: Producer>(
}
}
+/// Cap each (team, type, key) to its `k` highest-count values, dropping the
+/// rest. Keys with `<= k` distinct values are untouched, so low-cardinality
+/// keys keep everything; only high-cardinality keys lose their long tail.
+fn cap_top_k(
+ snapshot: Vec<(TupleKey, u64)>,
+ k: usize,
+ worker: &'static str,
+) -> Vec<(TupleKey, u64)> {
+ let mut by_key: HashMap<(i64, PropertyType, String), Vec<(TupleKey, u64)>> = HashMap::new();
+ for entry in snapshot {
+ let group = (
+ entry.0.team_id,
+ entry.0.property_type,
+ entry.0.property_key.clone(),
+ );
+ by_key.entry(group).or_default().push(entry);
+ }
+
+ let mut out = Vec::new();
+ for (_, mut values) in by_key {
+ if values.len() > k {
+ values.select_nth_unstable_by(k, |a, b| b.1.cmp(&a.1));
+ let dropped = values.len() - k;
+ values.truncate(k);
+ metrics::counter!(TOP_K_DROPPED, "worker" => worker).increment(dropped as u64);
+ }
+ out.extend(values);
+ }
+ out
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -225,6 +262,59 @@ mod tests {
}
}
+ #[test]
+ fn cap_top_k_keeps_keys_under_the_cap() {
+ let snap = vec![
+ (tuple(2, "$browser", "Chrome"), 5),
+ (tuple(2, "$browser", "Firefox"), 1),
+ (tuple(2, "$browser", "Safari"), 1),
+ ];
+ let out = cap_top_k(snap, 10, "test");
+ assert_eq!(
+ out.len(),
+ 3,
+ "a key with fewer than k values keeps all of them"
+ );
+ }
+
+ #[test]
+ fn cap_top_k_drops_tail_of_high_card_key() {
+ let snap = vec![
+ (tuple(2, "$insert_id", "a"), 1),
+ (tuple(2, "$insert_id", "b"), 9),
+ (tuple(2, "$insert_id", "c"), 5),
+ (tuple(2, "$insert_id", "d"), 1),
+ ];
+ let out = cap_top_k(snap, 2, "test");
+ assert_eq!(out.len(), 2);
+ let counts: Vec<u64> = out.iter().map(|(_, c)| *c).collect();
+ assert!(
+ counts.contains(&9) && counts.contains(&5),
+ "keeps the two highest counts"
+ );
+ }
+
+ #[test]
+ fn cap_top_k_caps_each_key_independently() {
+ let snap = vec![
+ (tuple(2, "$browser", "Chrome"), 3),
+ (tuple(2, "$insert_id", "a"), 1),
+ (tuple(2, "$insert_id", "b"), 2),
+ (tuple(2, "$insert_id", "c"), 3),
+ ];
+ let out = cap_top_k(snap, 2, "test");
+ let browser = out
+ .iter()
+ .filter(|(t, _)| t.property_key == "$browser")
+ .count();
+ let insert = out
+ .iter()
+ .filter(|(t, _)| t.property_key == "$insert_id")
+ .count();
+ assert_eq!(browser, 1, "low-card key untouched");
+ assert_eq!(insert, 2, "high-card key capped to k");
+ }
+
#[tokio::test]
async fn successful_flush_drains_aggregator() {
let mut agg = Aggregator::new();
@@ -238,6 +328,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
@@ -259,6 +350,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
@@ -283,6 +375,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
assert!(!agg.is_empty());
@@ -293,6 +386,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
assert!(agg.is_empty());
@@ -310,6 +404,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
assert_eq!(producer.call_count(), 0);
@@ -328,6 +423,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
@@ -339,6 +435,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
@@ -362,6 +459,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
)
.await;
}
@@ -437,6 +535,7 @@ mod tests {
&producer,
FLUSH_REASON_TIMER,
"test",
+ 0,
));
}
}