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(personhog): claim lifecycle marks in the tombstone rpc (#111444)

Eli Reismand72221936fb8
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 5c9a907fe871..26b7bf30b6b3 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -195,6 +195,8 @@ export type IngestionConsumerConfig = {
// Teams whose merges and deletes tombstone the person row instead of hard-deleting it, and
// whose creates revive a tombstoned key. Every environment rolled this out to all teams, so
// '*' is the default. Comma-separated team IDs, or '*' for all teams; empty means no teams.
+ // Teams off this list attach distinct ids without lifecycle marks. Personhog's tombstone RPC
+ // cannot coordinate with those attaches, so a delete can leave a live mapping on a deleted person.
PERSON_MERGE_TOMBSTONE_TEAM_ALLOWLIST: string
// Teams whose merges lock the person rows and write the survivor in the transaction; other teams queue it for
// the next flush. Enable after PERSON_BATCH_WRITING_PER_KEY_TEAM_ALLOWLIST. Team IDs, or '*'; empty means none.
diff --git a/rust/personhog-replica/.sqlx/query-138b31578ae24294373586142495b6fef5a1750e00e4797687861e4d0f1be82a.json b/rust/personhog-replica/.sqlx/query-138b31578ae24294373586142495b6fef5a1750e00e4797687861e4d0f1be82a.json
new file mode 100644
index 000000000000..b0642aac9ba6
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-138b31578ae24294373586142495b6fef5a1750e00e4797687861e4d0f1be82a.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM lifecycle_op\n WHERE op_id = $1 AND team_id = $2 AND op_type = 'delete'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "138b31578ae24294373586142495b6fef5a1750e00e4797687861e4d0f1be82a"
+}
diff --git a/rust/personhog-replica/.sqlx/query-3958235ea0ab256afb58556c5f7313160896606e08c7817540378491f9e29cd5.json b/rust/personhog-replica/.sqlx/query-3958235ea0ab256afb58556c5f7313160896606e08c7817540378491f9e29cd5.json
new file mode 100644
index 000000000000..b0385c835c64
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-3958235ea0ab256afb58556c5f7313160896606e08c7817540378491f9e29cd5.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, completed_at)\n VALUES ($1, 'delete', $2, 'completed', '{\"source\": \"personhog-replica-tombstone\"}'::jsonb, now())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3958235ea0ab256afb58556c5f7313160896606e08c7817540378491f9e29cd5"
+}
diff --git a/rust/personhog-replica/.sqlx/query-cea479ca77f0858695cec9eb21dafcc12bc2ecbfc9afc664fe9da195dbf48d54.json b/rust/personhog-replica/.sqlx/query-cea479ca77f0858695cec9eb21dafcc12bc2ecbfc9afc664fe9da195dbf48d54.json
new file mode 100644
index 000000000000..59a518ece7ce
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-cea479ca77f0858695cec9eb21dafcc12bc2ecbfc9afc664fe9da195dbf48d54.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ORDER BY id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uuid!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "cea479ca77f0858695cec9eb21dafcc12bc2ecbfc9afc664fe9da195dbf48d54"
+}
diff --git a/rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.json b/rust/personhog-replica/.sqlx/query-e6869d827b4d4d6e025415989e567c8ebc9c0410e13b35c31e7e9a4e064e8dc3.json
similarity index 80%
rename from rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.json
rename to rust/personhog-replica/.sqlx/query-e6869d827b4d4d6e025415989e567c8ebc9c0410e13b35c31e7e9a4e064e8dc3.json
index 6db73d6cdcc0..df551cd9fddc 100644
--- a/rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.json
+++ b/rust/personhog-replica/.sqlx/query-e6869d827b4d4d6e025415989e567c8ebc9c0410e13b35c31e7e9a4e064e8dc3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\",\n COALESCE(version, 0)::bigint as \"version!\", is_deleted as \"is_deleted!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ORDER BY id FOR UPDATE\n ",
+ "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\",\n COALESCE(version, 0)::bigint as \"version!\", is_deleted as \"is_deleted!\"\n FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2)\n ORDER BY id FOR UPDATE\n ",
"describe": {
"columns": [
{
@@ -27,7 +27,7 @@
"parameters": {
"Left": [
"Int4",
- "UuidArray"
+ "Int8Array"
]
},
"nullable": [
@@ -37,5 +37,5 @@
false
]
},
- "hash": "addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db"
+ "hash": "e6869d827b4d4d6e025415989e567c8ebc9c0410e13b35c31e7e9a4e064e8dc3"
}
diff --git a/rust/personhog-replica/.sqlx/query-eda7c405df055017ede90ed0c4ae242eca48b0565e2e4f0b5e58c1889c4a3e13.json b/rust/personhog-replica/.sqlx/query-eda7c405df055017ede90ed0c4ae242eca48b0565e2e4f0b5e58c1889c4a3e13.json
new file mode 100644
index 000000000000..f104dac2bf3a
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-eda7c405df055017ede90ed0c4ae242eca48b0565e2e4f0b5e58c1889c4a3e13.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status, mark_active)\n SELECT $1, $2, u.person_id, u.person_uuid, 'victim', 'marked', true\n FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)\n ON CONFLICT (team_id, person_id) WHERE mark_active DO NOTHING\n RETURNING person_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4",
+ "Int8Array",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "eda7c405df055017ede90ed0c4ae242eca48b0565e2e4f0b5e58c1889c4a3e13"
+}
diff --git a/rust/personhog-replica/src/service/error.rs b/rust/personhog-replica/src/service/error.rs
index eefba56a32c4..0b41a1153f57 100644
--- a/rust/personhog-replica/src/service/error.rs
+++ b/rust/personhog-replica/src/service/error.rs
@@ -1,6 +1,6 @@
use personhog_common::grpc::current_client_name;
use tonic::Status;
-use tracing::error;
+use tracing::{error, warn};
use crate::storage;
@@ -49,6 +49,57 @@ pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Sta
Status::internal(format!("Database error: {msg}"))
}
storage::StorageError::NotFound(msg) => Status::not_found(msg.clone()),
- storage::StorageError::FailedPrecondition(msg) => Status::failed_precondition(msg.clone()),
+ storage::StorageError::FailedPrecondition(msg) => {
+ warn!(operation, error = %msg, "Failed precondition");
+ common_metrics::inc(
+ STORAGE_ERRORS_TOTAL,
+ &[
+ ("error_type".to_string(), "failed_precondition".to_string()),
+ ("operation".to_string(), operation.to_string()),
+ ("client".to_string(), client.to_string()),
+ ],
+ 1,
+ );
+ Status::failed_precondition(msg.clone())
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};
+ use tonic::Code;
+
+ use super::*;
+
+ #[test]
+ fn failed_precondition_is_counted() {
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ let _guard = metrics::set_default_local_recorder(&recorder);
+
+ let status = log_and_convert_error(
+ storage::StorageError::FailedPrecondition("persons are claimed".to_string()),
+ "delete_persons",
+ );
+
+ assert_eq!(status.code(), Code::FailedPrecondition);
+ let counted: u64 = snapshotter
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .filter(|(key, _, _, _)| {
+ key.key().name() == STORAGE_ERRORS_TOTAL
+ && key
+ .key()
+ .labels()
+ .any(|l| l.key() == "error_type" && l.value() == "failed_precondition")
+ })
+ .map(|(_, _, _, value)| match value {
+ DebugValue::Counter(n) => n,
+ _ => 0,
+ })
+ .sum();
+ assert_eq!(counted, 1);
}
}
diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rs
index 592a21069841..46e03390cf4c 100644
--- a/rust/personhog-replica/src/storage/postgres/person.rs
+++ b/rust/personhog-replica/src/storage/postgres/person.rs
@@ -1358,18 +1358,20 @@ async fn tombstone_persons_by_uuids(
.execute(&mut *tx)
.await?;
- // Lock every requested person up front, in id order, the order the
- // ingestion writer and the tombstone drain take their locks in.
+ let (mark_op_id, claimed_ids) = claim_delete_marks(&mut tx, team_id, uuids).await?;
+
+ // Lock the claimed persons up front in id order, as the ingestion writer and the tombstone cleanup drain do.
+ // Lock by id, not uuid: a person re-created under a requested uuid after the claim holds no mark.
let rows = sqlx::query!(
r#"
SELECT id::bigint as "id!", uuid as "uuid!",
COALESCE(version, 0)::bigint as "version!", is_deleted as "is_deleted!"
FROM posthog_person
- WHERE team_id = $1 AND uuid = ANY($2)
+ WHERE team_id = $1 AND id = ANY($2)
ORDER BY id FOR UPDATE
"#,
team_id as i32,
- uuids
+ &claimed_ids
)
.fetch_all(&mut *tx)
.await?;
@@ -1427,6 +1429,9 @@ async fn tombstone_persons_by_uuids(
tombstones.extend(with_tombstoned_distinct_ids(&mut tx, team_id, already).await?);
+ if let Some(op_id) = mark_op_id {
+ release_delete_marks(&mut tx, team_id, op_id).await?;
+ }
tx.commit().await?;
tombstones.sort_by(|a, b| a.uuid.cmp(&b.uuid));
Ok(DeletePersonsOutcome {
@@ -1435,6 +1440,88 @@ async fn tombstone_persons_by_uuids(
})
}
+/// The person row lock cannot stop an ingestion attach, whose FK check passes on a tombstone, so the
+/// attach re-checks liveness under this mark; claims go in id order, as ingestion's do, to avoid deadlock.
+/// A mark held elsewhere fails the whole call, because the caller reads a missing person as already gone.
+async fn claim_delete_marks(
+ tx: &mut Transaction<'_, Postgres>,
+ team_id: i64,
+ uuids: &[Uuid],
+) -> StorageResult<(Option<Uuid>, Vec<i64>)> {
+ let persons = sqlx::query!(
+ r#"
+ SELECT id::bigint as "id!", uuid as "uuid!"
+ FROM posthog_person
+ WHERE team_id = $1 AND uuid = ANY($2)
+ ORDER BY id
+ "#,
+ team_id as i32,
+ uuids
+ )
+ .fetch_all(&mut **tx)
+ .await?;
+ if persons.is_empty() {
+ return Ok((None, Vec::new()));
+ }
+
+ let op_id = Uuid::new_v4();
+ sqlx::query!(
+ r#"
+ INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, completed_at)
+ VALUES ($1, 'delete', $2, 'completed', '{"source": "personhog-replica-tombstone"}'::jsonb, now())
+ "#,
+ op_id,
+ team_id as i32
+ )
+ .execute(&mut **tx)
+ .await?;
+
+ let person_ids: Vec<i64> = persons.iter().map(|p| p.id).collect();
+ let person_uuids: Vec<Uuid> = persons.iter().map(|p| p.uuid).collect();
+ let claimed = sqlx::query_scalar!(
+ r#"
+ INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status, mark_active)
+ SELECT $1, $2, u.person_id, u.person_uuid, 'victim', 'marked', true
+ FROM unnest($3::bigint[], $4::uuid[]) AS u(person_id, person_uuid)
+ ON CONFLICT (team_id, person_id) WHERE mark_active DO NOTHING
+ RETURNING person_id
+ "#,
+ op_id,
+ team_id as i32,
+ &person_ids,
+ &person_uuids
+ )
+ .fetch_all(&mut **tx)
+ .await?;
+
+ if claimed.len() != persons.len() {
+ return Err(StorageError::FailedPrecondition(format!(
+ "{} of {} persons are claimed by another lifecycle operation",
+ persons.len() - claimed.len(),
+ persons.len()
+ )));
+ }
+ Ok((Some(op_id), person_ids))
+}
+
+async fn release_delete_marks(
+ tx: &mut Transaction<'_, Postgres>,
+ team_id: i64,
+ op_id: Uuid,
+) -> StorageResult<()> {
+ sqlx::query!(
+ r#"
+ DELETE FROM lifecycle_op
+ WHERE op_id = $1 AND team_id = $2 AND op_type = 'delete'
+ "#,
+ op_id,
+ team_id as i32
+ )
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
+
/// Tombstone one chunk of persons inside the caller's transaction: their
/// rows get `is_deleted = true` and version + 1, properties scrubbed. The rows
/// stay so a later create on the same key revives above this version.
diff --git a/rust/personhog-replica/tests/common/mod.rs b/rust/personhog-replica/tests/common/mod.rs
index b6a702b79640..42d9cff7079d 100644
--- a/rust/personhog-replica/tests/common/mod.rs
+++ b/rust/personhog-replica/tests/common/mod.rs
@@ -51,9 +51,18 @@ impl TestContext {
&self,
distinct_id: &str,
properties: Option<serde_json::Value>,
+ ) -> Result<TestPerson, sqlx::Error> {
+ self.insert_person_with_uuid(distinct_id, properties, Uuid::now_v7())
+ .await
+ }
+
+ pub async fn insert_person_with_uuid(
+ &self,
+ distinct_id: &str,
+ properties: Option<serde_json::Value>,
+ uuid: Uuid,
) -> Result<TestPerson, sqlx::Error> {
let person_id = random_person_id();
- let uuid = Uuid::now_v7();
let properties = properties.unwrap_or_else(|| serde_json::json!({}));
sqlx::query(
@@ -299,6 +308,11 @@ impl TestContext {
}
pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
+ sqlx::query("DELETE FROM lifecycle_op WHERE team_id = $1")
+ .bind(self.team_id)
+ .execute(&self.pool)
+ .await?;
+
sqlx::query("DELETE FROM person_tombstone_publish_queue WHERE team_id = $1")
.bind(self.team_id)
.execute(&self.pool)
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index d2ecb27331c9..05ae70b1a893 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -518,6 +518,199 @@ async fn test_delete_persons_tombstone_mode_keeps_the_rows() {
let (_, version, _, _) = tombstone_state(&ctx.pool, ctx.team_id, person.id).await;
assert_eq!(version, 1);
+ assert_eq!(lifecycle_op_count(&ctx.pool, ctx.team_id).await, 0);
+
+ ctx.cleanup().await.ok();
+}
+
+async fn lifecycle_op_count(pool: &sqlx::PgPool, team_id: i64) -> i64 {
+ sqlx::query_scalar("SELECT count(*) FROM lifecycle_op WHERE team_id = $1")
+ .bind(team_id)
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+async fn claim_merge_mark(
+ conn: &mut sqlx::PgConnection,
+ team_id: i64,
+ person: &common::TestPerson,
+) -> Uuid {
+ let op_id = Uuid::new_v4();
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, request, completed_at)
+ VALUES ($1, 'merge', $2, 'completed', '{}'::jsonb, now())",
+ )
+ .bind(op_id)
+ .bind(team_id as i32)
+ .execute(&mut *conn)
+ .await
+ .unwrap();
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status, mark_active)
+ VALUES ($1, $2, $3, $4, 'target', 'marked', true)",
+ )
+ .bind(op_id)
+ .bind(team_id as i32)
+ .bind(person.id)
+ .bind(person.uuid)
+ .execute(&mut *conn)
+ .await
+ .unwrap();
+ op_id
+}
+
+#[tokio::test]
+async fn test_delete_persons_tombstone_mode_waits_for_an_inflight_attach_and_tombstones_it() {
+ let ctx = TestContext::new().await;
+ let person = ctx.insert_person("attach_race_a", None).await.unwrap();
+
+ let mut attach = ctx.pool.begin().await.unwrap();
+ let attach_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
+ .fetch_one(&mut *attach)
+ .await
+ .unwrap();
+ let op_id = claim_merge_mark(&mut attach, ctx.team_id, &person).await;
+ sqlx::query(
+ "INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version) VALUES ('attach_race_b', $1, $2, 1)",
+ )
+ .bind(person.id)
+ .bind(ctx.team_id)
+ .execute(&mut *attach)
+ .await
+ .unwrap();
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .execute(&mut *attach)
+ .await
+ .unwrap();
+
+ let 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
+ });
+
+ // 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;
+ attach.commit().await.unwrap();
+
+ let outcome = delete.await.unwrap().expect("delete persons");
+ assert_eq!(outcome.deleted, 1);
+ let (is_deleted, _, _, distinct_ids) = tombstone_state(&ctx.pool, ctx.team_id, person.id).await;
+ assert!(is_deleted);
+ assert_eq!(distinct_ids, vec![(true, 1), (true, 2)]);
+ assert_eq!(lifecycle_op_count(&ctx.pool, ctx.team_id).await, 0);
+
+ ctx.cleanup().await.ok();
+}
+
+async fn wait_for_a_mark_claim_blocked_by(pool: &sqlx::PgPool, holder_pid: i32) {
+ let deadline = Instant::now() + Duration::from_secs(5);
+ loop {
+ let waiting: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM pg_stat_activity
+ WHERE wait_event_type = 'Lock' AND $1 = ANY(pg_blocking_pids(pid))
+ AND query LIKE '%INSERT INTO lifecycle_op_person%'",
+ )
+ .bind(holder_pid)
+ .fetch_one(pool)
+ .await
+ .unwrap();
+ if waiting > 0 {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "the delete never waited on the held mark"
+ );
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+}
+
+#[tokio::test]
+async fn test_delete_persons_tombstone_mode_leaves_a_person_created_after_the_claim_live() {
+ let ctx = TestContext::new().await;
+ let held = ctx.insert_person("recreate_held", None).await.unwrap();
+ let recreated_uuid = Uuid::now_v7();
+
+ let mut holder = ctx.pool.begin().await.unwrap();
+ let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
+ .fetch_one(&mut *holder)
+ .await
+ .unwrap();
+ let op_id = claim_merge_mark(&mut holder, ctx.team_id, &held).await;
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .execute(&mut *holder)
+ .await
+ .unwrap();
+
+ let 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
+ });
+
+ // 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;
+ let recreated = ctx
+ .insert_person_with_uuid("recreate_new", None, recreated_uuid)
+ .await
+ .unwrap();
+ holder.commit().await.unwrap();
+
+ let outcome = delete.await.unwrap().expect("delete persons");
+ assert_eq!(outcome.deleted, 1);
+ let tombstoned: Vec<Uuid> = outcome.tombstones.unwrap().iter().map(|t| t.uuid).collect();
+ assert_eq!(tombstoned, vec![held.uuid]);
+ let (is_deleted, version, _, distinct_ids) =
+ tombstone_state(&ctx.pool, ctx.team_id, recreated.id).await;
+ assert!(!is_deleted);
+ assert_eq!(version, 0);
+ assert_eq!(distinct_ids, vec![(false, 0)]);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_delete_persons_tombstone_mode_fails_when_a_lifecycle_op_holds_the_person() {
+ let ctx = TestContext::new().await;
+ let held = ctx.insert_person("held_by_op", None).await.unwrap();
+ let free = ctx.insert_person("not_held", None).await.unwrap();
+ let mut conn = ctx.pool.acquire().await.unwrap();
+ claim_merge_mark(&mut conn, ctx.team_id, &held).await;
+ drop(conn);
+
+ let result = ctx
+ .storage
+ .delete_persons(
+ ctx.team_id,
+ &[held.uuid, free.uuid],
+ DeletePersonsMode::Tombstone,
+ )
+ .await;
+
+ assert!(
+ matches!(
+ result,
+ Err(personhog_replica::storage::StorageError::FailedPrecondition(_))
+ ),
+ "expected FailedPrecondition, got {result:?}"
+ );
+ for person in [&held, &free] {
+ let (is_deleted, version, _, _) = tombstone_state(&ctx.pool, ctx.team_id, person.id).await;
+ assert!(!is_deleted);
+ assert_eq!(version, 0);
+ }
+ assert_eq!(lifecycle_op_count(&ctx.pool, ctx.team_id).await, 1);
+
ctx.cleanup().await.ok();
}