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.

fix(aio): include long-running trace spans in trace view (#72421)

Alex LaGuardiacdb45313321a
diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.py
index 7ecf4095d6ab..d235c91a7d93 100644
--- a/posthog/hogql_queries/ai/ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/ai_table_resolver.py
@@ -76,6 +76,7 @@ def query_ai_events(
query_type: str,
*,
fall_back_to_events: bool = False,
+ fallback_placeholders: dict[str, ast.Expr] | None = None,
timings: HogQLTimings | None = None,
modifiers: HogQLQueryModifiers | None = None,
limit_context: LimitContext | None = None,
@@ -98,6 +99,9 @@ def query_ai_events(
so events is probed only to classify the miss — raising :class:`AIEventsExpiredError`
(the data aged past the TTL) or :class:`AIEventsNotFoundError` (it never existed).
+ ``fallback_placeholders`` lets callers keep predicates required by shared events out of
+ the dedicated table query. They use the ai_events schema and are rewritten before execution.
+
`workload` should be specified explicitly for batch / scheduled callers (e.g. usage
reports). Inside a Celery task the `task_prerun` signal sets `Workload.OFFLINE` on
the thread default, but outside Celery (Django shell, pytest, management commands)
@@ -127,7 +131,10 @@ def query_ai_events(
events_schema = use_new_events_schema(team.pk)
events_query = rewrite_query_for_events_table(query)
- events_placeholders = {k: rewrite_expr_for_events_table(v) for k, v in placeholders.items()}
+ fallback_source_placeholders = fallback_placeholders if fallback_placeholders is not None else placeholders
+ events_placeholders = {
+ key: rewrite_expr_for_events_table(value) for key, value in fallback_source_placeholders.items()
+ }
events_kwargs = {
**kwargs,
"context": HogQLContext(
diff --git a/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr b/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
index f1c3525477fb..30e6e474982b 100644
--- a/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
+++ b/posthog/hogql_queries/ai/test/__snapshots__/test_trace_query_runner.ambr
@@ -41,7 +41,7 @@
ai_events.output_state AS output_state,
ai_events.tools AS tools
FROM ai_events
- WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'bar'), 0)))
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'bar'), 0)))
LIMIT 1 BY ai_events.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -100,7 +100,7 @@
ai_events.output_state AS output_state,
ai_events.tools AS tools
FROM ai_events
- WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'baz'), 0)))
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'baz'), 0)))
LIMIT 1 BY ai_events.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -159,7 +159,7 @@
ai_events.output_state AS output_state,
ai_events.tools AS tools
FROM ai_events
- WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'barz'), 0)))
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(equals(ai_events.trace_id, 'trace1'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(ai_events.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'barz'), 0)))
LIMIT 1 BY ai_events.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -218,7 +218,7 @@
JSONExtractRaw(__ai_events_fallback.properties, '$ai_output_state') AS output_state,
JSONExtractRaw(__ai_events_fallback.properties, '$ai_tools') AS tools
FROM events AS __ai_events_fallback
- WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'barz'), 0)))
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-12-08 00:10:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, 'foo'), ''), 'null'), '^"|"$', ''), 'barz'), 0)))
LIMIT 1 BY __ai_events_fallback.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -356,7 +356,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi__person ON equals(ai_events__pdi.ai_events__pdi___person_id, ai_events__pdi__person.id)
- WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'baz'), 0)))
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'baz'), 0)))
LIMIT 1 BY ai_events.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -433,7 +433,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS ai_events__pdi__person ON equals(ai_events__pdi.ai_events__pdi___person_id, ai_events__pdi__person.id)
- WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(ai_events.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'foo'), 0)))
+ WHERE and(equals(ai_events.team_id, 99999), in(ai_events.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(equals(ai_events.trace_id, 'trace1'), ifNull(equals(ai_events__pdi__person.properties___bar, 'foo'), 0)))
LIMIT 1 BY ai_events.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
@@ -509,7 +509,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS __ai_events_fallback__person ON equals(if(not(empty(__ai_events_fallback__override.distinct_id)), __ai_events_fallback__override.person_id, __ai_events_fallback.person_id), __ai_events_fallback__person.id)
- WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-12-01 00:20:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(__ai_events_fallback__person.properties___bar, 'foo'), 0)))
+ WHERE and(equals(__ai_events_fallback.team_id, 99999), in(__ai_events_fallback.event, tuple('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$ai_feedback', '$ai_trace')), and(greaterOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-11-30 23:50:00', 'UTC'))), lessOrEquals(__ai_events_fallback.timestamp, assumeNotNull(toDateTime('2024-12-08 00:10:00', 'UTC'))), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(__ai_events_fallback.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', ''), 'trace1'), 0), ifNull(equals(__ai_events_fallback__person.properties___bar, 'foo'), 0)))
LIMIT 1 BY __ai_events_fallback.uuid) AS deduped
GROUP BY deduped.trace_id
LIMIT 1 SETTINGS readonly=2,
diff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
index 30adad56eccb..0fb037b39806 100644
--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
@@ -1,5 +1,5 @@
import uuid
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, Literal, TypedDict
from uuid import UUID
@@ -576,6 +576,33 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
self.assertEqual(len(response.results), 1)
self.assertEqual(len(response.results[0].events), 2)
+ def test_capture_range_includes_long_running_trace(self):
+ _create_person(distinct_ids=["person1"], team=self.team)
+ # Trace anchored at date_from with spans spread over days; every span must land in the
+ # tree even though the later ones fall well past the backward capture buffer (#43310).
+ # The multi-day offset covers a chat resumed after the first day, which a sub-day forward
+ # bound truncates.
+ forward_offsets_minutes = [0, 45, 180, 720, 3 * 24 * 60]
+ for offset in forward_offsets_minutes:
+ _create_ai_generation_event(
+ distinct_id="person1",
+ trace_id="trace1",
+ team=self.team,
+ timestamp=datetime(2024, 12, 1, 0, 0) + timedelta(minutes=offset),
+ )
+
+ # The frontend anchors date_from/date_to on the trace's first event timestamp.
+ response = TraceQueryRunner(
+ team=self.team,
+ query=TraceQuery(
+ traceId="trace1",
+ dateRange=DateRange(date_from="2024-12-01T00:00:00Z", date_to="2024-12-01T00:00:00Z"),
+ ),
+ ).calculate()
+
+ self.assertEqual(len(response.results), 1)
+ self.assertEqual(len(response.results[0].events), len(forward_offsets_minutes))
+
def test_overlap_semantics_trace_started_before_window(self):
_create_person(distinct_ids=["person1"], team=self.team)
diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.py
index 17abd91f0767..2f4cc3989e2c 100644
--- a/posthog/hogql_queries/ai/trace_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_query_runner.py
@@ -49,11 +49,18 @@ TRACE_FIELDS_MAPPING: dict[str, str] = {
class TraceQueryDateRange(QueryDateRange):
"""
- Extends the QueryDateRange to include a capture range of 10 minutes before and after the date range.
- It's a naive assumption that a trace finishes generating within 10 minutes of the first event so we can apply the date filters.
+ Provides a bounded capture range for the shared-events fallback.
+
+ The dedicated table is ordered by `(team_id, trace_id, timestamp)`, so an exact trace lookup
+ does not need timestamp bounds. Shared events is ordered by day and event, so its fallback
+ stays time-bounded.
"""
+ # Backward buffer: clock skew / the small negative anchor the frontend applies to date_from.
CAPTURE_RANGE_MINUTES = 10
+ # Forward buffer: an upper bound on a single trace's duration. A trace that maps to a chat can
+ # stay open across days, so a sub-day bound silently truncates it.
+ FORWARD_CAPTURE_RANGE_MINUTES = 7 * 24 * 60
def date_from_for_filtering(self) -> datetime:
return super().date_from()
@@ -65,7 +72,7 @@ class TraceQueryDateRange(QueryDateRange):
return super().date_from() - timedelta(minutes=self.CAPTURE_RANGE_MINUTES)
def date_to(self) -> datetime:
- return super().date_to() + timedelta(minutes=self.CAPTURE_RANGE_MINUTES)
+ return super().date_to() + timedelta(minutes=self.FORWARD_CAPTURE_RANGE_MINUTES)
class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
@@ -78,10 +85,11 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
def _calculate(self):
query_result = query_ai_events(
query=self._build_query(),
- placeholders={"filter_conditions": self._get_where_clause()},
+ placeholders={"filter_conditions": self._get_where_clause(include_timestamp_bounds=False)},
team=self.team,
query_type=NodeKind.TRACE_QUERY,
fall_back_to_events=True,
+ fallback_placeholders={"filter_conditions": self._get_where_clause()},
timings=self.timings,
modifiers=self.modifiers,
limit_context=self.limit_context,
@@ -221,7 +229,7 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
@cached_property
def _date_range(self):
- # Minute-level precision for 10m capture range
+ # Minute-level precision for the capture range buffers
return TraceQueryDateRange(self.query.dateRange, self.team, IntervalType.MINUTE, datetime.now())
def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
@@ -230,19 +238,23 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
return last_refresh + timedelta(minutes=1)
- def _get_where_clause(self) -> ast.Expr:
- where_exprs: list[ast.Expr] = [
- ast.CompareOperation(
- op=ast.CompareOperationOp.GtEq,
- left=ast.Field(chain=["ai_events", "timestamp"]),
- right=self._date_range.date_from_as_hogql(),
- ),
- ast.CompareOperation(
- op=ast.CompareOperationOp.LtEq,
- left=ast.Field(chain=["ai_events", "timestamp"]),
- right=self._date_range.date_to_as_hogql(),
- ),
- ]
+ def _get_where_clause(self, *, include_timestamp_bounds: bool = True) -> ast.Expr:
+ where_exprs: list[ast.Expr] = []
+ if include_timestamp_bounds:
+ where_exprs.extend(
+ [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["ai_events", "timestamp"]),
+ right=self._date_range.date_from_as_hogql(),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["ai_events", "timestamp"]),
+ right=self._date_range.date_to_as_hogql(),
+ ),
+ ]
+ )
where_exprs.append(
ast.CompareOperation(