: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
chore(personhog): optimize get persons in team (#62754)
Zach Browne3332599ad16
diff --git a/rust/personhog-replica/.sqlx/query-0878f57fcfedbfb95e16f5eb0fd90ed15cbb0850dc727c39073e346d9736358c.json b/rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.jsonsimilarity index 83%rename from rust/personhog-replica/.sqlx/query-0878f57fcfedbfb95e16f5eb0fd90ed15cbb0850dc727c39073e346d9736358c.jsonrename to rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.jsonindex e79ef21e6419..09193a8b21b2 100644--- a/rust/personhog-replica/.sqlx/query-0878f57fcfedbfb95e16f5eb0fd90ed15cbb0850dc727c39073e346d9736358c.json+++ b/rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT p.id, p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"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 d.distinct_id as \"distinct_id!\"\n FROM posthog_person p\n INNER JOIN posthog_persondistinctid d ON p.id = d.person_id AND p.team_id = d.team_id\n WHERE p.team_id = $1 AND d.distinct_id = ANY($2)\n ",+ "query": "\n SELECT p.id, p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END as \"properties_last_operation?\",\n p.created_at as \"created_at!\", p.version, p.is_identified as \"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 d.distinct_id as \"distinct_id!\"\n FROM UNNEST($2::text[]) AS batch(distinct_id)\n INNER JOIN posthog_persondistinctid d\n ON d.team_id = $1 AND d.distinct_id = batch.distinct_id\n INNER JOIN posthog_person p\n ON p.id = d.person_id AND p.team_id = d.team_id\n ","describe": {"columns": [{@@ -86,5 +86,5 @@false]},- "hash": "0878f57fcfedbfb95e16f5eb0fd90ed15cbb0850dc727c39073e346d9736358c"+ "hash": "019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29"}diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 5bdc4ab06a3f..325e1b685856 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use async_trait::async_trait;use futures::stream::{self, StreamExt, TryStreamExt};@@ -306,9 +306,22 @@ impl PersonLookup for PostgresStorage {let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);let pool = self.bulk_replica_pool.clone();- let chunks: Vec<Vec<String>> = distinct_ids+ // Drive from the supplied distinct IDs via UNNEST and probe the+ // (team_id, distinct_id) index, rather than `d.distinct_id = ANY($2)`+ // with the team predicate parked on `posthog_person`. The latter lets+ // the planner start from every person in the team and hash-join, which+ // is catastrophic for large teams. Deduplicate the input first so+ // UNNEST emits one row per distinct ID; the response below still+ // mirrors the caller's original list, repeats included.+ let mut seen: HashSet<&str> = HashSet::with_capacity(distinct_ids.len());+ let unique_ids: Vec<&str> = distinct_ids+ .iter()+ .map(|d| d.as_str())+ .filter(|&d| seen.insert(d))+ .collect();+ let chunks: Vec<Vec<String>> = unique_ids.chunks(self.bulk_chunk_size)- .map(|c| c.to_vec())+ .map(|c| c.iter().map(|&s| s.to_string()).collect()).collect();common_metrics::histogram(DB_BULK_CHUNKS,@@ -334,9 +347,11 @@ impl PersonLookup for PostgresStorage {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,d.distinct_id as "distinct_id!"- FROM posthog_person p- INNER JOIN posthog_persondistinctid d ON p.id = d.person_id AND p.team_id = d.team_id- WHERE p.team_id = $1 AND d.distinct_id = ANY($2)+ FROM UNNEST($2::text[]) AS batch(distinct_id)+ INNER JOIN posthog_persondistinctid d+ ON d.team_id = $1 AND d.distinct_id = batch.distinct_id+ INNER JOIN posthog_person p+ ON p.id = d.person_id AND p.team_id = d.team_id"#,team_id as i32,&chunk,diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex eb66899c58e6..77f493c93af1 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -1629,6 +1629,46 @@ async fn test_get_persons_by_distinct_ids_in_team_chunked_preserves_missing() {ctx.cleanup().await.ok();}+#[tokio::test]+async fn test_get_persons_by_distinct_ids_in_team_handles_duplicates() {+ let ctx = TestContext::new().await;++ ctx.insert_person("dup_did_a", None).await.unwrap();+ ctx.insert_person("dup_did_b", None).await.unwrap();++ // A repeated distinct_id, plus a repeated non-existent one. The query+ // deduplicates these, while the response mirrors the input list: each id+ // resolves on its first occurrence and is None on any repeat.+ let distinct_ids = vec![+ "dup_did_a".to_string(),+ "dup_did_a".to_string(),+ "dup_did_b".to_string(),+ "missing_dup".to_string(),+ "missing_dup".to_string(),+ ];++ let result = ctx+ .storage+ .get_persons_by_distinct_ids_in_team(ctx.team_id, &distinct_ids, true)+ .await+ .expect("Failed to get persons");++ assert_eq!(+ result+ .iter()+ .map(|(did, _)| did.clone())+ .collect::<Vec<_>>(),+ distinct_ids+ );+ assert!(result[0].1.is_some());+ assert!(result[1].1.is_none());+ assert!(result[2].1.is_some());+ assert!(result[3].1.is_none());+ assert!(result[4].1.is_none());++ ctx.cleanup().await.ok();+}+#[tokio::test]async fn test_get_distinct_ids_for_persons_chunked() {let ctx = TestContext::new().await;