Skip to content

: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.

fix(logs): scope person profile logs tab server-side via personId (#67714)

Christiaan Hendriksend0be311d5021
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 20619ce45c7a..8be2a31c7013 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28710,6 +28710,10 @@
"orderBy": {
"$ref": "#/definitions/LogsOrderBy"
},
+ "personId": {
+ "description": "Show logs for a given person",
+ "type": "string"
+ },
"resourceFingerprint": {
"type": "string"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index afa73f337587..b44cf63e5c60 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3520,6 +3520,8 @@ export interface LogsQuery extends DataNode<LogsQueryResponse> {
resourceFingerprint?: string
/** Omit the per-log `attributes` and `resource_attributes` maps from results to keep payloads compact */
excludeAttributes?: boolean
+ /** Show logs for a given person */
+ personId?: string
/**
* Custom column expressions evaluated per log row. Each entry is either a source-prefixed
* shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar
diff --git a/frontend/src/scenes/persons/PersonLogsTab.tsx b/frontend/src/scenes/persons/PersonLogsTab.tsx
index ff4fc8132b31..81ec01b119b1 100644
--- a/frontend/src/scenes/persons/PersonLogsTab.tsx
+++ b/frontend/src/scenes/persons/PersonLogsTab.tsx
@@ -1,19 +1,11 @@
import { useValues } from 'kea'
-import { useMemo } from 'react'
import { IconGear } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
-import {
- FilterLogicalOperator,
- LogPropertyFilter,
- PersonType,
- PropertyFilterType,
- PropertyOperator,
- UniversalFiltersGroup,
-} from '~/types'
+import { PersonType } from '~/types'
import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'
import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
@@ -21,30 +13,13 @@ import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'produc
// Renders the Logs tab on the person profile. Mounted only when the tab is active
// (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.
-// While the config loads, falls back to the default keys — accurate for the vast majority
-// of teams; non-default teams briefly see the wrong filter then resolve to the override.
+// 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.
export function PersonLogsTab({ person }: { person: PersonType }): JSX.Element {
const { logsConfig } = useValues(logsConfigLogic)
const distinctIdAttributeKeys =
logsConfig?.logs_distinct_id_attribute_keys ?? DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS
- const pinnedFilters = useMemo((): UniversalFiltersGroup => {
- const keyFilters = distinctIdAttributeKeys.map(
- (key): LogPropertyFilter => ({
- key,
- type: PropertyFilterType.LogAttribute,
- operator: PropertyOperator.Exact,
- value: person.distinct_ids,
- })
- )
- return {
- type: FilterLogicalOperator.And,
- // A single key pins a plain filter; multiple keys pin a nested OR group so a
- // log matches when any configured attribute holds one of the distinct IDs.
- values: keyFilters.length === 1 ? keyFilters : [{ type: FilterLogicalOperator.Or, values: keyFilters }],
- }
- }, [distinctIdAttributeKeys, person.distinct_ids])
-
return (
<div className="flex flex-col h-[calc(100vh-16rem)] min-h-[25rem]">
<p className="text-muted text-xs mb-2 flex items-center gap-1 flex-wrap">
@@ -67,7 +42,7 @@ export function PersonLogsTab({ person }: { person: PersonType }): JSX.Element {
</p>
<LogsViewer
id={`person-${person.uuid ?? person.id}`}
- pinnedFilters={pinnedFilters}
+ personId={String(person.uuid ?? person.id)}
showFullScreenButton={false}
showSavedViewsButton={false}
/>
diff --git a/posthog/schema.py b/posthog/schema.py
index babc8ee847f5..46e44a6b16f9 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -24919,6 +24919,7 @@ class LogsQuery(BaseModel):
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
offset: int | None = None
orderBy: LogsOrderBy | None = None
+ personId: str | None = Field(default=None, description="Show logs for a given person")
resourceFingerprint: str | None = None
response: LogsQueryResponse | None = None
searchTerm: str | None = None
diff --git a/products/logs/backend/log_facet_values_query_runner.py b/products/logs/backend/log_facet_values_query_runner.py
index f9a4cd87b07b..839a495e5bf3 100644
--- a/products/logs/backend/log_facet_values_query_runner.py
+++ b/products/logs/backend/log_facet_values_query_runner.py
@@ -169,8 +169,8 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQue
# Served from the pre-aggregated log_attributes rollup (sum(attribute_count)) rather than
# grouping the logs Map column, which reads the whole resource_attributes column and blows
# past the read cap at scale. The rollup carries severity_text and service_name, so severity
- # levels, service_name and other resource-attribute filters re-scope the counts; body-search
- # and log-attribute filters still aren't in the rollup.
+ # levels, service_name and other resource-attribute filters re-scope the counts; body-search,
+ # log-attribute filters and personId scoping still aren't in the rollup.
date_range = self._attributes_query_date_range
where_exprs: list[ast.Expr] = []
if self.query.serviceNames:
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index b7bad3239ecd..a0a74485558b 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -29,8 +29,12 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, QueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.filters.mixins.utils import cached_property
+from posthog.models.person.person import MAX_LIMIT_DISTINCT_IDS, get_distinct_ids_for_subquery
+from posthog.models.person.util import get_person_by_pk_or_uuid
+from posthog.personhog_client.caller_tag import personhog_caller_tag
from products.logs.backend.column_expressions import canonical_key, column_to_expr
+from products.logs.backend.models import DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, TeamLogsConfig
if TYPE_CHECKING:
from posthog.models import Team, User
@@ -385,6 +389,9 @@ class LogsFilterBuilder:
exprs.append(get_lowercase_index_hint(log_filter, team=self.team))
exprs.append(property_to_expr(log_filter, team=self.team))
+ if self.query.personId:
+ exprs.append(self._person_scope_expr())
+
exprs.append(ast.Placeholder(expr=ast.Field(chain=["filters"])))
if self.query.searchTerm:
@@ -465,6 +472,42 @@ class LogsFilterBuilder:
return ast.And(exprs=exprs)
+ def _person_scope_expr(self) -> ast.Expr:
+ # Expand personId server-side: person pages cap how many distinct ids they load
+ # (groupArray(101) / list serializer), so a client-built distinct-ids filter would
+ # silently drop ids on persons with many of them.
+ with personhog_caller_tag("persons/logs-query"):
+ person = get_person_by_pk_or_uuid(
+ self.team.pk, str(self.query.personId), distinct_id_limit=MAX_LIMIT_DISTINCT_IDS
+ )
+ distinct_ids = get_distinct_ids_for_subquery(person, self.team)
+ if not distinct_ids:
+ # Unknown person (or another team's person): match nothing. property_to_expr
+ # 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 = (
+ 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,
+ )
+ 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.
+ return key_exprs[0] if len(key_exprs) == 1 else ast.Or(exprs=key_exprs)
+
def resource_filter(self, *, existing_filters):
negative_resource_filter = ast.Constant(value=True)
# generate a query which excludes all the resources which match a negative filter
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index 28e5f0d9ce90..b3a38668f619 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -289,6 +289,13 @@ class _LogsQueryBodySerializer(serializers.Serializer):
"Values come back on each result row keyed by the aliases echoed in the response `columns` field."
),
)
+ personId = serializers.CharField(
+ required=False,
+ help_text=(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's "
+ "distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
+ )
class _LogsQueryRequestSerializer(serializers.Serializer):
@@ -324,6 +331,13 @@ class _LogsSparklineBodySerializer(serializers.Serializer):
required=False,
help_text='Break down sparkline by "severity" (default) or "service".',
)
+ personId = serializers.CharField(
+ required=False,
+ help_text=(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's "
+ "distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
+ )
class _LogsSparklineRequestSerializer(serializers.Serializer):
@@ -413,6 +427,13 @@ class _LogsFacetValuesBodySerializer(serializers.Serializer):
default=list,
help_text="Property filters for the query.",
)
+ personId = serializers.CharField(
+ required=False,
+ help_text=(
+ "Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's "
+ "distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
+ )
class _LogsFacetValuesRequestSerializer(serializers.Serializer):
@@ -1180,6 +1201,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"searchTerm": query_data.get("searchTerm", None),
"filterGroup": self._normalize_filter_group(query_data.get("filterGroup", None)),
"resourceFingerprint": query_data.get("resourceFingerprint", None),
+ "personId": query_data.get("personId", None),
"limit": requested_limit + 1, # Fetch limit plus 1 to see if theres another page
"excludeAttributes": query_data.get("excludeAttributes", False),
"customColumns": custom_columns,
@@ -1273,6 +1295,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
searchTerm=query_data.get("searchTerm", None),
filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
resourceFingerprint=query_data.get("resourceFingerprint", None),
+ personId=query_data.get("personId", None),
sparklineBreakdownBy=query_data.get("sparklineBreakdownBy"),
)
@@ -1321,6 +1344,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
serviceNames=query_data.get("serviceNames", []),
searchTerm=query_data.get("searchTerm", None),
filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
+ personId=query_data.get("personId", None),
)
runner = LogFacetValuesQueryRunner(
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index 3cf39ac074ca..8fde15c49825 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -1,5 +1,6 @@
import os
import json
+from uuid import uuid4
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -25,8 +26,11 @@ from posthog.hogql.query import HogQLQueryExecutor
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
+from posthog.models import Team
+from posthog.test.persons import create_person
from products.logs.backend.logs_query_runner import LogsQueryRunner
+from products.logs.backend.models import TeamLogsConfig
class TestAttributeFilters(APIBaseTest):
@@ -1132,3 +1136,159 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
}
response = self._make_logs_api_request(query_params)
self.assertGreater(len(response["results"]), 0)
+
+
+class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
+ # `personId` on LogsQuery is expanded server-side to the person's distinct ids. Person
+ # pages cap how many distinct ids they load client-side, so a client-built distinct-id
+ # filter silently misses logs for id-heavy persons — the bug this class guards against.
+ # Tests share one ClickHouse team; each uses unique distinct-id values for isolation.
+
+ def _insert_logs(self, rows: list[dict]) -> None:
+ payload = "\n".join(json.dumps({**row, "team_id": self.team.id}) for row in rows)
+ sync_execute(f"""
+ INSERT INTO logs
+ FORMAT JSONEachRow
+ {payload}
+ """)
+
+ def _log_row(self, distinct_id_value: str, attribute_key: str = "posthogDistinctId") -> dict:
+ return {
+ "uuid": str(uuid4()),
+ "timestamp": "2026-03-01 10:00:00.000000",
+ "observed_timestamp": "2026-03-01 10:00:01.000000",
+ "body": f"log for {distinct_id_value}",
+ "severity_text": "info",
+ "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},
+ }
+
+ def _person_query(self, person_id: str) -> LogsQuery:
+ return LogsQuery(
+ kind="LogsQuery",
+ dateRange=DateRange(date_from="2026-03-01T00:00:00Z", date_to="2026-03-02T00:00:00Z"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[])],
+ ),
+ personId=person_id,
+ )
+
+ def _run(self, person_id: str) -> list:
+ return LogsQueryRunner(query=self._person_query(person_id), team=self.team).calculate().results
+
+ def test_person_id_expands_to_all_distinct_ids(self):
+ person = create_person(team=self.team, distinct_ids=["person-id-test-a1", "person-id-test-a2"])
+ create_person(team=self.team, distinct_ids=["person-id-test-other"])
+ self._insert_logs(
+ [
+ self._log_row("person-id-test-a1"),
+ self._log_row("person-id-test-a2"),
+ self._log_row("person-id-test-other"),
+ ]
+ )
+
+ results = self._run(str(person.uuid))
+
+ self.assertEqual(
+ sorted(r["attributes"]["posthogDistinctId"] for r in results),
+ ["person-id-test-a1", "person-id-test-a2"],
+ )
+
+ @parameterized.expand([("unknown_person",), ("person_from_another_team",)])
+ def test_person_id_without_matching_person_matches_nothing(self, case: str):
+ # An empty distinct-id list must never reach property_to_expr: it treats an empty
+ # value list as always-true, which would leak every log in the project onto the tab.
+ self._insert_logs([self._log_row("person-id-test-leak")])
+ if case == "unknown_person":
+ person_id = str(uuid4())
+ else:
+ other_team = Team.objects.create(organization=self.organization)
+ person_id = str(create_person(team=other_team, distinct_ids=["person-id-test-leak"]).uuid)
+
+ self.assertEqual(self._run(person_id), [])
+
+ @parameterized.expand(
+ [
+ ("single_key", ["user.id"], {"user.id"}),
+ ("multiple_keys", ["user.id", "posthogDistinctId"], {"user.id", "posthogDistinctId"}),
+ ]
+ )
+ 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.
+ 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"),
+ ]
+ )
+
+ results = self._run(str(person.uuid))
+
+ 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_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.
+ person = create_person(team=self.team, distinct_ids=["12345", "67890"])
+ runner = LogsQueryRunner(query=self._person_query(str(person.uuid)), team=self.team)
+ executor = HogQLQueryExecutor(
+ query_type="LogsQuery",
+ query=runner.to_query(),
+ modifiers=runner.modifiers,
+ team=runner.team,
+ workload=Workload.LOGS,
+ timings=runner.timings,
+ limit_context=runner.limit_context,
+ filters=HogQLFilters(dateRange=runner.query.dateRange),
+ settings=runner.settings,
+ )
+ executor.generate_clickhouse_sql()
+ assert executor.clickhouse_prepared_ast is not None
+ query_str = executor.clickhouse_prepared_ast.to_hogql()
+
+ self.assertIn("posthogDistinctId__str", query_str)
+ self.assertNotIn("posthogDistinctId__float", query_str)
+ self.assertIn("12345", query_str)
+ self.assertIn("67890", query_str)
+
+ def test_person_id_via_query_sparkline_and_facet_values_apis(self):
+ # The logs endpoints hand-build LogsQuery from request data — a personId omitted
+ # from that whitelist silently un-scopes the person tab.
+ person = create_person(team=self.team, distinct_ids=["person-id-test-api"])
+ self._insert_logs([self._log_row("person-id-test-api"), self._log_row("person-id-test-api-unrelated")])
+ query_params = {
+ "dateRange": {"date_from": "2026-03-01T00:00:00Z", "date_to": "2026-03-02T00:00:00Z"},
+ "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},
+ "personId": str(person.uuid),
+ }
+
+ response = self.client.post(f"/api/projects/{self.team.id}/logs/query", data={"query": query_params})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ results = response.json()["results"]
+ self.assertEqual([r["attributes"]["posthogDistinctId"] for r in results], ["person-id-test-api"])
+
+ sparkline_response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/sparkline", data={"query": query_params}
+ )
+ self.assertEqual(sparkline_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(sum(bucket["count"] for bucket in sparkline_response.json()), 1)
+
+ facet_response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/facet_values",
+ data={"query": {**query_params, "facetField": "severity_text"}},
+ )
+ self.assertEqual(facet_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(facet_response.json()["results"], [{"value": "info", "count": 1}])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
index a52b7ce6eb45..35cf340d05c5 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
@@ -37,6 +37,7 @@ export interface FacetCountsLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetCountsLogicValues {
filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
@@ -143,7 +144,7 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
connect((props: FacetCountsLogicProps) => ({
values: [
logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup'],
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId'],
teamLogic,
['currentTeamId'],
],
@@ -213,6 +214,7 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
searchTerm: values.filters.searchTerm || undefined,
facetSearch: values.facetSearch[facet.key] || undefined,
filterGroup,
+ personId: values.personId,
},
})
return response.results
@@ -318,10 +320,10 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
})),
subscriptions(({ actions, values }) => {
- // Fires on mount (initial load) and on any change. We watch both `filters` (severity, service,
- // search, date, user filterGroup) and `queryFilterGroup` (which folds in pinnedFilters, e.g. the
- // person-tab distinct_id pin) so values re-fetch when the pinned scope changes too. `filterGroup`
- // feeds both, so a normal edit fires both — the 300ms debounce in the loader collapses that.
+ // Fires on mount (initial load) and on any change. We watch `filters` (severity, service,
+ // search, date, user filterGroup), `queryFilterGroup` (which folds in pinnedFilters) and
+ // `personId` (the person-tab scope) so values re-fetch when any scope changes. `filterGroup`
+ // feeds the first two, so a normal edit fires both — the 300ms debounce in the loader collapses that.
const reloadAll = (): void => {
// Before the presence probe settles, defer to loadPresentResourceKeys{Success,Failure}
// so we issue one full fetch over the final visible set instead of two.
@@ -332,6 +334,7 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
return {
filters: reloadAll,
queryFilterGroup: reloadAll,
+ personId: reloadAll,
}
}),
])
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
index 3e482cbb63bb..6e5a54eaa7b5 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
@@ -41,13 +41,17 @@ export const DEFAULT_SERVICE_NAMES = [] as LogsQuery['serviceNames']
export interface LogsViewerFiltersLogicProps {
id: string
initialFilters?: Partial<LogsViewerFilters>
- // Filters enforced by the embedding scene (e.g. the person profile Logs tab pins
- // a distinct_id filter so the tab can't fall back to project-wide logs). Kept
+ // Filters enforced by the embedding scene (e.g. the tracing span drawer pins a
+ // trace_id filter so the tab can't fall back to project-wide logs). Kept
// entirely separate from the user-editable `filterGroup` — combined with it only
// at query-build time via `queryFilterGroup` so the chips never see them and
- // can't drift when the pinned shape changes (e.g. `logs_distinct_id_attribute_keys`
- // resolves to non-default keys after mount).
+ // can't drift when the pinned shape changes.
pinnedFilters?: UniversalFiltersGroup
+ // Scope every query to this person (uuid or numeric id). Expanded server-side to the
+ // person's distinct ids and matched against the team's configured distinct-id log
+ // attributes — unlike a pinned distinct-ids filter, not capped by how many ids the
+ // person page happened to load.
+ personId?: string
}
// Combines the user-editable filterGroup with pinned filters (prepended to the inner
@@ -81,6 +85,7 @@ export interface logsViewerFiltersLogicValues {
filters: LogsViewerFilters
id: string
openFilterOnInsert: boolean
+ personId: string | undefined
pinnedFilters: UniversalFiltersGroup | undefined
queryFilterGroup: UniversalFiltersGroup
searchTerm: LogsQuery['searchTerm']
@@ -123,6 +128,9 @@ export interface logsViewerFiltersLogicActions {
filters: Partial<LogsViewerFilters>
pushToHistory: boolean
}
+ setPersonId: (personId: string | undefined) => {
+ personId: string | undefined
+ }
setPinnedFilters: (pinnedFilters: UniversalFiltersGroup | undefined) => {
pinnedFilters: UniversalFiltersGroup | undefined
}
@@ -198,6 +206,9 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
// (which doesn't accept optional props).
setPinnedFilters: (pinnedFilters: UniversalFiltersGroup | undefined) => ({ pinnedFilters }),
+ // Mirror of the `personId` prop into state, same rationale as `setPinnedFilters`.
+ setPersonId: (personId: string | undefined) => ({ personId }),
+
zoomDateRange: (multiplier: number) => ({ multiplier }),
addFilter: (
@@ -263,6 +274,12 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
setPinnedFilters: (_, { pinnedFilters }) => pinnedFilters,
},
],
+ personId: [
+ undefined as string | undefined,
+ {
+ setPersonId: (_, { personId }) => personId,
+ },
+ ],
}),
selectors({
@@ -348,6 +365,9 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
if (!equal(logicProps.pinnedFilters, oldProps.pinnedFilters)) {
actions.setPinnedFilters(logicProps.pinnedFilters)
}
+ if (logicProps.personId !== oldProps.personId) {
+ actions.setPersonId(logicProps.personId)
+ }
}),
afterMount(({ actions, props: logicProps }) => {
@@ -357,5 +377,8 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
if (logicProps.pinnedFilters) {
actions.setPinnedFilters(logicProps.pinnedFilters)
}
+ if (logicProps.personId) {
+ actions.setPersonId(logicProps.personId)
+ }
}),
])
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index 910320f1b1de..b48f631de09f 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -38,6 +38,11 @@ export interface LogsViewerProps {
// Filters enforced by the embedding scene. Merged into the user-editable filterGroup
// and rendered without an X so users can't accidentally drop the scope.
pinnedFilters?: UniversalFiltersGroup
+ // Scope all logs and sparkline queries to this person (uuid or numeric id). Expanded
+ // server-side to the person's distinct ids and matched against the team's configured
+ // distinct-id log attributes — unlike a pinned distinct-ids filter, not capped by how
+ // many ids the person page happened to load.
+ personId?: string
// Seed the facet/filter rail as collapsed on first mount for this id. Persisted per id,
// so a user who expands it keeps that choice; the "Show filters" toggle still re-expands.
defaultFacetRailCollapsed?: boolean
@@ -49,10 +54,11 @@ export function LogsViewer({
showSavedViewsButton = false,
initialFilters,
pinnedFilters,
+ personId,
defaultFacetRailCollapsed,
}: LogsViewerProps): JSX.Element {
return (
- <BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters }}>
+ <BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters, personId }}>
<BindLogic logic={logsViewerConfigLogic} props={{ id, defaultFacetRailCollapsed }}>
<BindLogic logic={logsViewerDataLogic} props={{ id }}>
<BindLogic logic={logDetailsModalLogic} props={{ id }}>
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index 34c9f118b46a..233e5ce8363f 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -144,6 +144,7 @@ export interface logsViewerDataLogicValues {
sparklineBreakdownBy: LogsSparklineBreakdownBy // logsViewerConfigLogic
filterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
@@ -495,7 +496,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
],
values: [
logsViewerFiltersLogic({ id }),
- ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup'],
+ ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup', 'personId'],
logsViewerConfigLogic({ id }),
['sparklineBreakdownBy', 'orderBy', 'customColumns'],
],
@@ -687,6 +688,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
severityLevels: values.filters.severityLevels,
serviceNames: values.filters.serviceNames,
+ personId: values.personId,
customColumns: sentCustomColumns,
},
signal,
@@ -738,6 +740,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
severityLevels: values.filters.severityLevels,
serviceNames: values.filters.serviceNames,
+ personId: values.personId,
customColumns: values.customColumns,
after: values.nextCursor,
},
@@ -772,6 +775,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
severityLevels: values.filters.severityLevels,
serviceNames: values.filters.serviceNames,
sparklineBreakdownBy: values.sparklineBreakdownBy,
+ personId: values.personId,
},
signal,
})
@@ -1148,6 +1152,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
severityLevels: values.filters.severityLevels,
serviceNames: values.filters.serviceNames,
+ personId: values.personId,
customColumns: values.customColumns,
liveLogsCheckpoint: values.liveLogsCheckpoint ?? undefined,
},
diff --git a/products/logs/frontend/components/LogsViewer/logsExportLogic.ts b/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
index 2eeec95c7fa5..9851fcef8c19 100644
--- a/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
@@ -51,6 +51,7 @@ export interface logsExportLogicValues {
orderBy: LogsOrderBy // logsViewerConfigLogic
maxExportableLogs: number // logsViewerDataLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -101,7 +102,7 @@ export const logsExportLogic = kea<logsExportLogicType>([
logsViewerLogic({ id }),
['selectedLogsArray', 'attributeColumns'],
logsViewerFiltersLogic({ id }),
- ['filters', 'utcDateRange'],
+ ['filters', 'utcDateRange', 'personId'],
logsViewerDataLogic({ id }),
['maxExportableLogs'],
logsViewerConfigLogic({ id }),
@@ -152,6 +153,7 @@ export const logsExportLogic = kea<logsExportLogicType>([
severityLevels: values.filters.severityLevels,
serviceNames: values.filters.serviceNames,
orderBy: values.orderBy,
+ personId: values.personId,
}
posthog.capture('logs exported', { format: 'csv', source: 'server', totalLogsCount })
try {
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 6e8ba9b5d2af..08c16ccfa575 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1054,6 +1054,8 @@ export interface _LogsFacetValuesBodyApi {
facetSearch?: string
/** Property filters for the query. */
filterGroup?: _LogPropertyFilterApi[]
+ /** Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string
}
export interface _LogsFacetValuesRequestApi {
@@ -1461,6 +1463,8 @@ export interface _LogsQueryBodyApi {
excludeAttributes?: boolean
/** Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field. */
customColumns?: string[]
+ /** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string
}
export interface _LogsQueryRequestApi {
@@ -1759,6 +1763,8 @@ export interface _LogsSparklineBodyApi {
* * `severity` - severity
* * `service` - service */
sparklineBreakdownBy?: SparklineBreakdownByEnumApi
+ /** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string
}
export interface _LogsSparklineRequestApi {
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index d60b150fa061..508b36fd81d0 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -702,6 +702,12 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe('Property filters for the query.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The facet values query to execute.'),
})
@@ -1272,6 +1278,12 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
"Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field."
),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The logs query to execute.'),
})
@@ -1629,6 +1641,12 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Break down sparkline by \"severity\" (default) or \"service\".\n\n\* `severity` - severity\n\* `service` - service'
),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The sparkline query to execute.'),
})
diff --git a/products/logs/frontend/logsConfigLogic.ts b/products/logs/frontend/logsConfigLogic.ts
index b38b589cfa57..b8fe659f94a0 100644
--- a/products/logs/frontend/logsConfigLogic.ts
+++ b/products/logs/frontend/logsConfigLogic.ts
@@ -6,8 +6,8 @@ import { teamLogic } from 'scenes/teamLogic'
// Mirrors the backend default in products/logs/backend/models.py — the convention
// documented at https://posthog.com/docs/logs/link-session-replay. Used as the
-// pre-load fallback in `PersonLogsTab` so the initial pinned filter matches the
-// SDK convention before `logs_config` resolves.
+// pre-load fallback for the attribute-key caption in `PersonLogsTab` before
+// `logs_config` resolves.
export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = 'posthogDistinctId'
export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3dcd99759174..bf7b80705ce4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -33917,6 +33917,8 @@ export namespace Schemas {
modifiers?: HogQLQueryModifiers | null;
offset?: number | null;
orderBy?: LogsOrderBy | null;
+ /** Show logs for a given person */
+ personId?: string | null;
resourceFingerprint?: string | null;
response?: LogsQueryResponse | null;
searchTerm?: string | null;
@@ -70636,6 +70638,8 @@ export namespace Schemas {
facetSearch?: string;
/** Property filters for the query. */
filterGroup?: _LogPropertyFilter[];
+ /** Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string;
}
export interface _LogsFacetValuesRequest {
@@ -70822,6 +70826,8 @@ export namespace Schemas {
excludeAttributes?: boolean;
/** Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field. */
customColumns?: string[];
+ /** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string;
}
export interface _LogsQueryRequest {
@@ -70942,6 +70948,8 @@ export namespace Schemas {
* * `severity` - severity
* * `service` - service */
sparklineBreakdownBy?: SparklineBreakdownByEnum;
+ /** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */
+ personId?: string;
}
export interface _LogsSparklineBucket {
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index d5188132d51f..6ead36c19d83 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -4329,6 +4329,12 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe('Property filters for the query.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The facet values query to execute.'),
})
@@ -4647,6 +4653,12 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
"Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field."
),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The logs query to execute.'),
})
@@ -4844,6 +4856,12 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Break down sparkline by \"severity\" (default) or \"service\".\n\n\* `severity` - severity\n\* `service` - service'
),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys."
+ ),
})
.describe('The sparkline query to execute.'),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json
index 4c7e4c4bdbd1..c5a8790c6b4b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-facet-values-create.json
@@ -101,6 +101,10 @@
},
"type": "array"
},
+ "personId": {
+ "description": "Scope counts to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys.",
+ "type": "string"
+ },
"searchTerm": {
"description": "Full-text search term to filter log bodies.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json
index e5860d7dde7e..d26e97cd78e4 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json
@@ -74,6 +74,10 @@
},
"type": "array"
},
+ "personId": {
+ "description": "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys.",
+ "type": "string"
+ },
"searchTerm": {
"description": "Full-text search term to filter log bodies.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
index c55b41ee180b..2e935fcdc606 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
@@ -101,6 +101,10 @@
"enum": ["latest", "earliest"],
"type": "string"
},
+ "personId": {
+ "description": "Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys.",
+ "type": "string"
+ },
"searchTerm": {
"description": "Full-text search term to filter log bodies.",
"type": "string"