: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
fix(logs): serve resource-attribute facet values from log_attributes (#65768)
Jon McCallum4042a4cd4b1a
diff --git a/products/logs/backend/log_facet_values_query_runner.py b/products/logs/backend/log_facet_values_query_runner.pyindex 3fe71c62c6d8..f3ac2c880aaa 100644--- a/products/logs/backend/log_facet_values_query_runner.py+++ b/products/logs/backend/log_facet_values_query_runner.py@@ -1,7 +1,9 @@+import datetime as dtfrom functools import cached_propertyfrom typing import cast+from zoneinfo import ZoneInfo-from posthog.schema import CachedLogsQueryResponse, LogsQuery+from posthog.schema import CachedLogsQueryResponse, IntervalType, LogsQueryfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -10,6 +12,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom products.logs.backend.logs_query_runner import (LogsFilterBuilder,@@ -24,14 +27,20 @@ FACET_FIELDS: frozenset[str] = frozenset({"severity_text", "service_name"})DEFAULT_FACET_LIMIT = 100+# Resource-attribute facets read the pre-aggregated log_attributes rollup; cap the read and return+# partial results rather than erroring, matching LogValuesQueryRunner.+MAX_RESOURCE_READ_BYTES = 5_000_000_000+class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):- """Per-value counts for a single facet, cross-filtered.+ """Per-value counts for a single facet.- 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.+ A column facet (severity_text/service_name) groups the logs table directly. A resource-attribute+ facet (e.g. k8s.namespace.name) reads the pre-aggregated log_attributes rollup instead of the+ logs Map column — orders of magnitude cheaper, and the only way to keep the query under the read+ cap at scale. Both exclude the facet's own filter so selecting a value re-scopes the *other*+ facets. Resource-attribute facet counts honour service_name and other resource-attribute filters+ but not severity / body-search / log-attribute filters (those dimensions aren't in the rollup)."""query: LogsQuery@@ -59,21 +68,34 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQue# 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.+ if self.facet_resource_attribute is not None:+ # The rollup is small; "break" returns partial results instead of erroring if we ever+ # hit the cap (mirrors LogValuesQueryRunner).+ return HogQLGlobalSettings(+ read_overflow_mode="break",+ max_bytes_to_read=MAX_RESOURCE_READ_BYTES,+ )+ # Column facets still group the logs table — fail fast rather than scan unbounded data.return HogQLGlobalSettings(max_execution_time=30,max_bytes_to_read=10_000_000_000,read_overflow_mode="throw",)+ @cached_property+ def _attributes_query_date_range(self) -> QueryDateRange:+ # log_attributes is bucketed at 10-minute granularity; align bounds to it.+ return QueryDateRange(+ date_range=self.query.dateRange,+ team=self.team,+ interval=IntervalType.MINUTE,+ interval_count=10,+ now=dt.datetime.now(),+ timezone_info=ZoneInfo("UTC"),+ )+def _calculate(self) -> LogsQueryResponse:response = execute_hogql_query(query_type="LogsQuery",@@ -89,14 +111,19 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQuereturn LogsQueryResponse(results=results)def to_query(self) -> ast.SelectQuery:+ if self.facet_resource_attribute is not None:+ return self._resource_attribute_query()+ return self._column_facet_query()++ def _column_facet_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).+ facet = ast.Field(chain=[cast(str, self.facet_field)])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 = [filter_builder.where(),@@ -108,22 +135,17 @@ 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} ILIKE {pattern}",placeholders={- "facet": self._facet_expr(),+ "facet": facet,# Escape %, _ and \ so user input matches literally instead of as wildcards."pattern": ast.Constant(value=ilike_pattern(self.facet_search)),},))- where = ast.And(exprs=exprs)query = parse_select("""SELECT {facet} AS value, count() AS count@@ -134,9 +156,63 @@ class LogFacetValuesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueLIMIT {limit}""",placeholders={- "facet": self._facet_expr(),- "where": where,+ "facet": facet,+ "where": ast.And(exprs=exprs),+ "limit": ast.Constant(value=self.query.limit or DEFAULT_FACET_LIMIT),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ return query++ def _resource_attribute_query(self) -> ast.SelectQuery:+ # Served from the pre-aggregated log_attributes rollup (sum(attribute_count)) rather than+ # grouping the logs Map column, which reads the whole resource_attributes column and blows+ # past the read cap at scale. The rollup has no severity/body/log-attribute dimension, so only+ # service_name and other resource-attribute filters re-scope the counts.+ date_range = self._attributes_query_date_range+ where_exprs: list[ast.Expr] = []+ if self.query.serviceNames:+ where_exprs.append(+ parse_expr(+ "service_name IN {serviceNames}",+ placeholders={+ "serviceNames": ast.Tuple(exprs=[ast.Constant(value=str(sn)) for sn in self.query.serviceNames])+ },+ )+ )+ # Cross-filter by other resource attributes, excluding this facet's own key so selecting a+ # value doesn't collapse the facet to that single value.+ filter_builder = LogsFilterBuilder(+ self.query,+ self.team,+ date_range,+ exclude_resource_attribute=self.facet_resource_attribute,+ )+ where_exprs.append(filter_builder.resource_filter(existing_filters=where_exprs))++ query = parse_select(+ """+ SELECT attribute_value AS value, sum(attribute_count) AS count+ FROM log_attributes+ WHERE time_bucket >= {date_from_start_of_interval}+ AND time_bucket <= {date_to_start_of_interval} + {one_interval_period}+ AND attribute_type = {attribute_type}+ AND attribute_key = {attribute_key}+ AND attribute_value != ''+ AND attribute_value ILIKE {search}+ AND {where}+ GROUP BY attribute_value+ ORDER BY sum(attribute_count) DESC, attribute_value ASC+ LIMIT {limit}+ """,+ placeholders={+ "attribute_type": ast.Constant(value="resource"),+ "attribute_key": ast.Constant(value=cast(str, self.facet_resource_attribute)),+ # ilike_pattern(None) -> '%', i.e. match every value when no facet search is given.+ "search": ast.Constant(value=ilike_pattern(self.facet_search)),+ "where": ast.And(exprs=where_exprs),"limit": ast.Constant(value=self.query.limit or DEFAULT_FACET_LIMIT),+ **date_range.to_placeholders(),},)assert isinstance(query, ast.SelectQuery)diff --git a/products/logs/backend/test/test_log_facet_values.py b/products/logs/backend/test/test_log_facet_values.pyindex 8672df96f019..058a214a16d7 100644--- a/products/logs/backend/test/test_log_facet_values.py+++ b/products/logs/backend/test/test_log_facet_values.py@@ -128,10 +128,25 @@ class TestLogFacetValues(ClickhouseTestMixin, APIBaseTest):]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)."""+ def test_resource_facet_ignores_severity_filter(self):+ # Resource-attribute facets are served from the log_attributes rollup, which has no severity+ # dimension — a severity filter is accepted but does not re-scope the counts.base = self._facet_attr("k8s.namespace.name")+ self.assertGreater(len(base), 0)scoped = self._facet_attr("k8s.namespace.name", severityLevels=["error"])+ self.assertEqual(scoped, base)++ def test_resource_facet_honors_other_resource_attribute_filter(self):+ # A different resource-attribute filter re-scopes the counts via the rollup's+ # resource_fingerprint subquery — proves cross-filtering still works on log_attributes.+ base = self._facet_attr("k8s.pod.name")+ one_namespace = next(iter(self._facet_attr("k8s.namespace.name")))+ filter_group = [+ {"key": "k8s.namespace.name", "type": "log_resource_attribute", "operator": "exact", "value": one_namespace}+ ]+ scoped = self._facet_attr("k8s.pod.name", filterGroup=filter_group)+ self.assertGreater(len(scoped), 0)+ self.assertTrue(set(scoped).issubset(set(base)))self.assertLess(sum(scoped.values()), sum(base.values()))@parameterized.expand([("argo",), ("ARGO",)])