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.

fix(propdefs): count cache replacements apart from evictions (#95492)

Eli Reisman60f23c723fb8
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index 0cad2f8d0b7a..a09a44cdf994 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -14,7 +14,14 @@ pub const CACHE_FILL_RATIO: &str = "prop_defs_cache_fill_ratio";
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";
+// quick_cache fires its eviction hook for capacity evictions and for in-place
+// replacements of a resident key alike, so this counter is the sum of both.
+// CACHE_REPLACEMENTS counts the replacements on their own; capacity evictions
+// are EVICTIONS minus REPLACEMENTS.
pub const CACHE_EVICTIONS: &str = "prop_defs_cache_evictions";
+// Inserts that moved a cached row identity forward in place: a newer eventdef
+// last_seen bucket, or a property type refreshed or upgraded from None.
+pub const CACHE_REPLACEMENTS: &str = "prop_defs_cache_replacements";
pub const UPDATES_CACHE: &str = "prop_defs_updates_cache";
// Kafka offset stores that failed. The producer loop continues past a failure, so a later
// successful store on the same partition supersedes it and nothing is redelivered. Redelivery
diff --git a/rust/property-defs-rs/src/read_filter.rs b/rust/property-defs-rs/src/read_filter.rs
index 66d790e6287e..51e271decf6b 100644
--- a/rust/property-defs-rs/src/read_filter.rs
+++ b/rust/property-defs-rs/src/read_filter.rs
@@ -148,7 +148,10 @@ pub async fn filter_property_definitions(
}
keep[idx] = false;
// Refresh the dedup cache with the stored type, so future typed sightings
- // of this row hit in memory instead of re-probing the reader.
+ // of this row hit in memory instead of re-probing the reader. The cache
+ // decides whether this changes anything: the entry may have been evicted
+ // or removed while the batch waited, so the batch row is not proof of
+ // the cached state.
if let Some(stored) = stored_type.and_then(|s| PropertyValueType::from_str(&s).ok()) {
if let Update::Property(pd) = &batch.cached[idx] {
let mut refreshed = pd.clone();
diff --git a/rust/property-defs-rs/src/update_cache.rs b/rust/property-defs-rs/src/update_cache.rs
index ea02e4e7de42..7b7a83f190f0 100644
--- a/rust/property-defs-rs/src/update_cache.rs
+++ b/rust/property-defs-rs/src/update_cache.rs
@@ -5,7 +5,9 @@ use metrics::Counter;
use quick_cache::{sync, DefaultHashBuilder, Equivalent, Lifecycle, UnitWeighter};
use crate::{
- metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, UPDATES_CACHE},
+ metrics_consts::{
+ CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, CACHE_REPLACEMENTS, UPDATES_CACHE,
+ },
types::{EventProperty, GroupType, PropertyParentType, PropertyValueType, Update},
};
@@ -13,6 +15,11 @@ use crate::{
// enabled, so all cache hit/miss/eviction signal in this service comes from
// explicit metrics emitted here and in `contains_key`.
//
+// quick_cache also calls `on_evict` with the old entry when `insert` finds the
+// key already resident, so this counter includes the in-place replacements
+// `Cache::insert` makes on purpose. Those are counted separately as
+// CACHE_REPLACEMENTS; capacity evictions are the difference.
+//
// Counter handles are resolved once at construction and reused: these paths run
// per update (and `on_evict` runs under the shard write lock), so a registry
// lookup per increment is measurable CPU. The metrics recorder must be installed
@@ -38,6 +45,47 @@ struct SubCacheEntry<K: Eq + Hash + Clone, V: Clone> {
cache: SubCache<K, V>,
hits: Counter,
misses: Counter,
+ replacements: Counter,
+}
+
+impl<K: Eq + Hash + Clone, V: Clone> SubCacheEntry<K, V> {
+ // Writes exactly what a plain `insert` would, and reports whether the write
+ // replaced a resident entry. quick_cache `replace` with `soft: false` takes
+ // the same `insert_existing` path as `insert` on a resident key (same
+ // segment, same `referenced` bump, same `on_evict`), and only differs by
+ // failing when the key is not resident. That failure is how a concurrent
+ // remove between the caller's peek and this write stays uncounted: the
+ // value then goes in through `insert`, as it would have anyway.
+ fn write(&self, key: K, value: V, peeked_resident: bool) -> InsertOutcome {
+ if !peeked_resident {
+ self.cache.insert(key, value);
+ return InsertOutcome::Inserted;
+ }
+ match self.cache.replace(key, value, false) {
+ Ok(()) => {
+ self.replacements.increment(1);
+ InsertOutcome::Replaced
+ }
+ Err((key, value)) => {
+ self.cache.insert(key, value);
+ InsertOutcome::Inserted
+ }
+ }
+ }
+}
+
+/// What `Cache::insert` did with an update. Only `Unchanged` skips the write,
+/// and it does so on exactly the guards that predate this bookkeeping.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum InsertOutcome {
+ /// The row identity was not resident and is now.
+ Inserted,
+ /// The identity was resident and quick_cache replaced the entry in place,
+ /// whether or not the value differs.
+ Replaced,
+ /// A guard rejected the update before any write: an older or equal eventdef
+ /// bucket, or an untyped property over a typed one.
+ Unchanged,
}
fn build_subcache<K: Eq + Hash + Clone, V: Clone>(
@@ -57,6 +105,7 @@ fn build_subcache<K: Eq + Hash + Clone, V: Clone>(
cache,
hits: metrics::counter!(CACHE_HITS, &[("cache", label)]),
misses: metrics::counter!(CACHE_MISSES, &[("cache", label)]),
+ replacements: metrics::counter!(CACHE_REPLACEMENTS, &[("cache", label)]),
}
}
@@ -255,7 +304,18 @@ impl Cache {
// cached fresher state; replacing that state would make the next sighting
// miss and re-issue a write Postgres treats as a no-op. The peek-then-insert
// pairs below race too, but losing that race costs one redundant upsert.
- pub fn insert(&self, key: Update) {
+ //
+ // Every write that reaches quick_cache here is the same write with or
+ // without the outcome bookkeeping: an equal value re-inserted over a
+ // resident key still goes through, so the entry keeps the `referenced`
+ // credit quick_cache grants on that path. The peek only decides whether
+ // the write is issued as a `replace` (counted) or an `insert`.
+ //
+ // The peek and the write are separate lock acquisitions. A concurrent
+ // producer can insert the same new key in between, which makes the second
+ // write an uncounted replacement. That race is the one already measured by
+ // DUPLICATES_IN_BATCH and is far too rare to move the replacement counter.
+ pub fn insert(&self, key: Update) -> InsertOutcome {
match key {
Update::Event(def) => {
let lookup = EventDefKeyRef {
@@ -263,22 +323,22 @@ impl Cache {
project_id: def.project_id,
name: &def.name,
};
- if self
- .eventdefs
- .cache
- .peek(&lookup)
- .is_some_and(|bucket| bucket >= def.last_seen_at)
- {
- return;
+ let cached = self.eventdefs.cache.peek(&lookup);
+ if cached.is_some_and(|bucket| bucket >= def.last_seen_at) {
+ return InsertOutcome::Unchanged;
}
let key = EventDefKey {
team_id: def.team_id,
project_id: def.project_id,
name: def.name,
};
- self.eventdefs.cache.insert(key, def.last_seen_at);
+ self.eventdefs
+ .write(key, def.last_seen_at, cached.is_some())
+ }
+ Update::EventProperty(ep) => {
+ let resident = self.eventprops.cache.peek(&ep).is_some();
+ self.eventprops.write(ep, (), resident)
}
- Update::EventProperty(ep) => self.eventprops.cache.insert(ep, ()),
Update::Property(def) => {
let lookup = PropDefKeyRef {
team_id: def.team_id,
@@ -287,14 +347,9 @@ impl Cache {
event_type: def.event_type,
group_name: def.group_type_index.as_ref().map(group_name),
};
- if def.property_type.is_none()
- && self
- .propdefs
- .cache
- .peek(&lookup)
- .is_some_and(|cached| cached.is_some())
- {
- return;
+ let cached = self.propdefs.cache.peek(&lookup);
+ if def.property_type.is_none() && matches!(cached, Some(Some(_))) {
+ return InsertOutcome::Unchanged;
}
let key = PropDefKey {
team_id: def.team_id,
@@ -305,7 +360,8 @@ impl Cache {
GroupType::Unresolved(name) | GroupType::Resolved(name, _) => name,
}),
};
- self.propdefs.cache.insert(key, def.property_type);
+ self.propdefs
+ .write(key, def.property_type, cached.is_some())
}
}
}
diff --git a/rust/property-defs-rs/tests/update_cache.rs b/rust/property-defs-rs/tests/update_cache.rs
index 57151461acca..13acb68c998e 100644
--- a/rust/property-defs-rs/tests/update_cache.rs
+++ b/rust/property-defs-rs/tests/update_cache.rs
@@ -4,12 +4,12 @@ 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},
+ metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, CACHE_REPLACEMENTS},
types::{
EventDefinition, EventProperty, GroupType, PropertyDefinition, PropertyParentType,
PropertyValueType, Update,
},
- update_cache::Cache,
+ update_cache::{Cache, InsertOutcome},
};
use rstest::rstest;
@@ -245,7 +245,7 @@ fn test_propdef_type_variants_collapse_to_one_entry() {
let typed = make_prop_def_typed("plan", Some(PropertyValueType::String));
let retyped = make_prop_def_typed("plan", Some(PropertyValueType::DateTime));
- cache.insert(untyped.clone());
+ assert_eq!(cache.insert(untyped.clone()), InsertOutcome::Inserted);
assert!(
cache.contains_key(&untyped),
"untyped resend cannot change the row"
@@ -255,7 +255,7 @@ fn test_propdef_type_variants_collapse_to_one_entry() {
"typed sighting must upgrade the untyped row"
);
- cache.insert(typed.clone());
+ assert_eq!(cache.insert(typed.clone()), InsertOutcome::Replaced);
assert_eq!(cache.propdefs_len(), 1, "variants must share one entry");
assert!(cache.contains_key(&typed));
assert!(
@@ -267,11 +267,69 @@ fn test_propdef_type_variants_collapse_to_one_entry() {
"the upsert never overwrites a non-null type"
);
- cache.insert(untyped);
- assert!(
- cache.contains_key(&typed),
+ assert_eq!(
+ cache.insert(untyped),
+ InsertOutcome::Unchanged,
"a racing untyped insert cannot downgrade the cached type"
);
+ assert!(cache.contains_key(&typed));
+
+ // Only the read filter inserts a differing non-null type, and it carries
+ // the type Postgres stored, so the cache follows it.
+ assert_eq!(cache.insert(retyped.clone()), InsertOutcome::Replaced);
+ assert_eq!(cache.propdefs_len(), 1);
+}
+
+// Re-inserting an identical update writes exactly what it did before the
+// outcome bookkeeping existed: the eventdef bucket guard still rejects it, and
+// the other two subcaches still push it through quick_cache, which counts as a
+// replacement so the dashboard can subtract it from the eviction counter.
+#[rstest]
+#[case::eventdefs(make_event_def("reinsert_eventdefs"), InsertOutcome::Unchanged)]
+#[case::eventprops(
+ make_event_prop("reinsert_eventprops_evt", "reinsert_eventprops_prop"),
+ InsertOutcome::Replaced
+)]
+#[case::propdefs(make_prop_def("reinsert_propdefs"), InsertOutcome::Replaced)]
+fn test_reinsert_of_identical_update(#[case] update: Update, #[case] expected: InsertOutcome) {
+ let cache = Cache::new(10, 10, 10);
+
+ assert_eq!(cache.insert(update.clone()), InsertOutcome::Inserted);
+ assert_eq!(cache.insert(update.clone()), expected);
+ assert!(cache.contains_key(&update));
+ assert_eq!(
+ cache.eventdefs_len() + cache.eventprops_len() + cache.propdefs_len(),
+ 1
+ );
+}
+
+// The eviction counter includes in-place replacements, because quick_cache
+// fires its eviction hook for them. The replacement counter is what lets a
+// dashboard subtract them back out.
+#[test]
+fn test_replacement_advances_replacement_and_eviction_metrics() {
+ // Recorder install must precede Cache::new; see assert_miss_then_hit.
+ let pre_replaced = counter_value(CACHE_REPLACEMENTS, "eventdefs");
+ let pre_evicted = counter_value(CACHE_EVICTIONS, "eventdefs");
+
+ let cache = Cache::new(64, 64, 64);
+ let t1 = Utc::now();
+ cache.insert(make_event_def_at("replace_metric_evt", t1));
+ cache.insert(make_event_def_at(
+ "replace_metric_evt",
+ t1 + chrono::Duration::hours(2),
+ ));
+
+ let post_replaced = counter_value(CACHE_REPLACEMENTS, "eventdefs");
+ let post_evicted = counter_value(CACHE_EVICTIONS, "eventdefs");
+ assert!(
+ post_replaced > pre_replaced,
+ "replacements did not advance ({pre_replaced} -> {post_replaced})",
+ );
+ assert!(
+ post_evicted > pre_evicted,
+ "evictions did not advance on replace ({pre_evicted} -> {post_evicted})",
+ );
}
fn make_event_def_at(name: &str, last_seen_at: chrono::DateTime<Utc>) -> Update {
@@ -296,14 +354,14 @@ fn test_eventdef_bucket_rollover_replaces_entry() {
let bucket1 = make_event_def_at("checkout", t1);
let bucket2 = make_event_def_at("checkout", t2);
- cache.insert(bucket1.clone());
+ assert_eq!(cache.insert(bucket1.clone()), InsertOutcome::Inserted);
assert!(cache.contains_key(&bucket1));
assert!(
!cache.contains_key(&bucket2),
"a new bucket must re-issue the write"
);
- cache.insert(bucket2.clone());
+ assert_eq!(cache.insert(bucket2.clone()), InsertOutcome::Replaced);
assert_eq!(
cache.eventdefs_len(),
1,
@@ -315,11 +373,12 @@ fn test_eventdef_bucket_rollover_replaces_entry() {
"an in-flight older bucket is covered by the newer cached one"
);
- cache.insert(bucket1);
- assert!(
- cache.contains_key(&bucket2),
+ assert_eq!(
+ cache.insert(bucket1),
+ InsertOutcome::Unchanged,
"a racing older insert cannot replace the newer bucket"
);
+ assert!(cache.contains_key(&bucket2));
}
// quick_cache enforces a minimum of 32 items per shard (`sync.rs` ~134: