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 session logs server-side so the keys OR (#90918)

Jon McCallum9e2a0f31eeab
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 73fba8b24778..6fef7c99be5f 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -32254,6 +32254,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Show logs for a given session ID",
+ "type": "string"
+ },
"severityLevels": {
"items": {
"$ref": "#/definitions/LogSeverityLevel"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 7708b5d08b73..65de25f41a11 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -4469,6 +4469,8 @@ export interface LogsQuery extends DataNode<LogsQueryResponse> {
excludeAttributes?: boolean
/** Show logs for a given person */
personId?: string
+ /** Show logs for a given session ID */
+ sessionId?: 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/posthog/schema.py b/posthog/schema.py
index ca9144879dec..e28b0d65aa3d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -29356,6 +29356,7 @@ class LogsQuery(BaseModel):
response: LogsQueryResponse | None = None
searchTerm: str | None = None
serviceNames: list[str]
+ sessionId: str | None = Field(default=None, description="Show logs for a given session ID")
severityLevels: list[LogSeverityLevel]
sparklineBreakdownBy: LogsSparklineBreakdownBy | None = Field(
default=None,
diff --git a/products/error_tracking/frontend/components/EventsTable/EventActions.tsx b/products/error_tracking/frontend/components/EventsTable/EventActions.tsx
index fe4eb5643ba5..c7eba6ac0aae 100644
--- a/products/error_tracking/frontend/components/EventsTable/EventActions.tsx
+++ b/products/error_tracking/frontend/components/EventsTable/EventActions.tsx
@@ -6,7 +6,7 @@ import { ErrorEventType } from 'lib/components/Errors/types'
import { getRecordingStatus, getSessionId } from 'lib/components/Errors/utils'
import { useRecordingButton } from 'lib/components/ViewRecordingButton/ViewRecordingButton'
import { IconLink, IconPlayCircle } from 'lib/lemon-ui/icons'
-import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Spinner } from 'lib/ui/quill'
+import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'lib/ui/quill'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { urls } from 'scenes/urls'
@@ -50,12 +50,12 @@ export function EventActions({ record }: { record: ErrorEventType }): JSX.Elemen
</DropdownMenuItem>
{logs.enabled && (
<DropdownMenuItem
- disabled={logs.loading || !logs.onClick}
+ disabled={!logs.onClick}
onClick={logs.onClick}
title={logs.disabledReason}
data-attr="error-tracking-view-logs"
>
- {logs.loading ? <Spinner /> : <IconLive />}
+ <IconLive />
View logs
</DropdownMenuItem>
)}
diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
index ebbe57be93ac..33548798bcb6 100644
--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
@@ -666,9 +666,9 @@ export function ExceptionCardHeaderWidthsWithAction(): JSX.Element {
}
ExceptionCardHeaderWidthsWithAction.parameters = headerActionParameters()
-// The action is a ViewLogsButton: feature-flagged, only rendered on the timeline/recording tabs, and
-// gated on the team's logs config. All three have to be satisfied or the right-hand cell renders empty
-// and the story stops testing the crowded case it exists for.
+// The action is a ViewLogsButton: feature-flagged, and only rendered on the timeline/recording tabs.
+// Both have to be satisfied or the right-hand cell renders empty and the story stops testing the
+// crowded case it exists for.
function headerActionParameters(): Record<string, unknown> {
const timeline = sessionTimelineParameters(asErrorEventType(TEST_EVENTS['javascript_resolved']))
const timelineMocks = (timeline.msw as { mocks: Mocks }).mocks
diff --git a/products/logs/backend/log_facet_values_query_runner.py b/products/logs/backend/log_facet_values_query_runner.py
index 097e51f4c22a..7908723b56db 100644
--- a/products/logs/backend/log_facet_values_query_runner.py
+++ b/products/logs/backend/log_facet_values_query_runner.py
@@ -195,7 +195,7 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQue
# grouping the logs Map column, which reads the whole attribute column and blows past the
# read cap at scale. The rollup carries severity_text and service_name, so severity levels,
# service_name and resource-attribute filters re-scope the counts; body-search, log-attribute
- # filters and personId scoping still aren't in the rollup.
+ # filters and personId / sessionId 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 87d87c2e05b0..63ad6457cb1a 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -35,7 +35,9 @@ 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,
+ DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,
DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS,
+ SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS,
TeamLogsConfig,
)
@@ -442,9 +444,15 @@ 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:
+ # Scope on the field being present at all, not on it being truthy: a caller that asks for a
+ # person or a session but holds a blank id must match nothing rather than widen to the
+ # whole project.
+ if self.query.personId is not None:
exprs.append(self._person_scope_expr())
+ if self.query.sessionId is not None:
+ exprs.append(self._session_scope_expr())
+
exprs.append(ast.Placeholder(expr=ast.Field(chain=["filters"])))
if self.query.searchTerm:
@@ -525,64 +533,91 @@ 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()
- configured_keys = (
- config.logs_distinct_id_attribute_keys if config else None
- ) or DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS
- # 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)
+ @cached_property
+ def _team_logs_config(self) -> TeamLogsConfig | None:
+ return TeamLogsConfig.objects.filter(team=self.team).first()
+
+ def _attribute_scope_expr(self, attribute_keys: list[str], values: list[str]) -> ast.Expr:
+ # Matches when any of the keys, in either the log attributes or the resource attributes,
+ # holds one of the values. Both maps are scoped because the logs UI resolves a person or a
+ # session from either one (LogAttributes.tsx renders the link regardless of which map the
+ # value came from), so a log the UI labels must also appear when you scope to that label.
+ # The two maps need different key spellings: attributes_map_str holds every attribute value
+ # stringified while attributes_map_float only exists for numeric values, so the `__str`
+ # suffix keeps an all-numeric id off the float map. resource_attributes is a plain string
+ # map on the row with no such split, so its key is matched directly.
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,
+ value=values,
),
team=self.team,
)
)
- # 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,
+ value=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 _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.
+ person_id = (self.query.personId or "").strip()
+ if not person_id:
+ return ast.Constant(value=False)
+ with personhog_caller_tag("persons/logs-query"):
+ person = get_person_by_pk_or_uuid(self.team.pk, person_id, 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 = self._team_logs_config
+ configured_keys = (
+ config.logs_distinct_id_attribute_keys if config else None
+ ) or DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS
+ # 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]))
+ return self._attribute_scope_expr(attribute_keys, list(distinct_ids))
+
+ def _session_scope_expr(self) -> ast.Expr:
+ # Resolve the key list server-side rather than letting the caller build a filter group.
+ # The keys must be OR'd, and a filterGroup can't express that here: its inner group is
+ # read as an AND of its leaves, and a nested group accepts log_attribute leaves only,
+ # so the resource-attribute half of each key could never join the OR.
+ session_id = (self.query.sessionId or "").strip()
+ if not session_id:
+ # property_to_expr treats an empty value as always-true, which would return every log.
+ return ast.Constant(value=False)
+
+ config = self._team_logs_config
+ configured_keys = (
+ config.logs_session_id_attribute_keys if config else None
+ ) or DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS
+ # Also scope on the built-in convention keys the logs UI reads a session from
+ # (isSessionIdKey in products/logs/frontend/utils.tsx), so a log the UI shows as belonging
+ # to a session appears when scoped to it even when the team hasn't configured that key.
+ # Deduped, configured keys first.
+ attribute_keys = list(dict.fromkeys([*configured_keys, *SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS]))
+ return self._attribute_scope_expr(attribute_keys, [session_id])
+
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/models.py b/products/logs/backend/models.py
index 3d0c3dedc240..026dea332479 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -77,6 +77,28 @@ def default_logs_pattern_message_keys() -> list[str]:
return list(DEFAULT_LOGS_PATTERN_MESSAGE_KEYS)
+# Built-in session-id attribute key conventions. Mirror of the frontend SESSION_ID_KEYS in
+# products/logs/frontend/utils.tsx, so keep the two in sync. The logs UI renders a value under any
+# of these keys as the log's session (isSessionIdKey), so a session-scoped viewer matches them too
+# (on top of a team's configured keys), otherwise a log the UI shows as belonging to a session
+# would not appear when scoped to it. Literal keys only: the frontend additionally matches
+# dot-suffixed variants (e.g. `span.session_id`), which an exact attribute filter can't express.
+# `posthogSessionId` is emitted by some pipelines even though no SDK sends it; removing it
+# breaks them.
+SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS = [
+ "session.id",
+ "session_id",
+ "sessionId",
+ "sessionID",
+ "$session_id",
+ "posthogSessionId",
+ "posthogSessionID",
+ "posthog_session_id",
+ "posthog.session.id",
+ "posthog.session_id",
+]
+
+
class TeamLogsConfig(models.Model):
# Plain `models.Model` (not `TeamScopedRootMixin`) — log emission and ingestion
# are per-environment, and so is this config. Inheriting the root-mixin would
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index d40de3d69641..5fac5693c681 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -252,6 +252,30 @@ class OrderBy(models.TextChoices):
EARLIEST = "earliest", "earliest"
+# Scope fields ride on every logs body that reaches the query runner, so they are built here
+# rather than redeclared per serializer — the help text is what drf-spectacular ships into the
+# generated TypeScript and the MCP tool schemas, and six copies drift.
+def _person_scope_field(noun: str) -> serializers.CharField:
+ return serializers.CharField(
+ required=False,
+ help_text=(
+ f"Scope {noun} 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."
+ ),
+ )
+
+
+def _session_scope_field(noun: str) -> serializers.CharField:
+ return serializers.CharField(
+ required=False,
+ help_text=(
+ f"Scope {noun} to one session ID. Matched server-side against the team's configured "
+ "session-id log attribute keys plus the built-in conventions, in both log attributes "
+ "and resource attributes."
+ ),
+ )
+
+
class _LogsQueryBodySerializer(serializers.Serializer):
dateRange = _DateRangeSerializer(
required=False,
@@ -299,13 +323,8 @@ 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."
- ),
- )
+ personId = _person_scope_field("results")
+ sessionId = _session_scope_field("results")
class _LogsQueryRequestSerializer(serializers.Serializer):
@@ -346,13 +365,8 @@ class _LogsSparklineBodySerializer(serializers.Serializer):
required=False,
help_text='Rank breakdown values by "count" (default) or "bytes" before collapsing the tail into "other".',
)
- 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."
- ),
- )
+ personId = _person_scope_field("results")
+ sessionId = _session_scope_field("results")
class _LogsSparklineRequestSerializer(serializers.Serializer):
@@ -449,13 +463,8 @@ 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."
- ),
- )
+ personId = _person_scope_field("counts")
+ sessionId = _session_scope_field("counts")
class _LogsFacetValuesRequestSerializer(serializers.Serializer):
@@ -763,6 +772,8 @@ class _LogsPatternsBodySerializer(serializers.Serializer):
default=list,
help_text="Property filters applied before mining. Same shape as the query-logs endpoint.",
)
+ personId = _person_scope_field("mining")
+ sessionId = _session_scope_field("mining")
class _LogsPatternsRequestSerializer(serializers.Serializer):
@@ -1079,6 +1090,8 @@ class _LogsGroupByBodySerializer(serializers.Serializer):
max_value=MAX_GROUP_LIMIT,
help_text=f"Maximum number of groups to return (top-N by orderGroupsBy). Defaults to {DEFAULT_GROUP_LIMIT}.",
)
+ personId = _person_scope_field("grouping")
+ sessionId = _session_scope_field("grouping")
class _LogsGroupByRequestSerializer(serializers.Serializer):
@@ -1193,6 +1206,10 @@ 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)),
+ # Patterns and Group are modes of the same viewer, so they inherit its scope. Dropping
+ # these would mine or aggregate the whole project and label the result one session.
+ personId=query_data.get("personId", None),
+ sessionId=query_data.get("sessionId", None),
)
@extend_schema(request=_LogsQueryRequestSerializer, responses={200: _LogsQueryResponseSerializer})
@@ -1251,6 +1268,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"filterGroup": self._normalize_filter_group(query_data.get("filterGroup", None)),
"resourceFingerprint": query_data.get("resourceFingerprint", None),
"personId": query_data.get("personId", None),
+ "sessionId": query_data.get("sessionId", None),
"limit": requested_limit + 1, # Fetch limit plus 1 to see if theres another page
"excludeAttributes": query_data.get("excludeAttributes", False),
"customColumns": custom_columns,
@@ -1346,6 +1364,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
resourceFingerprint=query_data.get("resourceFingerprint", None),
personId=query_data.get("personId", None),
+ sessionId=query_data.get("sessionId", None),
sparklineBreakdownBy=query_data.get("sparklineBreakdownBy"),
sparklineRankBy=query_data.get("sparklineRankBy"),
)
@@ -1398,6 +1417,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
searchTerm=query_data.get("searchTerm", None),
filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
personId=query_data.get("personId", None),
+ sessionId=query_data.get("sessionId", 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 422abfca4698..b0cda5bfea96 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -1189,11 +1189,13 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
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.
+class _LogsScopeFilterTestMixin:
+ # Shared fixtures for the two scope-filter classes below. Both insert the same shape of row:
+ # one attribute key per log, in either the log-attribute map or the resource-attribute map.
+ # They differ only in which LogsQuery scope field they then set.
+ team: Team
+ service_name: str
+ default_attribute_key: str
def _insert_logs(self, rows: list[dict]) -> None:
payload = "\n".join(json.dumps({**row, "team_id": self.team.id}) for row in rows)
@@ -1203,28 +1205,26 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
{payload}
""")
- def _log_row(
- self, distinct_id_value: str, attribute_key: str = "posthogDistinctId", *, resource: bool = False
- ) -> dict:
+ def _log_row(self, value: str, attribute_key: str | None = None, *, resource: bool = False) -> dict:
+ attribute_key = attribute_key or self.default_attribute_key
row: dict = {
"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}",
+ "body": f"log for {value}",
"severity_text": "info",
"severity_number": 9,
- "service_name": "person-id-test-svc",
- "resource_attributes": {"service.name": "person-id-test-svc"},
+ "service_name": self.service_name,
+ "resource_attributes": {"service.name": self.service_name},
"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
+ row["resource_attributes"][attribute_key] = value
else:
- row["attributes_map_str"][f"{attribute_key}__str"] = distinct_id_value
+ row["attributes_map_str"][f"{attribute_key}__str"] = value
return row
- def _person_query(self, person_id: str) -> LogsQuery:
+ def _scope_query(self, *, person_id: str | None = None, session_id: str | None = None) -> LogsQuery:
return LogsQuery(
kind="LogsQuery",
dateRange=DateRange(date_from="2026-03-01T00:00:00Z", date_to="2026-03-02T00:00:00Z"),
@@ -1235,10 +1235,21 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[])],
),
personId=person_id,
+ sessionId=session_id,
)
+
+class TestLogsPersonIdFilter(_LogsScopeFilterTestMixin, 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.
+
+ service_name = "person-id-test-svc"
+ default_attribute_key = "posthogDistinctId"
+
def _run(self, person_id: str) -> list:
- return LogsQueryRunner(query=self._person_query(person_id), team=self.team).calculate().results
+ return LogsQueryRunner(query=self._scope_query(person_id=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"])
@@ -1258,13 +1269,18 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
["person-id-test-a1", "person-id-test-a2"],
)
- @parameterized.expand([("unknown_person",), ("person_from_another_team",)])
+ @parameterized.expand([("unknown_person",), ("person_from_another_team",), ("blank",), ("whitespace",)])
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.
+ # A blank personId is the same hazard one step earlier — it never resolves a person.
self._insert_logs([self._log_row("person-id-test-leak")])
if case == "unknown_person":
person_id = str(uuid4())
+ elif case == "blank":
+ person_id = ""
+ elif case == "whitespace":
+ person_id = " "
else:
other_team = Team.objects.create(organization=self.organization)
person_id = str(create_person(team=other_team, distinct_ids=["person-id-test-leak"]).uuid)
@@ -1336,7 +1352,7 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
# 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)
+ runner = LogsQueryRunner(query=self._scope_query(person_id=str(person.uuid)), team=self.team)
executor = HogQLQueryExecutor(
query_type="LogsQuery",
query=runner.to_query(),
@@ -1385,3 +1401,113 @@ class TestLogsPersonIdFilter(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(facet_response.status_code, status.HTTP_200_OK)
self.assertEqual(facet_response.json()["results"], [{"value": "info", "count": 1}])
+
+
+class TestLogsSessionIdFilter(_LogsScopeFilterTestMixin, ClickhouseTestMixin, APIBaseTest):
+ # `sessionId` on LogsQuery is resolved server-side against every configured and conventional
+ # session-id attribute key, in both attribute maps. A client-built filter group cannot express
+ # that: the runner reads an inner group as an AND of its leaves, so a group listing every key
+ # asks for logs where all of them hold the session id at once, and matches nothing.
+ # Tests share one ClickHouse team; each uses unique session-id values for isolation.
+
+ service_name = "session-id-test-svc"
+ default_attribute_key = "sessionId"
+
+ def _run(self, session_id: str) -> list:
+ return LogsQueryRunner(query=self._scope_query(session_id=session_id), team=self.team).calculate().results
+
+ def test_session_id_matches_every_configured_and_convention_key(self):
+ # Each log carries the session id under one key only. The keys must be OR'd: an AND across
+ # them matches nothing, which is what a filter group built from the same key list produced.
+ # `sessionId` is the configured default; the rest are convention-only, and the UI renders a
+ # value under any of them as the log's session (isSessionIdKey).
+ self._insert_logs(
+ [
+ self._log_row("session-id-test-all", attribute_key="sessionId"),
+ self._log_row("session-id-test-all", attribute_key="session.id"),
+ self._log_row("session-id-test-all", attribute_key="$session_id"),
+ self._log_row("session-id-test-all", attribute_key="posthog_session_id"),
+ self._log_row("session-id-test-all", attribute_key="sessionId", resource=True),
+ self._log_row("session-id-test-all", attribute_key="session_id", resource=True),
+ self._log_row("session-id-test-other", attribute_key="sessionId"),
+ ]
+ )
+
+ results = self._run("session-id-test-all")
+
+ self.assertEqual(len(results), 6)
+ self.assertEqual({r["body"] for r in results}, {"log for session-id-test-all"})
+
+ @parameterized.expand([("attributes", False), ("resource_attributes", True)])
+ def test_session_id_respects_configured_attribute_key(self, _name: str, resource: bool):
+ # A team whose pipeline stamps the session under its own key must still match, in either
+ # map. A custom key (not a built-in convention) isolates configured-key handling from the
+ # convention fallback.
+ TeamLogsConfig.objects.update_or_create(
+ team=self.team, defaults={"logs_session_id_attribute_keys": ["trace.session"]}
+ )
+ self._insert_logs(
+ [
+ self._log_row("session-id-test-cfg", attribute_key="trace.session", resource=resource),
+ self._log_row("session-id-test-cfg-other", attribute_key="trace.session", resource=resource),
+ ]
+ )
+
+ results = self._run("session-id-test-cfg")
+
+ self.assertEqual(len(results), 1)
+ source = "resource_attributes" if resource else "attributes"
+ self.assertEqual(results[0][source]["trace.session"], "session-id-test-cfg")
+
+ @parameterized.expand([("empty", ""), ("whitespace", " ")])
+ def test_blank_session_id_matches_nothing(self, _name: str, session_id: str):
+ # A blank session id must never reach property_to_expr: it treats an empty value as
+ # always-true, which would leak every log in the project into a session-scoped viewer.
+ self._insert_logs([self._log_row("session-id-test-leak")])
+
+ self.assertEqual(self._run(session_id), [])
+
+ def test_session_id_reaches_every_endpoint_the_viewer_calls(self):
+ # Each logs endpoint hand-builds LogsQuery from request data, so a sessionId left out of
+ # one silently un-scopes that half of a session-scoped viewer. Patterns and Group are
+ # modes of the same viewer, so an unscoped one mines the whole project under a heading
+ # the user reads as this session.
+ self._insert_logs([self._log_row("session-id-test-api"), self._log_row("session-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": []}]},
+ "sessionId": "session-id-test-api",
+ }
+
+ 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"]["sessionId"] for r in results], ["session-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}])
+
+ # total_count is the rows the miner matched, not the templates it kept, so this asserts
+ # the scope without depending on which single-occurrence bodies survive mining.
+ patterns_response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/patterns", data={"query": query_params}
+ )
+ self.assertEqual(patterns_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(patterns_response.json()["total_count"], 1)
+
+ group_by_response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/group-by",
+ data={"query": {**query_params, "groupBys": [{"key": "service.name", "source": "resource"}]}},
+ )
+ self.assertEqual(group_by_response.status_code, status.HTTP_200_OK)
+ self.assertEqual(group_by_response.json()["total_logs"], 1)
diff --git a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
index 80e11f107efe..f804ad38184f 100644
--- a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
+++ b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
@@ -33,7 +33,9 @@ const EMPTY_RESPONSE: _LogsGroupByResponseApi = {
export interface logsGroupByLogicValues {
groupBys: LogsViewerGroupBy[] // logsViewerConfigLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ sessionId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -142,7 +144,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
teamLogic,
['currentTeamId'],
logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup'],
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'sessionId'],
logsViewerConfigLogic({ id: props.id }),
['groupBys'],
],
@@ -183,6 +185,10 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
// filters from an embedded viewer, so a scoped viewer can't aggregate
// project-wide logs.
filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],
+ // Person and session scoping travel as their own fields, not in the
+ // filter group, so they have to be sent explicitly here too.
+ personId: values.personId,
+ sessionId: values.sessionId,
groupBys: values.groupBys,
orderGroupsBy: values.orderGroupsBy,
},
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
index d7d56e267d40..dbf33dfd9962 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
@@ -78,7 +78,9 @@ export interface logsPatternsLogicValues {
compareEnabled: boolean // logsViewerConfigLogic
viewMode: LogsViewerViewMode // logsViewerConfigLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ sessionId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -98,7 +100,9 @@ export interface logsPatternsLogicValues {
explicitDate: boolean | null | undefined
}
filterGroup: _LogPropertyFilterApi[]
+ personId: string | undefined
searchTerm: string | undefined
+ sessionId: string | undefined
}
patternsResponse: _LogsPatternsResponseApi
patternsResponseLoading: boolean
@@ -192,7 +196,9 @@ export interface logsPatternsLogicMeta {
date_to: string | null | undefined
explicitDate: boolean | null | undefined
},
- queryFilterGroup: UniversalFiltersGroup
+ queryFilterGroup: UniversalFiltersGroup,
+ personId: string | undefined,
+ sessionId: string | undefined
) => {
dateRange: {
date_from: string | null | undefined
@@ -200,7 +206,9 @@ export interface logsPatternsLogicMeta {
explicitDate: boolean | null | undefined
}
filterGroup: _LogPropertyFilterApi[]
+ personId: string | undefined
searchTerm: string | undefined
+ sessionId: string | undefined
}
patterns: (patternsResponse: _LogsPatternsResponseApi) => _LogPatternApi[]
sparklineLabels: (patternsResponse: _LogsPatternsResponseApi) => string[]
@@ -227,7 +235,7 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
teamLogic,
['currentTeamId'],
logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup'],
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'sessionId'],
logsViewerConfigLogic({ id: props.id }),
['viewMode', 'compareEnabled', 'baselineMode'],
],
@@ -320,7 +328,7 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
// windows with exactly the filters a plain mine would use, or compare mode would
// silently answer a different question than the table next to it.
patternsQueryBody: [
- (s) => [s.filters, s.utcDateRange, s.queryFilterGroup],
+ (s) => [s.filters, s.utcDateRange, s.queryFilterGroup, s.personId, s.sessionId],
(
filters: import('../LogsViewer/config/types').LogsViewerFilters,
utcDateRange: {
@@ -328,7 +336,9 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
date_to: string | null | undefined
explicitDate: boolean | null | undefined
},
- queryFilterGroup: UniversalFiltersGroup
+ queryFilterGroup: UniversalFiltersGroup,
+ personId: string | undefined,
+ sessionId: string | undefined
) => ({
dateRange: utcDateRange,
searchTerm: filters.searchTerm || undefined,
@@ -336,6 +346,10 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
// `queryFilterGroup` folds in any pinned filters from an embedded viewer
// (person/trace logs), so a scoped viewer can't mine project-wide patterns.
filterGroup: queryFilterGroup as unknown as _LogPropertyFilterApi[],
+ // Person and session scoping travel as their own fields, not in the filter
+ // group, so they have to be sent explicitly here too.
+ personId,
+ sessionId,
}),
],
patterns: [
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
index daccd0e863ac..d9c6743a6843 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
@@ -27,6 +27,7 @@ export interface facetValuesLogicValues {
filters: LogsViewerFilters // logsViewerFiltersLogic
personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ sessionId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -82,6 +83,7 @@ export interface facetValuesLogicMeta {
filters: LogsViewerFilters,
queryFilterGroup: UniversalFiltersGroup,
personId: string | undefined,
+ sessionId: string | undefined,
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -122,7 +124,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
connect((props: FacetValuesLogicProps) => ({
values: [
logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'facetRefreshCounter'],
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'sessionId', 'facetRefreshCounter'],
teamLogic,
['currentTeamId'],
facetRailLogic({ id: props.id }),
@@ -188,6 +190,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
facetSearch: values.facetSearch || undefined,
filterGroup,
personId: values.personId,
+ sessionId: values.sessionId,
},
})
// Bail out right after the round-trip: the rail (and this logic) unmounts when the
@@ -211,6 +214,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
s.filters,
s.queryFilterGroup,
s.personId,
+ s.sessionId,
s.utcDateRange,
s.currentTeamId,
s.facetRefreshCounter,
@@ -220,6 +224,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
filters: LogsViewerFilters,
queryFilterGroup: UniversalFiltersGroup,
personId: string | undefined,
+ sessionId: string | undefined,
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -235,6 +240,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
searchTerm: filters.searchTerm,
queryFilterGroup,
personId,
+ sessionId,
})}|r${facetRefreshCounter}`,
],
// One trigger for the one in-flight request: a scope change and a keystroke in this facet's
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index d22bec250a9e..10909bf473ea 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -86,6 +86,7 @@ export interface FacetScope {
/** filterGroup with pinned filters folded in — what the query actually carries. */
queryFilterGroup: UniversalFiltersGroup | undefined
personId?: string
+ sessionId?: string
}
/**
@@ -126,6 +127,7 @@ export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): stri
scope.utcDateRange.explicitDate ?? null,
scope.searchTerm || null,
scope.personId ?? null,
+ scope.sessionId ?? null,
groupSignature,
])
}
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
index dfd03003fe39..4efbf9db5361 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
@@ -62,6 +62,10 @@ export interface LogsViewerFiltersLogicProps {
// attributes — unlike a pinned distinct-ids filter, not capped by how many ids the
// person page happened to load.
personId?: string
+ // Scope every query to this session id. Matched server-side against the team's configured
+ // session-id log attributes plus the built-in conventions, in both the attribute and
+ // resource-attribute maps. A filter group can't express that OR (see buildLogsSessionScope).
+ sessionId?: string
}
// Combines the user-editable filterGroup with pinned filters (prepended to the inner
@@ -141,6 +145,7 @@ export interface logsViewerFiltersLogicValues {
pinnedFilters: UniversalFiltersGroup | undefined
queryFilterGroup: UniversalFiltersGroup
searchTerm: LogsQuery['searchTerm']
+ sessionId: string | undefined
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -193,6 +198,9 @@ export interface logsViewerFiltersLogicActions {
setSearchTerm: (searchTerm: LogsQuery['searchTerm']) => {
searchTerm: string | undefined
}
+ setSessionId: (sessionId: string | undefined) => {
+ sessionId: string | undefined
+ }
zoomDateRange: (multiplier: number) => {
multiplier: number
}
@@ -257,6 +265,9 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
// Mirror of the `personId` prop into state, same rationale as `setPinnedFilters`.
setPersonId: (personId: string | undefined) => ({ personId }),
+ // Mirror of the `sessionId` prop into state, same rationale as `setPersonId`.
+ setSessionId: (sessionId: string | undefined) => ({ sessionId }),
+
zoomDateRange: (multiplier: number) => ({ multiplier }),
bumpFacetRefresh: true,
@@ -334,6 +345,12 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
setPersonId: (_, { personId }) => personId,
},
],
+ sessionId: [
+ undefined as string | undefined,
+ {
+ setSessionId: (_, { sessionId }) => sessionId,
+ },
+ ],
}),
selectors({
@@ -425,6 +442,9 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
if (logicProps.personId !== oldProps.personId) {
actions.setPersonId(logicProps.personId)
}
+ if (logicProps.sessionId !== oldProps.sessionId) {
+ actions.setSessionId(logicProps.sessionId)
+ }
}),
afterMount(({ actions, props: logicProps }) => {
@@ -437,5 +457,8 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
if (logicProps.personId) {
actions.setPersonId(logicProps.personId)
}
+ if (logicProps.sessionId) {
+ actions.setSessionId(logicProps.sessionId)
+ }
}),
])
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index f28361588141..8fc53f61a2c1 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -44,6 +44,7 @@ export interface LogsViewerProps {
// distinct-id log attributes — unlike a pinned distinct-ids filter, not capped by how
// many ids the person page happened to load.
personId?: string
+ sessionId?: 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
@@ -56,10 +57,11 @@ export function LogsViewer({
initialFilters,
pinnedFilters,
personId,
+ sessionId,
defaultFacetRailCollapsed,
}: LogsViewerProps): JSX.Element {
return (
- <BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters, personId }}>
+ <BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters, personId, sessionId }}>
<BindLogic logic={logsViewerConfigLogic} props={{ id, defaultFacetRailCollapsed }}>
<BindLogic logic={logsViewerDataLogic} props={{ id }}>
<BindLogic logic={logDetailsModalLogic} props={{ id }}>
@@ -69,7 +71,7 @@ export function LogsViewer({
<LogsViewerContent
showFullScreenButton={showFullScreenButton}
showSavedViewsButton={showSavedViewsButton}
- scope={{ initialFilters, pinnedFilters, personId }}
+ scope={{ initialFilters, pinnedFilters, personId, sessionId }}
/>
</BindLogic>
</BindLogic>
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerModal/LogsViewerModal.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerModal/LogsViewerModal.tsx
index 32939cae7543..59ade24480c4 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerModal/LogsViewerModal.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerModal/LogsViewerModal.tsx
@@ -12,7 +12,8 @@ import { LogsViewer } from 'products/logs/frontend/components/LogsViewer'
import { logsViewerModalLogic } from './logsViewerModalLogic'
export function LogsViewerModal(): JSX.Element | null {
- const { isOpen, viewerId, fullScreen, initialFilters, pinnedFilters, personId } = useValues(logsViewerModalLogic)
+ const { isOpen, viewerId, fullScreen, initialFilters, pinnedFilters, personId, sessionId } =
+ useValues(logsViewerModalLogic)
const { closeLogsViewerModal } = useActions(logsViewerModalLogic)
const [floatingContainer, setFloatingContainer] = useState<HTMLDivElement | null>(null)
const floatingContainerRef = useCallback((el: HTMLDivElement | null) => setFloatingContainer(el), [])
@@ -47,6 +48,7 @@ export function LogsViewerModal(): JSX.Element | null {
initialFilters={initialFilters ?? undefined}
pinnedFilters={pinnedFilters ?? undefined}
personId={personId ?? undefined}
+ sessionId={sessionId ?? undefined}
/>
</div>
</LemonModal.Content>
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic.ts b/products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic.ts
index 0c94c575f258..32a7e468dd2f 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic.ts
@@ -18,6 +18,7 @@ export interface logsViewerModalLogicValues {
isOpen: boolean
personId: string | null
pinnedFilters: UniversalFiltersGroup | null
+ sessionId: string | null
viewerId: string
}
@@ -53,6 +54,7 @@ export interface logsViewerModalLogicActions {
initialFilters: Partial<LogsViewerFilters> | null
personId: string | null
pinnedFilters: UniversalFiltersGroup | null
+ sessionId: string | null
}
}
@@ -70,6 +72,7 @@ export const logsViewerModalLogic = kea<logsViewerModalLogicType>([
initialFilters: options?.initialFilters ?? null,
pinnedFilters: options?.pinnedFilters ?? null,
personId: options?.personId ?? null,
+ sessionId: options?.sessionId ?? null,
}),
closeLogsViewerModal: true,
}),
@@ -93,12 +96,12 @@ export const logsViewerModalLogic = kea<logsViewerModalLogicType>([
openLogsViewerModal: (_, { fullScreen }) => fullScreen,
},
],
- // The three props below are what the modal binds its viewer with, and they deliberately
+ // The four props below are what the modal binds its viewer with, and they deliberately
// survive close. useKeepMountedWhileOpen holds the modal rendered for 300ms so the exit
// animation can finish, so clearing them on close would rebind the viewer logics (shared
// with the embedding tab, which is keyed by the same id) with no filters and no scope for
// that beat, firing an unscoped project-wide query. Nothing leaks into the next open
- // because openLogsViewerModal always writes all three, falling back to null.
+ // because openLogsViewerModal always writes all four, falling back to null.
initialFilters: [
null as Partial<LogsViewerFilters> | null,
{
@@ -117,6 +120,12 @@ export const logsViewerModalLogic = kea<logsViewerModalLogicType>([
openLogsViewerModal: (_, { personId }) => personId,
},
],
+ sessionId: [
+ null as string | null,
+ {
+ openLogsViewerModal: (_, { sessionId }) => sessionId,
+ },
+ ],
}),
listeners(({ values, actions, cache }) => ({
locationChanged: ({ pathname }) => {
diff --git a/products/logs/frontend/components/LogsViewer/config/types.ts b/products/logs/frontend/components/LogsViewer/config/types.ts
index 74cfbda54400..45697d5a5627 100644
--- a/products/logs/frontend/components/LogsViewer/config/types.ts
+++ b/products/logs/frontend/components/LogsViewer/config/types.ts
@@ -27,4 +27,5 @@ export interface LogsViewerScope {
initialFilters?: Partial<LogsViewerFilters>
pinnedFilters?: UniversalFiltersGroup
personId?: string
+ sessionId?: string
}
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index 87d43077fad1..1b2fca5eae85 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -140,6 +140,7 @@ export interface logsViewerDataLogicValues {
filters: LogsViewerFilters // logsViewerFiltersLogic
personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ sessionId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -481,7 +482,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
],
values: [
logsViewerFiltersLogic({ id }),
- ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup', 'personId'],
+ ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup', 'personId', 'sessionId'],
logsViewerConfigLogic({ id }),
['orderBy', 'customColumns'],
],
@@ -674,6 +675,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
...unsetColumnQueryFields(),
personId: values.personId,
+ sessionId: values.sessionId,
customColumns: sentCustomColumns,
},
signal,
@@ -725,6 +727,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
...unsetColumnQueryFields(),
personId: values.personId,
+ sessionId: values.sessionId,
customColumns: values.customColumns,
after: values.nextCursor,
},
@@ -761,6 +764,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
// severity breakdown, so state it rather than lean on the server default.
sparklineBreakdownBy: 'severity',
personId: values.personId,
+ sessionId: values.sessionId,
},
signal,
})
@@ -1145,6 +1149,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
...unsetColumnQueryFields(),
personId: values.personId,
+ sessionId: values.sessionId,
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 766ee279c00c..bb64c52920d4 100644
--- a/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
@@ -52,6 +52,7 @@ export interface logsExportLogicValues {
maxExportableLogs: number // logsViewerDataLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
personId: string | undefined // logsViewerFiltersLogic
+ sessionId: string | undefined // logsViewerFiltersLogic
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -102,7 +103,7 @@ export const logsExportLogic = kea<logsExportLogicType>([
logsViewerLogic({ id }),
['selectedLogsArray', 'attributeColumns'],
logsViewerFiltersLogic({ id }),
- ['filters', 'utcDateRange', 'personId'],
+ ['filters', 'utcDateRange', 'personId', 'sessionId'],
logsViewerDataLogic({ id }),
['maxExportableLogs'],
logsViewerConfigLogic({ id }),
@@ -153,6 +154,7 @@ export const logsExportLogic = kea<logsExportLogicType>([
...unsetColumnQueryFields(),
orderBy: values.orderBy,
personId: values.personId,
+ sessionId: values.sessionId,
}
posthog.capture('logs exported', { format: 'csv', source: 'server', totalLogsCount })
try {
diff --git a/products/logs/frontend/components/ViewLogsButton.tsx b/products/logs/frontend/components/ViewLogsButton.tsx
index 467c380bb6c8..9a1c243a4c37 100644
--- a/products/logs/frontend/components/ViewLogsButton.tsx
+++ b/products/logs/frontend/components/ViewLogsButton.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { useActions } from 'kea'
import { IconLive } from '@posthog/icons'
import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
@@ -6,8 +6,7 @@ import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'
-import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
-import { buildLogsSessionFilters } from 'products/logs/frontend/utils'
+import { buildLogsSessionScope } from 'products/logs/frontend/utils'
export interface ViewLogsButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {
sessionId: string | null | undefined
@@ -19,42 +18,35 @@ export interface ViewLogsButtonProps extends Pick<LemonButtonProps, 'size' | 'ty
export function useViewLogsButton({ sessionId, timestamp }: Pick<ViewLogsButtonProps, 'sessionId' | 'timestamp'>): {
enabled: boolean
onClick: (() => void) | undefined
- loading: boolean
disabledReason: string | undefined
} {
- const { configuredSessionIdKeys, logsConfigLoading } = useValues(logsConfigLogic)
const { openLogsViewerModal } = useActions(logsViewerModalLogic)
const enabled = useFeatureFlag('LOGS_IN_ERROR_TRACKING')
- // Until the team's logs config resolves we don't know which session-ID keys to filter on.
- // Opening with the fallback key here would silently show logs filtered by the wrong
- // attribute for teams that configured a custom key, so hold the button in a loading state.
- const onClick =
- sessionId && !logsConfigLoading
- ? () =>
- openLogsViewerModal({
- id: `session-${sessionId}`,
- fullScreen: false,
- initialFilters: buildLogsSessionFilters(sessionId, configuredSessionIdKeys, timestamp),
- })
- : undefined
+ const onClick = sessionId
+ ? () =>
+ openLogsViewerModal({
+ id: `session-${sessionId}`,
+ fullScreen: false,
+ ...buildLogsSessionScope(sessionId, timestamp),
+ })
+ : undefined
return {
enabled,
onClick,
- loading: logsConfigLoading,
disabledReason: sessionId ? undefined : 'No session ID associated with this event',
}
}
-// The shared hook keeps the feature flag and configured session ID keys consistent across every logs entry point.
+// The shared hook keeps the feature flag and the session scope consistent across every logs entry point.
export function ViewLogsButton({
sessionId,
timestamp,
iconOnly,
...buttonProps
}: ViewLogsButtonProps): JSX.Element | null {
- const { enabled, onClick, loading, disabledReason } = useViewLogsButton({ sessionId, timestamp })
+ const { enabled, onClick, disabledReason } = useViewLogsButton({ sessionId, timestamp })
if (!enabled) {
return null
@@ -64,7 +56,6 @@ export function ViewLogsButton({
<LemonButton
icon={<IconLive />}
onClick={onClick}
- loading={loading}
tooltip={iconOnly ? 'View logs from this session' : undefined}
disabledReason={disabledReason}
{...buttonProps}
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 06ebd4c12de8..027a019425d5 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1602,6 +1602,8 @@ export interface _LogsFacetValuesBodyApi {
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
+ /** Scope counts to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string
}
export interface _LogsFacetValuesRequestApi {
@@ -1695,6 +1697,10 @@ export interface _LogsGroupByBodyApi {
* @maximum 500
*/
limit?: number
+ /** Scope grouping 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
+ /** Scope grouping to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string
}
export interface _LogsGroupByRequestApi {
@@ -1818,6 +1824,10 @@ export interface _LogsPatternsBodyApi {
searchTerm?: string
/** Property filters applied before mining. Same shape as the query-logs endpoint. */
filterGroup?: _LogPropertyFilterApi[]
+ /** Scope mining 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
+ /** Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string
}
export interface _LogsPatternsRequestApi {
@@ -2011,6 +2021,8 @@ export interface _LogsQueryBodyApi {
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
+ /** Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string
}
export interface _LogsQueryRequestApi {
@@ -2413,6 +2425,8 @@ export interface _LogsSparklineBodyApi {
sparklineRankBy?: SparklineRankByEnumApi
/** 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
+ /** Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string
}
export interface _LogsSparklineRequestApi {
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 185545c6db3d..97a3bb7e928e 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -864,6 +864,12 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope counts to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The facet values query to execute.'),
})
@@ -1007,6 +1013,18 @@ export const LogsGroupByCreateBody = /* @__PURE__ */ zod.object({
.max(logsGroupByCreateBodyQueryOneLimitMax)
.default(logsGroupByCreateBodyQueryOneLimitDefault)
.describe('Maximum number of groups to return (top-N by orderGroupsBy). Defaults to 100.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope grouping 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."
+ ),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope grouping to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The group-by query to execute.'),
})
@@ -1230,6 +1248,18 @@ export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining 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."
+ ),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The patterns query to execute.'),
})
@@ -1316,6 +1346,18 @@ export const LogsPatternsDiffCreateBody = /* @__PURE__ */ zod.object({
)
.optional()
.describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining 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."
+ ),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe(
'The patterns query for the current (foreground) window: date range plus any severity\/service\/search\/property filters. The same filters are applied to the baseline window.'
@@ -1456,6 +1498,12 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The logs query to execute.'),
})
@@ -1942,6 +1990,12 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The sparkline query to execute.'),
})
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.ts
index d0ed05e1719d..675db2c7e1c7 100644
--- a/products/logs/frontend/utils.test.ts
+++ b/products/logs/frontend/utils.test.ts
@@ -1,9 +1,5 @@
-import { UniversalFiltersGroup } from '~/types'
-
-import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS } from 'products/logs/frontend/logsConfigLogic'
-
import {
- buildLogsSessionFilters,
+ buildLogsSessionScope,
formatFilterGroupValues,
getDistinctIdWithKey,
getFiltersSummaryLines,
@@ -191,92 +187,24 @@ describe('logs utils', () => {
})
})
- describe('buildLogsSessionFilters', () => {
- // Byte-for-byte SESSION_ID_KEYS from utils.tsx. Spelled out rather than imported so a
- // silent edit to that list shows up here as a failing assertion.
- const CONVENTION_KEYS = [
- 'session.id',
- 'session_id',
- 'sessionId',
- 'sessionID',
- '$session_id',
- 'posthogSessionId',
- 'posthogSessionID',
- 'posthog_session_id',
- 'posthog.session.id',
- 'posthog.session_id',
- ]
-
- // Keys of the log-attribute filters only. Every key also gets a resource-attribute
- // twin, asserted separately below.
- const filterKeys = (configuredKeys?: string[]): string[] => {
- const innerGroup = buildLogsSessionFilters('sess-1', configuredKeys).filterGroup!
- .values[0] as UniversalFiltersGroup
- expect(innerGroup.type).toBe('OR')
- return (innerGroup.values as { key: string; type: string }[])
- .filter((filter) => filter.type === 'log_attribute')
- .map((filter) => filter.key)
- }
-
- it.each([
- ['no configured keys', undefined],
- ['empty configured list', []],
- ])('%s queries the built-in conventions', (_, configuredKeys) => {
- expect(filterKeys(configuredKeys)).toEqual(CONVENTION_KEYS)
- })
-
- it('puts configured keys first, then the conventions, deduped', () => {
- // `sessionId` is configured and a convention: it keeps its configured position
- // and is not repeated.
- expect(filterKeys(['custom.key', 'sessionId'])).toEqual([
- 'custom.key',
- 'sessionId',
- ...CONVENTION_KEYS.filter((key) => key !== 'sessionId'),
- ])
- })
-
- it('queries the shipped default, which must be one of the conventions', () => {
- // buildLogsSessionFilters queries the conventions, not the default, so a default
- // outside this list would go unqueried for a team that never edited it.
- expect(CONVENTION_KEYS).toEqual(expect.arrayContaining(DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS))
- })
-
- it('queries sessionId for a team whose stored config is the old posthogSessionId default', () => {
- // Every team created before the default changed has `posthogSessionId` materialised.
- // The conventions union is what keeps their session link resolving SDK logs.
- expect(filterKeys(['posthogSessionId'])).toContain('sessionId')
- })
-
- it('queries each key as both a log attribute and a resource attribute', () => {
- // A log carrying the session id only under resource_attributes still renders the
- // session link, so View Logs has to match that map too.
- const filters = buildLogsSessionFilters('sess-1', ['custom.key'])
-
- const innerGroup = filters.filterGroup!.values[0] as UniversalFiltersGroup
- expect(innerGroup.values.slice(0, 2)).toEqual([
- { key: 'custom.key', value: ['sess-1'], operator: 'exact', type: 'log_attribute' },
- { key: 'custom.key', value: ['sess-1'], operator: 'exact', type: 'log_resource_attribute' },
- ])
- expect(filters.dateRange).toBeUndefined()
- })
-
- it('pairs every queried key across both maps', () => {
- const innerGroup = buildLogsSessionFilters('sess-1', ['custom.key']).filterGroup!
- .values[0] as UniversalFiltersGroup
- const values = innerGroup.values as { key: string; type: string }[]
- const keysByType = (type: string): string[] =>
- values.filter((filter) => filter.type === type).map((filter) => filter.key)
-
- expect(keysByType('log_resource_attribute')).toEqual(keysByType('log_attribute'))
- })
-
+ describe('buildLogsSessionScope', () => {
it('scopes the date range around the timestamp', () => {
- const filters = buildLogsSessionFilters('sess-1', undefined, '2026-03-24T12:00:00.000Z')
- expect(filters.dateRange).toEqual({
- date_from: '2026-03-24T11:30:00.000Z',
- date_to: '2026-03-24T12:30:00.000Z',
+ // Without a window the viewer's default range (last hour) hides any session older
+ // than that, which is most sessions reached from an error.
+ expect(buildLogsSessionScope('sess-1', '2026-03-24T12:00:00.000Z')).toEqual({
+ sessionId: 'sess-1',
+ initialFilters: {
+ dateRange: {
+ date_from: '2026-03-24T11:30:00.000Z',
+ date_to: '2026-03-24T12:30:00.000Z',
+ },
+ },
})
})
+
+ it('leaves the range alone without a timestamp', () => {
+ expect(buildLogsSessionScope('sess-1')).toEqual({ sessionId: 'sess-1', initialFilters: undefined })
+ })
})
const filterGroup = (
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 8f77675fbf41..4453159f2d18 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -3,7 +3,7 @@ import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'
import { dayjs } from 'lib/dayjs'
import { capitalizeFirstLetter } from 'lib/utils/strings'
-import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
+import { AnyPropertyFilter, PropertyOperator } from '~/types'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
import {
@@ -237,48 +237,20 @@ export function buildDateRangeAround(timestamp: string, windowMinutes: number):
}
}
-// Builds logs viewer filters scoped to one session, for other products surfacing logs
-// (error tracking, session replay). Filters (OR across keys, exact match) on the team's
-// configured session ID keys plus the SESSION_ID_KEYS conventions, deduped, configured
-// first — the same breadth `getSessionIdWithKey` resolves, so a team whose stored key their
-// pipeline never emits still matches. Literal keys only: an exact filter can't express the
-// dot-suffix variants `matchesKey` allows. A timestamp scopes the date range to ±30 minutes
-// so old sessions aren't hidden by the default range.
-export function buildLogsSessionFilters(
+// Builds the viewer scope for one session, for other products surfacing logs (error tracking,
+// session replay). The session id goes to the server as a scope rather than a filter group: it
+// has to match across every configured and conventional key in both attribute maps, and the
+// query runner reads a filter group's inner group as an AND of its leaves, so a group could only
+// ever express "every key holds this id at once". A timestamp scopes the date range to ±30
+// minutes so old sessions aren't hidden by the default range.
+export function buildLogsSessionScope(
sessionId: string,
- configuredKeys?: string[],
timestamp?: string
-): Partial<LogsViewerFilters> {
- const keys = Array.from(new Set([...(configuredKeys ?? []), ...SESSION_ID_KEYS]))
- const filters: Partial<LogsViewerFilters> = {
- filterGroup: {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.Or,
- // Each key is queried in both maps, because getSessionIdWithKey renders the
- // session link off attributes or resource_attributes. Person scoping resolves
- // distinct ids across both maps for the same reason.
- values: keys.flatMap((key) => [
- {
- key,
- value: [sessionId],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.LogAttribute,
- },
- {
- key,
- value: [sessionId],
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.LogResourceAttribute,
- },
- ]),
- },
- ],
- },
- }
- if (timestamp) {
- filters.dateRange = buildDateRangeAround(timestamp, SESSION_LOGS_WINDOW_MINUTES)
+): { sessionId: string; initialFilters?: Partial<LogsViewerFilters> } {
+ return {
+ sessionId,
+ initialFilters: timestamp
+ ? { dateRange: buildDateRangeAround(timestamp, SESSION_LOGS_WINDOW_MINUTES) }
+ : undefined,
}
- return filters
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b25b37d1c524..da4ac7b2f851 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -44249,6 +44249,8 @@ export namespace Schemas {
response?: LogsQueryResponse | null;
searchTerm?: string | null;
serviceNames: string[];
+ /** Show logs for a given session ID */
+ sessionId?: string | null;
severityLevels: LogSeverityLevel[];
/** Field to break down sparkline data by (used only by sparkline endpoint) */
sparklineBreakdownBy?: LogsSparklineBreakdownBy | null;
@@ -89097,6 +89099,8 @@ export namespace Schemas {
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;
+ /** Scope counts to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string;
}
export interface _LogsFacetValuesRequest {
@@ -89157,6 +89161,10 @@ export namespace Schemas {
* @maximum 500
*/
limit?: number;
+ /** Scope grouping 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;
+ /** Scope grouping to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string;
}
export interface _LogsGroupByGroup {
@@ -89199,6 +89207,10 @@ export namespace Schemas {
searchTerm?: string;
/** Property filters applied before mining. Same shape as the query-logs endpoint. */
filterGroup?: _LogPropertyFilter[];
+ /** Scope mining 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;
+ /** Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string;
}
export interface _LogsPatternsDiffRequest {
@@ -89285,6 +89297,8 @@ export namespace Schemas {
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;
+ /** Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string;
}
export interface _LogsQueryRequest {
@@ -89419,6 +89433,8 @@ export namespace Schemas {
sparklineRankBy?: SparklineRankByEnum;
/** 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;
+ /** Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes. */
+ sessionId?: string;
}
export interface _LogsSparklineBucket {
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index 524f97b7da97..e4a8b5af9728 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -5879,6 +5879,12 @@ export const LogsFacetValuesCreateBody = () => zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope counts to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The facet values query to execute.'),
})
@@ -5973,6 +5979,18 @@ export const LogsPatternsCreateBody = () => zod.object({
)
.optional()
.describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining 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."
+ ),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The patterns query to execute.'),
})
@@ -6067,6 +6085,18 @@ export const LogsPatternsDiffCreateBody = () => zod.object({
)
.optional()
.describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),
+ personId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining 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."
+ ),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe(
'The patterns query for the current (foreground) window: date range plus any severity\/service\/search\/property filters. The same filters are applied to the baseline window.'
@@ -6215,6 +6245,12 @@ export const LogsQueryCreateBody = () => zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.describe('The logs query to execute.'),
})
@@ -6442,6 +6478,12 @@ export const LogsSparklineCreateBody = () => zod.object({
.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."
),
+ sessionId: zod
+ .string()
+ .optional()
+ .describe(
+ "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes."
+ ),
})
.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 211431ec6695..becb21905b47 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
@@ -131,6 +131,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Scope counts to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes.",
+ "type": "string"
+ },
"severityLevels": {
"description": "Filter by log severity levels (ignored when faceting on severity_text).",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json
index 2203186b720b..13756f056284 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns-diff.json
@@ -105,6 +105,10 @@
},
"type": "array"
},
+ "personId": {
+ "description": "Scope mining 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 before mining.",
"type": "string"
@@ -116,6 +120,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes.",
+ "type": "string"
+ },
"severityLevels": {
"description": "Filter by log severity levels before mining.",
"items": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json
index 925486bc0d80..bf869cb0324a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-patterns.json
@@ -77,6 +77,10 @@
},
"type": "array"
},
+ "personId": {
+ "description": "Scope mining 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 before mining.",
"type": "string"
@@ -88,6 +92,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Scope mining to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes.",
+ "type": "string"
+ },
"severityLevels": {
"description": "Filter by log severity levels before mining.",
"items": {
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 d29bc9bcc911..bbcf70a06b2d 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
@@ -94,6 +94,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes.",
+ "type": "string"
+ },
"severityLevels": {
"default": [],
"description": "Filter by log severity levels.",
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 9306f5d53249..842314a67023 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
@@ -121,6 +121,10 @@
},
"type": "array"
},
+ "sessionId": {
+ "description": "Scope results to one session ID. Matched server-side against the team's configured session-id log attribute keys plus the built-in conventions, in both log attributes and resource attributes.",
+ "type": "string"
+ },
"severityLevels": {
"default": [],
"description": "Filter by log severity levels.",