: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): prefer user-defined distinct_id over anonymous one (#65197)
Thomas Obermüller6104f2783a0e
diff --git a/frontend/src/queries/nodes/DataTable/renderColumn.tsx b/frontend/src/queries/nodes/DataTable/renderColumn.tsxindex e0b50228b1fd..d2d57d920ccc 100644--- a/frontend/src/queries/nodes/DataTable/renderColumn.tsx+++ b/frontend/src/queries/nodes/DataTable/renderColumn.tsx@@ -18,6 +18,7 @@ import { formatCurrency } from 'lib/utils/currency'import { autoCaptureEventToDescription } from 'lib/utils/events'import { isURL } from 'lib/utils/url'import { GroupActorDisplay } from 'scenes/persons/GroupActorDisplay'+import { pickBestPersonDistinctId } from 'scenes/persons/person-utils'import { PersonDisplay, PersonDisplayProps } from 'scenes/persons/PersonDisplay'import { sessionColumnRenderers } from 'scenes/sessions/sessionColumnRenderers'import { urls } from 'scenes/urls'@@ -339,14 +340,15 @@ export function renderColumn(}if (isPersonsNode(query.source) && personRecord.distinct_ids) {- displayProps.href = urls.personByDistinctId(personRecord.distinct_ids[0])+ displayProps.href = urls.personByDistinctId(+ pickBestPersonDistinctId(personRecord.distinct_ids) ?? personRecord.distinct_ids[0]+ )}if (isActorsQuery(query.source) && value) {displayProps.person = value- displayProps.href = value.distinct_ids?.[0]- ? urls.personByDistinctId(value.distinct_ids[0])- : urls.personByUUID(value.id)+ const bestDistinctId = pickBestPersonDistinctId(value.distinct_ids)+ displayProps.href = bestDistinctId ? urls.personByDistinctId(bestDistinctId) : urls.personByUUID(value.id)}if (isTracesQuery(query.source) && value) {diff --git a/frontend/src/scenes/persons/PersonPreview.tsx b/frontend/src/scenes/persons/PersonPreview.tsxindex 3981e299a690..e13b4196a5c3 100644--- a/frontend/src/scenes/persons/PersonPreview.tsx+++ b/frontend/src/scenes/persons/PersonPreview.tsx@@ -19,7 +19,7 @@ import { ActivityTab, PropertyDefinitionType, PropertyFilterType, PropertyOperatimport { ComposeTicketButton } from 'products/conversations/frontend/components/ComposeTicket'-import { asDisplay } from './person-utils'+import { asDisplay, pickBestPersonDistinctId } from './person-utils'import { personLogic } from './personLogic'export type PersonPreviewProps = {@@ -78,7 +78,8 @@ function PersonPreviewInner(props: PersonPreviewProps): JSX.Element | null {}const display = asDisplay(person)- const url = urls.personByDistinctId(person?.distinct_ids[0])+ const bestDistinctId = pickBestPersonDistinctId(person?.distinct_ids)+ const url = urls.personByDistinctId(bestDistinctId ?? person?.distinct_ids[0])return (<div className="flex flex-col overflow-hidden max-h-80 max-w-160 gap-2">@@ -100,7 +101,7 @@ function PersonPreviewInner(props: PersonPreviewProps): JSX.Element | null {size="small"type="tertiary"iconOnly- distinctId={person?.distinct_ids?.[0]}+ distinctId={bestDistinctId}email={typeof person?.properties?.email === 'string' ? person.properties.email : undefined}onCompose={() => props.onClose?.()}/>diff --git a/frontend/src/scenes/persons/PersonScene.tsx b/frontend/src/scenes/persons/PersonScene.tsxindex 30cd4a644f3d..73bf52f225a7 100644--- a/frontend/src/scenes/persons/PersonScene.tsx+++ b/frontend/src/scenes/persons/PersonScene.tsx@@ -43,7 +43,7 @@ import { ComposeTicketButton } from 'products/conversations/frontend/components/import { FeedbackButton } from 'products/customer_analytics/frontend/components/FeedbackButton'import { MergeSplitPerson } from './MergeSplitPerson'-import { asDisplay } from './person-utils'+import { asDisplay, pickBestPersonDistinctId } from './person-utils'import { PersonCohorts } from './PersonCohorts'import { PersonLogsTab } from './PersonLogsTab'import PersonProfileCanvas from './PersonProfileCanvas'@@ -60,6 +60,9 @@ export const scene: SceneExport<PersonsLogicProps> = {}function PersonCaption({ person }: { person: PersonType }): JSX.Element {+ // Show the most human-readable distinct ID first; the rest fall into the "+N" menu.+ const primaryDistinctId = pickBestPersonDistinctId(person.distinct_ids) ?? person.distinct_ids[0]+ const otherDistinctIds = person.distinct_ids.filter((distinct_id) => distinct_id !== primaryDistinctId)return (<div className="flex flex-wrap items-center gap-2"><div className="flex deprecated-space-x-1">@@ -71,20 +74,20 @@ function PersonCaption({ person }: { person: PersonType }): JSX.Element {description="person distinct ID"style={{ justifyContent: 'flex-end' }}>- {person.distinct_ids[0]}+ {primaryDistinctId}</CopyToClipboardInline></span></div>- {person.distinct_ids.length > 1 && (+ {otherDistinctIds.length > 0 && (<LemonMenu- items={person.distinct_ids.slice(1).map((distinct_id: string) => ({+ items={otherDistinctIds.map((distinct_id: string) => ({label: distinct_id,sideIcon: <IconCopy className="text-primary-3000" />,onClick: () => copyToClipboard(distinct_id, 'distinct id'),}))}><LemonTag type="primary" className="inline-flex">- <span>+{person.distinct_ids.length - 1}</span>+ <span>+{otherDistinctIds.length}</span><IconChevronDown className="w-4 h-4" /></LemonTag></LemonMenu>@@ -246,7 +249,7 @@ export function PersonScene(): JSX.Element | null {<ComposeTicketButtonsize="small"type="secondary"- distinctId={person.distinct_ids[0]}+ distinctId={primaryDistinctId ?? person.distinct_ids[0]}email={typeof person.properties?.email === 'string' ? person.properties.email : undefined}/>{user?.is_staff && <OpenInAdminPanelButton />}diff --git a/frontend/src/scenes/persons/person-utils.test.ts b/frontend/src/scenes/persons/person-utils.test.tsindex 2fd57ffa828f..dfb1ac88b1f1 100644--- a/frontend/src/scenes/persons/person-utils.test.ts+++ b/frontend/src/scenes/persons/person-utils.test.ts@@ -9,6 +9,7 @@ import {coercePropertyValue,getPersonColorIndex,parsePersonFromHogQLRow,+ pickBestPersonDistinctId,scoreDistinctId,} from './person-utils'@@ -76,6 +77,12 @@ describe('the person header', () => {expectedLink: urls.personByDistinctId('a+dicey/@!'),name: 'with no ids',},+ {+ // Anonymous ID first, identified ID second — the link should use the identified one+ distinctIds: ['03b16e4c0b14ef-00000000000000-1633685d-13c680-17878af3ba9d1c', '[email protected]'],+ expectedLink: urls.personByDistinctId('[email protected]'),+ name: 'preferring an identified ID over an anonymous one',+ },]it.each(personLinksTestCases.map((testCase) => [testCase.name, testCase]))(@@ -288,3 +295,35 @@ describe('scoreDistinctId', () => {expect(scoreDistinctId(id)).toBe(expected)})})++describe('pickBestPersonDistinctId', () => {+ const anonId = '03b16e4c0b14ef-00000000000000-1633685d-13c680-17878af3ba9d1c'+ it.each([+ { distinctIds: undefined, expected: undefined, label: 'undefined returns undefined' },+ { distinctIds: [], expected: undefined, label: 'empty array returns undefined' },+ { distinctIds: ['only-one'], expected: 'only-one', label: 'single ID is returned as-is' },+ {+ distinctIds: [anonId, '[email protected]'],+ expected: '[email protected]',+ label: 'prefers an email over an anonymous ID regardless of position',+ },+ {+ distinctIds: [anonId, 'custom-123'],+ expected: 'custom-123',+ label: 'prefers a custom ID over an anonymous ID',+ },+ {+ distinctIds: ['custom-123', anonId, '[email protected]'],+ expected: '[email protected]',+ label: 'prefers an email over both custom and anonymous IDs',+ },+ ])('$label', ({ distinctIds, expected }) => {+ expect(pickBestPersonDistinctId(distinctIds)).toBe(expected)+ })++ it('does not mutate the input array', () => {+ const distinctIds = [anonId, '[email protected]']+ pickBestPersonDistinctId(distinctIds)+ expect(distinctIds).toEqual([anonId, '[email protected]'])+ })+})diff --git a/frontend/src/scenes/persons/person-utils.ts b/frontend/src/scenes/persons/person-utils.tsindex b0b2a6707723..d17700558ac4 100644--- a/frontend/src/scenes/persons/person-utils.ts+++ b/frontend/src/scenes/persons/person-utils.ts@@ -56,6 +56,22 @@ export function scoreDistinctId(id: string): number {return 1}+/**+ * Pick the most human-readable distinct ID for a person, preferring identified IDs (emails, custom+ * IDs) over auto-generated anonymous IDs. Returns `undefined` when there are no distinct IDs.+ *+ * Use this anywhere a single distinct ID must represent a person — profile/replay links,+ * copy-to-clipboard, the "IDs" caption — instead of blindly taking `distinct_ids[0]`. The order of+ * `distinct_ids` is not guaranteed to put the identified ID first (it varies by data source), so+ * `[0]` frequently surfaces the auto-generated anonymous ID even when a user-defined one exists.+ */+export function pickBestPersonDistinctId(distinctIds: string[] | null | undefined): string | undefined {+ if (!distinctIds?.length) {+ return undefined+ }+ return distinctIds.slice().sort((a, b) => scoreDistinctId(b) - scoreDistinctId(a))[0]+}+/*** Returns a human-friendly display name for a Person object.*@@ -94,9 +110,7 @@ export function asDisplay(const display: string | undefined = (customIdentifier ||person.distinct_id ||- (person.distinct_ids- ? person.distinct_ids.slice().sort((a, b) => scoreDistinctId(b) - scoreDistinctId(a))[0]- : undefined)+ pickBestPersonDistinctId(person.distinct_ids))?.trim()// Force return of the UUID truncated to 22 characters (unless maxLength is specified)@@ -136,13 +150,14 @@ export const asLink = (person?: PersonPropType | null): string | undefined => {if (!person?.properties) {return undefined}- return person.distinct_id- ? urls.personByDistinctId(person.distinct_id)- : person.distinct_ids?.length- ? urls.personByDistinctId(person.distinct_ids[0])- : person.id- ? urls.personByUUID(person.id)- : undefined+ if (person.distinct_id) {+ return urls.personByDistinctId(person.distinct_id)+ }+ const bestDistinctId = pickBestPersonDistinctId(person.distinct_ids)+ if (bestDistinctId) {+ return urls.personByDistinctId(bestDistinctId)+ }+ return person.id ? urls.personByUUID(person.id) : undefined}/**diff --git a/frontend/src/scenes/persons/personsLogic.tsx b/frontend/src/scenes/persons/personsLogic.tsxindex 296c7ea28223..c03b1d97067d 100644--- a/frontend/src/scenes/persons/personsLogic.tsx+++ b/frontend/src/scenes/persons/personsLogic.tsx@@ -41,7 +41,7 @@ import {coercePropertyValue,getHogqlQueryStringForPersonId,parsePersonFromHogQLRow,- scoreDistinctId,+ pickBestPersonDistinctId,} from './person-utils'import type { personsLogicType } from './personsLogicType'@@ -415,12 +415,7 @@ export const personsLogic = kea<personsLogicType>([feedEnabled: [(s) => [s.featureFlags], (featureFlags) => !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS]],primaryDistinctId: [(s) => [s.person],- (person): string | null => {- if (!person?.distinct_ids.length) {- return null- }- return person.distinct_ids.slice().sort((a, b) => scoreDistinctId(b) - scoreDistinctId(a))[0]- },+ (person): string | null => pickBestPersonDistinctId(person?.distinct_ids) ?? null,],eventsQueryIsDirty: [(s) => [s.eventsQuery, s.person],diff --git a/frontend/src/scenes/retention/RetentionModal.tsx b/frontend/src/scenes/retention/RetentionModal.tsxindex 34b49966b1bc..2fd5d29d131b 100644--- a/frontend/src/scenes/retention/RetentionModal.tsx+++ b/frontend/src/scenes/retention/RetentionModal.tsx@@ -13,7 +13,7 @@ import { percentage } from 'lib/utils/numbers'import { capitalizeFirstLetter } from 'lib/utils/strings'import { insightLogic } from 'scenes/insights/insightLogic'import { groupDisplayId } from 'scenes/persons/GroupActorDisplay'-import { asDisplay } from 'scenes/persons/person-utils'+import { asDisplay, pickBestPersonDistinctId } from 'scenes/persons/person-utils'import { RetentionTableAppearanceType } from 'scenes/retention/types'import { MissingPersonsAlert } from 'scenes/trends/persons-modal/PersonsModal'import { SaveCohortModal } from 'scenes/trends/persons-modal/SaveCohortModal'@@ -234,7 +234,9 @@ export function RetentionModal(): JSX.Element | null {<LemonButtonsize="small"to={urls.personByDistinctId(- personAppearances.person.distinct_ids[0]+ pickBestPersonDistinctId(+ personAppearances.person.distinct_ids+ ) ?? personAppearances.person.distinct_ids[0])}data-attr="retention-person-link">diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsxindex f783dd165aab..a52c91bad4c5 100644--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.tsx@@ -35,7 +35,7 @@ import { capitalizeFirstLetter, midEllipsis, pluralize } from 'lib/utils/stringsimport { InsightErrorState, InsightValidationError } from 'scenes/insights/EmptyStates'import { isOtherBreakdown } from 'scenes/insights/utils'import { GroupActorDisplay, groupDisplayId } from 'scenes/persons/GroupActorDisplay'-import { asDisplay } from 'scenes/persons/person-utils'+import { asDisplay, pickBestPersonDistinctId } from 'scenes/persons/person-utils'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { teamLogic } from 'scenes/teamLogic'@@ -396,6 +396,9 @@ export function ActorRow({ actor, propertiesTimelineFilter }: ActorRowProps): JS: isSession && actor.person? asDisplay(actor.person): asDisplay(actor)+ // The most human-readable distinct ID, for the person row's copyable subtitle+ const bestDistinctId =+ !isGroupType(actor) && !isSessionType(actor) ? pickBestPersonDistinctId(actor.distinct_ids) : undefinedconst onOpenRecordingClick = (): void => {if (!actor.matched_recordings) {@@ -435,14 +438,14 @@ export function ActorRow({ actor, propertiesTimelineFilter }: ActorRowProps): JS<div className="font-bold flex items-start"><PersonDisplay person={actor} withIcon={false} /></div>- {actor.distinct_ids?.[0] && (+ {bestDistinctId && (<CopyToClipboardInline- explicitValue={actor.distinct_ids[0]}+ explicitValue={bestDistinctId}iconStyle={{ color: 'var(--color-accent)' }}iconPosition="end"className="text-xs text-secondary">- {midEllipsis(actor.distinct_ids[0], 32)}+ {midEllipsis(bestDistinctId, 32)}</CopyToClipboardInline>)}</>diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.pyindex 0370af59ed60..923a7c3688e7 100644--- a/posthog/hogql_queries/actor_strategies.py+++ b/posthog/hogql_queries/actor_strategies.py@@ -27,6 +27,7 @@ from posthog.models.user import Userfrom posthog.person_db_router import PERSONS_DB_FOR_READfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_name+from posthog.utils import is_anonymous_idlogger = structlog.get_logger(__name__)@@ -81,21 +82,32 @@ class PersonStrategy(ActorStrategy):from posthog.personhog_client.client import get_personhog_clientclient = get_personhog_client()+ result: Optional[dict[str, dict]] = Noneif client is not None:try:result = self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending, limit_per_person)PERSONHOG_ROUTING_TOTAL.labels(operation="get_actors", source="personhog", client_name=get_client_name()).inc()- return resultexcept Exception:PERSONHOG_ROUTING_ERRORS_TOTAL.labels(operation="get_actors", source="personhog", error_type="grpc_error", client_name=get_client_name()).inc()logger.warning("personhog_get_actors_failure", team_id=self.team.pk, exc_info=True)- PERSONHOG_ROUTING_TOTAL.labels(operation="get_actors", source="raw_sql", client_name=get_client_name()).inc()- return self._get_actors_via_raw_sql(actor_ids, sort_by_created_at_descending)+ if result is None:+ PERSONHOG_ROUTING_TOTAL.labels(+ operation="get_actors", source="raw_sql", client_name=get_client_name()+ ).inc()+ result = self._get_actors_via_raw_sql(actor_ids, sort_by_created_at_descending)++ # Surface identified (non-anonymous) distinct IDs first so consumers that read distinct_ids[0]+ # (person links, CSV exports) get the user-defined ID rather than an auto-generated anonymous one.+ # Mirrors PersonSerializer.to_representation, which sorts the same way for the persons API.+ for person in result.values():+ person["distinct_ids"] = sorted(person["distinct_ids"], key=is_anonymous_id)++ return resultdef _get_actors_via_personhog(self,diff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.pyindex 8d02c5fa1fc6..3e46412d6d14 100644--- a/posthog/hogql_queries/test/test_actor_strategies_personhog.py+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py@@ -59,6 +59,24 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):entry = result[str(person.uuid)]assert set(entry["distinct_ids"]) == {"did-a", "did-b", "did-c"}+ def test_distinct_ids_prefer_identified_over_anonymous(self):+ # The anonymous-looking ID is seeded first, but the identified one must come first in the+ # result so consumers reading distinct_ids[0] (person links, CSV exports) get the+ # human-readable ID rather than the auto-generated anonymous one.+ anonymous_id = "0190f8e1-1234-7abc-89de-f0123456789a"+ person = self._seed_person(+ team=self.team,+ distinct_ids=[anonymous_id, "[email protected]"],+ properties={},+ )++ strategy = _make_strategy(self.team)+ result = strategy.get_actors([str(person.uuid)])++ entry = result[str(person.uuid)]+ assert entry["distinct_ids"][0] == "[email protected]"+ assert set(entry["distinct_ids"]) == {anonymous_id, "[email protected]"}+def test_multiple_persons(self):p1 = self._seed_person(team=self.team, distinct_ids=["u1"], properties={"n": "1"})p2 = self._seed_person(team=self.team, distinct_ids=["u2"], properties={"n": "2"})