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): revive a tombstoned person when a split regenerates its uuid (#102709)

Nick Best1fef7009236b
diff --git a/rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.json b/rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.json
new file mode 100644
index 000000000000..8e62001dc21d
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e.json
@@ -0,0 +1,30 @@
+{
+ "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 ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "uuid!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "version!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "UuidArray",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "3d4d238676f2e13b60a24262ae14f2242b3e1db6953311a5ad4d02c0dae7e93e"
+}
diff --git a/rust/personhog-replica/.sqlx/query-c09aa87a6a34fd6cd5023fac1d854b8270eb8927213e601b3c09d83acffe5ec9.json b/rust/personhog-replica/.sqlx/query-c09aa87a6a34fd6cd5023fac1d854b8270eb8927213e601b3c09d83acffe5ec9.json
deleted file mode 100644
index a87fa9a49722..000000000000
--- a/rust/personhog-replica/.sqlx/query-c09aa87a6a34fd6cd5023fac1d854b8270eb8927213e601b3c09d83acffe5ec9.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_person SET version = $3\n WHERE team_id = $1 AND uuid = ANY($2)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "UuidArray",
- "Int8"
- ]
- },
- "nullable": []
- },
- "hash": "c09aa87a6a34fd6cd5023fac1d854b8270eb8927213e601b3c09d83acffe5ec9"
-}
diff --git a/rust/personhog-replica/.sqlx/query-141a3c15c67572af8c7779ef6402f5463a8c4c0dd43e291a1e12436e788396c8.json b/rust/personhog-replica/.sqlx/query-c4932e4296f61cb06fbd827cd1855fc7251fcef1b69a402998b4f15c695f328a.json
similarity index 77%
rename from rust/personhog-replica/.sqlx/query-141a3c15c67572af8c7779ef6402f5463a8c4c0dd43e291a1e12436e788396c8.json
rename to rust/personhog-replica/.sqlx/query-c4932e4296f61cb06fbd827cd1855fc7251fcef1b69a402998b4f15c695f328a.json
index d9469d010037..2ce90a3ff8bc 100644
--- a/rust/personhog-replica/.sqlx/query-141a3c15c67572af8c7779ef6402f5463a8c4c0dd43e291a1e12436e788396c8.json
+++ b/rust/personhog-replica/.sqlx/query-c4932e4296f61cb06fbd827cd1855fc7251fcef1b69a402998b4f15c695f328a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT distinct_id as \"distinct_id!\", COALESCE(version, 0)::bigint as \"version!\"\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2 AND distinct_id = ANY($3)\n FOR UPDATE\n ",
+ "query": "\n SELECT distinct_id as \"distinct_id!\", COALESCE(version, 0)::bigint as \"version!\"\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2 AND distinct_id = ANY($3) AND is_deleted = false\n FOR UPDATE\n ",
"describe": {
"columns": [
{
@@ -26,5 +26,5 @@
null
]
},
- "hash": "141a3c15c67572af8c7779ef6402f5463a8c4c0dd43e291a1e12436e788396c8"
+ "hash": "c4932e4296f61cb06fbd827cd1855fc7251fcef1b69a402998b4f15c695f328a"
}
diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rs
index ec8800738965..f20a0128ce18 100644
--- a/rust/personhog-replica/src/storage/postgres/person.rs
+++ b/rust/personhog-replica/src/storage/postgres/person.rs
@@ -897,7 +897,7 @@ impl PersonLookup for PostgresStorage {
r#"
SELECT distinct_id as "distinct_id!", COALESCE(version, 0)::bigint as "version!"
FROM posthog_persondistinctid
- WHERE team_id = $1 AND person_id = $2 AND distinct_id = ANY($3)
+ WHERE team_id = $1 AND person_id = $2 AND distinct_id = ANY($3) AND is_deleted = false
FOR UPDATE
"#,
team_id as i32,
@@ -939,9 +939,11 @@ 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 (idempotent re-split).
- // No ON CONFLICT — the partitioned table has a unique index, not a
- // unique constraint, so ON CONFLICT inference doesn't work.
+ // 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!(
r#"
SELECT id::bigint as "id!", uuid as "uuid!", created_at as "created_at!"
@@ -959,6 +961,7 @@ impl PersonLookup for PostgresStorage {
.into_iter()
.map(|r| (r.uuid, (r.id, r.created_at)))
.collect();
+ let mut version_by_uuid: HashMap<Uuid, i64> = HashMap::new();
let existing_uuids: HashSet<Uuid> = person_by_uuid.keys().copied().collect();
@@ -984,23 +987,37 @@ impl PersonLookup for PostgresStorage {
.await?;
for r in inserted {
person_by_uuid.insert(r.uuid, (r.id, r.created_at));
+ version_by_uuid.insert(r.uuid, new_person_version);
}
}
let uuids_to_update: Vec<Uuid> = existing_uuids.into_iter().collect();
if !uuids_to_update.is_empty() {
- sqlx::query!(
+ // 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.
+ let updated = sqlx::query!(
r#"
- UPDATE posthog_person SET version = $3
+ UPDATE posthog_person
+ SET 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)
+ RETURNING uuid as "uuid!", version as "version!"
"#,
team_id as i32,
&uuids_to_update,
new_person_version
)
- .execute(&mut *tx)
+ .fetch_all(&mut *tx)
.await?;
+ for r in updated {
+ version_by_uuid.insert(r.uuid, r.version);
+ }
}
let new_person_rows: Vec<(i64, DateTime<Utc>)> = new_uuids
@@ -1046,16 +1063,23 @@ impl PersonLookup for PostgresStorage {
.zip(new_person_rows)
.map(
|(((distinct_id, new_person_uuid), pdi_version), (_, new_person_created_at))| {
- SplitResult {
+ Ok(SplitResult {
distinct_id,
new_person_uuid,
- new_person_version,
+ new_person_version: version_by_uuid
+ .get(&new_person_uuid)
+ .copied()
+ .ok_or_else(|| {
+ StorageError::Query(format!(
+ "version not populated for uuid {new_person_uuid}"
+ ))
+ })?,
pdi_version,
new_person_created_at,
- }
+ })
},
)
- .collect();
+ .collect::<StorageResult<Vec<_>>>()?;
common_metrics::histogram(
DB_ROWS_RETURNED,
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index 6d630f8a338c..d54691c571b9 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -2414,6 +2414,104 @@ async fn test_split_person_idempotent() {
ctx.cleanup().await.ok();
}
+#[tokio::test]
+async fn test_split_person_revives_a_tombstoned_generated_person() {
+ let ctx = TestContext::new().await;
+ // "loser" was created for the distinct id, then merged into "keeper": the
+ // mapping moved to keeper and loser stayed behind as a tombstone under the
+ // uuid a split of that distinct id regenerates.
+ let keeper = ctx
+ .insert_person("[email protected]", None)
+ .await
+ .unwrap();
+ let loser_id = rand::thread_rng().gen_range(1_000_000i64..100_000_000);
+ let loser_uuid =
+ personhog_common::persons::person_uuid(ctx.team_id, "[email protected]");
+ let loser_version: i64 = 500;
+ 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, is_deleted)
+ VALUES ($1, $2, $3, '{}'::jsonb, '{}', '{}', NOW(), $4, false, NULL, true)"#,
+ )
+ .bind(loser_id)
+ .bind(loser_uuid)
+ .bind(ctx.team_id)
+ .bind(loser_version)
+ .execute(&ctx.pool)
+ .await
+ .unwrap();
+ ctx.add_distinct_id_to_person(keeper.id, "[email protected]")
+ .await
+ .unwrap();
+
+ let results = ctx
+ .storage
+ .split_person(
+ ctx.team_id,
+ keeper.id,
+ &["[email protected]".to_string()],
+ )
+ .await
+ .expect("Split onto a tombstone should succeed");
+
+ assert_eq!(results[0].new_person_uuid, loser_uuid);
+ // One above the tombstone, because that outranks its ClickHouse tombstone
+ // and the split offset (0 + 101) is lower.
+ assert_eq!(results[0].new_person_version, loser_version + 1);
+
+ let revived = ctx
+ .storage
+ .get_person_by_uuid(ctx.team_id, loser_uuid)
+ .await
+ .unwrap()
+ .expect("The revived person reads as live");
+ assert_eq!(revived.id, loser_id);
+ assert_eq!(revived.version, Some(loser_version + 1));
+ let owner = ctx
+ .storage
+ .get_person_by_distinct_id(ctx.team_id, "[email protected]")
+ .await
+ .unwrap()
+ .expect("The split mapping reads as live");
+ assert_eq!(owner.id, loser_id);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_split_person_rejects_a_tombstoned_distinct_id() {
+ let ctx = TestContext::new().await;
+ let person = ctx
+ .insert_person("[email protected]", None)
+ .await
+ .unwrap();
+ ctx.add_distinct_id_to_person(person.id, "[email protected]")
+ .await
+ .unwrap();
+ sqlx::query(
+ "UPDATE posthog_persondistinctid SET is_deleted = true WHERE team_id = $1 AND distinct_id = $2",
+ )
+ .bind(ctx.team_id)
+ .execute(&ctx.pool)
+ .await
+ .unwrap();
+
+ let err = ctx
+ .storage
+ .split_person(
+ ctx.team_id,
+ person.id,
+ &["[email protected]".to_string()],
+ )
+ .await
+ .expect_err("A tombstoned mapping is not the person's to split");
+ assert!(err.to_string().contains("Not found"), "got: {err}");
+
+ ctx.cleanup().await.ok();
+}
+
#[tokio::test]
async fn test_split_person_preserves_created_at_of_existing_person() {
let ctx = TestContext::new().await;
@@ -2481,6 +2579,63 @@ async fn test_split_person_preserves_created_at_of_existing_person() {
ctx.cleanup().await.ok();
}
+#[tokio::test]
+async fn test_split_person_preserves_high_version_of_existing_person() {
+ let ctx = TestContext::new().await;
+ let person = ctx
+ .insert_person("[email protected]", None)
+ .await
+ .unwrap();
+ ctx.add_distinct_id_to_person(person.id, "[email protected]")
+ .await
+ .unwrap();
+
+ 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 existing_id = rand::thread_rng().gen_range(1_000_000i64..100_000_000);
+ 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)"#,
+ )
+ .bind(existing_id)
+ .bind(split_uuid)
+ .bind(ctx.team_id)
+ .execute(&ctx.pool)
+ .await
+ .unwrap();
+
+ let results = ctx
+ .storage
+ .split_person(
+ ctx.team_id,
+ person.id,
+ &["[email protected]".to_string()],
+ )
+ .await
+ .expect("Split should succeed");
+
+ assert_eq!(results[0].new_person_uuid, split_uuid);
+ assert_eq!(results[0].new_person_version, 200);
+
+ let upserted = ctx
+ .storage
+ .get_person_by_uuid(ctx.team_id, split_uuid)
+ .await
+ .expect("Lookup should succeed")
+ .expect("Person should exist");
+ assert_eq!(upserted.version, Some(200));
+
+ ctx.cleanup().await.ok();
+}
+
#[tokio::test]
async fn test_split_person_not_found_unknown_distinct_id() {
let ctx = TestContext::new().await;