: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(tracing): load roots that start just before the range (#112802)
Frank Hamand28acdef35979
diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex 9644a2a5aba5..1e5388814b8b 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -59,6 +59,10 @@ TIME_BUCKET_DATE_RANGE_WHERE = ("and toStartOfDay(time_bucket, 'UTC') <= toStartOfDay({date_to}, 'UTC')")+# A trace can start shortly before the selected range. The list loads a root span from up to this long+# before the range, so the trace does not show as having no root.+ROOT_SPAN_LOOKBACK = dt.timedelta(minutes=15)+# Hard cap on number of rows returned per period by the span aggregation runners. Keeps# payloads bounded when name cardinality blows up (e.g. untemplated URL paths). The flame# graph collapses long tails anyway so the lower-ranked rows aren't visible.@@ -678,6 +682,39 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Traif root_only:key_predicate = ast.And(exprs=[self.where(), parse_expr("is_root_span = 1")])+ filters_expr: ast.Expr = ast.Constant(value=True)+ if not self._unbounded_trace_lookup:+ # The day bound on time_bucket adds no rows, but it lets the primary key prune parts.+ # With only the timestamp bounds, ClickHouse checks every part the team has.+ filters_expr = ast.And(+ exprs=[+ ast.Placeholder(expr=ast.Field(chain=["filters"])),+ parse_expr(TIME_BUCKET_DATE_RANGE_WHERE, placeholders=self.query_date_range.to_placeholders()),+ ]+ )+ # Under root_only the subquery already picks traces by an in-range root.+ if not self._unbounded_trace_lookup and not root_only and self.query.traceId is None:+ date_from = self.query_date_range.date_from()+ lookback_bounds: dict[str, ast.Expr] = {+ "date_from": ast.Constant(value=date_from - ROOT_SPAN_LOOKBACK),+ "date_to": ast.Constant(value=date_from),+ }+ # The lookback can start on the day before date_from, so it needs its own time_bucket bound.+ filters_expr = ast.Or(+ exprs=[+ filters_expr,+ ast.And(+ exprs=[+ parse_expr(+ "is_root_span AND timestamp >= {date_from} AND timestamp < {date_to}",+ placeholders=lookback_bounds,+ ),+ parse_expr(TIME_BUCKET_DATE_RANGE_WHERE, placeholders=lookback_bounds),+ ]+ ),+ ]+ )+query = parse_select("""SELECT@@ -706,16 +743,7 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra"where_for_start": key_predicate,"trace_filter": trace_filter,"limit": ast.Constant(value=(self.query.limit or 1) * limit_by_n),- # The day bound on time_bucket adds no rows, but it lets the primary key prune parts.- # With only the timestamp bounds, ClickHouse checks every part the team has.- "filters": ast.Constant(value=True)- if self._unbounded_trace_lookup- else ast.And(- exprs=[- ast.Placeholder(expr=ast.Field(chain=["filters"])),- parse_expr(TIME_BUCKET_DATE_RANGE_WHERE, placeholders=self.query_date_range.to_placeholders()),- ]- ),+ "filters": filters_expr,# The attribute maps dominate payload size (db.statement holds multi-KB SQL;# process.command_args etc. bulk up the resource map). When excluded we still# SELECT a column so the positional result mapping stays stable — an empty mapdiff --git a/products/tracing/backend/tests/test_root_spans_filter.py b/products/tracing/backend/tests/test_root_spans_filter.pyindex 10808f4d6ae1..b7e94288b173 100644--- a/products/tracing/backend/tests/test_root_spans_filter.py+++ b/products/tracing/backend/tests/test_root_spans_filter.py@@ -22,6 +22,8 @@ CHILD_NAME = "redis_cluster.discovery"OTHER_ROOT_NAME = "POST /webhook"EARLY_CHILD_NAME = "queue.wait"LATE_CHILD_NAME = "email.send"+# Trace C: its root starts 5 minutes before DATE_FROM, and a child on "web" is inside the range.+EARLY_ROOT_NAME = "GET /early"def _b64(raw: bytes) -> str:@@ -48,6 +50,8 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):trace_b = _b64((2).to_bytes(16, "big"))root_a = _b64((1).to_bytes(8, "big"))root_b = _b64((4).to_bytes(8, "big"))+ trace_c = _b64((3).to_bytes(16, "big"))+ root_c = _b64((8).to_bytes(8, "big"))base = dt.datetime(2026, 6, 2, 8, 0, 0)def _row(@@ -72,6 +76,8 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):_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),+ _row(8, trace_c, root_c, "", EARLY_ROOT_NAME, "web", -65 * 60 * 1000),+ _row(9, trace_c, _b64((9).to_bytes(8, "big")), root_c, CHILD_NAME, "web", -59 * 60 * 1000),]sync_execute("INSERT INTO trace_spans (uuid, team_id, trace_id, span_id, parent_span_id, name, kind, "@@ -101,14 +107,15 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):[# rootSpans=True selects traces by ROOT match: only trace A (its root is on "web").# Trace B is dropped because its root is on "worker", even though a child is on "web".- ("true_prefetches_children_excludes_nonroot_traces", True, False),+ ("true_prefetches_children_excludes_nonroot_traces", True, False, False),# rootSpans=False matches a trace on ANY span, so trace B comes through via its "web" child.- ("false_includes_child_matched_traces", False, True),+ # It also loads trace C's root from before the range, so the trace does not lose its root.+ ("false_includes_child_matched_traces", False, True, True),# The frontend sends None; it behaves like False (relies on prefetch for the waterfall).- ("none_includes_child_matched_traces", None, True),+ ("none_includes_child_matched_traces", None, True, True),])- def test_root_spans_filter(self, _name, root_spans, expect_other_trace):+ def test_root_spans_filter(self, _name, root_spans, expect_other_trace, expect_early_root):results = self._run(root_spans=root_spans, prefetch=20, service_names=["web"])names = {r["name"] for r in results}# Trace A's root always matches the filter, and its children are always prefetched for the@@ -119,6 +126,10 @@ class TestRootSpansFilter(ClickhouseTestMixin, APIBaseTest):self.assertIn(OTHER_ROOT_NAME, names)else:self.assertNotIn(OTHER_ROOT_NAME, names)+ if expect_early_root:+ self.assertIn(EARLY_ROOT_NAME, names)+ else:+ self.assertNotIn(EARLY_ROOT_NAME, names)@parameterized.expand([