: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(property-defs): dedupe batch inserts with SELECT DISTINCT ON (#67222)
Eli Reisman35f57d75e3d8
diff --git a/rust/property-defs-rs/.sqlx/query-364424cbad4376ed070064c75410d0f62fb0b8c577559d76814039e28abe8514.json b/rust/property-defs-rs/.sqlx/query-364424cbad4376ed070064c75410d0f62fb0b8c577559d76814039e28abe8514.jsonnew file mode 100644index 000000000000..1a77b56b355c--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-364424cbad4376ed070064c75410d0f62fb0b8c577559d76814039e28abe8514.json@@ -0,0 +1,26 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT property_type, is_numerical FROM posthog_propertydefinition WHERE name = 'brand'",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 1,+ "name": "is_numerical",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ true,+ false+ ]+ },+ "hash": "364424cbad4376ed070064c75410d0f62fb0b8c577559d76814039e28abe8514"+}diff --git a/rust/property-defs-rs/.sqlx/query-6f73f126a7076d6f54cb2ec3409b18b349764648cf5d919c361380f1895ea58a.json b/rust/property-defs-rs/.sqlx/query-6f73f126a7076d6f54cb2ec3409b18b349764648cf5d919c361380f1895ea58a.jsonnew file mode 100644index 000000000000..175cb553794f--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-6f73f126a7076d6f54cb2ec3409b18b349764648cf5d919c361380f1895ea58a.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM posthog_propertydefinition WHERE name IN ('rev_a', 'rev_b')",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "6f73f126a7076d6f54cb2ec3409b18b349764648cf5d919c361380f1895ea58a"+}diff --git a/rust/property-defs-rs/.sqlx/query-a21af4b220a7cd50f42aea0169f8aa71e2cc3033015a2eecb958803b990b9ccd.json b/rust/property-defs-rs/.sqlx/query-a21af4b220a7cd50f42aea0169f8aa71e2cc3033015a2eecb958803b990b9ccd.jsonnew file mode 100644index 000000000000..80f1e0855334--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-a21af4b220a7cd50f42aea0169f8aa71e2cc3033015a2eecb958803b990b9ccd.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM posthog_propertydefinition WHERE name IN ('brand', 'current_page')",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "a21af4b220a7cd50f42aea0169f8aa71e2cc3033015a2eecb958803b990b9ccd"+}diff --git a/rust/property-defs-rs/.sqlx/query-a7bbc6a5aadd0e4cb1707e4bbe7e88e58aabcfe52c2c00f4ca7ab29a7fc17053.json b/rust/property-defs-rs/.sqlx/query-a7bbc6a5aadd0e4cb1707e4bbe7e88e58aabcfe52c2c00f4ca7ab29a7fc17053.jsonnew file mode 100644index 000000000000..ad9a7d1c4466--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-a7bbc6a5aadd0e4cb1707e4bbe7e88e58aabcfe52c2c00f4ca7ab29a7fc17053.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT property_type, is_numerical FROM posthog_propertydefinition WHERE name = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_type",+ "type_info": "Varchar"+ },+ {+ "ordinal": 1,+ "name": "is_numerical",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true,+ false+ ]+ },+ "hash": "a7bbc6a5aadd0e4cb1707e4bbe7e88e58aabcfe52c2c00f4ca7ab29a7fc17053"+}diff --git a/rust/property-defs-rs/.sqlx/query-a90223554e9eb6366b49ed6a711a067fca4b5e1aa7456a51d153572b73170147.json b/rust/property-defs-rs/.sqlx/query-a90223554e9eb6366b49ed6a711a067fca4b5e1aa7456a51d153572b73170147.jsonnew file mode 100644index 000000000000..9e3f2ff09bc9--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-a90223554e9eb6366b49ed6a711a067fca4b5e1aa7456a51d153572b73170147.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM posthog_eventdefinition WHERE name IN ('$pageview', '$autocapture')",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "a90223554e9eb6366b49ed6a711a067fca4b5e1aa7456a51d153572b73170147"+}diff --git a/rust/property-defs-rs/.sqlx/query-eb766c4af25ebb945ae519163e16e9927259de948a0cdafbd7c994b9cbb06238.json b/rust/property-defs-rs/.sqlx/query-eb766c4af25ebb945ae519163e16e9927259de948a0cdafbd7c994b9cbb06238.jsonnew file mode 100644index 000000000000..f324d525a2b6--- /dev/null+++ b/rust/property-defs-rs/.sqlx/query-eb766c4af25ebb945ae519163e16e9927259de948a0cdafbd7c994b9cbb06238.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) FROM posthog_propertydefinition WHERE name = 'shared'",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "eb766c4af25ebb945ae519163e16e9927259de948a0cdafbd7c994b9cbb06238"+}diff --git a/rust/property-defs-rs/src/batch_ingestion.rs b/rust/property-defs-rs/src/batch_ingestion.rsindex 4d885e4e67e6..e1970127efbc 100644--- a/rust/property-defs-rs/src/batch_ingestion.rs+++ b/rust/property-defs-rs/src/batch_ingestion.rs@@ -424,9 +424,19 @@ async fn write_property_definitions_batch(loop {// what if we just ditch properties without a property_type set? why update on conflict at all?+ //+ // SELECT DISTINCT ON collapses rows that share the ON CONFLICT key before they reach the+ // insert, so a property name repeated within one batch (e.g. `brand` seen as None then+ // Numeric) can't make Postgres raise "ON CONFLICT DO UPDATE command cannot affect row a+ // second time" (SQLSTATE 21000) and roll back the whole batch. The ORDER BY+ // must lead with the DISTINCT ON keys; the trailing keys make the surviving row deterministic+ // and pick the most useful one to write - a non-null property_type (then is_numerical),+ // mirroring the DO UPDATE that only fills a NULL property_type.let result = sqlx::query(r#"INSERT INTO posthog_propertydefinition (id, name, type, group_type_index, is_numerical, team_id, project_id, property_type)- (SELECT * FROM UNNEST(+ SELECT DISTINCT ON (COALESCE(project_id, team_id::bigint), name, type, COALESCE(group_type_index, -1))+ id, name, type, group_type_index, is_numerical, team_id, project_id, property_type+ FROM UNNEST($1::uuid[],$2::varchar[],$3::smallint[],@@ -434,7 +444,11 @@ async fn write_property_definitions_batch($5::boolean[],$6::int[],$7::bigint[],- $8::varchar[]))+ $8::varchar[])+ AS t(id, name, type, group_type_index, is_numerical, team_id, project_id, property_type)+ ORDER BY+ COALESCE(project_id, team_id::bigint), name, type, COALESCE(group_type_index, -1),+ (property_type IS NOT NULL) DESC, is_numerical DESCON CONFLICT (COALESCE(project_id, team_id::bigint), name, type,COALESCE(group_type_index, -1))@@ -520,16 +534,26 @@ async fn write_event_definitions_batch(// TODO: see if we can eliminate last_seen_at from being exposed in the UI,// then convert this stmt to ON CONFLICT DO NOTHING+ //+ // SELECT DISTINCT ON collapses rows that share the ON CONFLICT key before they reach the+ // insert, so an event name repeated within one batch can't make Postgres raise "ON CONFLICT+ // DO UPDATE command cannot affect row a second time" (SQLSTATE 21000) and roll back the whole+ // batch. last_seen_at is bound to a single per-attempt timestamp for every+ // row above, so the ORDER BY tiebreak is a no-op today, but keeps the survivor deterministic.let result = sqlx::query(r#"INSERT INTO posthog_eventdefinition (id, name, team_id, project_id, last_seen_at, created_at)- (SELECT * FROM UNNEST (+ SELECT DISTINCT ON (COALESCE(project_id, team_id::bigint), name)+ id, name, team_id, project_id, last_seen_at, created_at+ FROM UNNEST ($1::uuid[],$2::varchar[],$3::int[],$4::bigint[],$5::timestamptz[],- $5::timestamptz[]))+ $5::timestamptz[])+ AS t(id, name, team_id, project_id, last_seen_at, created_at)+ ORDER BY COALESCE(project_id, team_id::bigint), name, last_seen_at DESCON CONFLICT (coalesce(project_id, team_id::bigint), name) DO UPDATESET last_seen_at=EXCLUDED.last_seen_at,created_at=COALESCE(posthog_eventdefinition.created_at, EXCLUDED.created_at)diff --git a/rust/property-defs-rs/tests/batch_ingestion.rs b/rust/property-defs-rs/tests/batch_ingestion.rsindex 349c24681f51..a521def5fd5a 100644--- a/rust/property-defs-rs/tests/batch_ingestion.rs+++ b/rust/property-defs-rs/tests/batch_ingestion.rs@@ -1,7 +1,7 @@use std::collections::HashMap;use std::sync::Arc;-use chrono::Utc;+use chrono::{DateTime, Utc};use rand::Rng;use serde_json::{json, Value};use sqlx::PgPool;@@ -9,7 +9,10 @@ use sqlx::PgPool;use property_defs_rs::{batch_ingestion::process_batch,config::Config,- types::{Event, GroupType, PropertyParentType, Update},+ types::{+ Event, EventDefinition, GroupType, PropertyDefinition, PropertyParentType,+ PropertyValueType, Update,+ },update_cache::Cache,};@@ -321,3 +324,186 @@ async fn test_property_definitions_conflict_update(db: PgPool) {assert_eq!(count, Some(1));}++fn setup_cache(config: &Config) -> Arc<Cache> {+ Arc::new(Cache::new(+ config.eventdefs_cache_capacity,+ config.eventprops_cache_capacity,+ config.propdefs_cache_capacity,+ ))+}++fn prop(+ name: &str,+ property_type: Option<PropertyValueType>,+ is_numerical: bool,+ event_type: PropertyParentType,+) -> Update {+ Update::Property(PropertyDefinition {+ team_id: 111,+ project_id: 111,+ name: name.to_string(),+ property_type,+ is_numerical,+ event_type,+ group_type_index: None,+ property_type_format: None,+ volume_30_day: None,+ query_usage_30_day: None,+ })+}++fn evt(name: &str, last_seen_at: DateTime<Utc>) -> Update {+ Update::Event(EventDefinition {+ name: name.to_string(),+ team_id: 111,+ project_id: 111,+ last_seen_at,+ })+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_property_definitions_dedupe_within_batch(db: PgPool) {+ // A property name repeated within one batch on differing mutable columns shares the ON CONFLICT+ // key. Before the SELECT DISTINCT ON dedup this raised SQLSTATE 21000 and rolled back the *whole*+ // batch - including the unrelated, genuinely-new "current_page" def. All three inputs collapse+ // to two rows and must persist.+ let config = Config::init_with_defaults().unwrap();+ let cache = setup_cache(&config);++ let batch = vec![+ prop("brand", None, false, PropertyParentType::Event),+ prop(+ "brand",+ Some(PropertyValueType::Numeric),+ true,+ PropertyParentType::Event,+ ),+ prop("current_page", None, false, PropertyParentType::Event),+ ];+ process_batch(&config, cache, &db, batch).await;++ let count: Option<i64> = sqlx::query_scalar!(+ r#"SELECT COUNT(*) FROM posthog_propertydefinition WHERE name IN ('brand', 'current_page')"#+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(+ count,+ Some(2),+ "the deduped def and the unrelated new def must both persist"+ );++ // Typed row wins on the collapsed key, mirroring the DO UPDATE.+ let brand = sqlx::query!(+ r#"SELECT property_type, is_numerical FROM posthog_propertydefinition WHERE name = 'brand'"#+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(brand.property_type, Some("Numeric".to_string()));+ assert!(brand.is_numerical);+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_property_definitions_typed_row_wins_regardless_of_order(db: PgPool) {+ // The DISTINCT ON survivor is chosen by ORDER BY, not arrival order: rev_a arrives typed-then-null,+ // rev_b arrives null-then-typed. Both must resolve to the typed row.+ let config = Config::init_with_defaults().unwrap();+ let cache = setup_cache(&config);++ let batch = vec![+ prop(+ "rev_a",+ Some(PropertyValueType::Numeric),+ true,+ PropertyParentType::Event,+ ),+ prop("rev_a", None, false, PropertyParentType::Event),+ prop("rev_b", None, false, PropertyParentType::Event),+ prop(+ "rev_b",+ Some(PropertyValueType::Numeric),+ true,+ PropertyParentType::Event,+ ),+ ];+ process_batch(&config, cache, &db, batch).await;++ for name in ["rev_a", "rev_b"] {+ let row = sqlx::query!(+ r#"SELECT property_type, is_numerical FROM posthog_propertydefinition WHERE name = $1"#,+ name+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(+ row.property_type,+ Some("Numeric".to_string()),+ "{name} should keep the typed row"+ );+ assert!(row.is_numerical, "{name} should keep is_numerical=true");+ }++ let count: Option<i64> = sqlx::query_scalar!(+ r#"SELECT COUNT(*) FROM posthog_propertydefinition WHERE name IN ('rev_a', 'rev_b')"#+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(count, Some(2));+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_property_definitions_keeps_rows_that_differ_on_conflict_key(db: PgPool) {+ // Same name, different parent type => different ON CONFLICT key; dedup must NOT collapse them.+ let config = Config::init_with_defaults().unwrap();+ let cache = setup_cache(&config);++ let batch = vec![+ prop("shared", None, false, PropertyParentType::Event),+ prop("shared", None, false, PropertyParentType::Person),+ ];+ process_batch(&config, cache, &db, batch).await;++ let count: Option<i64> = sqlx::query_scalar!(+ r#"SELECT COUNT(*) FROM posthog_propertydefinition WHERE name = 'shared'"#+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(count, Some(2));+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn test_event_definitions_dedupe_within_batch(db: PgPool) {+ // An event name repeated within one batch shares the ON CONFLICT key; before the dedup this raised+ // SQLSTATE 21000 and rolled back the whole batch, dropping the unrelated "$autocapture" def too.+ let config = Config::init_with_defaults().unwrap();+ let cache = setup_cache(&config);++ // last_seen_at is regenerated server-side to one per-attempt timestamp for every row, so the+ // value passed here doesn't affect which key-duplicate survives; this asserts the dedup itself+ // (no SQLSTATE 21000) and that the unrelated new def survives.+ let now = Utc::now();+ let batch = vec![+ evt("$pageview", now),+ evt("$pageview", now),+ evt("$autocapture", now),+ ];+ process_batch(&config, cache, &db, batch).await;++ let count: Option<i64> = sqlx::query_scalar!(+ r#"SELECT COUNT(*) FROM posthog_eventdefinition WHERE name IN ('$pageview', '$autocapture')"#+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert_eq!(+ count,+ Some(2),+ "the deduped event def and the unrelated new one must both persist"+ );+}