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): chunk cohort inserts (#63058)

Zach Brown39dd6c8fb462
diff --git a/rust/personhog-replica/.sqlx/query-1094540dc7145671df1ee86bfa3f642d32c375fc398874750593ee943c1aefa9.json b/rust/personhog-replica/.sqlx/query-1094540dc7145671df1ee86bfa3f642d32c375fc398874750593ee943c1aefa9.json
new file mode 100644
index 000000000000..7485955d8f9b
--- /dev/null
+++ b/rust/personhog-replica/.sqlx/query-1094540dc7145671df1ee86bfa3f642d32c375fc398874750593ee943c1aefa9.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO posthog_cohortpeople (person_id, cohort_id, version)\n SELECT pid, $1, $3\n FROM UNNEST($2::bigint[]) AS t(pid)\n WHERE NOT EXISTS (\n SELECT 1 FROM posthog_cohortpeople cp\n WHERE cp.person_id = pid AND cp.cohort_id = $1\n )\n ON CONFLICT DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int4",
+ "Int8Array",
+ "Int4"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1094540dc7145671df1ee86bfa3f642d32c375fc398874750593ee943c1aefa9"
+}
diff --git a/rust/personhog-replica/.sqlx/query-2e3f6dc3a8dc9162c48e9f1b705055db544e09ec508d74125e03edfdbbf520f8.json b/rust/personhog-replica/.sqlx/query-2e3f6dc3a8dc9162c48e9f1b705055db544e09ec508d74125e03edfdbbf520f8.json
deleted file mode 100644
index c61d4c89a50f..000000000000
--- a/rust/personhog-replica/.sqlx/query-2e3f6dc3a8dc9162c48e9f1b705055db544e09ec508d74125e03edfdbbf520f8.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO posthog_cohortpeople (person_id, cohort_id, version)\n SELECT pid, $1, $3\n FROM UNNEST($2::bigint[]) AS t(pid)\n ON CONFLICT DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Int4",
- "Int8Array",
- "Int4"
- ]
- },
- "nullable": []
- },
- "hash": "2e3f6dc3a8dc9162c48e9f1b705055db544e09ec508d74125e03edfdbbf520f8"
-}
diff --git a/rust/personhog-replica/src/storage/postgres/cohort.rs b/rust/personhog-replica/src/storage/postgres/cohort.rs
index ff778b0c8892..691d0c6d93df 100644
--- a/rust/personhog-replica/src/storage/postgres/cohort.rs
+++ b/rust/personhog-replica/src/storage/postgres/cohort.rs
@@ -1,14 +1,48 @@
use std::collections::HashSet;
use async_trait::async_trait;
+use futures::stream::{self, StreamExt, TryStreamExt};
use personhog_common::grpc::{current_client_name, current_method_name};
-use super::{ConsistencyLevel, PostgresStorage, DB_QUERY_DURATION, DB_ROWS_RETURNED};
+use super::{
+ ConsistencyLevel, PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNED,
+};
use crate::storage::error::StorageResult;
use crate::storage::traits::CohortStorage;
use crate::storage::types::CohortMembership;
+/// Insert one bounded chunk of cohort members. NOT EXISTS makes re-running the same
+/// person_ids (e.g. on retry) idempotent without a unique index; the bare ON CONFLICT DO
+/// NOTHING is a forward-safeguard — if a unique (cohort_id, person_id) constraint is later
+/// added, a concurrent same-key insert is skipped cleanly instead of erroring.
+async fn insert_cohort_members_chunk(
+ pool: &sqlx::PgPool,
+ cohort_id: i64,
+ person_ids: &[i64],
+ version: Option<i32>,
+) -> StorageResult<i64> {
+ let mut conn = PostgresStorage::acquire_timed(pool, "bulk_primary").await?;
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO posthog_cohortpeople (person_id, cohort_id, version)
+ SELECT pid, $1, $3
+ FROM UNNEST($2::bigint[]) AS t(pid)
+ WHERE NOT EXISTS (
+ SELECT 1 FROM posthog_cohortpeople cp
+ WHERE cp.person_id = pid AND cp.cohort_id = $1
+ )
+ ON CONFLICT DO NOTHING
+ "#,
+ cohort_id as i32,
+ person_ids,
+ version,
+ )
+ .execute(&mut *conn)
+ .await?;
+ Ok(result.rows_affected() as i64)
+}
+
#[async_trait]
impl CohortStorage for PostgresStorage {
async fn check_cohort_membership(
@@ -214,28 +248,35 @@ impl CohortStorage for PostgresStorage {
let method = current_method_name();
let labels = [
("operation".to_string(), "insert_cohort_members".to_string()),
- ("pool".to_string(), "primary".to_string()),
+ ("pool".to_string(), "bulk_primary".to_string()),
("client".to_string(), client.to_string()),
("method".to_string(), method.to_string()),
];
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;
+ // Split into fixed-size chunks inserted concurrently on the bulk pool, mirroring
+ // delete_persons. Each chunk dedups with NOT EXISTS, so a retry of the full list
+ // sees the already-committed rows and skips them — idempotent without a unique index.
+ let pool = self.bulk_primary_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(), "insert_cohort_members".to_string())],
+ chunks.len() as f64,
+ );
- let result = sqlx::query!(
- r#"
- INSERT INTO posthog_cohortpeople (person_id, cohort_id, version)
- SELECT pid, $1, $3
- FROM UNNEST($2::bigint[]) AS t(pid)
- ON CONFLICT DO NOTHING
- "#,
- cohort_id as i32,
- person_ids,
- version,
- )
- .execute(&mut *conn)
+ let results: Vec<i64> = stream::iter(chunks.into_iter().map(|chunk| {
+ let pool = pool.clone();
+ async move { insert_cohort_members_chunk(&pool, cohort_id, &chunk, version).await }
+ }))
+ .buffer_unordered(self.bulk_max_concurrent_chunks)
+ .try_collect()
.await?;
+ let inserted: i64 = results.iter().sum();
common_metrics::histogram(
DB_ROWS_RETURNED,
&[
@@ -243,10 +284,10 @@ impl CohortStorage for PostgresStorage {
("client".to_string(), client.to_string()),
("method".to_string(), method.to_string()),
],
- result.rows_affected() as f64,
+ inserted as f64,
);
- Ok(result.rows_affected() as i64)
+ Ok(inserted)
}
async fn list_cohort_member_ids(
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index 77f493c93af1..a0bf61ae9ea1 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -309,6 +309,65 @@ async fn test_check_cohort_membership() {
ctx.cleanup().await.ok();
}
+async fn cohort_row_count(pool: &sqlx::PgPool, cohort_id: i64, person_ids: &[i64]) -> i64 {
+ sqlx::query_scalar::<_, i64>(
+ "SELECT COUNT(*) FROM posthog_cohortpeople WHERE cohort_id = $1 AND person_id = ANY($2)",
+ )
+ .bind(cohort_id)
+ .bind(person_ids)
+ .fetch_one(pool)
+ .await
+ .expect("count cohort rows")
+}
+
+// Idempotency across the concurrent chunked insert: a re-send of the full list (the retry /
+// partial-failure recovery case) must skip already-present members and never duplicate rows.
+#[rstest]
+#[case::all_new(0, 120)]
+#[case::retry_after_partial(70, 50)]
+#[case::full_retry(120, 0)]
+#[tokio::test]
+async fn test_insert_cohort_members_idempotent(
+ #[case] prior: usize,
+ #[case] expected_inserted: i64,
+) {
+ let ctx = TestContext::new().await;
+ let cohort_id: i64 = 7700;
+
+ // 120 persons exercises the concurrent chunk path (bulk_chunk_size = 50 → 3 chunks).
+ let mut person_ids = Vec::new();
+ for i in 0..120 {
+ let p = ctx
+ .insert_person(&format!("cohort_insert_{i}@example.com"), None)
+ .await
+ .expect("insert person");
+ person_ids.push(p.id);
+ }
+
+ // Seed `prior` members to simulate a prior partial commit that a retry re-sends in full.
+ for &pid in &person_ids[..prior] {
+ ctx.add_person_to_cohort(pid, cohort_id)
+ .await
+ .expect("seed prior members");
+ }
+
+ let inserted = ctx
+ .storage
+ .insert_cohort_members(cohort_id, &person_ids, Some(1))
+ .await
+ .expect("insert cohort members");
+
+ // Only the not-yet-present members are inserted; NOT EXISTS skips the rest.
+ assert_eq!(inserted, expected_inserted);
+ // Exactly one row per person — no duplicates, regardless of prior state or chunk fan-out.
+ assert_eq!(
+ cohort_row_count(&ctx.pool, cohort_id, &person_ids).await,
+ 120
+ );
+
+ ctx.cleanup().await.ok();
+}
+
#[tokio::test]
async fn test_person_properties() {
let ctx = TestContext::new().await;