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): wire group-by lens to a real grouped aggregation (#68878)

Jon McCallum5c8d648944ff
diff --git a/products/logs/backend/group_by_query_runner.py b/products/logs/backend/group_by_query_runner.py
new file mode 100644
index 000000000000..b5ec4f6c911e
--- /dev/null
+++ b/products/logs/backend/group_by_query_runner.py
@@ -0,0 +1,193 @@
+from typing import TYPE_CHECKING
+from zoneinfo import ZoneInfo
+
+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.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.models.filters.mixins.utils import cached_property
+
+from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixin
+
+if TYPE_CHECKING:
+ from posthog.models import User
+
+# Hard byte budget with "throw": a grouped aggregation with partial input would report
+# silently wrong counts, so an over-budget scan must fail loudly (the UI asks the user
+# to narrow the window) rather than return truncated aggregates.
+MAX_READ_BYTES = 10_000_000_000
+MAX_EXECUTION_TIME = 60
+
+DEFAULT_GROUP_LIMIT = 100
+MAX_GROUP_LIMIT = 500
+
+# Top-level log fields exposed as grouping keys (source="column"), mapped to the
+# HogQL expression that yields their display value. trace_id/span_id are stored
+# base64-encoded; hex is what users see in trace UIs.
+GROUPABLE_COLUMNS: dict[str, str] = {
+ "severity_level": "severity_text",
+ "trace_id": "hex(tryBase64Decode(trace_id))",
+ "span_id": "hex(tryBase64Decode(span_id))",
+}
+
+GROUP_SOURCES = ("log", "resource", "column")
+ORDER_FIELDS = ("log_count", "error_count", "last_seen")
+
+
+class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):
+ """Aggregates matching logs into groups by one attribute (or top-level field).
+
+ Single scan over the main `logs` table: the attribute maps live on the row
+ (`Map(LowCardinality(String), String)` with bloom-filter key indexes), so grouping
+ needs no join against the exploded `log_attributes` side table. One query returns
+ the top-N groups AND the total distinct-group/log counts, by nesting the GROUP BY
+ in a subquery and collecting `groupArray(N)` + `count()` + `sum()` in the outer
+ select — the same shape LogAttributesQueryRunner uses for its keys-only path.
+
+ The group-by parameters are runner constructor args, not query-model fields, so the
+ runner must be invoked via `calculate()` (which the logs API does) — never through
+ the caching `run()` path, where the cache key is derived from the query model alone.
+ """
+
+ query: LogsQuery
+ cached_response: CachedLogsQueryResponse
+
+ def __init__(
+ self,
+ query: LogsQuery,
+ *args,
+ group_by: str,
+ group_by_source: str = "log",
+ order_groups_by: str = "log_count",
+ group_limit: int = DEFAULT_GROUP_LIMIT,
+ **kwargs,
+ ):
+ super().__init__(query, *args, **kwargs)
+ if not group_by:
+ raise ValueError("group_by is required")
+ if group_by_source not in GROUP_SOURCES:
+ raise ValueError(f"group_by_source must be one of {GROUP_SOURCES}")
+ if group_by_source == "column" and group_by not in GROUPABLE_COLUMNS:
+ raise ValueError(f"group_by must be one of {tuple(GROUPABLE_COLUMNS)} when group_by_source is 'column'")
+ if order_groups_by not in ORDER_FIELDS:
+ raise ValueError(f"order_groups_by must be one of {ORDER_FIELDS}")
+ self.group_by = group_by
+ self.group_by_source = group_by_source
+ self.order_groups_by = order_groups_by
+ self.group_limit = max(1, min(group_limit, MAX_GROUP_LIMIT))
+
+ def validate_query_runner_access(self, user: "User") -> bool:
+ # Defensive: this runner is invoked directly via the logs API, never through the generic
+ # /api/projects/:id/query/ endpoint. Mirror LogsQueryRunner and refuse user-initiated
+ # generic-query access so it can't silently bypass that gate if ever registered.
+ from posthog.rbac.user_access_control import UserAccessControlError
+
+ raise UserAccessControlError("logs", "viewer")
+
+ @cached_property
+ def settings(self) -> HogQLGlobalSettings:
+ return HogQLGlobalSettings(
+ max_execution_time=MAX_EXECUTION_TIME,
+ max_bytes_to_read=MAX_READ_BYTES,
+ read_overflow_mode="throw",
+ timeout_overflow_mode="throw",
+ )
+
+ def _group_expr(self) -> ast.Expr:
+ # Map keys are bound chain members / parsed from a fixed allowlist — the user-supplied
+ # key can never be interpolated as SQL (same contract as column_expressions.path_to_expr).
+ if self.group_by_source == "log":
+ # Log attributes are physically stored in type-suffixed maps (`attributes_map_str`);
+ # the `__str` suffix routes the read there via the property-group resolver, the same
+ # way LogsFilterBuilder suffixes attribute filter keys. Reading the bare key would go
+ # through the `attributes` ALIAS, which mapApply-rewrites every row's whole map.
+ return ast.Field(chain=["attributes", f"{self.group_by}__str"])
+ if self.group_by_source == "resource":
+ return ast.Field(chain=["resource_attributes", self.group_by])
+ return parse_expr(GROUPABLE_COLUMNS[self.group_by])
+
+ def to_query(self) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT
+ groupArray({limit})((group_value, log_count, error_count, last_seen)) AS groups,
+ count() AS total_groups,
+ sum(log_count) AS total_logs
+ FROM (
+ SELECT
+ {group_expr} AS group_value,
+ count() AS log_count,
+ countIf(lower(severity_text) IN ('error', 'fatal')) AS error_count,
+ max(timestamp) AS last_seen
+ FROM logs
+ WHERE {where}
+ GROUP BY group_value
+ ORDER BY {order_field} DESC, group_value ASC
+ )
+ """,
+ placeholders={
+ "limit": ast.Constant(value=self.group_limit),
+ # Fresh AST nodes per placeholder — resolution annotates nodes in place.
+ "group_expr": self._group_expr(),
+ "where": self._where(),
+ "order_field": ast.Field(chain=[self.order_groups_by]),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _where(self) -> ast.Expr:
+ # LogsFilterBuilder.where() filters at day-precision via time_bucket; add explicit
+ # per-row timestamp bounds (half-open) so group counts match the requested window.
+ # Rows without the grouping attribute are not a group: a missing map key reads as
+ # NULL (property-group scrub) or '' (native subscript), and HogQL's `!=` lets NULL
+ # through, so both must be excluded via coalesce.
+ 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()),
+ },
+ ),
+ parse_expr("coalesce({group_expr}, '') != ''", placeholders={"group_expr": self._group_expr()}),
+ ]
+ )
+
+ 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,
+ )
+
+ groups_raw, total_groups, total_logs = response.results[0] if response.results else ([], 0, 0)
+ groups = [
+ {
+ "value": value,
+ "log_count": int(log_count),
+ "error_count": int(error_count),
+ "last_seen": last_seen.replace(tzinfo=ZoneInfo("UTC")).isoformat(),
+ }
+ for value, log_count, error_count, last_seen in groups_raw
+ ]
+ return LogsQueryResponse(
+ results={
+ "groups": groups,
+ "total_groups": int(total_groups),
+ "total_logs": int(total_logs),
+ "truncated": int(total_groups) > len(groups),
+ }
+ )
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index 044434ae6b60..4730e7d1a565 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -43,6 +43,13 @@ from products.logs.backend.count_ranges_query_runner import (
MAX_TARGET_BUCKETS,
CountRangesQueryRunner,
)
+from products.logs.backend.group_by_query_runner import (
+ DEFAULT_GROUP_LIMIT,
+ GROUP_SOURCES,
+ MAX_GROUP_LIMIT,
+ ORDER_FIELDS,
+ LogsGroupByQueryRunner,
+)
from products.logs.backend.has_logs_query_runner import team_has_logs
from products.logs.backend.log_attributes_query_runner import LogAttributesQueryRunner
from products.logs.backend.log_facet_values_query_runner import FACET_FIELDS, LogFacetValuesQueryRunner
@@ -792,6 +799,93 @@ class _LogsPatternsResponseSerializer(serializers.Serializer):
)
+class _LogsGroupByBodySerializer(serializers.Serializer):
+ dateRange = _DateRangeSerializer(
+ required=False,
+ help_text="Date range to aggregate over. Defaults to last hour.",
+ )
+ severityLevels = serializers.ListField(
+ child=serializers.ChoiceField(choices=["trace", "debug", "info", "warn", "error", "fatal"]),
+ required=False,
+ default=list,
+ help_text="Filter by log severity levels before grouping.",
+ )
+ serviceNames = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=list,
+ help_text="Restrict grouping to these service names.",
+ )
+ searchTerm = serializers.CharField(
+ required=False, help_text="Full-text search term to filter log bodies before grouping."
+ )
+ filterGroup = serializers.ListField(
+ child=_LogPropertyFilterSerializer(),
+ required=False,
+ default=list,
+ help_text="Property filters applied before grouping. Same shape as the query-logs endpoint.",
+ )
+ groupBy = serializers.CharField(
+ help_text=(
+ 'The key to group logs by — an attribute key (e.g. "session_id", "service.name") or, '
+ 'when groupBySource is "column", one of the top-level log fields: '
+ '"severity_level", "trace_id", "span_id".'
+ ),
+ )
+ groupBySource = serializers.ChoiceField(
+ choices=list(GROUP_SOURCES),
+ default="log",
+ help_text=(
+ 'Where the grouping key lives: "log" for log-level attributes, "resource" for '
+ 'resource-level attributes, "column" for top-level log fields.'
+ ),
+ )
+ orderGroupsBy = serializers.ChoiceField(
+ choices=list(ORDER_FIELDS),
+ default="log_count",
+ help_text=(
+ 'Aggregate to rank groups by (descending): "log_count" for the noisiest groups, '
+ '"error_count" for the most failing, "last_seen" for the most recent.'
+ ),
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=DEFAULT_GROUP_LIMIT,
+ min_value=1,
+ max_value=MAX_GROUP_LIMIT,
+ help_text=f"Maximum number of groups to return (top-N by orderGroupsBy). Defaults to {DEFAULT_GROUP_LIMIT}.",
+ )
+
+
+class _LogsGroupByRequestSerializer(serializers.Serializer):
+ query = _LogsGroupByBodySerializer(help_text="The group-by query to execute.")
+
+
+class _LogsGroupByGroupSerializer(serializers.Serializer):
+ value = serializers.CharField(help_text="The grouped attribute value identifying this group.")
+ log_count = serializers.IntegerField(help_text="Number of matching logs in this group.")
+ error_count = serializers.IntegerField(
+ help_text='Number of matching logs in this group at severity "error" or "fatal".',
+ )
+ last_seen = serializers.CharField(help_text="ISO 8601 timestamp of the most recent matching log in this group.")
+
+
+class _LogsGroupByResponseSerializer(serializers.Serializer):
+ groups = _LogsGroupByGroupSerializer(
+ many=True,
+ help_text="Top groups ordered by the requested aggregate, descending. Capped at `limit`.",
+ )
+ total_groups = serializers.IntegerField(
+ help_text="Total distinct group values matching the filters, before the top-N cap.",
+ )
+ total_logs = serializers.IntegerField(
+ help_text="Total matching logs across all groups (rows without the grouping key are excluded).",
+ )
+ truncated = serializers.BooleanField(
+ help_text="True when more groups matched than were returned (total_groups > groups length).",
+ )
+
+
class _LogAttributeEntrySerializer(serializers.Serializer):
name = serializers.CharField()
propertyFilterType = serializers.CharField(
@@ -1207,6 +1301,55 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
return Response(response.results, status=status.HTTP_200_OK)
+ @extend_schema(request=_LogsGroupByRequestSerializer, responses={200: _LogsGroupByResponseSerializer})
+ @action(detail=False, methods=["POST"], required_scopes=["logs:read"], url_path="group-by")
+ def group_by(self, request: Request, *args, **kwargs) -> Response:
+ tag_queries(product=Product.LOGS, feature=Feature.QUERY)
+ query_data = request.data.get("query", {})
+
+ query = LogsQuery(
+ dateRange=self.get_model(query_data.get("dateRange"), DateRange),
+ 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)),
+ )
+
+ try:
+ runner = LogsGroupByQueryRunner(
+ team=self.team,
+ query=query,
+ group_by=query_data.get("groupBy", ""),
+ group_by_source=query_data.get("groupBySource", "log"),
+ order_groups_by=query_data.get("orderGroupsBy", "log_count"),
+ group_limit=int(query_data.get("limit", DEFAULT_GROUP_LIMIT)),
+ )
+ except (ValueError, TypeError) as e:
+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
+
+ # calculate() bypasses the query cache on purpose: the group-by parameters are runner
+ # args, not query-model fields, so they can't participate in the cache key.
+ response = runner.calculate()
+
+ results = response.results if isinstance(response.results, dict) else {}
+ report_user_action(
+ request.user,
+ "logs group by queried",
+ {
+ "group_by_source": query_data.get("groupBySource", "log"),
+ "order_groups_by": query_data.get("orderGroupsBy", "log_count"),
+ "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", [])),
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(response.results, status=status.HTTP_200_OK)
+
@extend_schema(parameters=[_LogsAttributesQuerySerializer], responses={200: _LogsAttributesResponseSerializer})
@action(detail=False, methods=["GET"], required_scopes=["logs:read"])
def attributes(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/logs/backend/test/test_group_by_query_runner.py b/products/logs/backend/test/test_group_by_query_runner.py
new file mode 100644
index 000000000000..5cb2fe51739c
--- /dev/null
+++ b/products/logs/backend/test/test_group_by_query_runner.py
@@ -0,0 +1,245 @@
+import json
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.schema import DateRange, FilterLogicalOperator, LogsQuery, PropertyGroupFilter
+
+from posthog.clickhouse.client import sync_execute
+
+from products.logs.backend.group_by_query_runner import LogsGroupByQueryRunner
+
+_FROZEN_NOW = "2026-06-23T13:00:00Z"
+_WINDOW = DateRange(date_from="2026-06-23T12:00:00Z", date_to="2026-06-23T13:00:00Z")
+
+
+class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):
+ def _insert(self, rows: list[dict]) -> None:
+ sql = "".join(json.dumps({"team_id": self.team.id, **r}) + "\n" for r in rows)
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{sql}")
+
+ def _log(
+ self,
+ severity: str = "info",
+ service: str = "api",
+ hour: int = 12,
+ minute: int = 0,
+ attributes: dict | None = None,
+ resource_attributes: dict | None = None,
+ ) -> dict:
+ row: dict = {
+ "timestamp": f"2026-06-23 {hour:02d}:{minute:02d}:00.000000",
+ "body": "log line",
+ "severity_text": severity,
+ "service_name": service,
+ }
+ if attributes:
+ # `attributes` on the real table is an ALIAS over the type-suffixed physical map;
+ # inserts must target `attributes_map_str` like ingestion does.
+ row["attributes_map_str"] = {f"{k}__str": v for k, v in attributes.items()}
+ if resource_attributes:
+ row["resource_attributes"] = resource_attributes
+ return row
+
+ def _run(
+ self,
+ group_by: str,
+ group_by_source: str = "log",
+ order_groups_by: str = "log_count",
+ group_limit: int = 100,
+ service_names: list[str] | None = None,
+ ) -> dict:
+ query = LogsQuery(
+ dateRange=_WINDOW,
+ filterGroup=PropertyGroupFilter(type=FilterLogicalOperator.AND_, values=[]),
+ severityLevels=[],
+ serviceNames=service_names or [],
+ searchTerm=None,
+ )
+ runner = LogsGroupByQueryRunner(
+ team=self.team,
+ query=query,
+ group_by=group_by,
+ group_by_source=group_by_source,
+ order_groups_by=order_groups_by,
+ group_limit=group_limit,
+ )
+ results = runner.calculate().results
+ assert isinstance(results, dict)
+ return results
+
+ @freeze_time(_FROZEN_NOW)
+ def test_groups_by_log_attribute_with_counts_and_last_seen(self) -> None:
+ self._insert(
+ [
+ self._log(attributes={"session_id": "s1"}, severity="info", minute=0),
+ self._log(attributes={"session_id": "s1"}, severity="error", minute=1),
+ self._log(attributes={"session_id": "s1"}, severity="fatal", minute=2),
+ self._log(attributes={"session_id": "s2"}, severity="info", minute=5),
+ self._log(attributes={"session_id": "s2"}, severity="info", minute=6),
+ # No session_id: must not surface as an empty-valued group.
+ self._log(severity="error", minute=7),
+ ]
+ )
+
+ results = self._run("session_id")
+
+ assert results["total_groups"] == 2
+ assert results["total_logs"] == 5
+ assert results["truncated"] is False
+ s1, s2 = results["groups"]
+ assert s1 == {"value": "s1", "log_count": 3, "error_count": 2, "last_seen": "2026-06-23T12:02:00+00:00"}
+ assert s2 == {"value": "s2", "log_count": 2, "error_count": 0, "last_seen": "2026-06-23T12:06:00+00:00"}
+
+ @parameterized.expand(
+ [
+ ("resource_attribute", "env", "resource", ["prod", "dev"]),
+ ("top_level_column", "severity_level", "column", ["error", "info"]),
+ ]
+ )
+ @freeze_time(_FROZEN_NOW)
+ def test_groups_by_source(self, _name: str, group_by: str, source: str, expected_values: list[str]) -> None:
+ self._insert(
+ [
+ self._log(resource_attributes={"env": "prod"}, severity="error", minute=0),
+ self._log(resource_attributes={"env": "prod"}, severity="error", minute=1),
+ self._log(resource_attributes={"env": "dev"}, severity="info", minute=2),
+ ]
+ )
+
+ results = self._run(group_by, group_by_source=source)
+
+ assert [g["value"] for g in results["groups"]] == expected_values
+ assert [g["log_count"] for g in results["groups"]] == [2, 1]
+
+ @freeze_time(_FROZEN_NOW)
+ def test_limit_truncates_but_reports_full_totals(self) -> None:
+ self._insert(
+ [self._log(attributes={"session_id": f"s{i}"}, minute=i) for i in range(3)]
+ + [self._log(attributes={"session_id": "s0"}, minute=10)]
+ )
+
+ results = self._run("session_id", group_limit=2)
+
+ assert len(results["groups"]) == 2
+ assert results["groups"][0]["value"] == "s0"
+ assert results["total_groups"] == 3
+ assert results["total_logs"] == 4
+ assert results["truncated"] is True
+
+ @freeze_time(_FROZEN_NOW)
+ def test_order_groups_by_error_count_reranks(self) -> None:
+ self._insert(
+ [self._log(attributes={"session_id": "noisy"}, severity="info", minute=m) for m in range(3)]
+ + [self._log(attributes={"session_id": "failing"}, severity="error", minute=m) for m in range(2)]
+ )
+
+ by_count = self._run("session_id")
+ by_errors = self._run("session_id", order_groups_by="error_count")
+
+ assert [g["value"] for g in by_count["groups"]] == ["noisy", "failing"]
+ assert [g["value"] for g in by_errors["groups"]] == ["failing", "noisy"]
+
+ @freeze_time(_FROZEN_NOW)
+ def test_window_bounds_are_row_precise_not_day_precise(self) -> None:
+ # The shared filter builder bounds only time_bucket (day precision); the runner must
+ # add per-row timestamp bounds or same-day rows outside the window leak into counts.
+ self._insert(
+ [
+ self._log(attributes={"session_id": "s1"}, hour=11, minute=30),
+ self._log(attributes={"session_id": "s1"}, hour=12, minute=30),
+ ]
+ )
+
+ results = self._run("session_id")
+
+ assert results["total_logs"] == 1
+ assert results["groups"][0]["log_count"] == 1
+
+ @freeze_time(_FROZEN_NOW)
+ def test_respects_service_filter(self) -> None:
+ self._insert(
+ [
+ self._log(attributes={"session_id": "s1"}, service="api"),
+ self._log(attributes={"session_id": "s2"}, service="db", minute=1),
+ ]
+ )
+
+ results = self._run("session_id", service_names=["api"])
+
+ assert [g["value"] for g in results["groups"]] == ["s1"]
+
+ @parameterized.expand(
+ [
+ ("missing_group_by", "", "log", "log_count"),
+ ("unknown_source", "session_id", "nope", "log_count"),
+ # The column path parses a fixed expression allowlist; arbitrary keys must never
+ # reach parse_expr, where they would execute as HogQL.
+ ("column_not_in_allowlist", "attributes['x'] OR 1=1", "column", "log_count"),
+ ("unknown_order_field", "session_id", "log", "value"),
+ ]
+ )
+ def test_invalid_args_raise(self, _name: str, group_by: str, source: str, order: str) -> None:
+ query = LogsQuery(
+ dateRange=_WINDOW,
+ filterGroup=PropertyGroupFilter(type=FilterLogicalOperator.AND_, values=[]),
+ severityLevels=[],
+ serviceNames=[],
+ searchTerm=None,
+ )
+ with self.assertRaises(ValueError):
+ LogsGroupByQueryRunner(
+ team=self.team,
+ query=query,
+ group_by=group_by,
+ group_by_source=source,
+ order_groups_by=order,
+ )
+
+
+class TestGroupByAPI(ClickhouseTestMixin, APIBaseTest):
+ @freeze_time(_FROZEN_NOW)
+ def test_endpoint_returns_grouped_results(self) -> None:
+ sync_execute(
+ "INSERT INTO logs FORMAT JSONEachRow\n"
+ + json.dumps(
+ {
+ "team_id": self.team.id,
+ "timestamp": "2026-06-23 12:00:00.000000",
+ "body": "log line",
+ "severity_text": "error",
+ "service_name": "api",
+ "attributes_map_str": {"session_id__str": "s1"},
+ }
+ )
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/group-by",
+ data={
+ "query": {
+ "dateRange": {"date_from": "2026-06-23T12:00:00Z", "date_to": "2026-06-23T13:00:00Z"},
+ "groupBy": "session_id",
+ }
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["total_groups"] == 1
+ assert data["groups"] == [
+ {"value": "s1", "log_count": 1, "error_count": 1, "last_seen": "2026-06-23T12:00:00+00:00"}
+ ]
+
+ def test_endpoint_rejects_missing_group_by(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/group-by",
+ data={"query": {"dateRange": {"date_from": "-1h"}}},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx b/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
index fb08345f2510..8cdb2cb73f70 100644
--- a/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
+++ b/products/logs/frontend/components/LogsGroupBy/LogsGroupByResults.tsx
@@ -1,95 +1,101 @@
-import { LemonBanner, LemonTable } from '@posthog/lemon-ui'
+import { useActions, useValues } from 'kea'
+
+import { LemonTable } from '@posthog/lemon-ui'
+import type { LemonTableColumns } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
-import { dayjs } from 'lib/dayjs'
import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+import type { _LogsGroupByGroupApi, OrderGroupsByEnumApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { logsGroupByLogic } from './logsGroupByLogic'
+
/**
- * PROTOTYPE — visual exploration of the "group by" lens; the rows are mocked.
- * Behind the `logs-group-by` flag; nothing here queries the backend for results (the attribute
- * picker in the display bar searches real keys). The goal is to judge the UX shape before
- * building a real query runner.
+ * The grouped results table for the group-by lens (behind the `logs-group-by` flag).
*
* Column choice is deliberate — each column maps to a triage job:
* - value: which entity is this (identity, the pivot for drill-in)
- * - logs: which groups are noisiest (default sort)
- * - errors: which groups are failing (the "show me what's broken" sort)
+ * - logs: which groups are noisiest (default ranking)
+ * - errors: which groups are failing (the "show me what's broken" ranking)
* - last seen: is it still happening
* Anything that doesn't serve triage or drill-in (timeline art, duration, first seen) is out.
+ *
+ * Ranking is server-side: the endpoint returns the top-N by one aggregate, so a column sort
+ * click re-queries rather than reordering the (truncated) page client-side.
*/
-interface MockGroupRow {
- value: string
- count: number
- errorCount: number
- lastSeenMinutesAgo: number
-}
+const SORTABLE_COLUMNS: OrderGroupsByEnumApi[] = ['log_count', 'error_count', 'last_seen']
-const MOCK_VALUES: Record<string, string[]> = {
- transaction_id: ['txn_9f3ab21c', 'txn_04e77d90', 'txn_b81c33fa', 'txn_5a2e01dd', 'txn_c9f04e12', 'txn_77ab90e3'],
- person_id: ['person_018f3a', 'person_02d417', 'person_0a99c1', 'person_11e402', 'person_1c07b9', 'person_23f8d0'],
- session_id: ['sess_a1b2c3', 'sess_d4e5f6', 'sess_071829', 'sess_3a4b5c', 'sess_9d8e7f', 'sess_616263'],
- 'service.name': ['api', 'worker', 'ingestion', 'capture', 'feature-flags', 'billing'],
-}
+export function LogsGroupByResults({ id }: { id: string }): JSX.Element {
+ const { groupByResponse, groupByResponseLoading, groupByError, groups, orderGroupsBy } = useValues(
+ logsGroupByLogic({ id })
+ )
+ const { setOrderGroupsBy } = useActions(logsGroupByLogic({ id }))
+ const { groupBy } = useValues(logsViewerConfigLogic({ id }))
-// Deterministic pseudo-variety so each attribute renders distinct-looking (but stable) rows.
-function mockRowsFor(groupBy: string): MockGroupRow[] {
- const values = MOCK_VALUES[groupBy] ?? [`${groupBy}_a`, `${groupBy}_b`, `${groupBy}_c`, `${groupBy}_d`]
- return values.map((value, i) => ({
- value,
- count: [4183, 1962, 870, 412, 96, 23][i] ?? 10,
- errorCount: [37, 0, 214, 0, 3, 0][i] ?? 0,
- lastSeenMinutesAgo: [2, 45, 1, 118, 7, 31][i] ?? 60,
- }))
-}
+ const columns: LemonTableColumns<_LogsGroupByGroupApi> = [
+ {
+ title: groupBy?.key,
+ dataIndex: 'value',
+ render: (_, row) => <span className="font-mono text-xs">{row.value}</span>,
+ },
+ {
+ title: 'Logs',
+ dataIndex: 'log_count',
+ align: 'right',
+ render: (_, row) => humanFriendlyNumber(row.log_count),
+ sorter: true,
+ },
+ {
+ title: 'Errors',
+ dataIndex: 'error_count',
+ align: 'right',
+ render: (_, row) =>
+ row.error_count > 0 ? (
+ <span className="text-danger font-semibold">{humanFriendlyNumber(row.error_count)}</span>
+ ) : (
+ <span className="text-muted">0</span>
+ ),
+ sorter: true,
+ },
+ {
+ title: 'Last seen',
+ dataIndex: 'last_seen',
+ render: (_, row) => <TZLabel time={row.last_seen} />,
+ sorter: true,
+ },
+ ]
-export function LogsGroupByResults({ groupBy }: { groupBy: string }): JSX.Element {
- const rows = mockRowsFor(groupBy)
- const totalLogs = rows.reduce((sum, r) => sum + r.count, 0)
+ const { total_groups, total_logs, truncated } = groupByResponse
return (
<div className="flex-1 min-h-0 overflow-auto" data-attr="logs-group-by-results">
- <LemonBanner type="warning" className="m-2">
- Prototype — grouped results are mocked. This visualizes the group-by lens; no real query runs.
- </LemonBanner>
- <div className="px-2 pb-1 text-muted text-xs">
- {humanFriendlyNumber(rows.length)} groups found (based on {humanFriendlyNumber(totalLogs)} logs)
- </div>
+ {!groupByResponseLoading && !groupByError && total_groups > 0 && (
+ <div className="px-2 py-1 text-muted text-xs">
+ {truncated
+ ? `Top ${humanFriendlyNumber(groups.length)} of ${humanFriendlyNumber(total_groups)} groups`
+ : `${humanFriendlyNumber(total_groups)} groups`}{' '}
+ (based on {humanFriendlyNumber(total_logs)} logs)
+ </div>
+ )}
<LemonTable
- columns={[
- {
- title: groupBy,
- key: 'value',
- render: (_, row) => <span className="font-mono text-xs">{row.value}</span>,
- },
- {
- title: 'Logs',
- key: 'count',
- align: 'right',
- render: (_, row) => humanFriendlyNumber(row.count),
- sorter: (a, b) => a.count - b.count,
- },
- {
- title: 'Errors',
- key: 'errorCount',
- align: 'right',
- render: (_, row) =>
- row.errorCount > 0 ? (
- <span className="text-danger font-semibold">{humanFriendlyNumber(row.errorCount)}</span>
- ) : (
- <span className="text-muted">0</span>
- ),
- sorter: (a, b) => a.errorCount - b.errorCount,
- },
- {
- title: 'Last seen',
- key: 'lastSeen',
- render: (_, row) => <TZLabel time={dayjs().subtract(row.lastSeenMinutesAgo, 'minute')} />,
- sorter: (a, b) => a.lastSeenMinutesAgo - b.lastSeenMinutesAgo,
- },
- ]}
- dataSource={rows}
- defaultSorting={{ columnKey: 'count', order: -1 }}
+ columns={columns}
+ dataSource={groups}
+ loading={groupByResponseLoading}
+ // Ranking is a server concern: reflect the active order and re-query on change.
+ sorting={{ columnKey: orderGroupsBy, order: -1 }}
+ onSort={(sorting) => {
+ const columnKey = sorting?.columnKey as OrderGroupsByEnumApi | undefined
+ if (columnKey && SORTABLE_COLUMNS.includes(columnKey)) {
+ setOrderGroupsBy(columnKey)
+ }
+ }}
+ emptyState={
+ groupByError
+ ? 'Grouping failed — try a shorter time range or narrower filters'
+ : 'No groups found for the current filters'
+ }
rowKey="value"
size="small"
/>
diff --git a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
new file mode 100644
index 000000000000..934739802b69
--- /dev/null
+++ b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
@@ -0,0 +1,147 @@
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+import { logsGroupByCreate } from 'products/logs/frontend/generated/api'
+import type {
+ _LogPropertyFilterApi,
+ _LogsGroupByGroupApi,
+ _LogsGroupByResponseApi,
+ OrderGroupsByEnumApi,
+} from 'products/logs/frontend/generated/api.schemas'
+
+import type { logsGroupByLogicType } from './logsGroupByLogicType'
+
+export interface LogsGroupByLogicProps {
+ id: string
+}
+
+const EMPTY_RESPONSE: _LogsGroupByResponseApi = {
+ groups: [],
+ total_groups: 0,
+ total_logs: 0,
+ truncated: false,
+}
+
+// Keyed by the Viewer's `id`: the logic mounts only while a grouping key is active (the
+// Viewer conditionally renders <LogsGroupByResults/>), so loading on mount + reloading on
+// the shared filter actions never runs the aggregation while the user is in plain Logs mode.
+export const logsGroupByLogic = kea<logsGroupByLogicType>([
+ props({ id: 'default' } as LogsGroupByLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsGroupBy', 'logsGroupByLogic', key]),
+
+ connect((props: LogsGroupByLogicProps) => ({
+ values: [
+ teamLogic,
+ ['currentTeamId'],
+ logsViewerFiltersLogic({ id: props.id }),
+ ['filters', 'utcDateRange', 'queryFilterGroup'],
+ logsViewerConfigLogic({ id: props.id }),
+ ['groupBy'],
+ ],
+ actions: [
+ logsViewerFiltersLogic({ id: props.id }),
+ [
+ 'setDateRange',
+ 'zoomDateRange',
+ 'setSeverityLevels',
+ 'setServiceNames',
+ 'setSearchTerm',
+ 'setFilters',
+ 'setFilterGroup',
+ 'setPinnedFilters',
+ ],
+ logsViewerConfigLogic({ id: props.id }),
+ ['setGroupBy'],
+ ],
+ })),
+
+ actions({
+ setOrderGroupsBy: (orderGroupsBy: OrderGroupsByEnumApi) => ({ orderGroupsBy }),
+ }),
+
+ loaders(({ values }) => ({
+ groupByResponse: [
+ EMPTY_RESPONSE,
+ {
+ loadGroups: async (debounceMs: number = 0, breakpoint) => {
+ await breakpoint(debounceMs)
+ if (!values.groupBy) {
+ return EMPTY_RESPONSE
+ }
+ return await logsGroupByCreate(String(values.currentTeamId), {
+ query: {
+ dateRange: values.utcDateRange,
+ severityLevels: values.filters.severityLevels,
+ serviceNames: values.filters.serviceNames,
+ searchTerm: values.filters.searchTerm || undefined,
+ // Same scoping as Logs/Patterns: `queryFilterGroup` folds in any pinned
+ // filters from an embedded viewer, so a scoped viewer can't aggregate
+ // project-wide logs.
+ filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],
+ groupBy: values.groupBy.key,
+ groupBySource: values.groupBy.source,
+ orderGroupsBy: values.orderGroupsBy,
+ },
+ })
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ orderGroupsBy: [
+ 'log_count' as OrderGroupsByEnumApi,
+ {
+ setOrderGroupsBy: (_, { orderGroupsBy }) => orderGroupsBy,
+ },
+ ],
+ // A failed aggregation (e.g. the scan exceeding its byte budget) must surface as an
+ // error, not render as "no groups found" — that would misrepresent the data.
+ groupByError: [
+ null as string | null,
+ {
+ loadGroups: () => null,
+ loadGroupsSuccess: () => null,
+ loadGroupsFailure: (_, { error }) => error ?? 'Grouping failed',
+ },
+ ],
+ }),
+
+ selectors({
+ // Clear groups when the load fails so LemonTable's emptyState (and the error) shows
+ // instead of stale rows — kea-loaders leaves groupByResponse untouched on failure.
+ groups: [
+ (s) => [s.groupByResponse, s.groupByError],
+ (response: _LogsGroupByResponseApi, error: string | null): _LogsGroupByGroupApi[] =>
+ error ? [] : response.groups,
+ ],
+ }),
+
+ listeners(({ actions }) => {
+ // Debounced so a multi-filter change or search typing collapses into one request —
+ // kea's breakpoint cancels superseded loads before the fetch fires.
+ const reload = (): void => actions.loadGroups(300)
+ return {
+ setDateRange: reload,
+ zoomDateRange: reload,
+ setSeverityLevels: reload,
+ setServiceNames: reload,
+ setSearchTerm: reload,
+ setFilters: reload,
+ setFilterGroup: reload,
+ setPinnedFilters: reload,
+ // Immediate: switching the grouping key or ranking column is a deliberate click.
+ setGroupBy: () => actions.loadGroups(),
+ setOrderGroupsBy: () => actions.loadGroups(),
+ }
+ }),
+
+ afterMount(({ actions }) => {
+ actions.loadGroups()
+ }),
+])
diff --git a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
index 18ca0b4d511a..aaccbb4717da 100644
--- a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
@@ -9,10 +9,18 @@ import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import { logsPatternsLogic } from 'products/logs/frontend/components/LogsPatterns/logsPatternsLogic'
+import type { GroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { logsViewerConfigLogic } from './config/logsViewerConfigLogic'
import { LogsViewerToolbar } from './LogsViewerToolbar'
+// Maps the picker's taxonomic group onto the group-by endpoint's source vocabulary.
+const TAXONOMIC_GROUP_TO_SOURCE: Partial<Record<TaxonomicFilterGroupType, GroupBySourceEnumApi>> = {
+ [TaxonomicFilterGroupType.Logs]: 'column',
+ [TaxonomicFilterGroupType.LogAttributes]: 'log',
+ [TaxonomicFilterGroupType.LogResourceAttributes]: 'resource',
+}
+
export interface LogsDisplayBarProps {
id: string
// Whether to render the facet-rail collapse toggle in the frame (facet-rail layout only).
@@ -80,8 +88,12 @@ export const LogsDisplayBar = ({
// `message` is not a grouping key — high-cardinality free text is the
// Patterns lens's job. Excluding it also drops the message-search item.
excludedProperties={{ [TaxonomicFilterGroupType.Logs]: ['message'] }}
- value={groupBy ?? undefined}
- onChange={(value) => setGroupBy(value || null)}
+ value={groupBy?.key}
+ onChange={(value, groupType) =>
+ setGroupBy(
+ value ? { key: value, source: TAXONOMIC_GROUP_TO_SOURCE[groupType] ?? 'log' } : null
+ )
+ }
allowClear
placeholder="Group by"
renderValue={(value) => (
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index c4af11074526..f1c9e4f2742d 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -344,13 +344,13 @@ function LogsViewerContent({
// Gate on the flag too, so the patterns query stays unreachable when the flag is off regardless
// of the (non-persisted) viewMode state.
const inPatternsMode = showPatternsView && viewMode === 'patterns'
- // Group-by (prototype, logs-group-by flag): an active grouping swaps the Logs lens's results
+ // Group-by (logs-group-by flag): an active grouping swaps the Logs lens's results
// for the grouped table. Double-gated like Patterns so it's unreachable with the flag off.
const inGroupByMode = showGroupBy && !inPatternsMode && groupBy !== null
const resultsRegion = inPatternsMode ? (
<LogsPatterns id={id} />
) : inGroupByMode && groupBy ? (
- <LogsGroupByResults groupBy={groupBy} />
+ <LogsGroupByResults id={id} />
) : (
logList
)
diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
index ad9b587a9dda..c554ae59c16f 100644
--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
@@ -4,6 +4,7 @@ import { LogsSparklineBreakdownBy } from '~/queries/schema/schema-general'
import { FilterLogicalOperator } from '~/types'
import { LogsViewerConfig, LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
+import type { GroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'
import { LogsOrderBy } from 'products/logs/frontend/types'
import type { logsViewerConfigLogicType } from './logsViewerConfigLogicType'
@@ -25,6 +26,13 @@ export const DEFAULT_ORDER_BY: LogsOrderBy = 'latest'
export type LogsViewerViewMode = 'logs' | 'patterns'
export const DEFAULT_VIEW_MODE: LogsViewerViewMode = 'logs'
+export interface LogsViewerGroupBy {
+ key: string
+ // Where the key lives, in the group-by endpoint's vocabulary: "log" / "resource"
+ // attribute maps, or "column" for top-level log fields (severity_level, trace_id, span_id).
+ source: GroupBySourceEnumApi
+}
+
export interface LogsViewerConfigProps {
id: string
}
@@ -45,7 +53,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
toggleSparklineCollapsed: true,
setFacetRailCollapsed: (facetRailCollapsed: boolean) => ({ facetRailCollapsed }),
setViewMode: (viewMode: LogsViewerViewMode) => ({ viewMode }),
- setGroupBy: (groupBy: string | null) => ({ groupBy }),
+ setGroupBy: (groupBy: LogsViewerGroupBy | null) => ({ groupBy }),
}),
reducers({
@@ -96,7 +104,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
// The attribute to group results by (behind the logs-group-by flag); null = ungrouped.
// Not persisted — grouping is an explicit, per-visit exploration like Patterns.
groupBy: [
- null as string | null,
+ null as LogsViewerGroupBy | null,
{
setGroupBy: (_, { groupBy }) => groupBy,
},
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index f0902356439a..826685357614 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1053,6 +1053,92 @@ export interface _LogsFacetValuesResponseApi {
results: _LogFacetValueApi[]
}
+/**
+ * * `log` - log
+ * * `resource` - resource
+ * * `column` - column
+ */
+export type GroupBySourceEnumApi = (typeof GroupBySourceEnumApi)[keyof typeof GroupBySourceEnumApi]
+
+export const GroupBySourceEnumApi = {
+ Log: 'log',
+ Resource: 'resource',
+ Column: 'column',
+} as const
+
+/**
+ * * `log_count` - log_count
+ * * `error_count` - error_count
+ * * `last_seen` - last_seen
+ */
+export type OrderGroupsByEnumApi = (typeof OrderGroupsByEnumApi)[keyof typeof OrderGroupsByEnumApi]
+
+export const OrderGroupsByEnumApi = {
+ LogCount: 'log_count',
+ ErrorCount: 'error_count',
+ LastSeen: 'last_seen',
+} as const
+
+export interface _LogsGroupByBodyApi {
+ /** Date range to aggregate over. Defaults to last hour. */
+ dateRange?: _DateRangeApi
+ /** Filter by log severity levels before grouping. */
+ severityLevels?: SeverityLevelsEnumApi[]
+ /** Restrict grouping to these service names. */
+ serviceNames?: string[]
+ /** Full-text search term to filter log bodies before grouping. */
+ searchTerm?: string
+ /** Property filters applied before grouping. Same shape as the query-logs endpoint. */
+ filterGroup?: _LogPropertyFilterApi[]
+ /** The key to group logs by — an attribute key (e.g. "session_id", "service.name") or, when groupBySource is "column", one of the top-level log fields: "severity_level", "trace_id", "span_id". */
+ groupBy: string
+ /** Where the grouping key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields.
+ *
+ * * `log` - log
+ * * `resource` - resource
+ * * `column` - column */
+ groupBySource?: GroupBySourceEnumApi
+ /** Aggregate to rank groups by (descending): "log_count" for the noisiest groups, "error_count" for the most failing, "last_seen" for the most recent.
+ *
+ * * `log_count` - log_count
+ * * `error_count` - error_count
+ * * `last_seen` - last_seen */
+ orderGroupsBy?: OrderGroupsByEnumApi
+ /**
+ * Maximum number of groups to return (top-N by orderGroupsBy). Defaults to 100.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+}
+
+export interface _LogsGroupByRequestApi {
+ /** The group-by query to execute. */
+ query: _LogsGroupByBodyApi
+}
+
+export interface _LogsGroupByGroupApi {
+ /** The grouped attribute value identifying this group. */
+ value: string
+ /** Number of matching logs in this group. */
+ log_count: number
+ /** Number of matching logs in this group at severity "error" or "fatal". */
+ error_count: number
+ /** ISO 8601 timestamp of the most recent matching log in this group. */
+ last_seen: string
+}
+
+export interface _LogsGroupByResponseApi {
+ /** Top groups ordered by the requested aggregate, descending. Capped at `limit`. */
+ groups: _LogsGroupByGroupApi[]
+ /** Total distinct group values matching the filters, before the top-N cap. */
+ total_groups: number
+ /** Total matching logs across all groups (rows without the grouping key are excluded). */
+ total_logs: number
+ /** True when more groups matched than were returned (total_groups > groups length). */
+ truncated: boolean
+}
+
export interface _LogsPatternsBodyApi {
/** Date range to mine patterns from. Defaults to last hour. */
dateRange?: _DateRangeApi
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 0f9ac43035c6..1e56084aa7d2 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -43,6 +43,8 @@ import type {
_LogsCountResponseApi,
_LogsFacetValuesRequestApi,
_LogsFacetValuesResponseApi,
+ _LogsGroupByRequestApi,
+ _LogsGroupByResponseApi,
_LogsPatternsRequestApi,
_LogsPatternsResponseApi,
_LogsQueryRequestApi,
@@ -399,6 +401,23 @@ export const logsFacetValuesCreate = async (
})
}
+export const getLogsGroupByCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/logs/group-by/`
+}
+
+export const logsGroupByCreate = async (
+ projectId: string,
+ _logsGroupByRequestApi: _LogsGroupByRequestApi,
+ options?: RequestInit
+): Promise<_LogsGroupByResponseApi> => {
+ return apiMutator<_LogsGroupByResponseApi>(getLogsGroupByCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_logsGroupByRequestApi),
+ })
+}
+
export const getLogsHasLogsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/logs/has_logs/`
}
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 2a44c2feaa84..29ebbfca5835 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -709,6 +709,118 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({
.describe('The facet values query to execute.'),
})
+export const logsGroupByCreateBodyQueryOneGroupBySourceDefault = `log`
+export const logsGroupByCreateBodyQueryOneOrderGroupsByDefault = `log_count`
+export const logsGroupByCreateBodyQueryOneLimitDefault = 100
+export const logsGroupByCreateBodyQueryOneLimitMax = 500
+
+export const LogsGroupByCreateBody = /* @__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 to aggregate over. 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 before grouping.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Restrict grouping to these service names.'),
+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies before grouping.'),
+ 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',
+ '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\* `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\* `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 applied before grouping. Same shape as the query-logs endpoint.'),
+ groupBy: zod
+ .string()
+ .describe(
+ 'The key to group logs by — an attribute key (e.g. \"session_id\", \"service.name\") or, when groupBySource is \"column\", one of the top-level log fields: \"severity_level\", \"trace_id\", \"span_id\".'
+ ),
+ groupBySource: zod
+ .enum(['log', 'resource', 'column'])
+ .describe('\* `log` - log\n\* `resource` - resource\n\* `column` - column')
+ .default(logsGroupByCreateBodyQueryOneGroupBySourceDefault)
+ .describe(
+ 'Where the grouping key lives: \"log\" for log-level attributes, \"resource\" for resource-level attributes, \"column\" for top-level log fields.\n\n\* `log` - log\n\* `resource` - resource\n\* `column` - column'
+ ),
+ orderGroupsBy: zod
+ .enum(['log_count', 'error_count', 'last_seen'])
+ .describe('\* `log_count` - log_count\n\* `error_count` - error_count\n\* `last_seen` - last_seen')
+ .default(logsGroupByCreateBodyQueryOneOrderGroupsByDefault)
+ .describe(
+ 'Aggregate to rank groups by (descending): \"log_count\" for the noisiest groups, \"error_count\" for the most failing, \"last_seen\" for the most recent.\n\n\* `log_count` - log_count\n\* `error_count` - error_count\n\* `last_seen` - last_seen'
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(logsGroupByCreateBodyQueryOneLimitMax)
+ .default(logsGroupByCreateBodyQueryOneLimitDefault)
+ .describe('Maximum number of groups to return (top-N by orderGroupsBy). Defaults to 100.'),
+ })
+ .describe('The group-by query to execute.'),
+})
+
export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({
query: zod
.object({
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 9fac8c9e00cf..8e116fcc9f6c 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -355,6 +355,9 @@ tools:
response:
include:
- results
+ logs-group-by-create:
+ operation: logs_group_by_create
+ enabled: false
logs-has-logs-retrieve:
operation: logs_has_logs_retrieve
enabled: false
diff --git a/pyproject.toml b/pyproject.toml
index 8ef002a72187..546119abdf90 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -544,6 +544,7 @@ ignore_imports = [
# the facade.
"products.logs.backend.presentation.views.api -> products.logs.backend.count_query_runner",
"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.log_attributes_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.log_facet_values_query_runner",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f8b75885a35e..0175251f99f2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25145,6 +25145,20 @@ export namespace Schemas {
readonly created_at: string;
}
+ /**
+ * * `log` - log
+ * * `resource` - resource
+ * * `column` - column
+ */
+ export type GroupBySourceEnum = typeof GroupBySourceEnum[keyof typeof GroupBySourceEnum];
+
+
+ export const GroupBySourceEnum = {
+ Log: 'log',
+ Resource: 'resource',
+ Column: 'column',
+ } as const;
+
export interface GroupType {
readonly group_type: string;
readonly group_type_index: number;
@@ -31511,6 +31525,20 @@ export namespace Schemas {
Earliest: 'earliest',
} as const;
+ /**
+ * * `log_count` - log_count
+ * * `error_count` - error_count
+ * * `last_seen` - last_seen
+ */
+ export type OrderGroupsByEnum = typeof OrderGroupsByEnum[keyof typeof OrderGroupsByEnum];
+
+
+ export const OrderGroupsByEnum = {
+ LogCount: 'log_count',
+ ErrorCount: 'error_count',
+ LastSeen: 'last_seen',
+ } as const;
+
export type OrganizationTeamsItem = { [key: string]: unknown };
export type OrganizationProjectsItem = { [key: string]: unknown };
@@ -56276,6 +56304,66 @@ export namespace Schemas {
results: _LogFacetValue[];
}
+ export interface _LogsGroupByBody {
+ /** Date range to aggregate over. Defaults to last hour. */
+ dateRange?: _DateRange;
+ /** Filter by log severity levels before grouping. */
+ severityLevels?: SeverityLevelsEnum[];
+ /** Restrict grouping to these service names. */
+ serviceNames?: string[];
+ /** Full-text search term to filter log bodies before grouping. */
+ searchTerm?: string;
+ /** Property filters applied before grouping. Same shape as the query-logs endpoint. */
+ filterGroup?: _LogPropertyFilter[];
+ /** The key to group logs by — an attribute key (e.g. "session_id", "service.name") or, when groupBySource is "column", one of the top-level log fields: "severity_level", "trace_id", "span_id". */
+ groupBy: string;
+ /** Where the grouping key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields.
+ *
+ * * `log` - log
+ * * `resource` - resource
+ * * `column` - column */
+ groupBySource?: GroupBySourceEnum;
+ /** Aggregate to rank groups by (descending): "log_count" for the noisiest groups, "error_count" for the most failing, "last_seen" for the most recent.
+ *
+ * * `log_count` - log_count
+ * * `error_count` - error_count
+ * * `last_seen` - last_seen */
+ orderGroupsBy?: OrderGroupsByEnum;
+ /**
+ * Maximum number of groups to return (top-N by orderGroupsBy). Defaults to 100.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ }
+
+ export interface _LogsGroupByGroup {
+ /** The grouped attribute value identifying this group. */
+ value: string;
+ /** Number of matching logs in this group. */
+ log_count: number;
+ /** Number of matching logs in this group at severity "error" or "fatal". */
+ error_count: number;
+ /** ISO 8601 timestamp of the most recent matching log in this group. */
+ last_seen: string;
+ }
+
+ export interface _LogsGroupByRequest {
+ /** The group-by query to execute. */
+ query: _LogsGroupByBody;
+ }
+
+ export interface _LogsGroupByResponse {
+ /** Top groups ordered by the requested aggregate, descending. Capped at `limit`. */
+ groups: _LogsGroupByGroup[];
+ /** Total distinct group values matching the filters, before the top-N cap. */
+ total_groups: number;
+ /** Total matching logs across all groups (rows without the grouping key are excluded). */
+ total_logs: number;
+ /** True when more groups matched than were returned (total_groups > groups length). */
+ truncated: boolean;
+ }
+
export interface _LogsPatternsBody {
/** Date range to mine patterns from. Defaults to last hour. */
dateRange?: _DateRange;