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(propdefs): factor out quick_cache counters, enable in-app, misc. cleanups (#57577)

Eli Reisman9c4d87873ebb
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index c9ddbd24bd95..ae675fd89d41 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -7254,10 +7254,12 @@ dependencies = [
"futures",
"lifecycle",
"metrics",
+ "metrics-util",
"personhog-proto",
"quick_cache",
"rand 0.8.5",
"regex",
+ "rstest",
"serde",
"serde_json",
"serve-metrics",
diff --git a/rust/property-defs-rs/Cargo.toml b/rust/property-defs-rs/Cargo.toml
index 54888d28fee6..aee2e1df41b0 100644
--- a/rust/property-defs-rs/Cargo.toml
+++ b/rust/property-defs-rs/Cargo.toml
@@ -18,7 +18,7 @@ axum = { workspace = true }
serve-metrics = { path = "../common/serve_metrics" }
metrics = { workspace = true }
chrono = { workspace = true }
-quick_cache = { workspace = true, features = ["stats"] }
+quick_cache = { workspace = true }
common-metrics = { path = "../common/metrics" }
common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
@@ -34,6 +34,8 @@ regex.workspace = true
[dev-dependencies]
tokio-stream = { version = "0.1", features = ["net"] }
+metrics-util = { workspace = true }
+rstest = "0.26"
[lints]
workspace = true
diff --git a/rust/property-defs-rs/src/lib.rs b/rust/property-defs-rs/src/lib.rs
index 34e633f2a5e6..4ea45228b1b7 100644
--- a/rust/property-defs-rs/src/lib.rs
+++ b/rust/property-defs-rs/src/lib.rs
@@ -5,10 +5,10 @@ use batch_ingestion::process_batch;
use common_kafka::kafka_consumer::{RecvErr, SingleTopicConsumer};
use config::Config;
use metrics_consts::{
- BATCH_ACQUIRE_TIME, CACHE_CONSUMED, CACHE_HITS, CACHE_LEN, CACHE_MISSES, COMPACTED_UPDATES,
- DUPLICATES_IN_BATCH, EMPTY_EVENTS, EVENTS_RECEIVED, EVENT_PARSE_ERROR, FORCED_SMALL_BATCH,
- RECV_DEQUEUED, SKIPPED_DUE_TO_TEAM_FILTER, UPDATES_FILTERED_BY_CACHE, UPDATES_PER_EVENT,
- UPDATES_SEEN, UPDATE_PRODUCER_OFFSET, WORKER_BLOCKED,
+ BATCH_ACQUIRE_TIME, CACHE_CONSUMED, CACHE_LEN, COMPACTED_UPDATES, DUPLICATES_IN_BATCH,
+ EMPTY_EVENTS, EVENTS_RECEIVED, EVENT_PARSE_ERROR, FORCED_SMALL_BATCH, RECV_DEQUEUED,
+ SKIPPED_DUE_TO_TEAM_FILTER, UPDATES_FILTERED_BY_CACHE, UPDATES_PER_EVENT, UPDATES_SEEN,
+ UPDATE_PRODUCER_OFFSET, WORKER_BLOCKED,
};
use types::{Event, Update};
@@ -40,8 +40,6 @@ pub async fn update_consumer_loop(
handle: lifecycle::Handle,
) {
let _guard = handle.process_scope();
- let mut prev_hits = [0u64; 3];
- let mut prev_misses = [0u64; 3];
loop {
let mut batch = Vec::with_capacity(config.update_batch_size);
@@ -97,42 +95,34 @@ pub async fn update_consumer_loop(
metrics::counter!(DUPLICATES_IN_BATCH).increment((start_len - batch.len()) as u64);
- // Per-cache metrics once per batch (before DB write path)
- let caps = [
- (config.eventdefs_cache_capacity, "eventdefs"),
- (config.eventprops_cache_capacity, "eventprops"),
- (config.propdefs_cache_capacity, "propdefs"),
+ // Per-subcache size gauges once per batch. Hit/miss/eviction counters
+ // are emitted from inside `Cache::contains_key` and the EvictingLifecycle
+ // impl in `update_cache.rs`, not here.
+ let per_cache = [
+ (
+ config.eventdefs_cache_capacity,
+ "eventdefs",
+ cache.eventdefs_len(),
+ ),
+ (
+ config.eventprops_cache_capacity,
+ "eventprops",
+ cache.eventprops_len(),
+ ),
+ (
+ config.propdefs_cache_capacity,
+ "propdefs",
+ cache.propdefs_len(),
+ ),
];
- let lens = [
- cache.eventdefs_len(),
- cache.eventprops_len(),
- cache.propdefs_len(),
- ];
- let hits = [
- cache.eventdefs_hits(),
- cache.eventprops_hits(),
- cache.propdefs_hits(),
- ];
- let misses = [
- cache.eventdefs_misses(),
- cache.eventprops_misses(),
- cache.propdefs_misses(),
- ];
- for (i, (cap, label)) in caps.iter().enumerate() {
- let len = lens[i];
- let cap_f = *cap as f64;
- metrics::gauge!(CACHE_CONSUMED, &[("cache", *label)]).set(if cap_f > 0.0 {
+ for (cap, label, len) in per_cache {
+ let cap_f = cap as f64;
+ metrics::gauge!(CACHE_CONSUMED, &[("cache", label)]).set(if cap_f > 0.0 {
len as f64 / cap_f
} else {
0.0
});
- metrics::gauge!(CACHE_LEN, &[("cache", *label)]).set(len as f64);
- let delta_hits = hits[i].saturating_sub(prev_hits[i]);
- let delta_misses = misses[i].saturating_sub(prev_misses[i]);
- metrics::counter!(CACHE_HITS, &[("cache", *label)]).increment(delta_hits);
- metrics::counter!(CACHE_MISSES, &[("cache", *label)]).increment(delta_misses);
- prev_hits[i] = hits[i];
- prev_misses[i] = misses[i];
+ metrics::gauge!(CACHE_LEN, &[("cache", label)]).set(len as f64);
}
// enrich batch group events with resolved group_type_indices
@@ -239,7 +229,7 @@ pub async fn update_producer_loop(
last_send = tokio::time::Instant::now();
for update in batch.drain() {
if shared_cache.contains_key(&update) {
- // the above can replace this metric when we have new hit/miss stats both flowing
+ // kept for back-compat; equivalent to sum(prop_defs_cache_hits)
metrics::counter!(UPDATES_FILTERED_BY_CACHE).increment(1);
continue;
}
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index 4326c51e7ac4..5faab515a067 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -14,12 +14,12 @@ pub const CACHE_CONSUMED: &str = "prop_defs_cache_space";
pub const CACHE_LEN: &str = "prop_defs_cache_len";
pub const CACHE_HITS: &str = "prop_defs_cache_hits";
pub const CACHE_MISSES: &str = "prop_defs_cache_misses";
+pub const CACHE_EVICTIONS: &str = "prop_defs_cache_evictions";
pub const UPDATES_CACHE: &str = "prop_defs_updates_cache";
pub const UPDATE_PRODUCER_OFFSET: &str = "prop_defs_update_producer_offset";
pub const GROUP_TYPE_CACHE: &str = "prop_defs_group_type_cache";
pub const RECV_DEQUEUED: &str = "prop_defs_recv_dequeued";
pub const COMPACTED_UPDATES: &str = "prop_defs_compaction_dropped_updates";
-pub const CACHE_WARMING_STATE: &str = "prop_defs_cache_state";
pub const UPDATE_TRANSACTION_TIME: &str = "prop_defs_update_transaction_time_ms";
pub const GROUP_TYPE_RESOLVE_TIME: &str = "prop_defs_group_type_resolve_time_ms";
pub const UPDATES_SKIPPED: &str = "prop_defs_skipped_updates";
@@ -46,8 +46,6 @@ pub const V2_EVENT_DEFS_BATCH_ATTEMPT: &str = "propdefs_v2_eventdefs_batch_attem
pub const V2_EVENT_DEFS_BATCH_ROWS_AFFECTED: &str = "propdefs_v2_eventdefs_batch_rows";
pub const V2_EVENT_DEFS_BATCH_CACHE_TIME: &str = "propdefs_v2_eventdefs_batch_cache_time_ms";
pub const V2_EVENT_DEFS_CACHE_REMOVED: &str = "propdefs_v2_eventdefs_cache_removed";
-pub const V2_EVENT_DEFS_CACHE_HIT: &str = "propdefs_v2_eventdefs_cache_hit";
-pub const V2_EVENT_DEFS_CACHE_MISS: &str = "propdefs_v2_eventdefs_cache_miss";
pub const V2_EVENT_DEFS_BATCH_SIZE: &str = "propdefs_v2_eventdefs_batch_size";
pub const V2_EVENT_PROPS_BATCH_WRITE_TIME: &str = "propdefs_v2_eventprops_batch_ms";
@@ -55,8 +53,6 @@ pub const V2_EVENT_PROPS_BATCH_ATTEMPT: &str = "propdefs_v2_eventprops_batch_att
pub const V2_EVENT_PROPS_BATCH_ROWS_AFFECTED: &str = "propdefs_v2_eventprops_batch_rows";
pub const V2_EVENT_PROPS_BATCH_CACHE_TIME: &str = "propdefs_v2_eventprops_batch_cache_time_ms";
pub const V2_EVENT_PROPS_CACHE_REMOVED: &str = "propdefs_v2_eventprops_cache_removed";
-pub const V2_EVENT_PROPS_CACHE_HIT: &str = "propdefs_v2_eventprops_cache_hit";
-pub const V2_EVENT_PROPS_CACHE_MISS: &str = "propdefs_v2_eventprops_cache_miss";
pub const V2_EVENT_PROPS_BATCH_SIZE: &str = "propdefs_v2_eventprops_batch_size";
pub const V2_PROP_DEFS_BATCH_WRITE_TIME: &str = "propdefs_v2_propdefs_batch_ms";
@@ -64,6 +60,4 @@ pub const V2_PROP_DEFS_BATCH_ATTEMPT: &str = "propdefs_v2_propdefs_batch_attempt
pub const V2_PROP_DEFS_BATCH_ROWS_AFFECTED: &str = "propdefs_v2_propdefs_batch_rows";
pub const V2_PROP_DEFS_BATCH_CACHE_TIME: &str = "propdefs_v2_propdefs_batch_cache_time_ms";
pub const V2_PROP_DEFS_CACHE_REMOVED: &str = "propdefs_v2_propdefs_cache_removed";
-pub const V2_PROP_DEFS_CACHE_HIT: &str = "propdefs_v2_propdefs_cache_hit";
-pub const V2_PROP_DEFS_CACHE_MISS: &str = "propdefs_v2_propdefs_cache_miss";
pub const V2_PROP_DEFS_BATCH_SIZE: &str = "propdefs_v2_propdefs_batch_size";
diff --git a/rust/property-defs-rs/src/update_cache.rs b/rust/property-defs-rs/src/update_cache.rs
index f08f53a31bfc..98521ee3e39a 100644
--- a/rust/property-defs-rs/src/update_cache.rs
+++ b/rust/property-defs-rs/src/update_cache.rs
@@ -1,10 +1,44 @@
-use crate::{metrics_consts::UPDATES_CACHE, types::Update};
-use quick_cache::sync;
+use crate::{
+ metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, UPDATES_CACHE},
+ types::Update,
+};
+use quick_cache::{sync, DefaultHashBuilder, Lifecycle, UnitWeighter};
+
+// Per-subcache eviction observer. quick_cache's built-in `stats` feature
+// only tracks hits/misses on `get`/`get_key_value` paths (not `contains_key`/
+// `insert`, which is what we use), so all cache hit/miss/eviction signal in
+// this service comes from explicit metrics emitted here and in `contains_key`.
+#[derive(Clone)]
+struct EvictingLifecycle {
+ cache_label: &'static str,
+}
+
+impl Lifecycle<Update, ()> for EvictingLifecycle {
+ type RequestState = ();
+
+ fn begin_request(&self) -> Self::RequestState {}
+
+ fn on_evict(&self, _state: &mut Self::RequestState, _key: Update, _val: ()) {
+ metrics::counter!(CACHE_EVICTIONS, &[("cache", self.cache_label)]).increment(1);
+ }
+}
+
+type SubCache = sync::Cache<Update, (), UnitWeighter, DefaultHashBuilder, EvictingLifecycle>;
+
+fn build_subcache(capacity: usize, label: &'static str) -> SubCache {
+ sync::Cache::with(
+ capacity,
+ capacity as u64,
+ UnitWeighter,
+ DefaultHashBuilder::default(),
+ EvictingLifecycle { cache_label: label },
+ )
+}
pub struct Cache {
- eventdefs: sync::Cache<Update, ()>,
- eventprops: sync::Cache<Update, ()>,
- propdefs: sync::Cache<Update, ()>,
+ eventdefs: SubCache,
+ eventprops: SubCache,
+ propdefs: SubCache,
}
// TODO: next iter, try using unsync::Cache(s) here and manage sync access to each
@@ -19,9 +53,9 @@ impl Cache {
propdefs_capacity: usize,
) -> Self {
Self {
- eventdefs: sync::Cache::new(eventdefs_capacity),
- eventprops: sync::Cache::new(eventprops_capacity),
- propdefs: sync::Cache::new(propdefs_capacity),
+ eventdefs: build_subcache(eventdefs_capacity, "eventdefs"),
+ eventprops: build_subcache(eventprops_capacity, "eventprops"),
+ propdefs: build_subcache(propdefs_capacity, "propdefs"),
}
}
@@ -41,40 +75,22 @@ impl Cache {
self.propdefs.len()
}
- pub fn eventdefs_hits(&self) -> u64 {
- self.eventdefs.hits()
- }
-
- pub fn eventdefs_misses(&self) -> u64 {
- self.eventdefs.misses()
- }
-
- pub fn eventprops_hits(&self) -> u64 {
- self.eventprops.hits()
- }
-
- pub fn eventprops_misses(&self) -> u64 {
- self.eventprops.misses()
- }
-
- pub fn propdefs_hits(&self) -> u64 {
- self.propdefs.hits()
- }
-
- pub fn propdefs_misses(&self) -> u64 {
- self.propdefs.misses()
- }
-
pub fn is_empty(&self) -> bool {
self.propdefs.is_empty() && self.eventdefs.is_empty() && self.eventprops.is_empty()
}
pub fn contains_key(&self, key: &Update) -> bool {
- match key {
- Update::Event(_) => self.eventdefs.contains_key(key),
- Update::EventProperty(_) => self.eventprops.contains_key(key),
- Update::Property(_) => self.propdefs.contains_key(key),
+ let (found, label) = match key {
+ Update::Event(_) => (self.eventdefs.contains_key(key), "eventdefs"),
+ Update::EventProperty(_) => (self.eventprops.contains_key(key), "eventprops"),
+ Update::Property(_) => (self.propdefs.contains_key(key), "propdefs"),
+ };
+ if found {
+ metrics::counter!(CACHE_HITS, &[("cache", label)]).increment(1);
+ } else {
+ metrics::counter!(CACHE_MISSES, &[("cache", label)]).increment(1);
}
+ found
}
pub fn insert(&self, key: Update) {
diff --git a/rust/property-defs-rs/tests/update_cache.rs b/rust/property-defs-rs/tests/update_cache.rs
index 3d518958b89d..a2847d5d2278 100644
--- a/rust/property-defs-rs/tests/update_cache.rs
+++ b/rust/property-defs-rs/tests/update_cache.rs
@@ -1,39 +1,74 @@
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
use chrono::Utc;
+use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};
use property_defs_rs::{
batch_ingestion::PropertyDefinitionsBatch,
+ metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES},
types::{
EventDefinition, EventProperty, GroupType, PropertyDefinition, PropertyParentType,
PropertyValueType, Update,
},
update_cache::Cache,
};
+use rstest::rstest;
+
+// One global recorder per test process. Multiple #[test]s run in parallel, share
+// the same recorder, and read counters via labeled lookups against the snapshot.
+fn snapshotter() -> &'static Snapshotter {
+ static SNAPSHOTTER: OnceLock<Snapshotter> = OnceLock::new();
+ SNAPSHOTTER.get_or_init(|| {
+ let recorder = DebuggingRecorder::new();
+ let s = recorder.snapshotter();
+ // ignore install errors: a recorder may already be globally set if
+ // multiple test binaries share state in the future
+ drop(recorder.install());
+ s
+ })
+}
-#[test]
-fn test_cache_insertions() {
- let cache = Cache::new(10, 10, 10);
+fn counter_value(metric: &'static str, cache_label: &'static str) -> u64 {
+ snapshotter()
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .find(|(key, _, _, _)| {
+ key.key().name() == metric
+ && key
+ .key()
+ .labels()
+ .any(|l| l.key() == "cache" && l.value() == cache_label)
+ })
+ .and_then(|(_, _, _, value)| match value {
+ DebugValue::Counter(v) => Some(v),
+ _ => None,
+ })
+ .unwrap_or(0)
+}
- let evt_def = Update::Event(EventDefinition {
- name: String::from("foobar"),
+fn make_event_def(name: &str) -> Update {
+ Update::Event(EventDefinition {
+ name: name.into(),
team_id: 1,
project_id: 1,
last_seen_at: Utc::now(),
- });
- cache.insert(evt_def.clone());
+ })
+}
- let evt_prop = Update::EventProperty(EventProperty {
- event: String::from("foo"),
- property: String::from("bar"),
+fn make_event_prop(event: &str, property: &str) -> Update {
+ Update::EventProperty(EventProperty {
+ event: event.into(),
+ property: property.into(),
team_id: 1,
project_id: 1,
- });
- cache.insert(evt_prop.clone());
+ })
+}
- let prop_def = Update::Property(PropertyDefinition {
+fn make_prop_def(name: &str) -> Update {
+ Update::Property(PropertyDefinition {
team_id: 1,
project_id: 1,
- name: String::from("baz_count"),
+ name: name.into(),
is_numerical: true,
property_type: Some(PropertyValueType::Numeric),
event_type: PropertyParentType::Event,
@@ -41,7 +76,20 @@ fn test_cache_insertions() {
property_type_format: None,
query_usage_30_day: None,
volume_30_day: None,
- });
+ })
+}
+
+#[test]
+fn test_cache_insertions() {
+ let cache = Cache::new(10, 10, 10);
+
+ let evt_def = make_event_def("foobar");
+ cache.insert(evt_def.clone());
+
+ let evt_prop = make_event_prop("foo", "bar");
+ cache.insert(evt_prop.clone());
+
+ let prop_def = make_prop_def("baz_count");
cache.insert(prop_def.clone());
assert!(cache.contains_key(&evt_def));
@@ -53,34 +101,13 @@ fn test_cache_insertions() {
fn test_cache_removals() {
let cache = Cache::new(10, 10, 10);
- let evt_def = Update::Event(EventDefinition {
- name: String::from("foobar"),
- team_id: 1,
- project_id: 1,
- last_seen_at: Utc::now(),
- });
+ let evt_def = make_event_def("foobar");
cache.insert(evt_def.clone());
- let evt_prop = Update::EventProperty(EventProperty {
- event: String::from("foo"),
- property: String::from("bar"),
- team_id: 1,
- project_id: 1,
- });
+ let evt_prop = make_event_prop("foo", "bar");
cache.insert(evt_prop.clone());
- let prop_def = Update::Property(PropertyDefinition {
- team_id: 1,
- project_id: 1,
- name: String::from("baz_count"),
- is_numerical: true,
- property_type: Some(PropertyValueType::Numeric),
- event_type: PropertyParentType::Event,
- group_type_index: None,
- property_type_format: None,
- query_usage_30_day: None,
- volume_30_day: None,
- });
+ let prop_def = make_prop_def("baz_count");
cache.insert(prop_def.clone());
// remove the entries and check
@@ -159,3 +186,62 @@ fn test_uncache_batch_evicts_unresolved_entry_for_group_prop() {
"entry should be uncached after batch failure"
);
}
+
+// Drives one miss-then-hit through `Cache::contains_key` for a given subcache,
+// asserting that the corresponding `prop_defs_cache_misses{cache=label}` and
+// `prop_defs_cache_hits{cache=label}` counters advance. We compare deltas
+// (post - pre) instead of absolute values because the recorder is shared
+// across all tests in the binary and parallel tests touch the same labels.
+fn assert_miss_then_hit(label: &'static str, update: Update) {
+ let cache = Cache::new(64, 64, 64);
+
+ let pre_miss = counter_value(CACHE_MISSES, label);
+ let pre_hit = counter_value(CACHE_HITS, label);
+
+ assert!(!cache.contains_key(&update), "fresh cache should miss");
+ cache.insert(update.clone());
+ assert!(cache.contains_key(&update), "cached entry should hit");
+
+ let post_miss = counter_value(CACHE_MISSES, label);
+ let post_hit = counter_value(CACHE_HITS, label);
+
+ assert!(
+ post_miss > pre_miss,
+ "{label}: misses did not advance ({pre_miss} -> {post_miss})",
+ );
+ assert!(
+ post_hit > pre_hit,
+ "{label}: hits did not advance ({pre_hit} -> {post_hit})",
+ );
+}
+
+#[rstest]
+#[case::eventdefs("eventdefs", make_event_def("hit_miss_eventdefs"))]
+#[case::eventprops(
+ "eventprops",
+ make_event_prop("hit_miss_eventprops_evt", "hit_miss_eventprops_prop")
+)]
+#[case::propdefs("propdefs", make_prop_def("hit_miss_propdefs"))]
+fn test_contains_key_emits_hit_miss_metrics(#[case] label: &'static str, #[case] update: Update) {
+ assert_miss_then_hit(label, update);
+}
+
+// quick_cache enforces a minimum of 32 items per shard (`sync.rs` ~134:
+// `while shard_items_cap < 32 && num_shards > 1 { num_shards /= 2; ... }`),
+// so even with `Cache::new(2, 2, 2)` we get a single 32-slot shard per
+// subcache. We need >32 distinct inserts to provoke at least one eviction.
+#[test]
+fn test_overflowing_subcache_emits_eviction_metric() {
+ let cache = Cache::new(2, 2, 2);
+
+ let pre = counter_value(CACHE_EVICTIONS, "eventdefs");
+ for i in 0..200 {
+ cache.insert(make_event_def(&format!("evict_test_evt_{i}")));
+ }
+ let post = counter_value(CACHE_EVICTIONS, "eventdefs");
+
+ assert!(
+ post > pre,
+ "eventdefs evictions did not advance ({pre} -> {post}) after overflow",
+ );
+}