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): badge span rows with the errors their trace hit (#98841)

Jimmy Zhu397d9f447002
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 254945cbf16e..0c16a912581d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6568,6 +6568,26 @@ snapshots:
hash: v1.k794b7964.58421fb9485687230fc55051bb13eeefff6fec4dbc8cc0eeb9a9a9f3f39a30cd.RKEFDA_TPq6C7rBaWvs1_loggCz5bgkCHWNiGQWxX0c
products-tracing-operationstable--with-impact-columns--light:
hash: v1.k794b7964.eac04f11bc22c27252d415d04b4a1aa49fd3b8efcfc52ffee28a7e6b6e318417.A4sjcvRfFZFLstF9ShgxDiEyFTQSKg_n9y-x7DdIZpc
+ products-tracing-spanerrorsbadge--one-error--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.1kPC96NYK5FnS-qAPmFe5Vilt5aDnR_LOwvKi4SCHhw
+ products-tracing-spanerrorsbadge--one-error--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.fdUpUCRt8BNJMhVn-pVXvDtl7VL7OG6HNG1pzM621eU
+ products-tracing-spanerrorsbadge--session-tier--dark:
+ hash: v1.k794b7964.13255a21b0a89044711d43ad7eb7656bfa27780850612e2240ac5134ca655113.oahlSM-Db9HEzwv1RZ-hwmYT3YIGjGvdcpu0uTZIWNc
+ products-tracing-spanerrorsbadge--session-tier--light:
+ hash: v1.k794b7964.cc9c455a795e90f532f860835be59a78303f0aa59d41b94f5af2d50ca5a946bd.ZWyddRTjWYSYmz9XtbBcIK4nSTv8ixQwju_6-4utwQI
+ products-tracing-spanerrorsbadge--span-tier--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.MGVEuCnBxCAT14UwteNd9Rl3BG6A36Mi2YCuNej22BE
+ products-tracing-spanerrorsbadge--span-tier--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.htGoLWOj1PFYZ_cIuyahVh-15Lto4YBpb-h8aqqZNp4
+ products-tracing-spanerrorsbadge--trace-tier--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.uzDepTBFYU-pXEYJVCD0Ya_KaJzjKbvqtp1608gntps
+ products-tracing-spanerrorsbadge--trace-tier--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.358lw8N4eo9oKE_fz5YzCB6liehGpscOXtxfbgqWaus
+ products-tracing-spanerrorsbadge--trace-tier-with-more-in-session--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.FoUJvZ3pT1VvRHqfLTd8ng_hDXpYvjWqiodIwsZhnGw
+ products-tracing-spanerrorsbadge--trace-tier-with-more-in-session--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.I52iOSlgYhkIDdh5N-Zm-Kb0yYD09_Fdkwzq1RvocwQ
products-tracing-virtualizedspanlist--default--dark:
hash: v1.k794b7964.d6cf5ccbc379f67404b237b878878ce7e60512d45869c05c24dfab7784335406.zEh7cw_wZ10BGEuJkOUdjqS8SiWt7386-Cuz4Qc0Les
products-tracing-virtualizedspanlist--default--light:
@@ -6576,6 +6596,10 @@ snapshots:
hash: v1.k794b7964.5590e8e6497de2fefefa74cf07edd5f814a798deb8f7e5f0102a383f5e8ac6c8.ZvuooUS3qT6kDX8yW2_oQ1iDgO1DwVFMAWM517bhCHw
products-tracing-virtualizedspanlist--empty--light:
hash: v1.k794b7964.72ff685c9162da170263d416510a2cc5229c999691288c0b8038143000a40f15.ebvPm2A_7cN8QvjEaroudYEO1lp9qFUooW98MMcDBwY
+ products-tracing-virtualizedspanlist--with-error-badges--dark:
+ hash: v1.k794b7964.42abb3fdc9a580251a24fb411200fd29c62129989c435d24c92b88daf82b3886.bdomWMdvS-XzhaZRXAUC6CdeuNq2sAFSW9pmpYVSD7M
+ products-tracing-virtualizedspanlist--with-error-badges--light:
+ hash: v1.k794b7964.15d4fc501256abd83be7a13b59db0073a1d175aeec62177d327a92024d0186d9.XHqEWOoFuCaN7-Uc2dZ5PlU9VHycCpsiv3pS6Silirw
products-web-analytics-content-autopilot-proposal-card--blocking-validation--dark:
hash: v1.k794b7964.8209374f939a22b6b211c2a21698ca15c4d6e18eda905eafc2c826539fa6a6f3.iZuZv-_mdz_BoFNzarvgUmumBKyNRvbdYMCWKcRQ5Bs
products-web-analytics-content-autopilot-proposal-card--blocking-validation--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d9f5781227b1..a2f06b51db07 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -530,6 +530,7 @@ export const FEATURE_FLAGS = {
TRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracing
TRACING_SAVED_VIEWS: 'tracing-saved-views', // owner: #team-apm — gates saved views (saved filter sets) in tracing
TRACING_SESSION_PERSON_LINKS: 'tracing-session-person-links', // owner: #team-apm — gates span attribute links to session replay and persons, plus the tracing correlation settings
+ TRACING_SPAN_ERROR_BADGES: 'tracing-span-error-badges', // owner: #team-apm, badges span rows whose session hit errors and adds the Errors tab to the trace drawer
TRACING_UI_V2: 'tracing-ui-v2',
TRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analytics
UI_CUSTOMIZATION: 'ui-customization-enabled', // owner: @fercgomes #team-self-driving, gates sidebar/homepage UI customization
diff --git a/products/tracing/backend/error_counts.py b/products/tracing/backend/error_counts.py
new file mode 100644
index 000000000000..019b525f3e1a
--- /dev/null
+++ b/products/tracing/backend/error_counts.py
@@ -0,0 +1,121 @@
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+# One page of spans can carry hundreds of distinct ids. The lookup is one query either way,
+# but the IN list grows with it, so cap how many ids one request can ask about.
+MAX_IDS_PER_LOOKUP = 200
+
+
+def _run(query: ast.SelectQuery | ast.SelectSetQuery, team: "Team", query_type: str) -> dict[str, int]:
+ response = execute_hogql_query(query=query, team=team, query_type=query_type)
+ return {str(key): int(exceptions) for key, exceptions in response.results or []}
+
+
+def _window_placeholders(date_from: datetime, date_to: datetime) -> dict[str, ast.Expr]:
+ return {
+ "date_from": ast.Constant(value=date_from),
+ "date_to": ast.Constant(value=date_to),
+ # Explicit, because HogQL caps a select without a LIMIT at 100 rows, which is below the
+ # ids one request may ask about. A row cut there would read as a clean id.
+ "limit": ast.Constant(value=MAX_IDS_PER_LOOKUP),
+ }
+
+
+def count_trace_exceptions(
+ *, team: "Team", trace_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Exceptions Error Tracking linked to an issue, per trace, inside the window.
+
+ Keys come back lowercased. A trace with no such exceptions is absent from the result rather
+ than present with a zero.
+ """
+ if not trace_ids:
+ return {}
+ query = parse_select(
+ """
+ SELECT lower(properties.$trace_id) AS trace_id, count() AS exceptions
+ FROM events
+ WHERE event = '$exception'
+ AND isNotNull(properties.$exception_issue_id)
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ AND lower(properties.$trace_id) IN {trace_ids}
+ GROUP BY trace_id
+ LIMIT {limit}
+ """,
+ placeholders={
+ # Spans read their ids back as uppercase hex, while the SDKs write them lowercase, so
+ # both sides are lowercased here. Compare the two raw and every count comes back zero.
+ "trace_ids": ast.Constant(value=[trace_id.lower() for trace_id in trace_ids]),
+ **_window_placeholders(date_from, date_to),
+ },
+ )
+ return _run(query, team, "TracingTraceErrorCountsQuery")
+
+
+def count_span_exceptions(
+ *, team: "Team", span_ids: list[str], trace_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Exceptions Error Tracking linked to an issue, per span, inside the window.
+
+ A span id is only unique within its trace, so the traces the spans belong to bound the match
+ as well. Keys come back lowercased.
+ """
+ if not span_ids or not trace_ids:
+ return {}
+ query = parse_select(
+ """
+ SELECT lower(properties.$span_id) AS span_id, count() AS exceptions
+ FROM events
+ WHERE event = '$exception'
+ AND isNotNull(properties.$exception_issue_id)
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ AND lower(properties.$trace_id) IN {trace_ids}
+ AND lower(properties.$span_id) IN {span_ids}
+ GROUP BY span_id
+ LIMIT {limit}
+ """,
+ placeholders={
+ "span_ids": ast.Constant(value=[span_id.lower() for span_id in span_ids]),
+ "trace_ids": ast.Constant(value=[trace_id.lower() for trace_id in trace_ids]),
+ **_window_placeholders(date_from, date_to),
+ },
+ )
+ return _run(query, team, "TracingSpanErrorCountsQuery")
+
+
+def count_session_exceptions(
+ *, team: "Team", session_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Exceptions Error Tracking linked to an issue, per session, inside the window.
+
+ A session with no such exceptions is absent from the result rather than present with a zero.
+ """
+ if not session_ids:
+ return {}
+ query = parse_select(
+ """
+ SELECT properties.$session_id AS session_id, count() AS exceptions
+ FROM events
+ WHERE event = '$exception'
+ AND isNotNull(properties.$exception_issue_id)
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ AND properties.$session_id IN {session_ids}
+ GROUP BY session_id
+ LIMIT {limit}
+ """,
+ placeholders={
+ "session_ids": ast.Constant(value=session_ids),
+ **_window_placeholders(date_from, date_to),
+ },
+ )
+ return _run(query, team, "TracingSessionErrorCountsQuery")
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index eecb6849d71c..af2fb6b4c915 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -16,6 +16,7 @@ Do NOT:
- Return ORM instances or QuerySets
"""
+from datetime import datetime
from typing import TYPE_CHECKING
from posthog.schema import (
@@ -41,6 +42,12 @@ 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.error_counts import (
+ MAX_IDS_PER_LOOKUP as _MAX_IDS_PER_LOOKUP,
+ count_session_exceptions as _count_session_exceptions,
+ count_span_exceptions as _count_span_exceptions,
+ count_trace_exceptions as _count_trace_exceptions,
+)
from products.tracing.backend.impact_query_runner import run_impact_query as _run_impact_query
from products.tracing.backend.latency_heatmap_query_runner import (
run_latency_heatmap_query as _run_latency_heatmap_query,
@@ -56,6 +63,10 @@ if TYPE_CHECKING:
# presentation layer can validate `breakdownKey` without reaching into the query runner.
FACET_COLUMNS = _FACET_COLUMNS
+# Cap on the ids one error-count request may ask about, per id kind. Re-exported so the
+# presentation layer can bound its request serializer without reaching into the lookup module.
+MAX_IDS_PER_LOOKUP = _MAX_IDS_PER_LOOKUP
+
# --- Converters (model -> frozen dataclass) ---
#
@@ -195,3 +206,37 @@ def run_latency_heatmap_query(
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)
+
+
+def count_trace_exceptions(
+ *, team: "Team", trace_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Count the exceptions Error Tracking linked to an issue, per trace, inside the window.
+
+ Keys come back lowercased. A trace with no such exceptions is absent from the result rather
+ than present with a zero.
+ """
+ return _count_trace_exceptions(team=team, trace_ids=trace_ids, date_from=date_from, date_to=date_to)
+
+
+def count_span_exceptions(
+ *, team: "Team", span_ids: list[str], trace_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Count the exceptions Error Tracking linked to an issue, per span, inside the window.
+
+ A span id is only unique within its trace, so the traces the spans belong to bound the match
+ as well. Keys come back lowercased.
+ """
+ return _count_span_exceptions(
+ team=team, span_ids=span_ids, trace_ids=trace_ids, date_from=date_from, date_to=date_to
+ )
+
+
+def count_session_exceptions(
+ *, team: "Team", session_ids: list[str], date_from: datetime, date_to: datetime
+) -> dict[str, int]:
+ """Count the exceptions Error Tracking linked to an issue, per session, inside the window.
+
+ A session with no such exceptions is absent from the result rather than present with a zero.
+ """
+ return _count_session_exceptions(team=team, session_ids=session_ids, date_from=date_from, date_to=date_to)
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index b3660af56721..bd5013fa0684 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -16,11 +16,11 @@ from collections.abc import Callable
from django.db import models
-from drf_spectacular.utils import extend_schema, extend_schema_field
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from pydantic import ValidationError
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import ParseError
+from rest_framework.exceptions import ParseError, PermissionDenied
from rest_framework.request import Request
from rest_framework.response import Response
@@ -38,7 +38,7 @@ from posthog.schema import (
)
from posthog.api.documentation import _FallbackSerializer
-from posthog.api.mixins import PydanticModelMixin
+from posthog.api.mixins import PydanticModelMixin, ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.errors import CHQueryErrorTooManyBytes
@@ -49,7 +49,11 @@ from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS
from ..facade.api import (
FACET_COLUMNS,
+ MAX_IDS_PER_LOOKUP,
annotate_self_time,
+ count_session_exceptions,
+ count_span_exceptions,
+ count_trace_exceptions,
run_attribute_breakdown_query,
run_count_query,
run_duration_histogram_query,
@@ -380,6 +384,83 @@ class _TracingServiceNamesQuerySerializer(serializers.Serializer):
)
+def _error_count_rows(counts: dict[str, int], key: str) -> list[dict[str, object]]:
+ return [{key: value, "exceptions": count} for value, count in counts.items()]
+
+
+class _TracingErrorCountsRequestSerializer(serializers.Serializer):
+ traceIds = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ max_length=MAX_IDS_PER_LOOKUP,
+ help_text=(
+ f"Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` "
+ f"property. Case insensitive. At most {MAX_IDS_PER_LOOKUP} per request."
+ ),
+ )
+ spanIds = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ max_length=MAX_IDS_PER_LOOKUP,
+ help_text=(
+ f"Hex span IDs to count exceptions for, matched against the exception's `$span_id` "
+ f"property. Only counted within the requested traces, so `traceIds` is required "
+ f"alongside. At most {MAX_IDS_PER_LOOKUP} per request."
+ ),
+ )
+ sessionIds = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ max_length=MAX_IDS_PER_LOOKUP,
+ help_text=(
+ f"Session IDs to count exceptions for. The fallback for exceptions that carry no "
+ f"trace ID. At most {MAX_IDS_PER_LOOKUP} per request."
+ ),
+ )
+ dateFrom = serializers.DateTimeField(help_text="Start of the window the exceptions must fall in. ISO 8601.")
+ dateTo = serializers.DateTimeField(help_text="End of the window the exceptions must fall in. ISO 8601.")
+
+ def validate(self, attrs: dict) -> dict:
+ if not any(attrs.get(key) for key in ("traceIds", "spanIds", "sessionIds")):
+ raise serializers.ValidationError("Pass at least one of traceIds, spanIds or sessionIds.")
+ if attrs.get("spanIds") and not attrs.get("traceIds"):
+ raise serializers.ValidationError("spanIds needs traceIds, because a span ID is only unique in its trace.")
+ return attrs
+
+
+class _TracingErrorCountSerializer(serializers.Serializer):
+ exceptions = serializers.IntegerField(
+ help_text="Exception events in the window that error tracking linked to an issue."
+ )
+
+
+class _TracingTraceErrorCountSerializer(_TracingErrorCountSerializer):
+ trace_id = serializers.CharField(help_text="The trace the exceptions belong to, lowercase hex.")
+
+
+class _TracingSpanErrorCountSerializer(_TracingErrorCountSerializer):
+ span_id = serializers.CharField(help_text="The span the exceptions belong to, lowercase hex.")
+
+
+class _TracingSessionErrorCountSerializer(_TracingErrorCountSerializer):
+ session_id = serializers.CharField(help_text="The session the exceptions belong to.")
+
+
+class _TracingErrorCountsResponseSerializer(serializers.Serializer):
+ traceResults = _TracingTraceErrorCountSerializer(
+ many=True,
+ help_text="One entry per requested trace that had exceptions. Traces with none are omitted.",
+ )
+ spanResults = _TracingSpanErrorCountSerializer(
+ many=True,
+ help_text="One entry per requested span that had exceptions. Spans with none are omitted.",
+ )
+ sessionResults = _TracingSessionErrorCountSerializer(
+ many=True,
+ help_text="One entry per requested session that had exceptions. Sessions with none are omitted.",
+ )
+
+
class _TracingAttributesQuerySerializer(serializers.Serializer):
search = serializers.CharField(required=False, help_text="Search filter for attribute names.")
search_values = serializers.BooleanField(
@@ -932,6 +1013,51 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return None
return self.get_model(compare_data, CompareFilter)
+ @validated_request(
+ _TracingErrorCountsRequestSerializer,
+ responses={200: OpenApiResponse(response=_TracingErrorCountsResponseSerializer)},
+ )
+ # Both scopes: the response is Error Tracking data, so a token scoped to tracing alone must
+ # not reach it. Scopes gate the token; the access-control check below gates the user.
+ @action(
+ detail=False,
+ methods=["POST"],
+ url_path="error-counts",
+ required_scopes=["tracing:read", "error_tracking:read"],
+ )
+ def error_counts(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ """Count the exceptions the spans in view hit, by trace, by span and by session, for the
+ span list's error badges.
+
+ A caller asks about the id kinds it has, and each kind is a separate lookup.
+ """
+ if not self.user_access_control.check_access_level_for_resource("error_tracking", "viewer"):
+ raise PermissionDenied("You do not have access to error tracking.")
+
+ tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
+ data = request.validated_data
+ trace_ids = data.get("traceIds") or []
+ span_ids = data.get("spanIds") or []
+ session_ids = data.get("sessionIds") or []
+ window = {"date_from": data["dateFrom"], "date_to": data["dateTo"]}
+
+ # Through the response serializer, not a bare dict: `api-response-must-match-schema` keeps
+ # the wire shape tied to the declaration the generated types are built from.
+ response = _TracingErrorCountsResponseSerializer(
+ instance={
+ "traceResults": _error_count_rows(
+ count_trace_exceptions(team=self.team, trace_ids=trace_ids, **window), "trace_id"
+ ),
+ "spanResults": _error_count_rows(
+ count_span_exceptions(team=self.team, span_ids=span_ids, trace_ids=trace_ids, **window), "span_id"
+ ),
+ "sessionResults": _error_count_rows(
+ count_session_exceptions(team=self.team, session_ids=session_ids, **window), "session_id"
+ ),
+ }
+ )
+ return Response(response.data, status=status.HTTP_200_OK)
+
@extend_schema(parameters=[_TracingServiceNamesQuerySerializer])
@action(detail=False, methods=["GET"], url_path="service-names", required_scopes=["tracing:read"])
def service_names(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/tracing/backend/tests/test_error_counts.py b/products/tracing/backend/tests/test_error_counts.py
new file mode 100644
index 000000000000..dfaf4909de39
--- /dev/null
+++ b/products/tracing/backend/tests/test_error_counts.py
@@ -0,0 +1,174 @@
+import json
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+
+from django.http import HttpResponse
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, User
+
+from products.access_control.backend.models.access_control import AccessControl
+
+DATE_FROM = "2026-06-02T06:00:00Z"
+DATE_TO = "2026-06-02T10:00:00Z"
+
+# The form an SDK writes: lowercase hex, 32 characters for a trace and 16 for a span.
+TRACE_A = "4bf92f3577b34da6a3ce929d0e0e4736"
+TRACE_B = "8a3c60f7d188f8fa79d48a391a778fa6"
+SPAN_A = "00f067aa0ba902b7"
+SPAN_B = "b9c7c989f97918e1"
+
+
+class TestErrorCounts(ClickhouseTestMixin, APIBaseTest):
+ def _post(self, **body: Any) -> HttpResponse:
+ return self.client.post(
+ f"/api/projects/{self.team.id}/tracing/spans/error-counts/",
+ {"dateFrom": DATE_FROM, "dateTo": DATE_TO, **body},
+ format="json",
+ )
+
+ def _create_exception(
+ self,
+ *,
+ timestamp: str = "2026-06-02T08:00:00Z",
+ session_id: str | None = None,
+ trace_id: str | None = None,
+ span_id: str | None = None,
+ linked_to_issue: bool = True,
+ ) -> None:
+ properties: dict[str, str] = {}
+ if session_id is not None:
+ properties["$session_id"] = session_id
+ if trace_id is not None:
+ properties["$trace_id"] = trace_id
+ if span_id is not None:
+ properties["$span_id"] = span_id
+ if linked_to_issue:
+ properties["$exception_issue_id"] = str(uuid4())
+ _create_event(
+ distinct_id="user-1", event="$exception", team=self.team, properties=properties, timestamp=timestamp
+ )
+
+ def test_counts_issue_linked_exceptions_per_requested_session_in_the_window(self) -> None:
+ self._create_exception(session_id="session-a", timestamp="2026-06-02T08:00:00Z")
+ self._create_exception(session_id="session-a", timestamp="2026-06-02T09:00:00Z")
+ self._create_exception(session_id="session-a", timestamp="2026-06-02T08:30:00Z", linked_to_issue=False)
+ self._create_exception(session_id="session-a", timestamp="2026-06-02T11:00:00Z")
+ self._create_exception(session_id="session-b", timestamp="2026-06-02T08:00:00Z")
+ self._create_exception(session_id="session-not-asked", timestamp="2026-06-02T08:00:00Z")
+ flush_persons_and_events()
+
+ response = self._post(sessionIds=["session-a", "session-b", "session-quiet"])
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ counts = {row["session_id"]: row["exceptions"] for row in json.loads(response.content)["sessionResults"]}
+ assert counts == {"session-a": 2, "session-b": 1}
+
+ def test_counts_issue_linked_exceptions_per_requested_trace_in_the_window(self) -> None:
+ self._create_exception(trace_id=TRACE_A, timestamp="2026-06-02T08:00:00Z")
+ self._create_exception(trace_id=TRACE_A, timestamp="2026-06-02T09:00:00Z")
+ self._create_exception(trace_id=TRACE_A, timestamp="2026-06-02T08:30:00Z", linked_to_issue=False)
+ self._create_exception(trace_id=TRACE_A, timestamp="2026-06-02T11:00:00Z")
+ self._create_exception(trace_id=TRACE_B, timestamp="2026-06-02T08:00:00Z")
+ flush_persons_and_events()
+
+ response = self._post(traceIds=[TRACE_A, TRACE_B])
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ counts = {row["trace_id"]: row["exceptions"] for row in json.loads(response.content)["traceResults"]}
+ assert counts == {TRACE_A: 2, TRACE_B: 1}
+
+ # The span rows the caller holds carry uppercase hex, because the query runner reads the ids
+ # back through ClickHouse `hex()`, while an SDK writes them lowercase. Match the two raw and
+ # every count comes back zero, which reads as a clean trace rather than as a bug. Both sides
+ # vary, so neither half of the normalization can be dropped without a failure here.
+ @parameterized.expand(
+ [
+ ("stored lower, asked lower", str.lower, str.lower),
+ ("stored lower, asked upper", str.lower, str.upper),
+ ("stored upper, asked lower", str.upper, str.lower),
+ ("stored upper, asked upper", str.upper, str.upper),
+ ]
+ )
+ def test_matches_ids_whatever_case_either_side_uses(self, _name: str, stored: Any, asked: Any) -> None:
+ self._create_exception(trace_id=stored(TRACE_A), span_id=stored(SPAN_A))
+ flush_persons_and_events()
+
+ response = self._post(traceIds=[asked(TRACE_A)], spanIds=[asked(SPAN_A)])
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = json.loads(response.content)
+ assert {row["trace_id"]: row["exceptions"] for row in body["traceResults"]} == {TRACE_A: 1}
+ assert {row["span_id"]: row["exceptions"] for row in body["spanResults"]} == {SPAN_A: 1}
+
+ # A span id is only unique inside its trace, so a span count that ignores the trace would fold
+ # an unrelated trace's exceptions into this one's row.
+ def test_counts_a_span_only_within_the_requested_traces(self) -> None:
+ self._create_exception(trace_id=TRACE_A, span_id=SPAN_A)
+ self._create_exception(trace_id=TRACE_B, span_id=SPAN_A)
+ flush_persons_and_events()
+
+ response = self._post(traceIds=[TRACE_A], spanIds=[SPAN_A])
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ counts = {row["span_id"]: row["exceptions"] for row in json.loads(response.content)["spanResults"]}
+ assert counts == {SPAN_A: 1}
+
+ def test_answers_every_requested_session_past_the_default_row_limit(self) -> None:
+ session_ids = [f"session-{i}" for i in range(150)]
+ for session_id in session_ids:
+ self._create_exception(session_id=session_id)
+ flush_persons_and_events()
+
+ response = self._post(sessionIds=session_ids)
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert len(json.loads(response.content)["sessionResults"]) == 150
+
+ @parameterized.expand([("traceIds",), ("spanIds",), ("sessionIds",)])
+ def test_rejects_more_ids_than_one_lookup_allows(self, field: str) -> None:
+ body: dict[str, Any] = {field: [f"id-{i}" for i in range(201)]}
+ if field == "spanIds":
+ body["traceIds"] = [TRACE_A]
+
+ response = self._post(**body)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert json.loads(response.content)["attr"] == field
+
+ @parameterized.expand(
+ [
+ ("no ids at all", {}),
+ ("spans without their traces", {"spanIds": [SPAN_B]}),
+ ]
+ )
+ def test_rejects_a_request_it_cannot_answer(self, _name: str, body: dict[str, Any]) -> None:
+ response = self._post(**body)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+
+ @parameterized.expand([("viewer", status.HTTP_200_OK), ("none", status.HTTP_403_FORBIDDEN)])
+ def test_requires_error_tracking_viewer_access(self, access_level: str, expected_status: int) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="error_tracking",
+ resource_id=None,
+ access_level=access_level,
+ organization_member=membership,
+ )
+ self.client.force_login(user)
+
+ response = self._post(sessionIds=["session-a"])
+
+ assert response.status_code == expected_status, response.content
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsx
index f3131814f842..fc162d93647f 100644
--- a/products/tracing/frontend/TracingScene.tsx
+++ b/products/tracing/frontend/TracingScene.tsx
@@ -1,6 +1,7 @@
import { BindLogic, useActions, useValues } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'
+import { useCallback, useMemo } from 'react'
import { LemonBanner, LemonButton, LemonModal, Link } from '@posthog/lemon-ui'
@@ -23,9 +24,11 @@ import { TraceDrawer } from './components/TraceDrawer/TraceDrawer'
import { VirtualizedSpanList } from './components/VirtualizedSpanList/VirtualizedSpanList'
import { TRACING_DISPLAY_TIMEZONE } from './dateFormats'
import { tracingEmptyState } from './emptyState/tracingEmptyState'
+import type { ErrorScope } from './errorCorrelation'
import { OperationsTable } from './OperationsTable'
import { TraceCompareFlame } from './TraceCompareFlame'
import { TraceCompareTable } from './TraceCompareTable'
+import { TRACING_DOCS_URL } from './traceLinks'
import { TracingAgentIntegration } from './TracingAgentIntegration'
import { tracingConfigLogic } from './tracingConfigLogic'
import { tracingDataLogic } from './tracingDataLogic'
@@ -35,10 +38,9 @@ import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLo
import { tracingSceneLogic } from './tracingSceneLogic'
import { TracingSparkline } from './TracingSparkline'
import { tracingViewerLogic } from './tracingViewerLogic'
-import type { Span } from './types'
+import type { Span, SpanInspectorTab } from './types'
const TRACING_FEEDBACK_SURVEY_ID = '019e6a26-4943-0000-24a0-dc46310f6b7c'
-const TRACING_DOCS_URL = 'https://posthog.com/docs/tracing'
export const scene: SceneExport = {
component: TracingScene,
@@ -86,6 +88,11 @@ function TracingSceneContents(): JSX.Element {
sparklineLoading,
openTraceSpans,
traceIdentity,
+ traceSessionId,
+ sessionErrorBadgesEnabled,
+ errorBadgeByRow,
+ inspectorTab,
+ errorsScope,
isLoadingFullTrace,
canLoadMoreTraceSpans,
traceSpansLoadingMore,
@@ -121,6 +128,7 @@ function TracingSceneContents(): JSX.Element {
fetchNextPage,
loadMoreTraceSpans,
setVisibleRowRange,
+ selectInspectorTab,
setSort,
setChartType,
applyHeatmapBrush,
@@ -137,6 +145,34 @@ function TracingSceneContents(): JSX.Element {
const { sparklineWindowMs, utcDateRange } = useValues(tracingFiltersLogic)
const operationsWindowMs = sparklineWindowMs.endMs - sparklineWindowMs.startMs
+ // react-window rebuilds its row memo from the shallow values of rowProps, so one unstable
+ // value there re-renders every visible row. This handler and `spanErrors` below are both
+ // passed that way, so both hold their identity.
+ const onRowClick = useCallback(
+ (span: Span, tab?: SpanInspectorTab, errorsScope?: ErrorScope): void => {
+ // Clicking a row leaves the scrollable <main tabIndex="0"> as the active element;
+ // react-modal then scrolls it back into view when restoring focus on close. Blur so
+ // the restore target is <body>, which doesn't scroll.
+ ;(document.activeElement as HTMLElement | null)?.blur?.()
+ // Anchor the waterfall on the clicked span. In Spans mode this is often a child span,
+ // so without spanId the drawer would open unfocused at the root.
+ openTrace(span.trace_id, { spanId: span.span_id, ts: span.timestamp, tab, errorsScope })
+ },
+ [openTrace]
+ )
+
+ // Absent while the flag is off, which is how the list decides whether to keep a badge column.
+ const spanErrors = useMemo(
+ () =>
+ sessionErrorBadgesEnabled
+ ? {
+ badges: errorBadgeByRow,
+ onShow: (span: Span, scope: ErrorScope) => onRowClick(span, 'errors', scope),
+ }
+ : undefined,
+ [sessionErrorBadgesEnabled, errorBadgeByRow, onRowClick]
+ )
+
const onDocsLinkClick = (): void => {
addProductIntent({
product_type: ProductKey.TRACING,
@@ -262,6 +298,7 @@ function TracingSceneContents(): JSX.Element {
hasMoreToLoad={hasMoreToLoad}
onLoadMore={fetchNextPage}
onVisibleRowRangeChange={setVisibleRowRange}
+ spanErrors={spanErrors}
orderBy={filters.orderBy}
orderDirection={filters.orderDirection}
onSort={(column) =>
@@ -279,15 +316,7 @@ function TracingSceneContents(): JSX.Element {
</Link>
</div>
}
- onRowClick={(span: Span) => {
- // Clicking a row leaves the scrollable <main tabIndex="0"> as the active
- // element; react-modal then scrolls it back into view when restoring focus
- // on close. Blur so the restore target is <body>, which doesn't scroll.
- ;(document.activeElement as HTMLElement | null)?.blur?.()
- // Anchor the waterfall on the clicked span — in Spans mode this is often a
- // child span, so without spanId the drawer would open unfocused at the root.
- openTrace(span.trace_id, { spanId: span.span_id, ts: span.timestamp })
- }}
+ onRowClick={onRowClick}
/>
)}
</div>
@@ -299,6 +328,11 @@ function TracingSceneContents(): JSX.Element {
ts={selectedTraceTs}
spans={openTraceSpans}
identity={traceIdentity}
+ sessionId={traceSessionId}
+ showErrorsTab={sessionErrorBadgesEnabled}
+ inspectorTab={inspectorTab}
+ errorsScope={errorsScope}
+ onSelectInspectorTab={selectInspectorTab}
loading={isLoadingFullTrace}
hasMoreSpans={canLoadMoreTraceSpans}
loadingMoreSpans={traceSpansLoadingMore}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
index cbc64c374057..d404f6e6aebd 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -1,5 +1,5 @@
import { useValues } from 'kea'
-import { useMemo, useRef, useState } from 'react'
+import { useMemo, useRef } from 'react'
import { LemonButton, LemonTabs, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'
@@ -16,20 +16,20 @@ import { cn } from 'lib/utils/css-classes'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
+import type { ErrorScope } from '../../errorCorrelation'
import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'
import { getQueryText } from '../../spanSummary'
import type { TraceIdentity } from '../../traceIdentity'
import { absoluteTraceUrl } from '../../traceLinks'
import { buildServiceColorMap, formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'
-import type { Span } from '../../types'
+import type { Span, SpanInspectorTab } from '../../types'
import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'
import { SpanLogsTab } from './SpanLogsTab'
import { SpanMetricsTab } from './SpanMetricsTab'
import { SpanSummaryHeader } from './SpanSummaryHeader'
+import { TraceErrorsTab } from './TraceErrorsTab'
import { TraceIdentityChips } from './TraceIdentityChips'
-type InspectorTab = 'attributes' | 'query' | 'logs' | 'metrics' | 'raw'
-
// Below this the inspector's content (the attribute KVP tables) stops being readable; clamp so a
// drag can't crush it. The max is a flex `max-w` so a too-wide drag can't starve the waterfall.
const MIN_INSPECTOR_WIDTH = 320
@@ -42,6 +42,15 @@ export interface TraceDrawerProps {
spans: Span[]
/** The person and session the trace belongs to, resolved by tracingViewerLogic. */
identity: TraceIdentity
+ /** The trace's session for the Errors tab, or null when its spans resolve to no one session. */
+ sessionId: string | null
+ /** Show the Errors tab, which lists the issues connected to the trace. */
+ showErrorsTab: boolean
+ /** Which inspector tab is open. Held in tracingViewerLogic so a caller can open one directly. */
+ inspectorTab: SpanInspectorTab
+ /** The scope the Errors tab opens on, when the caller named one. */
+ errorsScope: ErrorScope | null
+ onSelectInspectorTab: (tab: SpanInspectorTab) => void
loading: boolean
/** The open trace has more spans than the loaded pages — drives the waterfall's infinite scroll. */
hasMoreSpans?: boolean
@@ -63,6 +72,11 @@ export function TraceDrawer({
ts,
spans,
identity,
+ sessionId,
+ showErrorsTab,
+ inspectorTab,
+ errorsScope,
+ onSelectInspectorTab,
loading,
hasMoreSpans = false,
loadingMoreSpans = false,
@@ -83,7 +97,6 @@ export function TraceDrawer({
}
const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))
const { featureFlags } = useValues(featureFlagLogic)
- const [inspectorTab, setInspectorTab] = useState<InspectorTab>('attributes')
// Metrics correlate to a trace via exemplars, so the tab only exists where the metrics
// product does: its own flag, plus the metrics feature and view access.
@@ -111,12 +124,14 @@ export function TraceDrawer({
// Only DB spans carry a query; the Query tab appears only when one is present.
const queryText = inspectedSpan ? getQueryText(inspectedSpan) : null
- // The Query and Metrics tabs are conditional, so if the active tab disappears (a span without
- // a query, or the metrics gates turning off), fall back to Attributes — otherwise activeKey
- // would point at a tab LemonTabs has dropped and the inspector body would render blank.
- // (Preference is preserved: a DB span re-shows Query.)
- const activeInspectorTab: InspectorTab =
- (inspectorTab === 'query' && !queryText) || (inspectorTab === 'metrics' && !showMetricsTab)
+ // The Query, Errors and Metrics tabs are conditional, so if the active tab disappears (a span
+ // without a query, or one of the gates turning off), fall back to Attributes. Otherwise
+ // activeKey would point at a tab LemonTabs has dropped and the inspector body would render
+ // blank. Preference is preserved: a DB span re-shows Query.
+ const activeInspectorTab: SpanInspectorTab =
+ (inspectorTab === 'query' && !queryText) ||
+ (inspectorTab === 'metrics' && !showMetricsTab) ||
+ (inspectorTab === 'errors' && !showErrorsTab)
? 'attributes'
: inspectorTab
@@ -181,7 +196,7 @@ export function TraceDrawer({
<SpanSummaryHeader span={inspectedSpan} serviceColorMap={serviceColorMap} />
<LemonTabs
activeKey={activeInspectorTab}
- onChange={setInspectorTab}
+ onChange={onSelectInspectorTab}
data-attr="tracing-inspector-tabs"
tabs={[
{
@@ -216,6 +231,26 @@ export function TraceDrawer({
// it) so we don't churn its logics or lose scroll.
content: <SpanLogsTab key={inspectedSpan.trace_id} span={inspectedSpan} />,
},
+ // Conditional on its own flag. The tab is session-scoped, so it
+ // stays available on a trace that resolved no session and
+ // explains there what is missing.
+ showErrorsTab
+ ? {
+ key: 'errors',
+ label: 'Errors',
+ content: (
+ <TraceErrorsTab
+ key={inspectedSpan.span_id}
+ traceId={inspectedSpan.trace_id}
+ spanId={inspectedSpan.span_id}
+ timestamp={rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts}
+ sessionId={sessionId}
+ initialScope={errorsScope}
+ resolving={loading}
+ />
+ ),
+ }
+ : null,
// Conditional: needs the metrics product (flag + access) and its own flag.
showMetricsTab
? {
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceErrorsTab.tsx b/products/tracing/frontend/components/TraceDrawer/TraceErrorsTab.tsx
new file mode 100644
index 000000000000..a3466720b68d
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceErrorsTab.tsx
@@ -0,0 +1,174 @@
+import { BindLogic, useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSegmentedButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
+import { pluralize } from 'lib/utils/strings'
+
+import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'
+
+import { ErrorTrackingIssueCard } from 'products/error_tracking/frontend/ErrorTrackingIssueCard'
+
+import { SESSION_ERRORS_WINDOW_HOURS } from '../../errorCorrelation'
+import { TRACING_DOCS_URL } from '../../traceLinks'
+import { TraceErrorsLogicProps, TraceErrorsScope, traceErrorsLogic } from './traceErrorsLogic'
+
+// Every string a scope needs, so adding one is a single entry and the Record keeps it exhaustive.
+const SCOPES: Record<TraceErrorsScope, { label: string; where: string; emptyTitle: string; emptyBody: string }> = {
+ span: {
+ label: 'This span',
+ where: 'in this span',
+ emptyTitle: 'No errors in this span',
+ emptyBody: 'No exceptions reported this span as the place they were thrown.',
+ },
+ trace: {
+ label: 'This trace',
+ where: 'in this trace',
+ emptyTitle: 'No errors in this trace',
+ emptyBody: 'No exceptions reported this trace as the request they happened in.',
+ },
+ session: {
+ label: 'This session',
+ where: 'in this session',
+ emptyTitle: 'No errors in this session',
+ emptyBody: `No exceptions were found in this session within ${SESSION_ERRORS_WINDOW_HOURS} hours of this trace.`,
+ },
+}
+
+export interface TraceErrorsTabProps {
+ traceId: string
+ /** The inspected span, which the span scope matches on. */
+ spanId: string | null
+ /** Trace start, which anchors the window the exceptions must fall in. */
+ timestamp: string | null
+ /** The trace's session, or null when the spans resolve to no single session. */
+ sessionId: string | null
+ /** The scope to open on, when the caller named one. A badge names the tier it counted. */
+ initialScope: TraceErrorsScope | null
+ /** The spans the session is resolved from are still arriving, so a null session is not yet an answer. */
+ resolving: boolean
+}
+
+export function TraceErrorsTab({
+ traceId,
+ spanId,
+ timestamp,
+ sessionId,
+ initialScope,
+ resolving,
+}: TraceErrorsTabProps): JSX.Element {
+ // Only the session scope waits. The trace and span scopes read ids the clicked row already
+ // carries, so holding the whole tab for a session resolve would delay the precise answer for
+ // the fuzzy one.
+ if (resolving && !traceId) {
+ return <LoadingState />
+ }
+
+ const logicProps: TraceErrorsLogicProps = { traceId, spanId, timestamp, sessionId, initialScope }
+
+ return (
+ <BindLogic logic={traceErrorsLogic} props={logicProps}>
+ <TraceErrorsTabContent />
+ </BindLogic>
+ )
+}
+
+function TraceErrorsTabContent(): JSX.Element {
+ const { issues, issuesLoading, issuesFailed, availableScopes, effectiveScope } = useValues(traceErrorsLogic)
+ const { loadIssues, setScope } = useActions(traceErrorsLogic)
+
+ if (!effectiveScope) {
+ return (
+ <div className="flex justify-center w-full py-8">
+ <EmptyMessage
+ title="No trace or session to match errors on"
+ description="This span carries no trace ID, and the spans carry no session ID. Add a session ID attribute to your spans to see errors from the same session."
+ buttonText="Learn more"
+ buttonTo={TRACING_DOCS_URL}
+ size="small"
+ />
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ {availableScopes.length > 1 && (
+ <div className="flex">
+ <LemonSegmentedButton
+ size="small"
+ value={effectiveScope}
+ onChange={(scope) => setScope(scope as TraceErrorsScope)}
+ options={availableScopes.map((scope) => ({
+ value: scope,
+ label: SCOPES[scope].label,
+ 'data-attr': `tracing-trace-errors-scope-${scope}`,
+ }))}
+ />
+ </div>
+ )}
+ <TraceErrorsList
+ issues={issues}
+ loading={issuesLoading}
+ failed={issuesFailed}
+ scope={effectiveScope}
+ onRetry={loadIssues}
+ />
+ </div>
+ )
+}
+
+function TraceErrorsList({
+ issues,
+ loading,
+ failed,
+ scope,
+ onRetry,
+}: {
+ issues: MaxErrorTrackingIssuePreview[]
+ loading: boolean
+ failed: boolean
+ scope: TraceErrorsScope
+ onRetry: () => void
+}): JSX.Element {
+ if (loading) {
+ return <LoadingState />
+ }
+
+ if (failed) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: onRetry }}>
+ Could not load the errors for this trace.
+ </LemonBanner>
+ )
+ }
+
+ if (issues.length === 0) {
+ return (
+ <div className="flex justify-center w-full py-8">
+ <EmptyMessage title={SCOPES[scope].emptyTitle} description={SCOPES[scope].emptyBody} size="small" />
+ </div>
+ )
+ }
+
+ const totalOccurrences = issues.reduce((sum, issue) => sum + issue.occurrences, 0)
+ return (
+ <div className="flex flex-col">
+ <p className="text-muted text-sm mb-2">
+ {pluralize(issues.length, 'issue')} with {pluralize(totalOccurrences, 'occurrence')}{' '}
+ {SCOPES[scope].where}
+ </p>
+ {issues.map((issue) => (
+ <ErrorTrackingIssueCard key={issue.id} issue={issue} showUserCount={false} />
+ ))}
+ </div>
+ )
+}
+
+function LoadingState(): JSX.Element {
+ return (
+ <div className="flex flex-col gap-3">
+ <LemonSkeleton className="h-16 w-full" repeat={3} />
+ </div>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.test.ts b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.test.ts
new file mode 100644
index 000000000000..c96e7d503cd9
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.test.ts
@@ -0,0 +1,128 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { initKeaTests } from '~/test/init'
+import { PropertyFilterType } from '~/types'
+
+import { TraceErrorsLogicProps, traceErrorsLogic } from './traceErrorsLogic'
+
+const TRACE_ID = '4BF92F3577B34DA6A3CE929D0E0E4736'
+const SPAN_ID = '00F067AA0BA902B7'
+const ALL_IDS: TraceErrorsLogicProps = {
+ traceId: TRACE_ID,
+ spanId: SPAN_ID,
+ timestamp: '2026-06-02T08:00:00Z',
+ sessionId: 'session-a',
+ initialScope: null,
+}
+
+describe('traceErrorsLogic', () => {
+ let logic: ReturnType<typeof traceErrorsLogic.build>
+ let querySpy: jest.SpyInstance
+
+ const mount = async (props: Partial<TraceErrorsLogicProps> = {}): Promise<void> => {
+ logic = traceErrorsLogic({ ...ALL_IDS, ...props })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ const lastQuery = (): any => querySpy.mock.calls[querySpy.mock.calls.length - 1][0]
+
+ const filterKeys = (): { key: string; value: unknown }[] =>
+ lastQuery().filterGroup.values[0].values.map((filter: any) => ({ key: filter.key, value: filter.value }))
+
+ beforeEach(() => {
+ initKeaTests()
+ querySpy = jest.spyOn(api, 'query').mockResolvedValue({ results: [] } as any)
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ querySpy.mockRestore()
+ })
+
+ // Getting the order wrong downgrades every trace that carries exact ids back to the session
+ // guess, which is the behavior this surface replaced.
+ it.each([
+ ['every id', {}, ['span', 'trace', 'session']],
+ ['no span id', { spanId: null }, ['trace', 'session']],
+ ['no session', { sessionId: null }, ['span', 'trace']],
+ ['a session only', { traceId: '', spanId: null }, ['session']],
+ // An all-zero id is OpenTelemetry's "no id" sentinel, so it offers no exact scope.
+ ['all-zero ids', { traceId: '0'.repeat(32), spanId: '0'.repeat(16) }, ['session']],
+ ['nothing to match on', { traceId: '', spanId: null, sessionId: null }, []],
+ ])('offers the scopes for a trace with %s, most precise first', async (_name, props, expected) => {
+ await mount(props)
+
+ expect(logic.values.availableScopes).toEqual(expected)
+ expect(logic.values.effectiveScope).toBe(expected[0] ?? null)
+ })
+
+ // A trace-tier badge exists only when the span scope found nothing, so defaulting to the most
+ // precise scope landed the click on the one list it had already ruled out.
+ it.each([
+ ['trace', 'trace'],
+ ['session', 'session'],
+ ])('opens on the %s scope the caller named, not the most precise one', async (_name, scope) => {
+ await mount({ initialScope: scope as any })
+
+ expect(logic.values.effectiveScope).toBe(scope)
+ })
+
+ // A scope the trace cannot offer must not strand the tab on an empty selection.
+ it('ignores a named scope the trace does not offer', async () => {
+ await mount({ initialScope: 'session', sessionId: null })
+
+ expect(logic.values.effectiveScope).toBe('span')
+ })
+
+ // The control is the user speaking; the caller's scope was only a starting point.
+ it('lets the scope control override the scope the caller named', async () => {
+ await mount({ initialScope: 'trace' })
+ logic.actions.setScope('session')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.effectiveScope).toBe('session')
+ })
+
+ // The filter decides which issues the tab lists, so a scope that sends the wrong property
+ // lists another request's errors under this one.
+ it.each([
+ [
+ 'span',
+ [
+ { key: '$trace_id', value: TRACE_ID.toLowerCase() },
+ { key: '$span_id', value: SPAN_ID.toLowerCase() },
+ ],
+ ],
+ ['trace', [{ key: '$trace_id', value: TRACE_ID.toLowerCase() }]],
+ ['session', [{ key: '$session_id', value: 'session-a' }]],
+ ])('matches on the %s scope', async (scope, expected) => {
+ await mount()
+ logic.actions.setScope(scope as any)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(filterKeys()).toEqual(expected)
+ expect(lastQuery().filterGroup.values[0].values[0].type).toBe(PropertyFilterType.Event)
+ })
+
+ // An exception carrying a trace id happened inside that trace, so the exact scopes have no
+ // reason to scan the six hours the session guess needs.
+ it.each([
+ ['trace', 'trace', '2026-06-02T07:00:00.000Z', '2026-06-02T09:00:00.000Z'],
+ ['session', 'session', '2026-06-02T02:00:00.000Z', '2026-06-02T14:00:00.000Z'],
+ ])('asks the %s scope over its own window', async (_name, scope, date_from, date_to) => {
+ await mount()
+ logic.actions.setScope(scope as any)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(lastQuery().dateRange).toEqual({ date_from, date_to })
+ })
+
+ it('asks nothing when the trace offers no scope', async () => {
+ await mount({ traceId: '', spanId: null, sessionId: null })
+
+ expect(querySpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts
new file mode 100644
index 000000000000..b2823d362b9c
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts
@@ -0,0 +1,250 @@
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+
+import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'
+import { ErrorTrackingQuery, NodeKind } from '~/queries/schema/schema-general'
+import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { type ErrorScope, sessionErrorsWindow, traceErrorsWindow, usableId } from '../../errorCorrelation'
+
+// The issues limit is the same one the Logs product's Related errors surface uses. A trace with
+// more issues than this is already past the point where a list helps.
+const MAX_ISSUES = 100
+
+/** Which ids the listed issues are matched on, in falling order of confidence. */
+export type TraceErrorsScope = ErrorScope
+
+export interface TraceErrorsLogicProps {
+ traceId: string
+ /** The inspected span, which the span scope matches on. Null when no span is anchored. */
+ spanId: string | null
+ /**
+ * Trace start, which anchors the window the exceptions must fall in. The trace anchors it
+ * rather than the inspected span, so walking the waterfall does not re-ask a question whose
+ * answer only moves by the trace's own duration.
+ */
+ timestamp: string | null
+ /** The trace's session, or null when the spans resolve to no single session. */
+ sessionId: string | null
+ /** The scope to open on, when the caller named one. Null falls back to the most precise. */
+ initialScope: TraceErrorsScope | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceErrorsLogicValues {
+ availableScopes: TraceErrorsScope[]
+ effectiveScope: TraceErrorsScope | null
+ issues: MaxErrorTrackingIssuePreview[]
+ issuesFailed: boolean
+ issuesLoading: boolean
+ selectedScope: TraceErrorsScope | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceErrorsLogicActions {
+ loadIssues: () => any
+ loadIssuesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadIssuesSuccess: (
+ issues: MaxErrorTrackingIssuePreview[],
+ payload?: any
+ ) => {
+ issues: MaxErrorTrackingIssuePreview[]
+ payload?: any
+ }
+ setScope: (scope: TraceErrorsScope) => {
+ scope: ErrorScope
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceErrorsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ availableScopes: (arg: TraceErrorsLogicProps) => TraceErrorsScope[]
+ effectiveScope: (
+ availableScopes: ErrorScope[],
+ selectedScope: ErrorScope | null,
+ arg: ErrorScope | null
+ ) => TraceErrorsScope | null
+ }
+}
+
+export type traceErrorsLogicType = MakeLogicType<
+ traceErrorsLogicValues,
+ traceErrorsLogicActions,
+ TraceErrorsLogicProps,
+ traceErrorsLogicMeta
+>
+
+function eventFilter(key: string, value: string): AnyPropertyFilter {
+ return {
+ type: PropertyFilterType.Event,
+ key,
+ value,
+ operator: PropertyOperator.Exact,
+ } as AnyPropertyFilter
+}
+
+// An SDK that propagated the trace context stamps the exception with `$trace_id` and `$span_id`,
+// which names the span that threw. Without those the only join left is the session plus a time
+// window, and those issues co-occurred with the trace rather than being caused by it.
+//
+// This runs the query node rather than the generated issues-list client, because that endpoint
+// defaults to active issues and to excluding test accounts. The badge counts every exception it
+// matched, so the tab has to answer over the same set or the two disagree.
+export const traceErrorsLogic = kea<traceErrorsLogicType>([
+ props({} as TraceErrorsLogicProps),
+ // The session is in the key, not just the trace: a trace that touches two sessions answers a
+ // different question for each, and walking to a span of the other session has to re-ask. The
+ // timestamp is in it too, because the root span, which sets it, can arrive on a later page.
+ key((props) => `${props.traceId}:${props.spanId ?? ''}:${props.sessionId ?? ''}:${props.timestamp ?? ''}`),
+ path((key) => ['products', 'tracing', 'frontend', 'components', 'TraceDrawer', 'traceErrorsLogic', key]),
+
+ actions({
+ setScope: (scope: TraceErrorsScope) => ({ scope }),
+ }),
+
+ loaders(({ props, values }) => ({
+ issues: {
+ __default: [] as MaxErrorTrackingIssuePreview[],
+ loadIssues: async (): Promise<MaxErrorTrackingIssuePreview[]> => {
+ const scope = values.effectiveScope
+ if (!scope) {
+ return []
+ }
+ // The exact scopes only have to cover the trace's own run. The session scope is the
+ // wider guess, so it keeps the wider window.
+ const range =
+ scope === 'session' ? sessionErrorsWindow([props.timestamp]) : traceErrorsWindow([props.timestamp])
+ if (!range) {
+ return []
+ }
+
+ // Spans read their ids back as uppercase hex, while the SDKs write them lowercase.
+ const traceId = usableId(props.traceId)
+ const spanId = usableId(props.spanId)
+ const filters: AnyPropertyFilter[] = []
+ if (scope === 'session' && props.sessionId) {
+ filters.push(eventFilter('$session_id', props.sessionId))
+ } else if (traceId) {
+ filters.push(eventFilter('$trace_id', traceId))
+ // A span id is only unique inside its trace, so both ids bound the span scope.
+ if (scope === 'span' && spanId) {
+ filters.push(eventFilter('$span_id', spanId))
+ }
+ }
+ if (filters.length === 0) {
+ return []
+ }
+
+ const query: ErrorTrackingQuery = {
+ kind: NodeKind.ErrorTrackingQuery,
+ orderBy: 'last_seen',
+ dateRange: range,
+ filterGroup: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: filters,
+ },
+ ],
+ },
+ volumeResolution: 0,
+ withAggregations: true,
+ limit: MAX_ISSUES,
+ }
+
+ const response = await api.query(query)
+
+ return response.results.map(
+ (issue): MaxErrorTrackingIssuePreview => ({
+ id: issue.id,
+ name: issue.name,
+ description: issue.description,
+ library: issue.library,
+ status: issue.status,
+ occurrences: issue.aggregations?.occurrences ?? 0,
+ sessions: issue.aggregations?.sessions ?? 0,
+ users: issue.aggregations?.users ?? 0,
+ first_seen: issue.first_seen,
+ last_seen: issue.last_seen,
+ })
+ )
+ },
+ },
+ })),
+
+ reducers({
+ // The banner shows its own copy rather than the raw failure, so only the fact is kept.
+ issuesFailed: [
+ false,
+ {
+ loadIssues: () => false,
+ loadIssuesFailure: () => true,
+ },
+ ],
+
+ selectedScope: [
+ null as TraceErrorsScope | null,
+ {
+ setScope: (_, { scope }) => scope,
+ },
+ ],
+ }),
+
+ selectors({
+ // Most precise first, so a trace that carries every id opens on the span that threw.
+ availableScopes: [
+ () => [(_, props: TraceErrorsLogicProps) => props],
+ (props: TraceErrorsLogicProps): TraceErrorsScope[] => {
+ const traceId = usableId(props.traceId)
+ const spanId = usableId(props.spanId)
+ const scopes: TraceErrorsScope[] = []
+ if (traceId && spanId) {
+ scopes.push('span')
+ }
+ if (traceId) {
+ scopes.push('trace')
+ }
+ if (props.sessionId) {
+ scopes.push('session')
+ }
+ return scopes
+ },
+ ],
+
+ // The user's own pick wins, then the scope the caller asked for, then the most precise the
+ // trace offers. A badge names the tier it counted, so the tab lists what the badge claimed
+ // rather than a narrower scope the badge already ruled out.
+ effectiveScope: [
+ (s) => [s.availableScopes, s.selectedScope, (_, props: TraceErrorsLogicProps) => props.initialScope],
+ (
+ availableScopes: TraceErrorsScope[],
+ selectedScope: TraceErrorsScope | null,
+ initialScope: TraceErrorsScope | null
+ ): TraceErrorsScope | null =>
+ [selectedScope, initialScope].find((scope) => scope && availableScopes.includes(scope)) ??
+ availableScopes[0] ??
+ null,
+ ],
+ }),
+
+ listeners(({ actions }) => ({
+ setScope: () => {
+ actions.loadIssues()
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadIssues()
+ }),
+])
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.stories.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.stories.tsx
new file mode 100644
index 000000000000..28b22494c41b
--- /dev/null
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.stories.tsx
@@ -0,0 +1,40 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { SpanErrorsBadge } from './SpanErrorsBadge'
+
+const meta: Meta<typeof SpanErrorsBadge> = {
+ title: 'Products/Tracing/SpanErrorsBadge',
+ component: SpanErrorsBadge,
+ args: {
+ tier: 'span',
+ errorCount: 3,
+ onClick: () => {},
+ },
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ },
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof SpanErrorsBadge>
+
+export const SpanTier: Story = {}
+
+export const TraceTier: Story = {
+ args: { tier: 'trace', errorCount: 2 },
+}
+
+export const SessionTier: Story = {
+ args: { tier: 'session', errorCount: 5 },
+}
+
+export const OneError: Story = {
+ args: { errorCount: 1 },
+}
+
+// A trace where one SDK stamped a trace id and another did not.
+export const TraceTierWithMoreInSession: Story = {
+ args: { tier: 'trace', errorCount: 1, alsoInSession: 3 },
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.tsx
new file mode 100644
index 000000000000..a7e4e11383b4
--- /dev/null
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanErrorsBadge.tsx
@@ -0,0 +1,48 @@
+import { IconWarning } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+import type { SpanErrorTier } from '../../spanErrorsLogic'
+
+export interface SpanErrorsBadgeProps {
+ tier: SpanErrorTier
+ errorCount: number
+ /** The session's total, when it is higher than the tier's own count. */
+ alsoInSession?: number
+ onClick: () => void
+}
+
+// A session count is only co-occurring evidence, so it reads as a warning rather than as this
+// span's own failure, and its noun stays vaguer.
+const TIERS: Record<SpanErrorTier, { iconClass: string; noun: string; where: string }> = {
+ span: { iconClass: 'text-danger', noun: 'error', where: 'in this span' },
+ trace: { iconClass: 'text-danger', noun: 'error', where: 'in this trace' },
+ session: { iconClass: 'text-warning', noun: 'error occurrence', where: 'in this session' },
+}
+
+export function SpanErrorsBadge({ tier, errorCount, alsoInSession, onClick }: SpanErrorsBadgeProps): JSX.Element {
+ const { iconClass, noun, where } = TIERS[tier]
+ const session = TIERS.session
+ // Each count names its own scope, because they are not summable. See `alsoInSession`.
+ const sentences = [
+ `${pluralize(errorCount, noun)} ${where}.`,
+ alsoInSession ? `${pluralize(alsoInSession, session.noun)} ${session.where}.` : null,
+ ].filter(Boolean)
+ const label = sentences.join(' ')
+
+ return (
+ <LemonButton
+ size="xsmall"
+ icon={<IconWarning className={iconClass} />}
+ tooltip={`${label} Click to see them.`}
+ aria-label={label}
+ data-attr="tracing-row-errors"
+ onMouseDown={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation()
+ onClick()
+ }}
+ />
+ )
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx
index 1a9279bf47f9..0b0096ca553a 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.stories.tsx
@@ -64,3 +64,17 @@ export const Default: Story = {}
export const Empty: Story = {
args: { dataSource: [] },
}
+
+// One row per badge tier, plus two rows with no errors, so the column's alignment shows.
+export const WithErrorBadges: Story = {
+ args: {
+ spanErrors: {
+ badges: new Map([
+ ['span-1', { tier: 'trace', count: 4 }],
+ ['span-3', { tier: 'session', count: 9 }],
+ ['span-5', { tier: 'span', count: 1 }],
+ ]),
+ onShow: () => {},
+ },
+ },
+}
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
index fc33da1f0dab..8b1a843e98d6 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/VirtualizedSpanList.tsx
@@ -10,14 +10,17 @@ import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'
import { cn } from 'lib/utils/css-classes'
import { TRACING_DATE_FORMAT, TRACING_DISPLAY_TIMEZONE, TRACING_TIME_FORMAT } from '../../dateFormats'
+import type { ErrorScope } from '../../errorCorrelation'
+import type { SpanErrorBadge } from '../../spanErrorsLogic'
import { formatDuration } from '../../TraceWaterfallView'
import type { TracingOrderBy, TracingOrderDirection } from '../../tracingFiltersLogic'
import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'
import type { Span } from '../../types'
-import { ResizableColumnSpec } from '../TableColumns/columnWidths'
+import { MIN_COLUMN_WIDTH, ResizableColumnSpec } from '../TableColumns/columnWidths'
import { TableCell } from '../TableColumns/TableCell'
import { TableHeaderCell } from '../TableColumns/TableHeaderCell'
import { ResizableColumns, useResizableColumns } from '../TableColumns/useResizableColumns'
+import { SpanErrorsBadge } from './SpanErrorsBadge'
import { SpanRowActions } from './SpanRowActions'
const ROW_HEIGHT = 36
@@ -33,9 +36,13 @@ const SPAN_COLUMNS: ResizableColumnSpec[] = [
{ key: 'kind', width: 90 },
{ key: 'duration', width: 90 },
{ key: 'status', width: 80 },
+ // The error badge. It holds its width on rows with no errors so the columns beside it stay
+ // aligned down the page as counts arrive.
+ { key: 'spanErrors', width: MIN_COLUMN_WIDTH },
{ key: 'traceId', width: 140 },
{ key: 'actions', width: 130 },
]
+const SPAN_COLUMNS_WITHOUT_ERRORS: ResizableColumnSpec[] = SPAN_COLUMNS.filter((column) => column.key !== 'spanErrors')
// pinned: identifies stored column widths — renaming resets everyone's widths
const TABLE_KEY = 'spans'
@@ -49,6 +56,14 @@ interface SortProps {
onSort: (column: TracingOrderBy) => void
}
+/** Badges rows that hit errors. Absent when the feature is off, and then no column. */
+export interface SpanErrors {
+ /** What each row badges, by span uuid. A row the map does not hold carries no badge. */
+ badges: Map<string, SpanErrorBadge>
+ /** The tier travels with the click so the drawer opens on the scope the badge just named. */
+ onShow: (span: Span, scope: ErrorScope) => void
+}
+
interface VirtualizedSpanListProps extends SortProps {
dataSource: Span[]
loading: boolean
@@ -57,18 +72,21 @@ interface VirtualizedSpanListProps extends SortProps {
hasMoreToLoad?: boolean
onLoadMore?: () => void
emptyState?: ReactNode
+ spanErrors?: SpanErrors
}
interface SpanRowProps {
dataSource: Span[]
widths: Record<string, number>
onRowClick: (span: Span) => void
+ spanErrors: SpanErrors | undefined
}
/** Header cell wired to the shared resize handle. `sort` marks the column as server-sortable. */
function SpanHeaderCell({
columnKey,
label,
+ resizeLabel,
widths,
columns,
sort,
@@ -76,13 +94,18 @@ function SpanHeaderCell({
columnKey: string
/** Omit for a column with no heading, e.g. row actions. */
label?: string
+ /** Names the column to assistive tech on the resize handle when it has no visible heading. */
+ resizeLabel?: string
widths: Record<string, number>
columns: ResizableColumns
sort?: { column: TracingOrderBy } & SortProps
}): JSX.Element {
const active = sort ? sort.orderBy === sort.column : false
return (
- <TableHeaderCell width={widths[columnKey]} resize={columns.resizeHandleProps(columnKey, label ?? columnKey)}>
+ <TableHeaderCell
+ width={widths[columnKey]}
+ resize={columns.resizeHandleProps(columnKey, label ?? resizeLabel ?? columnKey)}
+ >
{sort ? (
<button
type="button"
@@ -105,10 +128,15 @@ function SpanHeaderCell({
function SpanRowHeader({
widths,
columns,
+ showSpanErrors,
orderBy,
orderDirection,
onSort,
-}: { widths: Record<string, number>; columns: ResizableColumns } & SortProps): JSX.Element {
+}: {
+ widths: Record<string, number>
+ columns: ResizableColumns
+ showSpanErrors: boolean
+} & SortProps): JSX.Element {
const shared = { widths, columns }
const sortProps = { orderBy, orderDirection, onSort }
return (
@@ -133,6 +161,8 @@ function SpanRowHeader({
sort={{ column: 'duration', ...sortProps }}
/>
<SpanHeaderCell {...shared} columnKey="status" label="Status" />
+ {/* The error badge needs no heading; its tooltip says what the count means. */}
+ {showSpanErrors && <SpanHeaderCell {...shared} columnKey="spanErrors" resizeLabel="Errors" />}
<SpanHeaderCell {...shared} columnKey="traceId" label="Trace ID" />
{/* Row actions need no heading. */}
<SpanHeaderCell {...shared} columnKey="actions" />
@@ -143,13 +173,16 @@ function SpanRowHeader({
function SpanRow({
span,
widths,
+ spanErrors,
onClick,
}: {
span: Span
widths: Record<string, number>
+ spanErrors: SpanErrors | undefined
onClick: () => void
}): JSX.Element {
const status = STATUS_CODE_LABELS[span.status_code] ?? { label: String(span.status_code), type: 'default' as const }
+ const errorBadge = spanErrors?.badges.get(span.uuid)
return (
<div
@@ -157,8 +190,10 @@ function SpanRow({
// eslint-disable-next-line react/forbid-dom-props
style={{ height: ROW_HEIGHT }}
onClick={onClick}
+ // Only a key press on the row itself opens it. A press on a button inside the row
+ // bubbles here too, and taking it would cancel that button's own click.
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
+ if ((e.key === 'Enter' || e.key === ' ') && e.target === e.currentTarget) {
e.preventDefault()
onClick()
}
@@ -195,6 +230,18 @@ function SpanRow({
<TableCell width={widths.status}>
<LemonTag type={status.type}>{status.label}</LemonTag>
</TableCell>
+ {spanErrors && (
+ <TableCell width={widths.spanErrors}>
+ {errorBadge && (
+ <SpanErrorsBadge
+ tier={errorBadge.tier}
+ errorCount={errorBadge.count}
+ alsoInSession={errorBadge.alsoInSession}
+ onClick={() => spanErrors.onShow(span, errorBadge.tier)}
+ />
+ )}
+ </TableCell>
+ )}
<TableCell width={widths.traceId}>
<span className="font-mono">{span.trace_id.substring(0, 16)}...</span>
</TableCell>
@@ -211,6 +258,7 @@ function SpanListRow({
style,
dataSource,
widths,
+ spanErrors,
onRowClick,
}: {
ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
@@ -222,7 +270,7 @@ function SpanListRow({
return (
// eslint-disable-next-line react/forbid-dom-props
<div {...ariaAttributes} style={style} data-index={index} data-row-key={span.uuid}>
- <SpanRow span={span} widths={widths} onClick={() => onRowClick(span)} />
+ <SpanRow span={span} widths={widths} spanErrors={spanErrors} onClick={() => onRowClick(span)} />
</div>
)
}
@@ -235,6 +283,7 @@ export function VirtualizedSpanList({
hasMoreToLoad = false,
onLoadMore,
emptyState = 'No spans found',
+ spanErrors,
orderBy,
orderDirection,
onSort,
@@ -243,7 +292,10 @@ export function VirtualizedSpanList({
const lastVisibleRangeRef = useRef<{ startIndex: number; stopIndex: number } | null>(null)
const listRef = useListRef(null)
- const columns = useResizableColumns(TABLE_KEY, SPAN_COLUMNS)
+ // Both variants are module constants, because useResizableColumns reuses its resolved widths
+ // object while the specs identity holds. Building the array here would hand every virtualized
+ // row new widths on every render.
+ const columns = useResizableColumns(TABLE_KEY, spanErrors ? SPAN_COLUMNS : SPAN_COLUMNS_WITHOUT_ERRORS)
const handleRowsRendered = useCallback(
(
@@ -298,6 +350,7 @@ export function VirtualizedSpanList({
<SpanRowHeader
widths={widths}
columns={columns}
+ showSpanErrors={!!spanErrors}
orderBy={orderBy}
orderDirection={orderDirection}
onSort={onSort}
@@ -308,7 +361,7 @@ export function VirtualizedSpanList({
rowCount={dataSource.length}
rowHeight={ROW_HEIGHT}
rowComponent={SpanListRow}
- rowProps={{ dataSource, widths, onRowClick }}
+ rowProps={{ dataSource, widths, spanErrors, onRowClick }}
onRowsRendered={handleRowsRendered}
listRef={listRef}
/>
diff --git a/products/tracing/frontend/emptyState/tracingEmptyState.tsx b/products/tracing/frontend/emptyState/tracingEmptyState.tsx
index 30d7eb2358eb..947ee7401d57 100644
--- a/products/tracing/frontend/emptyState/tracingEmptyState.tsx
+++ b/products/tracing/frontend/emptyState/tracingEmptyState.tsx
@@ -6,6 +6,7 @@ import type { SceneProductEmptyState } from 'lib/components/ProductEmptyState/ty
import { ProductKey } from '~/queries/schema/schema-general'
+import { TRACING_DOCS_URL } from '../traceLinks'
import { TracingPreview } from './TracingPreview'
import { tracingSetupLogic } from './tracingSetupLogic'
@@ -26,7 +27,7 @@ export const tracingEmptyState: SceneProductEmptyState = {
lead: 'Send spans from the PostHog Node.js or Python SDK, or from any OpenTelemetry-compatible client over OTLP. Follow a request across services, find the span that slows it down, and watch latency over time.',
},
},
- docsUrl: 'https://posthog.com/docs/tracing',
+ docsUrl: TRACING_DOCS_URL,
previewLabel: 'Your traces, once connected',
Preview: TracingPreview,
},
diff --git a/products/tracing/frontend/errorCorrelation.test.ts b/products/tracing/frontend/errorCorrelation.test.ts
new file mode 100644
index 000000000000..1aa3ac8b4c7b
--- /dev/null
+++ b/products/tracing/frontend/errorCorrelation.test.ts
@@ -0,0 +1,45 @@
+import { sessionErrorsWindow, traceErrorsWindow, usableId } from './errorCorrelation'
+
+describe('errorCorrelation', () => {
+ // A span whose timestamp the parser rejects must not widen the range to an invalid one, which
+ // would put NaN into the query the badge lookup builds. The range is six hours either side.
+ it.each([
+ ['every timestamp parses', ['2026-09-03T10:00:00Z', '2026-09-03T12:00:00Z']],
+ [
+ 'one timestamp is missing and another unparseable',
+ ['2026-09-03T10:00:00Z', null, 'not-a-timestamp', '2026-09-03T12:00:00Z'],
+ ],
+ ])('spans the earliest and latest timestamp when %s', (_name, timestamps) => {
+ expect(sessionErrorsWindow(timestamps)).toEqual({
+ date_from: '2026-09-03T04:00:00.000Z',
+ date_to: '2026-09-03T18:00:00.000Z',
+ })
+ })
+
+ it.each([
+ ['no timestamps', []],
+ ['only unparseable timestamps', ['not-a-timestamp']],
+ ['only missing timestamps', [null]],
+ ])('resolves no range when there are %s', (_name, timestamps) => {
+ expect(sessionErrorsWindow(timestamps)).toBeNull()
+ })
+
+ it.each([
+ ['a real id', '4BF92F3577B34DA6A3CE929D0E0E4736', '4bf92f3577b34da6a3ce929d0e0e4736'],
+ ['an all-zero trace id', '0'.repeat(32), null],
+ ['an all-zero span id', '0'.repeat(16), null],
+ ['a missing id', null, null],
+ ['an empty id', '', null],
+ ])('resolves %s', (_name, value, expected) => {
+ expect(usableId(value)).toBe(expected)
+ })
+
+ // The exact join only has to cover the trace's own run, so it asks over a much narrower range
+ // than the session guess needs.
+ it('spans one hour either side for the trace window', () => {
+ expect(traceErrorsWindow(['2026-09-03T10:00:00Z'])).toEqual({
+ date_from: '2026-09-03T09:00:00.000Z',
+ date_to: '2026-09-03T11:00:00.000Z',
+ })
+ })
+})
diff --git a/products/tracing/frontend/errorCorrelation.ts b/products/tracing/frontend/errorCorrelation.ts
new file mode 100644
index 000000000000..89cc44bf599e
--- /dev/null
+++ b/products/tracing/frontend/errorCorrelation.ts
@@ -0,0 +1,77 @@
+import { dayjs } from 'lib/dayjs'
+
+import { TRACE_LOOKUP_WINDOW_HOURS } from './traceLinks'
+
+/**
+ * Which ids an exception was matched on, in falling order of confidence. One type for both
+ * surfaces, so a badge's answer can open the drawer's tab on the same footing.
+ */
+export type ErrorScope = 'span' | 'trace' | 'session'
+
+// How far from a span an exception in the same session can sit and still count as related. It
+// matches the window the Logs product's Related errors surface uses, so the same session reads
+// the same way in both products.
+export const SESSION_ERRORS_WINDOW_HOURS = 6
+
+export interface ErrorsWindow {
+ date_from: string
+ date_to: string
+}
+
+// The union of every timestamp's own window, so a set of spans that covers a wide range asks
+// about a wide range. Null when no timestamp parses, because there is then no range to ask about.
+function errorsWindow(timestamps: (string | null)[], hours: number): ErrorsWindow | null {
+ let earliest = Number.POSITIVE_INFINITY
+ let latest = Number.NEGATIVE_INFINITY
+ for (const timestamp of timestamps) {
+ // Guard before dayjs, because dayjs(undefined) reads as the current time.
+ if (!timestamp) {
+ continue
+ }
+ const parsed = dayjs(timestamp)
+ if (!parsed.isValid()) {
+ continue
+ }
+ const milliseconds = parsed.valueOf()
+ if (milliseconds < earliest) {
+ earliest = milliseconds
+ }
+ if (milliseconds > latest) {
+ latest = milliseconds
+ }
+ }
+ if (!Number.isFinite(earliest) || !Number.isFinite(latest)) {
+ return null
+ }
+ // The DateRange key names an ErrorTrackingQuery takes, so the drawer's tab passes the result
+ // straight through.
+ return {
+ date_from: dayjs(earliest).subtract(hours, 'hours').toISOString(),
+ date_to: dayjs(latest).add(hours, 'hours').toISOString(),
+ }
+}
+
+export function sessionErrorsWindow(timestamps: (string | null)[]): ErrorsWindow | null {
+ return errorsWindow(timestamps, SESSION_ERRORS_WINDOW_HOURS)
+}
+
+// An exception that carries a trace id happened inside that trace, so the window only has to cover
+// the trace itself. `traceLookupDateRange` is the same window for a single timestamp.
+export function traceErrorsWindow(timestamps: (string | null)[]): ErrorsWindow | null {
+ return errorsWindow(timestamps, TRACE_LOOKUP_WINDOW_HOURS)
+}
+
+/**
+ * A trace or span id in the form the events hold it, or null when the row carries none.
+ *
+ * Spans read their ids back as uppercase hex while the SDKs write them lowercase. An id of all
+ * zeros is OpenTelemetry's "no id" sentinel, and it arrives as a string like any other, so a
+ * caller that only checks for a value would match every uninstrumented row to it.
+ */
+export function usableId(value: string | null | undefined): string | null {
+ if (!value) {
+ return null
+ }
+ const normalized = value.toLowerCase()
+ return /^0+$/.test(normalized) ? null : normalized
+}
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 35333c9c864d..6274aa40f407 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -389,6 +389,58 @@ export interface _TracingDurationHistogramRequestApi {
query: _TracingDurationHistogramQueryBodyApi
}
+export interface _TracingErrorCountsRequestApi {
+ /**
+ * Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` property. Case insensitive. At most 200 per request.
+ * @maxItems 200
+ */
+ traceIds?: string[]
+ /**
+ * Hex span IDs to count exceptions for, matched against the exception's `$span_id` property. Only counted within the requested traces, so `traceIds` is required alongside. At most 200 per request.
+ * @maxItems 200
+ */
+ spanIds?: string[]
+ /**
+ * Session IDs to count exceptions for. The fallback for exceptions that carry no trace ID. At most 200 per request.
+ * @maxItems 200
+ */
+ sessionIds?: string[]
+ /** Start of the window the exceptions must fall in. ISO 8601. */
+ dateFrom: string
+ /** End of the window the exceptions must fall in. ISO 8601. */
+ dateTo: string
+}
+
+export interface _TracingTraceErrorCountApi {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number
+ /** The trace the exceptions belong to, lowercase hex. */
+ trace_id: string
+}
+
+export interface _TracingSpanErrorCountApi {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number
+ /** The span the exceptions belong to, lowercase hex. */
+ span_id: string
+}
+
+export interface _TracingSessionErrorCountApi {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number
+ /** The session the exceptions belong to. */
+ session_id: string
+}
+
+export interface _TracingErrorCountsResponseApi {
+ /** One entry per requested trace that had exceptions. Traces with none are omitted. */
+ traceResults: _TracingTraceErrorCountApi[]
+ /** One entry per requested span that had exceptions. Spans with none are omitted. */
+ spanResults: _TracingSpanErrorCountApi[]
+ /** One entry per requested session that had exceptions. Sessions with none are omitted. */
+ sessionResults: _TracingSessionErrorCountApi[]
+}
+
export interface _HasSpansResponseApi {
/** Whether the team has ingested any tracing spans yet. Used to gate the onboarding empty state. */
hasSpans: boolean
diff --git a/products/tracing/frontend/generated/api.ts b/products/tracing/frontend/generated/api.ts
index f8877ac669a4..87eeb2a5d650 100644
--- a/products/tracing/frontend/generated/api.ts
+++ b/products/tracing/frontend/generated/api.ts
@@ -29,6 +29,8 @@ import type {
_TracingCountRequestApi,
_TracingCountResponseApi,
_TracingDurationHistogramRequestApi,
+ _TracingErrorCountsRequestApi,
+ _TracingErrorCountsResponseApi,
_TracingImpactRequestApi,
_TracingImpactResponseApi,
_TracingLatencyHeatmapRequestApi,
@@ -199,6 +201,29 @@ export const tracingSpansDurationHistogramCreate = async (
})
}
+export const getTracingSpansErrorCountsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/tracing/spans/error-counts/`
+}
+
+/**
+ * Count the exceptions the spans in view hit, by trace, by span and by session, for the
+ * span list's error badges.
+ *
+ * A caller asks about the id kinds it has, and each kind is a separate lookup.
+ */
+export const tracingSpansErrorCountsCreate = async (
+ projectId: string,
+ _tracingErrorCountsRequestApi: _TracingErrorCountsRequestApi,
+ options?: RequestInit
+): Promise<_TracingErrorCountsResponseApi> => {
+ return apiMutator<_TracingErrorCountsResponseApi>(getTracingSpansErrorCountsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_tracingErrorCountsRequestApi),
+ })
+}
+
export const getTracingSpansHasSpansRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/tracing/spans/has_spans/`
}
diff --git a/products/tracing/frontend/generated/api.zod.ts b/products/tracing/frontend/generated/api.zod.ts
index c9b6dc472857..ecd4968eac8e 100644
--- a/products/tracing/frontend/generated/api.zod.ts
+++ b/products/tracing/frontend/generated/api.zod.ts
@@ -522,6 +522,44 @@ export const TracingSpansDurationHistogramCreateBody = /* @__PURE__ */ zod.objec
.describe('The duration-histogram query to execute.'),
})
+/**
+ * Count the exceptions the spans in view hit, by trace, by span and by session, for the
+ * span list's error badges.
+ *
+ * A caller asks about the id kinds it has, and each kind is a separate lookup.
+ */
+export const tracingSpansErrorCountsCreateBodyTraceIdsMax = 200
+
+export const tracingSpansErrorCountsCreateBodySpanIdsMax = 200
+
+export const tracingSpansErrorCountsCreateBodySessionIdsMax = 200
+
+export const TracingSpansErrorCountsCreateBody = /* @__PURE__ */ zod.object({
+ traceIds: zod
+ .array(zod.string())
+ .max(tracingSpansErrorCountsCreateBodyTraceIdsMax)
+ .optional()
+ .describe(
+ "Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` property. Case insensitive. At most 200 per request."
+ ),
+ spanIds: zod
+ .array(zod.string())
+ .max(tracingSpansErrorCountsCreateBodySpanIdsMax)
+ .optional()
+ .describe(
+ "Hex span IDs to count exceptions for, matched against the exception's `$span_id` property. Only counted within the requested traces, so `traceIds` is required alongside. At most 200 per request."
+ ),
+ sessionIds: zod
+ .array(zod.string())
+ .max(tracingSpansErrorCountsCreateBodySessionIdsMax)
+ .optional()
+ .describe(
+ 'Session IDs to count exceptions for. The fallback for exceptions that carry no trace ID. At most 200 per request.'
+ ),
+ dateFrom: zod.iso.datetime({ offset: true }).describe('Start of the window the exceptions must fall in. ISO 8601.'),
+ dateTo: zod.iso.datetime({ offset: true }).describe('End of the window the exceptions must fall in. ISO 8601.'),
+})
+
export const TracingSpansImpactCreateBody = /* @__PURE__ */ zod.object({
query: zod
.object({
diff --git a/products/tracing/frontend/spanErrorsLogic.test.ts b/products/tracing/frontend/spanErrorsLogic.test.ts
new file mode 100644
index 000000000000..c05ca42ce086
--- /dev/null
+++ b/products/tracing/frontend/spanErrorsLogic.test.ts
@@ -0,0 +1,318 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
+
+import { tracingSpansErrorCountsCreate } from 'products/tracing/frontend/generated/api'
+
+import { makeSpan } from './__mocks__/span'
+import { spanErrorsLogic } from './spanErrorsLogic'
+import { tracingCorrelationConfigLogic } from './tracingCorrelationConfigLogic'
+import { tracingDataLogic } from './tracingDataLogic'
+import type { Span } from './types'
+
+jest.mock('products/tracing/frontend/generated/api', () => ({
+ tracingSpansErrorCountsCreate: jest.fn(),
+}))
+
+const mockCountsCreate = tracingSpansErrorCountsCreate as jest.MockedFunction<typeof tracingSpansErrorCountsCreate>
+
+const NO_COUNTS = { traceResults: [], spanResults: [], sessionResults: [] }
+
+// A row with no trace or span id, so only the session join can answer it.
+function spanWithSession(uuid: string, sessionId: string | null): Span {
+ return makeSpan({
+ uuid,
+ trace_id: '',
+ span_id: '',
+ attributes: sessionId ? { sessionId } : {},
+ })
+}
+
+function spanWithIds(uuid: string, traceId: string, spanId: string, sessionId?: string): Span {
+ return makeSpan({
+ uuid,
+ trace_id: traceId,
+ span_id: spanId,
+ attributes: sessionId ? { sessionId } : {},
+ })
+}
+
+describe('spanErrorsLogic', () => {
+ let logic: ReturnType<typeof spanErrorsLogic.build>
+ let dataLogic: ReturnType<typeof tracingDataLogic.build>
+
+ // The loader success actions are what the list's fetches dispatch, so driving them is the
+ // cheapest way to load a page without standing up the spans endpoint.
+ const loadFirstPage = async (spans: Span[]): Promise<void> => {
+ dataLogic.actions.fetchSpansSuccess(spans)
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ // A next page arrives as the whole accumulated list, the way the spans loader appends it.
+ const loadNextPage = async (spans: Span[]): Promise<void> => {
+ dataLogic.actions.fetchNextPageSuccess(spans)
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ const asked = (field: 'traceIds' | 'spanIds' | 'sessionIds'): string[][] =>
+ mockCountsCreate.mock.calls.map(([, body]) => body[field]).filter((ids): ids is string[] => !!ids?.length)
+
+ const setErrorTrackingAccess = (level: AccessControlLevel): void => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.ErrorTracking]: level,
+ },
+ } as AppContext
+ }
+
+ // The access level is read from the app context when the flag selector first runs, so a
+ // test that changes it has to build the logics again afterwards.
+ const mountLogics = (): void => {
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES], {
+ [FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES]: true,
+ })
+ dataLogic = tracingDataLogic()
+ dataLogic.mount()
+ logic = spanErrorsLogic()
+ logic.mount()
+ }
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:teamId/tracing_config/': () => [
+ 200,
+ {
+ tracing_distinct_id_attribute_keys: ['posthogDistinctId'],
+ tracing_session_id_attribute_keys: ['sessionId'],
+ },
+ ],
+ },
+ })
+ mockCountsCreate.mockReset()
+ mockCountsCreate.mockResolvedValue({
+ ...NO_COUNTS,
+ sessionResults: [{ session_id: 'session-a', exceptions: 3 }],
+ })
+ setErrorTrackingAccess(AccessControlLevel.Viewer)
+ mountLogics()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ dataLogic.unmount()
+ })
+
+ it('badges the most precise join each row has', async () => {
+ mockCountsCreate.mockResolvedValue({
+ traceResults: [{ trace_id: 'trace-a', exceptions: 4 }],
+ spanResults: [{ span_id: 'span-thrower', exceptions: 1 }],
+ sessionResults: [{ session_id: 'session-c', exceptions: 7 }],
+ })
+
+ await loadFirstPage([
+ spanWithIds('row-span', 'trace-a', 'span-thrower'),
+ spanWithIds('row-trace', 'trace-a', 'span-quiet'),
+ spanWithSession('row-session', 'session-c'),
+ ])
+
+ expect(logic.values.errorBadgeByRow.get('row-span')).toEqual({ tier: 'span', count: 1 })
+ expect(logic.values.errorBadgeByRow.get('row-trace')).toEqual({ tier: 'trace', count: 4 })
+ expect(logic.values.errorBadgeByRow.get('row-session')).toEqual({ tier: 'session', count: 7 })
+ })
+
+ // An id of all zeros is OpenTelemetry's "no id" sentinel. Asking about it would match every
+ // uninstrumented exception in the window to every uninstrumented row.
+ it('treats an all-zero trace id as no trace at all', async () => {
+ await loadFirstPage([spanWithIds('row-1', '0'.repeat(32), '0'.repeat(16), 'session-a')])
+
+ expect(asked('traceIds')).toEqual([])
+ expect(asked('sessionIds')).toEqual([['session-a']])
+ })
+
+ // The counts are not nested, so neither asking about the session only where the exact join
+ // found nothing, nor suppressing a total that is not larger, is safe: both hide exceptions
+ // from an SDK that stamps no trace id.
+ const mockTraceAndSession = (trace: number, session: number): void => {
+ mockCountsCreate.mockImplementation(async (_teamId, body) =>
+ body.sessionIds?.length
+ ? { ...NO_COUNTS, sessionResults: [{ session_id: 'session-a', exceptions: session }] }
+ : { ...NO_COUNTS, traceResults: [{ trace_id: 'trace-a', exceptions: trace }] }
+ )
+ }
+
+ it.each([
+ ['the session holds more', 1, 3, { tier: 'trace', count: 1, alsoInSession: 3 }],
+ ['the counts match', 2, 2, { tier: 'trace', count: 2, alsoInSession: 2 }],
+ ['the session holds fewer', 3, 1, { tier: 'trace', count: 3, alsoInSession: 1 }],
+ ['the session is clean', 2, 0, { tier: 'trace', count: 2 }],
+ ])('carries the session total beside the trace count when %s', async (_name, trace, session, expected) => {
+ mockTraceAndSession(trace, session)
+
+ await loadFirstPage([spanWithIds('row-1', 'trace-a', 'span-1', 'session-a')])
+
+ expect(asked('sessionIds')).toEqual([['session-a']])
+ expect(logic.values.errorBadgeByRow.get('row-1')).toEqual(expected)
+ })
+
+ // The session tier is already the session count, so repeating it would read as two findings.
+ it('does not repeat the session total on a session-tier badge', async () => {
+ mockCountsCreate.mockResolvedValue({
+ ...NO_COUNTS,
+ sessionResults: [{ session_id: 'session-a', exceptions: 4 }],
+ })
+
+ await loadFirstPage([spanWithSession('row-1', 'session-a')])
+
+ expect(logic.values.errorBadgeByRow.get('row-1')).toEqual({ tier: 'session', count: 4 })
+ })
+
+ // Span rows read their ids back as uppercase hex while the SDKs write them lowercase.
+ it('asks about ids in the case the events are stored in', async () => {
+ await loadFirstPage([spanWithIds('row-1', 'TRACE-A', 'SPAN-1')])
+
+ expect(asked('traceIds')).toEqual([['trace-a']])
+ expect(asked('spanIds')).toEqual([['span-1']])
+ })
+
+ it('records a zero for every id it looked up, so the next page only asks about new ones', async () => {
+ await loadFirstPage([spanWithSession('span-1', 'session-a'), spanWithSession('span-2', 'session-b')])
+
+ expect(logic.values.errorCounts.session).toEqual({ 'session-a': 3, 'session-b': 0 })
+ // A clean session must leave the row out rather than badge it with a zero.
+ expect(logic.values.errorBadgeByRow.get('span-1')).toEqual({ tier: 'session', count: 3 })
+ expect(logic.values.errorBadgeByRow.has('span-2')).toBe(false)
+
+ await loadNextPage([
+ spanWithSession('span-1', 'session-a'),
+ spanWithSession('span-2', 'session-b'),
+ spanWithSession('span-3', 'session-c'),
+ ])
+
+ expect(asked('sessionIds')).toEqual([['session-a', 'session-b'], ['session-c']])
+ })
+
+ it('deduplicates the ids on the page', async () => {
+ await loadFirstPage([
+ spanWithSession('span-1', 'session-a'),
+ spanWithSession('span-2', 'session-a'),
+ spanWithSession('span-3', null),
+ ])
+
+ expect(asked('sessionIds')).toEqual([['session-a']])
+ })
+
+ // The exact join only has to cover the trace's own run, so it asks over a narrower range than
+ // the session guess needs.
+ it.each([
+ ['trace', 'traceIds' as const, '2026-06-02T07:00:00.000Z', '2026-06-02T09:00:00.000Z'],
+ ['session', 'sessionIds' as const, '2026-06-02T02:00:00.000Z', '2026-06-02T14:00:00.000Z'],
+ ])('asks the %s join over its own window', async (_name, field, dateFrom, dateTo) => {
+ const span =
+ field === 'traceIds' ? spanWithIds('span-1', 'trace-a', 'span-1') : spanWithSession('span-1', 'session-a')
+
+ await loadFirstPage([{ ...span, timestamp: '2026-06-02T08:00:00Z' }])
+
+ const call = mockCountsCreate.mock.calls.find(([, body]) => body[field]?.length)
+ expect(call?.[1]).toMatchObject({ dateFrom, dateTo })
+ })
+
+ // The endpoint refuses a person without Error Tracking access, so this gate is what keeps the
+ // badges from showing an error state to them. It also spares every other team the scan.
+ it.each([
+ ['the feature flag is off', (): void => featureFlagLogic.actions.setFeatureFlags([], {})],
+ [
+ 'the person has no Error Tracking access',
+ (): void => {
+ logic.unmount()
+ dataLogic.unmount()
+ setErrorTrackingAccess(AccessControlLevel.None)
+ mountLogics()
+ },
+ ],
+ ])('queries nothing and scans no rows while %s', async (_name, disable) => {
+ disable()
+ await loadFirstPage([spanWithIds('span-1', 'trace-a', 'span-1', 'session-a')])
+
+ expect(mockCountsCreate).not.toHaveBeenCalled()
+ expect(logic.values.errorCounts.session).toEqual({})
+ // Empty because the resolve is skipped, not because the rows carry no session. Without
+ // that guard every team pays the per-row attribute scan for a feature they cannot see.
+ expect(logic.values.sessionIdByRow.size).toBe(0)
+ })
+
+ // The cap bounds one request, not how many rows a page can badge.
+ it('splits a page over the cap into several requests and answers every id', async () => {
+ const firstPage = Array.from({ length: 250 }, (_, i) => spanWithSession(`span-${i}`, `session-${i}`))
+ await loadFirstPage(firstPage)
+
+ expect(asked('sessionIds').map((chunk) => chunk.length)).toEqual([200, 50])
+ expect(Object.keys(logic.values.errorCounts.session)).toHaveLength(250)
+
+ await loadNextPage([...firstPage, spanWithSession('span-new', 'session-new')])
+
+ expect(asked('sessionIds')[2]).toEqual(['session-new'])
+ })
+
+ // A team that stores the session under its own key resolves nothing until the configured keys
+ // arrive, and that can happen after the first page has already been looked up.
+ it('asks again when the configured session keys arrive after the page', async () => {
+ await loadFirstPage([
+ makeSpan({ uuid: 'span-1', trace_id: '', span_id: '', attributes: { customSession: 'x' } }),
+ ])
+ expect(asked('sessionIds')).toEqual([])
+
+ tracingCorrelationConfigLogic.actions.loadTracingConfigSuccess({
+ tracing_distinct_id_attribute_keys: ['posthogDistinctId'],
+ tracing_session_id_attribute_keys: ['customSession'],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(asked('sessionIds')).toEqual([['x']])
+ })
+
+ // No usable timestamp means no window to ask over. The lookup has to stop there rather than
+ // keep retrying a page it can never answer.
+ it('asks nothing when no row in view has a usable timestamp', async () => {
+ await loadFirstPage([{ ...spanWithSession('span-1', 'session-a'), timestamp: 'not-a-date' }])
+
+ expect(mockCountsCreate).not.toHaveBeenCalled()
+ expect(logic.values.errorCounts.session).toEqual({})
+ })
+
+ it('drops counts from the previous filters when a fresh query lands', async () => {
+ await loadFirstPage([spanWithSession('span-1', 'session-a')])
+ expect(logic.values.errorCounts.session).toEqual({ 'session-a': 3 })
+
+ await loadFirstPage([])
+
+ expect(logic.values.errorCounts.session).toEqual({})
+ })
+
+ // A first page shorter than the viewport asks for the next one immediately, which supersedes
+ // the fresh page's lookup before its debounce elapses. The counts still have to go, or the
+ // previous filters keep badging rows.
+ it('drops the previous counts even when the next page supersedes the lookup', async () => {
+ await loadFirstPage([spanWithSession('span-1', 'session-a')])
+ expect(logic.values.errorCounts.session).toEqual({ 'session-a': 3 })
+
+ // The fresh filters return no exceptions, so anything left over comes from the old page.
+ mockCountsCreate.mockResolvedValue(NO_COUNTS)
+
+ const freshPage = [spanWithSession('span-2', 'session-b')]
+ dataLogic.actions.fetchSpansSuccess(freshPage)
+ dataLogic.actions.fetchNextPageSuccess(freshPage)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.errorCounts.session).not.toHaveProperty('session-a')
+ })
+})
diff --git a/products/tracing/frontend/spanErrorsLogic.ts b/products/tracing/frontend/spanErrorsLogic.ts
new file mode 100644
index 000000000000..675b04e2cd7a
--- /dev/null
+++ b/products/tracing/frontend/spanErrorsLogic.ts
@@ -0,0 +1,443 @@
+import { MakeLogicType, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { chunk } from 'lib/utils/arrays'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { type ErrorScope, sessionErrorsWindow, traceErrorsWindow, usableId } from './errorCorrelation'
+import { tracingSpansErrorCountsCreate } from './generated/api'
+import type { TeamTracingConfigApi } from './generated/api.schemas'
+import { tracingSpansErrorCountsCreateBodySpanIdsMax } from './generated/api.zod'
+import { resolveSpanSessionId } from './traceIdentity'
+import { tracingCorrelationConfigLogic } from './tracingCorrelationConfigLogic'
+import { tracingDataLogic } from './tracingDataLogic'
+import { TRACING_SCENE_VIEWER_ID } from './tracingFiltersLogic'
+import type { Span } from './types'
+
+const MAX_IDS_PER_LOOKUP = tracingSpansErrorCountsCreateBodySpanIdsMax
+
+// A kea breakpoint cancels a superseded lookup, and the one that survives asks about every id
+// still unanswered, so this wait coalesces fast paging into a single query.
+const LOOKUP_DEBOUNCE_MS = 300
+
+// One shared instance, so the selectors below keep their identity while the feature is off.
+const NO_SESSIONS: Map<string, string> = new Map()
+
+/** Which join produced a row's count. The badge says a different thing for each. */
+export type SpanErrorTier = ErrorScope
+
+export interface SpanErrorBadge {
+ tier: SpanErrorTier
+ count: number
+ /**
+ * The session's own total, when the row matched on a narrower tier. It is a separate count
+ * over a separate set, not a remainder: the session query matches `$session_id` and the trace
+ * query matches `$trace_id`, so a backend exception can be in one and not the other.
+ */
+ alsoInSession?: number
+}
+
+export interface SpanErrorCounts {
+ trace: Record<string, number>
+ span: Record<string, number>
+ session: Record<string, number>
+}
+
+type ExactCounts = Pick<SpanErrorCounts, 'trace' | 'span'>
+
+export interface SpanErrorsLogicProps {
+ id: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spanErrorsLogicValues {
+ currentTeamId: number | null // teamLogic
+ configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic
+ sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
+ listRows: Span[] // tracingDataLogic
+ errorBadgeByRow: Map<string, SpanErrorBadge>
+ errorCounts: SpanErrorCounts
+ errorCountsLoading: boolean
+ sessionIdByRow: Map<string, string>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spanErrorsLogicActions {
+ loadTracingConfigSuccess: (
+ tracingConfig: TeamTracingConfigApi,
+ payload?: any
+ ) => {
+ payload?: any
+ tracingConfig: TeamTracingConfigApi
+ } // tracingCorrelationConfigLogic
+ fetchNextPageSuccess: (
+ spans: Span[],
+ payload?:
+ | {
+ value: true
+ }
+ | undefined
+ ) => {
+ payload?: {
+ value: true
+ }
+ spans: Span[]
+ } // tracingDataLogic
+ fetchSpansSuccess: (
+ spans: Span[],
+ payload?: any
+ ) => {
+ payload?: any
+ spans: Span[]
+ } // tracingDataLogic
+ loadErrorCounts: (_: void) => void
+ loadErrorCountsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadErrorCountsSuccess: (
+ errorCounts: SpanErrorCounts,
+ payload?: void
+ ) => {
+ errorCounts: SpanErrorCounts
+ payload?: void
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface spanErrorsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ sessionIdByRow: (
+ listRows: Span[],
+ configuredSessionIdKeys: string[] | undefined,
+ sessionErrorBadgesEnabled: boolean
+ ) => Map<string, string>
+ errorBadgeByRow: (
+ listRows: Span[],
+ sessionIdByRow: Map<string, string>,
+ errorCounts: SpanErrorCounts
+ ) => Map<string, SpanErrorBadge>
+ }
+}
+
+export type spanErrorsLogicType = MakeLogicType<
+ spanErrorsLogicValues,
+ spanErrorsLogicActions,
+ SpanErrorsLogicProps,
+ spanErrorsLogicMeta
+>
+
+const EMPTY_COUNTS: SpanErrorCounts = { trace: {}, span: {}, session: {} }
+
+function distinct(ids: (string | null)[]): string[] {
+ return Array.from(new Set(ids.filter((id): id is string => !!id)))
+}
+
+// hasOwn, not `in`, because `in` walks the prototype chain, so an id that collides with an Object
+// member would read as answered.
+function unanswered(ids: (string | null)[], known: Record<string, number>): string[] {
+ return distinct(ids).filter((id) => !Object.hasOwn(known, id))
+}
+
+// Every id looked up lands a count even when it is zero, which is what stops the next page asking
+// about it again.
+function seedZeros(ids: string[]): Record<string, number> {
+ return Object.fromEntries(ids.map((id) => [id, 0]))
+}
+
+function exactCountsFor(span: Span, counts: ExactCounts): { spanCount: number; traceCount: number } {
+ const spanId = usableId(span.span_id)
+ const traceId = usableId(span.trace_id)
+ return {
+ spanCount: spanId ? (counts.span[spanId] ?? 0) : 0,
+ traceCount: traceId ? (counts.trace[traceId] ?? 0) : 0,
+ }
+}
+
+/** Counts keyed on the ids the rows carry, which name the span or the request that threw. */
+async function lookUpExactCounts(rows: Span[], known: SpanErrorCounts, teamId: number): Promise<ExactCounts> {
+ const exact: ExactCounts = { trace: { ...known.trace }, span: { ...known.span } }
+ // A row needs the lookup while either of its ids is unanswered. Chunking by row rather than by
+ // id keeps a span and the trace it belongs to in the same request, which the endpoint requires:
+ // a span id is only unique in its trace.
+ const exactRows = rows.filter((span) => {
+ const traceId = usableId(span.trace_id)
+ // Without a trace id neither tier can answer: the endpoint needs one, and a span id alone
+ // is ambiguous across traces. Such a row would otherwise never be recorded as looked up,
+ // so every later page would ask about it again.
+ if (!traceId) {
+ return false
+ }
+ const spanId = usableId(span.span_id)
+ return !Object.hasOwn(known.trace, traceId) || (!!spanId && !Object.hasOwn(known.span, spanId))
+ })
+ if (exactRows.length === 0) {
+ return exact
+ }
+ // Only the rows this query asks about set the range. Taking every loaded row instead would
+ // widen it with each page and re-scan the time the earlier pages already covered.
+ const range = traceErrorsWindow(exactRows.map((span) => span.timestamp))
+ if (!range) {
+ return exact
+ }
+
+ // The endpoint, not a HogQL query from here, because it checks the caller's Error Tracking
+ // access before it answers.
+ const asks = chunk(exactRows, MAX_IDS_PER_LOOKUP).map((rowChunk) => ({
+ traceIds: distinct(rowChunk.map((span) => usableId(span.trace_id))),
+ spanIds: distinct(rowChunk.map((span) => usableId(span.span_id))),
+ }))
+ const responses = await Promise.all(
+ asks.map((ask) =>
+ tracingSpansErrorCountsCreate(String(teamId), {
+ ...ask,
+ dateFrom: range.date_from,
+ dateTo: range.date_to,
+ }).catch(() => null)
+ )
+ )
+
+ asks.forEach((ask, index) => {
+ const response = responses[index]
+ if (!response) {
+ return
+ }
+ // Only the ids this run had no answer for. The rest rode along to scope the span match, and
+ // their counts were measured over their own page's window, so this narrower one must not
+ // overwrite them.
+ const freshTraces = new Set(unanswered(ask.traceIds, known.trace))
+ const freshSpans = new Set(unanswered(ask.spanIds, known.span))
+ Object.assign(exact.trace, seedZeros([...freshTraces]))
+ Object.assign(exact.span, seedZeros([...freshSpans]))
+ for (const { trace_id, exceptions } of response.traceResults) {
+ if (freshTraces.has(trace_id)) {
+ exact.trace[trace_id] = exceptions
+ }
+ }
+ for (const { span_id, exceptions } of response.spanResults) {
+ if (freshSpans.has(span_id)) {
+ exact.span[span_id] = exceptions
+ }
+ }
+ })
+ return exact
+}
+
+/**
+ * Every row's session, not only the rows the exact lookup left blank. One exception carrying a
+ * trace id is enough to answer a row, which would hide the rest of its session from an SDK that
+ * stamps none. Only `posthog-python` stamps them today, so mixed traces are the normal case.
+ */
+async function lookUpSessionCounts(
+ rows: Span[],
+ known: SpanErrorCounts,
+ sessionIdByRow: Map<string, string>,
+ teamId: number
+): Promise<Record<string, number>> {
+ const askSessionIds = unanswered(
+ rows.map((span) => sessionIdByRow.get(span.uuid) ?? null),
+ known.session
+ )
+ if (askSessionIds.length === 0) {
+ return {}
+ }
+ const asked = new Set(askSessionIds)
+ const range = sessionErrorsWindow(
+ rows
+ .filter((span) => {
+ const sessionId = sessionIdByRow.get(span.uuid)
+ return !!sessionId && asked.has(sessionId)
+ })
+ .map((span) => span.timestamp)
+ )
+ if (!range) {
+ return {}
+ }
+
+ // One request per cap-sized chunk, all in flight together, so a page with more sessions than
+ // one request allows is answered in one run rather than one chunk per debounce.
+ const responses = await Promise.all(
+ chunk(askSessionIds, MAX_IDS_PER_LOOKUP).map((idChunk) =>
+ tracingSpansErrorCountsCreate(String(teamId), {
+ sessionIds: idChunk,
+ dateFrom: range.date_from,
+ dateTo: range.date_to,
+ }).catch(() => null)
+ )
+ )
+
+ const counts = seedZeros(askSessionIds)
+ for (const response of responses) {
+ if (!response) {
+ continue
+ }
+ for (const { session_id, exceptions } of response.sessionResults) {
+ if (Object.hasOwn(counts, session_id)) {
+ counts[session_id] = exceptions
+ }
+ }
+ }
+ return counts
+}
+
+// Three joins, in falling order of confidence. An exception from an SDK that propagated the trace
+// context carries `$trace_id` and `$span_id`, which names the span that threw. Without those the
+// only join left is the session the span belongs to plus a time window, which is co-occurring
+// evidence rather than a cause, so the badge says something weaker for it.
+//
+// Only exceptions error tracking linked to an issue count: an event with no issue id failed
+// ingestion parsing, so the Errors tab this badge opens can never list it. The two still disagree
+// at the edges, because the tab anchors its window to the open trace rather than the whole page,
+// caps at 100 issues, and resolves issues through fingerprint state this query cannot see.
+export const spanErrorsLogic = kea<spanErrorsLogicType>([
+ props({ id: TRACING_SCENE_VIEWER_ID } as SpanErrorsLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'tracing', 'frontend', 'spanErrorsLogic', key]),
+
+ connect(({ id }: SpanErrorsLogicProps) => ({
+ values: [
+ tracingDataLogic({ id }),
+ ['listRows'],
+ tracingCorrelationConfigLogic,
+ ['configuredSessionIdKeys', 'sessionErrorBadgesEnabled'],
+ teamLogic,
+ ['currentTeamId'],
+ ],
+ actions: [
+ tracingDataLogic({ id }),
+ ['fetchSpansSuccess', 'fetchNextPageSuccess'],
+ tracingCorrelationConfigLogic,
+ ['loadTracingConfigSuccess'],
+ ],
+ })),
+
+ loaders(({ values }) => ({
+ errorCounts: [
+ EMPTY_COUNTS,
+ {
+ loadErrorCounts: async (_: void, breakpoint): Promise<SpanErrorCounts> => {
+ // Wait first, so a lookup a faster page supersedes pays for none of the work
+ // below. Everything after this reads one snapshot, which keeps the ids and the
+ // range in agreement.
+ await breakpoint(LOOKUP_DEBOUNCE_MS)
+
+ const known = values.errorCounts
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ return known
+ }
+ const rows = values.listRows
+
+ // Both lookups read the same snapshot and neither needs the other's answer, so
+ // they go out together rather than one after the other.
+ //
+ // A failure in either is swallowed because the badge is decoration on a list
+ // that stays useful without it, and a toast would repeat on every page. The ids
+ // stay unanswered, so the next page asks again.
+ const [exact, session] = await Promise.all([
+ lookUpExactCounts(rows, known, teamId),
+ lookUpSessionCounts(rows, known, values.sessionIdByRow, teamId),
+ ])
+ breakpoint()
+
+ return { ...known, ...exact, session: { ...known.session, ...session } }
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ errorCounts: {
+ // A fresh page answers different filters, so the counts stop applying the moment it
+ // lands. Clearing here rather than inside the lookup keeps that true even when a next
+ // page supersedes the lookup before its debounce elapses.
+ fetchSpansSuccess: () => EMPTY_COUNTS,
+ },
+ }),
+
+ selectors({
+ sessionIdByRow: [
+ (s) => [s.listRows, s.configuredSessionIdKeys, s.sessionErrorBadgesEnabled],
+ (
+ listRows: Span[],
+ configuredSessionIdKeys: string[] | undefined,
+ sessionErrorBadgesEnabled: boolean
+ ): Map<string, string> => {
+ // The scan reads every attribute of every loaded row, so it must not run for a
+ // team that does not have the badges.
+ if (!sessionErrorBadgesEnabled) {
+ return NO_SESSIONS
+ }
+ const byRow = new Map<string, string>()
+ for (const span of listRows) {
+ // One row at a time, not the trace's other loaded spans: the list prefetches a
+ // capped number of spans per trace, so scanning them could resolve a session
+ // that a span still to load contradicts.
+ const sessionId = resolveSpanSessionId(span, configuredSessionIdKeys)
+ if (sessionId) {
+ byRow.set(span.uuid, sessionId)
+ }
+ }
+ return byRow
+ },
+ ],
+
+ // What each row badges, and on which join. A row is absent until one of its ids is looked
+ // up and comes back with exceptions, so an absent row is never a claim that it is clean.
+ errorBadgeByRow: [
+ (s) => [s.listRows, s.sessionIdByRow, s.errorCounts],
+ (
+ listRows: Span[],
+ sessionIdByRow: Map<string, string>,
+ errorCounts: SpanErrorCounts
+ ): Map<string, SpanErrorBadge> => {
+ const byRow = new Map<string, SpanErrorBadge>()
+ for (const span of listRows) {
+ const { spanCount, traceCount } = exactCountsFor(span, errorCounts)
+ const sessionId = sessionIdByRow.get(span.uuid)
+ const sessionCount = sessionId ? (errorCounts.session[sessionId] ?? 0) : 0
+ // One chain, so the tier and the count it names cannot drift apart.
+ const match =
+ spanCount > 0
+ ? { tier: 'span' as const, count: spanCount }
+ : traceCount > 0
+ ? { tier: 'trace' as const, count: traceCount }
+ : sessionCount > 0
+ ? { tier: 'session' as const, count: sessionCount }
+ : null
+ if (!match) {
+ continue
+ }
+ // The narrower tier stays the label, because it names what threw. The two
+ // counts are never compared, for the reason on `alsoInSession`.
+ byRow.set(
+ span.uuid,
+ match.tier !== 'session' && sessionCount > 0 ? { ...match, alsoInSession: sessionCount } : match
+ )
+ }
+ return byRow
+ },
+ ],
+ }),
+
+ listeners(({ actions, values }) => {
+ // Either way the lookup asks only about ids with no count yet. A fresh page has none,
+ // because the reducer above cleared them.
+ const lookUpNewIds = (): void => {
+ if (values.sessionErrorBadgesEnabled) {
+ actions.loadErrorCounts()
+ }
+ }
+ return {
+ fetchSpansSuccess: lookUpNewIds,
+ fetchNextPageSuccess: lookUpNewIds,
+ // The configured session keys can land after the first page. Rows that resolved no
+ // session under the built-in keys may resolve one now, and no page event follows.
+ loadTracingConfigSuccess: lookUpNewIds,
+ }
+ }),
+])
diff --git a/products/tracing/frontend/traceIdentity.ts b/products/tracing/frontend/traceIdentity.ts
index f51fee591925..3a04496ae2ae 100644
--- a/products/tracing/frontend/traceIdentity.ts
+++ b/products/tracing/frontend/traceIdentity.ts
@@ -50,6 +50,18 @@ export function resolveTraceIdentity(
}
return {
distinctId: singleValueAcrossSpans(spans, getDistinctIdWithKey, configuredDistinctIdKeys),
- sessionId: singleValueAcrossSpans(spans, getSessionIdWithKey, configuredSessionIdKeys),
+ sessionId: resolveTraceSessionId(spans, configuredSessionIdKeys),
}
}
+
+// The session half on its own, for callers that need no person. It keeps the same
+// disagreement rule as `resolveTraceIdentity`, so both surfaces resolve one session or none.
+export function resolveTraceSessionId(spans: Span[], configuredSessionIdKeys: string[] | undefined): string | null {
+ return singleValueAcrossSpans(spans, getSessionIdWithKey, configuredSessionIdKeys)
+}
+
+// One span's session, for a caller that answers a row rather than a whole trace. A single span
+// carries at most one session, so there is nothing here for the disagreement rule to decide.
+export function resolveSpanSessionId(span: Span, configuredSessionIdKeys: string[] | undefined): string | null {
+ return getSessionIdWithKey(span.attributes, span.resource_attributes, configuredSessionIdKeys)?.value ?? null
+}
diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.ts
index 16c39000cb4f..372b2d92126b 100644
--- a/products/tracing/frontend/traceLinks.ts
+++ b/products/tracing/frontend/traceLinks.ts
@@ -46,10 +46,15 @@ export function tracingUrlForService(serviceName: string, { dateRange }: { dateR
}).url
}
+/** The product's docs, linked from the empty states and from surfaces that need instrumenting. */
+export const TRACING_DOCS_URL = 'https://posthog.com/docs/tracing'
+
/** The window a `ts`-hinted cold load queries: ±1h is generous for any single trace's spans. */
+export const TRACE_LOOKUP_WINDOW_HOURS = 1
+
export function traceLookupDateRange(ts: string): { date_from: string; date_to: string } {
return {
- date_from: dayjs(ts).subtract(1, 'hour').toISOString(),
- date_to: dayjs(ts).add(1, 'hour').toISOString(),
+ date_from: dayjs(ts).subtract(TRACE_LOOKUP_WINDOW_HOURS, 'hour').toISOString(),
+ date_to: dayjs(ts).add(TRACE_LOOKUP_WINDOW_HOURS, 'hour').toISOString(),
}
}
diff --git a/products/tracing/frontend/tracingCorrelationConfigLogic.ts b/products/tracing/frontend/tracingCorrelationConfigLogic.ts
index e002315f166c..59e0abb6fa69 100644
--- a/products/tracing/frontend/tracingCorrelationConfigLogic.ts
+++ b/products/tracing/frontend/tracingCorrelationConfigLogic.ts
@@ -1,11 +1,15 @@
-import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'
+import { MakeLogicType, connect, kea, path, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
import type { PatchedTeamTracingConfigApi, TeamTracingConfigApi } from 'products/tracing/frontend/generated/api.schemas'
// Mirrors the backend defaults in products/tracing/backend/models.py — the same convention
@@ -23,7 +27,9 @@ export interface tracingCorrelationConfigLogicValues {
currentTeamId: number | null // teamLogic
configuredDistinctIdKeys: string[] | undefined
configuredSessionIdKeys: string[] | undefined
+ correlationConfigNeeded: boolean
correlationLinksEnabled: boolean
+ sessionErrorBadgesEnabled: boolean
tracingConfig: TeamTracingConfigApi | null
tracingConfigLoading: boolean
}
@@ -68,6 +74,8 @@ export interface tracingCorrelationConfigLogicMeta {
configuredDistinctIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefined
configuredSessionIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefined
correlationLinksEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ sessionErrorBadgesEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ correlationConfigNeeded: (correlationLinksEnabled: boolean, sessionErrorBadgesEnabled: boolean) => boolean
}
}
@@ -121,11 +129,34 @@ export const tracingCorrelationConfigLogic = kea<tracingCorrelationConfigLogicTy
(s) => [s.featureFlags],
(featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS],
],
+ // Single owner of the "badge spans whose session hit errors?" rule, for the span list
+ // badge and the trace drawer's Errors tab. Error Tracking viewer access is required as well
+ // as the flag, because the counts and the issues are that product's data. The endpoints
+ // behind both refuse a caller without it, so this gate is what keeps those surfaces from
+ // rendering a refusal as an error state.
+ sessionErrorBadgesEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean =>
+ !!featureFlags[FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES] &&
+ userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer),
+ ],
+ // This config only feeds correlation surfaces, so it is only worth a request when one of
+ // them is on. The error badges resolve a session from the same configured keys, so a team
+ // that renamed those keys needs the config loaded for the badges alone.
+ correlationConfigNeeded: [
+ (s) => [s.correlationLinksEnabled, s.sessionErrorBadgesEnabled],
+ (correlationLinksEnabled: boolean, sessionErrorBadgesEnabled: boolean): boolean =>
+ correlationLinksEnabled || sessionErrorBadgesEnabled,
+ ],
}),
- afterMount(({ actions, values }) => {
- // This config only feeds correlation links, so skip the request when they are off.
- if (values.correlationLinksEnabled) {
- actions.loadTracingConfig()
- }
- }),
+ subscriptions(({ actions, values }) => ({
+ // A subscription rather than afterMount, because posthog-js can resolve the flags after
+ // this logic mounts. Reading them once would leave the configured keys unloaded, and
+ // session detection would silently fall back to the built-in convention list.
+ correlationConfigNeeded: (needed: boolean) => {
+ if (needed && !values.tracingConfig && !values.tracingConfigLoading) {
+ actions.loadTracingConfig()
+ }
+ },
+ })),
])
diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.ts
index 7882844a1df6..5e1097ea3a49 100644
--- a/products/tracing/frontend/tracingSceneLogic.ts
+++ b/products/tracing/frontend/tracingSceneLogic.ts
@@ -16,6 +16,9 @@ import type { AggregatedSpanRow, DateRange, SpanTreeNode } from '../../../fronte
import type { UniversalFiltersGroup } from '../../../frontend/src/types'
import type { TracingDurationHistogramData, VisibleDurationRange } from './durationBuckets'
import type { TracingLatencyHeatmapData } from './durationBuckets'
+import type { ErrorScope } from './errorCorrelation'
+import { spanErrorsLogic } from './spanErrorsLogic'
+import type { SpanErrorBadge } from './spanErrorsLogic'
import type { TraceIdentity } from './traceIdentity'
import { tracingDataLogic } from './tracingDataLogic'
import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'
@@ -42,7 +45,7 @@ import type {
TracingViewMode,
} from './tracingFiltersLogic'
import { tracingViewerLogic } from './tracingViewerLogic'
-import type { Span } from './types'
+import type { Span, SpanInspectorTab } from './types'
/** What each result row represents: a trace (its root span), an individual span, or an operation aggregate. */
export type TracingDisplayMode = TracingViewMode | 'operations'
@@ -50,6 +53,7 @@ export type TracingDisplayMode = TracingViewMode | 'operations'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface tracingSceneLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
+ errorBadgeByRow: Map<string, SpanErrorBadge> // spanErrorsLogic
aggregation: {
current: AggregatedSpanRow[]
previous: AggregatedSpanRow[] | null
@@ -93,13 +97,17 @@ export interface tracingSceneLogicValues {
canLoadMoreTraceSpans: boolean // tracingViewerLogic
compareFlameServiceName: string | null // tracingViewerLogic
compareFlameSpanName: string | null // tracingViewerLogic
+ errorsScope: ErrorScope | null // tracingViewerLogic
+ inspectorTab: SpanInspectorTab // tracingViewerLogic
isLoadingFullTrace: boolean // tracingViewerLogic
isTraceOpen: boolean // tracingViewerLogic
openTraceSpans: Span[] // tracingViewerLogic
selectedSpanId: string | null // tracingViewerLogic
selectedTraceId: string | null // tracingViewerLogic
selectedTraceTs: string | null // tracingViewerLogic
+ sessionErrorBadgesEnabled: boolean // tracingViewerLogic
traceIdentity: TraceIdentity // tracingViewerLogic
+ traceSessionId: string | null // tracingViewerLogic
activeTracingTab: 'operations' | 'traces'
breadcrumbs: Breadcrumb[]
displayMode: TracingDisplayMode
@@ -219,15 +227,22 @@ export interface tracingSceneLogicActions {
traceId: string,
options?:
| {
+ errorsScope?: ErrorScope | null
spanId?: string | null
+ tab?: SpanInspectorTab | null
ts?: string | null
}
| undefined
) => {
+ errorsScope: ErrorScope | null
spanId: string | null
+ tab: SpanInspectorTab | null
traceId: string
ts: string | null
} // tracingViewerLogic
+ selectInspectorTab: (tab: SpanInspectorTab) => {
+ tab: SpanInspectorTab
+ } // tracingViewerLogic
selectSpan: (spanId: string | null) => {
spanId: string | null
} // tracingViewerLogic
@@ -301,6 +316,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
],
tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),
['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs', 'compareActive'],
+ spanErrorsLogic({ id: TRACING_SCENE_VIEWER_ID }),
+ ['errorBadgeByRow'],
tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
[
'selectedTraceId',
@@ -309,6 +326,10 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'isTraceOpen',
'openTraceSpans',
'traceIdentity',
+ 'traceSessionId',
+ 'sessionErrorBadgesEnabled',
+ 'inspectorTab',
+ 'errorsScope',
'isLoadingFullTrace',
'canLoadMoreTraceSpans',
'compareFlameSpanName',
@@ -341,7 +362,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([
'setFilters',
],
tracingViewerLogic({ id: TRACING_SCENE_VIEWER_ID }),
- ['openTrace', 'selectSpan', 'closeTrace', 'openCompareFlame', 'closeCompareFlame'],
+ ['openTrace', 'selectSpan', 'selectInspectorTab', 'closeTrace', 'openCompareFlame', 'closeCompareFlame'],
featureFlagLogic,
['setFeatureFlags'],
],
diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.ts
index bca371c85970..f53919168522 100644
--- a/products/tracing/frontend/tracingViewerLogic.test.ts
+++ b/products/tracing/frontend/tracingViewerLogic.test.ts
@@ -5,6 +5,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
import { makeSpan } from './__mocks__/span'
import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
@@ -16,6 +17,13 @@ describe('tracingViewerLogic', () => {
let getTraceSpy: jest.SpyInstance
beforeEach(() => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.ErrorTracking]: AccessControlLevel.Viewer,
+ },
+ } as AppContext
initKeaTests()
getTraceSpy = jest
.spyOn(api.tracing, 'getTrace')
@@ -49,7 +57,7 @@ describe('tracingViewerLogic', () => {
expect(getTraceSpy.mock.calls.length > 0).toBe(shouldFetch)
})
- describe('traceIdentity', () => {
+ 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.
beforeEach(() => {
@@ -110,6 +118,69 @@ describe('tracingViewerLogic', () => {
expect(logic.values.canLoadMoreTraceSpans).toBe(true)
expect(logic.values.traceIdentity).toEqual({ distinctId: null, sessionId: null })
})
+
+ // The Errors tab needs the session without the person, so it follows the error badge flag.
+ // Reading the person flag instead would leave the tab empty on a team that has only badges.
+ it.each([
+ ['the error badge flag', FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES, 'session-1'],
+ ['the person and replay flag', FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS, null],
+ ])('resolves traceSessionId under %s', (_name, flag, expected) => {
+ featureFlagLogic.actions.setFeatureFlags([flag], { [flag]: true })
+
+ openCompleteTrace({ posthogDistinctId: 'user-1', sessionId: 'session-1' })
+
+ expect(logic.values.traceSessionId).toBe(expected)
+ })
+
+ // A badge sits on one row and resolves that row's session. A trace touching two sessions
+ // must therefore still answer for the row the badge opened, or clicking a row that just
+ // showed a count lands on a tab saying the trace has no session. The full-trace fetch
+ // returns the earliest page of a large trace, so the anchored row can be missing from it
+ // while it still sits in the list the badge was clicked in.
+ it.each([
+ ['the prefetched list', false],
+ ['the list when the fetched trace page omits it', true],
+ ])('resolves traceSessionId from the anchored span in %s', (_name, tracePageOmitsAnchor) => {
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES], {
+ [FEATURE_FLAGS.TRACING_SPAN_ERROR_BADGES]: true,
+ })
+ const spanA = makeSpan({
+ uuid: 'span-0',
+ span_id: 'span-0',
+ trace_id: 'trace-x',
+ attributes: { sessionId: 'a' },
+ })
+ const spanB = makeSpan({
+ uuid: 'span-1',
+ span_id: 'span-1',
+ trace_id: 'trace-x',
+ attributes: { sessionId: 'b' },
+ })
+ tracingDataLogic().actions.fetchSpansSuccess([spanA, spanB])
+
+ logic.actions.openTrace('trace-x', { spanId: 'span-1', ts: '2024-01-01T00:00:00Z' })
+ if (tracePageOmitsAnchor) {
+ tracingDataLogic().actions.loadTraceSpansSuccess([spanA])
+ }
+
+ expect(logic.values.traceSessionId).toBe('b')
+ })
+ })
+
+ // The drawer stays mounted from one row to the next, so a person reading the Logs tab row by
+ // row must not be bounced back to Attributes on every click.
+ it('keeps the inspector tab across traces while the drawer is open, and resets it on close', () => {
+ logic.actions.openTrace('trace-x')
+ logic.actions.selectInspectorTab('logs')
+
+ logic.actions.openTrace('trace-y')
+ expect(logic.values.inspectorTab).toBe('logs')
+
+ logic.actions.openTrace('trace-z', { tab: 'errors' })
+ expect(logic.values.inspectorTab).toBe('errors')
+
+ logic.actions.closeTrace()
+ expect(logic.values.inspectorTab).toBe('attributes')
})
describe('closeTrace', () => {
diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.ts
index b928c4454783..ce1b1a1b2f5e 100644
--- a/products/tracing/frontend/tracingViewerLogic.ts
+++ b/products/tracing/frontend/tracingViewerLogic.ts
@@ -1,12 +1,19 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
-import { EMPTY_TRACE_IDENTITY, resolveTraceIdentity, type TraceIdentity } from './traceIdentity'
+import type { ErrorScope } from './errorCorrelation'
+import {
+ EMPTY_TRACE_IDENTITY,
+ resolveSpanSessionId,
+ resolveTraceIdentity,
+ resolveTraceSessionId,
+ type TraceIdentity,
+} from './traceIdentity'
import { tracingCorrelationConfigLogic } from './tracingCorrelationConfigLogic'
import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'
import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'
import type { OverlayWindow } from './tracingFiltersLogic'
-import type { Span } from './types'
+import type { Span, SpanInspectorTab } from './types'
export interface TracingViewerLogicProps {
id: string
@@ -17,6 +24,7 @@ export interface tracingViewerLogicValues {
configuredDistinctIdKeys: string[] | undefined // tracingCorrelationConfigLogic
configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic
correlationLinksEnabled: boolean // tracingCorrelationConfigLogic
+ sessionErrorBadgesEnabled: boolean // tracingCorrelationConfigLogic
spans: Span[] // tracingDataLogic
traceSpans: Span[] // tracingDataLogic
traceSpansHasMore: boolean // tracingDataLogic
@@ -26,6 +34,8 @@ export interface tracingViewerLogicValues {
canLoadMoreTraceSpans: boolean
compareFlameServiceName: string | null
compareFlameSpanName: string | null
+ errorsScope: ErrorScope | null
+ inspectorTab: SpanInspectorTab
isLoadingFullTrace: boolean
isTraceOpen: boolean
openTraceSpans: Span[]
@@ -33,6 +43,7 @@ export interface tracingViewerLogicValues {
selectedTraceId: string | null
selectedTraceTs: string | null
traceIdentity: TraceIdentity
+ traceSessionId: string | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -81,14 +92,21 @@ export interface tracingViewerLogicActions {
openTrace: (
traceId: string,
options?: {
+ errorsScope?: ErrorScope | null
spanId?: string | null
+ tab?: SpanInspectorTab | null
ts?: string | null
}
) => {
+ errorsScope: ErrorScope | null
spanId: string | null
+ tab: SpanInspectorTab | null
traceId: string
ts: string | null
}
+ selectInspectorTab: (tab: SpanInspectorTab) => {
+ tab: SpanInspectorTab
+ }
selectSpan: (spanId: string | null) => {
spanId: string | null
}
@@ -114,6 +132,13 @@ export interface tracingViewerLogicMeta {
configuredSessionIdKeys: string[] | undefined,
correlationLinksEnabled: boolean
) => TraceIdentity
+ traceSessionId: (
+ openTraceSpans: Span[],
+ spans: Span[],
+ selectedSpanId: string | null,
+ configuredSessionIdKeys: string[] | undefined,
+ sessionErrorBadgesEnabled: boolean
+ ) => string | null
}
}
@@ -139,7 +164,12 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
tracingFiltersLogic({ id }),
['hasDeferredFilterRefresh'],
tracingCorrelationConfigLogic,
- ['configuredDistinctIdKeys', 'configuredSessionIdKeys', 'correlationLinksEnabled'],
+ [
+ 'configuredDistinctIdKeys',
+ 'configuredSessionIdKeys',
+ 'correlationLinksEnabled',
+ 'sessionErrorBadgesEnabled',
+ ],
],
actions: [
tracingDataLogic({ id }),
@@ -150,11 +180,22 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
})),
actions({
- openTrace: (traceId: string, options?: { spanId?: string | null; ts?: string | null }) => ({
+ openTrace: (
+ traceId: string,
+ options?: {
+ spanId?: string | null
+ ts?: string | null
+ tab?: SpanInspectorTab | null
+ errorsScope?: ErrorScope | null
+ }
+ ) => ({
traceId,
spanId: options?.spanId ?? null,
ts: options?.ts ?? null,
+ tab: options?.tab ?? null,
+ errorsScope: options?.errorsScope ?? null,
}),
+ selectInspectorTab: (tab: SpanInspectorTab) => ({ tab }),
selectSpan: (spanId: string | null) => ({ spanId }),
closeTrace: true,
openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),
@@ -186,6 +227,28 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
closeTrace: () => null,
},
],
+ // Which inspector tab the drawer shows. It lives here rather than in the drawer so a
+ // caller can open a trace straight onto a tab, which the span list's error badge does.
+ // Deliberately not a URL param, unlike the trace and span the drawer opens on. A shared
+ // link carries which trace to read, and the reader picks their own tab from there, so a
+ // reload lands on Attributes by design. Opening another trace while the drawer is up
+ // keeps the tab, so a person reading the Logs tab row by row stays on it.
+ // The scope the Errors tab opens on, when the caller named one.
+ errorsScope: [
+ null as ErrorScope | null,
+ {
+ openTrace: (_, { errorsScope }) => errorsScope,
+ closeTrace: () => null,
+ },
+ ],
+ inspectorTab: [
+ 'attributes' as SpanInspectorTab,
+ {
+ openTrace: (state, { tab }) => tab ?? state,
+ closeTrace: () => 'attributes',
+ selectInspectorTab: (_, { tab }) => tab,
+ },
+ ],
compareFlameSpanName: [
null as string | null,
{
@@ -254,18 +317,61 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([
configuredSessionIdKeys: string[] | undefined,
correlationLinksEnabled: boolean
): TraceIdentity => {
- // Both guards run before the scan, which reads every attribute of every span.
+ // The flag guard runs before the scan, which reads every attribute of every span.
if (!correlationLinksEnabled) {
return EMPTY_TRACE_IDENTITY
}
- // A second, conflicting identity may sit on a page that has not loaded yet, and
- // the prefetch fallback on screen during the first fetch may itself be truncated.
+ // Nothing while more spans can arrive, because a second, conflicting identity may
+ // sit on a page that has not loaded, and the prefetch fallback shown during the
+ // first fetch may itself be truncated.
if (canLoadMoreTraceSpans || traceSpansLoading) {
return EMPTY_TRACE_IDENTITY
}
return resolveTraceIdentity(openTraceSpans, configuredDistinctIdKeys, configuredSessionIdKeys)
},
],
+ // The open trace's session for the Errors tab, which needs no person. It follows the badge
+ // flag rather than the person and replay one, so the tab works for a team that has only the
+ // badges. The gate also keeps the span scan off a team that has neither.
+ //
+ // It reads every span loaded so far, rather than waiting for a complete trace the way
+ // `traceIdentity` does. A large trace pages in as the user scrolls the waterfall, and
+ // waiting would leave the tab loading indefinitely. The badge that opens this tab already
+ // resolves from one row, so the stricter rule would also make the two disagree. A later
+ // page that carries a second session withdraws the answer rather than keeping a wrong one.
+ traceSessionId: [
+ (s) => [
+ s.openTraceSpans,
+ s.spans,
+ s.selectedSpanId,
+ s.configuredSessionIdKeys,
+ s.sessionErrorBadgesEnabled,
+ ],
+ (
+ openTraceSpans: Span[],
+ spans: Span[],
+ selectedSpanId: string | null,
+ configuredSessionIdKeys: string[] | undefined,
+ sessionErrorBadgesEnabled: boolean
+ ): string | null => {
+ if (!sessionErrorBadgesEnabled) {
+ return null
+ }
+ // The anchored span first, because a badge click opens the drawer on the row the
+ // user pressed. Reading the whole trace instead would answer null for a trace that
+ // touches two sessions, so a row that just showed a count would open a tab saying
+ // the trace has no session.
+ //
+ // The full-trace fetch returns the earliest page of a large trace, which can omit
+ // the anchored span. The row the user pressed is still in the list, so fall back to
+ // it rather than resolving from a page that may carry another session.
+ const findAnchored = (candidates: Span[]): Span | null =>
+ selectedSpanId ? (candidates.find((span) => span.span_id === selectedSpanId) ?? null) : null
+ const anchored = findAnchored(openTraceSpans) ?? findAnchored(spans)
+ const anchoredSessionId = anchored ? resolveSpanSessionId(anchored, configuredSessionIdKeys) : null
+ return anchoredSessionId ?? resolveTraceSessionId(openTraceSpans, configuredSessionIdKeys)
+ },
+ ],
}),
listeners(({ actions, values }) => ({
diff --git a/products/tracing/frontend/types.ts b/products/tracing/frontend/types.ts
index 1e0e000fcb78..d8070a7973a2 100644
--- a/products/tracing/frontend/types.ts
+++ b/products/tracing/frontend/types.ts
@@ -35,3 +35,7 @@ export const STATUS_CODE_LABELS: Record<number, { label: string; type: 'success'
1: { label: 'OK', type: 'success' },
2: { label: 'Error', type: 'danger' },
}
+
+// The trace drawer's inspector tabs. Query, Metrics and Errors are conditional, so the active tab
+// can point at a tab the drawer is not currently rendering.
+export type SpanInspectorTab = 'attributes' | 'query' | 'logs' | 'metrics' | 'errors' | 'raw'
diff --git a/products/tracing/mcp/tools.yaml b/products/tracing/mcp/tools.yaml
index f090b8c05f55..e317a6224bac 100644
--- a/products/tracing/mcp/tools.yaml
+++ b/products/tracing/mcp/tools.yaml
@@ -227,6 +227,9 @@ tools:
response:
include:
- results
+ tracing-spans-error-counts-create:
+ operation: tracing_spans_error_counts_create
+ enabled: false
tracing-spans-has-spans-retrieve:
operation: tracing_spans_has_spans_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a21ae2c01e94..eed93986064d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -101364,6 +101364,58 @@ export namespace Schemas {
query: _TracingDurationHistogramQueryBody;
}
+ export interface _TracingErrorCountsRequest {
+ /**
+ * Hex trace IDs to count exceptions for, matched against the exception's `$trace_id` property. Case insensitive. At most 200 per request.
+ * @maxItems 200
+ */
+ traceIds?: string[];
+ /**
+ * Hex span IDs to count exceptions for, matched against the exception's `$span_id` property. Only counted within the requested traces, so `traceIds` is required alongside. At most 200 per request.
+ * @maxItems 200
+ */
+ spanIds?: string[];
+ /**
+ * Session IDs to count exceptions for. The fallback for exceptions that carry no trace ID. At most 200 per request.
+ * @maxItems 200
+ */
+ sessionIds?: string[];
+ /** Start of the window the exceptions must fall in. ISO 8601. */
+ dateFrom: string;
+ /** End of the window the exceptions must fall in. ISO 8601. */
+ dateTo: string;
+ }
+
+ export interface _TracingTraceErrorCount {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number;
+ /** The trace the exceptions belong to, lowercase hex. */
+ trace_id: string;
+ }
+
+ export interface _TracingSpanErrorCount {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number;
+ /** The span the exceptions belong to, lowercase hex. */
+ span_id: string;
+ }
+
+ export interface _TracingSessionErrorCount {
+ /** Exception events in the window that error tracking linked to an issue. */
+ exceptions: number;
+ /** The session the exceptions belong to. */
+ session_id: string;
+ }
+
+ export interface _TracingErrorCountsResponse {
+ /** One entry per requested trace that had exceptions. Traces with none are omitted. */
+ traceResults: _TracingTraceErrorCount[];
+ /** One entry per requested span that had exceptions. Spans with none are omitted. */
+ spanResults: _TracingSpanErrorCount[];
+ /** One entry per requested session that had exceptions. Sessions with none are omitted. */
+ sessionResults: _TracingSessionErrorCount[];
+ }
+
export interface _TracingImpactRequest {
/** The impact query to execute. Takes the same filters as the count query. */
query: _TracingCountBody;