: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): facet values on resource attributes (#64911)
Jon McCallumd638fb106cd1
diff --git a/products/logs/backend/log_facet_values_query_runner.py b/products/logs/backend/log_facet_values_query_runner.pyindex 9b1c80d1d1d8..3fe71c62c6d8 100644--- a/products/logs/backend/log_facet_values_query_runner.py+++ b/products/logs/backend/log_facet_values_query_runner.py@@ -1,4 +1,5 @@from functools import cached_property+from typing import castfrom posthog.schema import CachedLogsQueryResponse, LogsQuery@@ -25,25 +26,45 @@ DEFAULT_FACET_LIMIT = 100class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):- """Per-value counts for a single facet field, cross-filtered.+ """Per-value counts for a single facet, cross-filtered.- Every active filter is applied except the one belonging to `facet_field`, so selecting a value- in a facet re-scopes the *other* facets without zeroing out the facet's own siblings — the- standard faceted-search behaviour.+ The facet is either a top-level column (severity_text/service_name) or a resource attribute map+ key (e.g. k8s.namespace.name). Every active filter is applied except the one belonging to this+ facet, so selecting a value re-scopes the *other* facets without zeroing out its own siblings —+ the standard faceted-search behaviour."""query: LogsQuerycached_response: CachedLogsQueryResponse- def __init__(self, query: LogsQuery, facet_field: str, *args, facet_search: str | None = None, **kwargs):+ def __init__(+ self,+ query: LogsQuery,+ *args,+ facet_field: str | None = None,+ facet_resource_attribute: str | None = None,+ facet_search: str | None = None,+ **kwargs,+ ):super().__init__(query, *args, **kwargs)- if facet_field not in FACET_FIELDS:+ # A facet targets either a top-level column (severity_text/service_name) or a resource+ # attribute map key (e.g. k8s.namespace.name). Exactly one must be supplied.+ if bool(facet_field) == bool(facet_resource_attribute):+ raise ValueError("Provide exactly one of facet_field or facet_resource_attribute")+ if facet_field is not None and facet_field not in FACET_FIELDS:raise ValueError(f"Unsupported facet field: {facet_field!r}")self.facet_field = facet_field+ self.facet_resource_attribute = facet_resource_attribute# Type-ahead over the facet's *own* values (e.g. service name contains "kafka"), distinct from# query.searchTerm which searches log bodies. Lets a dynamic facet search past the LIMIT window.self.facet_search = (facet_search or "").strip() or None+ def _facet_expr(self) -> ast.Expr:+ """The expression a facet groups by: a top-level column or a resource_attributes map lookup."""+ if self.facet_field is not None:+ return ast.Field(chain=[self.facet_field])+ return ast.Field(chain=["resource_attributes", cast(str, self.facet_resource_attribute)])+@cached_propertydef settings(self) -> HogQLGlobalSettings:# Fail fast rather than scan unbounded data, matching CountQueryRunner.@@ -70,10 +91,15 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQuedef to_query(self) -> ast.SelectQuery:# The day-precision time_bucket prune in where() is widened to exact timestamp bounds so the# counts match the requested window (same half-open pattern as CountQueryRunner).+ filter_builder = LogsFilterBuilder(+ self.query,+ self.team,+ self.query_date_range,+ exclude_facet_field=self.facet_field,+ exclude_resource_attribute=self.facet_resource_attribute,+ )exprs = [- LogsFilterBuilder(- self.query, self.team, self.query_date_range, exclude_facet_field=self.facet_field- ).where(),+ filter_builder.where(),parse_expr("timestamp >= {date_from} AND timestamp < {date_to}",placeholders={@@ -82,12 +108,16 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQue},),]+ if self.facet_resource_attribute is not None:+ # A missing map key reads back as '' in ClickHouse — exclude it so the facet doesn't show a+ # blank value counting every log that lacks the attribute.+ exprs.append(parse_expr("{facet} != ''", placeholders={"facet": self._facet_expr()}))if self.facet_search:exprs.append(parse_expr(- "{facet_field} ILIKE {pattern}",+ "{facet} ILIKE {pattern}",placeholders={- "facet_field": ast.Field(chain=[self.facet_field]),+ "facet": self._facet_expr(),# Escape %, _ and \ so user input matches literally instead of as wildcards."pattern": ast.Constant(value=ilike_pattern(self.facet_search)),},@@ -96,15 +126,15 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQuewhere = ast.And(exprs=exprs)query = parse_select("""- SELECT {facet_field} AS value, count() AS count+ SELECT {facet} AS value, count() AS countFROM logsWHERE {where}- GROUP BY {facet_field}- ORDER BY count() DESC, {facet_field} ASC+ GROUP BY {facet}+ ORDER BY count() DESC, {facet} ASCLIMIT {limit}""",placeholders={- "facet_field": ast.Field(chain=[self.facet_field]),+ "facet": self._facet_expr(),"where": where,"limit": ast.Constant(value=self.query.limit or DEFAULT_FACET_LIMIT),},diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.pyindex f6e68c9e4ee1..b9d95fe4152d 100644--- a/products/logs/backend/logs_query_runner.py+++ b/products/logs/backend/logs_query_runner.py@@ -209,6 +209,7 @@ class LogsFilterBuilder:team: "Team",query_date_range: QueryDateRange,exclude_facet_field: str | None = None,+ exclude_resource_attribute: str | None = None,):self.query = queryself.team = team@@ -217,6 +218,9 @@ class LogsFilterBuilder:# from the WHERE clause so facet counts reflect every *other* active filter — the standard# faceted-search behaviour where selecting a value doesn't zero out its siblings.self.exclude_facet_field = exclude_facet_field+ # The resource-attribute equivalent: when faceting on a resource attribute key, omit that+ # key's own log_resource_attribute filter so the facet doesn't zero out its own siblings.+ self.exclude_resource_attribute = exclude_resource_attributeself.resource_attribute_filters: list[LogPropertyFilter] = []self.resource_attribute_negative_filters: list[LogPropertyFilter] = []@@ -276,6 +280,14 @@ class LogsFilterBuilder:self.attribute_filters.insert(0, property_filter)+ if self.exclude_resource_attribute is not None:+ self.resource_attribute_filters = [+ f for f in self.resource_attribute_filters if f.key != self.exclude_resource_attribute+ ]+ self.resource_attribute_negative_filters = [+ f for f in self.resource_attribute_negative_filters if f.key != self.exclude_resource_attribute+ ]+def where(self) -> ast.Expr:exprs: list[ast.Expr] = []diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 5b0f214f4f5b..eda2b6dbb1c1 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -337,7 +337,17 @@ class _LogsFacetValuesResponseSerializer(serializers.Serializer):class _LogsFacetValuesBodySerializer(serializers.Serializer):facetField = serializers.ChoiceField(choices=["severity_text", "service_name"],- help_text="Column to facet on. Its own filter is excluded so counts reflect the other active filters.",+ required=False,+ allow_null=True,+ help_text="Top-level column to facet on. Provide exactly one of facetField or facetResourceAttribute. "+ "Its own filter is excluded so counts reflect the other active filters.",+ )+ facetResourceAttribute = serializers.CharField(+ required=False,+ allow_null=True,+ help_text="Resource attribute key to facet on (e.g. 'k8s.namespace.name'). Provide exactly one of "+ "facetField or facetResourceAttribute. Its own log_resource_attribute filter is excluded so counts "+ "reflect the other active filters.",)dateRange = _DateRangeSerializer(required=False, help_text="Date range. Defaults to last hour.")severityLevels = serializers.ListField(@@ -837,7 +847,10 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):query_data = request.data.get("query", {})facet_field = query_data.get("facetField")- if facet_field not in FACET_FIELDS:+ facet_resource_attribute = query_data.get("facetResourceAttribute")+ if bool(facet_field) == bool(facet_resource_attribute):+ raise ParseError("Provide exactly one of facetField or facetResourceAttribute")+ if facet_field and facet_field not in FACET_FIELDS:raise ParseError(f"facetField must be one of {sorted(FACET_FIELDS)}")date_range_data = query_data.get("dateRange")@@ -852,7 +865,11 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):)runner = LogFacetValuesQueryRunner(- team=self.team, query=query, facet_field=facet_field, facet_search=query_data.get("facetSearch")+ team=self.team,+ query=query,+ facet_field=facet_field or None,+ facet_resource_attribute=facet_resource_attribute or None,+ facet_search=query_data.get("facetSearch"),)response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS,diff --git a/products/logs/backend/test/test_log_facet_values.py b/products/logs/backend/test/test_log_facet_values.pyindex 1ebe0cdd4124..8672df96f019 100644--- a/products/logs/backend/test/test_log_facet_values.py+++ b/products/logs/backend/test/test_log_facet_values.py@@ -36,6 +36,12 @@ class TestLogFacetValues(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)return {r["value"]: r["count"] for r in response.json()["results"]}+ def _facet_attr(self, key: str, **filters) -> dict[str, int]:+ body = {"query": {"facetResourceAttribute": key, "dateRange": self.DATE_RANGE, **filters}}+ response = self.client.post(f"/api/projects/{self.team.pk}/logs/facet_values", body, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return {r["value"]: r["count"] for r in response.json()["results"]}+@parameterized.expand([("severity_text", "severityLevels"),@@ -98,3 +104,50 @@ class TestLogFacetValues(ClickhouseTestMixin, APIBaseTest):body = {"query": {"facetField": "body", "dateRange": self.DATE_RANGE}}response = self.client.post(f"/api/projects/{self.team.pk}/logs/facet_values", body, format="json")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand([("k8s.namespace.name",), ("k8s.pod.name",), ("k8s.node.name",)])+ def test_facet_on_resource_attribute_returns_values(self, key):+ """A resource attribute key can be faceted and returns its values with counts."""+ result = self._facet_attr(key)+ self.assertGreater(len(result), 0)+ self.assertTrue(all(count > 0 for count in result.values()))++ def test_resource_facet_excludes_blank_for_missing_key(self):+ """Logs lacking the key read back '' from the map; that bucket must not appear as a facet value."""+ # k8s.deployment.name is present on only some fixture rows (others carry a daemonset instead).+ result = self._facet_attr("k8s.deployment.name")+ self.assertGreater(len(result), 0)+ self.assertNotIn("", result)++ def test_resource_facet_ignores_its_own_filter(self):+ """Selecting a value via a log_resource_attribute filter must not change that facet's own counts."""+ base = self._facet_attr("k8s.namespace.name")+ own_value = next(iter(base))+ filter_group = [+ {"key": "k8s.namespace.name", "type": "log_resource_attribute", "operator": "exact", "value": own_value}+ ]+ self.assertEqual(self._facet_attr("k8s.namespace.name", filterGroup=filter_group), base)++ def test_resource_facet_honors_other_filter(self):+ """A top-level filter re-scopes a resource-attribute facet's counts (strictly fewer)."""+ base = self._facet_attr("k8s.namespace.name")+ scoped = self._facet_attr("k8s.namespace.name", severityLevels=["error"])+ self.assertLess(sum(scoped.values()), sum(base.values()))++ @parameterized.expand([("argo",), ("ARGO",)])+ def test_resource_facet_search_is_case_insensitive(self, term):+ searched = self._facet_attr("k8s.namespace.name", facetSearch=term)+ self.assertGreater(len(searched), 0)+ self.assertTrue(all(term.lower() in value.lower() for value in searched))++ def test_resource_facet_search_no_match_returns_empty(self):+ self.assertEqual(self._facet_attr("k8s.namespace.name", facetSearch="no-such-namespace-xyz"), {})++ def test_requires_exactly_one_facet_target(self):+ for query in (+ {}, # neither+ {"facetField": "service_name", "facetResourceAttribute": "k8s.pod.name"}, # both+ ):+ body = {"query": {**query, "dateRange": self.DATE_RANGE}}+ response = self.client.post(f"/api/projects/{self.team.pk}/logs/facet_values", body, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 050b79d77485..d144816a2f42 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1001,11 +1001,16 @@ export const FacetFieldEnumApi = {} as constexport interface _LogsFacetValuesBodyApi {- /** Column to facet on. Its own filter is excluded so counts reflect the other active filters.+ /** Top-level column to facet on. Provide exactly one of facetField or facetResourceAttribute. Its own filter is excluded so counts reflect the other active filters.** * `severity_text` - severity_text* * `service_name` - service_name */- facetField: FacetFieldEnumApi+ facetField?: FacetFieldEnumApi | null+ /**+ * Resource attribute key to facet on (e.g. 'k8s.namespace.name'). Provide exactly one of facetField or facetResourceAttribute. Its own log_resource_attribute filter is excluded so counts reflect the other active filters.+ * @nullable+ */+ facetResourceAttribute?: string | null/** Date range. Defaults to last hour. */dateRange?: _DateRangeApi/** Filter by log severity levels (ignored when faceting on severity_text). */diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex e9536ac7c015..c616c5b7ae5d 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -605,10 +605,21 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({query: zod.object({facetField: zod- .enum(['severity_text', 'service_name'])- .describe('\* `severity_text` - severity_text\n\* `service_name` - service_name')+ .union([+ zod+ .enum(['severity_text', 'service_name'])+ .describe('\* `severity_text` - severity_text\n\* `service_name` - service_name'),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Top-level column to facet on. Provide exactly one of facetField or facetResourceAttribute. Its own filter is excluded so counts reflect the other active filters.\n\n\* `severity_text` - severity_text\n\* `service_name` - service_name'+ ),+ facetResourceAttribute: zod+ .string()+ .nullish().describe(- 'Column to facet on. Its own filter is excluded so counts reflect the other active filters.\n\n\* `severity_text` - severity_text\n\* `service_name` - service_name'+ "Resource attribute key to facet on (e.g. 'k8s.namespace.name'). Provide exactly one of facetField or facetResourceAttribute. Its own log_resource_attribute filter is excluded so counts reflect the other active filters."),dateRange: zod.object({diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex be7c67b67287..9cfaba3a4ba8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -50294,11 +50294,16 @@ export namespace Schemas {}export interface _LogsFacetValuesBody {- /** Column to facet on. Its own filter is excluded so counts reflect the other active filters.+ /** Top-level column to facet on. Provide exactly one of facetField or facetResourceAttribute. Its own filter is excluded so counts reflect the other active filters.** * `severity_text` - severity_text* * `service_name` - service_name */- facetField: FacetFieldEnum;+ facetField?: FacetFieldEnum | null;+ /**+ * Resource attribute key to facet on (e.g. 'k8s.namespace.name'). Provide exactly one of facetField or facetResourceAttribute. Its own log_resource_attribute filter is excluded so counts reflect the other active filters.+ * @nullable+ */+ facetResourceAttribute?: string | null;/** Date range. Defaults to last hour. */dateRange?: _DateRange;/** Filter by log severity levels (ignored when faceting on severity_text). */