: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
fix(personhog): return the existing group on a duplicate create_group (#117275)
Phil Haack041f8b6397ee
diff --git a/rust/personhog-replica/.sqlx/query-a5fc4252aef5baeebd3f3578273763b871f1144dcb0569d568dba71b0c1a8027.json b/rust/personhog-replica/.sqlx/query-aad5b62569d75482cadc017fe6a32b88bd82903b3b4ba071b94dd3f32d198dec.jsonsimilarity index 66%rename from rust/personhog-replica/.sqlx/query-a5fc4252aef5baeebd3f3578273763b871f1144dcb0569d568dba71b0c1a8027.jsonrename to rust/personhog-replica/.sqlx/query-aad5b62569d75482cadc017fe6a32b88bd82903b3b4ba071b94dd3f32d198dec.jsonindex b3bdd5562e9e..f6badf4ceb7b 100644--- a/rust/personhog-replica/.sqlx/query-a5fc4252aef5baeebd3f3578273763b871f1144dcb0569d568dba71b0c1a8027.json+++ b/rust/personhog-replica/.sqlx/query-aad5b62569d75482cadc017fe6a32b88bd82903b3b4ba071b94dd3f32d198dec.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id::bigint as \"id!\", team_id::bigint as \"team_id!\",\n group_type_index, group_key, group_properties::text as \"group_properties?\",\n created_at,\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n version\n FROM posthog_group\n WHERE team_id = $1 AND group_type_index = $2 AND group_key = $3\n ",+ "query": "\n SELECT id::bigint as \"id!\", team_id::bigint as \"team_id!\",\n group_type_index, group_key, group_properties::text as \"group_properties?\",\n created_at,\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n version\n FROM posthog_group\n WHERE team_id = $1 AND group_type_index = $2 AND group_key = $3\n ","describe": {"columns": [{@@ -68,5 +68,5 @@false]},- "hash": "a5fc4252aef5baeebd3f3578273763b871f1144dcb0569d568dba71b0c1a8027"+ "hash": "aad5b62569d75482cadc017fe6a32b88bd82903b3b4ba071b94dd3f32d198dec"}diff --git a/rust/personhog-replica/.sqlx/query-a2430bffe9dd221cedb9883b777b59f1f33715d4aff7a35d44adadc62ea890b3.json b/rust/personhog-replica/.sqlx/query-d10e05207c9a3f213f79708414cbee0c9d240f828023a193865b78b034089d57.jsonsimilarity index 71%rename from rust/personhog-replica/.sqlx/query-a2430bffe9dd221cedb9883b777b59f1f33715d4aff7a35d44adadc62ea890b3.jsonrename to rust/personhog-replica/.sqlx/query-d10e05207c9a3f213f79708414cbee0c9d240f828023a193865b78b034089d57.jsonindex b20d88ee5c40..3e603b104ccf 100644--- a/rust/personhog-replica/.sqlx/query-a2430bffe9dd221cedb9883b777b59f1f33715d4aff7a35d44adadc62ea890b3.json+++ b/rust/personhog-replica/.sqlx/query-d10e05207c9a3f213f79708414cbee0c9d240f828023a193865b78b034089d57.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_group (team_id, group_type_index, group_key, group_properties, created_at, properties_last_updated_at, properties_last_operation, version)\n VALUES ($1, $2, $3, $4, $5, '{}'::jsonb, '{}'::jsonb, 0)\n RETURNING id::bigint as \"id!\", team_id::bigint as \"team_id!\",\n group_type_index, group_key, group_properties::text as \"group_properties?\",\n created_at,\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n version\n ",+ "query": "\n INSERT INTO posthog_group (team_id, group_type_index, group_key, group_properties, created_at, properties_last_updated_at, properties_last_operation, version)\n VALUES ($1, $2, $3, $4, $5, '{}'::jsonb, '{}'::jsonb, 0)\n ON CONFLICT (team_id, group_key, group_type_index) DO NOTHING\n RETURNING id::bigint as \"id!\", team_id::bigint as \"team_id!\",\n group_type_index, group_key, group_properties::text as \"group_properties?\",\n created_at,\n properties_last_updated_at::text as \"properties_last_updated_at?\",\n properties_last_operation::text as \"properties_last_operation?\",\n version\n ","describe": {"columns": [{@@ -70,5 +70,5 @@false]},- "hash": "a2430bffe9dd221cedb9883b777b59f1f33715d4aff7a35d44adadc62ea890b3"+ "hash": "d10e05207c9a3f213f79708414cbee0c9d240f828023a193865b78b034089d57"}diff --git a/rust/personhog-replica/src/storage/postgres/group.rs b/rust/personhog-replica/src/storage/postgres/group.rsindex 89e22f6ee9b2..ee0a31feca0c 100644--- a/rust/personhog-replica/src/storage/postgres/group.rs+++ b/rust/personhog-replica/src/storage/postgres/group.rs@@ -4,10 +4,38 @@ use chrono::{DateTime, Utc};use personhog_common::grpc::{current_client_name, current_method_name};use super::{ConsistencyLevel, PostgresStorage, DB_QUERY_DURATION, DB_ROWS_RETURNED};-use crate::storage::error::StorageResult;+use crate::storage::error::{StorageError, StorageResult};use crate::storage::traits::GroupStorage;use crate::storage::types::{Group, GroupIdentifier, GroupKey, GroupTypeMapping};+async fn fetch_group_by_key(+ conn: &mut sqlx::PgConnection,+ team_id: i64,+ group_type_index: i32,+ group_key: &str,+) -> StorageResult<Option<Group>> {+ let row = sqlx::query_as!(+ Group,+ r#"+ SELECT id::bigint as "id!", team_id::bigint as "team_id!",+ group_type_index, group_key, group_properties::text as "group_properties?",+ created_at,+ properties_last_updated_at::text as "properties_last_updated_at?",+ properties_last_operation::text as "properties_last_operation?",+ version+ FROM posthog_group+ WHERE team_id = $1 AND group_type_index = $2 AND group_key = $3+ "#,+ team_id as i32,+ group_type_index,+ group_key+ )+ .fetch_optional(&mut *conn)+ .await?;++ Ok(row)+}+#[async_trait]impl GroupStorage for PostgresStorage {async fn get_group(@@ -31,26 +59,7 @@ impl GroupStorage for PostgresStorage {let pool = self.pool_for_consistency(consistency);let mut conn = PostgresStorage::acquire_timed(pool, pool_label).await?;- let row = sqlx::query_as!(- Group,- r#"- SELECT id::bigint as "id!", team_id::bigint as "team_id!",- group_type_index, group_key, group_properties::text as "group_properties?",- created_at,- properties_last_updated_at::text as "properties_last_updated_at?",- properties_last_operation::text as "properties_last_operation?",- version- FROM posthog_group- WHERE team_id = $1 AND group_type_index = $2 AND group_key = $3- "#,- team_id as i32,- group_type_index,- group_key- )- .fetch_optional(&mut *conn)- .await?;-- Ok(row)+ fetch_group_by_key(&mut conn, team_id, group_type_index, group_key).await}async fn get_groups(@@ -629,11 +638,12 @@ impl GroupStorage for PostgresStorage {let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;- let row = sqlx::query_as!(+ let inserted = sqlx::query_as!(Group,r#"INSERT INTO posthog_group (team_id, group_type_index, group_key, group_properties, created_at, properties_last_updated_at, properties_last_operation, version)VALUES ($1, $2, $3, $4, $5, '{}'::jsonb, '{}'::jsonb, 0)+ ON CONFLICT (team_id, group_key, group_type_index) DO NOTHINGRETURNING id::bigint as "id!", team_id::bigint as "team_id!",group_type_index, group_key, group_properties::text as "group_properties?",created_at,@@ -647,10 +657,23 @@ impl GroupStorage for PostgresStorage {group_properties,created_at)- .fetch_one(&mut *conn)+ .fetch_optional(&mut *conn).await?;- Ok(row)+ if let Some(group) = inserted {+ return Ok(group);+ }++ // The lookup runs as a second statement, not as a CTE on the INSERT. A CTE reads the+ // INSERT's snapshot. That snapshot does not contain a row that another transaction+ // commits after the INSERT starts.+ fetch_group_by_key(&mut conn, team_id, group_type_index, group_key)+ .await?+ .ok_or_else(|| {+ StorageError::FailedPrecondition(format!(+ "group {team_id}/{group_type_index}/{group_key} deleted after insert conflict; retry"+ ))+ })}async fn update_group(diff --git a/rust/personhog-replica/src/storage/traits/group.rs b/rust/personhog-replica/src/storage/traits/group.rsindex 80363ac4ce75..4c2ef8fd2bb4 100644--- a/rust/personhog-replica/src/storage/traits/group.rs+++ b/rust/personhog-replica/src/storage/traits/group.rs@@ -48,6 +48,10 @@ pub trait GroupStorage: Send + Sync {// Group writes+ /// Inserts a group, or returns the stored group unchanged when one with the same+ /// `(team_id, group_type_index, group_key)` already exists.+ /// Returns `StorageError::FailedPrecondition` when another transaction deletes that row+ /// before this call reads it back.async fn create_group(&self,team_id: i64,diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex e6328530c289..164c6a32f39d 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -179,6 +179,91 @@ async fn test_get_group() {ctx.cleanup().await.ok();}+#[tokio::test]+async fn test_create_group_returns_existing_group_on_duplicate_key() {+ let ctx = TestContext::new().await;+ let first_properties = serde_json::json!({"name": "First"});+ let first_created_at = chrono::Utc::now() - chrono::Duration::hours(1);++ let first = ctx+ .storage+ .create_group(+ ctx.team_id,+ 0,+ "company_dup",+ &first_properties,+ first_created_at,+ )+ .await+ .expect("first create failed");++ let second = ctx+ .storage+ .create_group(+ ctx.team_id,+ 0,+ "company_dup",+ &serde_json::json!({"name": "Second"}),+ chrono::Utc::now(),+ )+ .await+ .expect("a duplicate create should return the existing group");++ assert_eq!(second.id, first.id);+ assert_eq!(second.created_at, first.created_at);+ assert_eq!(second.version, first.version);+ let second_props: serde_json::Value =+ serde_json::from_str(second.group_properties.as_deref().unwrap()).unwrap();+ assert_eq!(second_props, first_properties);++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_create_group_returns_a_group_committed_while_its_insert_waits() {+ let ctx = TestContext::new().await;++ let mut holder = ctx.pool.begin().await.unwrap();+ let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")+ .fetch_one(&mut *holder)+ .await+ .unwrap();+ let held_id: i64 = sqlx::query_scalar(+ "INSERT INTO posthog_group (team_id, group_type_index, group_key, group_properties, created_at, version) VALUES ($1, 0, 'company_race', '{}'::jsonb, NOW(), 0) RETURNING id::bigint",+ )+ .bind(ctx.team_id)+ .fetch_one(&mut *holder)+ .await+ .unwrap();++ let storage = ctx.storage.clone();+ let team_id = ctx.team_id;+ let create = tokio::spawn(async move {+ storage+ .create_group(+ team_id,+ 0,+ "company_race",+ &serde_json::json!({}),+ chrono::Utc::now(),+ )+ .await+ });++ // Commit the held row only after the create's INSERT waits on it. The row then commits+ // after the INSERT starts.+ wait_until_blocked_by(&ctx, holder_pid).await;+ holder.commit().await.unwrap();++ let group = create+ .await+ .unwrap()+ .expect("a create that waits on a committed insert should return the stored group");+ assert_eq!(group.id, held_id);++ ctx.cleanup().await.ok();+}+#[tokio::test]async fn test_get_group_type_mappings() {let ctx = TestContext::new().await;