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.

chore(personhog-replica): add more chunking (#60125)

Zach Brown82a42a699598
diff --git a/rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.json b/rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.json
new file mode 100644
index 000000000000..4214392f506a
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.json
@@ -0,0 +1,36 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT l.person_id, l.distinct_id, l.version\n FROM UNNEST($2::bigint[]) AS pid(id)\n CROSS JOIN LATERAL (\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id\n LIMIT $3\n ) l\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "person_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "distinct_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 2,
+ "name": "version",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514"
+}
diff --git a/rust/personhog-replica/.sqlx/query-f29dcd17ee2e9bb5fe3beb58b8fb294b0c80bc9c617733dafc91cd8b1c2e16c5.json b/rust/personhog-replica/.sqlx/query-495a965269a34f368ae76ceb61e956fa0dfa6b9bfa3d909497ddd6f02f6b6438.json
similarity index 59%
rename from rust/personhog-replica/.sqlx/query-f29dcd17ee2e9bb5fe3beb58b8fb294b0c80bc9c617733dafc91cd8b1c2e16c5.json
rename to rust/personhog-replica/.sqlx/query-495a965269a34f368ae76ceb61e956fa0dfa6b9bfa3d909497ddd6f02f6b6438.json
index 073ccac41e0b..fb40405051da 100644
--- a/rust/personhog-replica/.sqlx/query-f29dcd17ee2e9bb5fe3beb58b8fb294b0c80bc9c617733dafc91cd8b1c2e16c5.json
+++ b/rust/personhog-replica/.sqlx/query-495a965269a34f368ae76ceb61e956fa0dfa6b9bfa3d909497ddd6f02f6b6438.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 p.properties::text as \"properties!\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text 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 p.properties::text as \"properties!\",\n p.properties_last_updated_at::text as \"properties_last_updated_at?\",\n p.properties_last_operation::text 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 ",
"describe": {
"columns": [
{
@@ -85,5 +85,5 @@
false
]
},
- "hash": "f29dcd17ee2e9bb5fe3beb58b8fb294b0c80bc9c617733dafc91cd8b1c2e16c5"
+ "hash": "495a965269a34f368ae76ceb61e956fa0dfa6b9bfa3d909497ddd6f02f6b6438"
}
diff --git a/rust/personhog-replica/.sqlx/query-1398eece8dfe37bbd9fce78a47cf1e59ebc2ffefe7d40098e58563b70dc53a03.json b/rust/personhog-replica/.sqlx/query-93a691c94a59ef7bb53626ab7bc5b5c1c0f419e4719b9d6b5cf6a77a8e021f59.json
similarity index 66%
rename from rust/personhog-replica/.sqlx/query-1398eece8dfe37bbd9fce78a47cf1e59ebc2ffefe7d40098e58563b70dc53a03.json
rename to rust/personhog-replica/.sqlx/query-93a691c94a59ef7bb53626ab7bc5b5c1c0f419e4719b9d6b5cf6a77a8e021f59.json
index adab4953d6f0..a30d8be893f0 100644
--- a/rust/personhog-replica/.sqlx/query-1398eece8dfe37bbd9fce78a47cf1e59ebc2ffefe7d40098e58563b70dc53a03.json
+++ b/rust/personhog-replica/.sqlx/query-93a691c94a59ef7bb53626ab7bc5b5c1c0f419e4719b9d6b5cf6a77a8e021f59.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties!\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2)\n ",
+ "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties!\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n FROM posthog_person\n WHERE team_id = $1 AND id = ANY($2)\n ",
"describe": {
"columns": [
{
@@ -79,5 +79,5 @@
true
]
},
- "hash": "1398eece8dfe37bbd9fce78a47cf1e59ebc2ffefe7d40098e58563b70dc53a03"
+ "hash": "93a691c94a59ef7bb53626ab7bc5b5c1c0f419e4719b9d6b5cf6a77a8e021f59"
}
diff --git a/rust/personhog-replica/.sqlx/query-ed7276c7653c4c310c6b0f32be4640084b43fbae9da19f879d6d1ded171d85f6.json b/rust/personhog-replica/.sqlx/query-b03692c528fa947f6decbe1f4bdc7d32027c85a51e14238945ed3443de9a5204.json
similarity index 66%
rename from rust/personhog-replica/.sqlx/query-ed7276c7653c4c310c6b0f32be4640084b43fbae9da19f879d6d1ded171d85f6.json
rename to rust/personhog-replica/.sqlx/query-b03692c528fa947f6decbe1f4bdc7d32027c85a51e14238945ed3443de9a5204.json
index 4ec922dda5f4..793915805275 100644
--- a/rust/personhog-replica/.sqlx/query-ed7276c7653c4c310c6b0f32be4640084b43fbae9da19f879d6d1ded171d85f6.json
+++ b/rust/personhog-replica/.sqlx/query-b03692c528fa947f6decbe1f4bdc7d32027c85a51e14238945ed3443de9a5204.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties!\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ",
+ "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\", properties::text as \"properties!\",\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n created_at, version, is_identified,\n CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,\n last_seen_at\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ",
"describe": {
"columns": [
{
@@ -79,5 +79,5 @@
true
]
},
- "hash": "ed7276c7653c4c310c6b0f32be4640084b43fbae9da19f879d6d1ded171d85f6"
+ "hash": "b03692c528fa947f6decbe1f4bdc7d32027c85a51e14238945ed3443de9a5204"
}
diff --git a/rust/personhog-replica/.sqlx/query-ebb1251c44eb2dafd8ac339d9c1e9d59e6cbfddbc59472002726dc8b3dad154b.json b/rust/personhog-replica/.sqlx/query-ebb1251c44eb2dafd8ac339d9c1e9d59e6cbfddbc59472002726dc8b3dad154b.json
deleted file mode 100644
index 07f76775db62..000000000000
--- a/rust/personhog-replica/.sqlx/query-ebb1251c44eb2dafd8ac339d9c1e9d59e6cbfddbc59472002726dc8b3dad154b.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT l.person_id, l.distinct_id, l.version\n FROM UNNEST($2::bigint[]) AS pid(id)\n CROSS JOIN LATERAL (\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id\n LIMIT $3\n ) l\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "person_id",
- "type_info": "Int8"
- },
- {
- "ordinal": 1,
- "name": "distinct_id",
- "type_info": "Varchar"
- },
- {
- "ordinal": 2,
- "name": "version",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Int4",
- "Int8Array",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- true
- ]
- },
- "hash": "ebb1251c44eb2dafd8ac339d9c1e9d59e6cbfddbc59472002726dc8b3dad154b"
-}
diff --git a/rust/personhog-replica/.sqlx/query-3b8e37f1ea3b73ca1edc33c8b7ce828f5117978a92cc68a46f1eea476b008c2b.json b/rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.json
similarity index 60%
rename from rust/personhog-replica/.sqlx/query-3b8e37f1ea3b73ca1edc33c8b7ce828f5117978a92cc68a46f1eea476b008c2b.json
rename to rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.json
index c35eae826ee5..38f567b32e35 100644
--- a/rust/personhog-replica/.sqlx/query-3b8e37f1ea3b73ca1edc33c8b7ce828f5117978a92cc68a46f1eea476b008c2b.json
+++ b/rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2)\n ",
+ "query": "\n SELECT person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = ANY($2)\n ",
"describe": {
"columns": [
{
@@ -31,5 +31,5 @@
true
]
},
- "hash": "3b8e37f1ea3b73ca1edc33c8b7ce828f5117978a92cc68a46f1eea476b008c2b"
+ "hash": "fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65"
}
diff --git a/rust/personhog-replica/src/storage/postgres/distinct_id.rs b/rust/personhog-replica/src/storage/postgres/distinct_id.rs
index 5b2eb468d4e3..2fe6e0d57795 100644
--- a/rust/personhog-replica/src/storage/postgres/distinct_id.rs
+++ b/rust/personhog-replica/src/storage/postgres/distinct_id.rs
@@ -1,9 +1,12 @@
use async_trait::async_trait;
+use futures::stream::{self, StreamExt, TryStreamExt};
use personhog_common::grpc::current_client_name;
-use super::{ConsistencyLevel, PostgresStorage, DB_QUERY_DURATION, DB_ROWS_RETURNED};
-use crate::storage::error::StorageResult;
+use super::{
+ ConsistencyLevel, PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNED,
+};
+use crate::storage::error::{StorageError, StorageResult};
use crate::storage::traits::DistinctIdLookup;
use crate::storage::types::{DistinctIdMapping, DistinctIdWithVersion};
@@ -102,46 +105,67 @@ impl DistinctIdLookup for PostgresStorage {
];
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- let pool = self.bulk_pool_for_consistency(consistency);
- let mut conn = PostgresStorage::acquire_timed(pool, pool_label).await?;
-
- let rows = match limit_per_person {
- Some(l) => {
- sqlx::query_as!(
- DistinctIdMapping,
- r#"
- SELECT l.person_id, l.distinct_id, l.version
- FROM UNNEST($2::bigint[]) AS pid(id)
- CROSS JOIN LATERAL (
- SELECT person_id, distinct_id, version
- FROM posthog_persondistinctid
- WHERE team_id = $1 AND person_id = pid.id
- LIMIT $3
- ) l
- "#,
- team_id as i32,
- person_ids,
- l
- )
- .fetch_all(&mut *conn)
- .await?
- }
- _ => {
- sqlx::query_as!(
- DistinctIdMapping,
- r#"
- SELECT person_id, distinct_id, version
- FROM posthog_persondistinctid
- WHERE team_id = $1 AND person_id = ANY($2)
- "#,
- team_id as i32,
- person_ids
- )
- .fetch_all(&mut *conn)
- .await?
+ let pool = self.bulk_pool_for_consistency(consistency).clone();
+ let chunks: Vec<Vec<i64>> = person_ids
+ .chunks(self.bulk_chunk_size)
+ .map(|c| c.to_vec())
+ .collect();
+ common_metrics::histogram(
+ DB_BULK_CHUNKS,
+ &[(
+ "operation".to_string(),
+ "get_distinct_ids_for_persons".to_string(),
+ )],
+ chunks.len() as f64,
+ );
+ let results: Vec<Vec<DistinctIdMapping>> = stream::iter(chunks.into_iter().map(|chunk| {
+ let pool = pool.clone();
+ async move {
+ let mut conn = PostgresStorage::acquire_timed(&pool, pool_label).await?;
+ let rows = match limit_per_person {
+ Some(l) => {
+ sqlx::query_as!(
+ DistinctIdMapping,
+ r#"
+ SELECT l.person_id, l.distinct_id, l.version
+ FROM UNNEST($2::bigint[]) AS pid(id)
+ CROSS JOIN LATERAL (
+ SELECT person_id, distinct_id, version
+ FROM posthog_persondistinctid
+ WHERE team_id = $1 AND person_id = pid.id
+ LIMIT $3
+ ) l
+ "#,
+ team_id as i32,
+ &chunk,
+ l
+ )
+ .fetch_all(&mut *conn)
+ .await?
+ }
+ _ => {
+ sqlx::query_as!(
+ DistinctIdMapping,
+ r#"
+ SELECT person_id, distinct_id, version
+ FROM posthog_persondistinctid
+ WHERE team_id = $1 AND person_id = ANY($2)
+ "#,
+ team_id as i32,
+ &chunk
+ )
+ .fetch_all(&mut *conn)
+ .await?
+ }
+ };
+ Ok::<_, StorageError>(rows)
}
- };
+ }))
+ .buffer_unordered(self.bulk_max_concurrent_chunks)
+ .try_collect()
+ .await?;
+ let rows: Vec<DistinctIdMapping> = results.into_iter().flatten().collect();
common_metrics::histogram(
DB_ROWS_RETURNED,
&[
diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rs
index 081140841de6..32761b9410b1 100644
--- a/rust/personhog-replica/src/storage/postgres/person.rs
+++ b/rust/personhog-replica/src/storage/postgres/person.rs
@@ -8,7 +8,7 @@ use uuid::Uuid;
use personhog_common::grpc::current_client_name;
use super::{PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNED};
-use crate::storage::error::StorageResult;
+use crate::storage::error::{StorageError, StorageResult};
use crate::storage::traits::PersonLookup;
use crate::storage::types::Person;
@@ -102,27 +102,46 @@ impl PersonLookup for PostgresStorage {
];
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- let mut conn =
- PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;
-
- let rows = sqlx::query_as!(
- Person,
- r#"
- SELECT id, uuid, team_id::bigint as "team_id!", properties::text as "properties!",
- properties_last_updated_at::text as "properties_last_updated_at?",
- properties_last_operation::text as "properties_last_operation?",
- created_at, version, is_identified,
- CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
- last_seen_at
- FROM posthog_person
- WHERE team_id = $1 AND id = ANY($2)
- "#,
- team_id as i32,
- person_ids
- )
- .fetch_all(&mut *conn)
+ let pool = self.bulk_replica_pool.clone();
+ let chunks: Vec<Vec<i64>> = person_ids
+ .chunks(self.bulk_chunk_size)
+ .map(|c| c.to_vec())
+ .collect();
+ common_metrics::histogram(
+ DB_BULK_CHUNKS,
+ &[("operation".to_string(), "get_persons_by_ids".to_string())],
+ chunks.len() as f64,
+ );
+ let results: Vec<Vec<Person>> = stream::iter(chunks.into_iter().map(|chunk| {
+ let pool = pool.clone();
+ async move {
+ let mut conn =
+ PostgresStorage::acquire_timed(&pool, BULK_POOL_LABEL).await?;
+ let rows = sqlx::query_as!(
+ Person,
+ r#"
+ SELECT id, uuid, team_id::bigint as "team_id!", properties::text as "properties!",
+ properties_last_updated_at::text as "properties_last_updated_at?",
+ properties_last_operation::text as "properties_last_operation?",
+ created_at, version, is_identified,
+ CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
+ last_seen_at
+ FROM posthog_person
+ WHERE team_id = $1 AND id = ANY($2)
+ "#,
+ team_id as i32,
+ &chunk
+ )
+ .fetch_all(&mut *conn)
+ .await?;
+ Ok::<_, StorageError>(rows)
+ }
+ }))
+ .buffer_unordered(self.bulk_max_concurrent_chunks)
+ .try_collect()
.await?;
+ let rows: Vec<Person> = results.into_iter().flatten().collect();
common_metrics::histogram(
DB_ROWS_RETURNED,
&[
@@ -152,27 +171,46 @@ impl PersonLookup for PostgresStorage {
];
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- let mut conn =
- PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;
-
- let rows = sqlx::query_as!(
- Person,
- r#"
- SELECT id, uuid, team_id::bigint as "team_id!", properties::text as "properties!",
- properties_last_updated_at::text as "properties_last_updated_at?",
- properties_last_operation::text as "properties_last_operation?",
- created_at, version, is_identified,
- CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
- last_seen_at
- FROM posthog_person
- WHERE team_id = $1 AND uuid = ANY($2)
- "#,
- team_id as i32,
- uuids
- )
- .fetch_all(&mut *conn)
+ let pool = self.bulk_replica_pool.clone();
+ let chunks: Vec<Vec<Uuid>> = uuids
+ .chunks(self.bulk_chunk_size)
+ .map(|c| c.to_vec())
+ .collect();
+ common_metrics::histogram(
+ DB_BULK_CHUNKS,
+ &[("operation".to_string(), "get_persons_by_uuids".to_string())],
+ chunks.len() as f64,
+ );
+ let results: Vec<Vec<Person>> = stream::iter(chunks.into_iter().map(|chunk| {
+ let pool = pool.clone();
+ async move {
+ let mut conn =
+ PostgresStorage::acquire_timed(&pool, BULK_POOL_LABEL).await?;
+ let rows = sqlx::query_as!(
+ Person,
+ r#"
+ SELECT id, uuid, team_id::bigint as "team_id!", properties::text as "properties!",
+ properties_last_updated_at::text as "properties_last_updated_at?",
+ properties_last_operation::text as "properties_last_operation?",
+ created_at, version, is_identified,
+ CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,
+ last_seen_at
+ FROM posthog_person
+ WHERE team_id = $1 AND uuid = ANY($2)
+ "#,
+ team_id as i32,
+ &chunk
+ )
+ .fetch_all(&mut *conn)
+ .await?;
+ Ok::<_, StorageError>(rows)
+ }
+ }))
+ .buffer_unordered(self.bulk_max_concurrent_chunks)
+ .try_collect()
.await?;
+ let rows: Vec<Person> = results.into_iter().flatten().collect();
common_metrics::histogram(
DB_ROWS_RETURNED,
&[
@@ -246,27 +284,71 @@ impl PersonLookup for PostgresStorage {
];
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- let mut conn =
- PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;
- let rows = sqlx::query!(
- r#"
- SELECT p.id, p.uuid as "uuid!", p.team_id::bigint as "team_id!",
- p.properties::text as "properties!",
- p.properties_last_updated_at::text as "properties_last_updated_at?",
- p.properties_last_operation::text as "properties_last_operation?",
- p.created_at as "created_at!", p.version, p.is_identified as "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,
- 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)
- "#,
- team_id as i32,
- distinct_ids
- )
- .fetch_all(&mut *conn)
- .await?;
+ let pool = self.bulk_replica_pool.clone();
+ let chunks: Vec<Vec<String>> = distinct_ids
+ .chunks(self.bulk_chunk_size)
+ .map(|c| c.to_vec())
+ .collect();
+ common_metrics::histogram(
+ DB_BULK_CHUNKS,
+ &[(
+ "operation".to_string(),
+ "get_persons_by_distinct_ids_in_team".to_string(),
+ )],
+ chunks.len() as f64,
+ );
+ let chunk_results: Vec<Vec<(String, Person)>> =
+ stream::iter(chunks.into_iter().map(|chunk| {
+ let pool = pool.clone();
+ async move {
+ let mut conn =
+ PostgresStorage::acquire_timed(&pool, BULK_POOL_LABEL).await?;
+ let rows = sqlx::query!(
+ r#"
+ SELECT p.id, p.uuid as "uuid!", p.team_id::bigint as "team_id!",
+ p.properties::text as "properties!",
+ p.properties_last_updated_at::text as "properties_last_updated_at?",
+ p.properties_last_operation::text as "properties_last_operation?",
+ p.created_at as "created_at!", p.version, p.is_identified as "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,
+ 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)
+ "#,
+ team_id as i32,
+ &chunk
+ )
+ .fetch_all(&mut *conn)
+ .await?;
+ Ok::<_, StorageError>(
+ rows.into_iter()
+ .map(|row| {
+ let person = Person {
+ id: row.id,
+ uuid: row.uuid,
+ team_id: row.team_id,
+ properties: row.properties,
+ properties_last_updated_at: row.properties_last_updated_at,
+ properties_last_operation: row.properties_last_operation,
+ 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,
+ };
+ (row.distinct_id, person)
+ })
+ .collect(),
+ )
+ }
+ }))
+ .buffer_unordered(self.bulk_max_concurrent_chunks)
+ .try_collect()
+ .await?;
+
+ let mut found: HashMap<String, Person> = chunk_results.into_iter().flatten().collect();
common_metrics::histogram(
DB_ROWS_RETURNED,
@@ -277,29 +359,9 @@ impl PersonLookup for PostgresStorage {
),
("client".to_string(), client.to_string()),
],
- rows.len() as f64,
+ found.len() as f64,
);
- let mut found: HashMap<String, Person> = rows
- .into_iter()
- .map(|row| {
- let person = Person {
- id: row.id,
- uuid: row.uuid,
- team_id: row.team_id,
- properties: row.properties,
- properties_last_updated_at: row.properties_last_updated_at,
- properties_last_operation: row.properties_last_operation,
- 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,
- };
- (row.distinct_id, person)
- })
- .collect();
-
Ok(distinct_ids
.iter()
.map(|did| (did.clone(), found.remove(did)))
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index 7faba6aa5bc4..15d18aeefb8e 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -1413,3 +1413,202 @@ async fn test_delete_persons_partial_failure_returns_error() {
.ok();
ctx.cleanup().await.ok();
}
+
+// ============================================================
+// Bulk read chunking tests — exercise the parallel path
+// (test chunk_size=50, so >50 items triggers chunking)
+// ============================================================
+
+#[tokio::test]
+async fn test_get_persons_by_ids_chunked() {
+ let ctx = TestContext::new().await;
+
+ let mut ids = Vec::new();
+ for i in 0..80 {
+ let p = ctx
+ .insert_person(&format!("bulk_id_{i}"), None)
+ .await
+ .unwrap();
+ ids.push(p.id);
+ }
+
+ let result = ctx
+ .storage
+ .get_persons_by_ids(ctx.team_id, &ids)
+ .await
+ .expect("Failed to get persons by ids");
+
+ assert_eq!(result.len(), 80);
+ let returned_ids: Vec<i64> = result.iter().map(|p| p.id).collect();
+ for id in &ids {
+ assert!(returned_ids.contains(id), "Missing person id {id}");
+ }
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_get_persons_by_uuids_chunked() {
+ let ctx = TestContext::new().await;
+
+ let mut uuids = Vec::new();
+ for i in 0..80 {
+ let p = ctx
+ .insert_person(&format!("bulk_uuid_{i}"), None)
+ .await
+ .unwrap();
+ uuids.push(p.uuid);
+ }
+
+ let result = ctx
+ .storage
+ .get_persons_by_uuids(ctx.team_id, &uuids)
+ .await
+ .expect("Failed to get persons by uuids");
+
+ assert_eq!(result.len(), 80);
+ let returned_uuids: Vec<Uuid> = result.iter().map(|p| p.uuid).collect();
+ for uuid in &uuids {
+ assert!(returned_uuids.contains(uuid), "Missing person uuid {uuid}");
+ }
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_get_persons_by_distinct_ids_in_team_chunked() {
+ let ctx = TestContext::new().await;
+
+ let mut distinct_ids = Vec::new();
+ for i in 0..80 {
+ let did = format!("bulk_did_{i}");
+ ctx.insert_person(&did, None).await.unwrap();
+ distinct_ids.push(did);
+ }
+
+ let result = ctx
+ .storage
+ .get_persons_by_distinct_ids_in_team(ctx.team_id, &distinct_ids)
+ .await
+ .expect("Failed to get persons by distinct ids");
+
+ assert_eq!(result.len(), 80);
+ let mut found_count = 0;
+ for (did, person) in &result {
+ assert!(
+ distinct_ids.contains(did),
+ "Unexpected distinct_id {did} in result"
+ );
+ if person.is_some() {
+ found_count += 1;
+ }
+ }
+ assert_eq!(found_count, 80, "All persons should be found");
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_get_persons_by_distinct_ids_in_team_chunked_preserves_missing() {
+ let ctx = TestContext::new().await;
+
+ // Create 60 persons but request 80 distinct_ids (20 nonexistent)
+ let mut distinct_ids = Vec::new();
+ for i in 0..60 {
+ let did = format!("partial_did_{i}");
+ ctx.insert_person(&did, None).await.unwrap();
+ distinct_ids.push(did);
+ }
+ for i in 60..80 {
+ distinct_ids.push(format!("missing_did_{i}"));
+ }
+
+ let result = ctx
+ .storage
+ .get_persons_by_distinct_ids_in_team(ctx.team_id, &distinct_ids)
+ .await
+ .expect("Failed to get persons");
+
+ assert_eq!(result.len(), 80);
+ let found: Vec<_> = result.iter().filter(|(_, p)| p.is_some()).collect();
+ let missing: Vec<_> = result.iter().filter(|(_, p)| p.is_none()).collect();
+ assert_eq!(found.len(), 60);
+ assert_eq!(missing.len(), 20);
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_get_distinct_ids_for_persons_chunked() {
+ let ctx = TestContext::new().await;
+
+ let mut person_ids = Vec::new();
+ for i in 0..80 {
+ let p = ctx
+ .insert_person(&format!("did_bulk_{i}"), None)
+ .await
+ .unwrap();
+ // Add a second distinct_id to some persons
+ if i % 5 == 0 {
+ ctx.add_distinct_id_to_person(p.id, &format!("did_bulk_{i}_extra"))
+ .await
+ .unwrap();
+ }
+ person_ids.push(p.id);
+ }
+
+ let result = ctx
+ .storage
+ .get_distinct_ids_for_persons(ctx.team_id, &person_ids, ConsistencyLevel::Eventual, None)
+ .await
+ .expect("Failed to get distinct ids for persons");
+
+ // 80 persons, 16 with 2 distinct_ids each = 96 total
+ assert_eq!(result.len(), 96);
+
+ // Every person_id should appear at least once
+ let returned_person_ids: std::collections::HashSet<i64> =
+ result.iter().map(|d| d.person_id).collect();
+ for pid in &person_ids {
+ assert!(returned_person_ids.contains(pid), "Missing person_id {pid}");
+ }
+
+ ctx.cleanup().await.ok();
+}
+
+#[tokio::test]
+async fn test_get_distinct_ids_for_persons_chunked_with_limit() {
+ let ctx = TestContext::new().await;
+
+ let mut person_ids = Vec::new();
+ for i in 0..80 {
+ let p = ctx
+ .insert_person(&format!("did_lim_{i}"), None)
+ .await
+ .unwrap();
+ ctx.add_distinct_id_to_person(p.id, &format!("did_lim_{i}_b"))
+ .await
+ .unwrap();
+ ctx.add_distinct_id_to_person(p.id, &format!("did_lim_{i}_c"))
+ .await
+ .unwrap();
+ person_ids.push(p.id);
+ }
+
+ // Each person has 3 distinct_ids, limit to 1 per person
+ let result = ctx
+ .storage
+ .get_distinct_ids_for_persons(
+ ctx.team_id,
+ &person_ids,
+ ConsistencyLevel::Eventual,
+ Some(1),
+ )
+ .await
+ .expect("Failed to get distinct ids with limit");
+
+ // Should get exactly 80 rows (1 per person)
+ assert_eq!(result.len(), 80);
+
+ ctx.cleanup().await.ok();
+}