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): key the dedup cache on row identity, not the full update (#94453)

José Sequeira900eb0a3ebb0
diff --git a/rust/property-defs-rs/src/types.rs b/rust/property-defs-rs/src/types.rs
index 4a4fb8f2338d..ec0745f56036 100644
--- a/rust/property-defs-rs/src/types.rs
+++ b/rust/property-defs-rs/src/types.rs
@@ -145,10 +145,9 @@ impl GroupType {
}
}
- /// Returns the Unresolved form of this group type. The shared dedup cache
- /// always stores entries as Unresolved (inserted by the producer before
- /// resolution), so cache removal after a failed batch write must use this
- /// form to match the original key.
+ /// Returns the Unresolved form of this group type. The dedup cache keys
+ /// group properties by name, so cache operations accept either form; this
+ /// exists for call sites that want the canonical producer-side shape.
pub fn as_unresolved(&self) -> Self {
match self {
GroupType::Unresolved(_) => self.clone(),
diff --git a/rust/property-defs-rs/src/update_cache.rs b/rust/property-defs-rs/src/update_cache.rs
index a47c767486e2..f8de12607184 100644
--- a/rust/property-defs-rs/src/update_cache.rs
+++ b/rust/property-defs-rs/src/update_cache.rs
@@ -1,9 +1,13 @@
+use std::hash::{Hash, Hasher};
+
+use chrono::{DateTime, Utc};
+use metrics::Counter;
+use quick_cache::{sync, DefaultHashBuilder, Equivalent, Lifecycle, UnitWeighter};
+
use crate::{
metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, UPDATES_CACHE},
- types::Update,
+ types::{EventProperty, GroupType, PropertyParentType, PropertyValueType, Update},
};
-use metrics::Counter;
-use quick_cache::{sync, DefaultHashBuilder, Lifecycle, UnitWeighter};
// Per-subcache eviction observer. The `stats` feature of quick_cache is not
// enabled, so all cache hit/miss/eviction signal in this service comes from
@@ -18,25 +22,28 @@ struct EvictingLifecycle {
evictions: Counter,
}
-impl Lifecycle<Update, ()> for EvictingLifecycle {
+impl<K, V> Lifecycle<K, V> for EvictingLifecycle {
type RequestState = ();
fn begin_request(&self) -> Self::RequestState {}
- fn on_evict(&self, _state: &mut Self::RequestState, _key: Update, _val: ()) {
+ fn on_evict(&self, _state: &mut Self::RequestState, _key: K, _val: V) {
self.evictions.increment(1);
}
}
-type SubCache = sync::Cache<Update, (), UnitWeighter, DefaultHashBuilder, EvictingLifecycle>;
+type SubCache<K, V> = sync::Cache<K, V, UnitWeighter, DefaultHashBuilder, EvictingLifecycle>;
-struct SubCacheEntry {
- cache: SubCache,
+struct SubCacheEntry<K: Eq + Hash + Clone, V: Clone> {
+ cache: SubCache<K, V>,
hits: Counter,
misses: Counter,
}
-fn build_subcache(capacity: usize, label: &'static str) -> SubCacheEntry {
+fn build_subcache<K: Eq + Hash + Clone, V: Clone>(
+ capacity: usize,
+ label: &'static str,
+) -> SubCacheEntry<K, V> {
let cache = sync::Cache::with(
capacity,
capacity as u64,
@@ -53,10 +60,99 @@ fn build_subcache(capacity: usize, label: &'static str) -> SubCacheEntry {
}
}
+// Cache keys carry only the row identity Postgres enforces uniqueness on, and
+// everything else about an update lives in the cache VALUE. Keying on the full
+// update struct made every field variation a separate entry: a property whose
+// detected type flips (null values, a stray "true", a date-looking string)
+// occupied one slot per variant, and every event definition abandoned a dead
+// entry each time its floored last_seen bucket rolled over.
+
+/// Identity of a `posthog_eventdefinition` row. The floored `last_seen_at`
+/// bucket is the cache value, so a rollover replaces it in place.
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+struct EventDefKey {
+ team_id: i32,
+ project_id: i64,
+ name: String,
+}
+
+// Borrowed lookup forms. `contains_key` runs per update, so building an owned
+// key (two String allocations) per lookup is measurable; these hash and compare
+// identically to their owned counterparts. Field order must match the owned
+// struct declaration, because the derived Hash hashes fields in that order.
+struct EventDefKeyRef<'a> {
+ team_id: i32,
+ project_id: i64,
+ name: &'a str,
+}
+
+impl Hash for EventDefKeyRef<'_> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.team_id.hash(state);
+ self.project_id.hash(state);
+ self.name.hash(state);
+ }
+}
+
+impl Equivalent<EventDefKey> for EventDefKeyRef<'_> {
+ fn equivalent(&self, key: &EventDefKey) -> bool {
+ self.team_id == key.team_id && self.project_id == key.project_id && self.name == key.name
+ }
+}
+
+/// Identity of a `posthog_propertydefinition` row: the ON CONFLICT key of the
+/// upsert. Group types are keyed by name so the Unresolved form the producer
+/// caches and the Resolved form the writer works with address the same entry.
+/// The detected property type is the cache value: `None` upgrades to `Some`
+/// with one write (mirroring the guarded DO UPDATE), any other flip is a no-op
+/// for Postgres and stays a cache hit.
+#[derive(Clone, Debug, Hash, Eq, PartialEq)]
+struct PropDefKey {
+ team_id: i32,
+ project_id: i64,
+ name: String,
+ event_type: PropertyParentType,
+ group_name: Option<String>,
+}
+
+struct PropDefKeyRef<'a> {
+ team_id: i32,
+ project_id: i64,
+ name: &'a str,
+ event_type: PropertyParentType,
+ group_name: Option<&'a str>,
+}
+
+impl Hash for PropDefKeyRef<'_> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.team_id.hash(state);
+ self.project_id.hash(state);
+ self.name.hash(state);
+ self.event_type.hash(state);
+ self.group_name.hash(state);
+ }
+}
+
+impl Equivalent<PropDefKey> for PropDefKeyRef<'_> {
+ fn equivalent(&self, key: &PropDefKey) -> bool {
+ self.team_id == key.team_id
+ && self.project_id == key.project_id
+ && self.name == key.name
+ && self.event_type == key.event_type
+ && self.group_name == key.group_name.as_deref()
+ }
+}
+
+fn group_name(group: &GroupType) -> &str {
+ match group {
+ GroupType::Unresolved(name) | GroupType::Resolved(name, _) => name,
+ }
+}
+
pub struct Cache {
- eventdefs: SubCacheEntry,
- eventprops: SubCacheEntry,
- propdefs: SubCacheEntry,
+ eventdefs: SubCacheEntry<EventDefKey, DateTime<Utc>>,
+ eventprops: SubCacheEntry<EventProperty, ()>,
+ propdefs: SubCacheEntry<PropDefKey, Option<PropertyValueType>>,
removed: Counter,
not_cached: Counter,
}
@@ -81,14 +177,6 @@ impl Cache {
}
}
- fn entry_for(&self, key: &Update) -> &SubCacheEntry {
- match key {
- Update::Event(_) => &self.eventdefs,
- Update::EventProperty(_) => &self.eventprops,
- Update::Property(_) => &self.propdefs,
- }
- }
-
pub fn eventdefs_len(&self) -> usize {
self.eventdefs.cache.len()
}
@@ -101,31 +189,152 @@ impl Cache {
self.propdefs.cache.len()
}
+ /// True when the cached state already covers this update, meaning the write
+ /// it stands for would change nothing in Postgres.
+ ///
+ /// Lookups go through quick_cache `get`, which marks the entry referenced;
+ /// S3-FIFO eviction uses that to keep the working set resident. The
+ /// `contains_key` of quick_cache skips that marking, so every entry looks
+ /// cold at eviction time and the cache degrades to FIFO: live keys cycle
+ /// out and each cycle costs a useless definition upsert against Postgres.
pub fn contains_key(&self, key: &Update) -> bool {
- let entry = self.entry_for(key);
- // `get` marks the entry referenced, which quick_cache's S3-FIFO eviction
- // uses to keep the working set resident. The `contains_key` of quick_cache
- // skips that marking, so every entry looks cold at eviction time and the
- // cache degrades to FIFO: live keys cycle out and each cycle costs a
- // useless definition upsert against Postgres.
- let found = entry.cache.get(key).is_some();
- if found {
- entry.hits.increment(1);
+ let (covered, hits, misses) = match key {
+ Update::Event(def) => {
+ let lookup = EventDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ };
+ // Only a bucket newer than the cached one demands a re-issue.
+ // Producers interleave, so an update from the previous bucket
+ // can be checked after a rollover was cached; the newer write
+ // already refreshed the row, so the older update stays covered.
+ // The get refreshes the entry's recency either way.
+ let covered = self
+ .eventdefs
+ .cache
+ .get(&lookup)
+ .is_some_and(|bucket| bucket >= def.last_seen_at);
+ (covered, &self.eventdefs.hits, &self.eventdefs.misses)
+ }
+ Update::EventProperty(ep) => (
+ self.eventprops.cache.get(ep).is_some(),
+ &self.eventprops.hits,
+ &self.eventprops.misses,
+ ),
+ Update::Property(def) => {
+ let lookup = PropDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ event_type: def.event_type,
+ group_name: def.group_type_index.as_ref().map(group_name),
+ };
+ let covered = match self.propdefs.cache.get(&lookup) {
+ // An untyped cached row upgrades once when a typed sighting
+ // arrives; every other combination cannot change the row.
+ Some(cached) => !(cached.is_none() && def.property_type.is_some()),
+ None => false,
+ };
+ (covered, &self.propdefs.hits, &self.propdefs.misses)
+ }
+ };
+ if covered {
+ hits.increment(1);
} else {
- entry.misses.increment(1);
+ misses.increment(1);
}
- found
+ covered
}
+ // Both valued subcaches only move forward: a newer last_seen bucket, or a
+ // None to Some type upgrade. Concurrent producers interleave their
+ // contains_key/insert pairs, so an insert can arrive after another producer
+ // cached fresher state; replacing that state would make the next sighting
+ // miss and re-issue a write Postgres treats as a no-op. The get-then-insert
+ // pairs below race too, but losing that race costs one redundant upsert.
pub fn insert(&self, key: Update) {
- self.entry_for(&key).cache.insert(key, ());
+ match key {
+ Update::Event(def) => {
+ let lookup = EventDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ };
+ if self
+ .eventdefs
+ .cache
+ .get(&lookup)
+ .is_some_and(|bucket| bucket >= def.last_seen_at)
+ {
+ return;
+ }
+ 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);
+ }
+ Update::EventProperty(ep) => self.eventprops.cache.insert(ep, ()),
+ Update::Property(def) => {
+ let lookup = PropDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ 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
+ .get(&lookup)
+ .is_some_and(|cached| cached.is_some())
+ {
+ return;
+ }
+ let key = PropDefKey {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: def.name,
+ event_type: def.event_type,
+ group_name: def.group_type_index.map(|g| match g {
+ GroupType::Unresolved(name) | GroupType::Resolved(name, _) => name,
+ }),
+ };
+ self.propdefs.cache.insert(key, def.property_type);
+ }
+ }
}
// we don't return the retrieved KV since propdefs doesn't require it
pub fn remove(&self, key: &Update) {
- let result = self.entry_for(key).cache.remove(key);
+ let removed = match key {
+ Update::Event(def) => self
+ .eventdefs
+ .cache
+ .remove(&EventDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ })
+ .is_some(),
+ Update::EventProperty(ep) => self.eventprops.cache.remove(ep).is_some(),
+ Update::Property(def) => self
+ .propdefs
+ .cache
+ .remove(&PropDefKeyRef {
+ team_id: def.team_id,
+ project_id: def.project_id,
+ name: &def.name,
+ event_type: def.event_type,
+ group_name: def.group_type_index.as_ref().map(group_name),
+ })
+ .is_some(),
+ };
- if result.is_some() {
+ if removed {
self.removed.increment(1);
} else {
self.not_cached.increment(1);
diff --git a/rust/property-defs-rs/tests/update_cache.rs b/rust/property-defs-rs/tests/update_cache.rs
index d9d86d14ba0a..593607befa30 100644
--- a/rust/property-defs-rs/tests/update_cache.rs
+++ b/rust/property-defs-rs/tests/update_cache.rs
@@ -129,21 +129,23 @@ fn make_group_prop_def(group_type_index: Option<GroupType>) -> Update {
})
}
+// Group properties are keyed by group name, so the Resolved form the writer
+// holds after group-type resolution addresses the same cache entry the
+// producer inserted in Unresolved form. A failed batch write can therefore
+// evict with either form and never strands a stale entry.
#[test]
-fn test_resolved_group_prop_cannot_remove_unresolved_cache_entry() {
+fn test_resolved_group_prop_removes_entry_cached_unresolved() {
let cache = Cache::new(10, 10, 10);
let unresolved = make_group_prop_def(Some(GroupType::Unresolved("company".into())));
cache.insert(unresolved.clone());
assert!(cache.contains_key(&unresolved));
- // Simulates what uncache_batch used to do: try to remove the resolved
- // form. This fails because derived Eq distinguishes the variants.
let resolved = make_group_prop_def(Some(GroupType::Resolved("company".into(), 2)));
cache.remove(&resolved);
assert!(
- cache.contains_key(&unresolved),
- "stale entry should still be cached"
+ !cache.contains_key(&unresolved),
+ "either resolution form should evict the entry"
);
}
@@ -220,6 +222,106 @@ fn test_contains_key_emits_hit_miss_metrics(#[case] label: &'static str, #[case]
assert_miss_then_hit(label, update);
}
+fn make_prop_def_typed(name: &str, property_type: Option<PropertyValueType>) -> Update {
+ Update::Property(PropertyDefinition {
+ team_id: 1,
+ project_id: 1,
+ name: name.into(),
+ is_numerical: matches!(property_type, Some(PropertyValueType::Numeric)),
+ property_type,
+ event_type: PropertyParentType::Event,
+ group_type_index: None,
+ })
+}
+
+// One property identity occupies one cache slot no matter how its type is
+// detected per event; the only variant that re-issues a write is the
+// None -> typed upgrade, mirroring the guarded DO UPDATE in the upsert.
+#[test]
+fn test_propdef_type_variants_collapse_to_one_entry() {
+ let cache = Cache::new(10, 10, 10);
+
+ let untyped = make_prop_def_typed("plan", None);
+ 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!(
+ cache.contains_key(&untyped),
+ "untyped resend cannot change the row"
+ );
+ assert!(
+ !cache.contains_key(&typed),
+ "typed sighting must upgrade the untyped row"
+ );
+
+ cache.insert(typed.clone());
+ assert_eq!(cache.propdefs_len(), 1, "variants must share one entry");
+ assert!(cache.contains_key(&typed));
+ assert!(
+ cache.contains_key(&untyped),
+ "untyped resend cannot downgrade a typed row"
+ );
+ assert!(
+ cache.contains_key(&retyped),
+ "the upsert never overwrites a non-null type"
+ );
+
+ cache.insert(untyped);
+ assert!(
+ cache.contains_key(&typed),
+ "a racing untyped insert cannot downgrade the cached type"
+ );
+}
+
+fn make_event_def_at(name: &str, last_seen_at: chrono::DateTime<Utc>) -> Update {
+ Update::Event(EventDefinition {
+ name: name.into(),
+ team_id: 1,
+ project_id: 1,
+ last_seen_at,
+ })
+}
+
+// The floored last_seen bucket is the cache value, so a rollover re-issues
+// the write and replaces the entry instead of abandoning a dead entry for
+// every elapsed bucket.
+#[test]
+fn test_eventdef_bucket_rollover_replaces_entry() {
+ let cache = Cache::new(10, 10, 10);
+
+ let t1 = Utc::now();
+ let t2 = t1 + chrono::Duration::hours(2);
+
+ let bucket1 = make_event_def_at("checkout", t1);
+ let bucket2 = make_event_def_at("checkout", t2);
+
+ cache.insert(bucket1.clone());
+ 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.eventdefs_len(),
+ 1,
+ "rollover must replace, not accumulate"
+ );
+ assert!(cache.contains_key(&bucket2));
+ assert!(
+ cache.contains_key(&bucket1),
+ "an in-flight older bucket is covered by the newer cached one"
+ );
+
+ cache.insert(bucket1);
+ assert!(
+ cache.contains_key(&bucket2),
+ "a racing older insert cannot replace the newer bucket"
+ );
+}
+
// Guards the recency contract of `Cache::contains_key`: a lookup must mark the
// entry referenced (quick_cache `get`), so a key that was checked survives the
// next eviction pass by promotion into the protected segment. quick_cache's