: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(personhog): cascade person delete to cohort (#65837)
Zach Brownf6ac193eb9aa
diff --git a/rust/personhog-replica/.sqlx/query-400e720151f7640e659e6e645a1fe233eaffd38786b091c508d95e0630627dcd.json b/rust/personhog-replica/.sqlx/query-400e720151f7640e659e6e645a1fe233eaffd38786b091c508d95e0630627dcd.jsonnew file mode 100644index 000000000000..4153dc54eb0a--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-400e720151f7640e659e6e645a1fe233eaffd38786b091c508d95e0630627dcd.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM posthog_cohortpeople\n WHERE person_id = ANY($1)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "400e720151f7640e659e6e645a1fe233eaffd38786b091c508d95e0630627dcd"+}diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 85c82ee21876..61ef1e1268bb 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -460,14 +460,20 @@ impl PersonLookup for PostgresStorage {&[("operation".to_string(), "delete_persons".to_string())],chunks.len() as f64,);- let results: Vec<i64> = stream::iter(chunks.into_iter().map(|chunk| {- let pool = pool.clone();- let client = client.clone();- async move { delete_persons_by_ids_chunk(&pool, team_id, &chunk, &client).await }- }))- .buffer_unordered(self.bulk_max_concurrent_chunks)- .try_collect()- .await?;+ let results: Vec<i64> =+ stream::iter(+ chunks.into_iter().map(|chunk| {+ let pool = pool.clone();+ let client = client.clone();+ // Per-person delete: also clear cohort memberships (no DB cascade).+ async move {+ delete_persons_by_ids_chunk(&pool, team_id, &chunk, &client, true).await+ }+ }),+ )+ .buffer_unordered(self.bulk_max_concurrent_chunks)+ .try_collect()+ .await?;Ok(results.iter().sum())}@@ -580,14 +586,20 @@ impl PersonLookup for PostgresStorage {)],chunks.len() as f64,);- let results: Vec<i64> = stream::iter(chunks.into_iter().map(|chunk| {- let pool = pool.clone();- let client = client.clone();- async move { delete_persons_by_ids_chunk(&pool, team_id, &chunk, &client).await }- }))- .buffer_unordered(self.bulk_max_concurrent_chunks)- .try_collect()- .await?;+ let results: Vec<i64> =+ stream::iter(+ chunks.into_iter().map(|chunk| {+ let pool = pool.clone();+ let client = client.clone();+ // Team teardown clears cohortpeople separately, by cohort, before this runs.+ async move {+ delete_persons_by_ids_chunk(&pool, team_id, &chunk, &client, false).await+ }+ }),+ )+ .buffer_unordered(self.bulk_max_concurrent_chunks)+ .try_collect()+ .await?;Ok(results.iter().sum())}@@ -1019,6 +1031,7 @@ async fn delete_persons_by_ids_chunk(team_id: i64,person_ids: &[i64],client: &str,+ delete_cohortpeople: bool,) -> StorageResult<i64> {if person_ids.is_empty() {return Ok(0);@@ -1063,6 +1076,37 @@ async fn delete_persons_by_ids_chunk(did_result.rows_affected() as f64,);+ // Cohort memberships have no FK to posthog_person (the constraint was dropped+ // during person-table partitioning), so they don't cascade — delete them+ // explicitly for these persons. Gated because the team-teardown path already+ // clears cohortpeople up front by cohort; only the per-person DeletePersons+ // path needs this here.+ if delete_cohortpeople {+ let cohort_result = sqlx::query!(+ r#"+ DELETE FROM posthog_cohortpeople+ WHERE person_id = ANY($1)+ "#,+ person_ids+ )+ .execute(&mut *tx)+ .await?;++ common_metrics::histogram(+ DB_ROWS_RETURNED,+ &[+ (+ "operation".to_string(),+ "delete_cohortpeople_for_persons".to_string(),+ ),+ ("pool".to_string(), "bulk_primary".to_string()),+ ("client".to_string(), client.to_string()),+ ("method".to_string(), current_method_name().to_string()),+ ],+ cohort_result.rows_affected() as f64,+ );+ }+// Delete person rows (hash key overrides cascade at DB level).let result = sqlx::query!(r#"diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex a2d6bfdc605b..b400bb6bbab3 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -368,6 +368,82 @@ async fn test_insert_cohort_members_idempotent(ctx.cleanup().await.ok();}+#[tokio::test]+async fn test_delete_persons_clears_cohort_memberships() {+ // posthog_cohortpeople has no FK to posthog_person (no DB cascade), so the+ // per-person DeletePersons path must clear memberships itself.+ let ctx = TestContext::new().await;+ let cohort_id: i64 = 8800;+ let person = ctx+ .insert_person("[email protected]", None)+ .await+ .expect("insert person");+ ctx.add_person_to_cohort(person.id, cohort_id)+ .await+ .expect("add person to cohort");+ assert_eq!(+ cohort_row_count(&ctx.pool, cohort_id, &[person.id]).await,+ 1+ );++ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[person.uuid])+ .await+ .expect("delete persons");++ assert_eq!(deleted, 1);+ assert_eq!(+ cohort_row_count(&ctx.pool, cohort_id, &[person.id]).await,+ 0+ );++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_batch_for_team_leaves_cohort_memberships() {+ // The team-teardown path clears cohortpeople separately, by cohort, before+ // deleting persons — so delete_persons_batch_for_team must NOT touch it.+ let ctx = TestContext::new().await;+ let cohort_id: i64 = 8801;+ let person = ctx+ .insert_person("[email protected]", None)+ .await+ .expect("insert person");+ ctx.add_person_to_cohort(person.id, cohort_id)+ .await+ .expect("add person to cohort");+ assert_eq!(+ cohort_row_count(&ctx.pool, cohort_id, &[person.id]).await,+ 1+ );++ let deleted = ctx+ .storage+ .delete_persons_batch_for_team(ctx.team_id, 1000)+ .await+ .expect("delete persons batch for team");++ assert_eq!(deleted, 1);+ // Intentionally still present — the batch path leaves cohortpeople for the+ // by-cohort sweep in the team-teardown orchestration.+ assert_eq!(+ cohort_row_count(&ctx.pool, cohort_id, &[person.id]).await,+ 1+ );++ // The person is gone, so the standard cleanup (which scopes by team's persons)+ // won't reach this now-orphaned row; remove it explicitly.+ sqlx::query("DELETE FROM posthog_cohortpeople WHERE cohort_id = $1 AND person_id = $2")+ .bind(cohort_id)+ .bind(person.id)+ .execute(&ctx.pool)+ .await+ .ok();+ ctx.cleanup().await.ok();+}+#[tokio::test]async fn test_person_properties() {let ctx = TestContext::new().await;