: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): tombstone-aware reads and revival on recreate (#74126)
José Sequeira7adab667095c
diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.test.tsindex 19f5fc6dc3b3..0a64855a683c 100644--- a/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.test.ts@@ -201,6 +201,60 @@ describe('PostgresPersonRepository', () => {})})+ describe('tombstoned rows', () => {+ async function tombstonePerson(person: InternalPerson): Promise<void> {+ await postgres.query(+ PostgresUse.PERSONS_WRITE,+ 'UPDATE posthog_person SET is_deleted = true, version = version + 1 WHERE team_id = $1 AND id = $2',+ [person.team_id, person.id],+ 'tombstonePerson'+ )+ }++ async function tombstoneDistinctId(teamId: number, distinctId: string): Promise<void> {+ await postgres.query(+ PostgresUse.PERSONS_WRITE,+ 'UPDATE posthog_persondistinctid SET is_deleted = true, version = COALESCE(version, 0) + 1 WHERE team_id = $1 AND distinct_id = $2',+ [teamId, distinctId],+ 'tombstoneDistinctId'+ )+ }++ it('excludes tombstoned persons from person reads', async () => {+ const team = await getFirstTeam(hub.postgres)+ const person = await createTestPerson(team.id, 'tombstoned-person-did')+ await tombstonePerson(person)++ await expect(repository.fetchPerson(team.id, 'tombstoned-person-did')).resolves.toBeUndefined()+ await expect(+ repository.fetchPersonsByDistinctIds([{ teamId: team.id, distinctId: 'tombstoned-person-did' }])+ ).resolves.toEqual([])+ await expect(+ repository.fetchPersonsForUpdateByDistinctIds(team.id, ['tombstoned-person-did'])+ ).resolves.toEqual([])+ await expect(+ repository.fetchPersonsByPersonIds([{ teamId: team.id, personId: person.uuid }])+ ).resolves.toEqual([])+ })++ it('excludes tombstoned distinct id mappings from reads while live mappings still resolve', async () => {+ const team = await getFirstTeam(hub.postgres)+ const person = await createTestPerson(team.id, 'live-did')+ await repository.addDistinctId(person, 'dead-did', 0)+ await tombstoneDistinctId(team.id, 'dead-did')++ await expect(repository.fetchPerson(team.id, 'dead-did')).resolves.toBeUndefined()+ await expect(repository.fetchPerson(team.id, 'live-did')).resolves.toMatchObject({ uuid: person.uuid })+ await expect(repository.fetchPersonDistinctIds(person)).resolves.toEqual(['live-did'])+ await expect(repository.fetchDistinctIdsForPersons(team.id, [person.id])).resolves.toEqual({+ [person.id]: ['live-did'],+ })+ await expect(repository.countDistinctIdsForPersons(team.id, [person.id])).resolves.toEqual(+ new Map([[person.id, 1]])+ )+ })+ })+describe('createPerson()', () => {it('creates a person with basic properties', async () => {const team = await getFirstTeam(hub.postgres)diff --git a/nodejs/src/common/persons/repositories/postgres-person-repository.ts b/nodejs/src/common/persons/repositories/postgres-person-repository.tsindex 9e194a4dcd34..6f0f2669a14b 100644--- a/nodejs/src/common/persons/repositories/postgres-person-repository.ts+++ b/nodejs/src/common/persons/repositories/postgres-person-repository.ts@@ -270,7 +270,9 @@ export class PostgresPersonRepositoryWHEREposthog_person.team_id = $1AND posthog_persondistinctid.team_id = $1- AND posthog_persondistinctid.distinct_id = $2`+ AND posthog_persondistinctid.distinct_id = $2+ AND posthog_persondistinctid.is_deleted = false+ AND posthog_person.is_deleted = false`if (options.forUpdate) {// Locks the teamId and distinctId tied to this personId + this person's infoqueryString = queryString.concat(` FOR UPDATE`)@@ -335,7 +337,10 @@ export class PostgresPersonRepository)JOIN UNNEST($1::integer[], $2::text[]) AS batch(team_id, distinct_id)ON posthog_persondistinctid.team_id = batch.team_id- AND posthog_persondistinctid.distinct_id = batch.distinct_id`+ AND posthog_persondistinctid.distinct_id = batch.distinct_id+ WHERE+ posthog_persondistinctid.is_deleted = false+ AND posthog_person.is_deleted = false`const { rows } = await this.postgres.query<RawPerson & { distinct_id: string }>(useReadReplica ? PostgresUse.PERSONS_READ : PostgresUse.PERSONS_WRITE,@@ -386,6 +391,8 @@ export class PostgresPersonRepositoryposthog_person.team_id = $1AND posthog_persondistinctid.team_id = $1AND posthog_persondistinctid.distinct_id = ANY($2::text[])+ AND posthog_persondistinctid.is_deleted = false+ AND posthog_person.is_deleted = falseORDER BY posthog_person.idFOR UPDATE`@@ -441,7 +448,8 @@ export class PostgresPersonRepositoryposthog_person.is_identified,posthog_person.last_seen_atFROM posthog_person- WHERE (posthog_person.team_id, posthog_person.uuid) IN (SELECT * FROM UNNEST($1::integer[], $2::uuid[]))`+ WHERE (posthog_person.team_id, posthog_person.uuid) IN (SELECT * FROM UNNEST($1::integer[], $2::uuid[]))+ AND posthog_person.is_deleted = false`const { rows } = await this.postgres.query<RawPerson>(useReadReplica ? PostgresUse.PERSONS_READ : PostgresUse.PERSONS_WRITE,@@ -473,7 +481,7 @@ export class PostgresPersonRepositoryJOIN LATERAL (SELECT distinct_id, id AS pdi_idFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = p.id+ WHERE team_id = $1 AND person_id = p.id AND is_deleted = falseORDER BY id ASCLIMIT $3::bigint) pdi ON true`@@ -902,7 +910,7 @@ export class PostgresPersonRepositorytx ?? PostgresUse.PERSONS_WRITE,`SELECT person_id, count(*) AS countFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = ANY($2::bigint[])+ WHERE team_id = $1 AND person_id = ANY($2::bigint[]) AND is_deleted = falseGROUP BY person_id`,[teamId, personIds],'countDistinctIdsForPersons'@@ -987,14 +995,14 @@ export class PostgresPersonRepository? `SELECT distinct_idFROM posthog_persondistinctid- WHERE person_id = $1 AND team_id = $2+ WHERE person_id = $1 AND team_id = $2 AND is_deleted = falseORDER BY idLIMIT $3`: `SELECT distinct_idFROM posthog_persondistinctid- WHERE person_id = $1 AND team_id = $2+ WHERE person_id = $1 AND team_id = $2 AND is_deleted = falseORDER BY id`diff --git a/posthog/dags/detach_distinct_id.py b/posthog/dags/detach_distinct_id.pyindex 2b82096f6326..acecd4968be4 100644--- a/posthog/dags/detach_distinct_id.py+++ b/posthog/dags/detach_distinct_id.py@@ -74,6 +74,7 @@ def _lookup_distinct_id(FROM posthog_persondistinctid pdiJOIN posthog_person p ON p.id = pdi.person_id AND p.team_id = pdi.team_idWHERE pdi.team_id = %s AND pdi.distinct_id = %s+ AND pdi.is_deleted = false AND p.is_deleted = false""",[team_id, distinct_id],)@@ -107,7 +108,7 @@ def _count_other_distinct_ids("""SELECT COUNT(*) AS countFROM posthog_persondistinctid- WHERE team_id = %s AND person_id = %s AND id != %s+ WHERE team_id = %s AND person_id = %s AND id != %s AND is_deleted = false""",[team_id, person_pk, exclude_pdi_id],)diff --git a/posthog/dags/person_property_reconciliation.py b/posthog/dags/person_property_reconciliation.pyindex e9eb63567ec2..e4bfd46c65b2 100644--- a/posthog/dags/person_property_reconciliation.py+++ b/posthog/dags/person_property_reconciliation.py@@ -1405,7 +1405,7 @@ def fetch_person_from_postgres(cursor, team_id: int, person_uuid: str) -> dict |is_identified,created_atFROM posthog_person- WHERE team_id = %s AND uuid = %s::uuid+ WHERE team_id = %s AND uuid = %s::uuid AND is_deleted = false""",(team_id, person_uuid),)diff --git a/posthog/dags/person_property_reconciliation_restore.py b/posthog/dags/person_property_reconciliation_restore.pyindex dea8e30d178c..d26b19d5a1a4 100644--- a/posthog/dags/person_property_reconciliation_restore.py+++ b/posthog/dags/person_property_reconciliation_restore.py@@ -139,7 +139,7 @@ def fetch_person_by_id(cursor, team_id: int, person_id: int) -> dict | None:created_at,is_user_idFROM posthog_person- WHERE team_id = %s AND id = %s+ WHERE team_id = %s AND id = %s AND is_deleted = false""",(team_id, person_id),)@@ -173,7 +173,7 @@ def fetch_persons_by_ids(cursor, team_id: int, person_ids: list[int]) -> dict[increated_at,is_user_idFROM posthog_person- WHERE team_id = %s AND id = ANY(%s)+ WHERE team_id = %s AND id = ANY(%s) AND is_deleted = false""",(team_id, person_ids),)diff --git a/posthog/management/commands/export_distinct_ids.py b/posthog/management/commands/export_distinct_ids.pyindex 24fafd185ea8..927c0ee01490 100644--- a/posthog/management/commands/export_distinct_ids.py+++ b/posthog/management/commands/export_distinct_ids.py@@ -66,9 +66,9 @@ class Command(BaseCommand):self.stdout.write(self.style.SUCCESS(f"Exporting distinct IDs for team: {team.name}"))- # Build the distinct-id query, joining to the person table only when filtering on- # person attributes (identified / demo).- conditions = ["pdi.team_id = %s"]+ # Build the distinct-id query. The person join is unconditional: a mapping can+ # outlive its person's tombstone, so pdi.is_deleted alone is not enough.+ conditions = ["pdi.team_id = %s", "pdi.is_deleted = false"]if identified_only:conditions.append("p.is_identified = true")self.stdout.write("Filtering for identified persons only")@@ -76,11 +76,7 @@ class Command(BaseCommand):conditions.append("p.properties @> '{\"is_demo\": true}'::jsonb")self.stdout.write("Filtering for demo persons only")- person_join = (- f"JOIN {settings.PERSON_TABLE_NAME} p ON p.team_id = pdi.team_id AND p.id = pdi.person_id"- if (identified_only or demo_only)- else ""- )+ person_join = f"JOIN {settings.PERSON_TABLE_NAME} p ON p.team_id = pdi.team_id AND p.id = pdi.person_id AND p.is_deleted = false"query = (f"SELECT pdi.distinct_id FROM posthog_persondistinctid pdi {person_join} WHERE {' AND '.join(conditions)}")diff --git a/posthog/management/commands/sync_persons_to_clickhouse.py b/posthog/management/commands/sync_persons_to_clickhouse.pyindex f491834a2706..666a8a1773cd 100644--- a/posthog/management/commands/sync_persons_to_clickhouse.py+++ b/posthog/management/commands/sync_persons_to_clickhouse.py@@ -79,7 +79,8 @@ def run_person_sync(team_id: int, live_run: bool, deletes: bool):# lookup what needs to be updated in ClickHouse and send kafka messages for only thosewith persons_db_connection(writer=False) as conn, conn.cursor() as cursor:cursor.execute(- "SELECT uuid, version, properties, is_identified, created_at FROM posthog_person WHERE team_id = %s",+ "SELECT uuid, version, properties, is_identified, created_at FROM posthog_person"+ " WHERE team_id = %s AND is_deleted = false",[team_id],)persons = [@@ -150,7 +151,7 @@ def run_distinct_id_sync(team_id: int, live_run: bool, deletes: bool):cursor.execute("SELECT pdi.distinct_id, pdi.version, p.uuid ""FROM posthog_persondistinctid pdi JOIN posthog_person p ON p.id = pdi.person_id "- "WHERE pdi.team_id = %s",+ "WHERE pdi.team_id = %s AND pdi.is_deleted = false AND p.is_deleted = false",[team_id],)person_distinct_ids = [diff --git a/posthog/temporal/sync_person_distinct_ids/activities.py b/posthog/temporal/sync_person_distinct_ids/activities.pyindex b69650a4bc09..8fdf62e144c5 100644--- a/posthog/temporal/sync_person_distinct_ids/activities.py+++ b/posthog/temporal/sync_person_distinct_ids/activities.py@@ -166,6 +166,8 @@ async def lookup_pg_distinct_ids(inputs: LookupPgDistinctIdsInputs) -> LookupPgDAND pdi.team_id = p.team_idWHERE p.team_id = %sAND p.uuid IN (SELECT unnest(%s::uuid[]))+ AND p.is_deleted = false+ AND pdi.is_deleted = falseORDER BY p.uuid, pdi.id"""params = [inputs.team_id, inputs.person_uuids]@@ -214,6 +216,7 @@ async def lookup_pg_distinct_ids(inputs: LookupPgDistinctIdsInputs) -> LookupPgDFROM posthog_personWHERE team_id = %sAND uuid IN (SELECT unnest(%s::uuid[]))+ AND is_deleted = false"""params = [inputs.team_id, persons_not_found]diff --git a/rust/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json b/rust/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonsimilarity index 83%rename from rust/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.jsonrename to rust/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonindex f5325a210ec7..38b8f571dc62 100644--- a/rust/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json+++ b/rust/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983"-}+ "hash": "1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd"+}\ No newline at end of filediff --git a/rust/embedding-worker/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json b/rust/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonsimilarity index 84%rename from rust/embedding-worker/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.jsonrename to rust/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonindex a44afe1d2d12..aa1457117221 100644--- a/rust/embedding-worker/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json+++ b/rust/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8"-}+ "hash": "c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a"+}\ No newline at end of filediff --git a/rust/common/types/src/person.rs b/rust/common/types/src/person.rsindex 8d29cd961fd2..4d309c48e00d 100644--- a/rust/common/types/src/person.rs+++ b/rust/common/types/src/person.rs@@ -34,7 +34,9 @@ impl Person {WHEREposthog_persondistinctid.distinct_id = $1AND posthog_persondistinctid.team_id = $2+ AND posthog_persondistinctid.is_deleted = falseAND pp.team_id = $2+ AND pp.is_deleted = falseLIMIT 1"#,distinct_id,@@ -59,7 +61,9 @@ impl Person {WHEREposthog_persondistinctid.distinct_id = $1AND posthog_persondistinctid.team_id = $2+ AND posthog_persondistinctid.is_deleted = falseAND pp.team_id = $2+ AND pp.is_deleted = falseLIMIT 1"#,distinct_id,diff --git a/rust/embedding-worker/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json b/rust/cymbal/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonsimilarity index 83%rename from rust/embedding-worker/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.jsonrename to rust/cymbal/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonindex f5325a210ec7..38b8f571dc62 100644--- a/rust/embedding-worker/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json+++ b/rust/cymbal/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983"-}+ "hash": "1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd"+}\ No newline at end of filediff --git a/rust/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json b/rust/cymbal/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonsimilarity index 84%rename from rust/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.jsonrename to rust/cymbal/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonindex a44afe1d2d12..aa1457117221 100644--- a/rust/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json+++ b/rust/cymbal/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8"-}+ "hash": "c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a"+}\ No newline at end of filediff --git a/rust/cymbal/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json b/rust/embedding-worker/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonsimilarity index 83%rename from rust/cymbal/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.jsonrename to rust/embedding-worker/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.jsonindex f5325a210ec7..38b8f571dc62 100644--- a/rust/cymbal/.sqlx/query-0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983.json+++ b/rust/embedding-worker/.sqlx/query-1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, '{}'::jsonb as properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "0075dc262b54e2c4b0139e12a298169e4825500508e9a3a25971813a18fac983"-}+ "hash": "1a0a830fe83fd6bc0870fa1fdc226a5c67574fd9042b76c923b420a34f150bdd"+}\ No newline at end of filediff --git a/rust/cymbal/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json b/rust/embedding-worker/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonsimilarity index 84%rename from rust/cymbal/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.jsonrename to rust/embedding-worker/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.jsonindex a44afe1d2d12..aa1457117221 100644--- a/rust/cymbal/.sqlx/query-f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8.json+++ b/rust/embedding-worker/.sqlx/query-c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND pp.team_id = $2\n LIMIT 1\n ",+ "query": "\n SELECT pp.id, pp.created_at, pp.team_id, pp.uuid, pp.properties, pp.is_identified, pp.is_user_id, pp.version\n FROM posthog_person pp\n INNER JOIN posthog_persondistinctid\n ON pp.id = posthog_persondistinctid.person_id\n WHERE\n posthog_persondistinctid.distinct_id = $1\n AND posthog_persondistinctid.team_id = $2\n AND posthog_persondistinctid.is_deleted = false\n AND pp.team_id = $2\n AND pp.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -61,5 +61,5 @@true]},- "hash": "f73889687c0d58e9800b6df9c8faa1e85e7696dc5cabaa30e4490e558afa93b8"-}+ "hash": "c630f8d0ae43133684ee35d8d35b5c40e3054ae58bbac24f0723cc30fa709b1a"+}\ No newline at end of filediff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rsindex 0e8f7c0be4d7..47f612351e8d 100644--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs@@ -211,11 +211,13 @@ async fn scan_persons_page(FROM posthog_persondistinctid pdWHERE pd.person_id = p.idAND pd.team_id = p.team_id+ AND pd.is_deleted = falseORDER BY pd.idLIMIT 1) d ON trueWHERE p.team_id = $1AND p.id > $2+ AND p.is_deleted = falseORDER BY p.idLIMIT $3"#;diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rsindex fb09b5ddec02..dbaf13806708 100644--- a/rust/feature-flags/src/flags/flag_matching_utils.rs+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs@@ -849,6 +849,7 @@ async fn try_get_feature_flag_hash_key_overrides(AND fhko.team_id = ppd.team_idWHERE ppd.team_id = $1AND ppd.distinct_id = ANY($2)+ AND ppd.is_deleted = false"#;let query_start = Instant::now();@@ -1026,7 +1027,8 @@ async fn try_set_feature_flag_hash_key_overrides(ON existing.person_id = p.person_id AND existing.team_id = p.team_idWHERE p.team_id = $1AND p.distinct_id = ANY($2)- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)+ AND p.is_deleted = false+ AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)"#;// Query 2: Get all active feature flags with experience continuity (non-person pool)@@ -1333,7 +1335,8 @@ async fn try_should_write_hash_key_override(ON existing.person_id = p.person_id AND existing.team_id = p.team_idWHERE p.team_id = $1AND p.distinct_id = ANY($2)- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)+ AND p.is_deleted = false+ AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)"#;// Query 2: Get feature flags from non-person pooldiff --git a/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.json b/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.jsonnew file mode 100644index 000000000000..63713a73ee7e--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0.json@@ -0,0 +1,85 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO posthog_person\n (created_at, properties, properties_last_updated_at, properties_last_operation,\n team_id, is_identified, uuid, version, last_seen_at)\n SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,\n u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)\n FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])\n AS u(created_at, team_id, is_identified, uuid)\n ON CONFLICT (team_id, uuid) DO UPDATE SET\n is_deleted = false,\n version = COALESCE(posthog_person.version, 0) + 1,\n properties = '{}'::jsonb,\n properties_last_updated_at = '{}'::jsonb,\n properties_last_operation = '{}'::jsonb,\n created_at = EXCLUDED.created_at,\n is_identified = EXCLUDED.is_identified,\n last_seen_at = EXCLUDED.last_seen_at\n WHERE posthog_person.is_deleted = true\n RETURNING 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 ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "uuid",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "team_id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "properties?",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "properties_last_updated_at?",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "properties_last_operation?",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "version",+ "type_info": "Int8"+ },+ {+ "ordinal": 8,+ "name": "is_identified",+ "type_info": "Bool"+ },+ {+ "ordinal": 9,+ "name": "is_user_id",+ "type_info": "Bool"+ },+ {+ "ordinal": 10,+ "name": "last_seen_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "TimestamptzArray",+ "Int4Array",+ "BoolArray",+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ null,+ null,+ null,+ null,+ false,+ true,+ false,+ null,+ true+ ]+ },+ "hash": "05e7b864896795e8b9fe648d31de6810d5efb7f540f121421670cf3a7cee67d0"+}diff --git a/rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.json b/rust/personhog-identity/.sqlx/query-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.jsonsimilarity index 60%rename from rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.jsonrename to rust/personhog-identity/.sqlx/query-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.jsonindex 58adcd8132b5..b08a3186c18d 100644--- a/rust/personhog-identity/.sqlx/query-a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d.json+++ b/rust/personhog-identity/.sqlx/query-1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT k.team_id as \"key_team_id!\", k.distinct_id as \"key_distinct_id!\",\n p.id as \"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 FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN posthog_persondistinctid pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n JOIN posthog_person p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n ",+ "query": "\n SELECT k.team_id as \"key_team_id!\", k.distinct_id as \"key_distinct_id!\",\n p.id as \"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 FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)\n JOIN posthog_persondistinctid pdi\n ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id\n AND pdi.is_deleted = false\n JOIN posthog_person p\n ON p.team_id = pdi.team_id AND p.id = pdi.person_id\n AND p.is_deleted = false\n ","describe": {"columns": [{@@ -91,5 +91,5 @@true]},- "hash": "a9bfb47f93f0fadcc0a05a5182eb9e488ac1ecd1fd6517d3f23adaa2979e4b2d"+ "hash": "1cb2ca6936aadf02320896f0ddf24112dc87a5be5faeb03b160c6a1444c092b9"}diff --git a/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.json b/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.jsonnew file mode 100644index 000000000000..7834b1bf7347--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_persondistinctid\n SET is_deleted = true, version = COALESCE(version, 0) + 1\n WHERE team_id = $1 AND distinct_id = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "1de4f18ec4cad969752748986bfc2eac184854b58a2aa81118cec68277906266"+}diff --git a/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.json b/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.jsonnew file mode 100644index 000000000000..09a9a2db1c17--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_person\n SET is_deleted = true, version = COALESCE(version, 0) + 1,\n properties = '{}'::jsonb\n WHERE team_id = $1 AND id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "2cbd01e1c596e2c36f2253723d6b83dc864ba403fade858ce90a676caddad8a5"+}diff --git a/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.json b/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.jsondeleted file mode 100644index d06de8aca676..000000000000--- a/rust/personhog-identity/.sqlx/query-5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81.json+++ /dev/null@@ -1,37 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)\n SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])\n AS u(d, p, t, v)\n ON CONFLICT (team_id, distinct_id) DO NOTHING\n RETURNING team_id::bigint as \"team_id!\", distinct_id, person_id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "team_id!",- "type_info": "Int8"- },- {- "ordinal": 1,- "name": "distinct_id",- "type_info": "Varchar"- },- {- "ordinal": 2,- "name": "person_id",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "TextArray",- "Int8Array",- "Int4Array",- "Int8Array"- ]- },- "nullable": [- null,- false,- false- ]- },- "hash": "5a2c4ddc7893ddc7e538ceec011db61fe93a7caa738953b10401542e24168d81"-}diff --git a/rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.json b/rust/personhog-identity/.sqlx/query-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.jsonsimilarity index 72%rename from rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.jsonrename to rust/personhog-identity/.sqlx/query-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.jsonindex 9ab855fe5db6..314ced701d82 100644--- a/rust/personhog-identity/.sqlx/query-423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b.json+++ b/rust/personhog-identity/.sqlx/query-5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",+ "query": "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2 AND is_deleted = false","describe": {"columns": [{@@ -19,5 +19,5 @@false]},- "hash": "423195f96062037eb486b038c35db0a8556ba0d7f054b6bd661a4b5e514e397b"+ "hash": "5e8e078ce072b19e2d310d7ac3eb15edfaf70f9c945b0de1689645781b65cc47"}diff --git a/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.json b/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.jsondeleted file mode 100644index 73b8c94db0b6..000000000000--- a/rust/personhog-identity/.sqlx/query-a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n DELETE FROM posthog_personlessdistinctid pl\n USING unnest($1::int[], $2::text[]) AS u(t, d)\n WHERE pl.team_id = u.t AND pl.distinct_id = u.d\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4Array",- "TextArray"- ]- },- "nullable": []- },- "hash": "a0a0e59de0ba70e26bb6262d08a9d258e6f0a3bf0f0a7844474a6b299dc5403d"-}diff --git a/rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.json b/rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.jsonsimilarity index 61%rename from rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.jsonrename to rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.jsonindex 7f635092e1fc..a5fa478c87fa 100644--- a/rust/personhog-identity/.sqlx/query-b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677.json+++ b/rust/personhog-identity/.sqlx/query-a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT p.id as \"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 FROM posthog_person p\n JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)\n ON p.team_id = k.team_id AND p.uuid = k.uuid\n ",+ "query": "\n SELECT p.id as \"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 FROM posthog_person p\n JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)\n ON p.team_id = k.team_id AND p.uuid = k.uuid\n WHERE p.is_deleted = false\n ","describe": {"columns": [{@@ -79,5 +79,5 @@true]},- "hash": "b69ec4c1a3eaba4a40ef4c0fbbc3b3473ad6dbc501a3933a10ce759a36362677"+ "hash": "a2f7919331e9355e5b3147f0779062477ef175088031abbbdf3d9481431acb83"}diff --git a/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.json b/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.jsonnew file mode 100644index 000000000000..5e535536bba6--- /dev/null+++ b/rust/personhog-identity/.sqlx/query-bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d.json@@ -0,0 +1,43 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)\n SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])\n AS u(d, p, t, v)\n ON CONFLICT (team_id, distinct_id) DO UPDATE SET\n person_id = EXCLUDED.person_id,\n version = COALESCE(posthog_persondistinctid.version, 0) + 1,\n is_deleted = false\n WHERE posthog_persondistinctid.is_deleted = true\n RETURNING team_id::bigint as \"team_id!\", distinct_id, person_id,\n (xmax = 0) as \"inserted!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "distinct_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "person_id",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "inserted!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Int8Array",+ "Int4Array",+ "Int8Array"+ ]+ },+ "nullable": [+ null,+ false,+ false,+ null+ ]+ },+ "hash": "bf8eb5d5194b5b23421272e5265adb5d0574f0e98a215ee9bddf0ce9e731f68d"+}diff --git a/rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.json b/rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.jsonsimilarity index 65%rename from rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.jsonrename to rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.jsonindex 35b65adb925a..5579abc7e0f2 100644--- a/rust/personhog-identity/.sqlx/query-62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c.json+++ b/rust/personhog-identity/.sqlx/query-ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2",+ "query": "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2 AND is_deleted = false","describe": {"columns": [],"parameters": {@@ -11,5 +11,5 @@},"nullable": []},- "hash": "62e9588b4f822c063707416bec0cfc4e9ca9fdab71bad9b589fab3445b0faf1c"+ "hash": "ce35b3210de8eb6cee590be0e95249938ff558b42f981726a6fa27d0d294acc8"}diff --git a/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.json b/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.jsondeleted file mode 100644index 080fc404aebc..000000000000--- a/rust/personhog-identity/.sqlx/query-d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE posthog_personlessdistinctid pl\n SET is_merged = false\n FROM unnest($1::int[], $2::text[]) AS u(t, d)\n WHERE pl.team_id = u.t AND pl.distinct_id = u.d\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4Array",- "TextArray"- ]- },- "nullable": []- },- "hash": "d8b6bab380a1ace8a636722d9733fc1609a2b044b46efdadd316f0a5652c5955"-}diff --git a/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.json b/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.jsondeleted file mode 100644index dafbfd7cb763..000000000000--- a/rust/personhog-identity/.sqlx/query-df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d.json+++ /dev/null@@ -1,85 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_person\n (created_at, properties, properties_last_updated_at, properties_last_operation,\n team_id, is_identified, uuid, version, last_seen_at)\n SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,\n u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)\n FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])\n AS u(created_at, team_id, is_identified, uuid)\n ON CONFLICT (team_id, uuid) DO NOTHING\n RETURNING 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 ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Int8"- },- {- "ordinal": 1,- "name": "uuid",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "team_id!",- "type_info": "Int8"- },- {- "ordinal": 3,- "name": "properties?",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "properties_last_updated_at?",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "properties_last_operation?",- "type_info": "Text"- },- {- "ordinal": 6,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "version",- "type_info": "Int8"- },- {- "ordinal": 8,- "name": "is_identified",- "type_info": "Bool"- },- {- "ordinal": 9,- "name": "is_user_id",- "type_info": "Bool"- },- {- "ordinal": 10,- "name": "last_seen_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "TimestamptzArray",- "Int4Array",- "BoolArray",- "UuidArray"- ]- },- "nullable": [- false,- false,- null,- null,- null,- null,- false,- true,- false,- null,- true- ]- },- "hash": "df8fe96a88ca9bdae39ca8a24e5b61aef4e6fec01aaa222fb6775d355ca1bf5d"-}diff --git a/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.json b/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.jsondeleted file mode 100644index deb6980db07a..000000000000--- a/rust/personhog-identity/.sqlx/query-fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280.json+++ /dev/null@@ -1,35 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)\n SELECT d, true, now(), t FROM unnest($1::int[], $2::text[]) AS u(t, d)\n ON CONFLICT (team_id, distinct_id) DO UPDATE SET is_merged = true\n WHERE posthog_personlessdistinctid.is_merged = false\n RETURNING team_id::bigint as \"team_id!\", distinct_id, (xmax = 0) as \"inserted!\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "team_id!",- "type_info": "Int8"- },- {- "ordinal": 1,- "name": "distinct_id",- "type_info": "Varchar"- },- {- "ordinal": 2,- "name": "inserted!",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Int4Array",- "TextArray"- ]- },- "nullable": [- null,- false,- null- ]- },- "hash": "fa8aa398308891a81fb744122f3fecbb5fabf27d158099cb25adb33efe9ad280"-}diff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.mdindex c15057b1c457..5577952f438d 100644--- a/rust/personhog-identity/README.md+++ b/rust/personhog-identity/README.md@@ -12,7 +12,7 @@ Person state spans two planes:## How get-or-create works1. Batch resolve `(team_id, distinct_id)` keys on the Postgres primary (one UNNEST probe).-2. Misses get a person stub — deterministic uuidv5 of `team_id:distinct_id`, version 0, empty properties — plus distinct id rows, in one multi-row transaction with per-row `ON CONFLICT` handling. Extra distinct ids carry personless history forward (version 1 when a `posthog_personlessdistinctid` row already existed).+2. Misses get a person stub — deterministic uuidv5 of `team_id:distinct_id`, version 0, empty properties — plus distinct id rows, in one multi-row transaction with per-row `ON CONFLICT` handling. Extra distinct ids always get version 1: they can't be proven history-free, and version 1 is safe either way (the override it emits is a transient no-op when no events exist).3. Created stubs fan out initial properties to their owning leaders through the router (`UpdatePersonProperties` with `x-team-id`/`x-person-id` routing headers), with bounded concurrency.Races resolve per key, never failing the rest of a batch: a concurrent create conflicts on the deterministic uuid and returns the winner (`created = false`); a distinct id concurrently mapped elsewhere rolls back only that stub and re-resolves. A crash between the stub commit and the leader ack surfaces as a per-key error; the retried key resolves to the stub (`created = false`) and the caller applies properties through the normal update path.diff --git a/rust/personhog-identity/src/storage/postgres.rs b/rust/personhog-identity/src/storage/postgres.rsdeleted file mode 100644index 64c76ec4d801..000000000000--- a/rust/personhog-identity/src/storage/postgres.rs+++ /dev/null@@ -1,421 +0,0 @@-use std::collections::{HashMap, HashSet};--use async_trait::async_trait;-use chrono::{DateTime, Utc};-use sqlx::postgres::PgPool;-use uuid::Uuid;--use personhog_common::grpc::{current_client_name, current_method_name};-use personhog_common::persons::person_uuid;--use crate::storage::error::StorageResult;-use crate::storage::types::{Person, PersonStub, StubOutcome};-use crate::storage::{IdentityStorage, DB_QUERY_DURATION};--const POOL_LABEL: &str = "primary";--pub struct PostgresIdentityStorage {- pub primary_pool: PgPool,-}--impl PostgresIdentityStorage {- pub fn new(primary_pool: PgPool) -> Self {- Self { primary_pool }- }-- fn query_labels(operation: &str) -> [(String, String); 4] {- [- ("operation".to_string(), operation.to_string()),- ("pool".to_string(), POOL_LABEL.to_string()),- ("client".to_string(), current_client_name().to_string()),- ("method".to_string(), current_method_name().to_string()),- ]- }-}--#[async_trait]-impl IdentityStorage for PostgresIdentityStorage {- async fn resolve_distinct_ids(- &self,- keys: &[(i64, String)],- ) -> StorageResult<HashMap<(i64, String), Person>> {- if keys.is_empty() {- return Ok(HashMap::new());- }-- let labels = Self::query_labels("resolve_distinct_ids");- let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);-- let team_ids: Vec<i32> = keys.iter().map(|(t, _)| *t as i32).collect();- let distinct_ids: Vec<String> = keys.iter().map(|(_, d)| d.clone()).collect();-- let rows = sqlx::query!(- r#"- SELECT k.team_id as "key_team_id!", k.distinct_id as "key_distinct_id!",- p.id as "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- FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)- JOIN posthog_persondistinctid pdi- ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id- JOIN posthog_person p- ON p.team_id = pdi.team_id AND p.id = pdi.person_id- "#,- &team_ids,- &distinct_ids- )- .fetch_all(&self.primary_pool)- .await?;-- let mut resolved = HashMap::with_capacity(rows.len());- for row in rows {- resolved.insert(- (i64::from(row.key_team_id), row.key_distinct_id),- 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,- },- );- }- Ok(resolved)- }-- async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {- if stubs.is_empty() {- return Ok(Vec::new());- }-- let labels = Self::query_labels("create_person_stubs");- let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);-- let uuids: Vec<Uuid> = stubs- .iter()- .map(|s| person_uuid(s.team_id, &s.distinct_id))- .collect();- let team_ids: Vec<i32> = stubs.iter().map(|s| s.team_id as i32).collect();-- // Every multi-row statement below binds arrays sorted by its conflict- // key: row locks are taken in array order, so concurrent batches- // (main vs overflow) touching the same keys in different orders would- // otherwise deadlock.- let mut order: Vec<usize> = (0..stubs.len()).collect();- order.sort_by_key(|&i| (team_ids[i], uuids[i]));- let sorted_created_ats: Vec<DateTime<Utc>> =- order.iter().map(|&i| stubs[i].created_at).collect();- let sorted_team_ids: Vec<i32> = order.iter().map(|&i| team_ids[i]).collect();- let sorted_is_identified: Vec<bool> =- order.iter().map(|&i| stubs[i].is_identified).collect();- let sorted_uuids: Vec<Uuid> = order.iter().map(|&i| uuids[i]).collect();-- let mut tx = self.primary_pool.begin().await?;-- // 1. Multi-row stub insert. Concurrent creates for one distinct id- // derive the same uuid, so exactly one insert wins per key; losers- // fetch the committed winner in a fresh statement snapshot below.- let inserted = sqlx::query_as!(- Person,- r#"- INSERT INTO posthog_person- (created_at, properties, properties_last_updated_at, properties_last_operation,- team_id, is_identified, uuid, version, last_seen_at)- SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,- u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)- FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])- AS u(created_at, team_id, is_identified, uuid)- ON CONFLICT (team_id, uuid) DO NOTHING- RETURNING 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- "#,- &sorted_created_ats,- &sorted_team_ids,- &sorted_is_identified,- &sorted_uuids- )- .fetch_all(&mut *tx)- .await?;-- // (team_id, uuid) → (person, created-by-us)- let mut persons: HashMap<(i64, Uuid), (Person, bool)> = inserted- .into_iter()- .map(|p| ((p.team_id, p.uuid), (p, true)))- .collect();-- // 2. Batch-fetch the committed winners for conflicted keys. This must- // be a separate statement: the insert's snapshot predates a concurrent- // winner's commit, a fresh statement snapshot sees it.- let conflicted: Vec<usize> = (0..stubs.len())- .filter(|&i| !persons.contains_key(&(stubs[i].team_id, uuids[i])))- .collect();- if !conflicted.is_empty() {- let conflicted_teams: Vec<i32> = conflicted.iter().map(|&i| team_ids[i]).collect();- let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|&i| uuids[i]).collect();- let winners = sqlx::query_as!(- Person,- r#"- SELECT p.id as "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- FROM posthog_person p- JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)- ON p.team_id = k.team_id AND p.uuid = k.uuid- "#,- &conflicted_teams,- &conflicted_uuids- )- .fetch_all(&mut *tx)- .await?;- for winner in winners {- persons.insert((winner.team_id, winner.uuid), (winner, false));- }- }-- // 3. Extra distinct ids carry personless history forward: a distinct- // id already used personless needs its row at version 1 so ClickHouse- // emits an override re-pointing those events. The upsert also marks- // the personless row merged so concurrent personless events re-resolve.- // Deduped across stubs — DO UPDATE errors on same-command duplicates.- // The update is conditional on is_merged = false so RETURNING captures- // exactly what this transaction changed (insert vs flip), which step 6- // reverts for stubs whose rows are undone; already-merged rows return- // nothing and are never touched.- let mut personless_seen: HashSet<(i64, &str)> = HashSet::new();- let mut personless_pairs: Vec<(i32, String)> = Vec::new();- for stub in stubs {- for extra in &stub.extra_distinct_ids {- if personless_seen.insert((stub.team_id, extra.as_str())) {- personless_pairs.push((stub.team_id as i32, extra.clone()));- }- }- }- personless_pairs.sort();- let (personless_teams, personless_dids): (Vec<i32>, Vec<String>) =- personless_pairs.into_iter().unzip();- let mut personless_fresh: HashMap<(i64, String), bool> = HashMap::new();- if !personless_dids.is_empty() {- let rows = sqlx::query!(- r#"- INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)- SELECT d, true, now(), t FROM unnest($1::int[], $2::text[]) AS u(t, d)- ON CONFLICT (team_id, distinct_id) DO UPDATE SET is_merged = true- WHERE posthog_personlessdistinctid.is_merged = false- RETURNING team_id::bigint as "team_id!", distinct_id, (xmax = 0) as "inserted!"- "#,- &personless_teams,- &personless_dids- )- .fetch_all(&mut *tx)- .await?;- for row in rows {- personless_fresh.insert((row.team_id, row.distinct_id), row.inserted);- }- }-- // 4. Multi-row distinct id insert. The primary distinct id derives the- // person uuid, so personless events already used the same uuid —- // always version 0. Conflicts keep the existing mapping (per-row): an- // extra that raced into another person's hands is a merge scenario,- // which is the pipeline's job — never re-pointed here, and not an- // error (a retry could never succeed).- // (team_id, distinct_id, person_id, version)- let mut pdi_rows: Vec<(i32, String, i64, i64)> = Vec::new();- for (i, stub) in stubs.iter().enumerate() {- let Some((person, _)) = persons.get(&(stub.team_id, uuids[i])) else {- continue; // winner vanished; resolved to LostRace below- };- pdi_rows.push((stub.team_id as i32, stub.distinct_id.clone(), person.id, 0));- for extra in &stub.extra_distinct_ids {- // Missing from the map = the personless row pre-existed- // already merged, so the distinct id has history: version 1.- let fresh = personless_fresh- .get(&(stub.team_id, extra.clone()))- .copied()- .unwrap_or(false);- pdi_rows.push((- stub.team_id as i32,- extra.clone(),- person.id,- if fresh { 0 } else { 1 },- ));- }- }- // Stable sort: batch order still picks the winner among same-command- // duplicate keys (an extra shared between stubs).- pdi_rows.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));- let pdi_teams: Vec<i32> = pdi_rows.iter().map(|r| r.0).collect();- let pdi_dids: Vec<String> = pdi_rows.iter().map(|r| r.1.clone()).collect();- let pdi_person_ids: Vec<i64> = pdi_rows.iter().map(|r| r.2).collect();- let pdi_versions: Vec<i64> = pdi_rows.iter().map(|r| r.3).collect();- let mut mapped: HashMap<(i64, String), i64> = HashMap::new();- if !pdi_dids.is_empty() {- let rows = sqlx::query!(- r#"- INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)- SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])- AS u(d, p, t, v)- ON CONFLICT (team_id, distinct_id) DO NOTHING- RETURNING team_id::bigint as "team_id!", distinct_id, person_id- "#,- &pdi_dids,- &pdi_person_ids,- &pdi_teams,- &pdi_versions- )- .fetch_all(&mut *tx)- .await?;- for row in rows {- mapped.insert((row.team_id, row.distinct_id), row.person_id);- }- }-- // 5. Per-stub outcomes. A stub whose primary mapping went elsewhere is- // a lost race: undo its rows (created this transaction, so nothing can- // reference them) so the stub doesn't linger orphaned. `released`- // marks stubs that leave no distinct id mappings behind (undone or- // never inserted), so step 6 can revert their personless marks.- let mut outcomes = Vec::with_capacity(stubs.len());- let mut released = vec![false; stubs.len()];- for (i, stub) in stubs.iter().enumerate() {- let Some((person, created)) = persons.get(&(stub.team_id, uuids[i])) else {- released[i] = true;- outcomes.push(StubOutcome::LostRace);- continue;- };- let primary_key = (stub.team_id, stub.distinct_id.clone());- if mapped.get(&primary_key) == Some(&person.id) {- outcomes.push(StubOutcome::Committed {- person: person.clone(),- created: *created,- });- continue;- }- if *created {- sqlx::query!(- "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2",- stub.team_id as i32,- person.id- )- .execute(&mut *tx)- .await?;- sqlx::query!(- "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",- stub.team_id as i32,- person.id- )- .execute(&mut *tx)- .await?;- released[i] = true;- outcomes.push(StubOutcome::LostRace);- continue;- }- // The person pre-existed and its primary mapping wasn't inserted by- // us — verify the existing mapping points at this person.- let existing = sqlx::query_scalar!(- "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",- stub.team_id as i32,- &stub.distinct_id- )- .fetch_optional(&mut *tx)- .await?;- if existing == Some(person.id) {- outcomes.push(StubOutcome::Committed {- person: person.clone(),- created: false,- });- } else {- outcomes.push(StubOutcome::LostRace);- }- }-- // 6. Step 3 marked every extra distinct id merged, but a released- // stub's merge never happened. Revert exactly what this transaction- // changed (delete rows it inserted, unflip rows it flipped — the row- // lock held since step 3 guarantees the prior value was false), unless- // a surviving stub shares the extra: its mapping stands, so the mark- // must too. Lost races that keep a pre-existing person keep their- // extra mappings and are not released.- let mut kept_extras: HashSet<(i64, &str)> = HashSet::new();- for (i, stub) in stubs.iter().enumerate() {- if !released[i] {- for extra in &stub.extra_distinct_ids {- kept_extras.insert((stub.team_id, extra.as_str()));- }- }- }- let mut delete_teams: Vec<i32> = Vec::new();- let mut delete_dids: Vec<String> = Vec::new();- let mut unmark_teams: Vec<i32> = Vec::new();- let mut unmark_dids: Vec<String> = Vec::new();- for (i, stub) in stubs.iter().enumerate() {- if !released[i] {- continue;- }- for extra in &stub.extra_distinct_ids {- if kept_extras.contains(&(stub.team_id, extra.as_str())) {- continue;- }- match personless_fresh.remove(&(stub.team_id, extra.clone())) {- Some(true) => {- delete_teams.push(stub.team_id as i32);- delete_dids.push(extra.clone());- }- Some(false) => {- unmark_teams.push(stub.team_id as i32);- unmark_dids.push(extra.clone());- }- None => {} // pre-existed merged; step 3 changed nothing- }- }- }- if !delete_dids.is_empty() {- sqlx::query!(- r#"- DELETE FROM posthog_personlessdistinctid pl- USING unnest($1::int[], $2::text[]) AS u(t, d)- WHERE pl.team_id = u.t AND pl.distinct_id = u.d- "#,- &delete_teams,- &delete_dids- )- .execute(&mut *tx)- .await?;- }- if !unmark_dids.is_empty() {- sqlx::query!(- r#"- UPDATE posthog_personlessdistinctid pl- SET is_merged = false- FROM unnest($1::int[], $2::text[]) AS u(t, d)- WHERE pl.team_id = u.t AND pl.distinct_id = u.d- "#,- &unmark_teams,- &unmark_dids- )- .execute(&mut *tx)- .await?;- }-- tx.commit().await?;- Ok(outcomes)- }-}diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rsnew file mode 100644index 000000000000..58810359d760--- /dev/null+++ b/rust/personhog-identity/src/storage/postgres/mod.rs@@ -0,0 +1,56 @@+//! Postgres-backed identity storage. This module is dispatch-only: each+//! trait method's logic lives in its own submodule (`resolve`,+//! `stub_create`), keyed by the metrics operation label.++mod resolve;+mod stub_create;++use std::collections::HashMap;++use async_trait::async_trait;+use sqlx::postgres::PgPool;++use personhog_common::grpc::{current_client_name, current_method_name};++use crate::storage::error::StorageResult;+use crate::storage::types::{Person, PersonStub, StubOutcome};+use crate::storage::{IdentityStorage, DB_QUERY_DURATION};++const POOL_LABEL: &str = "primary";++pub struct PostgresIdentityStorage {+ pub primary_pool: PgPool,+}++impl PostgresIdentityStorage {+ pub fn new(primary_pool: PgPool) -> Self {+ Self { primary_pool }+ }++ fn query_labels(operation: &str) -> [(String, String); 4] {+ [+ ("operation".to_string(), operation.to_string()),+ ("pool".to_string(), POOL_LABEL.to_string()),+ ("client".to_string(), current_client_name().to_string()),+ ("method".to_string(), current_method_name().to_string()),+ ]+ }+}++#[async_trait]+impl IdentityStorage for PostgresIdentityStorage {+ async fn resolve_distinct_ids(+ &self,+ keys: &[(i64, String)],+ ) -> StorageResult<HashMap<(i64, String), Person>> {+ let labels = Self::query_labels("resolve_distinct_ids");+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);+ resolve::resolve_distinct_ids(&self.primary_pool, keys).await+ }++ async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {+ let labels = Self::query_labels("create_person_stubs");+ let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);+ stub_create::create_person_stubs(&self.primary_pool, stubs).await+ }+}diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rsnew file mode 100644index 000000000000..be3f8c5d51d0--- /dev/null+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs@@ -0,0 +1,66 @@+use std::collections::HashMap;++use sqlx::postgres::PgPool;++use crate::storage::error::StorageResult;+use crate::storage::types::Person;++/// Batch-resolve (team_id, distinct_id) keys to their live persons on the+/// primary. Tombstoned mappings and persons are invisible; unresolved keys+/// are absent from the result.+pub(super) async fn resolve_distinct_ids(+ pool: &PgPool,+ keys: &[(i64, String)],+) -> StorageResult<HashMap<(i64, String), Person>> {+ if keys.is_empty() {+ return Ok(HashMap::new());+ }++ let team_ids: Vec<i32> = keys.iter().map(|(t, _)| *t as i32).collect();+ let distinct_ids: Vec<String> = keys.iter().map(|(_, d)| d.clone()).collect();++ let rows = sqlx::query!(+ r#"+ SELECT k.team_id as "key_team_id!", k.distinct_id as "key_distinct_id!",+ p.id as "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+ FROM unnest($1::int[], $2::text[]) AS k(team_id, distinct_id)+ JOIN posthog_persondistinctid pdi+ ON pdi.team_id = k.team_id AND pdi.distinct_id = k.distinct_id+ AND pdi.is_deleted = false+ JOIN posthog_person p+ ON p.team_id = pdi.team_id AND p.id = pdi.person_id+ AND p.is_deleted = false+ "#,+ &team_ids,+ &distinct_ids+ )+ .fetch_all(pool)+ .await?;++ let mut resolved = HashMap::with_capacity(rows.len());+ for row in rows {+ resolved.insert(+ (i64::from(row.key_team_id), row.key_distinct_id),+ 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,+ },+ );+ }+ Ok(resolved)+}diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rsnew file mode 100644index 000000000000..bd2173ce3af6--- /dev/null+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs@@ -0,0 +1,437 @@+//! The stub-creation transaction: one transaction, four steps, each a+//! function below, called in order by [`create_person_stubs`]:+//!+//! 1. [`insert_or_revive_persons`] — multi-row person insert; a conflict+//! with a tombstoned row revives it, a conflict with a live row is left+//! for step 2.+//! 2. [`fetch_conflict_winners`] — fresh-snapshot fetch of the committed+//! rows behind live conflicts (concurrent winners).+//! 3. [`insert_distinct_id_mappings`] — multi-row distinct id insert;+//! tombstoned mappings revive, live conflicts keep the existing row.+//! 4. [`resolve_stub_outcomes`] — decide Committed/LostRace per stub and+//! undo the rows of stubs that lost their primary mapping.+//!+//! Cross-cutting invariants:+//! - Every multi-row statement binds arrays sorted by its conflict key —+//! row locks are taken in array order, so concurrent batches touching the+//! same keys in different orders would otherwise deadlock — and deduped by+//! that key, because ON CONFLICT DO UPDATE raises "cannot affect row a+//! second time" on same-command duplicates (the cardinality check fires+//! before the WHERE qual).+//! - Rows created in this transaction are invisible outside it until commit,+//! so step 5 can delete them without anything referencing them.+//! - Revived tombstones predate the transaction and must survive an undo:+//! they are re-tombstoned with another version bump, never deleted.++use std::collections::{HashMap, HashSet};++use chrono::{DateTime, Utc};+use sqlx::postgres::PgPool;+use uuid::Uuid;++use personhog_common::persons::person_uuid;++use crate::storage::error::StorageResult;+use crate::storage::types::{Person, PersonStub, StubOutcome};++type Tx<'a> = sqlx::Transaction<'a, sqlx::Postgres>;++/// A person resolved for one (team_id, uuid) conflict key during stub+/// creation, plus how this transaction obtained it — that determines the+/// stub's reported `created` flag and how an undo must treat the row.+struct ResolvedPerson {+ person: Person,+ /// Inserted (or revived) by this transaction, as opposed to fetched as a+ /// concurrent winner's committed row.+ created_by_us: bool,+ /// The insert revived a tombstoned row rather than creating a fresh one.+ /// An undo must re-tombstone it, never hard-delete it.+ revived_tombstone: bool,+}++/// Persons keyed by their (team_id, uuid) conflict key.+type PersonsByKey = HashMap<(i64, Uuid), ResolvedPerson>;++/// What the multi-row distinct id insert actually wrote.+struct MappingOutcome {+ /// (team_id, distinct_id) → person_id for each mapping this transaction+ /// inserted or revived. Keys that conflicted with a live mapping are+ /// absent — the existing mapping stands.+ written: HashMap<(i64, String), i64>,+ /// The subset of `written` that revived a tombstoned mapping; an undo+ /// must re-tombstone these instead of deleting them.+ revived: HashSet<(i64, String)>,+}++pub(super) async fn create_person_stubs(+ pool: &PgPool,+ stubs: &[PersonStub],+) -> StorageResult<Vec<StubOutcome>> {+ if stubs.is_empty() {+ return Ok(Vec::new());+ }++ // The primary distinct id derives the person uuid, so concurrent creates+ // for one distinct id target the same (team_id, uuid) row.+ let uuids: Vec<Uuid> = stubs+ .iter()+ .map(|s| person_uuid(s.team_id, &s.distinct_id))+ .collect();+ let team_ids: Vec<i32> = stubs.iter().map(|s| s.team_id as i32).collect();++ let mut tx = pool.begin().await?;++ let mut persons = insert_or_revive_persons(&mut tx, stubs, &team_ids, &uuids).await?;+ fetch_conflict_winners(&mut tx, stubs, &team_ids, &uuids, &mut persons).await?;+ let mapping = insert_distinct_id_mappings(&mut tx, stubs, &uuids, &persons).await?;+ let outcomes = resolve_stub_outcomes(&mut tx, stubs, &uuids, &persons, &mapping).await?;++ tx.commit().await?;+ Ok(outcomes)+}++/// Step 1: multi-row stub insert. Concurrent creates for one distinct id+/// derive the same uuid, so exactly one insert wins per key; losers fetch+/// the committed winner in a fresh statement snapshot (step 2).+///+/// A conflict with a tombstoned row (same uuidv5 key, previously deleted) is+/// a revival: flip is_deleted, bump the version above the tombstone so+/// ClickHouse collapses toward the new incarnation, and reset properties.+/// Conflicts with live rows fail the WHERE qual and return nothing here.+///+/// A returned version of 0 means fresh insert, anything else means revival+/// (xmax can't be read back from a partitioned table).+async fn insert_or_revive_persons(+ tx: &mut Tx<'_>,+ stubs: &[PersonStub],+ team_ids: &[i32],+ uuids: &[Uuid],+) -> StorageResult<PersonsByKey> {+ // Sorted and deduped by the (team_id, uuid) conflict key — see the+ // module invariants.+ let mut order: Vec<usize> = (0..stubs.len()).collect();+ order.sort_by_key(|&i| (team_ids[i], uuids[i]));+ order.dedup_by_key(|&mut i| (team_ids[i], uuids[i]));+ let sorted_created_ats: Vec<DateTime<Utc>> =+ order.iter().map(|&i| stubs[i].created_at).collect();+ let sorted_team_ids: Vec<i32> = order.iter().map(|&i| team_ids[i]).collect();+ let sorted_is_identified: Vec<bool> = order.iter().map(|&i| stubs[i].is_identified).collect();+ let sorted_uuids: Vec<Uuid> = order.iter().map(|&i| uuids[i]).collect();++ let inserted = sqlx::query!(+ r#"+ INSERT INTO posthog_person+ (created_at, properties, properties_last_updated_at, properties_last_operation,+ team_id, is_identified, uuid, version, last_seen_at)+ SELECT u.created_at, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,+ u.team_id, u.is_identified, u.uuid, 0, date_trunc('hour', u.created_at)+ FROM unnest($1::timestamptz[], $2::int[], $3::bool[], $4::uuid[])+ AS u(created_at, team_id, is_identified, uuid)+ ON CONFLICT (team_id, uuid) DO UPDATE SET+ is_deleted = false,+ version = COALESCE(posthog_person.version, 0) + 1,+ properties = '{}'::jsonb,+ properties_last_updated_at = '{}'::jsonb,+ properties_last_operation = '{}'::jsonb,+ created_at = EXCLUDED.created_at,+ is_identified = EXCLUDED.is_identified,+ last_seen_at = EXCLUDED.last_seen_at+ WHERE posthog_person.is_deleted = true+ RETURNING 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+ "#,+ &sorted_created_ats,+ &sorted_team_ids,+ &sorted_is_identified,+ &sorted_uuids+ )+ .fetch_all(&mut **tx)+ .await?;++ Ok(inserted+ .into_iter()+ .map(|row| {+ let revived_tombstone = row.version != Some(0);+ 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,+ };+ (+ (person.team_id, person.uuid),+ ResolvedPerson {+ person,+ created_by_us: true,+ revived_tombstone,+ },+ )+ })+ .collect())+}++/// Step 2: batch-fetch the committed winners for conflicted keys. This must+/// be a separate statement: the insert's snapshot predates a concurrent+/// winner's commit, a fresh statement snapshot sees it.+async fn fetch_conflict_winners(+ tx: &mut Tx<'_>,+ stubs: &[PersonStub],+ team_ids: &[i32],+ uuids: &[Uuid],+ persons: &mut PersonsByKey,+) -> StorageResult<()> {+ let conflicted: Vec<usize> = (0..stubs.len())+ .filter(|&i| !persons.contains_key(&(stubs[i].team_id, uuids[i])))+ .collect();+ if conflicted.is_empty() {+ return Ok(());+ }++ let conflicted_teams: Vec<i32> = conflicted.iter().map(|&i| team_ids[i]).collect();+ let conflicted_uuids: Vec<Uuid> = conflicted.iter().map(|&i| uuids[i]).collect();+ let winners = sqlx::query_as!(+ Person,+ r#"+ SELECT p.id as "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+ FROM posthog_person p+ JOIN unnest($1::int[], $2::uuid[]) AS k(team_id, uuid)+ ON p.team_id = k.team_id AND p.uuid = k.uuid+ WHERE p.is_deleted = false+ "#,+ &conflicted_teams,+ &conflicted_uuids+ )+ .fetch_all(&mut **tx)+ .await?;+ for winner in winners {+ persons.insert(+ (winner.team_id, winner.uuid),+ ResolvedPerson {+ person: winner,+ created_by_us: false,+ revived_tombstone: false,+ },+ );+ }+ Ok(())+}++/// Step 3: multi-row distinct id insert. The primary distinct id derives the+/// person uuid, so any events it sent before the person existed already used+/// the same uuid — always version 0. Extras always get version 1: without+/// the personless table there is no proof the distinct id never sent events,+/// and version 1 is safe either way (the override it emits is a transient+/// no-op when no events exist).+///+/// A conflict with a tombstoned mapping is a revival: repoint it at the new+/// person and bump the version above the tombstone. Conflicts with live+/// mappings keep the existing row (per-row): an extra that raced into+/// another person's hands is a merge scenario, which is the pipeline's job —+/// never re-pointed here, and not an error (a retry could never succeed).+async fn insert_distinct_id_mappings(+ tx: &mut Tx<'_>,+ stubs: &[PersonStub],+ uuids: &[Uuid],+ persons: &PersonsByKey,+) -> StorageResult<MappingOutcome> {+ // (team_id, distinct_id, person_id, version)+ let mut pdi_rows: Vec<(i32, String, i64, i64)> = Vec::new();+ for (i, stub) in stubs.iter().enumerate() {+ let Some(resolved) = persons.get(&(stub.team_id, uuids[i])) else {+ continue; // winner vanished; resolved to LostRace in step 4+ };+ pdi_rows.push((+ stub.team_id as i32,+ stub.distinct_id.clone(),+ resolved.person.id,+ 0,+ ));+ for extra in &stub.extra_distinct_ids {+ pdi_rows.push((stub.team_id as i32, extra.clone(), resolved.person.id, 1));+ }+ }+ // Stable sort + dedup: batch order picks the winner among duplicate keys+ // (an extra shared between stubs), and the dedup keeps ON CONFLICT DO+ // UPDATE from affecting one row twice in the same command.+ pdi_rows.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));+ pdi_rows.dedup_by(|a, b| (a.0, &a.1) == (b.0, &b.1));+ let pdi_teams: Vec<i32> = pdi_rows.iter().map(|r| r.0).collect();+ let pdi_dids: Vec<String> = pdi_rows.iter().map(|r| r.1.clone()).collect();+ let pdi_person_ids: Vec<i64> = pdi_rows.iter().map(|r| r.2).collect();+ let pdi_versions: Vec<i64> = pdi_rows.iter().map(|r| r.3).collect();++ let mut mapping = MappingOutcome {+ written: HashMap::new(),+ revived: HashSet::new(),+ };+ if pdi_dids.is_empty() {+ return Ok(mapping);+ }++ let rows = sqlx::query!(+ r#"+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)+ SELECT d, p, t, v FROM unnest($1::text[], $2::bigint[], $3::int[], $4::bigint[])+ AS u(d, p, t, v)+ 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 team_id::bigint as "team_id!", distinct_id, person_id,+ (xmax = 0) as "inserted!"+ "#,+ &pdi_dids,+ &pdi_person_ids,+ &pdi_teams,+ &pdi_versions+ )+ .fetch_all(&mut **tx)+ .await?;+ for row in rows {+ if !row.inserted {+ mapping+ .revived+ .insert((row.team_id, row.distinct_id.clone()));+ }+ mapping+ .written+ .insert((row.team_id, row.distinct_id), row.person_id);+ }+ Ok(mapping)+}++/// Step 4: per-stub outcomes. A stub is Committed when its primary distinct+/// id maps to its person; a stub whose primary mapping went elsewhere is a+/// lost race, and if this transaction created its person, the rows are+/// undone (created this transaction, so nothing can reference them) so the+/// stub doesn't linger orphaned.+async fn resolve_stub_outcomes(+ tx: &mut Tx<'_>,+ stubs: &[PersonStub],+ uuids: &[Uuid],+ persons: &PersonsByKey,+ mapping: &MappingOutcome,+) -> StorageResult<Vec<StubOutcome>> {+ let mut outcomes = Vec::with_capacity(stubs.len());+ for (i, stub) in stubs.iter().enumerate() {+ let Some(resolved) = persons.get(&(stub.team_id, uuids[i])) else {+ outcomes.push(StubOutcome::LostRace);+ continue;+ };+ let primary_key = (stub.team_id, stub.distinct_id.clone());+ if mapping.written.get(&primary_key) == Some(&resolved.person.id) {+ outcomes.push(StubOutcome::Committed {+ person: resolved.person.clone(),+ created: resolved.created_by_us,+ });+ continue;+ }+ if resolved.created_by_us {+ undo_created_person(tx, stub.team_id, resolved, mapping).await?;+ outcomes.push(StubOutcome::LostRace);+ continue;+ }+ // The person pre-existed and its primary mapping wasn't inserted by+ // us — verify the existing mapping points at this person.+ let existing = sqlx::query_scalar!(+ "SELECT person_id FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2 AND is_deleted = false",+ stub.team_id as i32,+ &stub.distinct_id+ )+ .fetch_optional(&mut **tx)+ .await?;+ if existing == Some(resolved.person.id) {+ outcomes.push(StubOutcome::Committed {+ person: resolved.person.clone(),+ created: false,+ });+ } else {+ outcomes.push(StubOutcome::LostRace);+ }+ }+ Ok(outcomes)+}++/// Undo one lost-race stub's rows: its distinct id mappings, then its person+/// row. Rows that revived a tombstone must be re-tombstoned (the tombstone+/// predates this transaction and must survive it), never hard-deleted; the+/// version bumps again so it stays monotonic. Re-tombstoning first lets the+/// fresh-row sweep distinguish them by is_deleted.+async fn undo_created_person(+ tx: &mut Tx<'_>,+ team_id: i64,+ resolved: &ResolvedPerson,+ mapping: &MappingOutcome,+) -> StorageResult<()> {+ let revived_dids: Vec<String> = mapping+ .written+ .iter()+ .filter(|((t, d), pid)| {+ *t == team_id+ && **pid == resolved.person.id+ && mapping.revived.contains(&(*t, d.clone()))+ })+ .map(|((_, d), _)| d.clone())+ .collect();+ if !revived_dids.is_empty() {+ sqlx::query!(+ r#"+ UPDATE posthog_persondistinctid+ SET is_deleted = true, version = COALESCE(version, 0) + 1+ WHERE team_id = $1 AND distinct_id = ANY($2)+ "#,+ team_id as i32,+ &revived_dids+ )+ .execute(&mut **tx)+ .await?;+ }+ sqlx::query!(+ "DELETE FROM posthog_persondistinctid WHERE team_id = $1 AND person_id = $2 AND is_deleted = false",+ team_id as i32,+ resolved.person.id+ )+ .execute(&mut **tx)+ .await?;+ if resolved.revived_tombstone {+ sqlx::query!(+ r#"+ UPDATE posthog_person+ SET is_deleted = true, version = COALESCE(version, 0) + 1,+ properties = '{}'::jsonb+ WHERE team_id = $1 AND id = $2+ "#,+ team_id as i32,+ resolved.person.id+ )+ .execute(&mut **tx)+ .await?;+ } else {+ sqlx::query!(+ "DELETE FROM posthog_person WHERE team_id = $1 AND id = $2",+ team_id as i32,+ resolved.person.id+ )+ .execute(&mut **tx)+ .await?;+ }+ Ok(())+}diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rsindex 4264848e9ac3..18269c699860 100644--- a/rust/personhog-identity/tests/common/mod.rs+++ b/rust/personhog-identity/tests/common/mod.rs@@ -66,10 +66,6 @@ impl TestContext {.bind(self.team_id as i32).execute(&self.pool).await?;- sqlx::query("DELETE FROM posthog_personlessdistinctid WHERE team_id = $1")- .bind(self.team_id as i32)- .execute(&self.pool)- .await?;sqlx::query("DELETE FROM posthog_person WHERE team_id = $1").bind(self.team_id as i32).execute(&self.pool)diff --git a/rust/personhog-identity/tests/storage_tests.rs b/rust/personhog-identity/tests/storage_tests.rsindex 9deecc2ec5a3..4c9aa156ac5d 100644--- a/rust/personhog-identity/tests/storage_tests.rs+++ b/rust/personhog-identity/tests/storage_tests.rs@@ -10,50 +10,119 @@ use personhog_identity::storage::{IdentityStorage, PersonStub, StubOutcome};/// Storage-assertion helpers used only by this test binary.impl TestContext {- async fn insert_personless_distinct_id(&self, distinct_id: &str, is_merged: bool) {+ async fn distinct_id_version(&self, distinct_id: &str) -> Option<i64> {+ sqlx::query_scalar(+ "SELECT version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",+ )+ .bind(self.team_id as i32)+ .bind(distinct_id)+ .fetch_optional(&self.pool)+ .await+ .expect("Failed to fetch distinct id version")+ .flatten()+ }++ async fn person_count(&self) -> i64 {+ sqlx::query_scalar("SELECT count(*) FROM posthog_person WHERE team_id = $1")+ .bind(self.team_id as i32)+ .fetch_one(&self.pool)+ .await+ .expect("Failed to count persons")+ }++ /// Tombstones a person the way the delete saga does: flag flipped,+ /// version parked above every prior write, properties cleared.+ async fn tombstone_person(&self, person_id: i64, version: i64) {sqlx::query(r#"- INSERT INTO posthog_personlessdistinctid (distinct_id, is_merged, created_at, team_id)- VALUES ($1, $2, now(), $3)+ UPDATE posthog_person+ SET is_deleted = true, version = $3, properties = '{}'::jsonb+ WHERE team_id = $1 AND id = $2"#,)- .bind(distinct_id)- .bind(is_merged).bind(self.team_id as i32)+ .bind(person_id)+ .bind(version).execute(&self.pool).await- .expect("Failed to insert personless distinct id");+ .expect("Failed to tombstone person");}- async fn distinct_id_version(&self, distinct_id: &str) -> Option<i64> {- sqlx::query_scalar(- "SELECT version FROM posthog_persondistinctid WHERE team_id = $1 AND distinct_id = $2",+ async fn tombstone_distinct_id(&self, distinct_id: &str, version: i64) {+ sqlx::query(+ r#"+ UPDATE posthog_persondistinctid+ SET is_deleted = true, version = $3+ WHERE team_id = $1 AND distinct_id = $2+ "#,).bind(self.team_id as i32).bind(distinct_id)- .fetch_optional(&self.pool)+ .bind(version)+ .execute(&self.pool).await- .expect("Failed to fetch distinct id version")- .flatten()+ .expect("Failed to tombstone distinct id");}- async fn personless_is_merged(&self, distinct_id: &str) -> Option<bool> {+ async fn insert_tombstoned_person(&self, uuid: uuid::Uuid, version: i64) -> i64 {sqlx::query_scalar(- "SELECT is_merged FROM posthog_personlessdistinctid WHERE team_id = $1 AND distinct_id = $2",+ r#"+ INSERT INTO posthog_person+ (created_at, properties, properties_last_updated_at, properties_last_operation,+ team_id, is_identified, uuid, version, is_deleted)+ VALUES (now(), '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, $1, false, $2, $3, true)+ RETURNING id+ "#,).bind(self.team_id as i32)+ .bind(uuid)+ .bind(version)+ .fetch_one(&self.pool)+ .await+ .expect("Failed to insert tombstoned person")+ }++ async fn insert_tombstoned_distinct_id(&self, distinct_id: &str, person_id: i64, version: i64) {+ sqlx::query(+ r#"+ INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version, is_deleted)+ VALUES ($1, $2, $3, $4, true)+ "#,+ ).bind(distinct_id)- .fetch_optional(&self.pool)+ .bind(person_id)+ .bind(self.team_id as i32)+ .bind(version)+ .execute(&self.pool).await- .expect("Failed to fetch personless row")+ .expect("Failed to insert tombstoned distinct id");}- async fn person_count(&self) -> i64 {- sqlx::query_scalar("SELECT count(*) FROM posthog_person WHERE team_id = $1")- .bind(self.team_id as i32)- .fetch_one(&self.pool)- .await- .expect("Failed to count persons")+ /// (is_deleted, version) for a person row, tombstoned or not.+ async fn person_state(&self, person_id: i64) -> (bool, Option<i64>) {+ sqlx::query_as(+ "SELECT is_deleted, version FROM posthog_person WHERE team_id = $1 AND id = $2",+ )+ .bind(self.team_id as i32)+ .bind(person_id)+ .fetch_one(&self.pool)+ .await+ .expect("Failed to fetch person state")+ }++ /// (person_id, is_deleted, version) for a distinct id row, tombstoned or not.+ async fn distinct_id_state(&self, distinct_id: &str) -> Option<(i64, bool, Option<i64>)> {+ sqlx::query_as(+ r#"+ SELECT person_id, is_deleted, version FROM posthog_persondistinctid+ WHERE team_id = $1 AND distinct_id = $2+ "#,+ )+ .bind(self.team_id as i32)+ .bind(distinct_id)+ .fetch_optional(&self.pool)+ .await+ .expect("Failed to fetch distinct id state")}}@@ -134,27 +203,24 @@ async fn retried_create_returns_existing_person_without_duplicating() {}#[tokio::test]-async fn extra_distinct_ids_carry_personless_history_as_version_one() {+async fn extra_distinct_ids_always_get_version_one() {let ctx = TestContext::new().await;- // "seen-before" was used personless; "fresh" was not.- ctx.insert_personless_distinct_id("seen-before", false)- .await;let outcomes = ctx.storage- .create_person_stubs(&[stub(&ctx, "primary", &["seen-before", "fresh"])])+ .create_person_stubs(&[stub(&ctx, "primary", &["extra-a", "extra-b"])]).await.expect("create should succeed");let [StubOutcome::Committed { created: true, .. }] = &outcomes[..] else {panic!("expected created outcome");};+ // The primary derives the person uuid, so its history is correct by+ // construction: version 0. Extras can't be proven history-free, so they+ // always get version 1 and let ClickHouse emit an override.assert_eq!(ctx.distinct_id_version("primary").await, Some(0));- assert_eq!(ctx.distinct_id_version("seen-before").await, Some(1));- assert_eq!(ctx.distinct_id_version("fresh").await, Some(0));- // Both extras are marked merged so concurrent personless events re-resolve.- assert_eq!(ctx.personless_is_merged("seen-before").await, Some(true));- assert_eq!(ctx.personless_is_merged("fresh").await, Some(true));+ assert_eq!(ctx.distinct_id_version("extra-a").await, Some(1));+ assert_eq!(ctx.distinct_id_version("extra-b").await, Some(1));ctx.cleanup().await.ok();}@@ -190,25 +256,18 @@ async fn create_loses_race_when_distinct_id_is_mapped_to_another_person() {}#[tokio::test]-async fn lost_race_undo_reverts_only_the_personless_marks_it_made() {+async fn lost_race_undo_keeps_extras_shared_with_a_committed_stub() {let ctx = TestContext::new().await;// The loser's primary distinct id is already mapped elsewhere, so its- // whole stub rolls back — including the step that marked its extras- // merged. One extra per prior state: no row, unmerged row, merged row.+ // whole stub rolls back — but an extra shared with a committed stub was+ // written under the winner's person and must survive the undo.ctx.insert_person_with_distinct_id("undo-taken").await;- ctx.insert_personless_distinct_id("undo-flipped", false)- .await;- ctx.insert_personless_distinct_id("undo-merged", true).await;let outcomes = ctx.storage.create_person_stubs(&[stub(&ctx, "undo-winner", &["undo-shared"]),- stub(- &ctx,- "undo-taken",- &["undo-fresh", "undo-flipped", "undo-merged", "undo-shared"],- ),+ stub(&ctx, "undo-taken", &["undo-own", "undo-shared"]),]).await.expect("create should not error");@@ -223,13 +282,9 @@ async fn lost_race_undo_reverts_only_the_personless_marks_it_made() {"expected committed + lost race, got {outcomes:?}");- // The undone stub's marks are reverted to their prior state…- assert_eq!(ctx.personless_is_merged("undo-fresh").await, None);- assert_eq!(ctx.personless_is_merged("undo-flipped").await, Some(false));- assert_eq!(ctx.personless_is_merged("undo-merged").await, Some(true));- // …but an extra shared with a committed stub keeps its mapping and mark.- assert_eq!(ctx.personless_is_merged("undo-shared").await, Some(true));- assert_eq!(ctx.distinct_id_version("undo-shared").await, Some(0));+ // The undone stub's own rows are gone, the shared extra's mapping stands.+ assert_eq!(ctx.distinct_id_version("undo-own").await, None);+ assert_eq!(ctx.distinct_id_version("undo-shared").await, Some(1));ctx.cleanup().await.ok();}@@ -458,6 +513,148 @@ async fn create_blocked_on_uncommitted_mapping_rolls_back_as_lost_race() {ctx.cleanup().await.ok();}+/// A deleted person's rows stay behind as tombstones; re-creating the same+/// distinct id must revive them above the tombstone version instead of+/// inserting a fresh row that restarts at version 0 (which would lose to the+/// ClickHouse tombstone forever).+#[tokio::test]+async fn deleted_person_is_revived_above_the_tombstone_on_recreate() {+ let ctx = TestContext::new().await;++ let first = ctx+ .storage+ .create_person_stubs(&[stub(&ctx, "revive-me", &[])])+ .await+ .expect("first create should succeed");+ let [StubOutcome::Committed { person, .. }] = &first[..] else {+ panic!("expected committed outcome");+ };+ let person_id = person.id;++ ctx.tombstone_person(person_id, 7).await;+ ctx.tombstone_distinct_id("revive-me", 3).await;++ // Tombstoned rows are invisible to resolution.+ let resolved = ctx+ .storage+ .resolve_distinct_ids(&[(ctx.team_id, "revive-me".to_string())])+ .await+ .expect("resolve should succeed");+ assert!(resolved.is_empty(), "tombstoned person must not resolve");++ let second = ctx+ .storage+ .create_person_stubs(&[stub(&ctx, "revive-me", &[])])+ .await+ .expect("recreate should succeed");+ let [StubOutcome::Committed { person, created }] = &second[..] else {+ panic!("expected committed outcome, got {second:?}");+ };+ assert!(created, "a revival is a creation to the caller");+ assert_eq!(person.id, person_id, "revival keeps the row, not a new one");+ assert_eq!(person.version, Some(8), "revived above the tombstone");+ assert_eq!(person.properties.as_deref(), Some("{}"));+ assert_eq!(+ ctx.distinct_id_state("revive-me").await,+ Some((person_id, false, Some(4))),+ "mapping revived above its tombstone"+ );+ assert_eq!(ctx.person_count().await, 1);++ ctx.cleanup().await.ok();+}++/// A revived stub that loses the mapping race must be re-tombstoned, not+/// hard-deleted: the tombstones predate this transaction and deleting them+/// would reopen the version-0-resurrection hole for the next recreate.+#[tokio::test]+async fn lost_race_rollback_re_tombstones_revived_rows() {+ let ctx = TestContext::new().await;+ // "steal-did" is live-mapped to another person, while its deterministic+ // uuid still belongs to a tombstoned person with a tombstoned extra.+ let live_id = ctx.insert_person_with_distinct_id("steal-did").await;+ let dead_id = ctx+ .insert_tombstoned_person(person_uuid(ctx.team_id, "steal-did"), 5)+ .await;+ ctx.insert_tombstoned_distinct_id("dead-extra", dead_id, 2)+ .await;++ let outcomes = ctx+ .storage+ .create_person_stubs(&[stub(&ctx, "steal-did", &["dead-extra"])])+ .await+ .expect("create should not error");+ assert!(+ matches!(outcomes[..], [StubOutcome::LostRace]),+ "live mapping must win, got {outcomes:?}"+ );++ let (is_deleted, version) = ctx.person_state(dead_id).await;+ assert!(+ is_deleted,+ "revived person must be re-tombstoned, not deleted"+ );+ assert!(+ version > Some(5),+ "re-tombstone stays above the old tombstone"+ );+ let (_, extra_deleted, extra_version) = ctx+ .distinct_id_state("dead-extra")+ .await+ .expect("revived mapping must be re-tombstoned, not deleted");+ assert!(extra_deleted);+ assert!(extra_version > Some(2));++ let resolved = ctx+ .storage+ .resolve_distinct_ids(&[(ctx.team_id, "steal-did".to_string())])+ .await+ .expect("resolve should succeed");+ assert_eq!(+ resolved[&(ctx.team_id, "steal-did".to_string())].id,+ live_id+ );+ assert_eq!(ctx.person_count().await, 2, "no orphan third person");++ ctx.cleanup().await.ok();+}++/// Duplicate keys in one batch conflict-update the same tombstoned row; the+/// pre-insert dedup keeps Postgres from rejecting the command with "ON+/// CONFLICT DO UPDATE cannot affect row a second time".+#[tokio::test]+async fn duplicate_batch_keys_against_tombstones_do_not_error() {+ let ctx = TestContext::new().await;+ let dead_id = ctx+ .insert_tombstoned_person(person_uuid(ctx.team_id, "dup-did"), 4)+ .await;+ ctx.insert_tombstoned_distinct_id("dup-did", dead_id, 1)+ .await;+ ctx.insert_tombstoned_distinct_id("dup-extra", dead_id, 1)+ .await;++ let outcomes = ctx+ .storage+ .create_person_stubs(&[+ stub(&ctx, "dup-did", &["dup-extra"]),+ stub(&ctx, "dup-did", &["dup-extra"]),+ ])+ .await+ .expect("duplicate keys in one batch must not error");++ let [StubOutcome::Committed { person: a, .. }, StubOutcome::Committed { person: b, .. }] =+ &outcomes[..]+ else {+ panic!("expected two committed outcomes, got {outcomes:?}");+ };+ assert_eq!(a.id, dead_id);+ assert_eq!(b.id, dead_id);+ let (is_deleted, _) = ctx.person_state(dead_id).await;+ assert!(!is_deleted, "person revived exactly once");++ ctx.cleanup().await.ok();+}+#[tokio::test]async fn resolve_returns_only_existing_keys() {let ctx = TestContext::new().await;diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rsindex 960fcbda48fd..1a2d9ec90f4d 100644--- a/rust/personhog-leader/src/pg.rs+++ b/rust/personhog-leader/src/pg.rs@@ -42,11 +42,13 @@ pub async fn load_person_from_pg(// whose PG-expanded rendering serde_json rejects, and the leniency// lives in our parse step (see below). The cost is identical — sqlx's// jsonb decode parses the same text under the hood.+ // A tombstoned person must not be re-served on a cache miss; not-found+ // is the truthful answer for a deleted person.let row = sqlx::query(&format!("SELECT id, team_id, uuid::text, properties::text AS properties, created_at, version, \is_identifiedFROM {table}- WHERE team_id = $1 AND id = $2",+ WHERE team_id = $1 AND id = $2 AND is_deleted = false",)).bind(team_id_i32).bind(key.person_id)diff --git a/rust/personhog-replica/.sqlx/query-6e250de7e8abd522979f516bd5236cff84021b41a8662c088e3cf6c9fb42b6dc.json b/rust/personhog-replica/.sqlx/query-01ea61615cc0eecc76989c2ccc42a581aa4a941e7f53746be1f577495f74e41f.jsonsimilarity index 92%rename from rust/personhog-replica/.sqlx/query-6e250de7e8abd522979f516bd5236cff84021b41a8662c088e3cf6c9fb42b6dc.jsonrename to rust/personhog-replica/.sqlx/query-01ea61615cc0eecc76989c2ccc42a581aa4a941e7f53746be1f577495f74e41f.jsonindex 3ad93e470338..5f52dc50d587 100644--- a/rust/personhog-replica/.sqlx/query-6e250de7e8abd522979f516bd5236cff84021b41a8662c088e3cf6c9fb42b6dc.json+++ b/rust/personhog-replica/.sqlx/query-01ea61615cc0eecc76989c2ccc42a581aa4a941e7f53746be1f577495f74e41f.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 CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END 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 d.person_id = p.id AND d.team_id = p.team_id\n INNER JOIN UNNEST($1::integer[], $2::text[]) AS batch(team_id, distinct_id)\n ON d.team_id = batch.team_id AND d.distinct_id = batch.distinct_id\n ",+ "query": "\n SELECT p.id, p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END 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 d.person_id = p.id AND d.team_id = p.team_id\n INNER JOIN UNNEST($1::integer[], $2::text[]) AS batch(team_id, distinct_id)\n ON d.team_id = batch.team_id AND d.distinct_id = batch.distinct_id\n WHERE p.is_deleted = false AND d.is_deleted = false\n ","describe": {"columns": [{@@ -86,5 +86,5 @@false]},- "hash": "6e250de7e8abd522979f516bd5236cff84021b41a8662c088e3cf6c9fb42b6dc"+ "hash": "01ea61615cc0eecc76989c2ccc42a581aa4a941e7f53746be1f577495f74e41f"}diff --git a/rust/personhog-replica/.sqlx/query-f0c3b45d37c742f954fbfac66d4bc46a5922c950f8ebb3662194ee42590f5331.json b/rust/personhog-replica/.sqlx/query-14e87c3f09438c2c73e7d98d8f132b146f13d84469cc30ab5dc531b8ca266831.jsonsimilarity index 92%rename from rust/personhog-replica/.sqlx/query-f0c3b45d37c742f954fbfac66d4bc46a5922c950f8ebb3662194ee42590f5331.jsonrename to rust/personhog-replica/.sqlx/query-14e87c3f09438c2c73e7d98d8f132b146f13d84469cc30ab5dc531b8ca266831.jsonindex 636c44b20ee5..e671ff63cea6 100644--- a/rust/personhog-replica/.sqlx/query-f0c3b45d37c742f954fbfac66d4bc46a5922c950f8ebb3662194ee42590f5331.json+++ b/rust/personhog-replica/.sqlx/query-14e87c3f09438c2c73e7d98d8f132b146f13d84469cc30ab5dc531b8ca266831.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT p.id, p.uuid, p.team_id::bigint as \"team_id!\", 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, p.version, p.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 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 = $2\n LIMIT 1\n ",+ "query": "\n SELECT p.id, p.uuid, p.team_id::bigint as \"team_id!\", 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, p.version, p.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 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 = $2\n AND p.is_deleted = false AND d.is_deleted = false\n LIMIT 1\n ","describe": {"columns": [{@@ -79,5 +79,5 @@true]},- "hash": "f0c3b45d37c742f954fbfac66d4bc46a5922c950f8ebb3662194ee42590f5331"+ "hash": "14e87c3f09438c2c73e7d98d8f132b146f13d84469cc30ab5dc531b8ca266831"}diff --git a/rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.json b/rust/personhog-replica/.sqlx/query-1b6e485b218b291921e5649c572fd413188bd09ce0a2f0883749c1500c4b18ca.jsonsimilarity index 80%rename from rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.jsonrename to rust/personhog-replica/.sqlx/query-1b6e485b218b291921e5649c572fd413188bd09ce0a2f0883749c1500c4b18ca.jsonindex 38f567b32e35..eb30d5e1ef4b 100644--- a/rust/personhog-replica/.sqlx/query-fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65.json+++ b/rust/personhog-replica/.sqlx/query-1b6e485b218b291921e5649c572fd413188bd09ce0a2f0883749c1500c4b18ca.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) AND is_deleted = false\n ","describe": {"columns": [{@@ -31,5 +31,5 @@true]},- "hash": "fc4538c02cd1b3f65f03431e67bf0d87c1af99499a71823bb1a25f11056a5b65"+ "hash": "1b6e485b218b291921e5649c572fd413188bd09ce0a2f0883749c1500c4b18ca"}diff --git a/rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.json b/rust/personhog-replica/.sqlx/query-1ef68f82436431c6472141e87054082b3bc710bbee75eb39c7384f53717c324c.jsonsimilarity index 89%rename from rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.jsonrename to rust/personhog-replica/.sqlx/query-1ef68f82436431c6472141e87054082b3bc710bbee75eb39c7384f53717c324c.jsonindex 09193a8b21b2..5de5387b5a2f 100644--- a/rust/personhog-replica/.sqlx/query-019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29.json+++ b/rust/personhog-replica/.sqlx/query-1ef68f82436431c6472141e87054082b3bc710bbee75eb39c7384f53717c324c.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 CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END 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 UNNEST($2::text[]) AS batch(distinct_id)\n INNER JOIN posthog_persondistinctid d\n ON d.team_id = $1 AND d.distinct_id = batch.distinct_id\n INNER JOIN posthog_person p\n ON p.id = d.person_id AND p.team_id = d.team_id\n ",+ "query": "\n SELECT p.id, p.uuid as \"uuid!\", p.team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN p.properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN p.properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN p.properties_last_operation::text ELSE NULL END 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 UNNEST($2::text[]) AS batch(distinct_id)\n INNER JOIN posthog_persondistinctid d\n ON d.team_id = $1 AND d.distinct_id = batch.distinct_id\n AND d.is_deleted = false\n INNER JOIN posthog_person p\n ON p.id = d.person_id AND p.team_id = d.team_id\n AND p.is_deleted = false\n ","describe": {"columns": [{@@ -86,5 +86,5 @@false]},- "hash": "019e2350b435082cecc3f9fd730bc40621f35faf24b44f618e197d72364e2c29"+ "hash": "1ef68f82436431c6472141e87054082b3bc710bbee75eb39c7384f53717c324c"}diff --git a/rust/personhog-replica/.sqlx/query-f45d837735ee305356d8dfda0787b3d0e4e25c04056a3b934a01507e8d1d3933.json b/rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.jsonsimilarity index 88%rename from rust/personhog-replica/.sqlx/query-f45d837735ee305356d8dfda0787b3d0e4e25c04056a3b934a01507e8d1d3933.jsonrename to rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.jsonindex 7fc4c4ed725d..96ef95655de5 100644--- a/rust/personhog-replica/.sqlx/query-f45d837735ee305356d8dfda0787b3d0e4e25c04056a3b934a01507e8d1d3933.json+++ b/rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT ppd.person_id, ppd.distinct_id,\n fhko.feature_flag_key as \"feature_flag_key?\",\n fhko.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid ppd\n LEFT JOIN posthog_featureflaghashkeyoverride fhko\n ON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id\n WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2)\n ",+ "query": "\n SELECT ppd.person_id, ppd.distinct_id,\n fhko.feature_flag_key as \"feature_flag_key?\",\n fhko.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid ppd\n LEFT JOIN posthog_featureflaghashkeyoverride fhko\n ON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id\n WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2) AND ppd.is_deleted = false\n ","describe": {"columns": [{@@ -37,5 +37,5 @@false]},- "hash": "f45d837735ee305356d8dfda0787b3d0e4e25c04056a3b934a01507e8d1d3933"+ "hash": "1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2"}diff --git a/rust/personhog-replica/.sqlx/query-82503be15bb0e86f5674a8d16a7b87d235a21cb2a8039848f2e3d59937e78713.json b/rust/personhog-replica/.sqlx/query-4470be01cb9ddfb906cd1b1f272a2950a9095b34700686b64b8844c255e01711.jsonsimilarity index 92%rename from rust/personhog-replica/.sqlx/query-82503be15bb0e86f5674a8d16a7b87d235a21cb2a8039848f2e3d59937e78713.jsonrename to rust/personhog-replica/.sqlx/query-4470be01cb9ddfb906cd1b1f272a2950a9095b34700686b64b8844c255e01711.jsonindex 2a8f849f7574..2777a818a06c 100644--- a/rust/personhog-replica/.sqlx/query-82503be15bb0e86f5674a8d16a7b87d235a21cb2a8039848f2e3d59937e78713.json+++ b/rust/personhog-replica/.sqlx/query-4470be01cb9ddfb906cd1b1f272a2950a9095b34700686b64b8844c255e01711.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 = $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 = $2 AND is_deleted = false\n ","describe": {"columns": [{@@ -79,5 +79,5 @@true]},- "hash": "82503be15bb0e86f5674a8d16a7b87d235a21cb2a8039848f2e3d59937e78713"+ "hash": "4470be01cb9ddfb906cd1b1f272a2950a9095b34700686b64b8844c255e01711"}diff --git a/rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.json b/rust/personhog-replica/.sqlx/query-52dcb2125ad7f52000c172d5722679001bc177642bbe0a68fdcbb33ebe437ca7.jsonsimilarity index 71%rename from rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.jsonrename to rust/personhog-replica/.sqlx/query-52dcb2125ad7f52000c172d5722679001bc177642bbe0a68fdcbb33ebe437ca7.jsonindex 511ce93eadd5..5caf485eac9e 100644--- a/rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.json+++ b/rust/personhog-replica/.sqlx/query-52dcb2125ad7f52000c172d5722679001bc177642bbe0a68fdcbb33ebe437ca7.json@@ -1,6 +1,6 @@{"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 capped.person_id, capped.distinct_id, capped.version\n FROM (\n SELECT person_id, distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ) l\n ",+ "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 capped.person_id, capped.distinct_id, capped.version\n FROM (\n SELECT person_id, distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.id AND is_deleted = false\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ) l\n ","describe": {"columns": [{@@ -32,5 +32,5 @@true]},- "hash": "d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2"+ "hash": "52dcb2125ad7f52000c172d5722679001bc177642bbe0a68fdcbb33ebe437ca7"}diff --git a/rust/personhog-replica/.sqlx/query-d6c4b0469b4c82657c213fbf265a58eb553db86f0a117f2c3b2abaa56be5bb0a.json b/rust/personhog-replica/.sqlx/query-5aa0db28dba0afef09fade180567a6d0d856151fc49bd8cd8e8fdb0660baa23b.jsonsimilarity index 94%rename from rust/personhog-replica/.sqlx/query-d6c4b0469b4c82657c213fbf265a58eb553db86f0a117f2c3b2abaa56be5bb0a.jsonrename to rust/personhog-replica/.sqlx/query-5aa0db28dba0afef09fade180567a6d0d856151fc49bd8cd8e8fdb0660baa23b.jsonindex 369bc8de8017..805a63b58632 100644--- a/rust/personhog-replica/.sqlx/query-d6c4b0469b4c82657c213fbf265a58eb553db86f0a117f2c3b2abaa56be5bb0a.json+++ b/rust/personhog-replica/.sqlx/query-5aa0db28dba0afef09fade180567a6d0d856151fc49bd8cd8e8fdb0660baa23b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN properties_last_operation::text ELSE NULL END 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!\",\n CASE WHEN $3::boolean THEN properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN properties_last_operation::text ELSE NULL END 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) AND is_deleted = false\n ","describe": {"columns": [{@@ -80,5 +80,5 @@true]},- "hash": "d6c4b0469b4c82657c213fbf265a58eb553db86f0a117f2c3b2abaa56be5bb0a"+ "hash": "5aa0db28dba0afef09fade180567a6d0d856151fc49bd8cd8e8fdb0660baa23b"}diff --git a/rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.json b/rust/personhog-replica/.sqlx/query-7637478e1f0961cfc6bd12a9f017dce8577d3543f809569bc21d4393a793ae83.jsonsimilarity index 66%rename from rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.jsonrename to rust/personhog-replica/.sqlx/query-7637478e1f0961cfc6bd12a9f017dce8577d3543f809569bc21d4393a793ae83.jsonindex 43da798e7a9a..b707ab983b82 100644--- a/rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.json+++ b/rust/personhog-replica/.sqlx/query-7637478e1f0961cfc6bd12a9f017dce8577d3543f809569bc21d4393a793ae83.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT capped.distinct_id, capped.version\n FROM (\n SELECT distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ",+ "query": "\n SELECT capped.distinct_id, capped.version\n FROM (\n SELECT distinct_id, version, id\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2 AND is_deleted = false\n LIMIT 2500\n ) capped\n ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id\n LIMIT $3\n ","describe": {"columns": [{@@ -26,5 +26,5 @@true]},- "hash": "7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908"+ "hash": "7637478e1f0961cfc6bd12a9f017dce8577d3543f809569bc21d4393a793ae83"}diff --git a/rust/personhog-replica/.sqlx/query-1a98b4e231c785a8bf345eba9bff959210162443c09089873dad1f24af56f259.json b/rust/personhog-replica/.sqlx/query-820bc26a1239fa88a2add1a672e634df3cdce0385025656da2d7aba9f1df8f79.jsonsimilarity index 75%rename from rust/personhog-replica/.sqlx/query-1a98b4e231c785a8bf345eba9bff959210162443c09089873dad1f24af56f259.jsonrename to rust/personhog-replica/.sqlx/query-820bc26a1239fa88a2add1a672e634df3cdce0385025656da2d7aba9f1df8f79.jsonindex bd3390ae98af..a7fc8ad1f817 100644--- a/rust/personhog-replica/.sqlx/query-1a98b4e231c785a8bf345eba9bff959210162443c09089873dad1f24af56f259.json+++ b/rust/personhog-replica/.sqlx/query-820bc26a1239fa88a2add1a672e634df3cdce0385025656da2d7aba9f1df8f79.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2\n ",+ "query": "\n SELECT distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2 AND is_deleted = false\n ","describe": {"columns": [{@@ -25,5 +25,5 @@true]},- "hash": "1a98b4e231c785a8bf345eba9bff959210162443c09089873dad1f24af56f259"+ "hash": "820bc26a1239fa88a2add1a672e634df3cdce0385025656da2d7aba9f1df8f79"}diff --git a/rust/personhog-replica/.sqlx/query-7787d31cff29491bfbf4e39ac7c5214329c92bb0159b77b596f1ce05622e9853.json b/rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.jsonsimilarity index 64%rename from rust/personhog-replica/.sqlx/query-7787d31cff29491bfbf4e39ac7c5214329c92bb0159b77b596f1ce05622e9853.jsonrename to rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.jsonindex 983b50f9fb5a..10b59685da4f 100644--- a/rust/personhog-replica/.sqlx/query-7787d31cff29491bfbf4e39ac7c5214329c92bb0159b77b596f1ce05622e9853.json+++ b/rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT $1, p.person_id, f.flag_key, $2\n FROM posthog_persondistinctid p\n CROSS JOIN UNNEST($4::text[]) AS f(flag_key)\n WHERE p.team_id = $1 AND p.distinct_id = ANY($3)\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)\n ON CONFLICT DO NOTHING\n ",+ "query": "\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT $1, p.person_id, f.flag_key, $2\n FROM posthog_persondistinctid p\n CROSS JOIN UNNEST($4::text[]) AS f(flag_key)\n WHERE p.team_id = $1 AND p.distinct_id = ANY($3) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n ON CONFLICT DO NOTHING\n ","describe": {"columns": [],"parameters": {@@ -13,5 +13,5 @@},"nullable": []},- "hash": "7787d31cff29491bfbf4e39ac7c5214329c92bb0159b77b596f1ce05622e9853"+ "hash": "85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09"}diff --git a/rust/personhog-replica/.sqlx/query-dc24262affa2307370c1fa1d18de028195e38f08a9eea4304a9191974909f1c2.json b/rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.jsonsimilarity index 78%rename from rust/personhog-replica/.sqlx/query-dc24262affa2307370c1fa1d18de028195e38f08a9eea4304a9191974909f1c2.jsonrename to rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.jsonindex 1eaec00cb179..1ef200cec894 100644--- a/rust/personhog-replica/.sqlx/query-dc24262affa2307370c1fa1d18de028195e38f08a9eea4304a9191974909f1c2.json+++ b/rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT DISTINCT p.person_id, p.distinct_id,\n existing.feature_flag_key as \"feature_flag_key?\",\n existing.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid p\n LEFT JOIN posthog_featureflaghashkeyoverride existing\n ON existing.person_id = p.person_id AND existing.team_id = p.team_id\n WHERE p.team_id = $1 AND p.distinct_id = ANY($2)\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)\n ",+ "query": "\n SELECT DISTINCT p.person_id, p.distinct_id,\n existing.feature_flag_key as \"feature_flag_key?\",\n existing.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid p\n LEFT JOIN posthog_featureflaghashkeyoverride existing\n ON existing.person_id = p.person_id AND existing.team_id = p.team_id\n WHERE p.team_id = $1 AND p.distinct_id = ANY($2) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n ","describe": {"columns": [{@@ -37,5 +37,5 @@false]},- "hash": "dc24262affa2307370c1fa1d18de028195e38f08a9eea4304a9191974909f1c2"+ "hash": "aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a"}diff --git a/rust/personhog-replica/.sqlx/query-b6d62a371a12a86e28487c9cbdaefee50ed10f15e6fadb3b791efe7c26282cca.json b/rust/personhog-replica/.sqlx/query-b1d7b6aaae2a3f343e59cbaba6093de154a33475b69017d0bb26a5b9f416d5c6.jsonsimilarity index 94%rename from rust/personhog-replica/.sqlx/query-b6d62a371a12a86e28487c9cbdaefee50ed10f15e6fadb3b791efe7c26282cca.jsonrename to rust/personhog-replica/.sqlx/query-b1d7b6aaae2a3f343e59cbaba6093de154a33475b69017d0bb26a5b9f416d5c6.jsonindex 6853459982e3..f19557f9879c 100644--- a/rust/personhog-replica/.sqlx/query-b6d62a371a12a86e28487c9cbdaefee50ed10f15e6fadb3b791efe7c26282cca.json+++ b/rust/personhog-replica/.sqlx/query-b1d7b6aaae2a3f343e59cbaba6093de154a33475b69017d0bb26a5b9f416d5c6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, uuid, team_id::bigint as \"team_id!\",\n CASE WHEN $3::boolean THEN properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN properties_last_operation::text ELSE NULL END 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!\",\n CASE WHEN $3::boolean THEN properties::text ELSE NULL END as \"properties?\",\n CASE WHEN $3::boolean THEN properties_last_updated_at::text ELSE NULL END as \"properties_last_updated_at?\",\n CASE WHEN $3::boolean THEN properties_last_operation::text ELSE NULL END 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) AND is_deleted = false\n ","describe": {"columns": [{@@ -80,5 +80,5 @@true]},- "hash": "b6d62a371a12a86e28487c9cbdaefee50ed10f15e6fadb3b791efe7c26282cca"+ "hash": "b1d7b6aaae2a3f343e59cbaba6093de154a33475b69017d0bb26a5b9f416d5c6"}diff --git a/rust/personhog-replica/.sqlx/query-82dae613d9bee4f21326109a939bba3c124c0b82e0d8f495661038b307e4c219.json b/rust/personhog-replica/.sqlx/query-e1093b8c68139b7c25fc944c9a91a8d060ea0f95af0351029928acb5a8d048de.jsonsimilarity index 92%rename from rust/personhog-replica/.sqlx/query-82dae613d9bee4f21326109a939bba3c124c0b82e0d8f495661038b307e4c219.jsonrename to rust/personhog-replica/.sqlx/query-e1093b8c68139b7c25fc944c9a91a8d060ea0f95af0351029928acb5a8d048de.jsonindex 3442ccf9deb8..0f1e4e573945 100644--- a/rust/personhog-replica/.sqlx/query-82dae613d9bee4f21326109a939bba3c124c0b82e0d8f495661038b307e4c219.json+++ b/rust/personhog-replica/.sqlx/query-e1093b8c68139b7c25fc944c9a91a8d060ea0f95af0351029928acb5a8d048de.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 = $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 = $2 AND is_deleted = false\n ","describe": {"columns": [{@@ -79,5 +79,5 @@true]},- "hash": "82dae613d9bee4f21326109a939bba3c124c0b82e0d8f495661038b307e4c219"+ "hash": "e1093b8c68139b7c25fc944c9a91a8d060ea0f95af0351029928acb5a8d048de"}diff --git a/rust/personhog-replica/src/storage/postgres/distinct_id.rs b/rust/personhog-replica/src/storage/postgres/distinct_id.rsindex ee250c7cd48a..8a67feba1874 100644--- a/rust/personhog-replica/src/storage/postgres/distinct_id.rs+++ b/rust/personhog-replica/src/storage/postgres/distinct_id.rs@@ -49,7 +49,7 @@ impl DistinctIdLookup for PostgresStorage {FROM (SELECT distinct_id, version, idFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = $2+ WHERE team_id = $1 AND person_id = $2 AND is_deleted = falseLIMIT 2500) cappedORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id@@ -68,7 +68,7 @@ impl DistinctIdLookup for PostgresStorage {r#"SELECT distinct_id, versionFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = $2+ WHERE team_id = $1 AND person_id = $2 AND is_deleted = false"#,team_id as i32,person_id@@ -151,7 +151,7 @@ impl DistinctIdLookup for PostgresStorage {FROM (SELECT person_id, distinct_id, version, idFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = pid.id+ WHERE team_id = $1 AND person_id = pid.id AND is_deleted = falseLIMIT 2500) cappedORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.id@@ -171,7 +171,7 @@ impl DistinctIdLookup for PostgresStorage {r#"SELECT person_id, distinct_id, versionFROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = ANY($2)+ WHERE team_id = $1 AND person_id = ANY($2) AND is_deleted = false"#,team_id as i32,&chunkdiff --git a/rust/personhog-replica/src/storage/postgres/feature_flag.rs b/rust/personhog-replica/src/storage/postgres/feature_flag.rsindex e8bb00bc0bb7..da6230408476 100644--- a/rust/personhog-replica/src/storage/postgres/feature_flag.rs+++ b/rust/personhog-replica/src/storage/postgres/feature_flag.rs@@ -71,8 +71,8 @@ impl FeatureFlagStorage for PostgresStorage {FROM posthog_persondistinctid pLEFT JOIN posthog_featureflaghashkeyoverride existingON existing.person_id = p.person_id AND existing.team_id = p.team_id- WHERE p.team_id = $1 AND p.distinct_id = ANY($2)- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)+ WHERE p.team_id = $1 AND p.distinct_id = ANY($2) AND p.is_deleted = false+ AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)"#,team_id as i32,distinct_ids@@ -89,7 +89,7 @@ impl FeatureFlagStorage for PostgresStorage {FROM posthog_persondistinctid ppdLEFT JOIN posthog_featureflaghashkeyoverride fhkoON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id- WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2)+ WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2) AND ppd.is_deleted = false"#,team_id as i32,distinct_ids@@ -174,8 +174,8 @@ impl FeatureFlagStorage for PostgresStorage {SELECT $1, p.person_id, f.flag_key, $2FROM posthog_persondistinctid pCROSS JOIN UNNEST($4::text[]) AS f(flag_key)- WHERE p.team_id = $1 AND p.distinct_id = ANY($3)- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id)+ WHERE p.team_id = $1 AND p.distinct_id = ANY($3) AND p.is_deleted = false+ AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)ON CONFLICT DO NOTHING"#,team_id as i32,diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex f213090a68fe..67143a2a3ec0 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -48,7 +48,7 @@ impl PersonLookup for PostgresStorage {CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,last_seen_atFROM posthog_person- WHERE team_id = $1 AND id = $2+ WHERE team_id = $1 AND id = $2 AND is_deleted = false"#,team_id as i32,person_id@@ -82,7 +82,7 @@ impl PersonLookup for PostgresStorage {CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,last_seen_atFROM posthog_person- WHERE team_id = $1 AND uuid = $2+ WHERE team_id = $1 AND uuid = $2 AND is_deleted = false"#,team_id as i32,uuid@@ -139,7 +139,7 @@ impl PersonLookup for PostgresStorage {CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,last_seen_atFROM posthog_person- WHERE team_id = $1 AND id = ANY($2)+ WHERE team_id = $1 AND id = ANY($2) AND is_deleted = false"#,team_id as i32,&chunk,@@ -214,7 +214,7 @@ impl PersonLookup for PostgresStorage {CASE WHEN is_user_id IS NULL THEN NULL ELSE (is_user_id != 0) END as is_user_id,last_seen_atFROM posthog_person- WHERE team_id = $1 AND uuid = ANY($2)+ WHERE team_id = $1 AND uuid = ANY($2) AND is_deleted = false"#,team_id as i32,&chunk,@@ -275,6 +275,7 @@ impl PersonLookup for PostgresStorage {FROM posthog_person pINNER JOIN posthog_persondistinctid d ON p.id = d.person_id AND p.team_id = d.team_idWHERE p.team_id = $1 AND d.distinct_id = $2+ AND p.is_deleted = false AND d.is_deleted = falseLIMIT 1"#,team_id as i32,@@ -354,8 +355,10 @@ impl PersonLookup for PostgresStorage {FROM UNNEST($2::text[]) AS batch(distinct_id)INNER JOIN posthog_persondistinctid dON d.team_id = $1 AND d.distinct_id = batch.distinct_id+ AND d.is_deleted = falseINNER JOIN posthog_person pON p.id = d.person_id AND p.team_id = d.team_id+ AND p.is_deleted = false"#,team_id as i32,&chunk,@@ -642,6 +645,7 @@ impl PersonLookup for PostgresStorage {INNER JOIN posthog_persondistinctid d ON d.person_id = p.id AND d.team_id = p.team_idINNER JOIN UNNEST($1::integer[], $2::text[]) AS batch(team_id, distinct_id)ON d.team_id = batch.team_id AND d.distinct_id = batch.distinct_id+ WHERE p.is_deleted = false AND d.is_deleted = false"#,&team_ids,&distinct_ids,