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.

feat(logs): show sessions and users behind the current log query (#94707)

Jimmy Zhuee82ca78e9f1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5cb4dbdcd930..1e4496d18324 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7924,6 +7924,22 @@ snapshots:
hash: v1.k794b7964.195aa4a5a39e8f947e17fe67f5c23303b7dd0579c278907761be24a08780be92.t2Zgr2Pj-cL6F6Xx11DpcCyR1L0QQ8fD17WzQNmXbw8
scenes-app-llm-observability-evaluationreportconfig--quill--light:
hash: v1.k794b7964.e6179df07dd55d64e0140d40ac812feb4662e28e5bded7ce2cf9e2575f245626.4iGTruUDV858d17xZIUMJCG2xFeWLagkzakPS2Yw4Ps
+ scenes-app-logs-logsimpactcounts--no-coverage--dark:
+ hash: v1.k794b7964.fcfa5be29c5721d0db9fa21ecab20f16c04a4074c9af7fb3a58311900e168a48.2eslY8aigbAuKJ2Bsn8AjSOah5Q77FoWONVdG2fb6C4
+ scenes-app-logs-logsimpactcounts--no-coverage--light:
+ hash: v1.k794b7964.dd17052cb0d5b98b9e6a3752b5cbb0905fd329b9216ddff2c333d8c6c16a2089.5Eis2dr7kHU9l1aEaq3KoHucDwMHubv-EVU9_pSNiAM
+ scenes-app-logs-logsimpactcounts--partial-coverage--dark:
+ hash: v1.k794b7964.55b48e5d94d7e675e57f939f596ad6316864f42590640b04c97847beb1a0a0c5.EvXzAP9FbzCgvJeTsIMyrqKbSSHkWhYLBipvYpfbGkU
+ scenes-app-logs-logsimpactcounts--partial-coverage--light:
+ hash: v1.k794b7964.7f25e2bc909d3e58aaa1d7a7c6e1e49ac51567b1bb0a42a3727719b2bea02e57.EjtOwlP29HI8Q-6sS5esZEqyE9P8c29-RIiKZOC1Rck
+ scenes-app-logs-logsimpactcounts--sessions-and-users--dark:
+ hash: v1.k794b7964.2aac72e80931e82eb128b6a035006761f485cdfb622b43dfd4c5168e8a1c7240.em4Uu3qSdFCAhTIUvUp__WUIiX1jia_m0gZIomVUuRQ
+ scenes-app-logs-logsimpactcounts--sessions-and-users--light:
+ hash: v1.k794b7964.a61ee82841da4d833362b1bf374542cc1abadf50f448ca6f34a63d0b806e7d8e.qwpRO7F4RvQmWhQGhWB7YzHa2Ikg2pPm9ec7Y5ZV4TI
+ scenes-app-logs-logsimpactcounts--sessions-only--dark:
+ hash: v1.k794b7964.35d3511b15e9d3aae36c5b8c134fd2fd0984883b2436459dabba605c6b75e6e3.y0RVoMB5HmmmOQv5GD99RYB9APZEnVLqIRKtob_Utw0
+ scenes-app-logs-logsimpactcounts--sessions-only--light:
+ hash: v1.k794b7964.4677a4785f1b026a7ee46ab105b05e4862768c39a41c84c41fc192523a5237ae.7NPAF-5cgNNIGaM6yavgjc990AB-UAplqFK_6V4eTes
scenes-app-logs-sparkline--volume-by-severity--dark:
hash: v1.k794b7964.0342a42ad3e96fb82282914a3c60aedb873de9f8dfc94c850b22b3f7f17d56a0.c_sYZ1aNex35E-5hGq0aHwwV1MQCROpZBvMfAznRPoY
scenes-app-logs-sparkline--volume-by-severity--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a4ddafc081f2..48b2d77e1626 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -370,6 +370,7 @@ export const FEATURE_FLAGS = {
LLM_OBSERVABILITY_TRACE_SEARCH: 'llm-observability-trace-search', // owner: #team-ai-observability
LOGS: 'logs', // owner: #team-logs
LOGS_ANOMALIES: 'logs-anomalies', // owner: @jonmcwest #team-logs
+ LOGS_IMPACT_STRIP: 'logs-impact-strip', // owner: #team-logs
LOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logs
LOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logs
LOGS_SERVICES_VIEW_V2: 'logs-services-view-v2', // owner: #team-logs
diff --git a/products/logs/backend/count_query_runner.py b/products/logs/backend/count_query_runner.py
index 17003a1a6819..6567aac70c42 100644
--- a/products/logs/backend/count_query_runner.py
+++ b/products/logs/backend/count_query_runner.py
@@ -4,13 +4,17 @@ from posthog.schema import CachedLogsQueryResponse, LogsQuery
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
-from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
-from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixin
+from products.logs.backend.logs_query_runner import (
+ LogsQueryResponse,
+ LogsQueryRunnerMixin,
+ fail_fast_aggregate_settings,
+)
class CountQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):
@@ -21,13 +25,7 @@ class CountQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerM
@cached_property
def settings(self) -> HogQLGlobalSettings:
- # A count should fail fast rather than scan unbounded data. Matches the
- # caps AlertCheckQuery uses against the same table.
- return HogQLGlobalSettings(
- max_execution_time=30,
- max_bytes_to_read=10_000_000_000,
- read_overflow_mode="throw",
- )
+ return fail_fast_aggregate_settings()
def _calculate(self) -> LogsQueryResponse:
response = execute_hogql_query(
@@ -44,25 +42,9 @@ class CountQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerM
return LogsQueryResponse(results={"count": count})
def to_query(self) -> ast.SelectQuery:
- # LogsFilterBuilder.where() filters by toStartOfDay(time_bucket) which is
- # day-precision; adding explicit per-row timestamp bounds (half-open to
- # avoid double-counting on boundaries) makes the count match the requested
- # window. Same pattern as AlertCheckQuery.
- where_with_timestamp = ast.And(
- exprs=[
- self.where(),
- parse_expr(
- "timestamp >= {date_from} AND timestamp < {date_to}",
- placeholders={
- "date_from": ast.Constant(value=self.query_date_range.date_from()),
- "date_to": ast.Constant(value=self.query_date_range.date_to()),
- },
- ),
- ]
- )
query = parse_select(
"SELECT count() FROM logs WHERE {where}",
- placeholders={"where": where_with_timestamp},
+ placeholders={"where": self.where_with_timestamp_bounds()},
)
assert isinstance(query, ast.SelectQuery)
return query
diff --git a/products/logs/backend/count_ranges_query_runner.py b/products/logs/backend/count_ranges_query_runner.py
index 9e3382e3e3c2..3223810ed2b7 100644
--- a/products/logs/backend/count_ranges_query_runner.py
+++ b/products/logs/backend/count_ranges_query_runner.py
@@ -5,13 +5,17 @@ from posthog.schema import CachedLogsQueryResponse, LogsQuery
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
-from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import Workload
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
-from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixin
+from products.logs.backend.logs_query_runner import (
+ LogsQueryResponse,
+ LogsQueryRunnerMixin,
+ fail_fast_aggregate_settings,
+)
DEFAULT_TARGET_BUCKETS = 10
MAX_TARGET_BUCKETS = 100
@@ -40,11 +44,7 @@ class CountRangesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
@cached_property
def settings(self) -> HogQLGlobalSettings:
- return HogQLGlobalSettings(
- max_execution_time=30,
- max_bytes_to_read=1_000_000_000,
- read_overflow_mode="throw",
- )
+ return fail_fast_aggregate_settings(max_bytes_to_read=1_000_000_000)
def _calculate(self) -> LogsQueryResponse:
response = execute_hogql_query(
@@ -93,22 +93,6 @@ class CountRangesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
return f"{count}m"
def to_query(self) -> ast.SelectQuery:
- # LogsFilterBuilder.where() filters by toStartOfDay(time_bucket) which is
- # day-precision; explicit per-row timestamp bounds (half-open) align the
- # group counts with the requested window. Same pattern as CountQueryRunner.
- where_with_timestamp = ast.And(
- exprs=[
- self.where(),
- parse_expr(
- "timestamp >= {date_from} AND timestamp < {date_to}",
- placeholders={
- "date_from": ast.Constant(value=self.query_date_range.date_from()),
- "date_to": ast.Constant(value=self.query_date_range.date_to()),
- },
- ),
- ]
- )
-
query = parse_select(
"""
SELECT
@@ -122,7 +106,7 @@ class CountRangesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
""",
placeholders={
**self.query_date_range.to_placeholders(),
- "where": where_with_timestamp,
+ "where": self.where_with_timestamp_bounds(),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/logs/backend/impact_query_runner.py b/products/logs/backend/impact_query_runner.py
new file mode 100644
index 000000000000..7ed40ee4423a
--- /dev/null
+++ b/products/logs/backend/impact_query_runner.py
@@ -0,0 +1,99 @@
+from functools import cached_property
+
+from posthog.schema import CachedLogsQueryResponse, LogsQuery
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+
+from products.logs.backend.logs_query_runner import (
+ LogsQueryResponse,
+ LogsQueryRunnerMixin,
+ fail_fast_aggregate_settings,
+)
+from products.logs.backend.models import resolved_distinct_id_attribute_keys, resolved_session_id_attribute_keys
+
+
+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] = []
+ 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)
+
+
+class ImpactQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):
+ """Counts the unique sessions and users behind the log entries matching the given filters."""
+
+ query: LogsQuery
+ cached_response: CachedLogsQueryResponse
+
+ @cached_property
+ def settings(self) -> HogQLGlobalSettings:
+ # Fail-fast caps like CountQueryRunner, plus the uncompressed block cache: unlike a
+ # bare count, this query decompresses the two attribute-map columns over the whole
+ # window and re-runs against a mostly identical window on every filter tweak.
+ return fail_fast_aggregate_settings(use_uncompressed_cache=True)
+
+ def _calculate(self) -> LogsQueryResponse:
+ response = execute_hogql_query(
+ query_type="LogsQuery",
+ query=self.to_query(),
+ modifiers=self.modifiers,
+ team=self.team,
+ workload=Workload.LOGS,
+ timings=self.timings,
+ limit_context=self.limit_context,
+ settings=self.settings,
+ )
+ row = 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],
+ }
+ )
+
+ 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.
+ query = parse_select(
+ """
+ SELECT
+ count() AS total,
+ count(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
+ FROM (
+ SELECT {session_value} AS session_value, {person_value} AS person_value
+ FROM logs
+ WHERE {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)),
+ "where": self.where_with_timestamp_bounds(),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index 63ad6457cb1a..3f906a38c00c 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -33,13 +33,7 @@ from posthog.models.person.util import get_person_by_pk_or_uuid
from posthog.personhog_client.caller_tag import personhog_caller_tag
from products.logs.backend.column_expressions import canonical_key, column_to_expr
-from products.logs.backend.models import (
- DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS,
- DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,
- DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS,
- SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS,
- TeamLogsConfig,
-)
+from products.logs.backend.models import resolved_distinct_id_attribute_keys, resolved_session_id_attribute_keys
if TYPE_CHECKING:
from posthog.models import Team, User
@@ -533,10 +527,6 @@ class LogsFilterBuilder:
return ast.And(exprs=exprs)
- @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
@@ -586,15 +576,11 @@ class LogsFilterBuilder:
# 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]))
+ # Scope on the configured keys plus 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.
+ attribute_keys = resolved_distinct_id_attribute_keys(self.team)
return self._attribute_scope_expr(attribute_keys, list(distinct_ids))
def _session_scope_expr(self) -> ast.Expr:
@@ -607,15 +593,10 @@ class LogsFilterBuilder:
# 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
+ # Configured keys plus 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]))
+ attribute_keys = resolved_session_id_attribute_keys(self.team)
return self._attribute_scope_expr(attribute_keys, [session_id])
def resource_filter(self, *, existing_filters):
@@ -650,6 +631,25 @@ class LogsFilterBuilder:
return ast.Constant(value=1)
+def fail_fast_aggregate_settings(
+ max_bytes_to_read: int = 10_000_000_000, *, use_uncompressed_cache: bool = False
+) -> HogQLGlobalSettings:
+ """Caps for headline aggregates: fail fast rather than scan unbounded data.
+
+ Matches the caps AlertCheckQuery uses against the same table. Runners that repeatedly
+ decompress the attribute maps over near-identical windows opt into the uncompressed
+ block cache, guarded to the runner's own read cap (see LogsGroupByQueryRunner).
+ """
+ return HogQLGlobalSettings(
+ max_execution_time=30,
+ max_bytes_to_read=max_bytes_to_read,
+ read_overflow_mode="throw",
+ use_uncompressed_cache=use_uncompressed_cache or None,
+ merge_tree_max_rows_to_use_cache=50_000_000 if use_uncompressed_cache else None,
+ merge_tree_max_bytes_to_use_cache=max_bytes_to_read if use_uncompressed_cache else None,
+ )
+
+
class LogsQueryRunnerMixin(QueryRunner):
# Target bucket count for the adaptive interval picker in `query_date_range`.
# Subclasses can override per-instance to request a different resolution.
@@ -723,6 +723,24 @@ class LogsQueryRunnerMixin(QueryRunner):
def where(self) -> ast.Expr:
return self._filter_builder.where()
+ def where_with_timestamp_bounds(self) -> ast.Expr:
+ # LogsFilterBuilder.where() filters by toStartOfDay(time_bucket), which is
+ # day-precision; the explicit per-row bounds (half-open to avoid double-counting
+ # on boundaries) make aggregate counts match the requested window. Same pattern
+ # as AlertCheckQuery.
+ return ast.And(
+ exprs=[
+ self.where(),
+ parse_expr(
+ "timestamp >= {date_from} AND timestamp < {date_to}",
+ placeholders={
+ "date_from": ast.Constant(value=self.query_date_range.date_from()),
+ "date_to": ast.Constant(value=self.query_date_range.date_to()),
+ },
+ ),
+ ]
+ )
+
def resource_filter(self, *, existing_filters):
return self._filter_builder.resource_filter(existing_filters=existing_filters)
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index 026dea332479..e0760b38accb 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -99,6 +99,22 @@ SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS = [
]
+def resolved_distinct_id_attribute_keys(team) -> list[str]:
+ """The attribute keys that link a log to a person: the team's configured keys (or the
+ default when unconfigured), then the built-in conventions the UI links regardless of
+ config. Deduped, configured keys first."""
+ config = TeamLogsConfig.objects.filter(team=team).first()
+ configured = (config.logs_distinct_id_attribute_keys if config else None) or DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS
+ return list(dict.fromkeys([*configured, *DISTINCT_ID_ATTRIBUTE_KEY_CONVENTIONS]))
+
+
+def resolved_session_id_attribute_keys(team) -> list[str]:
+ """The session-ID equivalent of resolved_distinct_id_attribute_keys."""
+ config = TeamLogsConfig.objects.filter(team=team).first()
+ configured = (config.logs_session_id_attribute_keys if config else None) or DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS
+ return list(dict.fromkeys([*configured, *SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS]))
+
+
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 5fac5693c681..138568cc5e71 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -52,6 +52,7 @@ from products.logs.backend.group_by_query_runner import (
LogsGroupByQueryRunner,
)
from products.logs.backend.has_logs_query_runner import team_has_logs
+from products.logs.backend.impact_query_runner import ImpactQueryRunner
from products.logs.backend.log_attributes_query_runner import LogAttributesQueryRunner
from products.logs.backend.log_facet_values_query_runner import FACET_FIELDS, LogFacetValuesQueryRunner
from products.logs.backend.log_values_query_runner import LogValuesQueryRunner
@@ -403,6 +404,28 @@ class _LogsCountRequestSerializer(serializers.Serializer):
query = _LogsCountBodySerializer(help_text="The count query to execute.")
+class _LogsImpactRequestSerializer(serializers.Serializer):
+ query = _LogsCountBodySerializer(
+ help_text="The impact query to execute. Takes the same filters as the count query."
+ )
+
+
+class _LogsImpactResponseSerializer(serializers.Serializer):
+ total = serializers.IntegerField(help_text="Number of log entries matching the filters.")
+ logsWithSessionId = serializers.IntegerField(
+ help_text="How many of the matching logs carry a session ID under the team's configured or conventional attribute keys."
+ )
+ sessions = serializers.IntegerField(
+ help_text="Estimated number of unique session IDs across the matching logs (HyperLogLog, about 1-2% error)."
+ )
+ logsWithDistinctId = serializers.IntegerField(
+ help_text="How many of the matching logs carry a person distinct ID under the team's configured or conventional attribute keys."
+ )
+ users = serializers.IntegerField(
+ help_text="Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error)."
+ )
+
+
class _LogFacetValueSerializer(serializers.Serializer):
value = serializers.CharField(help_text="The facet value (e.g. a severity level or service name).")
count = serializers.IntegerField(
@@ -1202,8 +1225,9 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
# The body serializers document dateRange as optional, so an absent range must
# default rather than 400 (get_model rejects None).
dateRange=self.get_model(date_range_data, DateRange) if date_range_data else DateRange(date_from="-1h"),
- severityLevels=query_data.get("severityLevels", []),
- serviceNames=query_data.get("serviceNames", []),
+ # A null list in the body must default like an absent one instead of failing validation.
+ severityLevels=query_data.get("severityLevels") or [],
+ serviceNames=query_data.get("serviceNames") or [],
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
@@ -1212,6 +1236,16 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
sessionId=query_data.get("sessionId", None),
)
+ @staticmethod
+ def _filter_analytics_props(query_data: dict) -> dict:
+ """The filter-shape properties every logs aggregation action reports."""
+ return {
+ "has_search_term": bool(query_data.get("searchTerm")),
+ "has_filter_group": bool(query_data.get("filterGroup")),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
+ }
+
@extend_schema(request=_LogsQueryRequestSerializer, responses={200: _LogsQueryResponseSerializer})
@action(detail=False, methods=["POST"], required_scopes=["logs:read"])
def query(self, request: Request, *args, **kwargs) -> Response:
@@ -1326,8 +1360,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"has_more": has_more,
"has_search_term": bool(query_data.get("searchTerm")),
"has_filter_group": bool(query_data.get("filterGroup")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
"is_paginated": bool(after_cursor),
},
team=self.team,
@@ -1382,8 +1416,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
{
"has_search_term": bool(query_data.get("searchTerm")),
"has_filter_group": bool(query_data.get("filterGroup")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
"breakdown_by": query_data.get("sparklineBreakdownBy"),
},
team=self.team,
@@ -1442,16 +1476,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
query_data = request.data.get("query", {})
self._require_dict_query(query_data)
- date_range_data = query_data.get("dateRange")
- date_range = self.get_model(date_range_data, DateRange) if date_range_data else DateRange(date_from="-1h")
-
- query = LogsQuery(
- dateRange=date_range,
- severityLevels=query_data.get("severityLevels", []),
- serviceNames=query_data.get("serviceNames", []),
- searchTerm=query_data.get("searchTerm", None),
- filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
- )
+ query = self._filtered_logs_query(query_data)
runner = CountQueryRunner(team=self.team, query=query)
response = runner.run(
@@ -1463,12 +1488,33 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
report_user_action(
request.user,
"logs count queried",
- {
- "has_search_term": bool(query_data.get("searchTerm")),
- "has_filter_group": bool(query_data.get("filterGroup")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
- },
+ self._filter_analytics_props(query_data),
+ team=self.team,
+ request=request,
+ )
+
+ return Response(response.results, status=status.HTTP_200_OK)
+
+ @extend_schema(request=_LogsImpactRequestSerializer, responses={200: _LogsImpactResponseSerializer})
+ @action(detail=False, methods=["POST"], required_scopes=["logs:read"])
+ def impact(self, request: Request, *args, **kwargs) -> Response:
+ tag_queries(product=Product.LOGS, feature=Feature.QUERY)
+ query_data = request.data.get("query", {})
+ self._require_dict_query(query_data)
+
+ query = self._filtered_logs_query(query_data)
+
+ runner = ImpactQueryRunner(team=self.team, query=query)
+ response = runner.run(
+ ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ analytics_props=get_request_analytics_properties(request),
+ )
+ assert isinstance(response, LogsQueryResponse | CachedLogsQueryResponse)
+
+ report_user_action(
+ request.user,
+ "logs impact queried",
+ self._filter_analytics_props(query_data),
team=self.team,
request=request,
)
@@ -1512,8 +1558,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"target_buckets": target_buckets,
"has_search_term": bool(query_data.get("searchTerm")),
"has_filter_group": bool(query_data.get("filterGroup")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
@@ -1555,8 +1601,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
if isinstance(response.results, dict)
else 0,
"has_search_term": bool(query_data.get("searchTerm")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
@@ -1589,8 +1635,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
else 0,
"sampled": response.results.get("sampled") if isinstance(response.results, dict) else None,
"has_search_term": bool(query_data.get("searchTerm")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
@@ -1622,8 +1668,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"changed_count": sum(1 for e in results["entries"] if e["classification"] != "unchanged"),
"auto_baseline": baseline_date_range is None,
"has_search_term": bool(query_data.get("searchTerm")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
@@ -1678,8 +1724,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"groups_count": len(results.get("groups", [])),
"truncated": results.get("truncated"),
"has_search_term": bool(query_data.get("searchTerm")),
- "severity_levels_count": len(query_data.get("severityLevels", [])),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "severity_levels_count": len(query_data.get("severityLevels") or []),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
@@ -1886,7 +1932,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"export_id": asset.id,
"columns_count": len(columns),
"has_search_term": bool(query_data.get("searchTerm")),
- "service_names_count": len(query_data.get("serviceNames", [])),
+ "service_names_count": len(query_data.get("serviceNames") or []),
},
team=self.team,
request=request,
diff --git a/products/logs/backend/test/test_impact_api.py b/products/logs/backend/test/test_impact_api.py
new file mode 100644
index 000000000000..bf6ba420240d
--- /dev/null
+++ b/products/logs/backend/test/test_impact_api.py
@@ -0,0 +1,113 @@
+import json
+import uuid
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.clickhouse.client import sync_execute
+
+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}
+
+
+def _log_row(
+ team_id: int,
+ body: str,
+ severity_text: str = "info",
+ severity_number: int = 9,
+ attributes: dict[str, str] | None = None,
+ resource_attributes: dict[str, str] | None = None,
+) -> dict:
+ return {
+ "uuid": str(uuid.uuid4()),
+ "team_id": team_id,
+ "trace_id": "",
+ "span_id": "",
+ "trace_flags": 0,
+ "timestamp": "2025-12-16 09:00:00.000000",
+ "observed_timestamp": "2025-12-16 09:00:01.000000",
+ "body": body,
+ "severity_text": severity_text,
+ "severity_number": severity_number,
+ "service_name": "checkout",
+ "resource_attributes": resource_attributes or {},
+ # The ingestion MV writes attributes into the typed map with a `__str` key suffix
+ # (posthog/clickhouse/logs/logs34.py); mirror that so the fixture matches production rows.
+ "attributes_map_str": {f"{key}__str": value for key, value in (attributes or {}).items()},
+ "attributes_map_float3": {},
+ "attributes_map_datetime": {},
+ "event_name": "",
+ "instrumentation_scope": "",
+ }
+
+
+class TestImpactApi(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ @classmethod
+ def setUpTestData(cls) -> None:
+ 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, "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, "upstream timed out", severity_text="error", severity_number=17),
+ _log_row(cls.team.id, "inventory synced", attributes={"my_session": "s9"}),
+ ]
+ sql = "\n".join(json.dumps(row) for row in rows)
+ sync_execute(f"""
+ INSERT INTO logs
+ FORMAT JSONEachRow
+ {sql}
+ """)
+
+ def _impact(self, query_params: dict) -> dict:
+ response = self.client.post(f"/api/projects/{self.team.id}/logs/impact", data={"query": query_params})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ return response.json()
+
+ @parameterized.expand(
+ [
+ (
+ "full_window",
+ _FIXTURE_WINDOW,
+ {"total": 6, "logsWithSessionId": 4, "sessions": 3, "logsWithDistinctId": 2, "users": 2},
+ ),
+ ("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)
+
+ @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)
+
+ @freeze_time("2025-12-18T12:00:00Z")
+ def test_impact_applies_filters(self) -> None:
+ # The only error-severity row carries no identity attributes, so every
+ # identity count must drop to zero with it.
+ response = self._impact({"dateRange": _FIXTURE_WINDOW, "severityLevels": ["error"]})
+ self.assertEqual(response, {**_ZERO_IMPACT, "total": 1})
+
+ @freeze_time("2025-12-18T12:00:00Z")
+ def test_impact_counts_team_configured_session_keys(self) -> None:
+ TeamLogsConfig.objects.update_or_create(
+ 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)
+
+ 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"})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
index a5e7e1ecd0ec..a8a022b7919e 100644
--- a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
@@ -4,8 +4,10 @@ import { Fragment } from 'react'
import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
+import { FlaggedFeature } from 'lib/components/FlaggedFeature'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { FEATURE_FLAGS } from 'lib/constants'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { logsGroupByLogic } from 'products/logs/frontend/components/LogsGroupBy/logsGroupByLogic'
@@ -13,6 +15,7 @@ import { logsPatternsLogic } from 'products/logs/frontend/components/LogsPattern
import { MAX_GROUP_BY_DIMENSIONS, logsViewerConfigLogic } from './config/logsViewerConfigLogic'
import { resolveGroupBySource } from './groupBySource'
+import { LogsImpactStrip } from './LogsImpactStrip'
import { LogsViewerToolbar } from './LogsViewerToolbar'
export interface LogsDisplayBarProps {
@@ -82,10 +85,15 @@ export const LogsDisplayBar = ({
) : inGroupByMode ? (
<GroupsCountIndicator id={id} />
) : (
- totalLogsCount !== undefined &&
- totalLogsCount > 0 && (
- <span className="text-muted text-xs">{humanFriendlyNumber(totalLogsCount)} logs</span>
- )
+ <>
+ {totalLogsCount !== undefined && totalLogsCount > 0 && (
+ <span className="text-muted text-xs">{humanFriendlyNumber(totalLogsCount)} logs</span>
+ )}
+ {/* Gated here so the strip's logic (and its query) only mount when the flag is on. */}
+ <FlaggedFeature flag={FEATURE_FLAGS.LOGS_IMPACT_STRIP}>
+ <LogsImpactStrip id={id} />
+ </FlaggedFeature>
+ </>
)}
</div>
{inPatternsMode ? (
diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx
new file mode 100644
index 000000000000..609dad69ecc7
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.stories.tsx
@@ -0,0 +1,48 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import type { _LogsImpactResponseApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { LogsImpactCounts } from './LogsImpactCounts'
+
+// The counts sit in the display bar beside "N logs". The states worth a snapshot are the ones
+// that read differently to someone scanning the bar: both IDs present, only one of them, and a
+// project whose logs carry neither.
+
+const meta: Meta<typeof LogsImpactCounts> = {
+ title: 'Scenes-App/Logs/LogsImpactCounts',
+ component: LogsImpactCounts,
+ parameters: { layout: 'padded', viewMode: 'story' },
+}
+export default meta
+
+type Story = StoryObj<typeof LogsImpactCounts>
+
+function makeImpact(overrides: Partial<_LogsImpactResponseApi> = {}): _LogsImpactResponseApi {
+ return {
+ total: 12400,
+ logsWithSessionId: 11800,
+ sessions: 214,
+ logsWithDistinctId: 9600,
+ users: 96,
+ ...overrides,
+ }
+}
+
+export const SessionsAndUsers: Story = {
+ args: { impact: makeImpact() },
+}
+
+/** Server logs that carry a session ID but were never linked to a person. */
+export const SessionsOnly: Story = {
+ args: { impact: makeImpact({ logsWithDistinctId: 0, users: 0 }) },
+}
+
+/** Partial instrumentation: the tooltip is what tells the reader the count covers a slice. */
+export const PartialCoverage: Story = {
+ args: { impact: makeImpact({ logsWithSessionId: 380, sessions: 12, logsWithDistinctId: 0, users: 0 }) },
+}
+
+/** Infrastructure logs with no identity attributes at all. */
+export const NoCoverage: Story = {
+ args: { impact: makeImpact({ logsWithSessionId: 0, sessions: 0, logsWithDistinctId: 0, users: 0 }) },
+}
diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx
new file mode 100644
index 000000000000..378717ee792f
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsImpactCounts.tsx
@@ -0,0 +1,66 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { humanFriendlyLargeNumber, percentage } from 'lib/utils/numbers'
+
+import type { _LogsImpactResponseApi } from 'products/logs/frontend/generated/api.schemas'
+
+export interface LogsImpactCountsProps {
+ impact: _LogsImpactResponseApi
+}
+
+/**
+ * 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.
+ */
+export function LogsImpactCounts({ impact }: LogsImpactCountsProps): JSX.Element | null {
+ if (impact.total === 0) {
+ return null
+ }
+
+ if (impact.logsWithSessionId === 0 && impact.logsWithDistinctId === 0) {
+ return (
+ <Tooltip title="No logs in this view carry a session ID or a person distinct ID. Add one to your log attributes to see the sessions and users behind them.">
+ <span className="text-muted text-xs" data-attr="logs-impact-no-coverage">
+ No session or user IDs
+ </span>
+ </Tooltip>
+ )
+ }
+
+ const percentOfLogs = (count: number): string => {
+ const fraction = count / impact.total
+ // Rounding must not contradict the visible counts: partial coverage never reads
+ // as a flat 0% or 100%.
+ if (fraction < 0.005) {
+ return '<1%'
+ }
+ if (fraction > 0.995 && fraction < 1) {
+ return '>99%'
+ }
+ return percentage(fraction, 0)
+ }
+
+ return (
+ <span className="flex items-center gap-2 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.`}
+ >
+ <span data-attr="logs-impact-sessions">{humanFriendlyLargeNumber(impact.sessions)} sessions</span>
+ </Tooltip>
+ )}
+ {impact.logsWithDistinctId > 0 && (
+ <Tooltip
+ title={`Estimated unique people on the matching logs. ${percentOfLogs(
+ impact.logsWithDistinctId
+ )} of them carry a distinct ID.`}
+ >
+ <span data-attr="logs-impact-users">{humanFriendlyLargeNumber(impact.users)} users</span>
+ </Tooltip>
+ )}
+ </span>
+ )
+}
diff --git a/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx b/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx
new file mode 100644
index 000000000000..3810c6336683
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsImpactStrip.tsx
@@ -0,0 +1,22 @@
+import { useValues } from 'kea'
+
+import { LogsImpactCounts } from './LogsImpactCounts'
+import { logsImpactLogic } from './logsImpactLogic'
+
+export interface LogsImpactStripProps {
+ id: string
+}
+
+/**
+ * The impact counts for the viewer's current query, shown beside the logs count. Mounting this
+ * component mounts the logic and runs the query, so the caller gates rendering on the flag.
+ */
+export function LogsImpactStrip({ id }: LogsImpactStripProps): JSX.Element | null {
+ const { impact } = useValues(logsImpactLogic({ id }))
+
+ if (!impact) {
+ return null
+ }
+
+ return <LogsImpactCounts impact={impact} />
+}
diff --git a/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts b/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts
new file mode 100644
index 000000000000..90cf620b0b23
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/logsImpactLogic.ts
@@ -0,0 +1,143 @@
+import { MakeLogicType, 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 { 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'
+import type { _LogsCountBodyApi, _LogsImpactResponseApi } from 'products/logs/frontend/generated/api.schemas'
+
+import type { LogsQuery } from '../../../../../frontend/src/queries/schema/schema-general'
+
+export interface LogsImpactLogicProps {
+ id: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsImpactLogicValues {
+ personId: string | undefined // logsViewerFiltersLogic
+ queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ searchTerm: LogsQuery[] // logsViewerFiltersLogic
+ utcDateRange: {
+ date_from: string | null | undefined
+ date_to: string | null | undefined
+ explicitDate: boolean | null | undefined
+ } // logsViewerFiltersLogic
+ currentTeamId: number | null // teamLogic
+ impact: _LogsImpactResponseApi | null
+ impactLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsImpactLogicActions {
+ runQuery: (debounce?: number | undefined) => {
+ debounce: number | undefined
+ } // logsViewerDataLogic
+ loadImpact: (_: any) => any
+ loadImpactFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadImpactSuccess: (
+ impact: _LogsImpactResponseApi | null,
+ payload?: any
+ ) => {
+ impact: _LogsImpactResponseApi | null
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsImpactLogicMeta {
+ key: string
+}
+
+export type logsImpactLogicType = MakeLogicType<
+ logsImpactLogicValues,
+ logsImpactLogicActions,
+ LogsImpactLogicProps,
+ logsImpactLogicMeta
+>
+
+export const logsImpactLogic = kea<logsImpactLogicType>([
+ props({} as LogsImpactLogicProps),
+ key(({ id }) => id),
+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'logsImpactLogic', key]),
+ connect(({ id }: LogsImpactLogicProps) => ({
+ values: [
+ logsViewerFiltersLogic({ id }),
+ ['utcDateRange', 'queryFilterGroup', 'searchTerm', 'personId'],
+ teamLogic,
+ ['currentTeamId'],
+ ],
+ actions: [logsViewerDataLogic({ id }), ['runQuery']],
+ })),
+ 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) {
+ return null
+ }
+ await breakpoint(300)
+ // The serializer models `filterGroup` as a flat filter list, but the endpoint
+ // also accepts the nested group the viewer holds (the view normalizes both),
+ // so the request body needs a cast the generated type can't express.
+ const query = {
+ dateRange: values.utcDateRange,
+ searchTerm: values.searchTerm,
+ filterGroup: values.queryFilterGroup,
+ } as unknown as _LogsCountBodyApi
+ // Re-adding the key aborts the superseded in-flight request, and unmount
+ // aborts the current one. A request is one-shot work, not background work,
+ // so a hidden tab must not abort it.
+ const controller = new AbortController()
+ cache.disposables.add(() => () => controller.abort(), 'impactRequest', {
+ pauseOnPageHidden: false,
+ })
+ let response: _LogsImpactResponseApi | null = null
+ try {
+ response = await logsImpactCreate(
+ String(values.currentTeamId),
+ { query },
+ { signal: controller.signal }
+ )
+ } catch {
+ // The strip is passive decoration: on failure show nothing rather than
+ // stale counts or the global error toast.
+ }
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ })),
+ reducers({
+ impact: {
+ // Clear on refresh so counts from the previous query never render next to the
+ // new query's results.
+ loadImpact: () => null,
+ },
+ }),
+ listeners(({ actions }) => ({
+ // runQuery is the viewer's execute-this-query entrypoint, so the strip refreshes with
+ // the query rather than coupling to the sparkline loader's schedule. Bursts (typing)
+ // collapse in loadImpact's own breakpoint.
+ runQuery: () => actions.loadImpact(null),
+ })),
+ afterMount(({ actions }) => {
+ // The data logic usually mounts (and fires its initial runQuery) before this logic
+ // exists, so the first load has to be explicit.
+ actions.loadImpact(null)
+ }),
+])
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index e6950606a663..e03bfea7f7f7 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1759,6 +1759,24 @@ export interface _LogsGroupByResponseApi {
truncated: boolean
}
+export interface _LogsImpactRequestApi {
+ /** The impact query to execute. Takes the same filters as the count query. */
+ query: _LogsCountBodyApi
+}
+
+export interface _LogsImpactResponseApi {
+ /** Number of log entries matching the filters. */
+ total: number
+ /** How many of the matching logs carry a session ID under the team's configured or conventional attribute keys. */
+ logsWithSessionId: number
+ /** Estimated number of unique session IDs across the matching logs (HyperLogLog, about 1-2% error). */
+ sessions: number
+ /** How many of the matching logs carry a person distinct ID under the team's configured or conventional attribute keys. */
+ logsWithDistinctId: number
+ /** Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error). */
+ users: number
+}
+
export interface LogsMetricRuleApi {
/** Unique identifier for this metric rule. */
readonly id: string
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index d9d79e87434d..3bf00ae62886 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -62,6 +62,8 @@ import type {
_LogsFacetValuesResponseApi,
_LogsGroupByRequestApi,
_LogsGroupByResponseApi,
+ _LogsImpactRequestApi,
+ _LogsImpactResponseApi,
_LogsPatternsDiffRequestApi,
_LogsPatternsDiffResponseApi,
_LogsPatternsRequestApi,
@@ -493,6 +495,23 @@ export const logsHasLogsRetrieve = async (
})
}
+export const getLogsImpactCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/logs/impact/`
+}
+
+export const logsImpactCreate = async (
+ projectId: string,
+ _logsImpactRequestApi: _LogsImpactRequestApi,
+ options?: RequestInit
+): Promise<_LogsImpactResponseApi> => {
+ return apiMutator<_LogsImpactResponseApi>(getLogsImpactCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_logsImpactRequestApi),
+ })
+}
+
export const getLogsMetricRulesListUrl = (projectId: string, params?: LogsMetricRulesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index abf56becac6f..54d8541c437d 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -1033,6 +1033,92 @@ export const LogsGroupByCreateBody = /* @__PURE__ */ zod.object({
.describe('The group-by query to execute.'),
})
+export const LogsImpactCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ dateRange: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),
+ })
+ .optional()
+ .describe('Date range for the count. Defaults to last hour.'),
+ severityLevels: zod
+ .array(
+ zod
+ .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])
+ .describe(
+ '\* `trace` - trace\n\* `debug` - debug\n\* `info` - info\n\* `warn` - warn\n\* `error` - error\n\* `fatal` - fatal'
+ )
+ )
+ .optional()
+ .describe('Filter by log severity levels.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies.'),
+ filterGroup: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'
+ ),
+ type: zod
+ .enum(['log', 'log_attribute', 'log_resource_attribute'])
+ .describe(
+ '\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'
+ )
+ .describe(
+ '\"log\" filters the log body\/message. \"log_attribute\" filters log-level attributes. \"log_resource_attribute\" filters resource-level attributes.\n\n\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'lt',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'is_set',
+ 'is_not_set',
+ ])
+ .describe(
+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ )
+ .describe(
+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'
+ ),
+ })
+ )
+ .optional()
+ .describe('Property filters for the query.'),
+ })
+ .describe('The impact query to execute. Takes the same filters as the count query.'),
+})
+
export const logsMetricRulesCreateBodyNameMax = 255
export const logsMetricRulesCreateBodyMetricNameMax = 200
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 01408471988f..2a3560814d75 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -132,6 +132,8 @@ const DISTINCT_ID_KEYS = [
'posthog.distinct.id',
'posthog.distinct_id',
]
+// Mirror of SESSION_ID_ATTRIBUTE_KEY_CONVENTIONS in products/logs/backend/models.py — keep the
+// two in sync, or the impact counts stop covering logs this list renders as session links.
// Some pipelines emit `posthogSessionId` even though no SDK does. Removing it breaks them.
const SESSION_ID_KEYS = [
'session.id',
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 3b29482d4fe8..2bef7b9cb34c 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -411,6 +411,9 @@ tools:
logs-has-logs-retrieve:
operation: logs_has_logs_retrieve
enabled: false
+ logs-impact-create:
+ operation: logs_impact_create
+ enabled: false
logs-metric-rules-create:
operation: logs_metric_rules_create
enabled: false
diff --git a/pyproject.toml b/pyproject.toml
index 9bfc5e522b79..cf0391f6c718 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -617,6 +617,7 @@ ignore_imports = [
"products.logs.backend.presentation.views.api -> products.logs.backend.count_ranges_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.group_by_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.has_logs_query_runner",
+ "products.logs.backend.presentation.views.api -> products.logs.backend.impact_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.log_attributes_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.log_facet_values_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.log_values_query_runner",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ab1b5c18f7f7..e5bda54f587e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -89780,6 +89780,24 @@ export namespace Schemas {
truncated: boolean;
}
+ export interface _LogsImpactRequest {
+ /** The impact query to execute. Takes the same filters as the count query. */
+ query: _LogsCountBody;
+ }
+
+ export interface _LogsImpactResponse {
+ /** Number of log entries matching the filters. */
+ total: number;
+ /** How many of the matching logs carry a session ID under the team's configured or conventional attribute keys. */
+ logsWithSessionId: number;
+ /** Estimated number of unique session IDs across the matching logs (HyperLogLog, about 1-2% error). */
+ sessions: number;
+ /** How many of the matching logs carry a person distinct ID under the team's configured or conventional attribute keys. */
+ logsWithDistinctId: number;
+ /** Estimated number of unique distinct IDs across the matching logs (HyperLogLog, about 1-2% error). */
+ users: number;
+ }
+
export interface _LogsPatternsBody {
/** Date range to mine patterns from. Defaults to last hour. */
dateRange?: _DateRange;