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 the trace list query (#112738)

Frank Hamand46b18686e27b
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index b1fb5e78724e..f2e2b99d57be 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -182,6 +182,7 @@ class HogQLQuerySettings(BaseModel):
grace_hash_join_initial_buckets: Optional[int] = None
force_data_skipping_indices: Optional[list[str]] = None
force_optimize_projection: Optional[bool] = None
+ query_plan_max_limit_for_top_k_optimization: Optional[int] = None
load_balancing: Optional[str] = None
format_csv_allow_double_quotes: Optional[bool] = None
optimize_skip_unused_shards: Optional[bool] = None
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.py
index d0fa9be5231d..20742e324437 100644
--- a/products/tracing/backend/logic.py
+++ b/products/tracing/backend/logic.py
@@ -34,10 +34,11 @@ from posthog.schema import (
)
from posthog.hogql import ast
-from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.constants import HogQLGlobalSettings, HogQLQuerySettings, LimitContext
from posthog.hogql.parser import parse_expr, parse_order_expr, parse_select
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.visitor import clone_expr
from posthog.clickhouse.client.connection import Workload
from posthog.hogql_queries.paginators import HogQLHasMorePaginator
@@ -70,6 +71,8 @@ _ROW_LIMIT = 5000
# callers that need the long tail opt into a higher `limit` (up to _ROW_LIMIT) or paginate.
DEFAULT_AGGREGATION_ROW_LIMIT = 100
+RECENT_TRACES_SPANS_PER_TRACE = 100
+
# Value-search probes attribute_value with ILIKE %search%, which scans far more rows than
# the key-only path. Require a meaningfully specific term so short prefixes (e.g. "id")
# don't trigger an expensive scan.
@@ -589,6 +592,7 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
# the filter. The outer fetch is deliberately left unfiltered — it still prefetches every
# span of the selected traces so the waterfall gets its children.
root_only = self.query.rootSpans is True
+ recent_traces = not by_duration and order_dir == "DESC" and self.query.traceId is None
subquery_where_exprs: list[ast.Expr] = [self.where()]
if root_only:
@@ -611,42 +615,57 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
placeholders={"cursor_ts": ast.Constant(value=cursor_ts)},
)
)
- having_expr = parse_expr(
- f"(min(timestamp), trace_id) {op} ({{cursor_ts}}, {{cursor_trace_id}})",
- placeholders={
- "cursor_ts": ast.Constant(value=cursor_ts),
- "cursor_trace_id": ast.Constant(value=cursor_trace_id),
- },
- )
+ keyset_placeholders: dict[str, ast.Expr] = {
+ "cursor_ts": ast.Constant(value=cursor_ts),
+ "cursor_trace_id": ast.Constant(value=cursor_trace_id),
+ }
+ if recent_traces:
+ subquery_where_exprs.append(
+ parse_expr(
+ f"(timestamp, trace_id) {op} ({{cursor_ts}}, {{cursor_trace_id}})",
+ placeholders=keyset_placeholders,
+ )
+ )
+ else:
+ having_expr = parse_expr(
+ f"(min(timestamp), trace_id) {op} ({{cursor_ts}}, {{cursor_trace_id}})",
+ placeholders=keyset_placeholders,
+ )
subquery_where = (
subquery_where_exprs[0] if len(subquery_where_exprs) == 1 else ast.And(exprs=subquery_where_exprs)
)
- trace_id_query = parse_select(
- """
- SELECT
- trace_id
- FROM posthog.trace_spans
- WHERE {where}
- GROUP BY trace_id
- LIMIT {limit}
- """,
- placeholders={
- "where": subquery_where,
- "limit": ast.Constant(value=self.query.limit),
- },
- )
-
- assert isinstance(trace_id_query, ast.SelectQuery)
- trace_id_query.order_by = [
- parse_order_expr(f"{sort_key_sql} {order_dir}"),
- parse_order_expr(f"trace_id {order_dir}"),
- ]
- if having_expr is not None:
- trace_id_query.having = having_expr
- if by_duration and self.query.offset:
- trace_id_query.offset = ast.Constant(value=self.query.offset)
+ trace_filter: ast.Expr
+ if self._unbounded_trace_lookup:
+ trace_filter = self._unbounded_trace_filter()
+ elif recent_traces:
+ trace_filter = self._recent_traces_filter(subquery_where)
+ else:
+ trace_id_query = parse_select(
+ """
+ SELECT
+ trace_id
+ FROM posthog.trace_spans
+ WHERE {where}
+ GROUP BY trace_id
+ LIMIT {limit}
+ """,
+ placeholders={
+ "where": subquery_where,
+ "limit": ast.Constant(value=self.query.limit),
+ },
+ )
+ assert isinstance(trace_id_query, ast.SelectQuery)
+ trace_id_query.order_by = [
+ parse_order_expr(f"{sort_key_sql} {order_dir}"),
+ parse_order_expr(f"trace_id {order_dir}"),
+ ]
+ if having_expr is not None:
+ trace_id_query.having = having_expr
+ if by_duration and self.query.offset:
+ trace_id_query.offset = ast.Constant(value=self.query.offset)
+ trace_filter = parse_expr("trace_id IN ({trace_id_query})", placeholders={"trace_id_query": trace_id_query})
# `trace_start` / `trace_duration` are the per-trace keys the view paginates and re-sorts on.
# They MUST aggregate over the same rows the trace-selection subquery grouped, or the keys
@@ -685,9 +704,7 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
placeholders={
"where": self.where(),
"where_for_start": key_predicate,
- "trace_filter": self._unbounded_trace_filter()
- if self._unbounded_trace_lookup
- else parse_expr("trace_id IN ({trace_id_query})", placeholders={"trace_id_query": trace_id_query}),
+ "trace_filter": trace_filter,
"limit": ast.Constant(value=(self.query.limit or 1) * limit_by_n),
"filters": ast.Constant(value=True)
if self._unbounded_trace_lookup
@@ -704,6 +721,9 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
)
assert isinstance(query, ast.SelectQuery)
+ if recent_traces:
+ query.settings = HogQLQuerySettings(query_plan_max_limit_for_top_k_optimization=self._recent_spans_limit)
+
# Root rows drive the displayed list order. Time sorts order them by timestamp; duration sorts
# by the per-trace duration window (constant within a trace, so spans of a trace stay grouped).
base_order = [parse_order_expr("is_root_span DESC"), parse_order_expr("matched_filter DESC")]
@@ -737,6 +757,114 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra
return query
+ @property
+ def _recent_spans_limit(self) -> int:
+ return (self.query.limit or 1) * RECENT_TRACES_SPANS_PER_TRACE
+
+ def _recent_spans(self, where: ast.Expr) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT (groupArray(trace_id), groupArray(timestamp), groupArray(is_root_span), min(timestamp), count())
+ FROM (
+ SELECT trace_id, timestamp, is_root_span
+ FROM posthog.trace_spans
+ WHERE {where}
+ ORDER BY timestamp DESC, trace_id DESC
+ LIMIT {limit}
+ )
+ """,
+ placeholders={"where": clone_expr(where), "limit": ast.Constant(value=self._recent_spans_limit)},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _recent_spans_rows(self, where: ast.Expr) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT tupleElement(span, 1) AS trace_id, tupleElement(span, 2) AS ts, tupleElement(span, 3) AS root
+ FROM (
+ SELECT arrayJoin(arrayZip(tupleElement(({spans}), 1), tupleElement(({spans}), 2), tupleElement(({spans}), 3))) AS span
+ )
+ """,
+ placeholders={"spans": self._recent_spans(where)},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _recent_traces_started_earlier(self, where: ast.Expr) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT groupUniqArray(trace_id)
+ FROM posthog.trace_spans
+ WHERE {where}
+ AND timestamp < tupleElement(({spans}), 4)
+ AND trace_id IN (SELECT trace_id FROM ({rows}) GROUP BY trace_id HAVING max(root) = 0)
+ """,
+ placeholders={
+ "where": clone_expr(where),
+ "spans": self._recent_spans(where),
+ "rows": self._recent_spans_rows(where),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _recent_traces_selected(self, where: ast.Expr) -> ast.SelectQuery:
+ query = parse_select(
+ """
+ SELECT (groupArray(trace_id), count())
+ FROM (
+ SELECT trace_id, min(ts) AS trace_key
+ FROM ({rows})
+ GROUP BY trace_id
+ HAVING max(root) = 1 OR NOT has(({started_earlier}), trace_id)
+ ORDER BY trace_key DESC, trace_id DESC
+ LIMIT {limit}
+ )
+ """,
+ placeholders={
+ "rows": self._recent_spans_rows(where),
+ "started_earlier": self._recent_traces_started_earlier(where),
+ "limit": ast.Constant(value=self.query.limit),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def _recent_traces_enough(self, where: ast.Expr) -> ast.Expr:
+ return parse_expr(
+ "tupleElement(({selected}), 2) >= {limit} OR tupleElement(({spans}), 5) < {spans_limit}",
+ placeholders={
+ "selected": self._recent_traces_selected(where),
+ "spans": self._recent_spans(where),
+ "limit": ast.Constant(value=self.query.limit),
+ "spans_limit": ast.Constant(value=self._recent_spans_limit),
+ },
+ )
+
+ def _recent_traces_filter(self, where: ast.Expr) -> ast.Expr:
+ return parse_expr(
+ """
+ trace_id IN (
+ SELECT trace_id FROM (SELECT arrayJoin(tupleElement(({selected}), 1)) AS trace_id) WHERE {enough}
+ UNION ALL
+ SELECT trace_id
+ FROM posthog.trace_spans
+ WHERE {where} AND NOT {fallback_enough}
+ GROUP BY trace_id
+ ORDER BY min(timestamp) DESC, trace_id DESC
+ LIMIT {limit}
+ )
+ """,
+ placeholders={
+ "selected": self._recent_traces_selected(where),
+ "enough": self._recent_traces_enough(where),
+ "fallback_enough": self._recent_traces_enough(where),
+ "where": clone_expr(where),
+ "limit": ast.Constant(value=self.query.limit),
+ },
+ )
+
def _unbounded_trace_filter(self) -> ast.Expr:
"""Find one trace's rows without a date bound, through `projection_index_team_trace_id`.
diff --git a/products/tracing/backend/tests/test_keyset_pagination.py b/products/tracing/backend/tests/test_keyset_pagination.py
index d7e40120f854..d1c033ce28e4 100644
--- a/products/tracing/backend/tests/test_keyset_pagination.py
+++ b/products/tracing/backend/tests/test_keyset_pagination.py
@@ -3,6 +3,7 @@ import base64
import datetime as dt
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from parameterized import parameterized
@@ -16,6 +17,7 @@ from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import tag_queries
from posthog.clickhouse.traces.spans import TRACE_SPANS_DISTRIBUTED_TABLE_SQL, TRACE_SPANS_TABLE_SQL
+from products.tracing.backend import logic
from products.tracing.backend.logic import TraceSpansQueryRunner
DATE_FROM = "2026-06-02T07:00:00Z"
@@ -299,3 +301,68 @@ class TestTraceSpansDurationRootScope(_TraceSpansTestBase):
)
def test_ranks_by_root_span_duration(self, _name, order_direction, expected):
self.assertEqual(self._ordered_trace_indices(order_direction=order_direction, limit=10), expected)
+
+
+# Trace 1 started first but owns the newest span; trace 4 never got a root; trace 5 has 15 spans.
+RECENT_TRACE_SPANS: list[tuple[int, int, bool]] = [
+ (1, 0, True),
+ (1, 100, False),
+ (2, 50, True),
+ (3, 60, True),
+ (4, 70, False),
+ (4, 71, False),
+ (5, 80, True),
+ *[(5, 80 + n, False) for n in range(1, 15)],
+]
+
+
+class TestTraceSpansRecentTraceSelection(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ base = dt.datetime(2026, 6, 2, 8, 0, 0)
+ rows = []
+ for n, (trace, offset_s, is_root) in enumerate(RECENT_TRACE_SPANS):
+ ts = (base + dt.timedelta(seconds=offset_s)).strftime("%Y-%m-%d %H:%M:%S.%f")
+ parent = "" if is_root else _b64((9999).to_bytes(8, "big"))
+ rows.append(
+ "("
+ f"'019e8755-0000-0000-0000-{n:012d}', {cls.team.id}, '{_b64(trace.to_bytes(16, 'big'))}', "
+ f"'{_b64((1000 + n).to_bytes(8, 'big'))}', '{parent}', 'op', 2, '{ts}', '{ts}', '{ts}', 0, 'web'"
+ ")"
+ )
+ sync_execute(
+ "INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
+ "timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows)
+ )
+
+ @parameterized.expand(
+ [
+ ("all_spans_fit_in_the_recent_window", "DESC", 3, None, {5, 4, 3}),
+ ("trace_started_earlier_is_not_ranked_by_its_newest_span", "DESC", 2, None, {5, 4}),
+ ("too_few_complete_traces_falls_back_to_grouping", "DESC", 1, None, {5}),
+ ("newest_first_continuation", "DESC", 10, (70, 4), {3, 2, 1}),
+ ("oldest_first_continuation", "ASC", 10, (70, 4), {5}),
+ ]
+ )
+ def test_traces_rank_by_their_earliest_span(self, _name, order_direction, limit, cursor, expected):
+ after = None
+ if cursor is not None:
+ offset_s, trace = cursor
+ cursor_ts = (dt.datetime(2026, 6, 2, 8, 0, 0, tzinfo=dt.UTC) + dt.timedelta(seconds=offset_s)).isoformat()
+ after = base64.b64encode(
+ json.dumps({"timestamp": cursor_ts, "trace_id": format(trace, "032x")}).encode("utf-8")
+ ).decode("utf-8")
+ query = TraceSpansQuery(
+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ orderBy="timestamp",
+ orderDirection=order_direction,
+ limit=limit,
+ after=after,
+ rootSpans=False,
+ prefetchSpans=20,
+ )
+ with patch.object(logic, "RECENT_TRACES_SPANS_PER_TRACE", 10):
+ self.assertEqual({int(row[1], 16) for row in self._execute(query)}, expected)
diff --git a/products/tracing/backend/tests/test_root_spans_filter.py b/products/tracing/backend/tests/test_root_spans_filter.py
index 0a2358749bd1..10808f4d6ae1 100644
--- a/products/tracing/backend/tests/test_root_spans_filter.py
+++ b/products/tracing/backend/tests/test_root_spans_filter.py
@@ -20,6 +20,8 @@ ROOT_NAME = "GET /api"
CHILD_NAME = "redis_cluster.discovery"
# Trace B: its root runs on service "worker" (won't match a "web" filter), but a child runs on "web".
OTHER_ROOT_NAME = "POST /webhook"
+EARLY_CHILD_NAME = "queue.wait"
+LATE_CHILD_NAME = "email.send"
def _b64(raw: bytes) -> str:
@@ -65,9 +67,11 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):
_row(1, trace_a, root_a, "", ROOT_NAME, "web", 0),
_row(2, trace_a, _b64((2).to_bytes(8, "big")), root_a, CHILD_NAME, "web", 10),
_row(3, trace_a, _b64((3).to_bytes(8, "big")), root_a, "clickhouse.query", "web", 20),
+ _row(6, trace_a, _b64((6).to_bytes(8, "big")), root_a, EARLY_CHILD_NAME, "web", -5 * 60 * 1000),
# Trace B: root on "worker" (won't match a "web" filter), child on "web" (will).
_row(4, trace_b, root_b, "", OTHER_ROOT_NAME, "worker", 0),
_row(5, trace_b, _b64((5).to_bytes(8, "big")), root_b, CHILD_NAME, "web", 10),
+ _row(7, trace_b, _b64((7).to_bytes(8, "big")), root_b, LATE_CHILD_NAME, "delayed", 5 * 60 * 1000),
]
sync_execute(
"INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "
@@ -115,3 +119,36 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):
self.assertIn(OTHER_ROOT_NAME, names)
else:
self.assertNotIn(OTHER_ROOT_NAME, names)
+
+ @parameterized.expand(
+ [
+ (
+ "single_trace_lookup",
+ {"traceId": (1).to_bytes(16, "big").hex(), "limit": 1, "rootSpans": True},
+ 1,
+ {ROOT_NAME, CHILD_NAME, "clickhouse.query", EARLY_CHILD_NAME},
+ ),
+ (
+ "root_span_list_keeps_children_before_the_root",
+ {"limit": 100, "rootSpans": True, "serviceNames": ["web"]},
+ 1,
+ {ROOT_NAME, CHILD_NAME, "clickhouse.query", EARLY_CHILD_NAME},
+ ),
+ (
+ "list_matched_on_a_late_child_keeps_the_earlier_spans",
+ {"limit": 100, "rootSpans": False, "serviceNames": ["delayed"]},
+ 2,
+ {OTHER_ROOT_NAME, CHILD_NAME, LATE_CHILD_NAME},
+ ),
+ ]
+ )
+ def test_prefetch_holds_every_span_of_the_trace(self, _name, query_fields, trace, expected):
+ query = TraceSpansQuery(
+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ orderBy="timestamp",
+ prefetchSpans=20,
+ **query_fields,
+ )
+ trace_hex = (trace).to_bytes(16, "big").hex().upper()
+ results = TraceSpansQueryRunner(query, self.team).run().results
+ self.assertEqual({r["name"] for r in results if r["trace_id"] == trace_hex}, expected)