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(tracing): add latency-heatmap query endpoint (#71555)

Jon McCallum4c5563d4816a
diff --git a/products/tracing/backend/duration_histogram_query_runner.py b/products/tracing/backend/duration_histogram_query_runner.py
index 3dbe3d55c9d3..04059198abb9 100644
--- a/products/tracing/backend/duration_histogram_query_runner.py
+++ b/products/tracing/backend/duration_histogram_query_runner.py
@@ -21,6 +21,43 @@ if TYPE_CHECKING:
from posthog.models import Team
+def duration_bucket_expr() -> ast.Expr:
+ """Bucket `duration_nano` onto the 1-2-5 series (1ms, 2ms, 5ms, 10ms, ...).
+
+ Takes the duration's decade (power of ten) and snaps the mantissa down to 1, 2 or 5.
+ `greatest(..., 1)` parks zero-duration spans in the 1ns bucket instead of feeding log10(0).
+ The mantissa expression repeats the decade rather than referencing its alias so HogQL
+ resolution never depends on sibling aliases; ClickHouse collapses the common subexpression.
+ `round()` before the cast absorbs float wobble in pow/log10 (e.g. 4.9999...e8 → 5e8).
+
+ Shared by the duration histogram and the latency heatmap, and mirrored in
+ `frontend/durationBuckets.ts` (snapDurationToBucket) — change the series in BOTH places.
+ """
+ return parse_expr(
+ """
+ toInt(round(
+ pow(10, floor(log10(greatest(duration_nano, 1)))) * multiIf(
+ duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 2, 1,
+ duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 5, 2,
+ 5
+ )
+ ))
+ """
+ )
+
+
+def root_scope_expr(root_spans: bool | None) -> ast.Expr:
+ """Restrict a span scan to root spans unless `root_spans` is explicitly False.
+
+ Root scoping is the default — a distribution of *traces* by root duration. `False`
+ (the operation detail page, scoped by span name) buckets every matching span instead.
+ Shared by the duration histogram and the latency heatmap so the two can't drift.
+ """
+ if root_spans is not False:
+ return parse_expr("is_root_span = 1")
+ return ast.Constant(value=True)
+
+
class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):
"""Trace counts per logarithmic duration bucket, stacked by service.
@@ -32,9 +69,9 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):
Root scoping is the default — a distribution of *traces* for the trace list, where counting
child spans would mix units. When `query.rootSpans` is explicitly False (the operation detail
page, which scopes by span name), every matching span is counted instead: same-named spans
- are the same unit, so a span-level distribution is sound there. The 1-2-5 bucketing below is
- mirrored in `frontend/durationBuckets.ts` (snapDurationToBucket), which re-snaps client-side
- only to place the scroll highlight — change the series in BOTH places.
+ are the same unit, so a span-level distribution is sound there. The 1-2-5 bucketing
+ (`duration_bucket_expr`) is mirrored in `frontend/durationBuckets.ts` (snapDurationToBucket),
+ which re-snaps client-side only to place the scroll highlight — change the series in BOTH places.
"""
def _calculate(self) -> TraceSpansQueryResponse:
@@ -62,22 +99,10 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):
return TraceSpansQueryResponse(results=results)
def to_query(self) -> ast.SelectQuery:
- # Bucket a duration onto the 1-2-5 series: take its decade (power of ten) and snap the
- # mantissa down to 1, 2 or 5. `greatest(..., 1)` parks zero-duration spans in the 1ns
- # bucket instead of feeding log10(0). The mantissa expression repeats the decade rather
- # than referencing its alias so HogQL resolution never depends on sibling aliases;
- # ClickHouse collapses the common subexpression. `round()` before the cast absorbs float
- # wobble in pow/log10 (e.g. 4.9999...e8 → 5e8).
query = parse_select(
"""
SELECT
- toInt(round(
- pow(10, floor(log10(greatest(duration_nano, 1)))) * multiIf(
- duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 2, 1,
- duration_nano / pow(10, floor(log10(greatest(duration_nano, 1)))) < 5, 2,
- 5
- )
- )) AS bucket_ns,
+ {bucket_expr} AS bucket_ns,
service_name AS service,
count() AS count
FROM posthog.trace_spans
@@ -91,10 +116,9 @@ class TraceSpansDurationHistogramQueryRunner(TraceSpansQueryRunner):
""",
placeholders={
**self.query_date_range.to_placeholders(),
+ "bucket_expr": duration_bucket_expr(),
"where": self.where(),
- "root_scope": parse_expr("is_root_span = 1")
- if self.query.rootSpans is not False
- else ast.Constant(value=True),
+ "root_scope": root_scope_expr(self.query.rootSpans),
},
)
assert isinstance(query, ast.SelectQuery)
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index 64a4ac207b87..645be878abcb 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -41,6 +41,9 @@ from products.tracing.backend.count_query_runner import run_count_query as _run_
from products.tracing.backend.duration_histogram_query_runner import (
run_duration_histogram_query as _run_duration_histogram_query,
)
+from products.tracing.backend.latency_heatmap_query_runner import (
+ run_latency_heatmap_query as _run_latency_heatmap_query,
+)
from products.tracing.backend.self_time import annotate_self_time as _annotate_self_time
from products.tracing.backend.symbol_stats_query_runner import run_symbol_stats_query as _run_symbol_stats_query
@@ -146,6 +149,30 @@ def run_duration_histogram_query(
)
+def run_latency_heatmap_query(
+ *,
+ team: "Team",
+ date_range: DateRange,
+ service_names: list[str] | None = None,
+ status_codes: list[int] | None = None,
+ filter_group: PropertyGroupFilter | None = None,
+ root_spans: bool = True,
+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:
+ """Run the latency-over-time heatmap: counts per (time bucket, 1-2-5 duration bucket).
+
+ Root spans by default (a distribution of traces); `root_spans=False` buckets every
+ matching span — pair with a span name filter for operation-scoped heatmaps.
+ """
+ return _run_latency_heatmap_query(
+ team=team,
+ date_range=date_range,
+ service_names=service_names,
+ status_codes=status_codes,
+ filter_group=filter_group,
+ root_spans=root_spans,
+ )
+
+
def annotate_self_time(spans: list[dict]) -> None:
"""Set `self_time_nano` on every span dict of a full trace, in place."""
_annotate_self_time(spans)
diff --git a/products/tracing/backend/latency_heatmap_query_runner.py b/products/tracing/backend/latency_heatmap_query_runner.py
new file mode 100644
index 000000000000..4032dac96332
--- /dev/null
+++ b/products/tracing/backend/latency_heatmap_query_runner.py
@@ -0,0 +1,140 @@
+from typing import TYPE_CHECKING
+from zoneinfo import ZoneInfo
+
+from posthog.schema import (
+ CachedTraceSpansQueryResponse,
+ DateRange,
+ PropertyGroupFilter,
+ TraceSpansQuery,
+ TraceSpansQueryResponse,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import Workload
+from posthog.hogql_queries.query_runner import ExecutionMode
+
+from products.tracing.backend.duration_histogram_query_runner import duration_bucket_expr, root_scope_expr
+from products.tracing.backend.logic import TraceSpansQueryRunner
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+
+class TraceSpansLatencyHeatmapQueryRunner(TraceSpansQueryRunner):
+ """Span counts per (time bucket, logarithmic duration bucket) — a latency-over-time heatmap.
+
+ x = the sparkline's gap-filled time axis (~50 buckets), y = the duration histogram's 1-2-5
+ series buckets (`duration_bucket_expr`), cell = count. Every time bucket in the window is
+ enumerated: a bucket with no matching spans comes back as a single `{time, bucket_ns: 0,
+ count: 0}` sentinel row, so the frontend derives the axis from the response instead of
+ re-implementing the interval logic. Cells encode density only — no service breakdown.
+
+ Root scoping matches the duration histogram: by default only root spans are bucketed (a
+ distribution of traces by root duration, the row the trace list displays). When
+ `query.rootSpans` is explicitly False (the operation detail page, scoped by span name),
+ every matching span counts instead.
+ """
+
+ def _calculate(self) -> TraceSpansQueryResponse:
+ response = execute_hogql_query(
+ query_type="TraceSpansLatencyHeatmapQuery",
+ query=self.to_query(),
+ modifiers=self.modifiers,
+ team=self.team,
+ workload=Workload.LOGS,
+ timings=self.timings,
+ limit_context=self.limit_context,
+ settings=self.settings,
+ )
+
+ results = []
+ for row in response.results:
+ results.append(
+ {
+ "time": row[0].replace(tzinfo=ZoneInfo("UTC")).isoformat(),
+ "bucket_ns": int(row[1]),
+ "count": int(row[2]),
+ }
+ )
+
+ return TraceSpansQueryResponse(results=results)
+
+ def to_query(self) -> ast.SelectQuery:
+ # The numbers() time axis mirrors sparkline_query_runner.py — keep the bucket edges
+ # identical so the two charts' x axes line up. Unlike the sparkline, the inner scan
+ # groups on raw `timestamp`: the sparkline's toStartOfMinute(timestamp) trick exists to
+ # hit a (minute, service) projection, which a group-by including duration buckets can
+ # never use anyway. LIMIT 40 BY time caps the duration axis per column; real durations
+ # (1ns–100s+) span at most ~35 of the 1-2-5 buckets.
+ query = parse_select(
+ """
+ SELECT
+ am.time_bucket AS time,
+ ifNull(ac.bucket_ns, 0) AS bucket_ns,
+ ifNull(ac.count, 0) AS count
+ FROM (
+ SELECT
+ dateAdd({date_from_start_of_interval}, {number_interval_period}) AS time_bucket
+ FROM numbers(
+ floor(
+ dateDiff({interval},
+ {date_from_start_of_interval},
+ {date_to_start_of_interval}) / {interval_count} + 1
+ )
+ )
+ WHERE
+ time_bucket >= {date_from_start_of_interval} and
+ time_bucket <= greatest(
+ {date_from_start_of_interval},
+ toStartOfInterval({date_to} - toIntervalSecond(1), {one_interval_period})
+ )
+ ) AS am
+ LEFT JOIN (
+ SELECT
+ toStartOfInterval(timestamp, {one_interval_period}) AS time,
+ {bucket_expr} AS bucket_ns,
+ count() AS count
+ FROM posthog.trace_spans
+ WHERE {where} AND {root_scope}
+ AND time >= {date_from_start_of_interval} AND time <= {date_to}
+ GROUP BY time, bucket_ns
+ ) AS ac ON am.time_bucket = ac.time
+ ORDER BY time ASC, bucket_ns ASC
+ LIMIT 40 BY time
+ LIMIT 10000
+ """,
+ placeholders={
+ **self.query_date_range.to_placeholders(),
+ "bucket_expr": duration_bucket_expr(),
+ "where": self.where(),
+ "root_scope": root_scope_expr(self.query.rootSpans),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+
+def run_latency_heatmap_query(
+ *,
+ team: "Team",
+ date_range: DateRange,
+ service_names: list[str] | None = None,
+ status_codes: list[int] | None = None,
+ filter_group: PropertyGroupFilter | None = None,
+ root_spans: bool = True,
+) -> TraceSpansQueryResponse | CachedTraceSpansQueryResponse:
+ """Facade-friendly entry point for running a latency heatmap query."""
+ query = TraceSpansQuery(
+ dateRange=date_range,
+ serviceNames=service_names,
+ statusCodes=status_codes,
+ filterGroup=filter_group,
+ rootSpans=root_spans,
+ )
+ runner = TraceSpansLatencyHeatmapQueryRunner(query, team)
+ response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS)
+ assert isinstance(response, TraceSpansQueryResponse | CachedTraceSpansQueryResponse)
+ return response
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 8d073b184b0e..b5e51df998be 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -48,6 +48,7 @@ from ..facade.api import (
run_attribute_breakdown_query,
run_count_query,
run_duration_histogram_query,
+ run_latency_heatmap_query,
run_symbol_stats_query,
)
from ..has_spans_query_runner import team_has_spans
@@ -228,6 +229,33 @@ class _TracingDurationHistogramRequestSerializer(serializers.Serializer):
query = _TracingDurationHistogramQueryBodySerializer(help_text="The duration-histogram query to execute.")
+class _TracingLatencyHeatmapRequestSerializer(serializers.Serializer):
+ query = _TracingDurationHistogramQueryBodySerializer(help_text="The latency-heatmap query to execute.")
+
+
+class _TracingLatencyHeatmapCellSerializer(serializers.Serializer):
+ time = serializers.CharField(help_text="ISO 8601 UTC start of the time bucket.")
+ bucket_ns = serializers.IntegerField(
+ help_text=(
+ "Lower edge of the 1-2-5 series duration bucket in nanoseconds (1ms, 2ms, 5ms, 10ms, ...). "
+ "0 on the sentinel row that enumerates a time bucket with no matching spans."
+ ),
+ )
+ count = serializers.IntegerField(
+ help_text="Spans (or traces when rootSpans is true) in this cell. 0 only on sentinel rows.",
+ )
+
+
+class _TracingLatencyHeatmapResponseSerializer(serializers.Serializer):
+ results = _TracingLatencyHeatmapCellSerializer(
+ many=True,
+ help_text=(
+ "Sparse heatmap cells ordered by time then duration bucket. Every time bucket in the "
+ "window appears in at least one row, so the full x axis can be derived from the response."
+ ),
+ )
+
+
class _TracingSparklineQueryBodySerializer(_TracingTimeseriesQueryBodySerializer):
rootSpans = serializers.BooleanField(
required=False,
@@ -972,6 +1000,36 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"results": response.results}, status=status.HTTP_200_OK)
+ @extend_schema(
+ request=_TracingLatencyHeatmapRequestSerializer,
+ responses={200: _TracingLatencyHeatmapResponseSerializer},
+ )
+ @action(detail=False, methods=["POST"], url_path="latency-heatmap", required_scopes=["tracing:read"])
+ def latency_heatmap(self, request: Request, *args, **kwargs) -> Response:
+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
+ query_data = request.data.get("query", {}) or {}
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
+
+ try:
+ filter_group = (
+ self.get_model(self._normalize_filter_group(query_data["filterGroup"]), PropertyGroupFilter)
+ if query_data.get("filterGroup")
+ else None
+ )
+ except (ValidationError, ValueError, ParseError):
+ filter_group = None
+
+ response = run_latency_heatmap_query(
+ team=self.team,
+ date_range=date_range,
+ service_names=query_data.get("serviceNames", None),
+ status_codes=query_data.get("statusCodes", None),
+ filter_group=filter_group,
+ root_spans=query_data.get("rootSpans", True),
+ )
+
+ return Response({"results": response.results}, status=status.HTTP_200_OK)
+
@extend_schema(request=_TracingAggregationRequestSerializer)
@action(detail=False, methods=["POST"], url_path="aggregate", required_scopes=["tracing:read"])
def aggregate(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/tracing/backend/tests/test_latency_heatmap.py b/products/tracing/backend/tests/test_latency_heatmap.py
new file mode 100644
index 000000000000..f8929cb461e1
--- /dev/null
+++ b/products/tracing/backend/tests/test_latency_heatmap.py
@@ -0,0 +1,111 @@
+import datetime as dt
+
+from posthog.clickhouse.client import sync_execute
+
+from products.tracing.backend.tests.test_keyset_pagination import DATE_FROM, DATE_TO, _b64, _TraceSpansTestBase
+
+# Roots across two 2-minute time buckets (08:00, 08:30) and 1-2-5 duration-bucket boundaries:
+# 1.5ms → 1ms bucket, 3ms and 3.5ms → 2ms bucket, 700ms → 500ms bucket. Trace 0 also gets a
+# 5s child span, which must not appear in the default heatmap — root durations only.
+TRACES = [
+ # (timestamp, root duration, child duration, service)
+ (dt.datetime(2026, 6, 2, 8, 0, 0), dt.timedelta(milliseconds=1.5), dt.timedelta(seconds=5), "web"),
+ (dt.datetime(2026, 6, 2, 8, 0, 0), dt.timedelta(milliseconds=3), None, "web"),
+ (dt.datetime(2026, 6, 2, 8, 30, 0), dt.timedelta(milliseconds=3.5), None, "web"),
+ (dt.datetime(2026, 6, 2, 8, 30, 0), dt.timedelta(milliseconds=700), None, "api"),
+]
+
+MS = 1_000_000 # ns per ms
+# The 07:00-09:00 window buckets to 2-minute intervals (~50 target buckets), so these
+# timestamps are bucket starts.
+T0800 = "2026-06-02T08:00:00+00:00"
+T0830 = "2026-06-02T08:30:00+00:00"
+
+
+class TestTraceSpansLatencyHeatmap(_TraceSpansTestBase):
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ cls._recreate_trace_spans_tables()
+
+ rows: list[str] = []
+ for i, (timestamp, root_duration, child_duration, service) in enumerate(TRACES):
+ trace_id = _b64(i.to_bytes(16, "big"))
+ root_span_id = _b64((1000 + i * 2).to_bytes(8, "big"))
+ ts_str = timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")
+ root_end = (timestamp + root_duration).strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows.append(
+ f"('019e8758-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{root_span_id}', '', "
+ f"'GET /api', 2, '{ts_str}', '{root_end}', '{ts_str}', 0, '{service}')"
+ )
+ if child_duration is not None:
+ child_span_id = _b64((1001 + i * 2).to_bytes(8, "big"))
+ child_end = (timestamp + child_duration).strftime("%Y-%m-%d %H:%M:%S.%f")
+ rows.append(
+ f"('019e8758-0000-0000-0000-{len(rows):012d}', {cls.team.id}, '{trace_id}', '{child_span_id}', "
+ f"'{root_span_id}', 'db query', 2, '{ts_str}', '{child_end}', '{ts_str}', 0, '{service}')"
+ )
+ 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)
+ )
+
+ def _heatmap(self, **extra_query: object) -> list[dict]:
+ query: dict = {"dateRange": {"date_from": DATE_FROM, "date_to": DATE_TO}, **extra_query}
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/latency-heatmap/",
+ {"query": query},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ return response.json()["results"]
+
+ def test_cells_bucket_root_durations_by_time_and_1_2_5_series(self):
+ rows = self._heatmap()
+ cells = {(row["time"], row["bucket_ns"]): row["count"] for row in rows if row["count"] > 0}
+ self.assertEqual(
+ cells,
+ {
+ (T0800, 1 * MS): 1, # 1.5ms → 1ms bucket
+ (T0800, 2 * MS): 1, # 3ms → 2ms bucket
+ (T0830, 2 * MS): 1, # 3.5ms → 2ms bucket
+ (T0830, 500 * MS): 1, # 700ms → 500ms bucket
+ },
+ )
+ # Implicit in the equality above, but loud: the 5s child span produces no cell — the
+ # default heatmap counts traces by ROOT duration, like the trace list and histogram.
+
+ # Quiet time buckets come back as one {time, bucket_ns: 0, count: 0} sentinel each, so
+ # the frontend can enumerate the full x axis without re-deriving the interval logic.
+ sentinels = [row for row in rows if row["count"] == 0]
+ self.assertTrue(sentinels)
+ self.assertTrue(all(row["bucket_ns"] == 0 for row in sentinels))
+ self.assertGreater(len({row["time"] for row in rows}), len({time for time, _ in cells}))
+
+ def test_root_spans_false_counts_child_spans_for_operation_scope(self):
+ # The operation detail page scopes by span name and needs child spans counted: the 5s
+ # 'db query' child (invisible to the root-only heatmap above) must appear, in its
+ # trace's time bucket.
+ rows = self._heatmap(
+ rootSpans=False,
+ filterGroup={
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"type": "span", "key": "name", "operator": "exact", "value": ["db query"]}],
+ }
+ ],
+ },
+ )
+ cells = {(row["time"], row["bucket_ns"]): row["count"] for row in rows if row["count"] > 0}
+ self.assertEqual(cells, {(T0800, 5_000 * MS): 1})
+
+ def test_null_query_body_does_not_crash(self):
+ # An explicit `{"query": null}` body must fall back to defaults, not AttributeError into a 500.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/latency-heatmap/",
+ {"query": None},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200, response.content)
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index c77d3e403292..f77c691beb9e 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -262,6 +262,25 @@ export interface _HasSpansResponseApi {
hasSpans: boolean
}
+export interface _TracingLatencyHeatmapRequestApi {
+ /** The latency-heatmap query to execute. */
+ query: _TracingDurationHistogramQueryBodyApi
+}
+
+export interface _TracingLatencyHeatmapCellApi {
+ /** ISO 8601 UTC start of the time bucket. */
+ time: string
+ /** Lower edge of the 1-2-5 series duration bucket in nanoseconds (1ms, 2ms, 5ms, 10ms, ...). 0 on the sentinel row that enumerates a time bucket with no matching spans. */
+ bucket_ns: number
+ /** Spans (or traces when rootSpans is true) in this cell. 0 only on sentinel rows. */
+ count: number
+}
+
+export interface _TracingLatencyHeatmapResponseApi {
+ /** Sparse heatmap cells ordered by time then duration bucket. Every time bucket in the window appears in at least one row, so the full x axis can be derived from the response. */
+ results: _TracingLatencyHeatmapCellApi[]
+}
+
/**
* * `timestamp` - timestamp
* * `duration` - duration
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index 1e61210f1e4f..a6da1adab149 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -26,6 +26,8 @@ import type {
_TracingCountRequestApi,
_TracingCountResponseApi,
_TracingDurationHistogramRequestApi,
+ _TracingLatencyHeatmapRequestApi,
+ _TracingLatencyHeatmapResponseApi,
_TracingQueryRequestApi,
_TracingSparklineRequestApi,
_TracingTraceRequestApi,
@@ -161,6 +163,23 @@ export const tracingSpansHasSpansRetrieve = async (
})
}
+export const getTracingSpansLatencyHeatmapCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tracing/spans/latency-heatmap/`
+}
+
+export const tracingSpansLatencyHeatmapCreate = async (
+ projectId: string,
+ _tracingLatencyHeatmapRequestApi: _TracingLatencyHeatmapRequestApi,
+ options?: RequestInit
+): Promise<_TracingLatencyHeatmapResponseApi> => {
+ return apiMutator<_TracingLatencyHeatmapResponseApi>(getTracingSpansLatencyHeatmapCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingLatencyHeatmapRequestApi),
+ })
+}
+
export const getTracingSpansQueryCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/tracing/spans/query/`
}
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index 9bae2ea66ebb..dc81446e9c28 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -381,6 +381,89 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec
.describe('The duration-histogram query to execute.'),
})
+export const tracingSpansLatencyHeatmapCreateBodyQueryOneFilterGroupDefault = []
+export const tracingSpansLatencyHeatmapCreateBodyQueryOneRootSpansDefault = true
+
+export const TracingSpansLatencyHeatmapCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ dateRange: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -1h, -6h, -1d, -7d, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .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 hour.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Filter by service names.'),
+ statusCodes: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'Filter by OTel span status codes (0 Unset, 1 OK, 2 Error) — not HTTP status codes. Use [2] to select error spans.'
+ ),
+ filterGroup: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'Attribute key. For type \"span\", use built-in fields (trace_id, span_id, duration, name, kind, status_code, is_root_span). For \"span_attribute\"\/\"span_resource_attribute\", use the attribute key (e.g. \"http.method\").'
+ ),
+ type: zod
+ .enum(['span', 'span_attribute', 'span_resource_attribute'])
+ .describe(
+ '\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'
+ )
+ .describe(
+ '\"span\" filters built-in span fields. \"span_attribute\" filters span-level attributes. \"span_resource_attribute\" filters resource-level attributes.\n\n\* `span` - span\n\* `span_attribute` - span_attribute\n\* `span_resource_attribute` - span_resource_attribute'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'lt',
+ 'is_set',
+ 'is_not_set',
+ ])
+ .describe(
+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ )
+ .describe(
+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'
+ ),
+ })
+ )
+ .default(tracingSpansLatencyHeatmapCreateBodyQueryOneFilterGroupDefault)
+ .describe('Property filters for the query.'),
+ rootSpans: zod
+ .boolean()
+ .default(tracingSpansLatencyHeatmapCreateBodyQueryOneRootSpansDefault)
+ .describe(
+ 'When true (default), bucket root-span durations only — a distribution of traces. When false, bucket every matching span — used with a span name filter for operation-scoped distributions.'
+ ),
+ })
+ .describe('The latency-heatmap query to execute.'),
+})
+
export const tracingSpansQueryCreateBodyQueryOneFilterGroupDefault = []
export const tracingSpansQueryCreateBodyQueryOneLimitDefault = 100
export const tracingSpansQueryCreateBodyQueryOneOffsetMin = 0
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index 36469cdfeaa6..8438f15c931f 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -207,6 +207,9 @@ tools:
tracing-spans-has-spans-retrieve:
operation: tracing_spans_has_spans_retrieve
enabled: false
+ tracing-spans-latency-heatmap-create:
+ operation: tracing_spans_latency_heatmap_create
+ enabled: false
tracing-spans-symbol-stats-create:
operation: tracing_spans_symbol_stats_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3f5d27ad6044..ab05a47c0f5a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64882,6 +64882,25 @@ export namespace Schemas {
query: _TracingDurationHistogramQueryBody;
}
+ export interface _TracingLatencyHeatmapCell {
+ /** ISO 8601 UTC start of the time bucket. */
+ time: string;
+ /** Lower edge of the 1-2-5 series duration bucket in nanoseconds (1ms, 2ms, 5ms, 10ms, ...). 0 on the sentinel row that enumerates a time bucket with no matching spans. */
+ bucket_ns: number;
+ /** Spans (or traces when rootSpans is true) in this cell. 0 only on sentinel rows. */
+ count: number;
+ }
+
+ export interface _TracingLatencyHeatmapRequest {
+ /** The latency-heatmap query to execute. */
+ query: _TracingDurationHistogramQueryBody;
+ }
+
+ export interface _TracingLatencyHeatmapResponse {
+ /** Sparse heatmap cells ordered by time then duration bucket. Every time bucket in the window appears in at least one row, so the full x axis can be derived from the response. */
+ results: _TracingLatencyHeatmapCell[];
+ }
+
/**
* * `timestamp` - timestamp
* * `duration` - duration