:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): add drill-down to the impact strip (#95439)
Jimmy Zhu299f0a3ae642
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8ca28b025664..8925eb43d220 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8197,17 +8197,17 @@ snapshots:scenes-app-logs-logsimpactcounts--no-coverage--light:hash: v1.k794b7964.dd17052cb0d5b98b9e6a3752b5cbb0905fd329b9216ddff2c333d8c6c16a2089.5Eis2dr7kHU9l1aEaq3KoHucDwMHubv-EVU9_pSNiAMscenes-app-logs-logsimpactcounts--partial-coverage--dark:- hash: v1.k794b7964.55b48e5d94d7e675e57f939f596ad6316864f42590640b04c97847beb1a0a0c5.EvXzAP9FbzCgvJeTsIMyrqKbSSHkWhYLBipvYpfbGkU+ hash: v1.k794b7964.bec2b97c41b6f47c056824bb4524c070062dad3f0cdcac7fcc0094e3b5380b7e.3dJ36eBpB7GT5ZE2MOzQdHB3Xq4MAekSLCAOgdw3uWYscenes-app-logs-logsimpactcounts--partial-coverage--light:- hash: v1.k794b7964.7f25e2bc909d3e58aaa1d7a7c6e1e49ac51567b1bb0a42a3727719b2bea02e57.EjtOwlP29HI8Q-6sS5esZEqyE9P8c29-RIiKZOC1Rck+ hash: v1.k794b7964.ee37e4228b8c9516e040a9796831b21eb6f83bd35c71b343e9c241d89ddbce36.GTxh2qViKyYCl-GZH67gM857UUojdhuHWJxioN3KgIEscenes-app-logs-logsimpactcounts--sessions-and-users--dark:- hash: v1.k794b7964.2aac72e80931e82eb128b6a035006761f485cdfb622b43dfd4c5168e8a1c7240.em4Uu3qSdFCAhTIUvUp__WUIiX1jia_m0gZIomVUuRQ+ hash: v1.k794b7964.741d151cb96e4d19030c71227eeca31b151ab671f263ef2fb9995b83619bef03.YVreTAjH8X1bgCu79Mpkc-73BASW2S5G6HDw4pT5cUIscenes-app-logs-logsimpactcounts--sessions-and-users--light:- hash: v1.k794b7964.a61ee82841da4d833362b1bf374542cc1abadf50f448ca6f34a63d0b806e7d8e.qwpRO7F4RvQmWhQGhWB7YzHa2Ikg2pPm9ec7Y5ZV4TI+ hash: v1.k794b7964.3ec41e5ef8fb64630308fa7e879fc4c51b4f50146a265d085a5eb5f9e1e58519.MD6oLpWOh1ZZ39h1HCJQRzcKkr_YvyoyFHj4A6OdE78scenes-app-logs-logsimpactcounts--sessions-only--dark:- hash: v1.k794b7964.35d3511b15e9d3aae36c5b8c134fd2fd0984883b2436459dabba605c6b75e6e3.y0RVoMB5HmmmOQv5GD99RYB9APZEnVLqIRKtob_Utw0+ hash: v1.k794b7964.b8c44f66626ff2d35a9a566c58337683e9ade9433d135be7f8bb4b17e338aa09.7bPm3c8fFjrHeUafx8VSL7V8MoY0Pu3_ayEeP_YTbBQscenes-app-logs-logsimpactcounts--sessions-only--light:- hash: v1.k794b7964.4677a4785f1b026a7ee46ab105b05e4862768c39a41c84c41fc192523a5237ae.7NPAF-5cgNNIGaM6yavgjc990AB-UAplqFK_6V4eTes+ hash: v1.k794b7964.1df982f4a9a5e13533ba18e16809fc68a44c64764aaf3713a8a7e98ab55e9b9b.1CPqsq76kdQ_uWZLQRqBLYswgFVx3N9_2mm6WN0mc_Mscenes-app-logs-sessionerrorsbadge--one-error--dark:hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.Zoa3-_zRiDxW2DVeBYD64fV80BWOtlngAzOqnRjMam8scenes-app-logs-sessionerrorsbadge--one-error--light:diff --git a/posthog/hogql/functions/aggregations.py b/posthog/hogql/functions/aggregations.pyindex 0eab266608d7..f96066d8d3ed 100644--- a/posthog/hogql/functions/aggregations.py+++ b/posthog/hogql/functions/aggregations.py@@ -174,7 +174,7 @@ HOGQL_AGGREGATIONS: dict[str, HogQLFunctionMeta] = {"avgWeighted": HogQLFunctionMeta("avgWeighted", 2, 2, aggregate=True),"avgWeightedIf": HogQLFunctionMeta("avgWeightedIf", 3, 3, aggregate=True),"avgArray": HogQLFunctionMeta("avgArrayOrNull", 1, 1, aggregate=True),- "topK": HogQLFunctionMeta("topK", 1, 1, min_params=1, max_params=1, aggregate=True),+ "topK": HogQLFunctionMeta("topK", 1, 1, min_params=1, max_params=3, aggregate=True),# "topKIf": HogQLFunctionMeta("topKIf", 2, 2, aggregate=True),# "topKWeighted": HogQLFunctionMeta("topKWeighted", 1, 1, aggregate=True),# "topKWeightedIf": HogQLFunctionMeta("topKWeightedIf", 2, 2, aggregate=True),diff --git a/products/logs/backend/impact_query_runner.py b/products/logs/backend/impact_query_runner.pyindex 7ed40ee4423a..4126f25dedb7 100644--- a/products/logs/backend/impact_query_runner.py+++ b/products/logs/backend/impact_query_runner.py@@ -1,4 +1,5 @@from functools import cached_property+from typing import NamedTuplefrom posthog.schema import CachedLogsQueryResponse, LogsQuery@@ -10,6 +11,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from products.logs.backend.group_by_query_runner import GroupByDimension, LogsGroupBySourcefrom products.logs.backend.logs_query_runner import (LogsQueryResponse,LogsQueryRunnerMixin,@@ -17,27 +19,95 @@ from products.logs.backend.logs_query_runner import ()from products.logs.backend.models import resolved_distinct_id_attribute_keys, resolved_session_id_attribute_keys+# Enough top values for a drill-down popover; the full distribution belongs to Group mode.+TOP_IDENTITY_VALUES = 5-def _identity_value_expr(attribute_keys: list[str]) -> ast.Expr:- # First non-empty value across the candidate keys, checking the log attributes before- # the resource attributes for each key — the same precedence getSessionIdWithKey applies- # in products/logs/frontend/utils.tsx, so the counts cover the logs the viewer renders- # as links. Both maps are read with a bare arrayElement: the property-resolver route- # wraps map reads in a has() guard that defeats the bucketed serialization and reads- # every key bucket (see group_by_query_runner._dimension_expr). attributes_map_str keys- # carry the ingestion MV's `__str` type suffix (posthog/clickhouse/logs/logs34.py);- # resource_attributes is a plain map with unsuffixed keys. A missing key reads as '',- # which nullIf scrubs to NULL so the aggregates can skip identity-less rows.- args: list[ast.Expr] = []++class _IdentityCandidate(NamedTuple):+ field: str+ map_key: str+ dimension: GroupByDimension+++def _identity_candidates(attribute_keys: list[str]) -> list[_IdentityCandidate]:+ # One candidate per (key, map), checking the log attributes before the resource+ # attributes for each key — the same precedence getSessionIdWithKey applies in+ # products/logs/frontend/utils.tsx, so the counts cover the logs the viewer renders+ # as links. attributes_map_str keys carry the ingestion MV's `__str` type suffix+ # (posthog/clickhouse/logs/logs34.py); resource_attributes is a plain map with+ # unsuffixed keys. The query reports a match by its position in this list, so the+ # order is a contract between the SQL and the response.+ candidates: list[_IdentityCandidate] = []for attribute_key in attribute_keys:- for field, key in (("attributes_map_str", f"{attribute_key}__str"), ("resource_attributes", attribute_key)):- read = ast.Call(name="arrayElement", args=[ast.Field(chain=[field]), ast.Constant(value=key)])- args.append(ast.Call(name="nullIf", args=[read, ast.Constant(value="")]))- return ast.Call(name="coalesce", args=args)+ candidates.append(+ _IdentityCandidate(+ field="attributes_map_str",+ map_key=f"{attribute_key}__str",+ dimension=GroupByDimension(key=attribute_key, source=LogsGroupBySource.LOG.value),+ )+ )+ candidates.append(+ _IdentityCandidate(+ field="resource_attributes",+ map_key=attribute_key,+ dimension=GroupByDimension(key=attribute_key, source=LogsGroupBySource.RESOURCE.value),+ )+ )+ return candidates+++def _identity_read(candidate: _IdentityCandidate) -> ast.Expr:+ # Both maps are read with a bare arrayElement: the property-resolver route wraps map+ # reads in a has() guard that defeats the bucketed serialization and reads every key+ # bucket (see group_by_query_runner._dimension_expr). A missing key reads as '', which+ # nullIf scrubs to NULL so the aggregates can skip identity-less rows.+ read = ast.Call(+ name="arrayElement", args=[ast.Field(chain=[candidate.field]), ast.Constant(value=candidate.map_key)]+ )+ return ast.Call(name="nullIf", args=[read, ast.Constant(value="")])+++def _identity_value_expr(candidates: list[_IdentityCandidate]) -> ast.Expr:+ # First non-empty value across the candidates.+ return ast.Call(name="coalesce", args=[_identity_read(candidate) for candidate in candidates])+++def _identity_index_expr(candidates: list[_IdentityCandidate]) -> ast.Expr:+ # Position of the candidate the value expr matched, NULL when none matched. An integer+ # rather than the key itself, because naming the key in the row builds and hashes one+ # string per scanned row. The reads are the same expressions the value expr uses, so+ # ClickHouse evaluates each one once and the extra column adds nothing to the scan.+ args: list[ast.Expr] = []+ for index, candidate in enumerate(candidates):+ args.extend(+ [ast.Call(name="isNotNull", args=[_identity_read(candidate)]), ast.Constant(value=index)],+ )+ args.append(ast.Constant(value=None))+ return ast.Call(name="multiIf", args=args)+++def _top_values(entries: list[tuple] | None) -> list[dict]:+ # topK(..., 'counts') rows are (value, count, error) tuples; the error margin is+ # noise for a popover, so only value and count survive.+ return [{"value": value, "count": int(count)} for value, count, _error in entries or []]+++def _group_key(candidates: list[_IdentityCandidate], indexes: list[int] | None) -> dict | None:+ # The most frequent candidate position names the dimension that carries the counts.+ if not indexes:+ return None+ return candidates[indexes[0]].dimension._asdict()class ImpactQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):- """Counts the unique sessions and users behind the log entries matching the given filters."""+ """Counts the unique sessions and users behind the log entries matching the given filters.++ Kept as its own scan instead of folding into the sparkline query: the sparkline+ aggregates over toStartOfMinute(timestamp) so ClickHouse serves it from the+ minute-aggregate projection, and that projection does not carry the attribute maps+ the identity expressions read. A fold would push every sparkline onto a full scan,+ also for teams that have the impact strip flag off.+ """query: LogsQuerycached_response: CachedLogsQueryResponse@@ -49,6 +119,15 @@ class ImpactQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunner# window and re-runs against a mostly identical window on every filter tweak.return fail_fast_aggregate_settings(use_uncompressed_cache=True)+ @cached_property+ def _session_candidates(self) -> list[_IdentityCandidate]:+ # The query and the response index into the same list, and resolved_* reads Postgres.+ return _identity_candidates(resolved_session_id_attribute_keys(self.team))++ @cached_property+ def _person_candidates(self) -> list[_IdentityCandidate]:+ return _identity_candidates(resolved_distinct_id_attribute_keys(self.team))+def _calculate(self) -> LogsQueryResponse:response = execute_hogql_query(query_type="LogsQuery",@@ -60,21 +139,36 @@ class ImpactQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerlimit_context=self.limit_context,settings=self.settings,)- row = response.results[0] if response.results else (0, 0, 0, 0, 0)+ (+ total,+ logs_with_session_id,+ sessions,+ logs_with_distinct_id,+ users,+ top_sessions,+ top_users,+ session_indexes,+ person_indexes,+ ) = response.results[0] if response.results else (0, 0, 0, 0, 0, [], [], [], [])return LogsQueryResponse(results={- "total": row[0],- "logsWithSessionId": row[1],- "sessions": row[2],- "logsWithDistinctId": row[3],- "users": row[4],+ "total": total,+ "logsWithSessionId": logs_with_session_id,+ "sessions": sessions,+ "logsWithDistinctId": logs_with_distinct_id,+ "users": users,+ "topSessions": _top_values(top_sessions),+ "topUsers": _top_values(top_users),+ "sessionGroupKey": _group_key(self._session_candidates, session_indexes),+ "personGroupKey": _group_key(self._person_candidates, person_indexes),})def to_query(self) -> ast.SelectQuery:# uniq() is HLL-based and ~1-2% off vs exact count(DISTINCT) on high-cardinality# ids, but much cheaper — the same tradeoff the error tracking aggregates accept.- # count(x)/uniq(x) skip NULLs, so rows without an identity need no explicit predicate.+ # topK is approximate in the same way. count(x)/uniq(x)/topK(x) skip NULLs, so rows+ # without an identity need no explicit predicate and stay out of the top lists.query = parse_select("""SELECT@@ -82,17 +176,28 @@ class ImpactQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnercount(session_value) AS logs_with_session_id,uniq(session_value) AS sessions,count(person_value) AS logs_with_distinct_id,- uniq(person_value) AS users+ uniq(person_value) AS users,+ topK({top_n}, 3, 'counts')(session_value) AS top_sessions,+ topK({top_n}, 3, 'counts')(person_value) AS top_users,+ topK(1)(session_index) AS session_indexes,+ topK(1)(person_index) AS person_indexesFROM (- SELECT {session_value} AS session_value, {person_value} AS person_value+ SELECT+ {session_value} AS session_value,+ {person_value} AS person_value,+ {session_index} AS session_index,+ {person_index} AS person_indexFROM logsWHERE {where})""",placeholders={- "session_value": _identity_value_expr(resolved_session_id_attribute_keys(self.team)),- "person_value": _identity_value_expr(resolved_distinct_id_attribute_keys(self.team)),+ "session_value": _identity_value_expr(self._session_candidates),+ "person_value": _identity_value_expr(self._person_candidates),+ "session_index": _identity_index_expr(self._session_candidates),+ "person_index": _identity_index_expr(self._person_candidates),"where": self.where_with_timestamp_bounds(),+ "top_n": ast.Constant(value=TOP_IDENTITY_VALUES),},)assert isinstance(query, ast.SelectQuery)diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 138568cc5e71..ab00c4336e94 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -410,6 +410,21 @@ class _LogsImpactRequestSerializer(serializers.Serializer):)+class _LogsImpactTopValueSerializer(serializers.Serializer):+ value = serializers.CharField(help_text="The session ID or person distinct ID.")+ count = serializers.IntegerField(+ help_text="Approximate number of matching logs that carry this value (topK estimate)."+ )+++class _LogsImpactGroupKeySerializer(serializers.Serializer):+ source = serializers.ChoiceField( # type: ignore[assignment] # field named `source` shadows DRF Field.source+ choices=list(GROUP_SOURCES),+ help_text='Attribute map the key lives in, in the group-by endpoint\'s vocabulary: "log" or "resource".',+ )+ key = serializers.CharField(help_text="The attribute key that carries the ID on most matching logs.")++class _LogsImpactResponseSerializer(serializers.Serializer):total = serializers.IntegerField(help_text="Number of log entries matching the filters.")logsWithSessionId = serializers.IntegerField(@@ -424,6 +439,28 @@ class _LogsImpactResponseSerializer(serializers.Serializer):users = serializers.IntegerField(help_text="Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error).")+ topSessions = _LogsImpactTopValueSerializer(+ many=True,+ help_text="Top session IDs on the matching logs, ordered by log count descending (topK, at most 5).",+ )+ topUsers = _LogsImpactTopValueSerializer(+ many=True,+ help_text="Top person distinct IDs on the matching logs, ordered by log count descending (topK, at most 5).",+ )+ sessionGroupKey = _LogsImpactGroupKeySerializer(+ allow_null=True,+ help_text=(+ "The dimension that carries the session ID on most matching logs. Group by this dimension to "+ "drill into the sessions behind the counts. Null when no matching log carries a session ID."+ ),+ )+ personGroupKey = _LogsImpactGroupKeySerializer(+ allow_null=True,+ help_text=(+ "The dimension that carries the person distinct ID on most matching logs. Group by this dimension to "+ "drill into the users behind the counts. Null when no matching log carries a distinct ID."+ ),+ )class _LogFacetValueSerializer(serializers.Serializer):diff --git a/products/logs/backend/test/test_impact_api.py b/products/logs/backend/test/test_impact_api.pyindex bf6ba420240d..1b0e1adceb8e 100644--- a/products/logs/backend/test/test_impact_api.py+++ b/products/logs/backend/test/test_impact_api.py@@ -13,7 +13,17 @@ from products.logs.backend.models import TeamLogsConfig_FIXTURE_WINDOW = {"date_from": "2025-12-14T00:00:00Z", "date_to": "2025-12-19T00:00:00Z"}-_ZERO_IMPACT = {"total": 0, "logsWithSessionId": 0, "sessions": 0, "logsWithDistinctId": 0, "users": 0}+_ZERO_IMPACT = {+ "total": 0,+ "logsWithSessionId": 0,+ "sessions": 0,+ "logsWithDistinctId": 0,+ "users": 0,+ "topSessions": [],+ "topUsers": [],+ "sessionGroupKey": None,+ "personGroupKey": None,+}def _log_row(@@ -55,9 +65,10 @@ class TestImpactApi(ClickhouseTestMixin, APIBaseTest):super().setUpTestData()rows = [_log_row(cls.team.id, "checkout started", attributes={"sessionId": "s1", "posthogDistinctId": "u1"}),- _log_row(cls.team.id, "cart loaded", attributes={"sessionId": "s1"}),+ _log_row(cls.team.id, "cart loaded", attributes={"sessionId": "s1", "posthogDistinctId": "u1"}),_log_row(cls.team.id, "payment authorized", attributes={"session_id": "s2", "distinct_id": "u2"}),_log_row(cls.team.id, "receipt rendered", resource_attributes={"sessionId": "s3"}),+ _log_row(cls.team.id, "cache warmed", attributes={"sessionId": "s4"}),_log_row(cls.team.id, "upstream timed out", severity_text="error", severity_number=17),_log_row(cls.team.id, "inventory synced", attributes={"my_session": "s9"}),]@@ -78,19 +89,41 @@ class TestImpactApi(ClickhouseTestMixin, APIBaseTest):("full_window",_FIXTURE_WINDOW,- {"total": 6, "logsWithSessionId": 4, "sessions": 3, "logsWithDistinctId": 2, "users": 2},+ {+ "total": 7,+ "logsWithSessionId": 5,+ "sessions": 4,+ "topSessions": [+ {"value": "s1", "count": 2},+ {"value": "s2", "count": 1},+ {"value": "s3", "count": 1},+ {"value": "s4", "count": 1},+ ],+ "logsWithDistinctId": 3,+ "users": 2,+ "topUsers": [{"value": "u1", "count": 2}, {"value": "u2", "count": 1}],+ # Three rows carry `sessionId` in the log attributes; every other session+ # key appears once, so this is the dominant group-by dimension. Same+ # shape for `posthogDistinctId` on the person side.+ "sessionGroupKey": {"source": "log", "key": "sessionId"},+ "personGroupKey": {"source": "log", "key": "posthogDistinctId"},+ },),("empty_window", {"date_from": "2000-01-01T00:00:00Z", "date_to": "2000-01-02T00:00:00Z"}, _ZERO_IMPACT),])@freeze_time("2025-12-18T12:00:00Z")def test_impact_counts_identity_coverage(self, _name: str, date_range: dict, expected: dict) -> None:- self.assertEqual(self._impact({"dateRange": date_range}), expected)+ response = self._impact({"dateRange": date_range})+ # topK breaks count ties in an unspecified order, so only the value set is stable.+ for top_list in ("topSessions", "topUsers"):+ response[top_list] = sorted(response[top_list], key=lambda entry: entry["value"])+ self.assertEqual(response, expected)@freeze_time("2025-12-18T12:00:00Z")def test_impact_accepts_null_filter_lists(self) -> None:response = self._impact({"dateRange": _FIXTURE_WINDOW, "severityLevels": None, "serviceNames": None})- self.assertEqual(response["total"], 6)+ self.assertEqual(response["total"], 7)@freeze_time("2025-12-18T12:00:00Z")def test_impact_applies_filters(self) -> None:@@ -105,8 +138,8 @@ class TestImpactApi(ClickhouseTestMixin, APIBaseTest):team=self.team, defaults={"logs_session_id_attribute_keys": ["my_session"]})response = self._impact({"dateRange": _FIXTURE_WINDOW})- self.assertEqual(response["logsWithSessionId"], 5)- self.assertEqual(response["sessions"], 4)+ self.assertEqual(response["logsWithSessionId"], 6)+ self.assertEqual(response["sessions"], 5)def test_impact_rejects_non_object_query(self) -> None:response = self.client.post(f"/api/projects/{self.team.id}/logs/impact", data={"query": "not-an-object"})diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsxindex 609dad69ecc7..da61a97a99c6 100644--- a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx@@ -24,6 +24,17 @@ function makeImpact(overrides: Partial<_LogsImpactResponseApi> = {}): _LogsImpacsessions: 214,logsWithDistinctId: 9600,users: 96,+ topSessions: [+ { value: '01936d3a-5983-7e70-b287-2f21ab1a70c1', count: 3200 },+ { value: '01936d3a-72aa-7c3e-8f10-4a5f0d9be2d4', count: 1900 },+ { value: '01936d3a-9c41-7b52-a6e3-1d8c27f4e0b9', count: 450 },+ ],+ topUsers: [+ { value: '[email protected]', count: 4100 },+ { value: '[email protected]', count: 2600 },+ ],+ sessionGroupKey: { source: 'log', key: 'sessionId' },+ personGroupKey: { source: 'log', key: 'posthogDistinctId' },...overrides,}}diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsxindex 378717ee792f..696c6b319c4a 100644--- a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx@@ -1,19 +1,33 @@-import { Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonDropdown, Tooltip } from '@posthog/lemon-ui'+import ViewRecordingButton, {+ RecordingPlayerType,+ ViewRecordingButtonVariant,+} from 'lib/components/ViewRecordingButton/ViewRecordingButton'import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'-import type { _LogsImpactResponseApi } from 'products/logs/frontend/generated/api.schemas'+import type { _LogsImpactResponseApi, _LogsImpactTopValueApi } from 'products/logs/frontend/generated/api.schemas'export interface LogsImpactCountsProps {impact: _LogsImpactResponseApi+ /** Pivots the viewer to Group mode grouped by the dominant session ID key. */+ onGroupBySessions?: () => void+ /** Pivots the viewer to Group mode grouped by the dominant distinct ID key. */+ onGroupByUsers?: () => void}/*** Sessions and users behind a set of logs, with how much of the set carries each ID.* The coverage figure is load-bearing: a session count over 3% of the logs means- * something different from the same count over all of them.+ * something different from the same count over all of them. Each count opens a+ * popover with the top values behind it, linking into replay and person profiles.*/-export function LogsImpactCounts({ impact }: LogsImpactCountsProps): JSX.Element | null {+export function LogsImpactCounts({+ impact,+ onGroupBySessions,+ onGroupByUsers,+}: LogsImpactCountsProps): JSX.Element | null {if (impact.total === 0) {return null}@@ -41,26 +55,119 @@ export function LogsImpactCounts({ impact }: LogsImpactCountsProps): JSX.Elementreturn percentage(fraction, 0)}+ const sessionsCaption = `Estimated unique session IDs, by log count. ${percentOfLogs(+ impact.logsWithSessionId+ )} of the matching logs carry a session ID.`+ const usersCaption = `Estimated unique people, by log count. ${percentOfLogs(+ impact.logsWithDistinctId+ )} of the matching logs carry a distinct ID.`+return (- <span className="flex items-center gap-2 text-muted text-xs" data-attr="logs-impact-counts">+ <span className="flex items-center gap-1 text-muted text-xs" data-attr="logs-impact-counts">{impact.logsWithSessionId > 0 && (- <Tooltip- title={`Estimated unique session IDs on the matching logs. ${percentOfLogs(- impact.logsWithSessionId- )} of them carry a session ID.`}+ <LemonDropdown+ placement="bottom-start"+ closeOnClickInside={false}+ overlay={+ <TopValuesOverlay+ caption={sessionsCaption}+ entries={impact.topSessions ?? []}+ renderValue={(value) => (+ <ViewRecordingButton+ sessionId={value}+ openPlayerIn={RecordingPlayerType.Modal}+ label={value}+ variant={ViewRecordingButtonVariant.Link}+ checkRecordingExists+ data-attr="logs-impact-top-session"+ />+ )}+ onGroupBy={onGroupBySessions}+ groupByLabel="Group logs by session ID"+ groupByDataAttr="logs-impact-group-by-sessions"+ />+ }>- <span data-attr="logs-impact-sessions">{humanFriendlyLargeNumber(impact.sessions)} sessions</span>- </Tooltip>+ <LemonButton size="xsmall" data-attr="logs-impact-sessions" tooltip={sessionsCaption}>+ <span className="text-muted text-xs font-normal">+ {/* The changing number gets its own element: a bare changing text+ node beside siblings breaks under in-page translation. */}+ <span>{humanFriendlyLargeNumber(impact.sessions)}</span> sessions+ </span>+ </LemonButton>+ </LemonDropdown>)}{impact.logsWithDistinctId > 0 && (- <Tooltip- title={`Estimated unique people on the matching logs. ${percentOfLogs(- impact.logsWithDistinctId- )} of them carry a distinct ID.`}+ <LemonDropdown+ placement="bottom-start"+ closeOnClickInside={false}+ overlay={+ <TopValuesOverlay+ caption={usersCaption}+ entries={impact.topUsers ?? []}+ renderValue={(value) => (+ <span onClick={(e) => e.stopPropagation()}>+ <PersonDisplay person={{ distinct_id: value }} noEllipsis inline />+ </span>+ )}+ onGroupBy={onGroupByUsers}+ groupByLabel="Group logs by distinct ID"+ groupByDataAttr="logs-impact-group-by-users"+ />+ }>- <span data-attr="logs-impact-users">{humanFriendlyLargeNumber(impact.users)} users</span>- </Tooltip>+ <LemonButton size="xsmall" data-attr="logs-impact-users" tooltip={usersCaption}>+ <span className="text-muted text-xs font-normal">+ <span>{humanFriendlyLargeNumber(impact.users)}</span> users+ </span>+ </LemonButton>+ </LemonDropdown>)}</span>)}++interface TopValuesOverlayProps {+ caption: string+ entries: _LogsImpactTopValueApi[]+ renderValue: (value: string) => JSX.Element+ onGroupBy?: () => void+ groupByLabel: string+ groupByDataAttr: string+}++/** Top identity values behind one impact count, each with its approximate log count. */+function TopValuesOverlay({+ caption,+ entries,+ renderValue,+ onGroupBy,+ groupByLabel,+ groupByDataAttr,+}: TopValuesOverlayProps): JSX.Element {+ return (+ <div className="flex flex-col gap-1 p-1 max-w-160">+ <span className="text-muted text-xs">{caption}</span>+ {entries.map(({ value, count }) => (+ <div key={value} className="flex items-center justify-between gap-4 text-xs">+ <span className="font-mono truncate">{renderValue(value)}</span>+ <span className="text-muted whitespace-nowrap">+ <span>{humanFriendlyLargeNumber(count)}</span> logs+ </span>+ </div>+ ))}+ {onGroupBy && (+ <LemonButton+ size="xsmall"+ type="secondary"+ fullWidth+ center+ onClick={onGroupBy}+ data-attr={groupByDataAttr}+ >+ {groupByLabel}+ </LemonButton>+ )}+ </div>+ )+}diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsxindex 3810c6336683..3c17d3e94415 100644--- a/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx@@ -1,4 +1,4 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { LogsImpactCounts } from './LogsImpactCounts'import { logsImpactLogic } from './logsImpactLogic'@@ -13,10 +13,21 @@ export interface LogsImpactStripProps {*/export function LogsImpactStrip({ id }: LogsImpactStripProps): JSX.Element | null {const { impact } = useValues(logsImpactLogic({ id }))+ const { pivotToGroupBy } = useActions(logsImpactLogic({ id }))if (!impact) {return null}- return <LogsImpactCounts impact={impact} />+ // The backend names the dimension carrying the ID on most matching logs, so the pivot groups+ // by the key the data uses. It names none when no matching log carries that ID at all.+ const { sessionGroupKey, personGroupKey } = impact++ return (+ <LogsImpactCounts+ impact={impact}+ onGroupBySessions={sessionGroupKey ? () => pivotToGroupBy(sessionGroupKey) : undefined}+ onGroupByUsers={personGroupKey ? () => pivotToGroupBy(personGroupKey) : undefined}+ />+ )}diff --git a/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts b/products/logs/frontend/components/LogsViewer/logsImpactLogic.tsindex 90cf620b0b23..b8976f401eb9 100644--- a/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts+++ b/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts@@ -1,10 +1,15 @@-import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'import { loaders } from 'kea-loaders'import { teamLogic } from 'scenes/teamLogic'import { UniversalFiltersGroup } from '~/types'+import {+ LogsViewerGroupBy,+ LogsViewerViewMode,+ logsViewerConfigLogic,+} from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { logsImpactCreate } from 'products/logs/frontend/generated/api'@@ -21,6 +26,7 @@ export interface logsImpactLogicValues {personId: string | undefined // logsViewerFiltersLogicqueryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogicsearchTerm: LogsQuery[] // logsViewerFiltersLogic+ sessionId: string | undefined // logsViewerFiltersLogicutcDateRange: {date_from: string | null | undefineddate_to: string | null | undefined@@ -33,6 +39,12 @@ export interface logsImpactLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsImpactLogicActions {+ setGroupBys: (groupBys: LogsViewerGroupBy[]) => {+ groupBys: LogsViewerGroupBy[]+ } // logsViewerConfigLogic+ setViewMode: (viewMode: LogsViewerViewMode) => {+ viewMode: LogsViewerViewMode+ } // logsViewerConfigLogicrunQuery: (debounce?: number | undefined) => {debounce: number | undefined} // logsViewerDataLogic@@ -51,6 +63,9 @@ export interface logsImpactLogicActions {impact: _LogsImpactResponseApi | nullpayload?: any}+ pivotToGroupBy: (dimension: LogsViewerGroupBy) => {+ dimension: LogsViewerGroupBy+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -72,21 +87,29 @@ export const logsImpactLogic = kea<logsImpactLogicType>([connect(({ id }: LogsImpactLogicProps) => ({values: [logsViewerFiltersLogic({ id }),- ['utcDateRange', 'queryFilterGroup', 'searchTerm', 'personId'],+ ['utcDateRange', 'queryFilterGroup', 'searchTerm', 'personId', 'sessionId'],teamLogic,['currentTeamId'],],- actions: [logsViewerDataLogic({ id }), ['runQuery']],+ actions: [+ logsViewerDataLogic({ id }),+ ['runQuery'],+ logsViewerConfigLogic({ id }),+ ['setViewMode', 'setGroupBys'],+ ],})),+ actions({+ pivotToGroupBy: (dimension: LogsViewerGroupBy) => ({ dimension }),+ }),loaders(({ cache, values }) => ({impact: [null as _LogsImpactResponseApi | null,{loadImpact: async (_, breakpoint) => {- // The person Logs tab pins a person scope that the impact query does not- // carry, so its counts would cover the whole project. Skip the query;- // `impact` stays null and the strip renders nothing.- if (values.personId) {+ // Person- and session-scoped viewers pin a scope that the impact query+ // does not carry, so its counts would cover the whole project. Skip the+ // query; `impact` stays null and the strip renders nothing.+ if (values.personId || values.sessionId) {return null}await breakpoint(300)@@ -134,6 +157,12 @@ export const logsImpactLogic = kea<logsImpactLogicType>([// the query rather than coupling to the sparkline loader's schedule. Bursts (typing)// collapse in loadImpact's own breakpoint.runQuery: () => actions.loadImpact(null),+ // Set the dimension before the view mode: logsGroupByLogic mounts with Group view and+ // loads on mount, so switching first would run a query against the old group-bys.+ pivotToGroupBy: ({ dimension }) => {+ actions.setGroupBys([dimension])+ actions.setViewMode('group')+ },})),afterMount(({ actions }) => {// The data logic usually mounts (and fires its initial runQuery) before this logicdiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex e03bfea7f7f7..2ddfc18fa0db 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1764,6 +1764,24 @@ export interface _LogsImpactRequestApi {query: _LogsCountBodyApi}+export interface _LogsImpactTopValueApi {+ /** The session ID or person distinct ID. */+ value: string+ /** Approximate number of matching logs that carry this value (topK estimate). */+ count: number+}++export interface _LogsImpactGroupKeyApi {+ /** Attribute map the key lives in, in the group-by endpoint's vocabulary: "log" or "resource".+ *+ * * `log` - log+ * * `resource` - resource+ * * `column` - column */+ source: LogsGroupBySourceEnumApi+ /** The attribute key that carries the ID on most matching logs. */+ key: string+}+export interface _LogsImpactResponseApi {/** Number of log entries matching the filters. */total: number@@ -1775,6 +1793,14 @@ export interface _LogsImpactResponseApi {logsWithDistinctId: number/** Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error). */users: number+ /** Top session IDs on the matching logs, ordered by log count descending (topK, at most 5). */+ topSessions: _LogsImpactTopValueApi[]+ /** Top person distinct IDs on the matching logs, ordered by log count descending (topK, at most 5). */+ topUsers: _LogsImpactTopValueApi[]+ /** The dimension that carries the session ID on most matching logs. Group by this dimension to drill into the sessions behind the counts. Null when no matching log carries a session ID. */+ sessionGroupKey: _LogsImpactGroupKeyApi | null+ /** The dimension that carries the person distinct ID on most matching logs. Group by this dimension to drill into the users behind the counts. Null when no matching log carries a distinct ID. */+ personGroupKey: _LogsImpactGroupKeyApi | null}export interface LogsMetricRuleApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex acb711ceeec5..a2fce34e46f7 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90783,11 +90783,29 @@ export namespace Schemas {truncated: boolean;}+ export interface _LogsImpactGroupKey {+ /** Attribute map the key lives in, in the group-by endpoint's vocabulary: "log" or "resource".+ *+ * * `log` - log+ * * `resource` - resource+ * * `column` - column */+ source: LogsGroupBySourceEnum;+ /** The attribute key that carries the ID on most matching logs. */+ key: string;+ }+export interface _LogsImpactRequest {/** The impact query to execute. Takes the same filters as the count query. */query: _LogsCountBody;}+ export interface _LogsImpactTopValue {+ /** The session ID or person distinct ID. */+ value: string;+ /** Approximate number of matching logs that carry this value (topK estimate). */+ count: number;+ }+export interface _LogsImpactResponse {/** Number of log entries matching the filters. */total: number;@@ -90799,6 +90817,14 @@ export namespace Schemas {logsWithDistinctId: number;/** Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error). */users: number;+ /** Top session IDs on the matching logs, ordered by log count descending (topK, at most 5). */+ topSessions: _LogsImpactTopValue[];+ /** Top person distinct IDs on the matching logs, ordered by log count descending (topK, at most 5). */+ topUsers: _LogsImpactTopValue[];+ /** The dimension that carries the session ID on most matching logs. Group by this dimension to drill into the sessions behind the counts. Null when no matching log carries a session ID. */+ sessionGroupKey: _LogsImpactGroupKey | null;+ /** The dimension that carries the person distinct ID on most matching logs. Group by this dimension to drill into the users behind the counts. Null when no matching log carries a distinct ID. */+ personGroupKey: _LogsImpactGroupKey | null;}export interface _LogsPatternsBody {