: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
feat(personhog): add person version floors to the replica storage (#111673)
Eli Reisman571f5e997800
diff --git a/rust/personhog-replica/.sqlx/query-a11441daea9b9c1d19d08ffcbb4abbe065aeab8968d44d5cea5df28f13377201.json b/rust/personhog-replica/.sqlx/query-a11441daea9b9c1d19d08ffcbb4abbe065aeab8968d44d5cea5df28f13377201.jsonnew file mode 100644index 000000000000..e8c727033e08--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-a11441daea9b9c1d19d08ffcbb4abbe065aeab8968d44d5cea5df28f13377201.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO posthog_person (uuid, team_id, properties, properties_last_updated_at,\n properties_last_operation, created_at, version,\n is_identified, is_deleted)\n SELECT f.uuid, $1, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, NOW(), f.version, false, true\n FROM UNNEST($2::uuid[], $3::bigint[]) AS f(uuid, version)\n ON CONFLICT (team_id, uuid) DO NOTHING\n RETURNING id::bigint as \"id!\", uuid as \"uuid!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "uuid!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "UuidArray",+ "Int8Array"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "a11441daea9b9c1d19d08ffcbb4abbe065aeab8968d44d5cea5df28f13377201"+}diff --git a/rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.json b/rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.jsonnew file mode 100644index 000000000000..6db73d6cdcc0--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id::bigint as \"id!\", uuid as \"uuid!\",\n COALESCE(version, 0)::bigint as \"version!\", is_deleted as \"is_deleted!\"\n FROM posthog_person\n WHERE team_id = $1 AND uuid = ANY($2)\n ORDER BY id FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "uuid!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "version!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "is_deleted!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ false+ ]+ },+ "hash": "addc1747821f2f45601a9524ee8f70aa58c8c2173e9e9aa2ba18632a5da005db"+}diff --git a/rust/personhog-replica/.sqlx/query-aebd2a9bd2d9292a6778dfee92a71dc6bac93c7da61b434543b2ef7e3498a33b.json b/rust/personhog-replica/.sqlx/query-aebd2a9bd2d9292a6778dfee92a71dc6bac93c7da61b434543b2ef7e3498a33b.jsonnew file mode 100644index 000000000000..03c48e263862--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-aebd2a9bd2d9292a6778dfee92a71dc6bac93c7da61b434543b2ef7e3498a33b.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_person p\n SET version = f.min_version\n FROM UNNEST($2::bigint[], $3::bigint[]) AS f(id, min_version)\n WHERE p.team_id = $1 AND p.id = f.id\n AND COALESCE(p.version, 0) < f.min_version\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Int8Array",+ "Int8Array"+ ]+ },+ "nullable": []+ },+ "hash": "aebd2a9bd2d9292a6778dfee92a71dc6bac93c7da61b434543b2ef7e3498a33b"+}diff --git a/rust/personhog-replica/src/service/tests/mocks.rs b/rust/personhog-replica/src/service/tests/mocks.rsindex d3dcfc40082e..adcc53bee39b 100644--- a/rust/personhog-replica/src/service/tests/mocks.rs+++ b/rust/personhog-replica/src/service/tests/mocks.rs@@ -167,6 +167,14 @@ impl storage::PersonLookup for FailingStorage {) -> storage::StorageResult<bool> {Err(self.error.clone())}++ async fn ensure_person_version_floors(+ &self,+ _team_id: i64,+ _floors: &[(Uuid, i64)],+ ) -> storage::StorageResult<Vec<storage::PersonVersionFloorResult>> {+ Err(self.error.clone())+ }}#[async_trait]@@ -580,6 +588,14 @@ impl storage::PersonLookup for SuccessStorage {) -> storage::StorageResult<bool> {Ok(false)}++ async fn ensure_person_version_floors(+ &self,+ _team_id: i64,+ _floors: &[(Uuid, i64)],+ ) -> storage::StorageResult<Vec<storage::PersonVersionFloorResult>> {+ Ok(Vec::new())+ }}#[async_trait]@@ -1052,6 +1068,14 @@ impl storage::PersonLookup for PopulatedStorage {) -> storage::StorageResult<bool> {Ok(false)}++ async fn ensure_person_version_floors(+ &self,+ _team_id: i64,+ _floors: &[(Uuid, i64)],+ ) -> storage::StorageResult<Vec<storage::PersonVersionFloorResult>> {+ Ok(Vec::new())+ }}#[async_trait]@@ -1500,6 +1524,14 @@ impl storage::PersonLookup for ConsistencyTrackingStorage {) -> storage::StorageResult<bool> {Ok(false)}++ async fn ensure_person_version_floors(+ &self,+ _team_id: i64,+ _floors: &[(Uuid, i64)],+ ) -> storage::StorageResult<Vec<storage::PersonVersionFloorResult>> {+ Ok(Vec::new())+ }}#[async_trait]diff --git a/rust/personhog-replica/src/storage/mod.rs b/rust/personhog-replica/src/storage/mod.rsindex 0c1b357efa79..5ee9407cdfb0 100644--- a/rust/personhog-replica/src/storage/mod.rs+++ b/rust/personhog-replica/src/storage/mod.rs@@ -8,7 +8,8 @@ pub use error::{StorageError, StorageResult};pub use types::{CohortMembership, DeletePersonsOutcome, DistinctIdMapping, DistinctIdWithVersion, Group,GroupIdentifier, GroupKey, GroupTypeMapping, HashKeyOverride, HashKeyOverrideContext, Person,- SplitResult, TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,+ PersonVersionFloorResult, SplitResult, TombstonedDeleteOutcome, TombstonedDistinctId,+ TombstonedPerson, VersionFloorOutcome,};pub use traits::{CohortStorage, DistinctIdLookup, FeatureFlagStorage, GroupStorage, PersonLookup};diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex d96e5b43acb6..9278653b66ef 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -13,8 +13,8 @@ use super::{PostgresStorage, DB_BULK_CHUNKS, DB_QUERY_DURATION, DB_ROWS_RETURNEDuse crate::storage::error::{StorageError, StorageResult};use crate::storage::traits::PersonLookup;use crate::storage::types::{- DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult, TombstonedDeleteOutcome,- TombstonedDistinctId, TombstonedPerson,+ DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, PersonVersionFloorResult, SplitResult,+ TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson, VersionFloorOutcome,};/// Version offset for split person/PDI rows — mirrors the Django convention.@@ -1285,6 +1285,236 @@ impl PersonLookup for PostgresStorage {Ok(result.rows_affected() > 0)}++ async fn ensure_person_version_floors(+ &self,+ team_id: i64,+ floors: &[(Uuid, i64)],+ ) -> StorageResult<Vec<PersonVersionFloorResult>> {+ if floors.is_empty() {+ return Ok(Vec::new());+ }+ let labels = bulk_primary_labels("ensure_person_version_floors");+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);++ let mut tx = self.bulk_primary_pool.begin().await?;+ // A held row means a merge, revival or delete in flight: fail fast and let+ // the caller retry instead of queueing behind it.+ sqlx::query("SET LOCAL lock_timeout = '2s'")+ .execute(&mut *tx)+ .await?;++ let uuids: Vec<Uuid> = floors.iter().map(|(uuid, _)| *uuid).collect();+ let mut before = lock_persons_by_uuids(&mut tx, team_id, &uuids).await?;++ // Insert in uuid order, so two calls racing on the same new uuids wait on each+ // other's inserts in one order and cannot deadlock.+ let mut absent: Vec<(Uuid, i64)> = floors+ .iter()+ .filter(|(uuid, _)| !before.contains_key(uuid))+ .copied()+ .collect();+ absent.sort_unstable_by_key(|(uuid, _)| *uuid);+ let (absent_uuids, absent_mins): (Vec<Uuid>, Vec<i64>) = absent.into_iter().unzip();+ let inserted =+ insert_person_tombstones(&mut tx, team_id, &absent_uuids, &absent_mins).await?;++ // ON CONFLICT DO NOTHING waited for a concurrent insert of the same uuid and+ // skipped it. Lock and classify that row like any other existing row.+ let raced: Vec<Uuid> = absent_uuids+ .iter()+ .filter(|uuid| !inserted.contains_key(uuid))+ .copied()+ .collect();+ if !raced.is_empty() {+ let late = lock_persons_by_uuids(&mut tx, team_id, &raced).await?;+ if late.len() != raced.len() {+ return Err(StorageError::FailedPrecondition(format!(+ "person rows changed during ensure_person_version_floors (team_id={team_id}); retry"+ )));+ }+ before.extend(late);+ }++ let (raise_ids, raise_mins): (Vec<i64>, Vec<i64>) = floors+ .iter()+ .filter_map(|(uuid, min_version)| {+ before+ .get(uuid)+ .filter(|row| row.is_deleted && row.version < *min_version)+ .map(|row| (row.id, *min_version))+ })+ .unzip();+ if !raise_ids.is_empty() {+ sqlx::query!(+ r#"+ UPDATE posthog_person p+ SET version = f.min_version+ FROM UNNEST($2::bigint[], $3::bigint[]) AS f(id, min_version)+ WHERE p.team_id = $1 AND p.id = f.id+ AND COALESCE(p.version, 0) < f.min_version+ "#,+ team_id as i32,+ &raise_ids,+ &raise_mins+ )+ .execute(&mut *tx)+ .await?;+ }++ tx.commit().await?;++ let results = floors+ .iter()+ .map(|(uuid, min_version)| {+ if inserted.contains_key(uuid) {+ return PersonVersionFloorResult {+ uuid: *uuid,+ outcome: VersionFloorOutcome::TombstoneInserted,+ version: *min_version,+ };+ }+ let row = &before[uuid];+ PersonVersionFloorResult {+ uuid: *uuid,+ outcome: VersionFloorOutcome::for_existing(+ row.is_deleted,+ row.version,+ *min_version,+ ),+ version: if row.is_deleted {+ row.version.max(*min_version)+ } else {+ row.version+ },+ }+ })+ .collect::<Vec<_>>();+ record_floor_outcomes(+ "ensure_person_version_floors",+ results.iter().map(|r| r.outcome),+ );+ Ok(results)+ }+}++fn bulk_primary_labels(operation: &str) -> [(String, String); 4] {+ [+ ("operation".to_string(), operation.to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),+ ("client".to_string(), current_client_name().to_string()),+ ("method".to_string(), current_method_name().to_string()),+ ]+}++const VERSION_FLOOR_OUTCOMES_TOTAL: &str = "personhog_replica_version_floor_outcomes_total";++fn record_floor_outcomes(operation: &str, outcomes: impl Iterator<Item = VersionFloorOutcome>) {+ record_outcomes(+ VERSION_FLOOR_OUTCOMES_TOTAL,+ operation,+ outcomes.map(|outcome| match outcome {+ VersionFloorOutcome::TombstoneInserted => "tombstone_inserted",+ VersionFloorOutcome::TombstoneRaised => "tombstone_raised",+ VersionFloorOutcome::TombstoneAtFloor => "tombstone_at_floor",+ VersionFloorOutcome::Live => "live",+ }),+ );+}++/// Count each outcome label once per call, so a batch costs one increment per label.+fn record_outcomes(+ metric: &'static str,+ operation: &str,+ outcomes: impl Iterator<Item = &'static str>,+) {+ let mut counts: HashMap<&'static str, u64> = HashMap::new();+ for outcome in outcomes {+ *counts.entry(outcome).or_default() += 1;+ }+ let client = current_client_name();+ for (outcome, count) in counts {+ common_metrics::inc(+ metric,+ &[+ ("operation".to_string(), operation.to_string()),+ ("outcome".to_string(), outcome.to_string()),+ ("client".to_string(), client.to_string()),+ ],+ count,+ );+ }+}++struct LockedPerson {+ id: i64,+ version: i64,+ is_deleted: bool,+}++/// Lock the existing persons among `uuids` in id order, the order the ingestion+/// writer and the tombstone paths take person locks in.+async fn lock_persons_by_uuids(+ tx: &mut Transaction<'_, Postgres>,+ team_id: i64,+ uuids: &[Uuid],+) -> StorageResult<HashMap<Uuid, LockedPerson>> {+ let rows = sqlx::query!(+ r#"+ SELECT id::bigint as "id!", uuid as "uuid!",+ COALESCE(version, 0)::bigint as "version!", is_deleted as "is_deleted!"+ FROM posthog_person+ WHERE team_id = $1 AND uuid = ANY($2)+ ORDER BY id FOR UPDATE+ "#,+ team_id as i32,+ uuids+ )+ .fetch_all(&mut **tx)+ .await?;+ Ok(rows+ .into_iter()+ .map(|row| {+ (+ row.uuid,+ LockedPerson {+ id: row.id,+ version: row.version,+ is_deleted: row.is_deleted,+ },+ )+ })+ .collect())+}++/// Insert scrubbed person tombstones, skipping any uuid a concurrent transaction+/// inserted first. Returns the inserted rows' ids by uuid.+async fn insert_person_tombstones(+ tx: &mut Transaction<'_, Postgres>,+ team_id: i64,+ uuids: &[Uuid],+ versions: &[i64],+) -> StorageResult<HashMap<Uuid, i64>> {+ if uuids.is_empty() {+ return Ok(HashMap::new());+ }+ let rows = sqlx::query!(+ r#"+ INSERT INTO posthog_person (uuid, team_id, properties, properties_last_updated_at,+ properties_last_operation, created_at, version,+ is_identified, is_deleted)+ SELECT f.uuid, $1, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, NOW(), f.version, false, true+ FROM UNNEST($2::uuid[], $3::bigint[]) AS f(uuid, version)+ ON CONFLICT (team_id, uuid) DO NOTHING+ RETURNING id::bigint as "id!", uuid as "uuid!"+ "#,+ team_id as i32,+ uuids,+ versions+ )+ .fetch_all(&mut **tx)+ .await?;+ Ok(rows.into_iter().map(|row| (row.uuid, row.id)).collect())}/// Tombstone the requested persons in one transaction, so the caller getsdiff --git a/rust/personhog-replica/src/storage/traits/person.rs b/rust/personhog-replica/src/storage/traits/person.rsindex d6d7684e8fa6..7d0bdc122421 100644--- a/rust/personhog-replica/src/storage/traits/person.rs+++ b/rust/personhog-replica/src/storage/traits/person.rs@@ -3,8 +3,8 @@ use uuid::Uuid;use crate::storage::error::StorageResult;use crate::storage::types::{- DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, SplitResult, TombstonedDeleteOutcome,- TombstonedPerson,+ DeletePersonsOutcome, Person, PersonTombstoneQueueEntry, PersonVersionFloorResult, SplitResult,+ TombstonedDeleteOutcome, TombstonedPerson,};/// Person lookup operations by ID, UUID, and distinct ID@@ -144,4 +144,12 @@ pub trait PersonLookup: Send + Sync {person_id: i64,min_version: i64,) -> StorageResult<bool>;++ /// Raise each person tombstone to at least its min version in one primary transaction, inserting a+ /// tombstone for a missing person and leaving a live row unchanged; `floors` must not repeat a uuid.+ async fn ensure_person_version_floors(+ &self,+ team_id: i64,+ floors: &[(Uuid, i64)],+ ) -> StorageResult<Vec<PersonVersionFloorResult>>;}diff --git a/rust/personhog-replica/src/storage/types/person.rs b/rust/personhog-replica/src/storage/types/person.rsindex 69c1955dda24..25bc23832934 100644--- a/rust/personhog-replica/src/storage/types/person.rs+++ b/rust/personhog-replica/src/storage/types/person.rs@@ -63,6 +63,32 @@ pub struct TombstonedDeleteOutcome {pub rows_deleted: i64,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum VersionFloorOutcome {+ TombstoneInserted,+ TombstoneRaised,+ TombstoneAtFloor,+ Live,+}++impl VersionFloorOutcome {+ /// Classify a row that existed before the call, from its state then.+ pub fn for_existing(is_deleted: bool, version: i64, min_version: i64) -> Self {+ match (is_deleted, version < min_version) {+ (false, _) => Self::Live,+ (true, true) => Self::TombstoneRaised,+ (true, false) => Self::TombstoneAtFloor,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PersonVersionFloorResult {+ pub uuid: Uuid,+ pub outcome: VersionFloorOutcome,+ pub version: i64,+}+#[derive(Debug, Clone)]pub struct SplitResult {pub distinct_id: String,diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex 48660e9063d7..57de39ee8c56 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -4,7 +4,8 @@ use common::TestContext;use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};use personhog_replica::storage::postgres::ConsistencyLevel;use personhog_replica::storage::{- GroupKey, TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson,+ GroupKey, PersonVersionFloorResult, StorageError, TombstonedDeleteOutcome,+ TombstonedDistinctId, TombstonedPerson, VersionFloorOutcome,};use rand::Rng;use rstest::rstest;@@ -4189,13 +4190,26 @@ async fn test_delete_tombstoned_persons_cross_team_isolation() {other.cleanup().await.ok();}+#[derive(Debug, Clone, Copy)]+enum HeldRowWrite {+ DeleteTombstoned,+ EnsurePersonFloor,+}++#[rstest]+#[case::delete_tombstoned(HeldRowWrite::DeleteTombstoned)]+#[case::ensure_person_floor(HeldRowWrite::EnsurePersonFloor)]#[tokio::test]-async fn test_delete_tombstoned_persons_gives_up_when_a_writer_holds_the_row() {+async fn test_primary_writes_give_up_when_a_writer_holds_the_row(#[case] write: HeldRowWrite) {// lock_timeout makes the request fail fast behind a held row; without it this call would// block until the holder commits.let ctx = TestContext::new().await;- let person = ctx.insert_person("tomb_locked", None).await.unwrap();- ctx.tombstone_person(person.id, None).await.unwrap();+ let person = ctx.insert_person("held_row", None).await.unwrap();+ if matches!(write, HeldRowWrite::DeleteTombstoned) {+ ctx.tombstone_person(person.id, None).await.unwrap();+ }+ let person_before = person_state(&ctx, person.uuid).await;+ let distinct_id_before = distinct_id_state(&ctx, "held_row").await;let mut holder = ctx.pool.begin().await.unwrap();sqlx::query("SELECT id FROM posthog_person WHERE team_id = $1 AND id = $2 FOR UPDATE").bind(ctx.team_id)@@ -4205,21 +4219,308 @@ async fn test_delete_tombstoned_persons_gives_up_when_a_writer_holds_the_row() {.unwrap();let started = Instant::now();- let result = ctx- .storage- .delete_tombstoned_persons(ctx.team_id, &[person.uuid], TEST_MAX_ROWS)- .await;+ let result = match write {+ HeldRowWrite::DeleteTombstoned => ctx+ .storage+ .delete_tombstoned_persons(ctx.team_id, &[person.uuid], TEST_MAX_ROWS)+ .await+ .map(|_| ()),+ HeldRowWrite::EnsurePersonFloor => ctx+ .storage+ .ensure_person_version_floors(ctx.team_id, &[(person.uuid, 5)])+ .await+ .map(|_| ()),+ };assert!(- matches!(- result,- Err(personhog_replica::storage::StorageError::Query(_))- ),- "expected the lock_timeout to fail the chunk, got {result:?}"+ matches!(result, Err(StorageError::Query(_))),+ "expected the lock_timeout to fail the request, got {result:?}");assert!(started.elapsed() < Duration::from_secs(20));holder.rollback().await.unwrap();- assert!(ctx.person_row_exists(person.id).await.unwrap());+ assert_eq!(person_state(&ctx, person.uuid).await, person_before);+ assert_eq!(+ distinct_id_state(&ctx, "held_row").await,+ distinct_id_before+ );+ assert_eq!(distinct_id_state(&ctx, "held_row_absent").await, None);++ ctx.cleanup().await.ok();+}++// ============================================================+// Version floor tests+// ============================================================++type PersonState = (Option<i64>, bool, serde_json::Value);++/// (version, is_deleted, properties) of the person row with `uuid`.+async fn person_state(ctx: &TestContext, uuid: Uuid) -> Option<PersonState> {+ sqlx::query_as(+ "SELECT version, is_deleted, properties FROM posthog_person WHERE team_id = $1 AND uuid = $2",+ )+ .bind(ctx.team_id)+ .bind(uuid)+ .fetch_optional(&ctx.pool)+ .await+ .unwrap()+}++async fn person_id_of(ctx: &TestContext, uuid: Uuid) -> i64 {+ sqlx::query_scalar("SELECT id FROM posthog_person WHERE team_id = $1 AND uuid = $2")+ .bind(ctx.team_id)+ .bind(uuid)+ .fetch_one(&ctx.pool)+ .await+ .unwrap()+}++/// (person_id, version, is_deleted) of the distinct id row.+async fn distinct_id_state(+ ctx: &TestContext,+ distinct_id: &str,+) -> Option<(i64, Option<i64>, bool)> {+ sqlx::query_as(+ "SELECT person_id, version, is_deleted FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",+ )+ .bind(ctx.team_id)+ .bind(distinct_id)+ .fetch_optional(&ctx.pool)+ .await+ .unwrap()+}++async fn wait_until_blocked_by(ctx: &TestContext, holder_pid: i32) {+ let deadline = Instant::now() + Duration::from_millis(1500);+ loop {+ let blocked: bool = sqlx::query_scalar(+ "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))",+ )+ .bind(holder_pid)+ .fetch_one(&ctx.pool)+ .await+ .unwrap();+ if blocked {+ return;+ }+ assert!(+ Instant::now() < deadline,+ "the request never waited on the holder"+ );+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+}++/// The conflict clauses of the nodejs createPerson upsert: a tombstoned person or+/// distinct id revives at its stored version + 1. Returns the rows written.+async fn revive_with_ingestion_upsert(ctx: &TestContext, uuid: Uuid, distinct_id: &str) -> i64 {+ sqlx::query_scalar(+ r#"+ WITH inserted_person AS (+ INSERT INTO posthog_person (+ created_at, properties, properties_last_updated_at, properties_last_operation,+ team_id, is_user_id, is_identified, uuid, version+ )+ VALUES (NOW(), '{"revived": true}', '{}', '{}', $1, NULL, false, $2, 0)+ ON CONFLICT (team_id, uuid) DO UPDATE SET+ is_deleted = false,+ version = COALESCE(posthog_person.version, 0) + 1,+ properties = EXCLUDED.properties+ WHERE posthog_person.is_deleted = true+ RETURNING id+ ),+ inserted_distinct_ids AS (+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)+ SELECT $3, ip.id, $1, 0+ FROM inserted_person ip+ ON CONFLICT (team_id, distinct_id) DO UPDATE SET+ person_id = EXCLUDED.person_id,+ version = COALESCE(posthog_persondistinctid.version, 0) + 1,+ is_deleted = false+ WHERE posthog_persondistinctid.is_deleted = true+ RETURNING id+ )+ SELECT (SELECT count(*) FROM inserted_person) + (SELECT count(*) FROM inserted_distinct_ids)+ "#,+ )+ .bind(ctx.team_id)+ .bind(uuid)+ .bind(distinct_id)+ .fetch_one(&ctx.pool)+ .await+ .unwrap()+}++#[tokio::test]+async fn test_ensure_person_version_floors_outcomes_and_idempotence() {+ use VersionFloorOutcome::*;+ let ctx = TestContext::new().await;+ // (seeded (version, is_deleted), min_version, outcome, reported version)+ let cases = vec![+ (None, 7, TombstoneInserted, 7),+ (Some((Some(3), true)), 5, TombstoneRaised, 5),+ (Some((Some(5), true)), 5, TombstoneAtFloor, 5),+ (Some((Some(9), true)), 5, TombstoneAtFloor, 9),+ (Some((None, true)), 0, TombstoneAtFloor, 0),+ (Some((None, true)), 4, TombstoneRaised, 4),+ (Some((Some(2), false)), 6, Live, 2),+ (Some((Some(8), false)), 6, Live, 8),+ (Some((None, false)), 3, Live, 0),+ ];+ let mut floors = Vec::new();+ for (i, (seed, min_version, _, _)) in cases.iter().enumerate() {+ let uuid = match seed {+ Some((version, is_deleted)) => {+ seed_person(&ctx, &format!("floor_person_{i}"), *version, *is_deleted)+ .await+ .uuid+ }+ None => Uuid::now_v7(),+ };+ floors.push((uuid, *min_version));+ }++ let results = ctx+ .storage+ .ensure_person_version_floors(ctx.team_id, &floors)+ .await+ .unwrap();++ let expected: Vec<PersonVersionFloorResult> = floors+ .iter()+ .zip(&cases)+ .map(+ |((uuid, _), (_, _, outcome, version))| PersonVersionFloorResult {+ uuid: *uuid,+ outcome: *outcome,+ version: *version,+ },+ )+ .collect();+ assert_eq!(results, expected);+ for ((uuid, min_version), (seed, _, _, version)) in floors.iter().zip(&cases) {+ let expected_state = match seed {+ None => (Some(*min_version), true, serde_json::json!({})),+ Some((seeded_version, is_deleted)) => (+ if *is_deleted && seeded_version.unwrap_or(0) < *min_version {+ Some(*version)+ } else {+ *seeded_version+ },+ *is_deleted,+ serde_json::json!({"seeded": true}),+ ),+ };+ assert_eq!(+ person_state(&ctx, *uuid).await,+ Some(expected_state),+ "{uuid}"+ );+ }++ // A redelivered call changes nothing and reports the versions the first call left.+ let again = ctx+ .storage+ .ensure_person_version_floors(ctx.team_id, &floors)+ .await+ .unwrap();+ let expected_again: Vec<PersonVersionFloorResult> = expected+ .into_iter()+ .map(|result| PersonVersionFloorResult {+ outcome: match result.outcome {+ TombstoneInserted | TombstoneRaised => TombstoneAtFloor,+ outcome => outcome,+ },+ ..result+ })+ .collect();+ assert_eq!(again, expected_again);++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_ingestion_revives_above_the_written_tombstone() {+ let ctx = TestContext::new().await;+ let uuid = Uuid::now_v7();+ let distinct_id = "revived";+ ctx.storage+ .ensure_person_version_floors(ctx.team_id, &[(uuid, 5)])+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(person_id_of(&ctx, uuid).await, distinct_id)+ .await+ .unwrap();+ set_distinct_id_state(&ctx, distinct_id, Some(0), true).await;++ assert_eq!(+ revive_with_ingestion_upsert(&ctx, uuid, distinct_id).await,+ 2+ );++ assert_eq!(+ person_state(&ctx, uuid).await,+ Some((Some(6), false, serde_json::json!({"revived": true})))+ );+ assert_eq!(+ distinct_id_state(&ctx, distinct_id).await,+ Some((person_id_of(&ctx, uuid).await, Some(1), false))+ );++ ctx.cleanup().await.ok();+}++#[rstest]+#[case::person_insert_commits(true, VersionFloorOutcome::Live)]+#[case::person_insert_rolls_back(false, VersionFloorOutcome::TombstoneInserted)]+#[tokio::test]+async fn test_ensure_version_floors_wait_for_a_concurrent_insert(+ #[case] commit: bool,+ #[case] expected_outcome: VersionFloorOutcome,+) {+ let ctx = TestContext::new().await;+ let uuid = Uuid::now_v7();+ 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();+ sqlx::query(+ r#"INSERT INTO posthog_person+ (id, uuid, team_id, properties, properties_last_updated_at,+ properties_last_operation, created_at, version, is_identified)+ VALUES ($1, $2, $3, '{}', '{}', '{}', NOW(), 0, false)"#,+ )+ .bind(rand::thread_rng().gen_range(1_000_000i64..100_000_000))+ .bind(uuid)+ .bind(ctx.team_id)+ .execute(&mut *holder)+ .await+ .unwrap();++ let storage = ctx.storage.clone();+ let team_id = ctx.team_id;+ let request = tokio::spawn(async move {+ storage+ .ensure_person_version_floors(team_id, &[(uuid, 3)])+ .await+ .map(|results| (results[0].outcome, results[0].version))+ });+ // Only the ON CONFLICT insert can wait here: the locking reads skip uncommitted rows.+ wait_until_blocked_by(&ctx, holder_pid).await;+ if commit {+ holder.commit().await.unwrap();+ } else {+ holder.rollback().await.unwrap();+ }++ // The committed insert is live at version 0, which the call leaves unchanged.+ let (version, is_deleted) = if commit { (0, false) } else { (3, true) };+ assert_eq!(request.await.unwrap().unwrap(), (expected_outcome, version));+ assert_eq!(+ person_state(&ctx, uuid).await,+ Some((Some(version), is_deleted, serde_json::json!({})))+ );ctx.cleanup().await.ok();}