: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-reader): chunk delete calls (#59519)
Zach Brown0fab93e0dbcc
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 4b49021cbacf..99b844857816 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -6730,6 +6730,7 @@ dependencies = ["common-database","common-metrics","envconfig",+ "futures","lifecycle","metrics-exporter-prometheus","personhog-common",diff --git a/rust/personhog-replica/.sqlx/query-52c5a242550abf52c13cfc576794dbbe83835b9abc590a696d421463084cbe84.json b/rust/personhog-replica/.sqlx/query-52c5a242550abf52c13cfc576794dbbe83835b9abc590a696d421463084cbe84.jsondeleted file mode 100644index edf9900cd2c8..000000000000--- a/rust/personhog-replica/.sqlx/query-52c5a242550abf52c13cfc576794dbbe83835b9abc590a696d421463084cbe84.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4",- "Int8Array"- ]- },- "nullable": []- },- "hash": "52c5a242550abf52c13cfc576794dbbe83835b9abc590a696d421463084cbe84"-}diff --git a/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.json b/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.jsonnew file mode 100644index 000000000000..dbc3629047b4--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id::bigint as \"id!\" FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325"+}diff --git a/rust/personhog-replica/.sqlx/query-3f6268a40b84ddbaa9d216b67556ed0fba7bb2ae9d40459d83b637a5964efa87.json b/rust/personhog-replica/.sqlx/query-7a41ce7b7aa693ada1a71572c4f22f0d95d9fe3c42176f3749b0ca21a66680a3.jsonsimilarity index 75%rename from rust/personhog-replica/.sqlx/query-3f6268a40b84ddbaa9d216b67556ed0fba7bb2ae9d40459d83b637a5964efa87.jsonrename to rust/personhog-replica/.sqlx/query-7a41ce7b7aa693ada1a71572c4f22f0d95d9fe3c42176f3749b0ca21a66680a3.jsonindex f4b29faf6dfb..5e0e79eefaf6 100644--- a/rust/personhog-replica/.sqlx/query-3f6268a40b84ddbaa9d216b67556ed0fba7bb2ae9d40459d83b637a5964efa87.json+++ b/rust/personhog-replica/.sqlx/query-7a41ce7b7aa693ada1a71572c4f22f0d95d9fe3c42176f3749b0ca21a66680a3.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id::bigint as \"id!\" FROM posthog_person\n WHERE team_id = $1\n LIMIT $2\n FOR UPDATE SKIP LOCKED\n ",+ "query": "\n SELECT id::bigint as \"id!\" FROM posthog_person\n WHERE team_id = $1\n LIMIT $2\n ","describe": {"columns": [{@@ -19,5 +19,5 @@false]},- "hash": "3f6268a40b84ddbaa9d216b67556ed0fba7bb2ae9d40459d83b637a5964efa87"+ "hash": "7a41ce7b7aa693ada1a71572c4f22f0d95d9fe3c42176f3749b0ca21a66680a3"}diff --git a/rust/personhog-replica/.sqlx/query-8773bd5fa20ef0e278b8d08cd89405a01ca79048553ccfaabcbc947c856891cd.json b/rust/personhog-replica/.sqlx/query-8773bd5fa20ef0e278b8d08cd89405a01ca79048553ccfaabcbc947c856891cd.jsondeleted file mode 100644index f3669df47aee..000000000000--- a/rust/personhog-replica/.sqlx/query-8773bd5fa20ef0e278b8d08cd89405a01ca79048553ccfaabcbc947c856891cd.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4",- "UuidArray"- ]- },- "nullable": []- },- "hash": "8773bd5fa20ef0e278b8d08cd89405a01ca79048553ccfaabcbc947c856891cd"-}diff --git a/rust/personhog-replica/.sqlx/query-b82d95e05f46fcea33970f3ab12f696b041d86f9873707d0e77bce6c5d89ea68.json b/rust/personhog-replica/.sqlx/query-b82d95e05f46fcea33970f3ab12f696b041d86f9873707d0e77bce6c5d89ea68.jsondeleted file mode 100644index c15d4a808ff4..000000000000--- a/rust/personhog-replica/.sqlx/query-b82d95e05f46fcea33970f3ab12f696b041d86f9873707d0e77bce6c5d89ea68.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4",- "Int8Array"- ]- },- "nullable": []- },- "hash": "b82d95e05f46fcea33970f3ab12f696b041d86f9873707d0e77bce6c5d89ea68"-}diff --git a/rust/personhog-replica/.sqlx/query-bbe820dca30600d0ac7f65615d9b8f065be5d1c767c21ac681df2ebb7a0676b2.json b/rust/personhog-replica/.sqlx/query-bbe820dca30600d0ac7f65615d9b8f065be5d1c767c21ac681df2ebb7a0676b2.jsonnew file mode 100644index 000000000000..d22d1dcc5268--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-bbe820dca30600d0ac7f65615d9b8f065be5d1c767c21ac681df2ebb7a0676b2.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "bbe820dca30600d0ac7f65615d9b8f065be5d1c767c21ac681df2ebb7a0676b2"+}diff --git a/rust/personhog-replica/.sqlx/query-c0a44370305a825f943f7c2b8777b5e52b85d9bd148fba6005b32d951e593df4.json b/rust/personhog-replica/.sqlx/query-c0a44370305a825f943f7c2b8777b5e52b85d9bd148fba6005b32d951e593df4.jsondeleted file mode 100644index c8cd7a0adfbf..000000000000--- a/rust/personhog-replica/.sqlx/query-c0a44370305a825f943f7c2b8777b5e52b85d9bd148fba6005b32d951e593df4.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM posthog_persondistinctid\n WHERE team_id = $1\n AND person_id IN (SELECT id FROM posthog_person WHERE team_id = $1 AND uuid = ANY($2))\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4",- "UuidArray"- ]- },- "nullable": []- },- "hash": "c0a44370305a825f943f7c2b8777b5e52b85d9bd148fba6005b32d951e593df4"-}diff --git a/rust/personhog-replica/.sqlx/query-f69869e56dd9f5492a97e9b503328b001d026c0295d7087cc4484662a33439ff.json b/rust/personhog-replica/.sqlx/query-f69869e56dd9f5492a97e9b503328b001d026c0295d7087cc4484662a33439ff.jsonnew file mode 100644index 000000000000..a7753ba17883--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-f69869e56dd9f5492a97e9b503328b001d026c0295d7087cc4484662a33439ff.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "f69869e56dd9f5492a97e9b503328b001d026c0295d7087cc4484662a33439ff"+}diff --git a/rust/personhog-replica/Cargo.toml b/rust/personhog-replica/Cargo.tomlindex c04c3991876c..75ff828a4e99 100644--- a/rust/personhog-replica/Cargo.toml+++ b/rust/personhog-replica/Cargo.toml@@ -14,6 +14,7 @@ metrics-exporter-prometheus = { workspace = true }lifecycle = { path = "../common/lifecycle" }async-trait = { workspace = true }+futures = { workspace = true }axum = { workspace = true }chrono = { workspace = true }envconfig = { workspace = true }diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rsindex 1e8bbc18952c..7747a8769c57 100644--- a/rust/personhog-replica/src/config.rs+++ b/rust/personhog-replica/src/config.rs@@ -49,6 +49,18 @@ pub struct Config {#[envconfig(default = "10")]pub bulk_acquire_timeout_secs: u64,+ /// Number of items per chunk when splitting bulk operations (reads and+ /// deletes) into parallel queries.+ #[envconfig(default = "200")]+ pub bulk_chunk_size: usize,++ /// Maximum number of chunks to execute concurrently. Each concurrent+ /// chunk holds a connection from the bulk pool, so this should not+ /// exceed bulk_max_pg_connections. Kept conservative to limit burst+ /// load on the database when multiple callers delete concurrently.+ #[envconfig(default = "2")]+ pub bulk_max_concurrent_chunks: usize,+/// Maximum number of server-side (PgBouncer → Postgres) connections to/// warm at startup via SELECT 1. Clamped to min_pg_connections. Set to 0/// to skip server-side warming entirely.diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex 5600a60f9cb0..b477f3b92226 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -92,11 +92,28 @@ async fn create_storage(config: &Config) -> Arc<PostgresStorage> {"Created bulk database pools");+ assert!(+ config.bulk_chunk_size >= 1,+ "BULK_CHUNK_SIZE must be at least 1"+ );+ assert!(+ config.bulk_max_concurrent_chunks >= 1,+ "BULK_MAX_CONCURRENT_CHUNKS must be at least 1"+ );+ assert!(+ config.bulk_max_concurrent_chunks <= config.bulk_max_pg_connections as usize,+ "BULK_MAX_CONCURRENT_CHUNKS ({}) must not exceed BULK_MAX_PG_CONNECTIONS ({})",+ config.bulk_max_concurrent_chunks,+ config.bulk_max_pg_connections+ );+Arc::new(PostgresStorage::new(primary_pool,replica_pool,bulk_primary_pool,bulk_replica_pool,+ config.bulk_chunk_size,+ config.bulk_max_concurrent_chunks,))}other => {diff --git a/rust/personhog-replica/src/storage/postgres/mod.rs b/rust/personhog-replica/src/storage/postgres/mod.rsindex 6c3a82e8e807..2b64a906d846 100644--- a/rust/personhog-replica/src/storage/postgres/mod.rs+++ b/rust/personhog-replica/src/storage/postgres/mod.rs@@ -15,6 +15,7 @@ use super::error::StorageError;pub(crate) const DB_QUERY_DURATION: &str = "personhog_replica_db_query_duration_ms";pub(crate) const DB_POOL_ACQUIRE_DURATION: &str = "personhog_replica_db_pool_acquire_duration_ms";pub(crate) const DB_ROWS_RETURNED: &str = "personhog_replica_db_rows_returned";+pub(crate) const DB_BULK_CHUNKS: &str = "personhog_replica_db_bulk_chunks";/// Consistency level for read operations#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]@@ -38,6 +39,8 @@ pub struct PostgresStorage {pub bulk_primary_pool: PgPool,/// Bulk pool for the replica database (large batch reads)pub bulk_replica_pool: PgPool,+ pub(crate) bulk_chunk_size: usize,+ pub(crate) bulk_max_concurrent_chunks: usize,}impl PostgresStorage {@@ -47,22 +50,16 @@ impl PostgresStorage {replica_pool: PgPool,bulk_primary_pool: PgPool,bulk_replica_pool: PgPool,+ bulk_chunk_size: usize,+ bulk_max_concurrent_chunks: usize,) -> Self {Self {primary_pool,replica_pool,bulk_primary_pool,bulk_replica_pool,- }- }-- /// Create a new PostgresStorage with a single pool used for everything.- pub fn new_single_pool(pool: PgPool) -> Self {- Self {- primary_pool: pool.clone(),- replica_pool: pool.clone(),- bulk_primary_pool: pool.clone(),- bulk_replica_pool: pool,+ bulk_chunk_size,+ bulk_max_concurrent_chunks,}}diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 8c0023f0660d..081140841de6 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -1,11 +1,13 @@use std::collections::HashMap;use async_trait::async_trait;+use futures::stream::{self, StreamExt, TryStreamExt};+use sqlx::postgres::PgPool;use uuid::Uuid;use personhog_common::grpc::current_client_name;-use super::{PostgresStorage, DB_QUERY_DURATION, DB_ROWS_RETURNED};+use super::{PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNED};use crate::storage::error::StorageResult;use crate::storage::traits::PersonLookup;use crate::storage::types::Person;@@ -317,61 +319,47 @@ impl PersonLookup for PostgresStorage {];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut tx = self.bulk_primary_pool.begin().await?;-- // Delete distinct_id rows first — the FK on posthog_persondistinctid.person_id- // is NO ACTION, so the person delete would fail if these still exist.- let did_result = sqlx::query!(- r#"- DELETE FROM posthog_persondistinctid- WHERE team_id = $1- AND person_id IN (SELECT id FROM posthog_person WHERE team_id = $1 AND uuid = ANY($2))- "#,- team_id as i32,- uuids- )- .execute(&mut *tx)- .await?;-- common_metrics::histogram(- DB_ROWS_RETURNED,- &[- (- "operation".to_string(),- "delete_distinct_ids_for_persons".to_string(),- ),- ("pool".to_string(), "bulk_primary".to_string()),- ("client".to_string(), client.to_string()),- ],- did_result.rows_affected() as f64,- );-- // Delete person rows. posthog_featureflaghashkeyoverride rows cascade- // automatically at the DB level (ON DELETE CASCADE).- let result = sqlx::query!(+ // Resolve UUIDs to integer IDs in one query, then chunk and delete+ // by ID. This avoids scanning the UUID index per-chunk.+ let person_ids: Vec<i64> = sqlx::query_scalar!(r#"- DELETE FROM posthog_person+ SELECT id::bigint as "id!" FROM posthog_personWHERE team_id = $1 AND uuid = ANY($2)"#,team_id as i32,uuids)- .execute(&mut *tx)+ .fetch_all(&self.bulk_primary_pool).await?;+ if person_ids.is_empty() {+ return Ok(0);+ }++ // Split into fixed-size chunks and delete concurrently. On the first+ // error, stop starting new chunks and return the error. Chunks that+ // already committed are durable; the caller retries the full UUID+ // list and already-deleted UUIDs are idempotent no-ops.+ let pool = self.bulk_primary_pool.clone();+ let chunks: Vec<Vec<i64>> = person_ids+ .chunks(self.bulk_chunk_size)+ .map(|c| c.to_vec())+ .collect();common_metrics::histogram(- DB_ROWS_RETURNED,- &[- ("operation".to_string(), "delete_persons".to_string()),- ("pool".to_string(), "bulk_primary".to_string()),- ("client".to_string(), client.to_string()),- ],- result.rows_affected() as f64,+ DB_BULK_CHUNKS,+ &[("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?;- tx.commit().await?;-- Ok(result.rows_affected() as i64)+ Ok(results.iter().sum())}async fn delete_persons_batch_for_team(@@ -394,80 +382,47 @@ impl PersonLookup for PostgresStorage {];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut tx = self.bulk_primary_pool.begin().await?;-- // Step 1: Select up to batch_size person IDs for the team+ // Select up to batch_size person IDs.let person_ids: Vec<i64> = sqlx::query_scalar!(r#"SELECT id::bigint as "id!" FROM posthog_personWHERE team_id = $1LIMIT $2- FOR UPDATE SKIP LOCKED"#,team_id as i32,batch_size)- .fetch_all(&mut *tx)+ .fetch_all(&self.bulk_primary_pool).await?;if person_ids.is_empty() {- tx.commit().await?;return Ok(0);}- // Step 2: Delete distinct_id rows first — FK is NO ACTION- let did_result = sqlx::query!(- r#"- DELETE FROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = ANY($2)- "#,- team_id as i32,- &person_ids[..]- )- .execute(&mut *tx)- .await?;-+ // Split into fixed-size chunks and delete concurrently.+ let pool = self.bulk_primary_pool.clone();+ let chunks: Vec<Vec<i64>> = person_ids+ .chunks(self.bulk_chunk_size)+ .map(|c| c.to_vec())+ .collect();common_metrics::histogram(- DB_ROWS_RETURNED,- &[- (- "operation".to_string(),- "delete_distinct_ids_batch_for_team".to_string(),- ),- ("pool".to_string(), "bulk_primary".to_string()),- ("client".to_string(), client.to_string()),- ],- did_result.rows_affected() as f64,+ DB_BULK_CHUNKS,+ &[(+ "operation".to_string(),+ "delete_persons_batch_for_team".to_string(),+ )],+ chunks.len() as f64,);-- // Step 3: Delete person rows (hash key overrides cascade at DB level)- let result = sqlx::query!(- r#"- DELETE FROM posthog_person- WHERE team_id = $1 AND id = ANY($2)- "#,- team_id as i32,- &person_ids[..]- )- .execute(&mut *tx)+ 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?;- common_metrics::histogram(- DB_ROWS_RETURNED,- &[- (- "operation".to_string(),- "delete_persons_batch_for_team".to_string(),- ),- ("pool".to_string(), "bulk_primary".to_string()),- ("client".to_string(), client.to_string()),- ],- result.rows_affected() as f64,- );-- tx.commit().await?;-- Ok(result.rows_affected() as i64)+ Ok(results.iter().sum())}async fn get_persons_by_distinct_ids_cross_team(@@ -559,3 +514,83 @@ impl PersonLookup for PostgresStorage {.collect())}}++/// Delete a chunk of persons by integer ID in a single transaction:+/// distinct_ids first (FK is NO ACTION), then persons (feature flag hash+/// key overrides cascade at the DB level).+async fn delete_persons_by_ids_chunk(+ pool: &PgPool,+ team_id: i64,+ person_ids: &[i64],+ client: &str,+) -> StorageResult<i64> {+ if person_ids.is_empty() {+ return Ok(0);+ }++ let chunk_labels = [+ (+ "operation".to_string(),+ "delete_persons_batch_for_team_chunk".to_string(),+ ),+ ("pool".to_string(), "bulk_primary".to_string()),+ ("client".to_string(), client.to_string()),+ ];+ let _chunk_timer = common_metrics::timing_guard(DB_QUERY_DURATION, &chunk_labels);++ let mut tx = pool.begin().await?;++ // Delete distinct_id rows first — FK is NO ACTION.+ let did_result = sqlx::query!(+ r#"+ DELETE FROM posthog_persondistinctid+ WHERE team_id = $1 AND person_id = ANY($2)+ "#,+ team_id as i32,+ person_ids+ )+ .execute(&mut *tx)+ .await?;++ common_metrics::histogram(+ DB_ROWS_RETURNED,+ &[+ (+ "operation".to_string(),+ "delete_distinct_ids_batch_for_team".to_string(),+ ),+ ("pool".to_string(), "bulk_primary".to_string()),+ ("client".to_string(), client.to_string()),+ ],+ did_result.rows_affected() as f64,+ );++ // Delete person rows (hash key overrides cascade at DB level).+ let result = sqlx::query!(+ r#"+ DELETE FROM posthog_person+ WHERE team_id = $1 AND id = ANY($2)+ "#,+ team_id as i32,+ person_ids+ )+ .execute(&mut *tx)+ .await?;++ common_metrics::histogram(+ DB_ROWS_RETURNED,+ &[+ (+ "operation".to_string(),+ "delete_persons_batch_for_team".to_string(),+ ),+ ("pool".to_string(), "bulk_primary".to_string()),+ ("client".to_string(), client.to_string()),+ ],+ result.rows_affected() as f64,+ );++ tx.commit().await?;++ Ok(result.rows_affected() as i64)+}diff --git a/rust/personhog-replica/src/storage/traits/person.rs b/rust/personhog-replica/src/storage/traits/person.rsindex 337da3a11401..4ad4dabaa541 100644--- a/rust/personhog-replica/src/storage/traits/person.rs+++ b/rust/personhog-replica/src/storage/traits/person.rs@@ -47,17 +47,19 @@ pub trait PersonLookup: Send + Sync {// Deletes- /// Delete persons by UUID for a given team. In a single transaction:- /// 1. Deletes associated posthog_persondistinctid rows (FK is NO ACTION, would block otherwise)- /// 2. Deletes the posthog_person rows (posthog_featureflaghashkeyoverride cascades at DB level)- /// Returns the number of deleted person records.+ /// Delete persons by UUID for a given team. Large batches are split into+ /// fixed-size chunks and deleted concurrently. Each chunk runs in its own+ /// transaction, deleting distinct_ids first (FK is NO ACTION) then persons+ /// (feature flag hash key overrides cascade at the DB level). Idempotent:+ /// deleting already-removed UUIDs is a no-op.async fn delete_persons(&self, team_id: i64, uuids: &[Uuid]) -> StorageResult<i64>;- /// Delete up to `batch_size` persons for a team. In a single transaction:- /// 1. Selects up to batch_size person IDs for the team- /// 2. Deletes their posthog_persondistinctid rows (FK is NO ACTION)- /// 3. Deletes the posthog_person rows (posthog_featureflaghashkeyoverride cascades at DB level)- /// Returns the number of deleted person records. 0 means no more persons to delete.+ /// Delete up to `batch_size` persons for a team. Selects person IDs with+ /// FOR UPDATE SKIP LOCKED, then splits them into fixed-size chunks and+ /// deletes concurrently. Each chunk deletes distinct_ids first (FK is+ /// NO ACTION) then persons (feature flag hash key overrides cascade at+ /// the DB level). Returns the number of deleted person records; 0 means+ /// no more persons to delete.async fn delete_persons_batch_for_team(&self,team_id: i64,diff --git a/rust/personhog-replica/tests/common/mod.rs b/rust/personhog-replica/tests/common/mod.rsindex c6b90947f8e0..2841bc404af1 100644--- a/rust/personhog-replica/tests/common/mod.rs+++ b/rust/personhog-replica/tests/common/mod.rs@@ -29,7 +29,14 @@ impl TestContext {.await.expect("Failed to connect to test database");// In tests, use the same pool for everything- let storage = Arc::new(PostgresStorage::new_single_pool(pool.clone()));+ let storage = Arc::new(PostgresStorage::new(+ pool.clone(),+ pool.clone(),+ pool.clone(),+ pool.clone(),+ 50, // bulk_chunk_size — small so parallel path is exercised with fewer test rows+ 5, // bulk_max_concurrent_chunks+ ));let team_id = random_team_id();Self {diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex 102c51733df1..7faba6aa5bc4 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -4,6 +4,7 @@ use common::TestContext;use personhog_replica::storage::postgres::ConsistencyLevel;use personhog_replica::storage::GroupKey;use rand::Rng;+use uuid::Uuid;#[tokio::test]async fn test_get_person_by_id() {@@ -1060,3 +1061,355 @@ async fn test_delete_persons_batch_for_team_rolls_back_on_partial_failure() {.ok();ctx.cleanup().await.ok();}++// ============================================================+// Delete persons by UUID tests+// ============================================================++#[tokio::test]+async fn test_delete_persons_small_batch() {+ let ctx = TestContext::new().await;++ let p1 = ctx.insert_person("del_uuid_1", None).await.unwrap();+ let p2 = ctx.insert_person("del_uuid_2", None).await.unwrap();+ let p3 = ctx.insert_person("del_uuid_3", None).await.unwrap();++ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid])+ .await+ .expect("Failed to delete persons");++ assert_eq!(deleted, 2);++ // p1 and p2 gone, p3 remains+ assert!(ctx+ .storage+ .get_person_by_id(ctx.team_id, p1.id)+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_id(ctx.team_id, p2.id)+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_id(ctx.team_id, p3.id)+ .await+ .unwrap()+ .is_some());++ // Distinct IDs for deleted persons should also be gone+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "del_uuid_1")+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "del_uuid_2")+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "del_uuid_3")+ .await+ .unwrap()+ .is_some());++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_empty_uuids() {+ let ctx = TestContext::new().await;+ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[])+ .await+ .expect("Failed to delete persons");+ assert_eq!(deleted, 0);+ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_nonexistent_uuids() {+ let ctx = TestContext::new().await;+ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[Uuid::now_v7(), Uuid::now_v7()])+ .await+ .expect("Failed to delete persons");+ assert_eq!(deleted, 0);+ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_with_multiple_distinct_ids() {+ let ctx = TestContext::new().await;++ let p1 = ctx.insert_person("multi_did_1", None).await.unwrap();+ ctx.add_distinct_id_to_person(p1.id, "multi_did_1b")+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(p1.id, "multi_did_1c")+ .await+ .unwrap();++ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[p1.uuid])+ .await+ .expect("Failed to delete persons");++ assert_eq!(deleted, 1);++ // All three distinct IDs should be gone+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "multi_did_1")+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "multi_did_1b")+ .await+ .unwrap()+ .is_none());+ assert!(ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, "multi_did_1c")+ .await+ .unwrap()+ .is_none());++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_large_batch_triggers_parallel() {+ let ctx = TestContext::new().await;++ // Create 150 persons — with chunk_size=50, this triggers 3 parallel chunks+ let mut uuids = Vec::new();+ for i in 0..150 {+ let p = ctx+ .insert_person(&format!("parallel_del_{i}"), None)+ .await+ .unwrap();+ // Give some persons extra distinct_ids to exercise bin-packing+ if i % 10 == 0 {+ for j in 0..5 {+ ctx.add_distinct_id_to_person(p.id, &format!("parallel_del_{i}_extra_{j}"))+ .await+ .unwrap();+ }+ }+ uuids.push(p.uuid);+ }++ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &uuids)+ .await+ .expect("Failed to delete persons");++ assert_eq!(deleted, 150);++ // Verify all are gone+ for i in 0..150 {+ assert!(+ ctx.storage+ .get_person_by_distinct_id(ctx.team_id, &format!("parallel_del_{i}"))+ .await+ .unwrap()+ .is_none(),+ "Person {i} should have been deleted"+ );+ }++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_batch_for_team_large_batch() {+ let ctx = TestContext::new().await;++ // Create 150 persons. batch_size=100 selects 100, chunk_size=50 means+ // two parallel chunks per call — exercises the parallel delete path.+ for i in 0..150 {+ let p = ctx+ .insert_person(&format!("batch_team_del_{i}"), None)+ .await+ .unwrap();+ if i % 10 == 0 {+ for j in 0..5 {+ ctx.add_distinct_id_to_person(p.id, &format!("batch_team_del_{i}_extra_{j}"))+ .await+ .unwrap();+ }+ }+ }++ // First call: selects and deletes 100 of 150+ let deleted = ctx+ .storage+ .delete_persons_batch_for_team(ctx.team_id, 100)+ .await+ .expect("Failed to delete persons batch");+ assert_eq!(deleted, 100);++ // Second call: deletes the remaining 50+ let deleted = ctx+ .storage+ .delete_persons_batch_for_team(ctx.team_id, 100)+ .await+ .expect("Failed to delete persons batch");+ assert_eq!(deleted, 50);++ // Third call: nothing left+ let remaining = ctx+ .storage+ .delete_persons_batch_for_team(ctx.team_id, 100)+ .await+ .expect("Failed to delete persons batch");+ assert_eq!(remaining, 0);++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_idempotent() {+ let ctx = TestContext::new().await;++ let p1 = ctx.insert_person("idem_1", None).await.unwrap();+ let p2 = ctx.insert_person("idem_2", None).await.unwrap();++ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid])+ .await+ .expect("Failed to delete persons");+ assert_eq!(deleted, 2);++ // Second call with the same UUIDs should be a no-op+ let deleted_again = ctx+ .storage+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid])+ .await+ .expect("Failed to delete persons");+ assert_eq!(deleted_again, 0);++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_cross_team_isolation() {+ let ctx = TestContext::new().await;++ let p1 = ctx.insert_person("cross_team_1", None).await.unwrap();++ // Create a person in a different team+ let other_team_id = ctx.team_id + 1;+ let other_person_id: i64 =+ rand::Rng::gen_range(&mut rand::thread_rng(), 1_000_000..100_000_000);+ let other_uuid = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO posthog_person \+ (id, uuid, team_id, properties, properties_last_updated_at, \+ properties_last_operation, created_at, version, is_identified, is_user_id) \+ VALUES ($1, $2, $3, '{}', '{}', '{}', NOW(), 0, false, NULL) \+ ON CONFLICT DO NOTHING",+ )+ .bind(other_person_id)+ .bind(other_uuid)+ .bind(other_team_id as i32)+ .execute(&ctx.pool)+ .await+ .unwrap();++ // Delete from ctx.team_id — should not touch the other team's person+ let deleted = ctx+ .storage+ .delete_persons(ctx.team_id, &[p1.uuid, other_uuid])+ .await+ .expect("Failed to delete persons");+ assert_eq!(deleted, 1);++ // Other team's person should still exist+ let still_exists = sqlx::query_scalar::<_, i64>(+ "SELECT COUNT(*) FROM posthog_person WHERE team_id = $1 AND uuid = $2",+ )+ .bind(other_team_id as i32)+ .bind(other_uuid)+ .fetch_one(&ctx.pool)+ .await+ .unwrap();+ assert_eq!(still_exists, 1);++ // Cleanup+ sqlx::query("DELETE FROM posthog_person WHERE team_id = $1")+ .bind(other_team_id as i32)+ .execute(&ctx.pool)+ .await+ .ok();+ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_delete_persons_partial_failure_returns_error() {+ let ctx = TestContext::new().await;++ // Create a person and block its deletion with a RESTRICT FK.+ let blocked = ctx.insert_person("blocked_person", None).await.unwrap();+ let normal = ctx.insert_person("normal_person", None).await.unwrap();++ sqlx::query(+ "CREATE TABLE IF NOT EXISTS _test_person_fk_block (+ id SERIAL PRIMARY KEY,+ team_id INTEGER NOT NULL,+ person_id BIGINT NOT NULL,+ FOREIGN KEY (team_id, person_id)+ REFERENCES posthog_person(team_id, id) ON DELETE RESTRICT+ )",+ )+ .execute(&ctx.pool)+ .await+ .expect("Failed to create blocking FK table");++ sqlx::query("INSERT INTO _test_person_fk_block (team_id, person_id) VALUES ($1, $2)")+ .bind(ctx.team_id as i32)+ .bind(blocked.id)+ .execute(&ctx.pool)+ .await+ .expect("Failed to insert blocking reference");++ // The call should return an error because the FK blocks deletion+ let result = ctx+ .storage+ .delete_persons(ctx.team_id, &[blocked.uuid, normal.uuid])+ .await;+ assert!(result.is_err(), "Expected error due to blocked FK");++ // The blocked person should still exist+ assert!(ctx+ .storage+ .get_person_by_id(ctx.team_id, blocked.id)+ .await+ .unwrap()+ .is_some());++ // Cleanup+ sqlx::query("DELETE FROM _test_person_fk_block WHERE team_id = $1")+ .bind(ctx.team_id as i32)+ .execute(&ctx.pool)+ .await+ .ok();+ ctx.cleanup().await.ok();+}