: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(logs): link person logs via built-in distinct-id conventions (#76007)
Daniel Viscaddae2ab5bb13
diff --git a/frontend/src/scenes/persons/PersonLogsTab.tsx b/frontend/src/scenes/persons/PersonLogsTab.tsxindex 81ec01b119b1..5c2048f96382 100644--- a/frontend/src/scenes/persons/PersonLogsTab.tsx+++ b/frontend/src/scenes/persons/PersonLogsTab.tsx@@ -14,7 +14,8 @@ import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'produc// (LemonTabs renders just the active tab's content), so `logsConfigLogic` only fetches// the team's `logs_distinct_id_attribute_keys` on demand rather than on every team load.// The config only drives the caption here — the query is scoped via `personId`, which the-// backend expands to the person's distinct ids and matches against the configured keys.+// backend expands to the person's distinct ids and matches against the configured keys plus+// the built-in distinct-id conventions (the same keys the logs UI links as a person).export function PersonLogsTab({ person }: { person: PersonType }): JSX.Element {const { logsConfig } = useValues(logsConfigLogic)const distinctIdAttributeKeys =@@ -31,7 +32,7 @@ export function PersonLogsTab({ person }: { person: PersonType }): JSX.Element {<code>{key}</code></span>))}{' '}- log {distinctIdAttributeKeys.length === 1 ? 'attribute' : 'attributes'}.+ and other common distinct ID attributes.</span><LemonButtonsize="xsmall"diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.pyindex 3eff55849bd6..6f68029c2674 100644--- a/products/logs/backend/logs_query_runner.py+++ b/products/logs/backend/logs_query_runner.py@@ -33,7 +33,11 @@ from posthog.models.person.util import get_person_by_pk_or_uuidfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom products.logs.backend.column_expressions import canonical_key, column_to_expr-from products.logs.backend.models import DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, TeamLogsConfig+from products.logs.backend.models import (+ DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS,+ DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS,+ TeamLogsConfig,+)if TYPE_CHECKING:from posthog.models import Team, User@@ -487,26 +491,48 @@ class LogsFilterBuilder:# treats an empty value list as always-true, which would return every log.return ast.Constant(value=False)config = TeamLogsConfig.objects.filter(team=self.team).first()- attribute_keys = (+ configured_keys = (config.logs_distinct_id_attribute_keys if config else None) or DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS- # Force the __str map: attributes_map_str holds every attribute value (stringified),- # while attributes_map_float only exists for numeric values — all-numeric distinct ids- # must not route there via the usual value-type detection.- key_exprs = [- property_to_expr(- LogPropertyFilter(- key=f"{attribute_key}__str",- operator=PropertyOperator.EXACT,- type=LogPropertyFilterType.LOG_ATTRIBUTE,- value=list(distinct_ids),- ),- team=self.team,+ # Also scope on the built-in convention keys the logs UI renders as clickable person+ # links (isDistinctIdKey in products/logs/frontend/utils.tsx), so a log the UI shows as+ # belonging to a person appears on their Logs tab even when the team hasn't configured+ # that key. Deduped, configured keys first.+ attribute_keys = list(dict.fromkeys([*configured_keys, *DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS]))+ distinct_id_values = list(distinct_ids)+ key_exprs: list[ast.Expr] = []+ for attribute_key in attribute_keys:+ # Log attribute: force the __str map. attributes_map_str holds every attribute value+ # (stringified), while attributes_map_float only exists for numeric values — all-numeric+ # distinct ids must not route there via the usual value-type detection.+ key_exprs.append(+ property_to_expr(+ LogPropertyFilter(+ key=f"{attribute_key}__str",+ operator=PropertyOperator.EXACT,+ type=LogPropertyFilterType.LOG_ATTRIBUTE,+ value=distinct_id_values,+ ),+ team=self.team,+ ))- for attribute_key in attribute_keys- ]- # A log links to the person when any configured attribute key holds one of their- # distinct ids — mirrors the OR the person tab previously pinned client-side.+ # Resource attribute: the logs UI links these keys under resource_attributes too+ # (LogAttributes.tsx renders the person link regardless of attribute vs+ # resource_attribute), so scope on both. resource_attributes is a plain string map on+ # the row — no typed __str/__float split — so match the key directly.+ key_exprs.append(+ property_to_expr(+ LogPropertyFilter(+ key=attribute_key,+ operator=PropertyOperator.EXACT,+ type=LogPropertyFilterType.LOG_RESOURCE_ATTRIBUTE,+ value=distinct_id_values,+ ),+ team=self.team,+ )+ )+ # A log links to the person when any of these attribute keys — in either the log+ # attributes or the resource attributes — holds one of their distinct ids.return key_exprs[0] if len(key_exprs) == 1 else ast.Or(exprs=key_exprs)def resource_filter(self, *, existing_filters):diff --git a/products/logs/backend/models.py b/products/logs/backend/models.pyindex 5f8579732146..3478d972f6ef 100644--- a/products/logs/backend/models.py+++ b/products/logs/backend/models.py@@ -34,6 +34,26 @@ def default_logs_distinct_id_attribute_keys() -> list[str]:return list(DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS)+# Built-in distinct-id attribute key conventions. Mirror of the frontend DISTINCT_ID_KEYS in+# products/logs/frontend/utils.tsx — keep the two in sync. The logs UI renders a value under+# any of these keys as a clickable person link (isDistinctIdKey), so the person Logs tab scopes+# on them too (on top of a team's configured keys), otherwise a log shown as belonging to a+# person would not appear on that person's tab. Literal keys only: the frontend additionally+# matches dot-suffixed variants (e.g. `span.distinct_id`), which an exact attribute filter can't+# express.+DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS = [+ "distinct.id",+ "distinct_id",+ "distinctId",+ "distinctID",+ "posthogDistinctId",+ "posthogDistinctID",+ "posthog_distinct_id",+ "posthog.distinct.id",+ "posthog.distinct_id",+]++# Default log attribute keys whose values hold the PostHog session ID. `posthogSessionId`# is the key the posthog-js / posthog-react-native SDKs auto-attach to every log they# emit (see https://posthog.com/docs/logs/link-session-replay). Ordered: detection checksdiff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.pyindex fc1886f05ac4..422abfca4698 100644--- a/products/logs/backend/test/test_logs_query_runner.py+++ b/products/logs/backend/test/test_logs_query_runner.py@@ -1203,8 +1203,10 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):{payload}""")- def _log_row(self, distinct_id_value: str, attribute_key: str = "posthogDistinctId") -> dict:- return {+ def _log_row(+ self, distinct_id_value: str, attribute_key: str = "posthogDistinctId", *, resource: bool = False+ ) -> dict:+ row: dict = {"uuid": str(uuid4()),"timestamp": "2026-03-01 10:00:00.000000","observed_timestamp": "2026-03-01 10:00:01.000000",@@ -1213,8 +1215,14 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):"severity_number": 9,"service_name": "person-id-test-svc","resource_attributes": {"service.name": "person-id-test-svc"},- "attributes_map_str": {f"{attribute_key}__str": distinct_id_value},+ "attributes_map_str": {},}+ # Place the distinct id under a resource attribute or a log attribute.+ if resource:+ row["resource_attributes"][attribute_key] = distinct_id_value+ else:+ row["attributes_map_str"][f"{attribute_key}__str"] = distinct_id_value+ return rowdef _person_query(self, person_id: str) -> LogsQuery:return LogsQuery(@@ -1265,23 +1273,24 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):@parameterized.expand([- ("single_key", ["user.id"], {"user.id"}),- ("multiple_keys", ["user.id", "posthogDistinctId"], {"user.id", "posthogDistinctId"}),+ ("single_key", ["team_ref"], {"team_ref"}),+ ("multiple_keys", ["team_ref", "account_ref"], {"team_ref", "account_ref"}),])def test_person_id_respects_configured_attribute_keys(self, _name: str, configured_keys: list[str], matching_keys: set[str]):# Matching only the first configured key (or the legacy singular column) would- # silently drop logs linked via the other keys.+ # silently drop logs linked via the other keys. Custom keys (not built-in+ # conventions) isolate configured-key handling from the convention fallback.TeamLogsConfig.objects.update_or_create(team=self.team, defaults={"logs_distinct_id_attribute_keys": configured_keys})person = create_person(team=self.team, distinct_ids=["person-id-test-cfg"])self._insert_logs([- self._log_row("person-id-test-cfg", attribute_key="user.id"),- self._log_row("person-id-test-cfg", attribute_key="posthogDistinctId"),+ self._log_row("person-id-test-cfg", attribute_key="team_ref"),+ self._log_row("person-id-test-cfg", attribute_key="account_ref"),])@@ -1290,6 +1299,39 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):self.assertEqual({key for r in results for key in r["attributes"]}, matching_keys)self.assertEqual(len(results), len(matching_keys))+ def test_person_id_matches_builtin_convention_keys(self):+ # A log stamped under a built-in distinct-id convention key (e.g. `distinct_id`) is+ # rendered as a clickable person link in the logs UI (isDistinctIdKey), so it must also+ # appear on that person's Logs tab even when the team never configured that key. Here+ # only the default `posthogDistinctId` is configured; `distinct_id` is convention-only.+ person = create_person(team=self.team, distinct_ids=["person-id-test-conv"])+ self._insert_logs(+ [+ self._log_row("person-id-test-conv", attribute_key="distinct_id"),+ self._log_row("person-id-test-conv", attribute_key="posthogDistinctId"),+ ]+ )++ results = self._run(str(person.uuid))++ self.assertEqual(+ {key for r in results for key in r["attributes"]},+ {"distinct_id", "posthogDistinctId"},+ )++ def test_person_id_matches_distinct_id_in_resource_attributes(self):+ # The logs UI renders a distinct-id convention key as a clickable person link whether the+ # value sits in attributes or resource_attributes (LogAttributes.tsx), so a distinct id+ # under resource_attributes must link the log to the person's tab too — not just log+ # attributes.+ person = create_person(team=self.team, distinct_ids=["person-id-test-res"])+ self._insert_logs([self._log_row("person-id-test-res", attribute_key="distinct_id", resource=True)])++ results = self._run(str(person.uuid))++ self.assertEqual(len(results), 1)+ self.assertEqual(results[0]["resource_attributes"]["distinct_id"], "person-id-test-res")+def test_person_id_filter_targets_string_attribute_map_for_numeric_ids(self):# All-numeric distinct ids must not route to the float attribute map — only the# string map is guaranteed to hold every attribute value.diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsxindex 8050dc8002a0..cbda6f9b9a23 100644--- a/products/logs/frontend/utils.tsx+++ b/products/logs/frontend/utils.tsx@@ -69,6 +69,9 @@ export function getFiltersSummaryLines(filters: Record<string, any>): FiltersSumreturn lines}+// Mirror of DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS in products/logs/backend/models.py — keep the+// two in sync. Values under these keys render as clickable person links here, and the person+// Logs tab scopes on them server-side so those logs appear on the person's tab.const DISTINCT_ID_KEYS = ['distinct.id','distinct_id',