:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): keep identified distinct_ids under per-person fetch limits (#73083)
Thomas Obermüller0cb478a87a15
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsxindex b3a0877de4ea..2f52a94c2a07 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx@@ -3,6 +3,7 @@ import { LemonButton, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { pluralize } from 'lib/utils/strings'+import { pickBestPersonDistinctId } from 'scenes/persons/person-utils'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { urls } from 'scenes/urls'@@ -28,7 +29,7 @@ const recordingsUrlForPerson = (distinctId: string): string =>`${urls.personByDistinctId(distinctId)}#activeTab=${PersonsTabType.SESSION_RECORDINGS}`export const LivePersonDrillDownRow = ({ person, recordingCount }: LivePersonDrillDownRowProps): JSX.Element => {- const distinctId = person.distinct_ids?.[0]+ const distinctId = pickBestPersonDistinctId(person.distinct_ids)const secondary = pickSecondaryProperty(person)const href = distinctId ? urls.personByDistinctId(distinctId) : undefineddiff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.pyindex e178d01ce4e8..1e8da3706b8a 100644--- a/posthog/hogql_queries/test/test_actor_strategies_personhog.py+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py@@ -71,6 +71,24 @@ class TestPersonStrategyGetActors(BaseTest):assert entry["distinct_ids"][0] == "[email protected]"assert set(entry["distinct_ids"]) == {anonymous_id, "[email protected]"}+ def test_distinct_id_limit_keeps_identified(self):+ # The identified ID is seeded after more anonymous IDs than the fetch limit; the+ # fetch must order identified-first before truncating, or the identified ID would+ # be dropped before the post-fetch sort ever sees it.+ anonymous_ids = [f"0190f8e1-1234-7abc-89de-f012345678{suffix}" for suffix in ("aa", "ab", "ac")]+ person = create_person(+ team=self.team,+ distinct_ids=[*anonymous_ids, "[email protected]"],+ properties={},+ )++ strategy = _make_strategy(self.team)+ result = strategy.get_actors([str(person.uuid)], limit_per_person=2)++ entry = result[str(person.uuid)]+ assert len(entry["distinct_ids"]) == 2+ assert entry["distinct_ids"][0] == "[email protected]"+def test_multiple_persons(self):p1 = create_person(team=self.team, distinct_ids=["u1"], properties={"n": "1"})p2 = create_person(team=self.team, distinct_ids=["u2"], properties={"n": "2"})diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 5f8f674c8dee..0a5e4a52a3a4 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -32,6 +32,7 @@ from posthog.personhog_client.proto.generated.personhog.types.v1 import (group_pb2,person_pb2,)+from posthog.utils import is_anonymous_id@dataclass@@ -41,6 +42,14 @@ class _Call:response: Any = None+def _order_identified_first(+ dids: list[person_pb2.DistinctIdWithVersion],+) -> list[person_pb2.DistinctIdWithVersion]:+ """Mirror the server-side ordering of limited distinct_id fetches (personhog-replica+ orders anonymous-shaped ids last before applying LIMIT, so identified ids survive)."""+ return sorted(dids, key=lambda d: is_anonymous_id(d.distinct_id))++class FakePersonHogClient:"""In-memory fake that implements the same interface as PersonHogClient.@@ -243,7 +252,7 @@ class FakePersonHogClient:dids = self._distinct_ids.get((request.team_id, request.person_id), [])limit = request.limit if request.HasField("limit") and request.limit > 0 else Noneif limit is not None:- dids = dids[:limit]+ dids = _order_identified_first(dids)[:limit]return person_pb2.GetDistinctIdsForPersonResponse(distinct_ids=dids)def get_distinct_ids_for_persons(@@ -257,7 +266,7 @@ class FakePersonHogClient:for pid in request.person_ids:dids = self._distinct_ids.get((request.team_id, pid), [])if limit is not None:- dids = dids[:limit]+ dids = _order_identified_first(dids)[:limit]results.append(person_pb2.PersonDistinctIds(person_id=pid, distinct_ids=dids))return person_pb2.GetDistinctIdsForPersonsResponse(person_distinct_ids=results)diff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.pyindex 5c7b05e0aa04..a84f9a50f7dd 100644--- a/posthog/personhog_client/test_fake_client.py+++ b/posthog/personhog_client/test_fake_client.py@@ -60,6 +60,22 @@ class TestFakePersonHogClientPersons:assert resp.person_distinct_ids[0].person_id == 10assert len(resp.person_distinct_ids[0].distinct_ids) == 2+ def test_limited_fetch_orders_identified_first(self):+ # Mirrors personhog-replica: the anonymous-shaped id is seeded first, but a limited+ # fetch must order identified ids first so they survive the limit.+ anon = "0190f8e1-1234-7abc-89de-f0123456789a"+ self.client.add_person(team_id=1, person_id=30, uuid="ghi-789", distinct_ids=[anon, "[email protected]"])++ single = self.client.get_distinct_ids_for_person(+ person_pb2.GetDistinctIdsForPersonRequest(team_id=1, person_id=30, limit=1)+ )+ bulk = self.client.get_distinct_ids_for_persons(+ person_pb2.GetDistinctIdsForPersonsRequest(team_id=1, person_ids=[30], limit_per_person=1)+ )++ assert [d.distinct_id for d in single.distinct_ids] == ["[email protected]"]+ assert [d.distinct_id for d in bulk.person_distinct_ids[0].distinct_ids] == ["[email protected]"]+def test_get_persons_by_distinct_ids_in_team(self):resp = self.client.get_persons_by_distinct_ids_in_team(person_pb2.GetPersonsByDistinctIdsInTeamRequest(diff --git a/rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.json b/rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.jsonnew file mode 100644index 000000000000..43da798e7a9a--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908.json@@ -0,0 +1,30 @@+{+ "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 ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "distinct_id",+ "type_info": "Varchar"+ },+ {+ "ordinal": 1,+ "name": "version",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "Int8",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "7d3846e685cae3ab6bffbe9aaca15662603efc3abf27ae0347c1b6fd1220b908"+}diff --git a/rust/personhog-replica/.sqlx/query-963d58f461b9acaa7a993b9463892051fea8c20cf9f1c72de70040c4055e6b7d.json b/rust/personhog-replica/.sqlx/query-963d58f461b9acaa7a993b9463892051fea8c20cf9f1c72de70040c4055e6b7d.jsondeleted file mode 100644index 7fa828ee3902..000000000000--- a/rust/personhog-replica/.sqlx/query-963d58f461b9acaa7a993b9463892051fea8c20cf9f1c72de70040c4055e6b7d.json+++ /dev/null@@ -1,30 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = $2\n LIMIT $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "distinct_id",- "type_info": "Varchar"- },- {- "ordinal": 1,- "name": "version",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Int4",- "Int8",- "Int8"- ]- },- "nullable": [- false,- true- ]- },- "hash": "963d58f461b9acaa7a993b9463892051fea8c20cf9f1c72de70040c4055e6b7d"-}diff --git a/rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.json b/rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.jsonsimilarity index 51%rename from rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.jsonrename to rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.jsonindex 4214392f506a..511ce93eadd5 100644--- a/rust/personhog-replica/.sqlx/query-212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514.json+++ b/rust/personhog-replica/.sqlx/query-d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2.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 person_id, distinct_id, version\n FROM posthog_persondistinctid\n WHERE team_id = $1 AND person_id = pid.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\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": "212a34161c87b00c70419dd617043dab766215f7d8b180299dad3e6b1bd20514"+ "hash": "d10f8f0a3bbca22894b10fe78378c28efbb8e8c4ad7c76ae92954005afe222d2"}diff --git a/rust/personhog-replica/src/storage/postgres/distinct_id.rs b/rust/personhog-replica/src/storage/postgres/distinct_id.rsindex 43cbb4ffd6d7..ee250c7cd48a 100644--- a/rust/personhog-replica/src/storage/postgres/distinct_id.rs+++ b/rust/personhog-replica/src/storage/postgres/distinct_id.rs@@ -36,14 +36,23 @@ impl DistinctIdLookup for PostgresStorage {let pool = self.pool_for_consistency(consistency);let mut conn = PostgresStorage::acquire_timed(pool, pool_label).await?;+ // Identified (non-anonymous) distinct_ids must survive the LIMIT, so consumers that+ // read the first id get the user-defined one. The regex mirrors ANONYMOUS_REGEX in+ // posthog/utils.py (keep in sync). The inner LIMIT bounds the scan for pathological+ // persons with enormous distinct_id sets; beyond it the selection is best-effort.let rows = match limit {Some(l) => {sqlx::query_as!(DistinctIdWithVersion,r#"- SELECT distinct_id, version- FROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = $2+ SELECT capped.distinct_id, capped.version+ FROM (+ SELECT distinct_id, version, id+ FROM posthog_persondistinctid+ WHERE team_id = $1 AND person_id = $2+ LIMIT 2500+ ) capped+ ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.idLIMIT $3"#,team_id as i32,@@ -127,6 +136,9 @@ impl DistinctIdLookup for PostgresStorage {let pool = pool.clone();async move {let mut conn = PostgresStorage::acquire_timed(&pool, pool_label).await?;+ // Same ordering contract as get_distinct_ids_for_person: identified ids+ // survive the per-person LIMIT (regex mirrors ANONYMOUS_REGEX in+ // posthog/utils.py), with the scan capped for pathological persons.let rows = match limit_per_person {Some(l) => {sqlx::query_as!(@@ -135,9 +147,14 @@ impl DistinctIdLookup for PostgresStorage {SELECT l.person_id, l.distinct_id, l.versionFROM UNNEST($2::bigint[]) AS pid(id)CROSS JOIN LATERAL (- SELECT person_id, distinct_id, version- FROM posthog_persondistinctid- WHERE team_id = $1 AND person_id = pid.id+ SELECT capped.person_id, capped.distinct_id, capped.version+ FROM (+ SELECT person_id, distinct_id, version, id+ FROM posthog_persondistinctid+ WHERE team_id = $1 AND person_id = pid.id+ LIMIT 2500+ ) capped+ ORDER BY (capped.distinct_id ~ '^([a-z0-9]+-){4}[a-z0-9]+$'), capped.idLIMIT $3) l"#,diff --git a/rust/personhog-replica/tests/service_tests.rs b/rust/personhog-replica/tests/service_tests.rsindex f76a714a0b54..4e6c4ce7a313 100644--- a/rust/personhog-replica/tests/service_tests.rs+++ b/rust/personhog-replica/tests/service_tests.rs@@ -669,6 +669,67 @@ async fn test_get_distinct_ids_for_persons_with_limit(ctx.cleanup().await.ok();}+// The anonymous-shaped id is inserted first, so insertion order alone would return it;+// the limited queries must order identified ids first so they survive the LIMIT.+#[tokio::test]+async fn test_get_distinct_ids_for_person_limit_keeps_identified() {+ let ctx = ServiceTestContext::new().await;+ let person = ctx+ .insert_person("0190f8e1-1234-7abc-89de-f0123456789a", None)+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(person.id, "[email protected]")+ .await+ .unwrap();++ let response = ctx+ .service+ .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {+ team_id: ctx.team_id,+ person_id: person.id,+ read_options: None,+ limit: Some(1),+ }))+ .await+ .expect("RPC failed");++ let distinct_ids = response.into_inner().distinct_ids;+ assert_eq!(distinct_ids.len(), 1);+ assert_eq!(distinct_ids[0].distinct_id, "[email protected]");++ ctx.cleanup().await.ok();+}++#[tokio::test]+async fn test_get_distinct_ids_for_persons_limit_keeps_identified() {+ let ctx = ServiceTestContext::new().await;+ let person = ctx+ .insert_person("0190f8e1-1234-7abc-89de-f0123456789a", None)+ .await+ .unwrap();+ ctx.add_distinct_id_to_person(person.id, "[email protected]")+ .await+ .unwrap();++ let response = ctx+ .service+ .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {+ team_id: ctx.team_id,+ person_ids: vec![person.id],+ read_options: None,+ limit_per_person: Some(1),+ }))+ .await+ .expect("RPC failed");++ let results = response.into_inner().person_distinct_ids;+ assert_eq!(results.len(), 1);+ assert_eq!(results[0].distinct_ids.len(), 1);+ assert_eq!(results[0].distinct_ids[0].distinct_id, "[email protected]");++ ctx.cleanup().await.ok();+}+// ============================================================// Additional group tests// ============================================================