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.

feat(personhog): attach personless sources inline in MergePersons (#81381)

Nick Bestcda2554ad65f
diff --git a/rust/personhog-identity/src/service/merge.rs b/rust/personhog-identity/src/service/merge.rs
index 70094d5daac4..e07282c316de 100644
--- a/rust/personhog-identity/src/service/merge.rs
+++ b/rust/personhog-identity/src/service/merge.rs
@@ -24,10 +24,11 @@ use crate::lifecycle::merge::{
OUTCOME_SKIPPED_CONFLICT, OUTCOME_SKIPPED_MOVE_LIMIT,
};
use crate::lifecycle::validation::{is_distinct_id_illegal, validate_merge_persons};
-use crate::storage::IdentityStorage;
+use crate::storage::{AttachOutcome, IdentityStorage};
-/// The handler-decided outcome for a source that never reaches the saga.
+/// Handler-decided outcomes that never reach the saga.
const OUTCOME_SKIPPED_ILLEGAL: &str = "skipped_illegal";
+const OUTCOME_ATTACHED: &str = "attached";
/// The full MergePersons flow, owned by the identity side of the crate.
pub struct MergeEntrance {
@@ -114,6 +115,7 @@ impl MergeEntrance {
let target_person = target_person.clone();
let mut inline_results: HashMap<String, String> = HashMap::new();
+ let mut attach: Vec<String> = Vec::new();
let mut saga_sources: Vec<MergeSourceEntry> = Vec::new();
for source in &request.sources {
let did = &source.source_distinct_id;
@@ -122,10 +124,7 @@ impl MergeEntrance {
continue;
}
match resolved.get(&(request.team_id, did.clone())) {
- None => {
- // Unresolved-source attach is not implemented yet.
- inline_results.insert(did.clone(), OUTCOME_ERROR.to_string());
- }
+ None => attach.push(did.clone()),
Some(person) if person.id == target_person.id => {
inline_results.insert(did.clone(), OUTCOME_NOOP_SAME_PERSON.to_string());
}
@@ -136,6 +135,30 @@ impl MergeEntrance {
}
}
+ // Unresolved sources attach to the target with plain mapping
+ // inserts. A source that resolved elsewhere between classification
+ // and attach is a retryable conflict, unless it landed on the
+ // target anyway.
+ if !attach.is_empty() {
+ let attached = self
+ .storage
+ .attach_distinct_ids(request.team_id, target_person.id, &attach)
+ .await
+ .map_err(|e| Status::internal(format!("attach failed: {e}")))?;
+ for did in attach {
+ let outcome = match attached.get(&did) {
+ Some(AttachOutcome::Attached { .. }) => OUTCOME_ATTACHED,
+ Some(AttachOutcome::AlreadyMapped { person_id })
+ if *person_id == target_person.id =>
+ {
+ OUTCOME_ATTACHED
+ }
+ Some(AttachOutcome::AlreadyMapped { .. }) | None => OUTCOME_SKIPPED_CONFLICT,
+ };
+ inline_results.insert(did, outcome.to_string());
+ }
+ }
+
if saga_sources.is_empty() {
// Nothing to destroy, so no op row. Inline settlement is
// idempotent: a retry re-executes against the current world,
@@ -143,8 +166,9 @@ impl MergeEntrance {
// the only semantics available, since recorded outcomes are
// GC'd after retention and a late replay re-classifies
// regardless. The op row resumes interrupted destruction; it
- // is not a dedupe of idempotent work. The event's properties
- // still reach the survivor.
+ // is not a dedupe of idempotent work (an attached source
+ // re-answers noop_same_person). The event's properties still
+ // reach the survivor.
let pushed = self
.push_event_properties(&request, target_person.id)
.await?;
@@ -266,6 +290,7 @@ fn outcome_enum(outcome: &str) -> MergeSourceOutcome {
match outcome {
OUTCOME_MERGED => MergeSourceOutcome::Merged,
OUTCOME_NOOP_SAME_PERSON => MergeSourceOutcome::NoopSamePerson,
+ OUTCOME_ATTACHED => MergeSourceOutcome::Attached,
OUTCOME_SKIPPED_ILLEGAL => MergeSourceOutcome::SkippedIllegal,
OUTCOME_SKIPPED_ALREADY_IDENTIFIED => MergeSourceOutcome::SkippedAlreadyIdentified,
OUTCOME_SKIPPED_CONFLICT => MergeSourceOutcome::SkippedConflict,
diff --git a/rust/personhog-identity/src/storage/mod.rs b/rust/personhog-identity/src/storage/mod.rs
index 9401f23b23fa..e7fef7b5d34b 100644
--- a/rust/personhog-identity/src/storage/mod.rs
+++ b/rust/personhog-identity/src/storage/mod.rs
@@ -7,7 +7,7 @@ use std::collections::HashMap;
use async_trait::async_trait;
pub use error::{StorageError, StorageResult};
-pub use types::{DistinctIdMapping, Person, PersonStub, StubOutcome};
+pub use types::{AttachOutcome, DistinctIdMapping, Person, PersonStub, StubOutcome};
pub const DB_QUERY_DURATION: &str = "personhog_identity_db_query_duration_ms";
@@ -42,4 +42,14 @@ pub trait IdentityStorage: Send + Sync {
/// Callers must dedupe stubs by (team_id, distinct_id); duplicate keys in
/// one call have unspecified per-row outcomes. Outcomes are in stub order.
async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>>;
+
+ /// Attach personless distinct ids to a live person with plain mapping
+ /// inserts. Live mappings are never repointed (`AlreadyMapped`); an id
+ /// absent from the result attached nothing. Callers dedupe.
+ async fn attach_distinct_ids(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ distinct_ids: &[String],
+ ) -> StorageResult<HashMap<String, AttachOutcome>>;
}
diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rs
new file mode 100644
index 000000000000..5fa876052e98
--- /dev/null
+++ b/rust/personhog-identity/src/storage/postgres/attach.rs
@@ -0,0 +1,110 @@
+//! Attach personless distinct ids to an existing person with plain mapping
+//! inserts — the personless-source merge case, settled inline with no saga.
+
+use std::collections::HashMap;
+
+use sqlx::postgres::PgPool;
+use sqlx::Row;
+
+use crate::config::IdentityTables;
+use crate::storage::error::StorageResult;
+use crate::storage::types::AttachOutcome;
+
+/// Fresh inserts get version 1, like a stub's extra distinct ids: with no
+/// personless table there is no proof the id never sent events, and 1 is
+/// safe either way. Tombstoned mappings revive (repoint + version bump);
+/// live mappings are never repointed — that would be a silent merge.
+/// Callers dedupe; sorted insert order keeps row locks deadlock-free.
+///
+/// Two guards keep a racing lifecycle op from acquiring a mapping it can
+/// no longer sweep. The join on a live person row rejects committed
+/// deletions. The mark check rejects persons held by a live op: the
+/// destructive transaction sweeps the person's distinct ids before it
+/// tombstones the person, so an attach overlapping it would insert a row
+/// the sweep already missed — a live mapping onto a tombstoned person.
+/// The saga commits its mark before any destructive statement, so an
+/// attach that could land in that window always observes the mark.
+pub(super) async fn attach_distinct_ids(
+ pool: &PgPool,
+ tables: &IdentityTables,
+ team_id: i64,
+ person_id: i64,
+ distinct_ids: &[String],
+) -> StorageResult<HashMap<String, AttachOutcome>> {
+ if distinct_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let mut sorted: Vec<String> = distinct_ids.to_vec();
+ sorted.sort_unstable();
+
+ let insert_sql = format!(
+ r#"
+ INSERT INTO {pdi} (distinct_id, person_id, team_id, version)
+ SELECT u.d, p.id, p.team_id, 1
+ FROM unnest($1::text[]) AS u(d)
+ JOIN {person} p
+ ON p.team_id = $3 AND p.id = $2 AND p.is_deleted = false
+ WHERE NOT EXISTS (
+ SELECT 1 FROM lifecycle_op_person m
+ WHERE m.team_id = p.team_id AND m.person_id = p.id
+ AND m.status IN ('marked', 'sealed')
+ )
+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET
+ person_id = EXCLUDED.person_id,
+ version = COALESCE({pdi}.version, 0) + 1,
+ is_deleted = false
+ WHERE {pdi}.is_deleted = true
+ RETURNING distinct_id, version
+ "#,
+ pdi = tables.person_distinct_id,
+ person = tables.person,
+ );
+ let written = sqlx::query(&insert_sql)
+ .bind(&sorted)
+ .bind(person_id)
+ .bind(team_id as i32)
+ .fetch_all(pool)
+ .await?;
+
+ let mut outcomes: HashMap<String, AttachOutcome> = HashMap::new();
+ for row in written {
+ let distinct_id: String = row.try_get("distinct_id")?;
+ let version: i64 = row.try_get("version")?;
+ outcomes.insert(distinct_id, AttachOutcome::Attached { version });
+ }
+
+ let losers: Vec<String> = sorted
+ .iter()
+ .filter(|d| !outcomes.contains_key(*d))
+ .cloned()
+ .collect();
+ if losers.is_empty() {
+ return Ok(outcomes);
+ }
+ // Fresh statement snapshot: the insert's snapshot may predate a
+ // concurrent winner's commit.
+ let losers_sql = format!(
+ r#"
+ SELECT distinct_id, person_id
+ FROM {pdi}
+ WHERE team_id = $1 AND distinct_id = ANY($2) AND is_deleted = false
+ "#,
+ pdi = tables.person_distinct_id,
+ );
+ let rows = sqlx::query(&losers_sql)
+ .bind(team_id as i32)
+ .bind(&losers)
+ .fetch_all(pool)
+ .await?;
+ for row in rows {
+ let distinct_id: String = row.try_get("distinct_id")?;
+ let mapped_person_id: i64 = row.try_get("person_id")?;
+ outcomes.insert(
+ distinct_id,
+ AttachOutcome::AlreadyMapped {
+ person_id: mapped_person_id,
+ },
+ );
+ }
+ Ok(outcomes)
+}
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index c7d17182c392..76a1bdf22e26 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -1,7 +1,8 @@
//! Postgres-backed identity storage. This module is dispatch-only: each
//! trait method's logic lives in its own submodule (`resolve`,
-//! `stub_create`), keyed by the metrics operation label.
+//! `stub_create`, `attach`), keyed by the metrics operation label.
+mod attach;
mod distinct_ids;
mod resolve;
mod stub_create;
@@ -16,7 +17,7 @@ use personhog_common::grpc::{current_client_name, current_method_name};
use crate::config::IdentityTables;
use crate::storage::error::StorageResult;
-use crate::storage::types::{DistinctIdMapping, Person, PersonStub, StubOutcome};
+use crate::storage::types::{AttachOutcome, DistinctIdMapping, Person, PersonStub, StubOutcome};
use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
const POOL_LABEL: &str = "primary";
@@ -114,4 +115,22 @@ impl IdentityStorage for PostgresIdentityStorage {
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
stub_create::create_person_stubs(&self.primary_pool, &self.tables, stubs).await
}
+
+ async fn attach_distinct_ids(
+ &self,
+ team_id: i64,
+ person_id: i64,
+ distinct_ids: &[String],
+ ) -> StorageResult<HashMap<String, AttachOutcome>> {
+ let labels = Self::query_labels("attach_distinct_ids");
+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
+ attach::attach_distinct_ids(
+ &self.primary_pool,
+ &self.tables,
+ team_id,
+ person_id,
+ distinct_ids,
+ )
+ .await
+ }
}
diff --git a/rust/personhog-identity/src/storage/types.rs b/rust/personhog-identity/src/storage/types.rs
index 9ec64519a173..fdc7a2305b52 100644
--- a/rust/personhog-identity/src/storage/types.rs
+++ b/rust/personhog-identity/src/storage/types.rs
@@ -12,6 +12,15 @@ pub struct PersonStub {
pub is_identified: bool,
}
+/// Per-distinct-id outcome of an attach call.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AttachOutcome {
+ /// Mapping inserted fresh or revived from a tombstone.
+ Attached { version: i64 },
+ /// A live mapping already exists; attach never repoints a live row.
+ AlreadyMapped { person_id: i64 },
+}
+
/// Per-stub outcome of a stub-creation transaction.
#[derive(Debug, Clone)]
pub enum StubOutcome {
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index 1ff940144fbe..43686ff5f412 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -283,4 +283,15 @@ impl personhog_identity::storage::IdentityStorage for UnusedStorage {
{
panic!("not exercised by this test")
}
+
+ async fn attach_distinct_ids(
+ &self,
+ _team_id: i64,
+ _person_id: i64,
+ _distinct_ids: &[String],
+ ) -> personhog_identity::storage::StorageResult<
+ std::collections::HashMap<String, personhog_identity::storage::AttachOutcome>,
+ > {
+ panic!("not exercised by this test")
+ }
}
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 28edb1be624c..27eb188c1ac3 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -1630,7 +1630,7 @@ async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {
);
request.event_set = serde_json::to_vec(&json!({"plan": "pro"})).unwrap();
let response = service
- .merge_persons(Request::new(request))
+ .merge_persons(Request::new(request.clone()))
.await
.expect("inline call succeeds")
.into_inner();
@@ -1643,9 +1643,13 @@ async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {
MergeSourceOutcome::NoopSamePerson
),
("anonymous".to_string(), MergeSourceOutcome::SkippedIllegal),
- ("inline-unresolved".to_string(), MergeSourceOutcome::Error),
+ (
+ "inline-unresolved".to_string(),
+ MergeSourceOutcome::Attached
+ ),
]
);
+ assert_eq!(h.pdi_state("inline-unresolved").await, (target, false, 1));
let survivor = response.survivor.expect("survivor present");
assert_eq!(survivor.id, target);
// The survivor's created_at unit must not depend on which branch
@@ -1675,6 +1679,21 @@ async fn inline_cases_settle_without_an_op_row_and_push_the_event_properties() {
.unwrap();
assert_eq!(op_count, 0);
+ // On re-classification the attached source resolves to the target and
+ // settles as a no-op — an equivalent answer, not an error.
+ let retry = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect("retry succeeds")
+ .into_inner();
+ assert_eq!(
+ rpc_outcomes(&retry)[2],
+ (
+ "inline-unresolved".to_string(),
+ MergeSourceOutcome::NoopSamePerson
+ )
+ );
+
h.ctx.cleanup().await.expect("cleanup");
}
@@ -1686,30 +1705,40 @@ async fn a_mixed_call_folds_inline_and_saga_outcomes_in_request_order() {
h.add_distinct_id(target, "mixed-alias").await;
let source = h.ctx.insert_person_with_distinct_id("mixed-source").await;
+ let request = rpc_request(
+ h.ctx.team_id,
+ "mixed-target",
+ &["mixed-alias", "mixed-personless", "mixed-source"],
+ Uuid::now_v7(),
+ );
let response = service
- .merge_persons(Request::new(rpc_request(
- h.ctx.team_id,
- "mixed-target",
- &["mixed-alias", "mixed-source"],
- Uuid::now_v7(),
- )))
+ .merge_persons(Request::new(request.clone()))
.await
.expect("merge succeeds")
.into_inner();
- assert_eq!(
- rpc_outcomes(&response),
- vec![
- (
- "mixed-alias".to_string(),
- MergeSourceOutcome::NoopSamePerson
- ),
- ("mixed-source".to_string(), MergeSourceOutcome::Merged),
- ]
- );
+ let expected = vec![
+ (
+ "mixed-alias".to_string(),
+ MergeSourceOutcome::NoopSamePerson,
+ ),
+ ("mixed-personless".to_string(), MergeSourceOutcome::Attached),
+ ("mixed-source".to_string(), MergeSourceOutcome::Merged),
+ ];
+ assert_eq!(rpc_outcomes(&response), expected);
+ assert_eq!(h.pdi_state("mixed-personless").await, (target, false, 1));
let (source_deleted, _, _) = h.person_state(source).await;
assert!(source_deleted);
+ // The attach outcome is frozen in the op row: a retry reproduces it
+ // instead of re-classifying the pair as a no-op.
+ let retry = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect("retry attaches to the op")
+ .into_inner();
+ assert_eq!(rpc_outcomes(&retry), expected);
+
h.ctx.cleanup().await.expect("cleanup");
}
@@ -2023,3 +2052,54 @@ async fn a_failed_property_push_errors_the_call_and_the_retry_settles() {
h.ctx.cleanup().await.expect("cleanup");
}
+
+#[tokio::test]
+async fn a_failed_push_after_attach_leaves_the_attach_durable() {
+ let h = MergeHarness::new().await;
+ let service = h.service();
+ let target = h
+ .ctx
+ .insert_person_with_distinct_id("att-pushfail-target")
+ .await;
+
+ let op_id = Uuid::now_v7();
+ let mut request = rpc_request(
+ h.ctx.team_id,
+ "att-pushfail-target",
+ &["att-pushfail-anon"],
+ op_id,
+ );
+ request.event_set = serde_json::to_vec(&json!({"plan": "pro"})).unwrap();
+ h.leader.fail_next(
+ Rpc::PropertyPush,
+ target,
+ Status::unavailable("leader down"),
+ );
+
+ let status = service
+ .merge_persons(Request::new(request.clone()))
+ .await
+ .expect_err("a failed push fails the call");
+ assert_eq!(status.code(), Code::Unavailable);
+ // The attach committed before the push and must survive the failure —
+ // the retry contract depends on it.
+ assert_eq!(h.pdi_state("att-pushfail-anon").await, (target, false, 1));
+
+ // The retry re-classifies: the attached pair settles as the
+ // equivalent no-op and the push succeeds.
+ let retry = service
+ .merge_persons(Request::new(request))
+ .await
+ .expect("retry succeeds")
+ .into_inner();
+ assert_eq!(
+ rpc_outcomes(&retry),
+ vec![(
+ "att-pushfail-anon".to_string(),
+ MergeSourceOutcome::NoopSamePerson
+ )]
+ );
+ assert_eq!(retry.survivor.as_ref().expect("survivor").id, target);
+
+ h.ctx.cleanup().await.expect("cleanup");
+}
diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rs
index 4c9aa156ac5d..8ff8c53bc9ad 100644
--- a/rust/personhog-identity/tests/storage_tests.rs
+++ b/rust/personhog-identity/tests/storage_tests.rs
@@ -6,7 +6,7 @@ use chrono::{TimeZone, Utc};
use common::TestContext;
use personhog_common::persons::person_uuid;
-use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};
+use personhog_identity::storage::{AttachOutcome, IdentityStorage, PersonStub, StubOutcome};
/// Storage-assertion helpers used only by this test binary.
impl TestContext {
@@ -674,3 +674,179 @@ async fn resolve_returns_only_existing_keys() {
ctx.cleanup().await.ok();
}
+
+#[tokio::test]
+async fn attach_covers_fresh_revived_and_live_mappings_per_row() {
+ let ctx = TestContext::new().await;
+ let owner = ctx.insert_person_with_distinct_id("attach-owner").await;
+ let target = ctx.insert_person_with_distinct_id("attach-target").await;
+ ctx.insert_tombstoned_distinct_id("attach-tomb", owner, 5)
+ .await;
+
+ let outcomes = ctx
+ .storage
+ .attach_distinct_ids(
+ ctx.team_id,
+ target,
+ &[
+ "attach-fresh".to_string(),
+ "attach-tomb".to_string(),
+ "attach-owner".to_string(),
+ ],
+ )
+ .await
+ .expect("attach should succeed");
+
+ assert_eq!(
+ outcomes.get("attach-fresh"),
+ Some(&AttachOutcome::Attached { version: 1 })
+ );
+ assert_eq!(
+ outcomes.get("attach-tomb"),
+ Some(&AttachOutcome::Attached { version: 6 })
+ );
+ assert_eq!(
+ outcomes.get("attach-owner"),
+ Some(&AttachOutcome::AlreadyMapped { person_id: owner })
+ );
+ assert_eq!(
+ ctx.distinct_id_state("attach-fresh").await,
+ Some((target, false, Some(1)))
+ );
+ assert_eq!(
+ ctx.distinct_id_state("attach-tomb").await,
+ Some((target, false, Some(6)))
+ );
+ assert_eq!(
+ ctx.distinct_id_state("attach-owner").await,
+ Some((owner, false, Some(0)))
+ );
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn attach_to_a_dead_person_attaches_nothing() {
+ let ctx = TestContext::new().await;
+ let corpse = ctx.insert_tombstoned_person(uuid::Uuid::new_v4(), 3).await;
+
+ let outcomes = ctx
+ .storage
+ .attach_distinct_ids(ctx.team_id, corpse, &["attach-corpse".to_string()])
+ .await
+ .expect("attach should succeed");
+
+ assert!(outcomes.is_empty());
+ assert_eq!(ctx.distinct_id_state("attach-corpse").await, None);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn attach_works_on_a_configured_table_set() {
+ // Runs attach against the tmp namespace — a leftover hardcoded posthog_
+ // table in its interpolated queries would pass silently on the default
+ // set. Asserted through table-aware storage reads, not the raw-SQL
+ // helpers above (those assume the default set).
+ let ctx = TestContext::new_with_tables(common::tmp_tables()).await;
+ let target = ctx
+ .insert_person_with_distinct_id("tmp-attach-target")
+ .await;
+
+ let outcomes = ctx
+ .storage
+ .attach_distinct_ids(ctx.team_id, target, &["tmp-attach-fresh".to_string()])
+ .await
+ .expect("attach should succeed");
+
+ assert_eq!(
+ outcomes.get("tmp-attach-fresh"),
+ Some(&AttachOutcome::Attached { version: 1 })
+ );
+ let key = (ctx.team_id, "tmp-attach-fresh".to_string());
+ let resolved = ctx
+ .storage
+ .resolve_distinct_ids(std::slice::from_ref(&key))
+ .await
+ .expect("resolve should succeed");
+ assert_eq!(resolved.get(&key).map(|p| p.id), Some(target));
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn attach_refuses_a_person_held_by_a_live_lifecycle_op() {
+ // A deletion overlapping an attach: the delete saga's destructive
+ // transaction sweeps the person's distinct id rows, then tombstones
+ // the person row, then commits. An attach whose liveness join runs
+ // mid-transaction still reads the live person version, so without a
+ // further guard it inserts a mapping the sweep already missed — a
+ // live distinct id pointing at a tombstoned person, which can never
+ // resolve and never gets cleaned up. The saga commits its mark before
+ // any destructive statement, so an attach that could land in that
+ // window always observes the mark; refusing marked persons closes it.
+ let ctx = TestContext::new().await;
+ let victim = ctx.insert_person_with_distinct_id("marked-victim").await;
+
+ // The saga's claim, committed before the fence and the destructive TX.
+ let op_id = uuid::Uuid::now_v7();
+ sqlx::query(
+ "INSERT INTO lifecycle_op (op_id, op_type, team_id, step, lease_expires_at, request) \
+ VALUES ($1, 'delete', $2, 'marked', now() + interval '1 hour', '{}'::jsonb)",
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .execute(&ctx.pool)
+ .await
+ .expect("seed op row");
+ sqlx::query(
+ "INSERT INTO lifecycle_op_person (op_id, team_id, person_id, person_uuid, role, status) \
+ VALUES ($1, $2, $3, gen_random_uuid(), 'victim', 'marked')",
+ )
+ .bind(op_id)
+ .bind(ctx.team_id as i32)
+ .bind(victim)
+ .execute(&ctx.pool)
+ .await
+ .expect("seed mark row");
+
+ // The destructive transaction, mid-flight: distinct ids swept, person
+ // not yet tombstoned, nothing committed.
+ let mut destroying_tx = ctx.pool.begin().await.expect("begin destroying tx");
+ sqlx::query("UPDATE posthog_persondistinctid SET is_deleted = true, version = COALESCE(version, 0) + 1 WHERE team_id = $1 AND person_id = $2")
+ .bind(ctx.team_id as i32)
+ .bind(victim)
+ .execute(&mut *destroying_tx)
+ .await
+ .expect("sweep distinct ids");
+
+ // The overlapping attach must refuse: the person is mark-held.
+ let outcomes = ctx
+ .storage
+ .attach_distinct_ids(ctx.team_id, victim, &["zombie-did".to_string()])
+ .await
+ .expect("attach call succeeds");
+ assert!(
+ outcomes.is_empty(),
+ "attach must not touch a mark-held person, got {outcomes:?}"
+ );
+
+ // The deletion finishes.
+ sqlx::query("UPDATE posthog_person SET is_deleted = true, version = COALESCE(version, 0) + 1 WHERE team_id = $1 AND id = $2")
+ .bind(ctx.team_id as i32)
+ .bind(victim)
+ .execute(&mut *destroying_tx)
+ .await
+ .expect("tombstone person");
+ destroying_tx.commit().await.expect("commit deletion");
+
+ // No zombie: nothing maps the distinct id to the dead person.
+ assert_eq!(ctx.distinct_id_state("zombie-did").await, None);
+
+ sqlx::query("DELETE FROM lifecycle_op WHERE op_id = $1")
+ .bind(op_id)
+ .execute(&ctx.pool)
+ .await
+ .expect("cleanup op");
+ ctx.cleanup().await.ok();
+}