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(autoresearch): speed up logs group-by queries on non-indexed attributes (#71602)

Jon McCallum1eaa38a5360a
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index 738cd1f91037..4cefec5fe637 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -200,6 +200,13 @@ class HogQLGlobalSettings(HogQLQuerySettings):
allow_experimental_join_condition: Optional[bool] = True
preferred_block_size_bytes: Optional[int] = None
use_hive_partitioning: Optional[int] = 0
+ # Serve repeated scans of the same parts from the server's uncompressed block cache
+ # instead of re-decompressing. Off by default (None): only opt in for interactive
+ # queries that re-read the same narrow data repeatedly, and mind that scans larger
+ # than the two merge_tree_*_to_use_cache guards below bypass the cache entirely.
+ use_uncompressed_cache: Optional[bool] = None
+ merge_tree_max_rows_to_use_cache: Optional[int] = None
+ merge_tree_max_bytes_to_use_cache: Optional[int] = None
def get_default_hogql_global_settings(
diff --git a/posthog/hogql/database/schema/logs.py b/posthog/hogql/database/schema/logs.py
index f7c380ac40f1..8a5faf7d0958 100644
--- a/posthog/hogql/database/schema/logs.py
+++ b/posthog/hogql/database/schema/logs.py
@@ -81,6 +81,10 @@ class LogsTable(Table):
name="service_name", nullable=False, description="Name of the service that emitted the log."
),
# internal fields for query optimization
+ # Physical type-suffixed backing map of `attributes`. A bare arrayElement() on it reads only
+ # the serialization bucket holding the key; membership guards (has/mapContains) force reading
+ # every key bucket, so internal hot paths grouping on one attribute use this directly.
+ "attributes_map_str": MapStringDatabaseField(name="attributes_map_str", nullable=False, hidden=True),
"_part_starting_offset": IntegerDatabaseField(name="_part_starting_offset", nullable=True, hidden=True),
"_part_offset": IntegerDatabaseField(name="_part_offset", nullable=True, hidden=True),
"_bytes_uncompressed": IntegerDatabaseField(name="_bytes_uncompressed", nullable=True, hidden=True),
diff --git a/products/logs/backend/group_by_query_runner.py b/products/logs/backend/group_by_query_runner.py
index b5ec4f6c911e..6c5e2475b8fa 100644
--- a/products/logs/backend/group_by_query_runner.py
+++ b/products/logs/backend/group_by_query_runner.py
@@ -5,6 +5,8 @@ from posthog.schema import CachedLogsQueryResponse, LogsQuery
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -38,16 +40,26 @@ GROUPABLE_COLUMNS: dict[str, str] = {
GROUP_SOURCES = ("log", "resource", "column")
ORDER_FIELDS = ("log_count", "error_count", "last_seen")
+# 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.
+_TOTALS_WINDOW = "count() OVER () AS group_count, sum(log_count) OVER () AS log_count_sum"
+
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.
+ 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.
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
@@ -96,42 +108,64 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
max_bytes_to_read=MAX_READ_BYTES,
read_overflow_mode="throw",
timeout_overflow_mode="throw",
+ # Group-by is interactive: users re-query the same window while switching the
+ # grouping key or ordering, re-decompressing the same attribute-map blocks each
+ # time — over half the query cost. Let those scans use the server's uncompressed
+ # block cache (a no-op where the cache is unsized). Guards sized to the runner's
+ # own read cap so an over-budget scan can't pump more than MAX_READ_BYTES into it.
+ use_uncompressed_cache=True,
+ merge_tree_max_rows_to_use_cache=50_000_000,
+ merge_tree_max_bytes_to_use_cache=MAX_READ_BYTES,
)
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"])
+ # 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
+ # 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")],
+ )
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:
+ 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"""
SELECT
- groupArray({limit})((group_value, log_count, error_count, last_seen)) AS groups,
- count() AS total_groups,
- sum(log_count) AS total_logs
+ 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 (
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
+ 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={
- "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(),
@@ -141,27 +175,113 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
assert isinstance(query, ast.SelectQuery)
return query
- def _where(self) -> ast.Expr:
+ 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
+ query = parse_select(
+ 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 (
+ SELECT
+ group_value, 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
+ 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]),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _base_where(self) -> list[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.
+ return [
+ self.where(),
+ parse_expr(
+ "timestamp >= {date_from} AND timestamp < {date_to}",
+ placeholders={
+ "date_from": ast.Constant(value=self.query_date_range.date_from()),
+ "date_to": ast.Constant(value=self.query_date_range.date_to()),
+ },
+ ),
+ ]
+
+ def _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.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()),
- },
- ),
+ *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
+ # Database up front. Without it, the `{filters}` placeholder LogsFilterBuilder.where()
+ # always emits makes the executor run the full per-query database build — warehouse
+ # tables, saved queries, endpoints: several Postgres round trips this query never uses.
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ enable_select_queries=True,
+ database=Database(timezone=self.team.timezone, week_start_day=self.team.week_start_day),
+ )
response = execute_hogql_query(
query_type="LogsQuery",
query=self.to_query(),
@@ -171,6 +291,7 @@ class LogsGroupByQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryR
timings=self.timings,
limit_context=self.limit_context,
settings=self.settings,
+ context=context,
)
groups_raw, total_groups, total_logs = response.results[0] if response.results else ([], 0, 0)