:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): accept combined group-by dimensions in the group-by API (#72243)
Jon McCalluma73df10a88e1
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 3bfe51683f6d..00bc646ea24a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -568,6 +568,8 @@ SPECTACULAR_SETTINGS = {"IngestionWarningSeverityEnum": "posthog.api.ingestion_warnings_v2.INGESTION_WARNING_SEVERITIES",# Disambiguates from the same-valued inline enum on the signals LogsAlertStateChangeSignalExtra contract."LogsAlertThresholdOperatorEnum": "products.logs.backend.models.LogsAlertConfiguration.ThresholdOperator",+ # Shared by _LogsGroupByBody.groupBySource and _LogsGroupByDimension.source (labels == values).+ "LogsGroupBySourceEnum": "products.logs.backend.group_by_query_runner.GROUP_SOURCES","LLMProviderEnum": "products.ai_observability.backend.models.provider_keys.LLMProvider","EvaluationReportFrequencyEnum": ("products.ai_observability.backend.models.evaluation_reports.EvaluationReport.Frequency"diff --git a/products/logs/backend/group_by_query_runner.py b/products/logs/backend/group_by_query_runner.pyindex 6c5e2475b8fa..2ba05a39c650 100644--- a/products/logs/backend/group_by_query_runner.py+++ b/products/logs/backend/group_by_query_runner.py@@ -1,4 +1,5 @@-from typing import TYPE_CHECKING+from collections.abc import Sequence+from typing import TYPE_CHECKING, NamedTuplefrom zoneinfo import ZoneInfofrom posthog.schema import CachedLogsQueryResponse, LogsQuery@@ -28,6 +29,10 @@ MAX_EXECUTION_TIME = 60DEFAULT_GROUP_LIMIT = 100MAX_GROUP_LIMIT = 500+# Cap on combined group-by dimensions: each extra dimension multiplies group cardinality+# and widens the GROUP BY tuple, while the scan cost stays roughly flat.+MAX_GROUP_DIMENSIONS = 4+# 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.@@ -40,6 +45,12 @@ GROUPABLE_COLUMNS: dict[str, str] = {GROUP_SOURCES = ("log", "resource", "column")ORDER_FIELDS = ("log_count", "error_count", "last_seen")++class GroupByDimension(NamedTuple):+ key: str+ source: str++# Whole-set totals as window aggregates over the grouped rows: computed in one unsorted# pass, so the ORDER BY + LIMIT below can heap-select the top-N instead of fully sorting# every group, and the outer select only consumes N rows instead of the whole group set.@@ -47,19 +58,21 @@ _TOTALS_WINDOW = "count() OVER () AS group_count, sum(log_count) OVER () AS log_class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):- """Aggregates matching logs into groups by one attribute (or top-level field).-- Log attributes and top-level columns group in a 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. Resource attributes are- constant per `resource_fingerprint` (the hash of the whole resource map, part of- the sort key), so that path instead aggregates by the fingerprint — never reading- the wide `resource_attributes` map — and translates fingerprint → value through the- exploded `log_attributes` rollup, like LogFacetValuesQueryRunner's resource path.- 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.+ """Aggregates matching logs into groups by one or more attributes (or top-level fields).++ Grouping accepts up to MAX_GROUP_DIMENSIONS ordered dimensions; a group is the+ combination of its per-dimension values (GROUP BY tuple). Log attributes and+ top-level columns group in a 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. Resource attributes are constant per+ `resource_fingerprint` (the hash of the whole resource map, part of the sort key),+ so those dimensions instead aggregate by the fingerprint — never reading the wide+ `resource_attributes` map — and translate fingerprint → value through the exploded+ `log_attributes` rollup, one INNER JOIN per resource dimension, like+ LogFacetValuesQueryRunner's resource path. 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 therunner must be invoked via `calculate()` (which the logs API does) — never through@@ -73,23 +86,27 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRself,query: LogsQuery,*args,- group_by: str,- group_by_source: str = "log",+ group_bys: Sequence[tuple[str, str]],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 not 1 <= len(group_bys) <= MAX_GROUP_DIMENSIONS:+ raise ValueError(f"group_bys must contain between 1 and {MAX_GROUP_DIMENSIONS} dimensions")+ dimensions = [GroupByDimension(key=key, source=source) for key, source in group_bys]+ for dimension in dimensions:+ if not dimension.key:+ raise ValueError("every group-by dimension requires a key")+ if dimension.source not in GROUP_SOURCES:+ raise ValueError(f"group-by dimension source must be one of {GROUP_SOURCES}")+ if dimension.source == "column" and dimension.key not in GROUPABLE_COLUMNS:+ raise ValueError(f"a 'column' dimension's key must be one of {tuple(GROUPABLE_COLUMNS)}")+ if len(set(dimensions)) != len(dimensions):+ raise ValueError("group_bys must not contain duplicate dimensions")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.group_bys = dimensionsself.order_groups_by = order_groups_byself.group_limit = max(1, min(group_limit, MAX_GROUP_LIMIT))@@ -118,129 +135,128 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRmerge_tree_max_bytes_to_use_cache=MAX_READ_BYTES,)- def _group_expr(self) -> ast.Expr:+ def _dimension_expr(self, dimension: GroupByDimension) -> 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":+ # Resource dimensions never come through here: they aggregate by resource_fingerprint+ # and translate to values via the log_attributes rollup join.+ if dimension.source == "log":# Log attributes are physically stored in type-suffixed maps (`attributes_map_str`).# Read the key with a bare arrayElement on the physical map: the property-resolver# route (`attributes.key__str`) wraps the read in a has() guard that defeats the# bucketed map serialization and reads every key bucket, ~5x the bytes. A missing- # key yields '' here instead of NULL — both are excluded by the `_where` coalesce+ # key yields '' here instead of NULL — both are excluded by the WHERE coalesce# filter, so group results are identical. An explicit Call (not ArrayAccess) keeps# the resolver from folding the subscript back into a property chain.return ast.Call(name="arrayElement",- args=[ast.Field(chain=["attributes_map_str"]), ast.Constant(value=f"{self.group_by}__str")],+ args=[ast.Field(chain=["attributes_map_str"]), ast.Constant(value=f"{dimension.key}__str")],)- if self.group_by_source == "resource":- return ast.Field(chain=["resource_attributes", self.group_by])- return parse_expr(GROUPABLE_COLUMNS[self.group_by])+ return parse_expr(GROUPABLE_COLUMNS[dimension.key])def to_query(self) -> ast.SelectQuery:- if self.group_by_source == "resource":- return self._resource_query()- # nosemgrep: hogql-fstring-audit - only interpolates the int self.group_limit and the module-level _TOTALS_WINDOW constant (no user input); the grouping key flows in as an ast.Constant placeholder- query = parse_select(- f"""+ # One generated alias (g0..gN) per dimension, in request order; the aliases are+ # module-generated strings, so interpolating them into the template is safe.+ aliases = [f"g{i}" for i in range(len(self.group_bys))]+ scan_dims = [(a, d) for a, d in zip(aliases, self.group_bys) if d.source != "resource"]+ resource_dims = [(a, d) for a, d in zip(aliases, self.group_bys) if d.source == "resource"]++ placeholders: dict[str, ast.Expr] = {"order_field": ast.Field(chain=[self.order_groups_by])}++ # Scan over `logs`: group by the non-resource dimension expressions plus (when any+ # resource dimension exists) the fingerprint. Rows without a non-resource dimension's+ # 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 are excluded via+ # coalesce. Fresh AST nodes per placeholder — resolution annotates nodes in place.+ where_exprs = self._base_where()+ scan_cols = []+ for alias, dimension in scan_dims:+ placeholders[f"expr_{alias}"] = self._dimension_expr(dimension)+ where_exprs.append(+ parse_expr("coalesce({expr}, '') != ''", placeholders={"expr": self._dimension_expr(dimension)})+ )+ scan_cols.append(f"{{expr_{alias}}} AS {alias}")+ placeholders["where"] = ast.And(exprs=where_exprs)+ if resource_dims:+ scan_cols.append("resource_fingerprint")+ scan_group_cols = [alias for alias, _ in scan_dims] + (["resource_fingerprint"] if resource_dims else [])+ scan_sql = f"""SELECT- groupArray({self.group_limit})((group_value, log_count, error_count, last_seen)) AS groups,- coalesce(any(group_count), 0) AS total_groups,- coalesce(any(log_count_sum), 0) AS total_logs- FROM (+ {", ".join(scan_cols)},+ 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 {", ".join(scan_group_cols)}+ """++ if resource_dims:+ # Resource attributes are fixed per resource_fingerprint (the fingerprint IS the+ # hash of the whole map), so the scan aggregates by the sort-key UInt64 alone and+ # each resource dimension's fingerprint → value translation comes from the+ # log_attributes rollup — the wide resource_attributes map is never read. The+ # INNER JOIN doubles as that dimension's "has this attribute, non-empty" filter:+ # fingerprints without the key (or with '' as the value) have no mapping row, so+ # their logs drop out of groups and totals alike.+ join_sql_parts = []+ for alias, dimension in resource_dims:+ placeholders[f"attribute_key_{alias}"] = ast.Constant(value=dimension.key)+ # Pruning only: the mapping is time-invariant, but bounding time_bucket keeps+ # the rollup read to the parts covering the window. The rollup's time_bucket is+ # toStartOfInterval(timestamp, 10min), so a log with timestamp >= date_from can+ # only land in a bucket >= toStartOfInterval(date_from, 10min) — the tightest+ # lower bound that still covers every in-window row (matches LogFacetValues).+ placeholders[f"date_from_{alias}"] = ast.Constant(value=self.query_date_range.date_from())+ placeholders[f"date_to_{alias}"] = ast.Constant(value=self.query_date_range.date_to())+ join_sql_parts.append(f"""+ INNER JOIN (+ SELECT+ resource_fingerprint,+ any(attribute_value) AS group_value+ FROM log_attributes+ WHERE attribute_type = 'resource'+ AND attribute_key = {{attribute_key_{alias}}}+ AND attribute_value != ''+ AND time_bucket >= toStartOfInterval({{date_from_{alias}}}, toIntervalMinute(10))+ AND time_bucket <= {{date_to_{alias}}}+ GROUP BY resource_fingerprint+ ) AS mapping_{alias}+ ON agg.resource_fingerprint = mapping_{alias}.resource_fingerprint+ """)+ grouped_cols = [f"agg.{alias} AS {alias}" for alias, _ in scan_dims] + [+ f"mapping_{alias}.group_value AS {alias}" for alias, _ in resource_dims+ ]+ grouped_sql = f"""SELECT- group_value, log_count, error_count, last_seen,- {_TOTALS_WINDOW}- 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- LIMIT {self.group_limit}- )- """,- placeholders={- # 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+ {", ".join(grouped_cols)},+ sum(agg.log_count) AS log_count,+ sum(agg.error_count) AS error_count,+ max(agg.last_seen) AS last_seen+ FROM ({scan_sql}) AS agg+ {" ".join(join_sql_parts)}+ GROUP BY {", ".join(aliases)}+ """+ else:+ grouped_sql = scan_sql- def _resource_query(self) -> ast.SelectQuery:- # Resource attributes are fixed per resource_fingerprint (the fingerprint IS the- # hash of the whole map), so the scan aggregates by the sort-key UInt64 alone and- # the fingerprint → attribute-value translation comes from the log_attributes- # rollup — the wide resource_attributes map is never read. The INNER JOIN doubles- # as the "has this attribute, non-empty" filter the map path expresses via- # coalesce(...) != '': fingerprints without the key (or with '' as the value)- # have no mapping row, so their logs drop out of groups and totals alike.- # nosemgrep: hogql-fstring-audit - only interpolates the int self.group_limit and the module-level _TOTALS_WINDOW constant (no user input); attribute_key/date bounds flow in as ast.Constant placeholders+ # nosemgrep: hogql-fstring-audit - only interpolates the int self.group_limit, the module-level _TOTALS_WINDOW constant, and generated g0..gN aliases (no user input); grouping keys and date bounds flow in as ast placeholdersquery = parse_select(f"""SELECT- groupArray({self.group_limit})((group_value, log_count, error_count, last_seen)) AS groups,+ groupArray({self.group_limit})((tuple({", ".join(aliases)}), log_count, error_count, last_seen)) AS groups,coalesce(any(group_count), 0) AS total_groups,coalesce(any(log_count_sum), 0) AS total_logsFROM (SELECT- group_value, log_count, error_count, last_seen,+ {", ".join(aliases)}, log_count, error_count, last_seen,{_TOTALS_WINDOW}- FROM (- SELECT- mapping.group_value AS group_value,- sum(agg.log_count) AS log_count,- sum(agg.error_count) AS error_count,- max(agg.last_seen) AS last_seen- FROM (- SELECT- resource_fingerprint,- 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 resource_fingerprint- ) AS agg- INNER JOIN (- SELECT- resource_fingerprint,- any(attribute_value) AS group_value- FROM log_attributes- WHERE attribute_type = 'resource'- AND attribute_key = {{attribute_key}}- AND attribute_value != ''- AND time_bucket >= toStartOfInterval({{date_from}}, toIntervalMinute(10))- AND time_bucket <= {{date_to}}- GROUP BY resource_fingerprint- ) AS mapping- ON agg.resource_fingerprint = mapping.resource_fingerprint- GROUP BY group_value- )- ORDER BY {{order_field}} DESC, group_value ASC+ FROM ({grouped_sql})+ ORDER BY {{order_field}} DESC, {", ".join(f"{alias} ASC" for alias in aliases)}LIMIT {self.group_limit})""",- placeholders={- "where": ast.And(exprs=self._base_where()),- "attribute_key": ast.Constant(value=self.group_by),- # Pruning only: the mapping is time-invariant, but bounding time_bucket keeps- # the rollup read to the parts covering the window. The rollup's time_bucket is- # toStartOfInterval(timestamp, 10min), so a log with timestamp >= date_from can- # only land in a bucket >= toStartOfInterval(date_from, 10min) — the tightest- # lower bound that still covers every in-window row (matches LogFacetValues).- "date_from": ast.Constant(value=self.query_date_range.date_from()),- "date_to": ast.Constant(value=self.query_date_range.date_to()),- "order_field": ast.Field(chain=[self.order_groups_by]),- },+ placeholders=placeholders,)assert isinstance(query, ast.SelectQuery)return query@@ -259,17 +275,6 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR),]- def _where(self) -> ast.Expr:- # 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._base_where(),- parse_expr("coalesce({group_expr}, '') != ''", placeholders={"group_expr": self._group_expr()}),- ]- )-def _calculate(self) -> LogsQueryResponse:# The group-by templates only reference posthog-native tables (logs, log_attributes)# and the grouping key is a bound constant, so hand the executor a plain posthog-only@@ -297,12 +302,15 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRgroups_raw, total_groups, total_logs = response.results[0] if response.results else ([], 0, 0)groups = [{- "value": value,+ # `value` mirrors the first dimension for single-dimension callers; `values`+ # carries every dimension's value in request order.+ "value": values[0],+ "values": list(values),"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+ for values, log_count, error_count, last_seen in groups_raw]return LogsQueryResponse(results={diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 60e820efcb8b..28e5f0d9ce90 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -51,6 +51,7 @@ from products.logs.backend.count_ranges_query_runner import (from products.logs.backend.group_by_query_runner import (DEFAULT_GROUP_LIMIT,GROUP_SOURCES,+ MAX_GROUP_DIMENSIONS,MAX_GROUP_LIMIT,ORDER_FIELDS,LogsGroupByQueryRunner,@@ -929,6 +930,24 @@ class _LogsPatternsDiffResponseSerializer(serializers.Serializer):)+class _LogsGroupByDimensionSerializer(serializers.Serializer):+ key = serializers.CharField(+ help_text=(+ 'The key this dimension groups by — an attribute key (e.g. "session_id", "service.name") '+ 'or, when source is "column", one of the top-level log fields: '+ '"severity_level", "trace_id", "span_id".'+ ),+ )+ source = serializers.ChoiceField( # type: ignore[assignment] # field named `source` shadows DRF Field.source+ choices=list(GROUP_SOURCES),+ default="log",+ help_text=(+ 'Where this dimension\'s key lives: "log" for log-level attributes, "resource" for '+ 'resource-level attributes, "column" for top-level log fields.'+ ),+ )++class _LogsGroupByBodySerializer(serializers.Serializer):dateRange = _DateRangeSerializer(required=False,@@ -956,10 +975,11 @@ class _LogsGroupByBodySerializer(serializers.Serializer):help_text="Property filters applied before grouping. Same shape as the query-logs endpoint.",)groupBy = serializers.CharField(+ required=False,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".'+ '"severity_level", "trace_id", "span_id". Ignored when groupBys is provided.'),)groupBySource = serializers.ChoiceField(@@ -967,7 +987,18 @@ class _LogsGroupByBodySerializer(serializers.Serializer):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.'+ 'resource-level attributes, "column" for top-level log fields. Ignored when groupBys is provided.'+ ),+ )+ groupBys = serializers.ListField(+ child=_LogsGroupByDimensionSerializer(),+ required=False,+ min_length=1,+ max_length=MAX_GROUP_DIMENSIONS,+ help_text=(+ "Ordered group-by dimensions to combine (a group is one combination of per-dimension "+ f"values), up to {MAX_GROUP_DIMENSIONS}. Takes precedence over groupBy/groupBySource; "+ "one of the two must be provided."),)orderGroupsBy = serializers.ChoiceField(@@ -992,7 +1023,13 @@ class _LogsGroupByRequestSerializer(serializers.Serializer):class _LogsGroupByGroupSerializer(serializers.Serializer):- value = serializers.CharField(help_text="The grouped attribute value identifying this group.")+ value = serializers.CharField(+ help_text="The first dimension's grouped value. Kept for single-dimension callers; prefer `values`."+ )+ values = serializers.ListField(+ child=serializers.CharField(),+ help_text="This group's values, one per requested dimension, in request order.",+ )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".',@@ -1499,12 +1536,23 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):query = self._filtered_logs_query(query_data)+ raw_dimensions = query_data.get("groupBys")+ if raw_dimensions is not None:+ # The dimension serializer is the request contract; running it here keeps the+ # enforced shape (required key, source vocabulary, defaults) identical to the+ # published schema instead of hand-rolling a second definition.+ dimension_serializer = _LogsGroupByDimensionSerializer(data=raw_dimensions, many=True)+ if not dimension_serializer.is_valid():+ return Response({"error": str(dimension_serializer.errors)}, status=status.HTTP_400_BAD_REQUEST)+ group_bys = [(d["key"], d["source"]) for d in dimension_serializer.validated_data]+ else:+ group_bys = [(query_data.get("groupBy", ""), query_data.get("groupBySource", "log"))]+try:runner = LogsGroupByQueryRunner(team=self.team,query=query,- group_by=query_data.get("groupBy", ""),- group_by_source=query_data.get("groupBySource", "log"),+ group_bys=group_bys,order_groups_by=query_data.get("orderGroupsBy", "log_count"),group_limit=int(query_data.get("limit", DEFAULT_GROUP_LIMIT)),)@@ -1520,7 +1568,8 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):request.user,"logs group by queried",{- "group_by_source": query_data.get("groupBySource", "log"),+ "group_by_source": group_bys[0][1],+ "group_dimensions": len(group_bys),"order_groups_by": query_data.get("orderGroupsBy", "log_count"),"groups_count": len(results.get("groups", [])),"truncated": results.get("truncated"),diff --git a/products/logs/backend/test/test_group_by_query_runner.py b/products/logs/backend/test/test_group_by_query_runner.pyindex 5cb2fe51739c..f3acbabd5751 100644--- a/products/logs/backend/test/test_group_by_query_runner.py+++ b/products/logs/backend/test/test_group_by_query_runner.py@@ -3,6 +3,8 @@ import jsonfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from django.urls import resolve+from parameterized import parameterizedfrom rest_framework import status@@ -46,8 +48,9 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):def _run(self,- group_by: str,+ group_by: str = "",group_by_source: str = "log",+ group_bys: list[tuple[str, str]] | None = None,order_groups_by: str = "log_count",group_limit: int = 100,service_names: list[str] | None = None,@@ -62,8 +65,7 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):runner = LogsGroupByQueryRunner(team=self.team,query=query,- group_by=group_by,- group_by_source=group_by_source,+ group_bys=group_bys if group_bys is not None else [(group_by, group_by_source)],order_groups_by=order_groups_by,group_limit=group_limit,)@@ -91,8 +93,20 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):assert results["total_logs"] == 5assert results["truncated"] is Falses1, 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"}+ assert s1 == {+ "value": "s1",+ "values": ["s1"],+ "log_count": 3,+ "error_count": 2,+ "last_seen": "2026-06-23T12:02:00+00:00",+ }+ assert s2 == {+ "value": "s2",+ "values": ["s2"],+ "log_count": 2,+ "error_count": 0,+ "last_seen": "2026-06-23T12:06:00+00:00",+ }@parameterized.expand([@@ -172,6 +186,73 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):assert [g["value"] for g in results["groups"]] == ["s1"]+ @freeze_time(_FROZEN_NOW)+ def test_combined_dimensions_group_by_value_tuples(self) -> None:+ # Combined grouping must count per value-combination with values in request order;+ # a row missing one of the log-attribute dimensions is not a group member.+ self._insert(+ [+ self._log(attributes={"session_id": "s1"}, severity="error", minute=0),+ self._log(attributes={"session_id": "s1"}, severity="error", minute=1),+ self._log(attributes={"session_id": "s1"}, severity="info", minute=2),+ self._log(attributes={"session_id": "s2"}, severity="info", minute=3),+ # No session_id: excluded from groups and totals.+ self._log(severity="info", minute=4),+ ]+ )++ results = self._run(group_bys=[("session_id", "log"), ("severity_level", "column")])++ assert results["total_groups"] == 3+ assert results["total_logs"] == 4+ assert [(g["values"], g["log_count"], g["error_count"]) for g in results["groups"]] == [+ (["s1", "error"], 2, 2),+ (["s1", "info"], 1, 0),+ (["s2", "info"], 1, 0),+ ]++ @freeze_time(_FROZEN_NOW)+ def test_combined_resource_dimension_joins_without_fanout(self) -> None:+ # A resource dimension inside a combination still translates via the fingerprint+ # join; broken composition would drop rows (missed join) or double-count (fan-out).+ self._insert(+ [+ self._log(resource_attributes={"env": "prod", "region": "us"}, severity="error", minute=0),+ self._log(resource_attributes={"env": "prod", "region": "us"}, severity="info", minute=1),+ self._log(resource_attributes={"env": "dev", "region": "us"}, severity="info", minute=2),+ # No env attribute: the INNER JOIN drops it from groups and totals.+ self._log(resource_attributes={"region": "us"}, severity="info", minute=3),+ ]+ )++ results = self._run(group_bys=[("env", "resource"), ("severity_level", "column")])++ assert results["total_groups"] == 3+ assert results["total_logs"] == 3+ assert [(g["values"], g["log_count"]) for g in results["groups"]] == [+ (["dev", "info"], 1),+ (["prod", "error"], 1),+ (["prod", "info"], 1),+ ]++ @parameterized.expand(+ [+ ("too_many_dimensions", [("a", "log"), ("b", "log"), ("c", "log"), ("d", "log"), ("e", "log")]),+ ("duplicate_dimensions", [("session_id", "log"), ("session_id", "log")]),+ ("empty_dimensions", []),+ ]+ )+ def test_invalid_group_bys_raise(self, _name: str, group_bys: list[tuple[str, 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_bys=group_bys)+@parameterized.expand([("missing_group_by", "", "log", "log_count"),@@ -194,13 +275,21 @@ class TestGroupByQueryRunner(ClickhouseTestMixin, APIBaseTest):LogsGroupByQueryRunner(team=self.team,query=query,- group_by=group_by,- group_by_source=source,+ group_bys=[(group_by, source)],order_groups_by=order,)class TestGroupByAPI(ClickhouseTestMixin, APIBaseTest):+ @classmethod+ def setUpClass(cls) -> None:+ super().setUpClass()+ # The process's first request imports the URLconf, which transitively pulls+ # langchain's pydantic.v1 shim — an import that crashes if it first runs under+ # freeze_time (FakeDate breaks pydantic.v1's date metaclass). Load it unfrozen+ # so no frozen test is the one to trigger it.+ resolve("/")+@freeze_time(_FROZEN_NOW)def test_endpoint_returns_grouped_results(self) -> None:sync_execute(@@ -232,9 +321,66 @@ class TestGroupByAPI(ClickhouseTestMixin, APIBaseTest):data = response.json()assert data["total_groups"] == 1assert data["groups"] == [- {"value": "s1", "log_count": 1, "error_count": 1, "last_seen": "2026-06-23T12:00:00+00:00"}+ {+ "value": "s1",+ "values": ["s1"],+ "log_count": 1,+ "error_count": 1,+ "last_seen": "2026-06-23T12:00:00+00:00",+ }]+ @freeze_time(_FROZEN_NOW)+ def test_endpoint_accepts_combined_dimensions(self) -> None:+ # Wiring guard for the groupBys request shape: the view must parse the dimension+ # list (not fall back to the legacy single-key fields) and surface per-dimension+ # values in order.+ 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"},+ "groupBys": [+ {"key": "session_id", "source": "log"},+ {"key": "severity_level", "source": "column"},+ ],+ }+ },+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ data = response.json()+ assert [g["values"] for g in data["groups"]] == [["s1", "error"]]++ def test_endpoint_rejects_too_many_dimensions(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/logs/group-by",+ data={+ "query": {+ "dateRange": {"date_from": "-1h"},+ "groupBys": [{"key": f"k{i}", "source": "log"} for i in range(5)],+ }+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+def test_endpoint_rejects_missing_group_by(self) -> None:response = self.client.post(f"/api/projects/{self.team.id}/logs/group-by",diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.tsindex 1d81ffe591ec..1f26a3500baf 100644--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts@@ -11,7 +11,7 @@ import {normalizeColumns,} from 'products/logs/frontend/components/LogsViewer/config/columns'import { LogsViewerConfig, LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'-import type { GroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'+import type { LogsGroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'import { AttributeColumnConfig, LogsOrderBy } from 'products/logs/frontend/types'import type { DateRange, LogSeverityLevel } from '../../../../../../frontend/src/queries/schema/schema-general'@@ -43,7 +43,7 @@ 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+ source: LogsGroupBySourceEnumApi}export interface LogsViewerConfigProps {diff --git a/products/logs/frontend/components/LogsViewer/groupBySource.test.ts b/products/logs/frontend/components/LogsViewer/groupBySource.test.tsindex 6c4f961e4ee9..b181b7e82028 100644--- a/products/logs/frontend/components/LogsViewer/groupBySource.test.ts+++ b/products/logs/frontend/components/LogsViewer/groupBySource.test.ts@@ -3,7 +3,7 @@ import * as path from 'path'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import type { GroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'+import type { LogsGroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'import { GROUPABLE_COLUMN_KEYS, resolveGroupBySource } from './groupBySource'@@ -11,7 +11,7 @@ describe('resolveGroupBySource', () => {// A recent for a top-level column is recorded under LogAttributes (the search bar stores it as// filter type `log`), so trusting the group would send source `log` and the aggregation reads a// missing attribute -> empty results. These keys must resolve to `column` regardless of group.- it.each<[string, TaxonomicFilterGroupType, GroupBySourceEnumApi]>([+ it.each<[string, TaxonomicFilterGroupType, LogsGroupBySourceEnumApi]>([['severity_level', TaxonomicFilterGroupType.LogAttributes, 'column'],['trace_id', TaxonomicFilterGroupType.LogAttributes, 'column'],['span_id', TaxonomicFilterGroupType.LogAttributes, 'column'],diff --git a/products/logs/frontend/components/LogsViewer/groupBySource.ts b/products/logs/frontend/components/LogsViewer/groupBySource.tsindex 414bdd3ca0a1..f0e6bf15efaa 100644--- a/products/logs/frontend/components/LogsViewer/groupBySource.ts+++ b/products/logs/frontend/components/LogsViewer/groupBySource.ts@@ -1,9 +1,9 @@import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import type { GroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'+import type { LogsGroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'// Maps the picker's taxonomic group onto the group-by endpoint's source vocabulary.-export const TAXONOMIC_GROUP_TO_SOURCE: Partial<Record<TaxonomicFilterGroupType, GroupBySourceEnumApi>> = {+export const TAXONOMIC_GROUP_TO_SOURCE: Partial<Record<TaxonomicFilterGroupType, LogsGroupBySourceEnumApi>> = {[TaxonomicFilterGroupType.Logs]: 'column',[TaxonomicFilterGroupType.LogAttributes]: 'log',[TaxonomicFilterGroupType.LogResourceAttributes]: 'resource',@@ -18,7 +18,7 @@ export const TAXONOMIC_GROUP_TO_SOURCE: Partial<Record<TaxonomicFilterGroupType,// This mirrors the backend dict by hand; `groupBySource.test.ts` fails if the two drift apart.export const GROUPABLE_COLUMN_KEYS = new Set<string>(['severity_level', 'trace_id', 'span_id'])-export function resolveGroupBySource(key: string, groupType: TaxonomicFilterGroupType): GroupBySourceEnumApi {+export function resolveGroupBySource(key: string, groupType: TaxonomicFilterGroupType): LogsGroupBySourceEnumApi {if (GROUPABLE_COLUMN_KEYS.has(key)) {return 'column'}diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 16fc4ac11a2d..181b945024e1 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1068,14 +1068,25 @@ export interface _LogsFacetValuesResponseApi {* * `resource` - resource* * `column` - column*/-export type GroupBySourceEnumApi = (typeof GroupBySourceEnumApi)[keyof typeof GroupBySourceEnumApi]+export type LogsGroupBySourceEnumApi = (typeof LogsGroupBySourceEnumApi)[keyof typeof LogsGroupBySourceEnumApi]-export const GroupBySourceEnumApi = {+export const LogsGroupBySourceEnumApi = {Log: 'log',Resource: 'resource',Column: 'column',} as const+export interface _LogsGroupByDimensionApi {+ /** The key this dimension groups by — an attribute key (e.g. "session_id", "service.name") or, when source is "column", one of the top-level log fields: "severity_level", "trace_id", "span_id". */+ key: string+ /** Where this dimension's key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields.+ *+ * * `log` - log+ * * `resource` - resource+ * * `column` - column */+ source?: LogsGroupBySourceEnumApi+}+/*** * `log_count` - log_count* * `error_count` - error_count@@ -1100,14 +1111,20 @@ export interface _LogsGroupByBodyApi {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.+ /** 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". Ignored when groupBys is provided. */+ groupBy?: string+ /** Where the grouping key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields. Ignored when groupBys is provided.** * `log` - log* * `resource` - resource* * `column` - column */- groupBySource?: GroupBySourceEnumApi+ groupBySource?: LogsGroupBySourceEnumApi+ /**+ * Ordered group-by dimensions to combine (a group is one combination of per-dimension values), up to 4. Takes precedence over groupBy/groupBySource; one of the two must be provided.+ * @minItems 1+ * @maxItems 4+ */+ groupBys?: _LogsGroupByDimensionApi[]/** 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@@ -1128,8 +1145,10 @@ export interface _LogsGroupByRequestApi {}export interface _LogsGroupByGroupApi {- /** The grouped attribute value identifying this group. */+ /** The first dimension's grouped value. Kept for single-dimension callers; prefer `values`. */value: string+ /** This group's values, one per requested dimension, in request order. */+ values: string[]/** Number of matching logs in this group. */log_count: number/** Number of matching logs in this group at severity "error" or "fatal". */diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 257bd89df54c..d60b150fa061 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -707,6 +707,9 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({})export const logsGroupByCreateBodyQueryOneGroupBySourceDefault = `log`+export const logsGroupByCreateBodyQueryOneGroupBysItemSourceDefault = `log`+export const logsGroupByCreateBodyQueryOneGroupBysMax = 4+export const logsGroupByCreateBodyQueryOneOrderGroupsByDefault = `log_count`export const logsGroupByCreateBodyQueryOneLimitDefault = 100export const logsGroupByCreateBodyQueryOneLimitMax = 500@@ -791,15 +794,39 @@ export const LogsGroupByCreateBody = /* @__PURE__ */ zod.object({.describe('Property filters applied before grouping. Same shape as the query-logs endpoint.'),groupBy: zod.string()+ .optional().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\".'+ '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\". Ignored when groupBys is provided.'),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'+ 'Where the grouping key lives: \"log\" for log-level attributes, \"resource\" for resource-level attributes, \"column\" for top-level log fields. Ignored when groupBys is provided.\n\n\* `log` - log\n\* `resource` - resource\n\* `column` - column'+ ),+ groupBys: zod+ .array(+ zod.object({+ key: zod+ .string()+ .describe(+ 'The key this dimension groups by — an attribute key (e.g. \"session_id\", \"service.name\") or, when source is \"column\", one of the top-level log fields: \"severity_level\", \"trace_id\", \"span_id\".'+ ),+ source: zod+ .enum(['log', 'resource', 'column'])+ .describe('\* `log` - log\n\* `resource` - resource\n\* `column` - column')+ .default(logsGroupByCreateBodyQueryOneGroupBysItemSourceDefault)+ .describe(+ 'Where this dimension\'s 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'+ ),+ })+ )+ .min(1)+ .max(logsGroupByCreateBodyQueryOneGroupBysMax)+ .optional()+ .describe(+ 'Ordered group-by dimensions to combine (a group is one combination of per-dimension values), up to 4. Takes precedence over groupBy\/groupBySource; one of the two must be provided.'),orderGroupsBy: zod.enum(['log_count', 'error_count', 'last_seen'])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 407dfb5c1163..7f7ad046f96f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29338,20 +29338,6 @@ 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;@@ -34481,6 +34467,20 @@ export namespace Schemas {url: string;}+ /**+ * * `log` - log+ * * `resource` - resource+ * * `column` - column+ */+ export type LogsGroupBySourceEnum = typeof LogsGroupBySourceEnum[keyof typeof LogsGroupBySourceEnum];+++ export const LogsGroupBySourceEnum = {+ Log: 'log',+ Resource: 'resource',+ Column: 'column',+ } as const;+export type LogsListWidgetCatalogEntryOpenApiWidgetType = typeof LogsListWidgetCatalogEntryOpenApiWidgetType[keyof typeof LogsListWidgetCatalogEntryOpenApiWidgetType];@@ -64432,6 +64432,17 @@ export namespace Schemas {results: _LogFacetValue[];}+ export interface _LogsGroupByDimension {+ /** The key this dimension groups by — an attribute key (e.g. "session_id", "service.name") or, when source is "column", one of the top-level log fields: "severity_level", "trace_id", "span_id". */+ key: string;+ /** Where this dimension's key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields.+ *+ * * `log` - log+ * * `resource` - resource+ * * `column` - column */+ source?: LogsGroupBySourceEnum;+ }+export interface _LogsGroupByBody {/** Date range to aggregate over. Defaults to last hour. */dateRange?: _DateRange;@@ -64443,14 +64454,20 @@ export namespace Schemas {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.+ /** 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". Ignored when groupBys is provided. */+ groupBy?: string;+ /** Where the grouping key lives: "log" for log-level attributes, "resource" for resource-level attributes, "column" for top-level log fields. Ignored when groupBys is provided.** * `log` - log* * `resource` - resource* * `column` - column */- groupBySource?: GroupBySourceEnum;+ groupBySource?: LogsGroupBySourceEnum;+ /**+ * Ordered group-by dimensions to combine (a group is one combination of per-dimension values), up to 4. Takes precedence over groupBy/groupBySource; one of the two must be provided.+ * @minItems 1+ * @maxItems 4+ */+ groupBys?: _LogsGroupByDimension[];/** 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@@ -64466,8 +64483,10 @@ export namespace Schemas {}export interface _LogsGroupByGroup {- /** The grouped attribute value identifying this group. */+ /** The first dimension's grouped value. Kept for single-dimension callers; prefer `values`. */value: string;+ /** This group's values, one per requested dimension, in request order. */+ values: string[];/** Number of matching logs in this group. */log_count: number;/** Number of matching logs in this group at severity "error" or "fatal". */