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): strip FK-poison rows from failed write batches (#75772)

Eli Reisman7120703f014a
diff --git a/rust/property-defs-rs/src/batch_ingestion.rs b/rust/property-defs-rs/src/batch_ingestion.rs
index dd503e27fa62..582744288336 100644
--- a/rust/property-defs-rs/src/batch_ingestion.rs
+++ b/rust/property-defs-rs/src/batch_ingestion.rs
@@ -10,14 +10,14 @@ use uuid::Uuid;
use crate::{
config::Config,
metrics_consts::{
- ISSUE_FAILED, V2_EVENT_DEFS_BATCH_ATTEMPT, V2_EVENT_DEFS_BATCH_CACHE_TIME,
- V2_EVENT_DEFS_BATCH_ROWS_AFFECTED, V2_EVENT_DEFS_BATCH_SIZE,
- V2_EVENT_DEFS_BATCH_WRITE_TIME, V2_EVENT_DEFS_CACHE_REMOVED, V2_EVENT_PROPS_BATCH_ATTEMPT,
- V2_EVENT_PROPS_BATCH_CACHE_TIME, V2_EVENT_PROPS_BATCH_ROWS_AFFECTED,
- 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_DROPPED_UNCACHED,
+ ISSUE_FAILED, V2_BATCH_ROWS_DROPPED_FK, V2_EVENT_DEFS_BATCH_ATTEMPT,
+ V2_EVENT_DEFS_BATCH_CACHE_TIME, V2_EVENT_DEFS_BATCH_ROWS_AFFECTED,
+ V2_EVENT_DEFS_BATCH_SIZE, V2_EVENT_DEFS_BATCH_WRITE_TIME, V2_EVENT_DEFS_CACHE_REMOVED,
+ V2_EVENT_PROPS_BATCH_ATTEMPT, V2_EVENT_PROPS_BATCH_CACHE_TIME,
+ V2_EVENT_PROPS_BATCH_ROWS_AFFECTED, 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_DROPPED_UNCACHED,
},
types::{
EventDefinition, EventProperty, GroupType, PropertyDefinition, PropertyParentType, Update,
@@ -27,6 +27,40 @@ use crate::{
const V2_BATCH_MAX_RETRY_ATTEMPTS: u64 = 3;
const V2_BATCH_RETRY_DELAY_MS: u64 = 50;
+// How many distinct FK-violating tenants a single batch write will strip-and-rewrite
+// around before falling back to the normal retry path. Bounds the failed-INSERT loop
+// when a batch is riddled with rows for deleted teams/projects.
+const V2_BATCH_MAX_FK_STRIPS: u64 = 3;
+
+// Retains only the elements of `v` whose index holds `true` in `mask`.
+fn retain_by_mask<T>(v: &mut Vec<T>, mask: &[bool]) {
+ let mut idx = 0;
+ v.retain(|_| {
+ let keep = mask[idx];
+ idx += 1;
+ keep
+ });
+}
+
+/// Extracts the offending column/value from a Postgres foreign-key violation
+/// (SQLSTATE 23503) error detail, e.g.
+/// `Key (team_id)=(522607) is not present in table "posthog_team".`
+/// Returns None for any other error, or when the detail isn't a single integer
+/// key (composite keys, unexpected formats) — callers then use the normal
+/// retry path, so parsing can only ever narrow behavior, never break it.
+fn fk_violation_key(e: &sqlx::Error) -> Option<(String, i64)> {
+ let sqlx::Error::Database(db) = e else {
+ return None;
+ };
+ if db.code().as_deref() != Some("23503") {
+ return None;
+ }
+ let pg = db.try_downcast_ref::<sqlx::postgres::PgDatabaseError>()?;
+ let rest = pg.detail()?.strip_prefix("Key (")?;
+ let (column, rest) = rest.split_once(")=(")?;
+ let (value, _) = rest.split_once(')')?;
+ Some((column.to_string(), value.parse().ok()?))
+}
// Derived hash since these are keyed on all fields in the DB
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -83,6 +117,32 @@ impl EventPropertiesBatch {
timer.fin();
}
+
+ // Strips rows referencing a missing FK target (deleted team/project); returns how many
+ // were removed. Their `cached` entries are removed too, so a later uncache_batch can't
+ // evict them from the shared dedup cache: staying cached is what stops the dead
+ // tenant's events from re-issuing the same failing write.
+ pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
+ let keep: Vec<bool> = match column {
+ "team_id" => self
+ .team_ids
+ .iter()
+ .map(|id| i64::from(*id) != value)
+ .collect(),
+ "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
+ _ => return 0,
+ };
+ let removed = keep.iter().filter(|k| !**k).count();
+ if removed == 0 {
+ return 0;
+ }
+ retain_by_mask(&mut self.team_ids, &keep);
+ retain_by_mask(&mut self.project_ids, &keep);
+ retain_by_mask(&mut self.event_names, &keep);
+ retain_by_mask(&mut self.property_names, &keep);
+ retain_by_mask(&mut self.cached, &keep);
+ removed
+ }
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -142,6 +202,30 @@ impl EventDefinitionsBatch {
timer.fin();
}
+
+ // See EventPropertiesBatch::remove_rows_for_fk.
+ pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
+ let keep: Vec<bool> = match column {
+ "team_id" => self
+ .team_ids
+ .iter()
+ .map(|id| i64::from(*id) != value)
+ .collect(),
+ "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
+ _ => return 0,
+ };
+ let removed = keep.iter().filter(|k| !**k).count();
+ if removed == 0 {
+ return 0;
+ }
+ retain_by_mask(&mut self.ids, &keep);
+ retain_by_mask(&mut self.names, &keep);
+ retain_by_mask(&mut self.team_ids, &keep);
+ retain_by_mask(&mut self.project_ids, &keep);
+ retain_by_mask(&mut self.last_seen_ats, &keep);
+ retain_by_mask(&mut self.cached, &keep);
+ removed
+ }
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -270,6 +354,34 @@ impl PropertyDefinitionsBatch {
timer.fin();
}
+
+ // See EventPropertiesBatch::remove_rows_for_fk. `dropped_unresolved` is untouched:
+ // those entries were never part of the write.
+ pub fn remove_rows_for_fk(&mut self, column: &str, value: i64) -> usize {
+ let keep: Vec<bool> = match column {
+ "team_id" => self
+ .team_ids
+ .iter()
+ .map(|id| i64::from(*id) != value)
+ .collect(),
+ "project_id" => self.project_ids.iter().map(|id| *id != value).collect(),
+ _ => return 0,
+ };
+ let removed = keep.iter().filter(|k| !**k).count();
+ if removed == 0 {
+ return 0;
+ }
+ retain_by_mask(&mut self.ids, &keep);
+ retain_by_mask(&mut self.team_ids, &keep);
+ retain_by_mask(&mut self.project_ids, &keep);
+ retain_by_mask(&mut self.names, &keep);
+ retain_by_mask(&mut self.are_numerical, &keep);
+ retain_by_mask(&mut self.event_types, &keep);
+ retain_by_mask(&mut self.property_types, &keep);
+ retain_by_mask(&mut self.group_type_indices, &keep);
+ retain_by_mask(&mut self.cached, &keep);
+ removed
+ }
}
// HACK: making this public so the test suite file can live under "../tests/" dir
@@ -377,11 +489,12 @@ pub async fn process_batch(
async fn write_event_properties_batch(
cache: Arc<Cache>,
- batch: EventPropertiesBatch,
+ mut batch: EventPropertiesBatch,
pool: &PgPool,
) -> Result<(), sqlx::Error> {
let total_time = common_metrics::timing_guard(V2_EVENT_PROPS_BATCH_WRITE_TIME, &[]);
let mut tries = 1;
+ let mut fk_strips: u64 = 0;
loop {
let result = sqlx::query(
@@ -402,6 +515,35 @@ async fn write_event_properties_batch(
match result {
Err(e) => {
+ // Rows referencing a deleted team/project can never be written; strip them
+ // (they stay cached, suppressing future re-issues) and rewrite the survivors.
+ // Unparseable FK errors, no matching rows, or an exhausted strip budget all
+ // fall through to the normal retry path below, so parsing can only ever
+ // narrow behavior, never change it.
+ if fk_strips < V2_BATCH_MAX_FK_STRIPS {
+ if let Some((column, value)) = fk_violation_key(&e) {
+ let removed = batch.remove_rows_for_fk(&column, value);
+ if removed > 0 {
+ fk_strips += 1;
+ metrics::counter!(
+ V2_EVENT_PROPS_BATCH_ATTEMPT,
+ &[("result", "dropped_fk")]
+ )
+ .increment(1);
+ metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "eventprops")])
+ .increment(removed as u64);
+ warn!(
+ "Dropped {removed} event property rows referencing missing {column}={value}"
+ );
+ if batch.is_empty() {
+ total_time.fin();
+ return Ok(());
+ }
+ continue;
+ }
+ }
+ }
+
if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
metrics::counter!(V2_EVENT_PROPS_BATCH_ATTEMPT, &[("result", "failed")])
.increment(1);
@@ -449,11 +591,12 @@ async fn write_event_properties_batch(
async fn write_property_definitions_batch(
cache: Arc<Cache>,
- batch: PropertyDefinitionsBatch,
+ mut batch: PropertyDefinitionsBatch,
pool: &PgPool,
) -> Result<(), sqlx::Error> {
let total_time = common_metrics::timing_guard(V2_PROP_DEFS_BATCH_WRITE_TIME, &[]);
let mut tries: u64 = 1;
+ let mut fk_strips: u64 = 0;
// 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.
@@ -513,6 +656,39 @@ async fn write_property_definitions_batch(
match result {
Err(e) => {
+ // Rows referencing a deleted team/project can never be written; strip them
+ // (they stay cached, suppressing future re-issues) and rewrite the survivors.
+ // Unparseable FK errors, no matching rows, or an exhausted strip budget all
+ // fall through to the normal retry path below, so parsing can only ever
+ // narrow behavior, never change it.
+ if fk_strips < V2_BATCH_MAX_FK_STRIPS {
+ if let Some((column, value)) = fk_violation_key(&e) {
+ let removed = batch.remove_rows_for_fk(&column, value);
+ if removed > 0 {
+ fk_strips += 1;
+ metrics::counter!(
+ V2_PROP_DEFS_BATCH_ATTEMPT,
+ &[("result", "dropped_fk")]
+ )
+ .increment(1);
+ metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "propdefs")])
+ .increment(removed as u64);
+ warn!(
+ "Dropped {removed} property definition rows referencing missing {column}={value}"
+ );
+ // Not `is_empty()`: that returns false when only dropped-unresolved
+ // entries remain, and here we mean "no writable rows left".
+ #[allow(clippy::len_zero)]
+ if batch.len() == 0 {
+ total_time.fin();
+ batch.uncache_dropped(&cache);
+ return Ok(());
+ }
+ continue;
+ }
+ }
+ }
+
if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
metrics::counter!(V2_PROP_DEFS_BATCH_ATTEMPT, &[("result", "failed")])
.increment(1);
@@ -564,11 +740,12 @@ async fn write_property_definitions_batch(
async fn write_event_definitions_batch(
cache: Arc<Cache>,
- batch: EventDefinitionsBatch,
+ mut batch: EventDefinitionsBatch,
pool: &PgPool,
) -> Result<(), sqlx::Error> {
let total_time = common_metrics::timing_guard(V2_EVENT_DEFS_BATCH_WRITE_TIME, &[]);
let mut tries: u64 = 1;
+ let mut fk_strips: u64 = 0;
loop {
// last_seen_ats are manipulated on event defs for cache expiration
@@ -618,6 +795,35 @@ async fn write_event_definitions_batch(
match result {
Err(e) => {
+ // Rows referencing a deleted team/project can never be written; strip them
+ // (they stay cached, suppressing future re-issues) and rewrite the survivors.
+ // Unparseable FK errors, no matching rows, or an exhausted strip budget all
+ // fall through to the normal retry path below, so parsing can only ever
+ // narrow behavior, never change it.
+ if fk_strips < V2_BATCH_MAX_FK_STRIPS {
+ if let Some((column, value)) = fk_violation_key(&e) {
+ let removed = batch.remove_rows_for_fk(&column, value);
+ if removed > 0 {
+ fk_strips += 1;
+ metrics::counter!(
+ V2_EVENT_DEFS_BATCH_ATTEMPT,
+ &[("result", "dropped_fk")]
+ )
+ .increment(1);
+ metrics::counter!(V2_BATCH_ROWS_DROPPED_FK, &[("table", "eventdefs")])
+ .increment(removed as u64);
+ warn!(
+ "Dropped {removed} event definition rows referencing missing {column}={value}"
+ );
+ if batch.is_empty() {
+ total_time.fin();
+ return Ok(());
+ }
+ continue;
+ }
+ }
+ }
+
if tries == V2_BATCH_MAX_RETRY_ATTEMPTS {
metrics::counter!(V2_EVENT_DEFS_BATCH_ATTEMPT, &[("result", "failed")])
.increment(1);
@@ -723,4 +929,47 @@ mod tests {
assert!(batch.dropped_unresolved.is_empty());
assert_eq!(batch.group_type_indices, vec![Some(2)]);
}
+
+ fn event_prop(team_id: i32, prop: &str) -> EventProperty {
+ EventProperty {
+ team_id,
+ project_id: team_id as i64,
+ event: "$pageview".to_string(),
+ property: prop.to_string(),
+ }
+ }
+
+ // UNNEST pads mismatched input arrays with NULLs instead of erroring, so a desync
+ // between the parallel vecs would corrupt writes silently. Guard that a strip keeps
+ // every vec (including `cached`) aligned, across both FK columns.
+ #[test]
+ fn remove_rows_for_fk_keeps_parallel_vecs_aligned() {
+ for column in ["team_id", "project_id"] {
+ let mut batch = EventPropertiesBatch::new(100);
+ batch.append(event_prop(1, "a"));
+ batch.append(event_prop(999, "b"));
+ batch.append(event_prop(1, "c"));
+ batch.append(event_prop(999, "d"));
+
+ assert_eq!(batch.remove_rows_for_fk(column, 999), 2);
+ assert_eq!(batch.len(), 2);
+ assert_eq!(batch.team_ids, vec![1, 1]);
+ assert_eq!(batch.project_ids, vec![1, 1]);
+ assert_eq!(batch.property_names, vec!["a", "c"]);
+ assert_eq!(batch.event_names.len(), 2);
+ assert_eq!(batch.cached.len(), 2);
+ }
+ }
+
+ #[test]
+ fn remove_rows_for_fk_ignores_unknown_columns_and_missing_values() {
+ let mut batch = EventPropertiesBatch::new(100);
+ batch.append(event_prop(1, "a"));
+
+ // an FK column we don't carry (e.g. a composite or exotic constraint) strips nothing
+ assert_eq!(batch.remove_rows_for_fk("organization_id", 1), 0);
+ // and neither does a value no row references
+ assert_eq!(batch.remove_rows_for_fk("team_id", 42), 0);
+ assert_eq!(batch.len(), 1);
+ }
}
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index f3f85c36901b..249cd0d0d7aa 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -69,3 +69,9 @@ pub const V2_PROP_DEFS_BATCH_SIZE: &str = "propdefs_v2_propdefs_batch_size";
// 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";
+
+// Rows stripped from a write batch because they reference a team/project that no longer
+// exists (Postgres FK violation, e.g. a deleted team still sending events). Labeled by
+// target table. Stripped rows stay in the shared dedup cache on purpose, so the dead
+// tenant's events stop re-issuing the same failing write.
+pub const V2_BATCH_ROWS_DROPPED_FK: &str = "propdefs_v2_batch_rows_dropped_fk";
diff --git a/rust/property-defs-rs/tests/batch_ingestion.rs b/rust/property-defs-rs/tests/batch_ingestion.rs
index bd5e52d1cb32..4b2ca4e00a15 100644
--- a/rust/property-defs-rs/tests/batch_ingestion.rs
+++ b/rust/property-defs-rs/tests/batch_ingestion.rs
@@ -528,3 +528,158 @@ async fn test_event_definitions_dedupe_within_batch(db: PgPool) {
"the deduped event def and the unrelated new one must both persist"
);
}
+
+fn gen_updates_for_team(team_id: i32, event_name: &str, num_props: usize) -> Vec<Update> {
+ let mut properties = HashMap::<String, Value>::new();
+ for i in 0..num_props {
+ properties.insert(format!("prop_{i}"), Value::String(format!("value_{i}")));
+ }
+ let event = json!({
+ "team_id": team_id,
+ "project_id": team_id,
+ "event": event_name,
+ "properties": json!(properties).to_string(),
+ });
+ serde_json::from_value::<Event>(event)
+ .unwrap()
+ .into_updates(10000)
+}
+
+fn filter_team(updates: &[Update], team_id: i32) -> Vec<Update> {
+ updates
+ .iter()
+ .filter(|u| match u {
+ Update::Event(ed) => ed.team_id == team_id,
+ Update::Property(pd) => pd.team_id == team_id,
+ Update::EventProperty(ep) => ep.team_id == team_id,
+ })
+ .cloned()
+ .collect()
+}
+
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn test_fk_violation_strips_dead_team_rows_and_keeps_them_cached(db: PgPool) {
+ // Prod tables enforce team FKs; a deleted team still sending events used to fail the
+ // whole batch and evict it from the dedup cache, re-issuing the same doomed writes on
+ // every future event. The shared test schema has no FKs, so recreate them locally.
+ sqlx::query(r#"CREATE TABLE posthog_team (id INTEGER PRIMARY KEY)"#)
+ .execute(&db)
+ .await
+ .unwrap();
+ sqlx::query(r#"INSERT INTO posthog_team (id) VALUES (111)"#)
+ .execute(&db)
+ .await
+ .unwrap();
+ for table in [
+ "posthog_eventdefinition",
+ "posthog_propertydefinition",
+ "posthog_eventproperty",
+ ] {
+ sqlx::query(&format!(
+ "ALTER TABLE {table} ADD CONSTRAINT {table}_team_fk FOREIGN KEY (team_id) REFERENCES posthog_team(id)"
+ ))
+ .execute(&db)
+ .await
+ .unwrap();
+ }
+
+ let config = Config::init_with_defaults().unwrap();
+ let cache = setup_cache(&config);
+
+ let mut updates = gen_updates_for_team(111, "$pageview", 10);
+ updates.extend(gen_updates_for_team(999, "$pageview", 10)); // team 999 was deleted
+
+ // the producer inserts every update into the shared dedup cache before the write path runs
+ for u in &updates {
+ cache.insert(u.clone());
+ }
+
+ process_batch(
+ &config,
+ cache.clone(),
+ &db,
+ updates.clone(),
+ &test_lifecycle_handle(),
+ )
+ .await;
+
+ // the live team's rows all landed despite sharing chunks with the dead team's rows
+ for (table, expected) in [
+ ("posthog_eventdefinition", 1i64),
+ ("posthog_propertydefinition", 10),
+ ("posthog_eventproperty", 10),
+ ] {
+ let live: i64 =
+ sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table} WHERE team_id = 111"))
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(live, expected, "live team rows missing from {table}");
+
+ let dead: i64 =
+ sqlx::query_scalar(&format!("SELECT COUNT(*) FROM {table} WHERE team_id = 999"))
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(dead, 0, "dead team rows written to {table}");
+ }
+
+ // every update stays cached: the dead team's (so its events stop re-issuing doomed
+ // writes) and the live team's (written successfully, never evicted)
+ for u in &updates {
+ assert!(cache.contains_key(u), "update evicted from cache: {u:?}");
+ }
+}
+
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn test_unparseable_fk_falls_back_to_retry_and_uncache(db: PgPool) {
+ // A composite-key FK produces detail `Key (team_id, project_id)=(999, 999) ...`, which
+ // fk_violation_key can't reduce to one column/value. The write must then behave exactly
+ // like master: bounded retries, then evict the batch from the dedup cache.
+ sqlx::query(
+ r#"CREATE TABLE posthog_team (id INTEGER, project_id BIGINT, PRIMARY KEY (id, project_id))"#,
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+ sqlx::query(
+ r#"ALTER TABLE posthog_eventproperty ADD CONSTRAINT eventproperty_team_proj_fk
+ FOREIGN KEY (team_id, project_id) REFERENCES posthog_team(id, project_id)"#,
+ )
+ .execute(&db)
+ .await
+ .unwrap();
+
+ let config = Config::init_with_defaults().unwrap();
+ let cache = setup_cache(&config);
+
+ let updates = gen_updates_for_team(999, "$pageview", 5);
+ for u in &updates {
+ cache.insert(u.clone());
+ }
+
+ process_batch(
+ &config,
+ cache.clone(),
+ &db,
+ updates.clone(),
+ &test_lifecycle_handle(),
+ )
+ .await;
+
+ let written: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM posthog_eventproperty")
+ .fetch_one(&db)
+ .await
+ .unwrap();
+ assert_eq!(written, 0, "no eventproperty rows can satisfy the FK");
+
+ // master fallback ran: the failed eventprops chunk was evicted for a future retry
+ for u in filter_team(&updates, 999) {
+ if matches!(u, Update::EventProperty(_)) {
+ assert!(
+ !cache.contains_key(&u),
+ "eventprop update not evicted by fallback path: {u:?}"
+ );
+ }
+ }
+}