: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
fix(personhog): tombstone by default and reject hard deletes in DeletePersons (#112069)
Eli Reisman937a3707b252
diff --git a/nodejs/src/common/generated/personhog/personhog/service/v1/service_pb.ts b/nodejs/src/common/generated/personhog/personhog/service/v1/service_pb.tsindex 8236fd3fa98e..63a4fb5f0b3b 100644--- a/nodejs/src/common/generated/personhog/personhog/service/v1/service_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/service/v1/service_pb.ts@@ -477,8 +477,8 @@ export const PersonHogService: GenService<{}/*** Person deletes- * DeletePersons removes the persons in any state. A caller working from an advisory- * list of tombstoned persons must use DeleteTombstonedPersons instead, which re-checks+ * DeletePersons tombstones the persons and reports the versions written. A caller that+ * hard-deletes tombstoned persons must use DeleteTombstonedPersons instead, which re-checks* the tombstone under the row lock.* WARNING: This is a write operation on person data. It should route to the leader* once personhog-leader supports deletes. Currently routed through the replicadiff --git a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.tsindex 086286f0810e..fd2f30133adb 100644--- a/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts+++ b/nodejs/src/common/generated/personhog/personhog/types/v1/person_pb.ts@@ -822,7 +822,7 @@ export type DeletePersonsResponse = Message<'personhog.types.v1.DeletePersonsResdeletedCount: bigint/**- * True when the rows were tombstoned rather than removed.+ * True when the rows were tombstoned rather than removed, which is every successful call.** @generated from field: bool tombstoned = 2;*/@@ -833,8 +833,7 @@ export type DeletePersonsResponse = Message<'personhog.types.v1.DeletePersonsRes* versions its rows hold, so the caller can publish its ClickHouse tombstones* at exactly those versions. Persons tombstoned before the call are included* too, so a retry after a lost response gets the same versions again;- * deleted_count counts only the rows this call tombstoned. Empty on a hard- * delete.+ * deleted_count counts only the rows this call tombstoned.** @generated from field: repeated personhog.types.v1.TombstonedPerson tombstones = 3;*/@@ -1873,15 +1872,15 @@ export const FoldPersonDocumentResponseSchema: GenMessage<FoldPersonDocumentResp*/export enum DeletePersonsMode {/**- * Same as HARD.+ * Same as TOMBSTONE.** @generated from enum value: DELETE_PERSONS_MODE_UNSPECIFIED = 0;*/UNSPECIFIED = 0,/**- * Remove the rows, tombstoned ones included. For callers that publish no- * ClickHouse tombstones and want nothing left behind, such as a purge.+ * Rejected with INVALID_ARGUMENT, because a hard delete leaves the live ClickHouse rows above a+ * re-created person's version 0. A deleted team's persons go through DeletePersonsBatchForTeam.** @generated from enum value: DELETE_PERSONS_MODE_HARD = 1;*/diff --git a/packages/personhog-proto/personhog/service/v1/service_pb2_grpc.py b/packages/personhog-proto/personhog/service/v1/service_pb2_grpc.pyindex 8e355f7b97ca..e479a551e23e 100644--- a/packages/personhog-proto/personhog/service/v1/service_pb2_grpc.py+++ b/packages/personhog-proto/personhog/service/v1/service_pb2_grpc.py@@ -588,8 +588,8 @@ class PersonHogServiceServicer:def DeletePersons(self, request, context):"""Person deletes- DeletePersons removes the persons in any state. A caller working from an advisory- list of tombstoned persons must use DeleteTombstonedPersons instead, which re-checks+ DeletePersons tombstones the persons and reports the versions written. A caller that+ hard-deletes tombstoned persons must use DeleteTombstonedPersons instead, which re-checksthe tombstone under the row lock.WARNING: This is a write operation on person data. It should route to the leaderonce personhog-leader supports deletes. Currently routed through the replicadiff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 307a3b9735eb..1cf918ceb91b 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -643,16 +643,15 @@ class FakePersonHogClient:self, request: person_pb2.DeletePersonsRequest, timeout: float | None = None) -> person_pb2.DeletePersonsResponse:self.calls.append(_Call("delete_persons", request))- tombstone = request.mode == person_pb2.DELETE_PERSONS_MODE_TOMBSTONE- response = person_pb2.DeletePersonsResponse(tombstoned=tombstone)+ if request.mode == person_pb2.DELETE_PERSONS_MODE_HARD:+ raise ValueError("DELETE_PERSONS_MODE_HARD is not supported")+ if request.mode not in (person_pb2.DELETE_PERSONS_MODE_UNSPECIFIED, person_pb2.DELETE_PERSONS_MODE_TOMBSTONE):+ raise ValueError(f"Unknown DeletePersonsMode {request.mode}")+ response = person_pb2.DeletePersonsResponse(tombstoned=True)for uuid in request.person_uuids:person = self._persons_by_uuid.get((request.team_id, uuid))if person is None:continue- if not tombstone:- response.deleted_count += 1- self._remove_person(request.team_id, person)- continuetombstoned = response.tombstones.add(person_uuid=person.uuid)if person.is_deleted:# Mirrors the server: an already tombstoned row is reported with the versions itdiff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.pyindex 943186dbb231..98ae4f32f702 100644--- a/posthog/personhog_client/test_fake_client.py+++ b/posthog/personhog_client/test_fake_client.py@@ -623,21 +623,31 @@ class TestFakePersonHogClientDeleteTombstonedPersons:assert resp == person_pb2.DeleteTombstonedPersonsResponse()assert self._present("tombstoned")- def test_delete_persons_still_removes_tombstoned_and_live_alike(self):- resp = self.client.delete_persons(- person_pb2.DeletePersonsRequest(team_id=self.TEAM_ID, person_uuids=["tombstoned", "live", "blocked"])- )+ @pytest.mark.parametrize(+ "mode,message",+ [+ (person_pb2.DELETE_PERSONS_MODE_HARD, "HARD"),+ (99, "Unknown DeletePersonsMode 99"),+ ],+ )+ def test_delete_persons_rejects_hard_and_unknown_modes(self, mode, message):+ with pytest.raises(ValueError, match=message):+ self.client.delete_persons(+ person_pb2.DeletePersonsRequest(team_id=self.TEAM_ID, person_uuids=["live"], mode=mode)+ )- assert resp.deleted_count == 3- for uuid in ("tombstoned", "live", "blocked"):- assert not self._present(uuid)+ stored = self.client.stored_person(self.TEAM_ID, "live")+ assert stored is not None and not stored.is_deleted- def test_delete_persons_tombstone_mode_keeps_rows_and_reports_versions(self):+ @pytest.mark.parametrize(+ "mode", [person_pb2.DELETE_PERSONS_MODE_UNSPECIFIED, person_pb2.DELETE_PERSONS_MODE_TOMBSTONE]+ )+ def test_delete_persons_tombstone_mode_keeps_rows_and_reports_versions(self, mode):resp = self.client.delete_persons(person_pb2.DeletePersonsRequest(team_id=self.TEAM_ID,person_uuids=["live", "tombstoned"],- mode=person_pb2.DELETE_PERSONS_MODE_TOMBSTONE,+ mode=mode,))@@ -652,15 +662,3 @@ class TestFakePersonHogClientDeleteTombstonedPersons:stored = self.client.stored_person(self.TEAM_ID, "live")assert stored is not None and stored.is_deletedassert stored.version == 1-- hard = self.client.delete_persons(- person_pb2.DeletePersonsRequest(- team_id=self.TEAM_ID, person_uuids=["live"], mode=person_pb2.DELETE_PERSONS_MODE_HARD- )- )- assert hard.deleted_count == 1- assert not hard.tombstoned- assert (- self.client.get_person(person_pb2.GetPersonRequest(team_id=self.TEAM_ID, person_id=2)).HasField("person")- is False- )diff --git a/posthog/test/persons.py b/posthog/test/persons.pyindex cdddbf30ff75..2bc08eca8139 100644--- a/posthog/test/persons.py+++ b/posthog/test/persons.py@@ -413,7 +413,6 @@ def delete_person(person: Person) -> None:fake = _get_active_fake()if fake is None:return- from personhog.types.v1 import person_pb2 # noqa: PLC0415dids_with_version = list(fake._distinct_ids.get((person.team_id, person.pk), []))_ch_create_person(@@ -430,7 +429,9 @@ def delete_person(person: Person) -> None:person.team_id, did.distinct_id, str(person.uuid), version=(did.version or 0) + 100, is_deleted=True)- fake.delete_persons(person_pb2.DeletePersonsRequest(team_id=person.team_id, person_uuids=[str(person.uuid)]))+ stored = fake._persons_by_uuid.get((person.team_id, str(person.uuid)))+ if stored is not None:+ fake._remove_person(person.team_id, stored)def update_person(person: Person) -> None:diff --git a/proto/personhog/service/v1/service.proto b/proto/personhog/service/v1/service.protoindex 9793866bfef5..5effd59de556 100644--- a/proto/personhog/service/v1/service.proto+++ b/proto/personhog/service/v1/service.proto@@ -74,8 +74,8 @@ service PersonHogService {rpc FoldPersonDocument(personhog.types.v1.FoldPersonDocumentRequest) returns (personhog.types.v1.FoldPersonDocumentResponse);// Person deletes- // DeletePersons removes the persons in any state. A caller working from an advisory- // list of tombstoned persons must use DeleteTombstonedPersons instead, which re-checks+ // DeletePersons tombstones the persons and reports the versions written. A caller that+ // hard-deletes tombstoned persons must use DeleteTombstonedPersons instead, which re-checks// the tombstone under the row lock.// WARNING: This is a write operation on person data. It should route to the leader// once personhog-leader supports deletes. Currently routed through the replicadiff --git a/proto/personhog/types/v1/person.proto b/proto/personhog/types/v1/person.protoindex 9f50457c2d65..297e593c4352 100644--- a/proto/personhog/types/v1/person.proto+++ b/proto/personhog/types/v1/person.proto@@ -188,10 +188,10 @@ message UpdatePersonPropertiesResponse {// How DeletePersons removes the rows.enum DeletePersonsMode {- // Same as HARD.+ // Same as TOMBSTONE.DELETE_PERSONS_MODE_UNSPECIFIED = 0;- // Remove the rows, tombstoned ones included. For callers that publish no- // ClickHouse tombstones and want nothing left behind, such as a purge.+ // Rejected with INVALID_ARGUMENT, because a hard delete leaves the live ClickHouse rows above a+ // re-created person's version 0. A deleted team's persons go through DeletePersonsBatchForTeam.DELETE_PERSONS_MODE_HARD = 1;// Keep the rows as tombstones and report the versions written. The caller// owns the prerequisite: ingestion must revive tombstones for the team.@@ -221,14 +221,13 @@ message TombstonedPerson {message DeletePersonsResponse {int64 deleted_count = 1;- // True when the rows were tombstoned rather than removed.+ // True when the rows were tombstoned rather than removed, which is every successful call.bool tombstoned = 2;// One entry per requested person that is tombstoned after the call, with the// versions its rows hold, so the caller can publish its ClickHouse tombstones// at exactly those versions. Persons tombstoned before the call are included// too, so a retry after a lost response gets the same versions again;- // deleted_count counts only the rows this call tombstoned. Empty on a hard- // delete.+ // deleted_count counts only the rows this call tombstoned.repeated TombstonedPerson tombstones = 3;}diff --git a/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.json b/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.jsondeleted file mode 100644index dbc3629047b4..000000000000--- a/rust/personhog-replica/.sqlx/query-70cf033a0b9a5823d86ea1833016857e6dac25f5740bc35f0ae291833fd14325.json+++ /dev/null@@ -1,23 +0,0 @@-{- "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/README.md b/rust/personhog-replica/README.mdindex 997e331265c5..f942f0980655 100644--- a/rust/personhog-replica/README.md+++ b/rust/personhog-replica/README.md@@ -8,12 +8,12 @@### Person deletes-`DeletePersons` hard-deletes person and distinct-id rows unless the request asks for `DELETE_PERSONS_MODE_TOMBSTONE`.+`DeletePersons` tombstones person and distinct-id rows, and rejects `DELETE_PERSONS_MODE_HARD` with `INVALID_ARGUMENT`.+A hard delete would leave the live ClickHouse rows above a re-created person's version 0.A tombstone keeps the rows with `is_deleted = true`, the version bumped by one, and person properties scrubbed, and the response reports the versions written so the caller can publish ClickHouse tombstones at exactly those versions.The row's version counter survives, so a later create on the same key revives it above its own ClickHouse tombstone instead of restarting at version 0.The tombstone cleanup drain (`DeleteTombstonedPersons`) removes the rows later, once their ClickHouse history is gone.`DeletePersonsBatchForTeam` always hard-deletes, tombstoned rows included: it serves team teardown, where no sweep would ever clean the tombstones up.-Hard deletes remove tombstoned rows too, so a caller that stops asking for tombstones leaves nothing behind.### Known Implementation Detailsdiff --git a/rust/personhog-replica/src/service/mod.rs b/rust/personhog-replica/src/service/mod.rsindex acfe40dc3940..b8d4b64d2962 100644--- a/rust/personhog-replica/src/service/mod.rs+++ b/rust/personhog-replica/src/service/mod.rs@@ -50,7 +50,6 @@ use personhog_proto::personhog::types::v1::{use tonic::{Request, Response, Status};use uuid::Uuid;-use crate::storage::types::DeletePersonsMode;use crate::storage::{self, FullStorage};const MAX_BATCH_LOOKUP_SIZE: usize = 250;@@ -421,21 +420,24 @@ impl PersonHogReplica for PersonHogReplicaService {.collect::<Result<Vec<_>, _>>().map_err(|e| Status::invalid_argument(format!("Invalid UUID: {e}")))?;- let mode = match ProtoDeletePersonsMode::try_from(req.mode) {- Ok(ProtoDeletePersonsMode::Unspecified) => DeletePersonsMode::Hard,- Ok(ProtoDeletePersonsMode::Hard) => DeletePersonsMode::Hard,- Ok(ProtoDeletePersonsMode::Tombstone) => DeletePersonsMode::Tombstone,+ match ProtoDeletePersonsMode::try_from(req.mode) {+ Ok(ProtoDeletePersonsMode::Unspecified | ProtoDeletePersonsMode::Tombstone) => {}+ Ok(ProtoDeletePersonsMode::Hard) => {+ return Err(Status::invalid_argument(+ "DELETE_PERSONS_MODE_HARD is not supported: tombstone the persons, or delete a deleted team's persons with DeletePersonsBatchForTeam",+ ))+ }Err(_) => {return Err(Status::invalid_argument(format!("Unknown DeletePersonsMode {}",req.mode)))}- };+ }let outcome = self.storage- .delete_persons(req.team_id, &uuids, mode)+ .delete_persons(req.team_id, &uuids).await.map_err(|e| log_and_convert_error(e, "delete_persons"))?;diff --git a/rust/personhog-replica/src/service/tests/mocks.rs b/rust/personhog-replica/src/service/tests/mocks.rsindex dc562c73dfe7..d3dcfc40082e 100644--- a/rust/personhog-replica/src/service/tests/mocks.rs+++ b/rust/personhog-replica/src/service/tests/mocks.rs@@ -95,7 +95,6 @@ impl storage::PersonLookup for FailingStorage {&self,_team_id: i64,_uuids: &[Uuid],- _mode: storage::DeletePersonsMode,) -> storage::StorageResult<storage::DeletePersonsOutcome> {Err(self.error.clone())}@@ -509,7 +508,6 @@ impl storage::PersonLookup for SuccessStorage {&self,_team_id: i64,_uuids: &[Uuid],- _mode: storage::DeletePersonsMode,) -> storage::StorageResult<storage::DeletePersonsOutcome> {Ok(storage::DeletePersonsOutcome::default())}@@ -982,7 +980,6 @@ impl storage::PersonLookup for PopulatedStorage {&self,_team_id: i64,_uuids: &[Uuid],- _mode: storage::DeletePersonsMode,) -> storage::StorageResult<storage::DeletePersonsOutcome> {Ok(storage::DeletePersonsOutcome::default())}@@ -1431,7 +1428,6 @@ impl storage::PersonLookup for ConsistencyTrackingStorage {&self,_team_id: i64,_uuids: &[Uuid],- _mode: storage::DeletePersonsMode,) -> storage::StorageResult<storage::DeletePersonsOutcome> {Ok(storage::DeletePersonsOutcome::default())}diff --git a/rust/personhog-replica/src/storage/mod.rs b/rust/personhog-replica/src/storage/mod.rsindex afef277b144c..0c1b357efa79 100644--- a/rust/personhog-replica/src/storage/mod.rs+++ b/rust/personhog-replica/src/storage/mod.rs@@ -6,10 +6,9 @@ pub mod types;pub use error::{StorageError, StorageResult};pub use types::{- CohortMembership, DeletePersonsMode, DeletePersonsOutcome, DistinctIdMapping,- DistinctIdWithVersion, Group, GroupIdentifier, GroupKey, GroupTypeMapping, HashKeyOverride,- HashKeyOverrideContext, Person, SplitResult, TombstonedDeleteOutcome, TombstonedDistinctId,- TombstonedPerson,+ CohortMembership, DeletePersonsOutcome, DistinctIdMapping, DistinctIdWithVersion, Group,+ GroupIdentifier, GroupKey, GroupTypeMapping, HashKeyOverride, HashKeyOverrideContext, Person,+ SplitResult, TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,};pub use traits::{CohortStorage, DistinctIdLookup, FeatureFlagStorage, GroupStorage, PersonLookup};diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 46e03390cf4c..d96e5b43acb6 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -13,8 +13,8 @@ use super::{PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNEDuse crate::storage::error::{StorageError, StorageResult};use crate::storage::traits::PersonLookup;use crate::storage::types::{- DeletePersonsMode, DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult,- TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,+ DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult, TombstonedDeleteOutcome,+ TombstonedDistinctId, TombstonedPerson,};/// Version offset for split person/PDI rows — mirrors the Django convention.@@ -421,7 +421,6 @@ impl PersonLookup for PostgresStorage {&self,team_id: i64,uuids: &[Uuid],- mode: DeletePersonsMode,) -> StorageResult<DeletePersonsOutcome> {if uuids.is_empty() {return Ok(DeletePersonsOutcome::default());@@ -437,61 +436,7 @@ impl PersonLookup for PostgresStorage {];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- if mode == DeletePersonsMode::Tombstone {- return tombstone_persons_by_uuids(self, team_id, uuids, &client).await;- }-- // Resolve UUIDs to integer IDs in one query, then chunk and delete- // by ID. This avoids scanning the UUID index per-chunk.- let mut person_ids: Vec<i64> = sqlx::query_scalar!(- r#"- SELECT id::bigint as "id!" FROM posthog_person- WHERE team_id = $1 AND uuid = ANY($2)- "#,- team_id as i32,- uuids- )- .fetch_all(&self.bulk_primary_pool)- .await?;-- if person_ids.is_empty() {- return Ok(DeletePersonsOutcome::default());- }- person_ids.sort_unstable();-- // 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_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();- // 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(DeletePersonsOutcome {- deleted: results.iter().sum(),- tombstones: None,- })+ tombstone_persons_by_uuids(self, team_id, uuids, &client).await}async fn delete_persons_batch_for_team(diff --git a/rust/personhog-replica/src/storage/traits/person.rs b/rust/personhog-replica/src/storage/traits/person.rsindex 306821fef916..d6d7684e8fa6 100644--- a/rust/personhog-replica/src/storage/traits/person.rs+++ b/rust/personhog-replica/src/storage/traits/person.rs@@ -3,8 +3,8 @@ use uuid::Uuid;use crate::storage::error::StorageResult;use crate::storage::types::{- DeletePersonsMode, DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult,- TombstonedDeleteOutcome, TombstonedPerson,+ DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult, TombstonedDeleteOutcome,+ TombstonedPerson,};/// Person lookup operations by ID, UUID, and distinct ID@@ -54,13 +54,11 @@ pub trait PersonLookup: Send + Sync {// Deletes- /// `Hard` removes the rows, tombstoned ones included. `Tombstone` keeps- /// them and reports the versions written for the ClickHouse tombstones.+ /// Tombstones the persons and reports the versions written for the ClickHouse tombstones.async fn delete_persons(&self,team_id: i64,uuids: &[Uuid],- mode: DeletePersonsMode,) -> StorageResult<DeletePersonsOutcome>;/// Delete persons that are still tombstoned, at most `max_rows` dependent rows per call:diff --git a/rust/personhog-replica/src/storage/types/person.rs b/rust/personhog-replica/src/storage/types/person.rsindex b8932278d092..69c1955dda24 100644--- a/rust/personhog-replica/src/storage/types/person.rs+++ b/rust/personhog-replica/src/storage/types/person.rs@@ -16,14 +16,6 @@ pub struct DistinctIdWithVersion {pub id: i64,}-/// How DeletePersons removes rows. A caller that publishes ClickHouse tombstones-/// asks for `Tombstone` and reads the versions back; everything else hard-deletes.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum DeletePersonsMode {- Hard,- Tombstone,-}-#[derive(Debug, Clone, PartialEq, Eq)]pub struct TombstonedDistinctId {pub distinct_id: String,diff --git a/rust/personhog-replica/tests/service_tests.rs b/rust/personhog-replica/tests/service_tests.rsindex fd9c40c8a41d..0a45daa27022 100644--- a/rust/personhog-replica/tests/service_tests.rs+++ b/rust/personhog-replica/tests/service_tests.rs@@ -1427,8 +1427,11 @@ async fn test_delete_tombstoned_persons_reports_each_outcome(ctx.cleanup().await.ok();}+#[rstest]+#[case::unspecified(DeletePersonsMode::Unspecified as i32)]+#[case::tombstone(DeletePersonsMode::Tombstone as i32)]#[tokio::test]-async fn test_delete_persons_tombstone_mode_reports_versions() {+async fn test_delete_persons_tombstone_mode_reports_versions(#[case] mode: i32) {let ctx = ServiceTestContext::new().await;let person = ctx.insert_person("svc_tomb_mode", None).await.unwrap();@@ -1437,7 +1440,7 @@ async fn test_delete_persons_tombstone_mode_reports_versions() {.delete_persons(Request::new(DeletePersonsRequest {team_id: ctx.team_id,person_uuids: vec![person.uuid.to_string()],- mode: DeletePersonsMode::Tombstone as i32,+ mode,})).await.expect("RPC failed")@@ -1455,37 +1458,31 @@ async fn test_delete_persons_tombstone_mode_reports_versions() {);assert_eq!(response.tombstones[0].distinct_ids[0].version, 1);- // A hard delete reports no versions and removes the tombstone.- let response = ctx- .service- .delete_persons(Request::new(DeletePersonsRequest {- team_id: ctx.team_id,- person_uuids: vec![person.uuid.to_string()],- mode: DeletePersonsMode::Hard as i32,- }))- .await- .expect("RPC failed")- .into_inner();- assert_eq!(response.deleted_count, 1);- assert!(!response.tombstoned);- assert!(response.tombstones.is_empty());-ctx.cleanup().await.ok();}+#[rstest]+#[case::hard(DeletePersonsMode::Hard as i32)]+#[case::unknown(99)]#[tokio::test]-async fn test_delete_persons_rejects_an_unknown_mode() {+async fn test_delete_persons_rejects_unsupported_modes(#[case] mode: i32) {let ctx = ServiceTestContext::new().await;+ let person = ctx.insert_person("svc_rejected_mode", None).await.unwrap();+let status = ctx.service.delete_persons(Request::new(DeletePersonsRequest {team_id: ctx.team_id,- person_uuids: vec![Uuid::now_v7().to_string()],- mode: 99,+ person_uuids: vec![person.uuid.to_string()],+ mode,})).await.unwrap_err();+assert_eq!(status.code(), tonic::Code::InvalidArgument);+ assert!(ctx.person_row_exists(person.id).await.unwrap());+ assert_eq!(ctx.distinct_id_row_count(person.id).await.unwrap(), 1);+ctx.cleanup().await.ok();}diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex 05ae70b1a893..d09f4851eaf7 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -4,7 +4,7 @@ use common::TestContext;use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};use personhog_replica::storage::postgres::ConsistencyLevel;use personhog_replica::storage::{- DeletePersonsMode, GroupKey, TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,+ GroupKey, TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,};use rand::Rng;use rstest::rstest;@@ -398,7 +398,7 @@ async fn test_delete_persons_clears_cohort_memberships() {let deleted = ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[person.uuid]).await.expect("delete persons").deleted;@@ -470,7 +470,7 @@ async fn test_delete_persons_tombstone_mode_keeps_the_rows() {let deleted = ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.expect("delete persons").deleted;@@ -510,7 +510,7 @@ async fn test_delete_persons_tombstone_mode_keeps_the_rows() {// Deleting again is a no-op: no second version bump.let deleted = ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.unwrap().deleted;@@ -588,11 +588,7 @@ async fn test_delete_persons_tombstone_mode_waits_for_an_inflight_attach_and_tomlet storage = ctx.storage.clone();let team_id = ctx.team_id;let uuid = person.uuid;- let delete = tokio::spawn(async move {- storage- .delete_persons(team_id, &[uuid], DeletePersonsMode::Tombstone)- .await- });+ let delete = tokio::spawn(async move { storage.delete_persons(team_id, &[uuid]).await });// Commit the attach only once the delete waits on the mark, so the delete cannot finish first.wait_for_a_mark_claim_blocked_by(&ctx.pool, attach_pid).await;@@ -652,11 +648,7 @@ async fn test_delete_persons_tombstone_mode_leaves_a_person_created_after_the_cllet storage = ctx.storage.clone();let team_id = ctx.team_id;let uuids = [held.uuid, recreated_uuid];- let delete = tokio::spawn(async move {- storage- .delete_persons(team_id, &uuids, DeletePersonsMode::Tombstone)- .await- });+ let delete = tokio::spawn(async move { storage.delete_persons(team_id, &uuids).await });// Create the second person only after the delete's claim read missed it.wait_for_a_mark_claim_blocked_by(&ctx.pool, holder_pid).await;@@ -690,11 +682,7 @@ async fn test_delete_persons_tombstone_mode_fails_when_a_lifecycle_op_holds_the_let result = ctx.storage- .delete_persons(- ctx.team_id,- &[held.uuid, free.uuid],- DeletePersonsMode::Tombstone,- )+ .delete_persons(ctx.team_id, &[held.uuid, free.uuid]).await;assert!(@@ -724,7 +712,7 @@ async fn test_delete_persons_tombstone_mode_reports_the_versions() {let outcome = ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.unwrap();@@ -762,7 +750,7 @@ async fn test_delete_persons_tombstone_mode_reports_versions_again_on_retry() {let first = ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.unwrap();// A caller that lost the first response must get the same versions back, or@@ -770,11 +758,7 @@ async fn test_delete_persons_tombstone_mode_reports_versions_again_on_retry() {// request is tombstoned and counted; the earlier one is reported, not counted.let retry = ctx.storage- .delete_persons(- ctx.team_id,- &[person.uuid, live.uuid],- DeletePersonsMode::Tombstone,- )+ .delete_persons(ctx.team_id, &[person.uuid, live.uuid]).await.unwrap();@@ -812,7 +796,7 @@ async fn test_delete_persons_tombstone_mode_requeues_a_revived_person() {let ctx = TestContext::new().await;let person = ctx.insert_person("requeue", None).await.unwrap();ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.unwrap();sqlx::query(@@ -839,7 +823,7 @@ async fn test_delete_persons_tombstone_mode_requeues_a_revived_person() {}ctx.storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &[person.uuid]).await.unwrap();@@ -861,11 +845,7 @@ async fn test_ack_person_tombstones_clears_only_rows_at_or_below_the_acked_versilet acked = ctx.insert_person("ack_delivered", None).await.unwrap();let stale = ctx.insert_person("ack_stale", None).await.unwrap();ctx.storage- .delete_persons(- ctx.team_id,- &[acked.uuid, stale.uuid],- DeletePersonsMode::Tombstone,- )+ .delete_persons(ctx.team_id, &[acked.uuid, stale.uuid]).await.unwrap();@@ -895,7 +875,7 @@ async fn test_list_person_tombstone_queue_pages_in_key_order() {uuids.push(ctx.insert_person(name, None).await.unwrap().uuid);}ctx.storage- .delete_persons(ctx.team_id, &uuids, DeletePersonsMode::Tombstone)+ .delete_persons(ctx.team_id, &uuids).await.unwrap();uuids.sort();@@ -933,11 +913,7 @@ async fn test_get_person_tombstones_reports_only_tombstoned_persons() {let live = ctx.insert_person("get_live", None).await.unwrap();let deleted = ctx.storage- .delete_persons(- ctx.team_id,- &[tombstoned.uuid],- DeletePersonsMode::Tombstone,- )+ .delete_persons(ctx.team_id, &[tombstoned.uuid]).await.unwrap();@@ -957,35 +933,13 @@ async fn test_get_person_tombstones_reports_only_tombstoned_persons() {ctx.cleanup().await.ok();}-#[tokio::test]-async fn test_delete_persons_hard_mode_reports_no_versions() {- let ctx = TestContext::new().await;- let person = ctx.insert_person("hard_mode", None).await.unwrap();-- let outcome = ctx- .storage- .delete_persons(ctx.team_id, &[person.uuid], DeletePersonsMode::Hard)- .await- .unwrap();-- assert_eq!(outcome.deleted, 1);- assert_eq!(outcome.tombstones, None);- assert!(!ctx.person_row_exists(person.id).await.unwrap());-- ctx.cleanup().await.ok();-}-#[tokio::test]async fn test_delete_persons_batch_for_team_removes_tombstoned_rows() {let ctx = TestContext::new().await;let live = ctx.insert_person("batch_live", None).await.unwrap();let tombstoned = ctx.insert_person("batch_tombstoned", None).await.unwrap();ctx.storage- .delete_persons(- ctx.team_id,- &[tombstoned.uuid],- DeletePersonsMode::Tombstone,- )+ .delete_persons(ctx.team_id, &[tombstoned.uuid]).await.unwrap();let (is_deleted, _, _, _) = tombstone_state(&ctx.pool, ctx.team_id, tombstoned.id).await;@@ -2004,7 +1958,7 @@ async fn test_delete_persons_small_batch() {let deleted = ctx.storage- .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid]).await.expect("Failed to delete persons").deleted;@@ -2059,7 +2013,7 @@ async fn test_delete_persons_empty_uuids() {let ctx = TestContext::new().await;let deleted = ctx.storage- .delete_persons(ctx.team_id, &[], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[]).await.expect("Failed to delete persons").deleted;@@ -2072,11 +2026,7 @@ 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()],- DeletePersonsMode::Hard,- )+ .delete_persons(ctx.team_id, &[Uuid::now_v7(), Uuid::now_v7()]).await.expect("Failed to delete persons").deleted;@@ -2098,7 +2048,7 @@ async fn test_delete_persons_with_multiple_distinct_ids() {let deleted = ctx.storage- .delete_persons(ctx.team_id, &[p1.uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[p1.uuid]).await.expect("Failed to delete persons").deleted;@@ -2129,30 +2079,32 @@ async fn test_delete_persons_with_multiple_distinct_ids() {}#[tokio::test]-async fn test_delete_persons_large_batch_triggers_parallel() {+async fn test_delete_persons_large_batch_tombstones_every_chunk() {let ctx = TestContext::new().await;- // Create 150 persons — with chunk_size=50, this triggers 3 parallel chunks+ // 150 persons with chunk_size=50 make 3 chunks in one transaction.let mut uuids = Vec::new();+ let mut persons_with_extra_ids = Vec::new();for i in 0..150 {let p = ctx- .insert_person(&format!("parallel_del_{i}"), None)+ .insert_person(&format!("large_batch_del_{i}"), None).await.unwrap();// Give some persons extra distinct_ids to exercise bin-packingif i % 10 == 0 {for j in 0..5 {- ctx.add_distinct_id_to_person(p.id, &format!("parallel_del_{i}_extra_{j}"))+ ctx.add_distinct_id_to_person(p.id, &format!("large_batch_del_{i}_extra_{j}")).await.unwrap();}+ persons_with_extra_ids.push(p.id);}uuids.push(p.uuid);}let deleted = ctx.storage- .delete_persons(ctx.team_id, &uuids, DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &uuids).await.expect("Failed to delete persons").deleted;@@ -2163,7 +2115,7 @@ async fn test_delete_persons_large_batch_triggers_parallel() {for i in 0..150 {assert!(ctx.storage- .get_person_by_distinct_id(ctx.team_id, &format!("parallel_del_{i}"))+ .get_person_by_distinct_id(ctx.team_id, &format!("large_batch_del_{i}")).await.unwrap().is_none(),@@ -2171,6 +2123,17 @@ async fn test_delete_persons_large_batch_triggers_parallel() {);}+ for person_id in persons_with_extra_ids {+ let (is_deleted, _, _, distinct_ids) =+ tombstone_state(&ctx.pool, ctx.team_id, person_id).await;+ assert!(is_deleted, "Person {person_id} should be tombstoned");+ assert_eq!(distinct_ids.len(), 6);+ assert!(+ distinct_ids.iter().all(|(is_deleted, _)| *is_deleted),+ "Every distinct id of person {person_id} should be tombstoned"+ );+ }+ctx.cleanup().await.ok();}@@ -2230,7 +2193,7 @@ async fn test_delete_persons_idempotent() {let deleted = ctx.storage- .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid]).await.expect("Failed to delete persons").deleted;@@ -2239,7 +2202,7 @@ async fn test_delete_persons_idempotent() {// Second call with the same UUIDs should be a no-oplet deleted_again = ctx.storage- .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[p1.uuid, p2.uuid]).await.expect("Failed to delete persons").deleted;@@ -2276,7 +2239,7 @@ async fn test_delete_persons_cross_team_isolation() {// Delete from ctx.team_id — should not touch the other team's personlet deleted = ctx.storage- .delete_persons(ctx.team_id, &[p1.uuid, other_uuid], DeletePersonsMode::Hard)+ .delete_persons(ctx.team_id, &[p1.uuid, other_uuid]).await.expect("Failed to delete persons").deleted;@@ -2302,62 +2265,6 @@ async fn test_delete_persons_cross_team_isolation() {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],- DeletePersonsMode::Hard,- )- .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();-}-// ============================================================// Bulk read chunking tests — exercise the parallel path// (test chunk_size=50, so >50 items triggers chunking)