: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): never split a distinct id onto a live person (#117239)
Eli Reisman6b6f5f57e1c7
diff --git a/rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.json b/rust/personhog-replica/.sqlx/query-038d77f5d96873dcb90dffb0993844533fa32aafc72f181293ea3c2e430c386c.jsonsimilarity index 59%rename from rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.jsonrename to rust/personhog-replica/.sqlx/query-038d77f5d96873dcb90dffb0993844533fa32aafc72f181293ea3c2e430c386c.jsonindex 8e62001dc21d..7f3d21ac45c5 100644--- a/rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.json+++ b/rust/personhog-replica/.sqlx/query-038d77f5d96873dcb90dffb0993844533fa32aafc72f181293ea3c2e430c386c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE posthog_person\n SET is_deleted = false,\n version = GREATEST(\n COALESCE(version, 0) + CASE WHEN is_deleted THEN 1 ELSE 0 END,\n $3\n )\n WHERE team_id = $1 AND uuid = ANY($2)\n RETURNING uuid as \"uuid!\", version as \"version!\"\n ",+ "query": "\n UPDATE posthog_person\n SET is_deleted = false,\n version = GREATEST(COALESCE(version, 0) + 1, $3)\n WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = true\n RETURNING uuid as \"uuid!\", version as \"version!\"\n ","describe": {"columns": [{@@ -26,5 +26,5 @@true]},- "hash": "3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e"+ "hash": "038d77f5d96873dcb90dffb0993844533fa32aafc72f181293ea3c2e430c386c"}diff --git a/rust/personhog-replica/.sqlx/query-073aa855206237c9c0e4d9e21f6c9f957bf8514110577ce87cdcd7bae41f587f.json b/rust/personhog-replica/.sqlx/query-073aa855206237c9c0e4d9e21f6c9f957bf8514110577ce87cdcd7bae41f587f.jsonnew file mode 100644index 000000000000..5f664d375326--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-073aa855206237c9c0e4d9e21f6c9f957bf8514110577ce87cdcd7bae41f587f.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT uuid as \"uuid!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = false\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "uuid!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "073aa855206237c9c0e4d9e21f6c9f957bf8514110577ce87cdcd7bae41f587f"+}diff --git a/rust/personhog-replica/.sqlx/query-49bcc915e71cec48ea8e91fac80f2e4a004a39a064354ea5ef7dd6ae4e5afb78.json b/rust/personhog-replica/.sqlx/query-829c512d1303149dff2e61b607b1789731674457f18365449438493efc510b24.jsonsimilarity index 73%rename from rust/personhog-replica/.sqlx/query-49bcc915e71cec48ea8e91fac80f2e4a004a39a064354ea5ef7dd6ae4e5afb78.jsonrename to rust/personhog-replica/.sqlx/query-829c512d1303149dff2e61b607b1789731674457f18365449438493efc510b24.jsonindex f9a13ecd40ef..faa00cf95bce 100644--- a/rust/personhog-replica/.sqlx/query-49bcc915e71cec48ea8e91fac80f2e4a004a39a064354ea5ef7dd6ae4e5afb78.json+++ b/rust/personhog-replica/.sqlx/query-829c512d1303149dff2e61b607b1789731674457f18365449438493efc510b24.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\", created_at as \"created_at!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n FOR UPDATE\n ",+ "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\", created_at as \"created_at!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = true\n ORDER BY id\n FOR UPDATE\n ","describe": {"columns": [{@@ -31,5 +31,5 @@false]},- "hash": "49bcc915e71cec48ea8e91fac80f2e4a004a39a064354ea5ef7dd6ae4e5afb78"+ "hash": "829c512d1303149dff2e61b607b1789731674457f18365449438493efc510b24"}diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 8d90bfe2f009..147b34d2460d 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -983,8 +983,8 @@ impl PersonLookup for PostgresStorage {// service-layer cap bounds the number of rows locked.let mut tx = self.bulk_primary_pool.begin().await?;- // No FOR UPDATE on the source person: deletes lock PDI rows before person- // rows, so locking the person first here would invert that order and risk+ // No FOR UPDATE on the source person: deletes lock the person before its+ // PDIs, so locking it after the PDIs here would invert that order and risk// deadlock. The PDI locks below are what guard the reassignment.let person_version: i64 = sqlx::query_scalar!(r#"@@ -1041,7 +1041,7 @@ impl PersonLookup for PostgresStorage {.map(|pdi| (pdi.distinct_id.as_str(), pdi.version)).collect();let dids: Vec<String> = distinct_ids_to_split.to_vec();- let new_uuids: Vec<Uuid> = dids+ let derived_uuids: Vec<Uuid> = dids.iter().map(|did| personhog_common::persons::person_uuid(team_id, did)).collect();@@ -1050,16 +1050,41 @@ impl PersonLookup for PostgresStorage {.map(|did| pdi_version_by_did[did.as_str()] + SPLIT_VERSION_OFFSET).collect();- // Find persons that already exist for these UUIDs: an idempotent- // re-split, or a tombstone left by a merge or delete of the person- // that once owned the distinct id. No ON CONFLICT — the partitioned- // table has a unique index, not a unique constraint, so ON CONFLICT- // inference doesn't work.- let existing_persons = sqlx::query!(+ // A live person here (the source itself, for the distinct id that created it) would absorb+ // the distinct id and get its ClickHouse row blanked by the split's empty-person publish.+ // It is never written, so it is not locked: deletes lock the person before its PDIs.+ let live_uuids: HashSet<Uuid> = sqlx::query_scalar!(+ r#"+ SELECT uuid as "uuid!"+ FROM posthog_person+ WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = false+ "#,+ team_id as i32,+ &derived_uuids+ )+ .fetch_all(&mut *tx)+ .await?+ .into_iter()+ .collect();+ let new_uuids: Vec<Uuid> = derived_uuids+ .into_iter()+ .map(|u| {+ if live_uuids.contains(&u) {+ Uuid::new_v4()+ } else {+ u+ }+ })+ .collect();++ // No ON CONFLICT — the partitioned table has a unique index, not a+ // unique constraint, so ON CONFLICT inference doesn't work.+ let tombstones = sqlx::query!(r#"SELECT id::bigint as "id!", uuid as "uuid!", created_at as "created_at!"FROM posthog_person- WHERE team_id = $1 AND uuid = ANY($2)+ WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = true+ ORDER BY idFOR UPDATE"#,team_id as i32,@@ -1068,7 +1093,7 @@ impl PersonLookup for PostgresStorage {.fetch_all(&mut *tx).await?;- let mut person_by_uuid: HashMap<Uuid, (i64, DateTime<Utc>)> = existing_persons+ let mut person_by_uuid: HashMap<Uuid, (i64, DateTime<Utc>)> = tombstones.into_iter().map(|r| (r.uuid, (r.id, r.created_at))).collect();@@ -1107,17 +1132,13 @@ impl PersonLookup for PostgresStorage {if !uuids_to_update.is_empty() {// A tombstoned row comes back to life here, one above its own// version so it outranks its ClickHouse tombstone; the split- // offset applies when that is higher. A live row never moves- // down, or ClickHouse would ignore the next update from ingestion.+ // offset applies when that is higher.let updated = sqlx::query!(r#"UPDATE posthog_personSET is_deleted = false,- version = GREATEST(- COALESCE(version, 0) + CASE WHEN is_deleted THEN 1 ELSE 0 END,- $3- )- WHERE team_id = $1 AND uuid = ANY($2)+ version = GREATEST(COALESCE(version, 0) + 1, $3)+ WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = trueRETURNING uuid as "uuid!", version as "version!""#,team_id as i32,diff --git a/rust/personhog-replica/src/storage/traits/person.rs b/rust/personhog-replica/src/storage/traits/person.rsindex 4bcd760ec3ca..81bb4a2d87fb 100644--- a/rust/personhog-replica/src/storage/traits/person.rs+++ b/rust/personhog-replica/src/storage/traits/person.rs@@ -112,7 +112,8 @@ pub trait PersonLookup: Send + Sync {/// 1. Locks the specified PersonDistinctId rows with SELECT FOR UPDATE and/// validates ownership under the lock/// 2. Creates new persons via one bulk upsert (deterministic UUIDv5,- /// version = original person version + 101)+ /// version = original person version + 101). A live person at that+ /// UUID is never reused: the distinct_id gets a random UUID instead./// 3. Reassigns PDIs to new persons in one bulk update/// (version = original PDI version + 101)///diff --git a/rust/personhog-replica/src/storage/types/person.rs b/rust/personhog-replica/src/storage/types/person.rsindex a9a92522792b..c37f2946242e 100644--- a/rust/personhog-replica/src/storage/types/person.rs+++ b/rust/personhog-replica/src/storage/types/person.rs@@ -115,7 +115,7 @@ pub struct SplitResult {pub new_person_uuid: Uuid,pub new_person_version: i64,pub pdi_version: i64,- /// For pre-existing persons (idempotent re-split) this is the original- /// created_at, preserved by the upsert — not the time of this request.+ /// For a revived tombstone this is its original created_at, not the time+ /// of this request.pub new_person_created_at: chrono::DateTime<chrono::Utc>,}diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex 45205de5abbf..e6328530c289 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -3127,7 +3127,7 @@ async fn test_split_person_rejects_a_tombstoned_distinct_id() {}#[tokio::test]-async fn test_split_person_preserves_created_at_of_existing_person() {+async fn test_split_person_revive_keeps_the_tombstone_created_at() {let ctx = TestContext::new().await;let person = ctx.insert_person("[email protected]", None)@@ -3137,16 +3137,8 @@ async fn test_split_person_preserves_created_at_of_existing_person() {.await.unwrap();- // Pre-create the person the split will upsert into (same deterministic- // UUIDv5), with a created_at in the past.- let namespace = Uuid::from_bytes([- 0x93, 0x29, 0x79, 0xb4, 0x65, 0xc3, 0x44, 0x24, 0x84, 0x67, 0x0b, 0x66, 0xec, 0x27, 0xbc,- 0x22,- ]);- let split_uuid = Uuid::new_v5(- &namespace,- format!("{}:[email protected]", ctx.team_id).as_bytes(),- );+ let split_uuid =+ personhog_common::persons::person_uuid(ctx.team_id, "[email protected]");let old_created_at = chrono::DateTime::parse_from_rfc3339("2020-01-02T03:04:05Z").unwrap().with_timezone(&chrono::Utc);@@ -3154,8 +3146,8 @@ async fn test_split_person_preserves_created_at_of_existing_person() {sqlx::query(r#"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, '{}'::jsonb, '{}', '{}', $4, 3, false, NULL)"#,+ properties_last_operation, created_at, version, is_identified, is_user_id, is_deleted)+ VALUES ($1, $2, $3, '{}'::jsonb, '{}', '{}', $4, 3, false, NULL, true)"#,).bind(existing_id).bind(split_uuid)@@ -3175,77 +3167,179 @@ async fn test_split_person_preserves_created_at_of_existing_person() {.await.expect("Split should succeed");- // The upsert keeps the existing person's created_at; the response must- // report it so callers publish the value that matches Postgres.+ // Callers publish the returned created_at, so it must match the revived row.assert_eq!(results[0].new_person_uuid, split_uuid);assert_eq!(results[0].new_person_created_at, old_created_at);assert_eq!(results[0].new_person_version, 101); // source person version 0 + 101- let upserted = ctx+ let revived = ctx.storage.get_person_by_uuid(ctx.team_id, split_uuid).await.expect("Lookup should succeed")- .expect("Upserted person should exist");- assert_eq!(upserted.created_at, old_created_at);- assert_eq!(upserted.version, Some(101));+ .expect("Revived person should exist");+ assert_eq!(revived.id, existing_id);+ assert_eq!(revived.created_at, old_created_at);+ assert_eq!(revived.version, Some(101));ctx.cleanup().await.ok();}+#[rstest]+#[case::source_person_created_by_the_distinct_id(true)]+#[case::another_live_person(false)]#[tokio::test]-async fn test_split_person_preserves_high_version_of_existing_person() {+async fn test_split_person_never_reuses_a_live_person(#[case] live_is_source: bool) {let ctx = TestContext::new().await;- let person = ctx- .insert_person("[email protected]", None)+ let split_did = "[email protected]";+ let derived_uuid = personhog_common::persons::person_uuid(ctx.team_id, split_did);+ let properties = serde_json::json!({"email": "[email protected]"});++ let (source, live) = if live_is_source {+ let source = ctx+ .insert_person_with_uuid(split_did, Some(properties.clone()), derived_uuid)+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(source.id, "[email protected]")+ .await+ .unwrap();+ (source.clone(), source)+ } else {+ let live = ctx+ .insert_person_with_uuid(+ "[email protected]",+ Some(properties.clone()),+ derived_uuid,+ )+ .await+ .unwrap();+ let source = ctx+ .insert_person("[email protected]", None)+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(source.id, split_did)+ .await+ .unwrap();+ (source, live)+ };+ let source_version_before = ctx+ .storage+ .get_person_by_uuid(ctx.team_id, source.uuid).await- .unwrap();- ctx.add_distinct_id_to_person(person.id, "[email protected]")+ .unwrap()+ .expect("source exists")+ .version;++ let results = ctx+ .storage+ .split_person(ctx.team_id, source.id, &[split_did.to_string()]).await- .unwrap();+ .expect("Split should succeed");- let namespace = Uuid::from_bytes([- 0x93, 0x29, 0x79, 0xb4, 0x65, 0xc3, 0x44, 0x24, 0x84, 0x67, 0x0b, 0x66, 0xec, 0x27, 0xbc,- 0x22,- ]);- let split_uuid = Uuid::new_v5(- &namespace,- format!("{}:[email protected]", ctx.team_id).as_bytes(),+ let new_uuid = results[0].new_person_uuid;+ assert_ne!(new_uuid, derived_uuid);+ assert_ne!(new_uuid, source.uuid);+ assert_eq!(results[0].new_person_version, 101); // source person version 0 + 101++ let owner = ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, split_did)+ .await+ .unwrap()+ .expect("The split mapping reads as live");+ assert_eq!(owner.uuid, new_uuid);+ assert_eq!(owner.version, Some(101));+ assert_eq!(owner.properties.as_deref(), Some("{}"));++ let untouched = ctx+ .storage+ .get_person_by_uuid(ctx.team_id, live.uuid)+ .await+ .unwrap()+ .expect("The live person stays live");+ assert_eq!(untouched.id, live.id);+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(untouched.properties.as_deref().unwrap())+ .unwrap(),+ properties);- let existing_id = rand::thread_rng().gen_range(1_000_000i64..100_000_000);+ if live_is_source {+ assert_eq!(untouched.version, source_version_before);+ } else {+ assert_eq!(untouched.version, Some(0));+ }++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_split_person_mixed_targets_keep_request_order() {+ let ctx = TestContext::new().await;+ let creator = "[email protected]";+ let revived = "[email protected]";+ let fresh = "[email protected]";+ let creator_uuid = personhog_common::persons::person_uuid(ctx.team_id, creator);+ let revived_uuid = personhog_common::persons::person_uuid(ctx.team_id, revived);+ let fresh_uuid = personhog_common::persons::person_uuid(ctx.team_id, fresh);++ let source = ctx+ .insert_person_with_uuid(creator, None, creator_uuid)+ .await+ .unwrap();+ for did in [revived, fresh, "[email protected]"] {+ ctx.add_distinct_id_to_person(source.id, did).await.unwrap();+ }+ let tombstone_id = rand::thread_rng().gen_range(1_000_000i64..100_000_000);+ let tombstone_created_at = chrono::DateTime::parse_from_rfc3339("2020-01-02T03:04:05Z")+ .unwrap()+ .with_timezone(&chrono::Utc);sqlx::query(r#"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, '{}'::jsonb, '{}', '{}', NOW(), 200, false, NULL)"#,+ properties_last_operation, created_at, version, is_identified, is_user_id, is_deleted)+ VALUES ($1, $2, $3, '{}'::jsonb, '{}', '{}', $4, 500, false, NULL, true)"#,)- .bind(existing_id)- .bind(split_uuid)+ .bind(tombstone_id)+ .bind(revived_uuid).bind(ctx.team_id)+ .bind(tombstone_created_at).execute(&ctx.pool).await.unwrap();+ let request = [creator, revived, fresh].map(String::from);let results = ctx.storage- .split_person(- ctx.team_id,- person.id,- &["[email protected]".to_string()],- )+ .split_person(ctx.team_id, source.id, &request).await.expect("Split should succeed");- assert_eq!(results[0].new_person_uuid, split_uuid);- assert_eq!(results[0].new_person_version, 200);+ let dids: Vec<&str> = results.iter().map(|r| r.distinct_id.as_str()).collect();+ assert_eq!(dids, vec![creator, revived, fresh]);+ assert_ne!(results[0].new_person_uuid, creator_uuid);+ assert_eq!(results[0].new_person_version, 101);+ assert_eq!(results[1].new_person_uuid, revived_uuid);+ assert_eq!(results[1].new_person_version, 501);+ assert_eq!(results[1].new_person_created_at, tombstone_created_at);+ assert_eq!(results[2].new_person_uuid, fresh_uuid);+ assert_eq!(results[2].new_person_version, 101);- let upserted = ctx+ for result in &results {+ let owner = ctx+ .storage+ .get_person_by_distinct_id(ctx.team_id, &result.distinct_id)+ .await+ .unwrap()+ .expect("Each split mapping reads as live");+ assert_eq!(owner.uuid, result.new_person_uuid);+ }+ let kept = ctx.storage- .get_person_by_uuid(ctx.team_id, split_uuid)+ .get_person_by_distinct_id(ctx.team_id, "[email protected]").await- .expect("Lookup should succeed")- .expect("Person should exist");- assert_eq!(upserted.version, Some(200));+ .unwrap()+ .expect("The source keeps its other distinct id");+ assert_eq!(kept.id, source.id);ctx.cleanup().await.ok();}