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): evict unresolved group defs to stop cache poisoning (#70268)

Eli Reisman5d1249365168
diff --git a/rust/property-defs-rs/.sqlx/query-98344d37df67429762341c091992954cf6d6801f26d2a1c74dcacf1c7edd7f56.json b/rust/property-defs-rs/.sqlx/query-98344d37df67429762341c091992954cf6d6801f26d2a1c74dcacf1c7edd7f56.json
new file mode 100644
index 000000000000..adb012d50354
--- /dev/null
+++ b/rust/property-defs-rs/.sqlx/query-98344d37df67429762341c091992954cf6d6801f26d2a1c74dcacf1c7edd7f56.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT group_type_index FROM posthog_propertydefinition WHERE type = 3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "group_type_index",
+ "type_info": "Int2"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "98344d37df67429762341c091992954cf6d6801f26d2a1c74dcacf1c7edd7f56"
+}
diff --git a/rust/property-defs-rs/src/batch_ingestion.rs b/rust/property-defs-rs/src/batch_ingestion.rs
index e1970127efbc..6bb70ec1a72e 100644
--- a/rust/property-defs-rs/src/batch_ingestion.rs
+++ b/rust/property-defs-rs/src/batch_ingestion.rs
@@ -16,7 +16,7 @@ use crate::{
V2_EVENT_PROPS_BATCH_SIZE, V2_EVENT_PROPS_BATCH_WRITE_TIME, V2_EVENT_PROPS_CACHE_REMOVED,
V2_PROP_DEFS_BATCH_ATTEMPT, V2_PROP_DEFS_BATCH_CACHE_TIME,
V2_PROP_DEFS_BATCH_ROWS_AFFECTED, V2_PROP_DEFS_BATCH_SIZE, V2_PROP_DEFS_BATCH_WRITE_TIME,
- V2_PROP_DEFS_CACHE_REMOVED,
+ V2_PROP_DEFS_CACHE_REMOVED, V2_PROP_DEFS_DROPPED_UNCACHED,
},
types::{
EventDefinition, EventProperty, GroupType, PropertyDefinition, PropertyParentType, Update,
@@ -156,6 +156,10 @@ pub struct PropertyDefinitionsBatch {
pub group_type_indices: Vec<Option<i16>>,
// note: I left off deprecated fields we null out on writes
pub cached: Vec<Update>,
+ // Group propdefs dropped for an unresolved group_type_index. They're never written, but
+ // the producer already inserted them (as Unresolved) into the shared dedup cache, so we
+ // evict them post-batch to avoid poisoning the cache against a later resolvable retry.
+ pub dropped_unresolved: Vec<Update>,
}
impl PropertyDefinitionsBatch {
@@ -171,6 +175,7 @@ impl PropertyDefinitionsBatch {
event_types: Vec::with_capacity(batch_size),
group_type_indices: Vec::with_capacity(batch_size),
cached: Vec::with_capacity(batch_size),
+ dropped_unresolved: Vec::new(),
}
}
@@ -195,6 +200,11 @@ impl PropertyDefinitionsBatch {
// during the transaction (which we do if we don't have a group-type index for a
// group property), the entire transaction is aborted, so instead we just warn
// loudly about this (above, and at resolve time), and drop the update.
+ //
+ // Record it so we can evict the producer's (Unresolved) shared-cache entry after
+ // the batch: without this, a transient resolution miss (new group type not yet
+ // visible to personhog) permanently blocks the def from ever persisting.
+ self.dropped_unresolved.push(Update::Property(pd));
return;
}
@@ -221,7 +231,19 @@ impl PropertyDefinitionsBatch {
}
pub fn is_empty(&self) -> bool {
- self.len() == 0
+ // Dropped-unresolved entries carry no write, but they still need a flush so their
+ // shared-cache entries get evicted, so a batch with only drops is not "empty".
+ self.len() == 0 && self.dropped_unresolved.is_empty()
+ }
+
+ // Evict the shared-cache entries for group propdefs we dropped for an unresolved
+ // group_type_index. The producer inserted them as Unresolved and the resolver preserves
+ // that form on a miss, so these keys match the originals directly (no revert needed).
+ pub fn uncache_dropped(&self, cache: &Arc<Cache>) {
+ for update in &self.dropped_unresolved {
+ cache.remove(update);
+ metrics::counter!(V2_PROP_DEFS_DROPPED_UNCACHED).increment(1);
+ }
}
pub fn uncache_batch(&self, cache: &Arc<Cache>) {
@@ -422,6 +444,17 @@ async fn write_property_definitions_batch(
let total_time = common_metrics::timing_guard(V2_PROP_DEFS_BATCH_WRITE_TIME, &[]);
let mut tries: u64 = 1;
+ // A batch may contain only dropped-unresolved entries (nothing to write). Skip the empty
+ // INSERT but still evict those poisoned shared-cache entries so they can be retried.
+ // Not `is_empty()`: that intentionally returns false when only drops are present (they
+ // still need a flush to evict); here we specifically mean "no writable rows".
+ #[allow(clippy::len_zero)]
+ if batch.len() == 0 {
+ batch.uncache_dropped(&cache);
+ total_time.fin();
+ return Ok(());
+ }
+
loop {
// what if we just ditch properties without a property_type set? why update on conflict at all?
//
@@ -482,6 +515,7 @@ async fn write_property_definitions_batch(
// remove all entries from cache so they get another shot
// at persisting on future event submissions
batch.uncache_batch(&cache);
+ batch.uncache_dropped(&cache);
return Err(e);
}
@@ -507,6 +541,10 @@ async fn write_property_definitions_batch(
count
);
+ // Dropped group propdefs were never written; evict their (Unresolved) shared-cache
+ // entries so a later, now-resolvable $groupidentify is not filtered out.
+ batch.uncache_dropped(&cache);
+
return Ok(());
}
}
@@ -611,3 +649,67 @@ async fn write_event_definitions_batch(
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::{GroupType, PropertyDefinition, PropertyParentType};
+
+ fn group_pd(team_id: i32, group_name: &str, prop: &str) -> PropertyDefinition {
+ PropertyDefinition {
+ team_id,
+ project_id: team_id as i64,
+ name: prop.to_string(),
+ is_numerical: false,
+ property_type: None,
+ event_type: PropertyParentType::Group,
+ group_type_index: Some(GroupType::Unresolved(group_name.to_string())),
+ property_type_format: None,
+ volume_30_day: None,
+ query_usage_30_day: None,
+ }
+ }
+
+ #[test]
+ fn unresolved_group_pd_is_dropped_and_recorded_for_eviction() {
+ let mut batch = PropertyDefinitionsBatch::new(100);
+ batch.append(group_pd(1, "org", "seats"));
+
+ // Nothing to write (the CHECK constraint forbids a NULL group_type_index)...
+ assert_eq!(batch.len(), 0);
+ assert!(batch.cached.is_empty());
+ // ...but it's recorded so its shared-cache entry gets evicted, and a drop-only batch
+ // must still flush.
+ assert_eq!(batch.dropped_unresolved.len(), 1);
+ assert!(!batch.is_empty());
+ }
+
+ #[test]
+ fn uncache_dropped_evicts_the_producer_inserted_key() {
+ let cache = Arc::new(Cache::new(10, 10, 10));
+ let pd = group_pd(1, "org", "seats");
+
+ // The producer inserts the Unresolved form before resolution runs.
+ cache.insert(Update::Property(pd.clone()));
+ assert!(cache.contains_key(&Update::Property(pd.clone())));
+
+ let mut batch = PropertyDefinitionsBatch::new(100);
+ batch.append(pd.clone());
+ batch.uncache_dropped(&cache);
+
+ // The poisoned entry is gone, so a later resolvable $groupidentify won't be filtered.
+ assert!(!cache.contains_key(&Update::Property(pd)));
+ }
+
+ #[test]
+ fn resolved_group_pd_is_written_not_dropped() {
+ let mut batch = PropertyDefinitionsBatch::new(100);
+ let mut pd = group_pd(1, "org", "seats");
+ pd.group_type_index = Some(GroupType::Resolved("org".to_string(), 2));
+ batch.append(pd);
+
+ assert_eq!(batch.len(), 1);
+ assert!(batch.dropped_unresolved.is_empty());
+ assert_eq!(batch.group_type_indices, vec![Some(2)]);
+ }
+}
diff --git a/rust/property-defs-rs/src/config.rs b/rust/property-defs-rs/src/config.rs
index 05b87a722f35..2eaf41326b28 100644
--- a/rust/property-defs-rs/src/config.rs
+++ b/rust/property-defs-rs/src/config.rs
@@ -81,6 +81,19 @@ pub struct Config {
#[envconfig(default = "100000")]
pub group_type_cache_size: usize,
+ // Negative cache for group-type resolution misses (personhog returned no mapping).
+ // A new group type's $groupidentify can arrive here before its GroupTypeMapping is
+ // visible to personhog's eventual read, so a miss is often a transient race, not
+ // terminal misuse. We cache the miss for this TTL so we neither hammer personhog for
+ // repeated unresolvable keys nor block a legitimate new group for longer than the TTL:
+ // once the entry expires the next $groupidentify re-attempts resolution. Kept short on
+ // purpose (the mapping is committed to PG primary before we consume the event, so only
+ // replica lag remains).
+ #[envconfig(default = "30")]
+ pub group_type_negative_ttl_secs: u64,
+ #[envconfig(default = "100000")]
+ pub group_type_negative_cache_size: usize,
+
#[envconfig(from = "BIND_HOST", default = "::")]
pub host: String,
diff --git a/rust/property-defs-rs/src/group_type_resolver.rs b/rust/property-defs-rs/src/group_type_resolver.rs
index 0fe40990ca29..a8f67dfb4cb7 100644
--- a/rust/property-defs-rs/src/group_type_resolver.rs
+++ b/rust/property-defs-rs/src/group_type_resolver.rs
@@ -6,7 +6,7 @@ use quick_cache::sync::Cache;
use rand::Rng;
use std::collections::HashMap;
use std::future::Future;
-use std::time::Duration;
+use std::time::{Duration, Instant};
use tokio::time::sleep;
use tonic::transport::Channel;
use tonic::{Code, Status};
@@ -108,6 +108,10 @@ where
pub struct GroupTypeResolver {
cache: Cache<String, i32>,
+ // Stores the expiry Instant for a resolution miss. quick_cache has no native TTL, so we
+ // check the stored expiry on read and treat the entry as live only while unexpired.
+ negative_cache: Cache<String, Instant>,
+ negative_ttl: Duration,
personhog_client: Option<PersonHogServiceClient<Channel>>,
max_retries: u32,
initial_backoff_ms: u64,
@@ -117,6 +121,8 @@ pub struct GroupTypeResolver {
impl GroupTypeResolver {
pub fn new(config: &Config) -> Self {
let cache = Cache::new(config.group_type_cache_size);
+ let negative_cache = Cache::new(config.group_type_negative_cache_size);
+ let negative_ttl = Duration::from_secs(config.group_type_negative_ttl_secs);
let personhog_client = if !config.personhog_addr.is_empty() {
let timeout = std::time::Duration::from_millis(config.personhog_timeout_ms);
@@ -152,6 +158,8 @@ impl GroupTypeResolver {
Self {
cache,
+ negative_cache,
+ negative_ttl,
personhog_client,
max_retries: config.personhog_max_retries,
initial_backoff_ms: config.personhog_initial_backoff_ms,
@@ -159,6 +167,19 @@ impl GroupTypeResolver {
}
}
+ /// Returns true if `cache_key` has a live (unexpired) resolution-miss entry. Expired
+ /// entries are removed so the next lookup re-attempts resolution via personhog.
+ fn is_negatively_cached(&self, cache_key: &str) -> bool {
+ match self.negative_cache.get(cache_key) {
+ Some(expiry) if Instant::now() < expiry => true,
+ Some(_) => {
+ self.negative_cache.remove(cache_key);
+ false
+ }
+ None => false,
+ }
+ }
+
pub async fn resolve(&self, updates: &mut [Update]) -> Result<(), anyhow::Error> {
// Collect all unresolved group types that need lookup
let mut to_resolve: Vec<(usize, String, i32)> = Vec::new();
@@ -178,6 +199,11 @@ impl GroupTypeResolver {
metrics::counter!(GROUP_TYPE_CACHE, &[("action", "hit")]).increment(1);
update.group_type_index =
update.group_type_index.take().map(|gti| gti.resolve(index));
+ } else if self.is_negatively_cached(&cache_key) {
+ // Known-unresolvable within the TTL window: skip the personhog lookup and
+ // leave the update Unresolved so batch_ingestion drops it and evicts it from
+ // the shared dedup cache, letting a later event retry once the TTL lapses.
+ metrics::counter!(GROUP_TYPE_CACHE, &[("action", "negative_hit")]).increment(1);
} else {
to_resolve.push((idx, group_name.clone(), update.team_id));
}
@@ -216,9 +242,13 @@ impl GroupTypeResolver {
"Failed to resolve group type index for group name: {group_name} and team id: {team_id}"
);
- if let Update::Property(update) = &mut updates[idx] {
- update.group_type_index = None;
- }
+ // Record the miss so repeated unresolvable keys don't re-hit personhog for
+ // the TTL window. We deliberately leave update.group_type_index as
+ // Some(Unresolved(name)) (rather than None): batch_ingestion drops it either
+ // way, but preserving the name keeps the shared-cache key recoverable so the
+ // dropped entry can be evicted and retried instead of poisoning the cache.
+ self.negative_cache
+ .insert(cache_key, Instant::now() + self.negative_ttl);
}
}
}
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index 2884545f42aa..f3f85c36901b 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -64,3 +64,8 @@ pub const V2_PROP_DEFS_BATCH_ROWS_AFFECTED: &str = "propdefs_v2_propdefs_batch_r
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_BATCH_SIZE: &str = "propdefs_v2_propdefs_batch_size";
+
+// Group property definitions dropped for an unresolved group_type_index and evicted from
+// the shared dedup cache, so a later $groupidentify (whose type resolves once the mapping
+// lands) is not filtered out and can persist.
+pub const V2_PROP_DEFS_DROPPED_UNCACHED: &str = "propdefs_v2_propdefs_dropped_uncached";
diff --git a/rust/property-defs-rs/tests/group_type_resolver.rs b/rust/property-defs-rs/tests/group_type_resolver.rs
index 19897e79c47c..5ef2a8799280 100644
--- a/rust/property-defs-rs/tests/group_type_resolver.rs
+++ b/rust/property-defs-rs/tests/group_type_resolver.rs
@@ -6,12 +6,15 @@ use personhog_proto::personhog::{
service::v1::person_hog_service_server::{PersonHogService, PersonHogServiceServer},
types::v1::*,
};
+use sqlx::PgPool;
use tokio::net::TcpListener;
use tonic::{Code, Request, Response, Status};
use property_defs_rs::{
+ batch_ingestion::process_batch,
group_type_resolver::GroupTypeResolver,
types::{GroupType, PropertyParentType, Update},
+ update_cache::Cache,
};
// -- mock server --------------------------------------------------------
@@ -21,6 +24,9 @@ struct MockPersonHogService {
/// Number of calls that should fail before succeeding. usize::MAX = always fail.
fail_remaining: AtomicUsize,
fail_code: Code,
+ /// The first N successful calls return no mappings, simulating a GroupTypeMapping that
+ /// hasn't yet reached the eventual read replica; later calls return `mappings_by_team`.
+ empty_first_calls: usize,
call_count: Arc<AtomicUsize>,
}
@@ -30,6 +36,7 @@ impl MockPersonHogService {
mappings_by_team,
fail_remaining: AtomicUsize::new(0),
fail_code: Code::Internal,
+ empty_first_calls: 0,
call_count: Arc::new(AtomicUsize::new(0)),
}
}
@@ -42,6 +49,7 @@ impl MockPersonHogService {
mappings_by_team,
fail_remaining: AtomicUsize::new(0),
fail_code: Code::Internal,
+ empty_first_calls: 0,
call_count,
}
}
@@ -51,6 +59,7 @@ impl MockPersonHogService {
mappings_by_team: vec![],
fail_remaining: AtomicUsize::new(usize::MAX),
fail_code: Code::InvalidArgument,
+ empty_first_calls: 0,
call_count: Arc::new(AtomicUsize::new(0)),
}
}
@@ -65,6 +74,7 @@ impl MockPersonHogService {
mappings_by_team,
fail_remaining: AtomicUsize::new(fail_count),
fail_code,
+ empty_first_calls: 0,
call_count,
}
}
@@ -74,6 +84,24 @@ impl MockPersonHogService {
mappings_by_team: vec![],
fail_remaining: AtomicUsize::new(usize::MAX),
fail_code,
+ empty_first_calls: 0,
+ call_count,
+ }
+ }
+
+ /// The first `empty_first_calls` lookups resolve to nothing (a miss); later lookups return
+ /// `mappings_by_team`. Models a newly created group type only becoming visible after an
+ /// initial window, which is exactly the transient miss that used to poison the cache.
+ fn resolves_after_empty_calls(
+ mappings_by_team: Vec<GroupTypeMappingsByKey>,
+ empty_first_calls: usize,
+ call_count: Arc<AtomicUsize>,
+ ) -> Self {
+ Self {
+ mappings_by_team,
+ fail_remaining: AtomicUsize::new(0),
+ fail_code: Code::Internal,
+ empty_first_calls,
call_count,
}
}
@@ -85,7 +113,7 @@ impl PersonHogService for MockPersonHogService {
&self,
_req: Request<GetGroupTypeMappingsByTeamIdsRequest>,
) -> Result<Response<GroupTypeMappingsBatchResponse>, Status> {
- self.call_count.fetch_add(1, Ordering::SeqCst);
+ let this_call = self.call_count.fetch_add(1, Ordering::SeqCst) + 1;
// Decrement fail_remaining; if it was > 0 before the decrement, fail this call.
// Uses saturating to avoid wrapping usize::MAX (always-fail case).
@@ -99,9 +127,14 @@ impl PersonHogService for MockPersonHogService {
return Err(Status::new(self.fail_code, "mock failure"));
}
- Ok(Response::new(GroupTypeMappingsBatchResponse {
- results: self.mappings_by_team.clone(),
- }))
+ // Simulate the mapping only becoming visible after `empty_first_calls` lookups.
+ let results = if this_call <= self.empty_first_calls {
+ vec![]
+ } else {
+ self.mappings_by_team.clone()
+ };
+
+ Ok(Response::new(GroupTypeMappingsBatchResponse { results }))
}
// -- stubs for the rest of the trait (never called) ------------------
@@ -508,7 +541,11 @@ async fn test_personhog_resolves_multiple_teams() {
}
#[tokio::test]
-async fn test_personhog_unresolved_group_type_cleared() {
+async fn test_personhog_unresolved_group_type_preserved_not_cleared() {
+ // On a resolution miss we must keep the Unresolved(name) form rather than clearing to
+ // None: batch_ingestion drops it either way, but preserving the name keeps the shared
+ // dedup-cache key recoverable so the dropped entry can be evicted and retried, instead
+ // of the entry poisoning the cache and permanently blocking the def.
let mock = MockPersonHogService::with_mappings(vec![GroupTypeMappingsByKey {
key: 1,
mappings: vec![],
@@ -523,11 +560,76 @@ async fn test_personhog_unresolved_group_type_cleared() {
resolver.resolve(&mut updates).await.unwrap();
match &updates[0] {
- Update::Property(p) => assert!(p.group_type_index.is_none()),
+ Update::Property(p) => assert_eq!(
+ p.group_type_index,
+ Some(GroupType::Unresolved("nonexistent".to_string()))
+ ),
+ _ => panic!("expected Property update"),
+ }
+}
+
+#[tokio::test]
+async fn test_negative_cache_skips_personhog_within_ttl() {
+ // A miss is cached for the TTL window so repeated unresolvable keys don't re-hit personhog.
+ let call_count = Arc::new(AtomicUsize::new(0));
+ let mock = MockPersonHogService::with_mappings_counted(
+ vec![GroupTypeMappingsByKey {
+ key: 1,
+ mappings: vec![],
+ }],
+ call_count.clone(),
+ );
+
+ let addr = start_mock_server(mock).await;
+ let config = make_config(&format!("http://{addr}")); // default TTL is 30s
+ let resolver = GroupTypeResolver::new(&config);
+
+ let mut updates = vec![make_group_update(1, "nonexistent")];
+ resolver.resolve(&mut updates).await.unwrap();
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
+
+ // Second resolve of the same key is served from the negative cache: no personhog call,
+ // and the update is still left Unresolved so it gets dropped + evicted downstream.
+ let mut updates2 = vec![make_group_update(1, "nonexistent")];
+ resolver.resolve(&mut updates2).await.unwrap();
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
+ match &updates2[0] {
+ Update::Property(p) => assert_eq!(
+ p.group_type_index,
+ Some(GroupType::Unresolved("nonexistent".to_string()))
+ ),
_ => panic!("expected Property update"),
}
}
+#[tokio::test]
+async fn test_negative_cache_reattempts_after_ttl_expiry() {
+ // With TTL=0 the negative entry is immediately expired, so a subsequent event re-attempts
+ // resolution via personhog (this is what lets a legitimate new group resolve once its
+ // mapping lands).
+ let call_count = Arc::new(AtomicUsize::new(0));
+ let mock = MockPersonHogService::with_mappings_counted(
+ vec![GroupTypeMappingsByKey {
+ key: 1,
+ mappings: vec![],
+ }],
+ call_count.clone(),
+ );
+
+ let addr = start_mock_server(mock).await;
+ let mut config = make_config(&format!("http://{addr}"));
+ config.group_type_negative_ttl_secs = 0;
+ let resolver = GroupTypeResolver::new(&config);
+
+ let mut updates = vec![make_group_update(1, "nonexistent")];
+ resolver.resolve(&mut updates).await.unwrap();
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
+
+ let mut updates2 = vec![make_group_update(1, "nonexistent")];
+ resolver.resolve(&mut updates2).await.unwrap();
+ assert_eq!(call_count.load(Ordering::SeqCst), 2);
+}
+
#[tokio::test]
async fn test_personhog_failure_returns_error() {
let mock = MockPersonHogService::failing();
@@ -705,3 +807,135 @@ async fn test_no_retries_when_max_retries_is_zero() {
assert!(result.is_err());
assert_eq!(call_count.load(Ordering::SeqCst), 1);
}
+
+// -- end-to-end test ----------------------------------------------------
+
+fn group_type_of(update: &Update) -> Option<GroupType> {
+ match update {
+ Update::Property(p) => p.group_type_index.clone(),
+ _ => None,
+ }
+}
+
+async fn group_prop_def_count(db: &PgPool) -> i64 {
+ // type = 3 is PropertyParentType::Group. Query text matches the existing cached entry.
+ sqlx::query_scalar!(r#"SELECT count(*) from posthog_propertydefinition WHERE type = 3"#)
+ .fetch_one(db)
+ .await
+ .unwrap()
+ .unwrap_or(0)
+}
+
+// Walks the full production loop end to end for a $groupidentify group property whose group type
+// isn't yet resolvable (its GroupTypeMapping hasn't reached the eventual read replica):
+//
+// round 1 (poison + evict): producer caches the Unresolved key, resolver misses, the batch
+// drops the def AND evicts the poisoned cache key so a retry is possible.
+// round 2 (recover + persist): the mapping has "landed", the producer re-forwards the def (it's
+// no longer filtered by the cache), the resolver resolves it, and the batch persists it.
+//
+// This is the regression guard the isolated resolver/batch unit tests don't provide: it ties the
+// resolver miss, the shared-cache eviction, the negative cache, and the Postgres write together,
+// so a future refactor that quietly reintroduces the cache-poisoning bug fails here.
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn test_end_to_end_poisoned_group_def_recovers_and_persists(db: PgPool) {
+ const TEAM: i32 = 111;
+
+ let call_count = Arc::new(AtomicUsize::new(0));
+ // First personhog lookup returns no mapping (the miss that poisons); the second returns the
+ // now-visible mapping at index 5.
+ let mock = MockPersonHogService::resolves_after_empty_calls(
+ vec![GroupTypeMappingsByKey {
+ key: TEAM as i64,
+ mappings: vec![GroupTypeMapping {
+ id: 1,
+ team_id: TEAM as i64,
+ project_id: TEAM as i64,
+ group_type: "Organization".to_string(),
+ group_type_index: 5,
+ name_singular: None,
+ name_plural: None,
+ default_columns: None,
+ detail_dashboard_id: None,
+ created_at: None,
+ }],
+ }],
+ 1,
+ call_count.clone(),
+ );
+
+ let addr = start_mock_server(mock).await;
+ let mut config = make_config(&format!("http://{addr}"));
+ config.skip_writes = false;
+ // TTL 0 makes round 1's negative-cache entry immediately stale, so round 2 re-drives personhog.
+ // This is the deterministic stand-in for "the TTL lapsed" between the two sparse events.
+ config.group_type_negative_ttl_secs = 0;
+
+ let resolver = GroupTypeResolver::new(&config);
+ let cache: Arc<Cache> = Arc::new(Cache::new(
+ config.eventdefs_cache_capacity,
+ config.eventprops_cache_capacity,
+ config.propdefs_cache_capacity,
+ ));
+
+ // The producer inserts the Unresolved form into the shared dedup cache before resolution runs.
+ let unresolved_key = make_group_update(TEAM, "Organization");
+
+ // ---- round 1: poison, then evict ----
+ let mut round1 = vec![make_group_update(TEAM, "Organization")];
+ assert!(!cache.contains_key(&unresolved_key), "cache starts empty");
+ cache.insert(unresolved_key.clone());
+
+ resolver.resolve(&mut round1).await.unwrap();
+ // Miss: the group type is preserved as Unresolved (not cleared to None).
+ assert_eq!(
+ group_type_of(&round1[0]),
+ Some(GroupType::Unresolved("Organization".to_string()))
+ );
+
+ process_batch(&config, cache.clone(), &db, round1).await;
+
+ assert_eq!(
+ group_prop_def_count(&db).await,
+ 0,
+ "an unresolved group def must not be written"
+ );
+ assert!(
+ !cache.contains_key(&unresolved_key),
+ "the poisoned key must be evicted so a later event can retry"
+ );
+ assert_eq!(call_count.load(Ordering::SeqCst), 1);
+
+ // ---- round 2: mapping landed -> retry resolves and persists ----
+ let mut round2 = vec![make_group_update(TEAM, "Organization")];
+ // The producer no longer filters it (the key was evicted), so it re-forwards.
+ assert!(!cache.contains_key(&round2[0]));
+ cache.insert(round2[0].clone());
+
+ resolver.resolve(&mut round2).await.unwrap();
+ // The negative entry has expired (TTL 0), so personhog is re-driven and now resolves to 5.
+ assert_eq!(get_resolved_index(&round2[0]), Some(5));
+
+ process_batch(&config, cache.clone(), &db, round2).await;
+
+ assert_eq!(
+ group_prop_def_count(&db).await,
+ 1,
+ "the def must persist once its group type resolves"
+ );
+ let persisted_index: Option<i16> = sqlx::query_scalar!(
+ r#"SELECT group_type_index FROM posthog_propertydefinition WHERE type = 3"#
+ )
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(persisted_index, Some(5));
+ assert_eq!(
+ call_count.load(Ordering::SeqCst),
+ 2,
+ "round 2 must re-drive personhog after the TTL lapse"
+ );
+ // The (Unresolved) dedup key remains cached from round 2, so an identical later event is
+ // deduped rather than reprocessed.
+ assert!(cache.contains_key(&unresolved_key));
+}