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): prune person partitions in the identity resolve query (#104764)

Nick Bestaa5bde791bbd
diff --git a/rust/personhog-identity/.sqlx/query-a8babd1df479f0d2cf62c5f3a77460cbe4c741182b7d74103f57bad7275dd09c.json b/rust/personhog-identity/.sqlx/query-a8babd1df479f0d2cf62c5f3a77460cbe4c741182b7d74103f57bad7275dd09c.json
new file mode 100644
index 000000000000..b8da15e4e6e8
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-a8babd1df479f0d2cf62c5f3a77460cbe4c741182b7d74103f57bad7275dd09c.json
@@ -0,0 +1,77 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='resolve_persons' */ \n SELECT k.team_id AS \"key_team_id!\", k.distinct_id AS \"key_distinct_id!\",\n p.id, p.uuid, p.team_id::bigint AS \"team_id!\", p.created_at, p.version,\n p.is_identified,\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END AS is_user_id,\n p.last_seen_at\n FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN posthog_persondistinctid pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n AND pdi.is_deleted = false\n JOIN posthog_person p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n AND p.team_id = ANY($1::int[])\n AND p.is_deleted = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "key_team_id!",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "key_distinct_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "is_identified",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
+ "name": "is_user_id",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 9,
+ "name": "last_seen_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ false,
+ false,
+ null,
+ false,
+ true,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "a8babd1df479f0d2cf62c5f3a77460cbe4c741182b7d74103f57bad7275dd09c"
+}
diff --git a/rust/personhog-identity/.sqlx/query-e5899e80d1665000da68b0802106c1ed8f089cfbb821f0841164e0e122b4800e.json b/rust/personhog-identity/.sqlx/query-e5899e80d1665000da68b0802106c1ed8f089cfbb821f0841164e0e122b4800e.json
new file mode 100644
index 000000000000..28b5c6369eac
--- /dev/null
+++ b/rust/personhog-identity/.sqlx/query-e5899e80d1665000da68b0802106c1ed8f089cfbb821f0841164e0e122b4800e.json
@@ -0,0 +1,77 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "/* service='personhog-identity', operation='resolve_persons' */ \n SELECT k.team_id AS \"key_team_id!\", k.distinct_id AS \"key_distinct_id!\",\n p.id, p.uuid, p.team_id::bigint AS \"team_id!\", p.created_at, p.version,\n p.is_identified,\n CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END AS is_user_id,\n p.last_seen_at\n FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN personhog_persondistinctid_tmp pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n AND pdi.is_deleted = false\n JOIN personhog_person_tmp p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n AND p.team_id = ANY($1::int[])\n AND p.is_deleted = false\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "key_team_id!",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "key_distinct_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "team_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "version",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "is_identified",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
+ "name": "is_user_id",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 9,
+ "name": "last_seen_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4Array",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ false,
+ false,
+ null,
+ false,
+ true,
+ false,
+ null,
+ true
+ ]
+ },
+ "hash": "e5899e80d1665000da68b0802106c1ed8f089cfbb821f0841164e0e122b4800e"
+}
diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rs
index dc617c19ce3c..51cf93eafa5b 100644
--- a/rust/personhog-identity/src/storage/postgres/resolve.rs
+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs
@@ -1,13 +1,26 @@
use std::collections::HashMap;
-use sqlx::Row;
+use chrono::{DateTime, Utc};
+use common_sqlx_macros::mirrored_query_as;
+use uuid::Uuid;
use crate::config::IdentityTables;
use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
-use crate::storage::postgres::{person_columns, person_from_row};
use crate::storage::types::Person;
-use personhog_common::query_tag;
+
+struct ResolvedRow {
+ key_team_id: i32,
+ key_distinct_id: String,
+ id: i64,
+ uuid: Uuid,
+ team_id: i64,
+ created_at: DateTime<Utc>,
+ version: Option<i64>,
+ is_identified: bool,
+ is_user_id: Option<bool>,
+ last_seen_at: Option<DateTime<Utc>>,
+}
/// Batch-resolve (team_id, distinct_id) keys to their live persons on the
/// primary. Tombstoned mappings and persons are invisible; unresolved keys
@@ -24,36 +37,48 @@ pub(super) async fn resolve_distinct_ids(
let team_ids: Vec<i32> = keys.iter().map(|(t, _)| *t as i32).collect();
let distinct_ids: Vec<String> = keys.iter().map(|(_, d)| d.clone()).collect();
- let sql = format!(
+ let mut conn = pools.acquire(Lane::Fast).await?;
+ let rows = mirrored_query_as!(
+ ResolvedRow,
+ tables.is_validation(),
+ op = "resolve_persons",
r#"
- SELECT k.team_id AS key_team_id, k.distinct_id AS key_distinct_id,
- {person_cols}
+ SELECT k.team_id AS "key_team_id!", k.distinct_id AS "key_distinct_id!",
+ p.id, p.uuid, p.team_id::bigint AS "team_id!", p.created_at, p.version,
+ p.is_identified,
+ CASE WHEN p.is_user_id IS NULL THEN NULL ELSE (p.is_user_id != 0) END AS is_user_id,
+ p.last_seen_at
FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)
- JOIN {pdi_table} pdi
+ JOIN {posthog_persondistinctid|personhog_persondistinctid_tmp} pdi
ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id
AND pdi.is_deleted = false
- JOIN {person_table} p
+ JOIN {posthog_person|personhog_person_tmp} p
ON p.team_id = pdi.team_id AND p.id = pdi.person_id
+ AND p.team_id = ANY($1::int[])
AND p.is_deleted = false
"#,
- person_cols = person_columns("p"),
- pdi_table = tables.person_distinct_id,
- person_table = tables.person,
- );
- let mut conn = pools.acquire(Lane::Fast).await?;
- let rows = sqlx::query(&query_tag!("resolve_persons", sql))
- .bind(&team_ids)
- .bind(&distinct_ids)
- .fetch_all(&mut *conn)
- .await?;
+ &team_ids,
+ &distinct_ids
+ => fetch_all(&mut *conn)
+ )?;
let mut resolved = HashMap::with_capacity(rows.len());
for row in rows {
- let key_team_id: i32 = row.try_get("key_team_id")?;
- let key_distinct_id: String = row.try_get("key_distinct_id")?;
resolved.insert(
- (i64::from(key_team_id), key_distinct_id),
- person_from_row(&row)?,
+ (i64::from(row.key_team_id), row.key_distinct_id),
+ Person {
+ id: row.id,
+ uuid: row.uuid,
+ team_id: row.team_id,
+ properties: None,
+ properties_last_updated_at: None,
+ properties_last_operation: None,
+ created_at: row.created_at,
+ version: row.version,
+ is_identified: row.is_identified,
+ is_user_id: row.is_user_id,
+ last_seen_at: row.last_seen_at,
+ },
);
}
Ok(resolved)
diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rs
index a6d8b73a8c10..e26cce0636d0 100644
--- a/rust/personhog-identity/tests/storage_tests.rs
+++ b/rust/personhog-identity/tests/storage_tests.rs
@@ -759,6 +759,53 @@ async fn resolve_returns_only_existing_keys() {
ctx.cleanup().await.ok();
}
+#[tokio::test]
+async fn resolve_does_not_lock_person_partitions_outside_the_batch() {
+ let ctx = TestContext::new().await;
+ let person_id = ctx.insert_person_with_distinct_id("pruned").await;
+
+ let own_partition: String = sqlx::query_scalar(&format!(
+ "SELECT tableoid::regclass::text FROM {} WHERE team_id = $1 AND id = $2",
+ ctx.tables.person
+ ))
+ .bind(ctx.team_id as i32)
+ .bind(person_id)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("person row should name its partition");
+ let other_partition: String = sqlx::query_scalar(
+ "SELECT inhrelid::regclass::text FROM pg_inherits
+ WHERE inhparent = $1::regclass AND inhrelid::regclass::text <> $2
+ ORDER BY 1 LIMIT 1",
+ )
+ .bind(&ctx.tables.person)
+ .bind(&own_partition)
+ .fetch_one(&ctx.pool)
+ .await
+ .expect("person table should have another partition");
+
+ let mut blocker = ctx.pool.begin().await.expect("begin should succeed");
+ sqlx::query(&format!(
+ "LOCK TABLE {other_partition} IN ACCESS EXCLUSIVE MODE"
+ ))
+ .execute(&mut *blocker)
+ .await
+ .expect("lock should succeed");
+
+ let resolved = tokio::time::timeout(
+ Duration::from_secs(5),
+ ctx.storage
+ .resolve_distinct_ids(&[(ctx.team_id, "pruned".to_string())]),
+ )
+ .await
+ .expect("resolve waited on a person partition its batch does not touch")
+ .expect("resolve should succeed");
+ assert_eq!(resolved[&(ctx.team_id, "pruned".to_string())].id, person_id);
+
+ blocker.rollback().await.ok();
+ ctx.cleanup().await.ok();
+}
+
#[tokio::test]
async fn attach_covers_fresh_revived_and_live_mappings_per_row() {
let ctx = TestContext::new().await;