: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
feat(tracing): look up a trace by id without a date (#106171)
Frank Hamand4f2c81abff5c
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex b8dae0dc31ba..ffe7555a73ea 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2859,13 +2859,7 @@ const api = {return new ApiRequest().tracingSpans().withAction(`trace/${traceId}`)- .create({- signal,- data: {- ...query,- dateRange: query?.dateRange ?? { date_from: '-24h' },- },- })+ .create({ signal, data: { ...query } })},async sparkline(query: {diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 3f966426f85d..cdb4c1ec04bf 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -54387,7 +54387,7 @@"type": "number"}},- "required": ["dateRange", "kind"],+ "required": ["kind"],"type": "object"},"TraceSpansQueryResponse": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex b8a622be224e..17fcf7cb8d17 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -4991,7 +4991,7 @@ export type CachedLogsQueryResponse = CachedQueryResponse<LogsQueryResponse>export interface TraceSpansQuery extends DataNode<TraceSpansQueryResponse> {kind: NodeKind.TraceSpansQuery- dateRange: DateRange+ dateRange?: DateRangelimit?: integeroffset?: integer/** Column to order by. Defaults to timestamp. `timestamp` paginates via keyset cursor (`after`); other columns via `offset`. */diff --git a/posthog/hogql/database/schema/spans.py b/posthog/hogql/database/schema/spans.pyindex a9940575eec2..c53002df8634 100644--- a/posthog/hogql/database/schema/spans.py+++ b/posthog/hogql/database/schema/spans.py@@ -69,6 +69,9 @@ class TraceSpansTable(Table):"time_bucket": DateTimeDatabaseField(name="time_bucket", nullable=False, description="Coarse time bucket used for partitioning and filtering."),+ # internal fields for query optimization+ "_part": StringDatabaseField(name="_part", nullable=True, hidden=True),+ "_part_offset": IntegerDatabaseField(name="_part_offset", nullable=True, hidden=True),}def to_printed_clickhouse(self, context):diff --git a/posthog/schema.py b/posthog/schema.pyindex 407253f1805d..b037ea3401b5 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -29833,7 +29833,7 @@ class TraceSpansQuery(BaseModel):extra="forbid",)after: str | None = Field(default=None, description="Cursor for fetching the next page of results")- dateRange: DateRange+ dateRange: DateRange | None = NoneexcludeAttributes: bool | None = Field(default=None,description=("Omit the per-span `attributes` map from results to keep payloads compact"),diff --git a/products/tracing/backend/logic.py b/products/tracing/backend/logic.pyindex c2c3d127be07..e5af9342b300 100644--- a/products/tracing/backend/logic.py+++ b/products/tracing/backend/logic.py@@ -274,19 +274,32 @@ class TraceSpansQueryRunnerMixin(QueryRunner):prop = with_span_attribute_type_suffix(prop)self.span_attribute_filters.append(prop)+ @property+ def _unbounded_trace_lookup(self) -> bool:+ """A trace looked up by id with no date range, for example from a link without a `ts` hint."""+ return bool(self.query.traceId) and self.query.dateRange is None++ @property+ def _trace_id_b64(self) -> str:+ """The trace id in the table's base64 storage form. Callers pass it as hex or as base64."""+ assert self.query.traceId+ return _normalise_to_base64(self.query.traceId)+def where(self) -> ast.Expr:exprs: list[ast.Expr] = []- exprs.append(- parse_expr(- TIME_BUCKET_DATE_RANGE_WHERE,- placeholders={- **self.query_date_range.to_placeholders(),- },+ # A lookup by trace id alone has no date bound. `to_query` finds its rows through a projection instead.+ if not self._unbounded_trace_lookup:+ exprs.append(+ parse_expr(+ TIME_BUCKET_DATE_RANGE_WHERE,+ placeholders={+ **self.query_date_range.to_placeholders(),+ },+ ))- )- exprs.append(ast.Placeholder(expr=ast.Field(chain=["filters"])))+ exprs.append(ast.Placeholder(expr=ast.Field(chain=["filters"])))if self.query.serviceNames:exprs.append(@@ -321,12 +334,11 @@ class TraceSpansQueryRunnerMixin(QueryRunner):exprs.append(property_to_expr(f, team=self.team))if self.query.traceId:- trace_id_b64 = base64.b64encode(bytes.fromhex(self.query.traceId)).decode("ascii")exprs.append(parse_expr("trace_id = {traceId}",placeholders={- "traceId": ast.Constant(value=trace_id_b64),+ "traceId": ast.Constant(value=self._trace_id_b64),},))@@ -667,14 +679,18 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Tra{resource_attributes},max(if({where_for_start}, duration_nano, NULL)) OVER (PARTITION BY trace_id) as trace_durationFROM posthog.trace_spans- WHERE {filters} AND trace_id IN ({trace_id_query}) LIMIT {limit}+ WHERE {filters} AND {trace_filter} LIMIT {limit}""",placeholders={"where": self.where(),"where_for_start": key_predicate,- "trace_id_query": trace_id_query,+ "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}),"limit": ast.Constant(value=(self.query.limit or 1) * limit_by_n),- "filters": ast.Placeholder(expr=ast.Field(chain=["filters"])),+ "filters": ast.Constant(value=True)+ if self._unbounded_trace_lookup+ else ast.Placeholder(expr=ast.Field(chain=["filters"])),# 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 map@@ -720,6 +736,19 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Trareturn query+ def _unbounded_trace_filter(self) -> ast.Expr:+ """Find one trace's rows without a date bound, through `projection_index_team_trace_id`.++ `trace_id = X` on the main table loads the per-part `idx_trace_bloom_part` filter of every part+ in retention. The subquery below needs only team_id, trace_id and _part_offset, which the+ projection holds, so ClickHouse answers it from the projection and never opens those filters.+ HogQL adds the team_id guard to the subquery, which is why the projection must hold team_id.+ """+ return parse_expr(+ "(_part, _part_offset) IN (SELECT _part, _part_offset FROM posthog.trace_spans WHERE trace_id = {trace_id})",+ placeholders={"trace_id": ast.Constant(value=self._trace_id_b64)},+ )+def _build_flat_spans_query(self, *, by_duration: bool, order_dir: str) -> ast.SelectQuery:"""Flat span list: the matching spans themselves, no whole-trace expansion (see _flat_spans).@@ -730,6 +759,8 @@ class TraceSpansQueryRunner(TraceSpansQueryRunnerMixin, AnalyticsQueryRunner[Traare the span's own timestamp / duration."""where_exprs: list[ast.Expr] = [self.where()]+ if self._unbounded_trace_lookup:+ where_exprs.append(self._unbounded_trace_filter())# Time order keysets on (timestamp, span_id) in the WHERE; duration order offset-paginates via# the paginator (see _calculate). The coarse UTC day bound lets ClickHouse prune parts first —diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.pyindex 0ff70435aab2..d131d78459a7 100644--- a/products/tracing/backend/presentation/views.py+++ b/products/tracing/backend/presentation/views.py@@ -369,7 +369,7 @@ class _TracingSparklineRequestSerializer(serializers.Serializer):class _TracingTraceRequestSerializer(serializers.Serializer):dateRange = _TracingDateRangeSerializer(required=False,- help_text="Date range for the query. Defaults to last 24 hours.",+ help_text="Date range for the query. Omit it to search all retained spans for this trace.",)excludeAttributes = serializers.BooleanField(required=False,@@ -1834,8 +1834,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)def trace(self, request: Request, trace_id: str, *args, **kwargs) -> Response:tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)query_data = request.data or {}- date_range = self.get_model(- normalize_tracing_date_range(query_data.get("dateRange"), default_date_from="-24h"), DateRange+ date_range = (+ self.get_model(normalize_tracing_date_range(query_data["dateRange"], default_date_from="-24h"), DateRange)+ if query_data.get("dateRange")+ else None)try:# verify the trace_id is validdiff --git a/products/tracing/backend/tests/test_trace_pagination.py b/products/tracing/backend/tests/test_trace_pagination.pyindex 0a0cc6933a17..5c270708987f 100644--- a/products/tracing/backend/tests/test_trace_pagination.py+++ b/products/tracing/backend/tests/test_trace_pagination.py@@ -1,12 +1,22 @@import datetime as dt+from parameterized import parameterized++from posthog.schema import TraceSpansQuery+from posthog.clickhouse.client import sync_execute+from products.tracing.backend.logic import TraceSpansQueryRunnerfrom products.tracing.backend.presentation.views import TRACE_SPANS_PAGE_SIZEfrom products.tracing.backend.tests.test_keyset_pagination import _b64, _TraceSpansTestBaseBASE = dt.datetime(2026, 6, 2, 8, 0, 0)SPAN_COUNT = TRACE_SPANS_PAGE_SIZE + 3 # spills past one page so paging actually kicks in+# BASE is older than any default window, so the undated lookup can find the trace only by its id.+LOOKUPS = [+ ("dated", {"date_from": "2026-06-02T07:00:00Z", "date_to": "2026-06-02T09:00:00Z"}),+ ("undated", None),+]class TestTracePagination(_TraceSpansTestBase):@@ -35,21 +45,20 @@ class TestTracePagination(_TraceSpansTestBase):"timestamp, end_time, observed_timestamp, status_code, service_name) VALUES " + ",".join(rows))- def _fetch_page(self, offset: int = 0) -> dict:+ def _fetch_page(self, date_range: dict | None, offset: int = 0) -> dict:trace_hex = (1).to_bytes(16, "big").hex()+ body: dict = {"offset": offset}+ if date_range is not None:+ body["dateRange"] = date_rangeresponse = self.client.post(- f"/api/projects/{self.team.id}/tracing/spans/trace/{trace_hex}/",- {- "dateRange": {"date_from": "2026-06-02T07:00:00Z", "date_to": "2026-06-02T09:00:00Z"},- "offset": offset,- },- format="json",+ f"/api/projects/{self.team.id}/tracing/spans/trace/{trace_hex}/", body, format="json")self.assertEqual(response.status_code, 200, response.content)return response.json()- def test_first_page_is_the_earliest_spans_by_start_time(self):- page = self._fetch_page()+ @parameterized.expand(LOOKUPS)+ def test_first_page_is_the_earliest_spans_by_start_time(self, _name: str, date_range: dict | None):+ page = self._fetch_page(date_range)names = [span["name"] for span in page["results"]]self.assertEqual(len(names), TRACE_SPANS_PAGE_SIZE)# The first page is exactly the earliest-starting spans (span_no 1..PAGE_SIZE), in order.@@ -57,15 +66,43 @@ class TestTracePagination(_TraceSpansTestBase):self.assertTrue(page["hasMore"])self.assertEqual(page["nextOffset"], TRACE_SPANS_PAGE_SIZE)- def test_second_page_returns_the_remainder_and_ends(self):- page = self._fetch_page(offset=TRACE_SPANS_PAGE_SIZE)+ @parameterized.expand(LOOKUPS)+ def test_second_page_returns_the_remainder_and_ends(self, _name: str, date_range: dict | None):+ page = self._fetch_page(date_range, offset=TRACE_SPANS_PAGE_SIZE)names = {span["name"] for span in page["results"]}self.assertEqual(names, {f"op-{n}" for n in range(TRACE_SPANS_PAGE_SIZE + 1, SPAN_COUNT + 1)})self.assertFalse(page["hasMore"])self.assertIsNone(page["nextOffset"])- def test_pages_do_not_overlap(self):- first = {span["span_id"] for span in self._fetch_page()["results"]}- second = {span["span_id"] for span in self._fetch_page(offset=TRACE_SPANS_PAGE_SIZE)["results"]}+ @parameterized.expand(LOOKUPS)+ def test_pages_do_not_overlap(self, _name: str, date_range: dict | None):+ first = {span["span_id"] for span in self._fetch_page(date_range)["results"]}+ second = {span["span_id"] for span in self._fetch_page(date_range, offset=TRACE_SPANS_PAGE_SIZE)["results"]}self.assertEqual(first & second, set())self.assertEqual(len(first | second), SPAN_COUNT)++ # The query API passes traceId through unvalidated, so it can arrive in the stored base64 form too. Both+ # query shapes must reach an undated trace through the projection subquery, not a scan of every part.+ @parameterized.expand(+ [+ (f"{fmt}_{shape}", trace_id, flat)+ for fmt, trace_id in (("hex", (1).to_bytes(16, "big").hex()), ("base64", _b64((1).to_bytes(16, "big"))))+ for shape, flat in (("grouped", False), ("flat", True))+ ]+ )+ def test_undated_lookup_finds_the_trace_through_the_projection(self, _name: str, trace_id: str, flat: bool):+ query = TraceSpansQuery(+ traceId=trace_id,+ orderBy="timestamp",+ orderDirection="ASC",+ limit=1,+ prefetchSpans=SPAN_COUNT,+ rootSpans=False,+ flatSpans=flat,+ )+ where = TraceSpansQueryRunner(query, self.team).to_query().where+ assert where is not None+ self.assertIn("_part_offset", where.to_hogql())+ rows = self._execute(query)+ self.assertTrue(rows)+ self.assertEqual({row[1] for row in rows}, {(1).to_bytes(16, "big").hex().upper()})diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.tsindex b39a9e7806c7..fa29a149a31d 100644--- a/products/tracing/frontend/generated/api.schemas.ts+++ b/products/tracing/frontend/generated/api.schemas.ts@@ -894,7 +894,7 @@ export interface _SymbolStatsResponseApi {}export interface _TracingTraceRequestApi {- /** Date range for the query. Defaults to last 24 hours. */+ /** Date range for the query. Omit it to search all retained spans for this trace. */dateRange?: _TracingDateRangeApi/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */excludeAttributes?: booleandiff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.tsindex c3a8d8155c38..afa17ebe7542 100644--- a/products/tracing/frontend/generated/api.zod.ts+++ b/products/tracing/frontend/generated/api.zod.ts@@ -1196,7 +1196,7 @@ export const TracingSpansTraceCreateBody = /* @__PURE__ */ zod.object({.describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),}).optional()- .describe('Date range for the query. Defaults to last 24 hours.'),+ .describe('Date range for the query. Omit it to search all retained spans for this trace.'),excludeAttributes: zod.boolean().default(tracingSpansTraceCreateBodyExcludeAttributesDefault)diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.tsindex 372b2d92126b..a401147f1ef1 100644--- a/products/tracing/frontend/traceLinks.ts+++ b/products/tracing/frontend/traceLinks.ts@@ -1,7 +1,7 @@// Canonical trace URLs (JON-33). The URL is the atomic, shareable form of a trace view:-// `/tracing?trace=<hex>` opens the drawer, `&span=<hex>` anchors a span, `&ts=<iso>` carries the-// root timestamp so a cold load can bound the ClickHouse lookup (the table is time-keyed and OTel-// trace ids embed no timestamp — an unhinted id lookup would scan the whole retention window).+// `/tracing?trace=<hex>` opens the drawer, `&span=<hex>` anchors a span, and the optional `&ts=<iso>`+// carries the root timestamp so a cold load can bound the ClickHouse lookup to a narrow window. A link+// without `ts` still opens the trace: the backend finds it by id through the trace_id projection.import { combineUrl } from 'kea-router'diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex fa9d8b93ed22..2308dfa3ec81 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -86,21 +86,12 @@ const DEFAULT_PAGE_SIZE = 100const OPERATIONS_AGGREGATION_LIMIT = 5000export const PREFETCH_SPANS = 20-// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace instead of the-// scene's current date range — the table is time-keyed, so this is what keeps an id lookup from-// scanning the whole window. Guard validity: a hand-edited/corrupted ts would otherwise make dayjs-// throw on toISOString().-function resolveTraceLookupRange(- ts: string | null | undefined,- utcDateRange: { date_from?: string | null; date_to?: string | null }-): { date_from?: string | null; date_to?: string | null } {- if (ts && dayjs(ts).isValid()) {- return traceLookupDateRange(ts)- }- return {- date_from: utcDateRange.date_from ?? '-24h',- date_to: utcDateRange.date_to ?? undefined,- }+// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace. Without one, the+// lookup sends no date range, so the backend finds the trace by id in all retained spans instead of+// only in the scene's current window. Guard validity: a hand-edited/corrupted ts would otherwise make+// dayjs throw on toISOString().+function resolveTraceLookupRange(ts: string | null | undefined): { date_from: string; date_to: string } | undefined {+ return ts && dayjs(ts).isValid() ? traceLookupDateRange(ts) : undefined}function captureTracingResults(count: number, queryType: 'spans' | 'aggregation'): void {@@ -948,7 +939,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([{loadTraceSpans: async ({ traceId, ts }: { traceId: string; ts?: string | null }): Promise<Span[]> => {const response = await api.tracing.getTrace(traceId, {- dateRange: resolveTraceLookupRange(ts, values.utcDateRange),+ dateRange: resolveTraceLookupRange(ts),serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.queryFilterGroup as PropertyGroupFilter,})@@ -963,7 +954,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([}const { traceId, ts } = values.traceLoadContextconst response = await api.tracing.getTrace(traceId, {- dateRange: resolveTraceLookupRange(ts, values.utcDateRange),+ dateRange: resolveTraceLookupRange(ts),serviceNames: values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.queryFilterGroup as PropertyGroupFilter,offset: values.traceSpansNextOffset,diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.tsindex f53919168522..15633150377f 100644--- a/products/tracing/frontend/tracingViewerLogic.test.ts+++ b/products/tracing/frontend/tracingViewerLogic.test.ts@@ -57,6 +57,21 @@ describe('tracingViewerLogic', () => {expect(getTraceSpy.mock.calls.length > 0).toBe(shouldFetch)})+ // Without a ts hint the lookup must not fall back to a date window, or a trace older than that+ // window never loads. With a hint, the lookup stays bounded to the hint's narrow window.+ it.each([+ [+ 'a ts hint',+ '2024-01-01T00:00:00Z',+ { date_from: '2023-12-31T23:00:00.000Z', date_to: '2024-01-01T01:00:00.000Z' },+ ],+ ['no ts hint', undefined, undefined],+ ])('openTrace with %s sends the matching date range', async (_name, ts, dateRange) => {+ await expectLogic(logic, () => logic.actions.openTrace('trace-x', { ts })).toFinishAllListeners()++ expect(getTraceSpy.mock.calls[0][1].dateRange).toEqual(dateRange)+ })+describe('identity resolution', () => {// The featureFlags reducer persists, so it survives initKeaTests. Each test sets the flag// it wants, otherwise a flag one test enables leaks into the next.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex dc50a0a88300..e9a15809d1d8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -52265,7 +52265,7 @@ export namespace Schemas {export interface TraceSpansQuery {/** Cursor for fetching the next page of results */after?: string | null;- dateRange: DateRange;+ dateRange?: DateRange | null;/** Omit the per-span `attributes` map from results to keep payloads compact */excludeAttributes?: boolean | null;filterGroup?: PropertyGroupFilter | null;@@ -105466,7 +105466,7 @@ export namespace Schemas {}export interface _TracingTraceRequest {- /** Date range for the query. Defaults to last 24 hours. */+ /** Date range for the query. Omit it to search all retained spans for this trace. */dateRange?: _TracingDateRange;/** Omit the per-span attributes and resource attributes maps from results to keep payloads compact. Defaults to false. */excludeAttributes?: boolean;diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.tsindex 3cc0cd131347..db1403209a1f 100644--- a/services/mcp/src/generated/tracing/api.ts+++ b/services/mcp/src/generated/tracing/api.ts@@ -930,7 +930,7 @@ export const TracingSpansTraceCreateBody = () => zod.object({.describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),}).optional()- .describe('Date range for the query. Defaults to last 24 hours.'),+ .describe('Date range for the query. Omit it to search all retained spans for this trace.'),excludeAttributes: zod.boolean().default(tracingSpansTraceCreateBodyExcludeAttributesDefault)diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.jsonindex 2409fad3870f..11f28b332e40 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-trace-get.json@@ -2,7 +2,7 @@"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {"dateRange": {- "description": "Date range for the query. Defaults to last 24 hours.",+ "description": "Date range for the query. Omit it to search all retained spans for this trace.","properties": {"date_from": {"anyOf": [