:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): link an exception to its trace (#116829)
Paul D'Ambraa484286cfd37
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cc30fb8467de..1b0a250c008e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3085,9 +3085,9 @@ snapshots:errortracking-exceptioncard--exception-card-header-widths--light:hash: v1.k794b7964.96ab37bc32797721d97410925e8c89bf739322a340ff8ee62dbd014a139a7f59.HCV39CI_4XqbwUW8QD8DDxSw_CeL5cui9smBv0MDeY0errortracking-exceptioncard--exception-card-header-widths-with-action--dark:- hash: v1.k794b7964.d573c7881713d67ef1a7dc960fd33c48212b432d655fdd88bf41930c75d00b8b.Hq0oLw33s_BJHtZ4VmLPD0SCZ7xmP8glZGkjfy7remc+ hash: v1.k794b7964.bc431c91e3d2c75733228cba7ea49100187653303d32b80972691c1bd2ab6fac.5G8_BH_wEQ7-bX_fxoUS_bpIhFYn-ntOg1O0QogN5_Yerrortracking-exceptioncard--exception-card-header-widths-with-action--light:- hash: v1.k794b7964.fa3926467438994babfeb859e507aa4071b0489654e5a9151e856b3fc6695459.WmIqn8c1cmv9lbViVkzoqkrA6UF08Z-BkInlJIBINNM+ hash: v1.k794b7964.1598db8976260f58899c06bc626c642404efefabadcb1f72c58e8274f9c2cc59.j9p2UZEipMzh2BffOz6M5OTKCy23BGagkTdlx4uYnCQerrortracking-exceptioncard--exception-card-logs--dark:hash: v1.k794b7964.9596d891ecde70954b0f85f1c026c58e481a74a6cfcb60b8be94e0dd01f4668c.otNvVYs8nJqXLqJdsYqhJPhduawyKMyUJpdGxxxBkGUerrortracking-exceptioncard--exception-card-logs--light:diff --git a/products/tracing/frontend/components/ViewTraceButton.test.tsx b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.test.tsxsimilarity index 97%rename from products/tracing/frontend/components/ViewTraceButton.test.tsxrename to frontend/src/lib/components/ViewTraceButton/ViewTraceButton.test.tsxindex 8b52f9144daa..9810eb08724c 100644--- a/products/tracing/frontend/components/ViewTraceButton.test.tsx+++ b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.test.tsx@@ -57,7 +57,7 @@ describe('ViewTraceButton', () => {expect(screen.getByText('View trace').closest('a')).toHaveAttribute('href',- expect.stringContaining('trace=abc123')+ expect.stringContaining('trace=ABC123'))// The timestamp bounds the cold-load query; without it the lookup scans the whole// retention window, because OTel trace ids embed no time.diff --git a/products/tracing/frontend/components/ViewTraceButton.tsx b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsxsimilarity index 96%rename from products/tracing/frontend/components/ViewTraceButton.tsxrename to frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsxindex 763e62289cea..fad31703f3ec 100644--- a/products/tracing/frontend/components/ViewTraceButton.tsx+++ b/frontend/src/lib/components/ViewTraceButton/ViewTraceButton.tsx@@ -5,7 +5,7 @@ import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { AccessControlLevel, AccessControlResourceType } from '~/types'-import { traceUrl } from 'products/tracing/frontend/traceLinks'+import { traceUrl } from './traceUrl'export interface ViewTraceButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {/** Hex trace id, as every product's query runner returns it. */diff --git a/frontend/src/lib/components/ViewTraceButton/traceUrl.test.ts b/frontend/src/lib/components/ViewTraceButton/traceUrl.test.tsnew file mode 100644index 000000000000..34314566ad7a--- /dev/null+++ b/frontend/src/lib/components/ViewTraceButton/traceUrl.test.ts@@ -0,0 +1,20 @@+import { traceUrl } from './traceUrl'++describe('traceUrl', () => {+ it.each([+ [{ traceId: 'abc123' }, '/tracing?trace=ABC123'],+ [{ traceId: 'abc123', spanId: 'def456' }, '/tracing?trace=ABC123&span=DEF456'],+ [+ { traceId: 'abc123', spanId: 'def456', ts: '2026-06-11T08:00:00.000Z' },+ '/tracing?trace=ABC123&span=DEF456&ts=2026-06-11T08%3A00%3A00.000Z',+ ],+ [+ { traceId: 'abc123', spanId: 'ai:0190a1b2-0000-7000-8000-000000000001' },+ '/tracing?trace=ABC123&span=ai%3A0190a1b2-0000-7000-8000-000000000001',+ ],+ // Null/undefined anchor and hint are simply omitted.+ [{ traceId: 'abc123', spanId: null, ts: null }, '/tracing?trace=ABC123'],+ ])('traceUrl(%j) → %s', (params, expected) => {+ expect(traceUrl(params)).toBe(expected)+ })+})diff --git a/frontend/src/lib/components/ViewTraceButton/traceUrl.ts b/frontend/src/lib/components/ViewTraceButton/traceUrl.tsnew file mode 100644index 000000000000..2260a55d1872--- /dev/null+++ b/frontend/src/lib/components/ViewTraceButton/traceUrl.ts@@ -0,0 +1,33 @@+// Canonical trace URLs (JON-33). The URL is the atomic, shareable form of a trace view:+// `/tracing?trace=<hex>` opens the drawer, `&span=<hex>` anchors a span, and the optional `&ts=<iso>`+// carries the root timestamp so a cold load can bound the ClickHouse lookup to a narrow window. A link+// without `ts` still opens the trace: the backend finds it by id through the trace_id projection.++import { urls } from 'scenes/urls'++import { usableId } from './usableId'++export interface TraceLinkParams {+ traceId: string+ spanId?: string | null+ /** ISO timestamp of (any span of) the trace, used to bound the cold-load query. */+ ts?: string | null+}++// The trace API returns hex ids in uppercase, and the viewer matches the URL ids against them exactly.+// Other ids, such as the drawer's `ai:<uuid>` rows, keep their case.+function inApiCase(id: string): string {+ return usableId(id) ? id.toUpperCase() : id+}++/** Path + query for a trace view, relative to the app root. */+export function traceUrl({ traceId, spanId, ts }: TraceLinkParams): string {+ const params = new URLSearchParams({ trace: inApiCase(traceId) })+ if (spanId) {+ params.set('span', inApiCase(spanId))+ }+ if (ts) {+ params.set('ts', ts)+ }+ return `${urls.tracing()}?${params.toString()}`+}diff --git a/frontend/src/lib/components/ViewTraceButton/usableId.test.ts b/frontend/src/lib/components/ViewTraceButton/usableId.test.tsnew file mode 100644index 000000000000..8cb609396ef1--- /dev/null+++ b/frontend/src/lib/components/ViewTraceButton/usableId.test.ts@@ -0,0 +1,16 @@+import { usableId } from './usableId'++describe('usableId', () => {+ 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],+ ['a value with path characters', 'a/b', null],+ ['a value that is not hex', 'notatrace', null],+ ['an odd-length hex value', 'abc', null],+ ])('resolves %s', (_name, value, expected) => {+ expect(usableId(value)).toBe(expected)+ })+})diff --git a/frontend/src/lib/components/ViewTraceButton/usableId.ts b/frontend/src/lib/components/ViewTraceButton/usableId.tsnew file mode 100644index 000000000000..08590809c448--- /dev/null+++ b/frontend/src/lib/components/ViewTraceButton/usableId.ts@@ -0,0 +1,16 @@+/**+ * 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.+ * Stored trace and span ids are always whole bytes of hex, so any other value is null too. Event+ * properties such as `$trace_id` accept any string, and callers put the id into URLs and API paths.+ */+export function usableId(value: string | null | undefined): string | null {+ if (!value) {+ return null+ }+ const normalized = value.toLowerCase()+ return /^(?:[0-9a-f]{2})+$/.test(normalized) && !/^0+$/.test(normalized) ? normalized : null+}diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsxindex e38dba6829dc..6905b177bc1d 100644--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx@@ -10,6 +10,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'import type { Mocks } from '~/mocks/utils'import { LogMessage, LogSeverityLevel, NodeKind } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { TEST_EVENTS } from '../../__mocks__/events'import { results as batchGetResults } from '../../__mocks__/stack_frames/batch_get'@@ -24,6 +25,18 @@ const meta: Meta = {layout: 'centered',viewMode: 'story',},+ // The trace link hides without tracing access, and the default story context grants none.+ beforeEach: () => {+ const context = window.POSTHOG_APP_CONTEXT!+ const previous = context.resource_access_control+ context.resource_access_control = {+ ...previous,+ [AccessControlResourceType.Tracing]: AccessControlLevel.Viewer,+ }+ return () => {+ context.resource_access_control = previous+ }+ },decorators: [mswDecorator({post: {@@ -615,6 +628,16 @@ const HEADER_WIDTHS: { width: number; caption: string }[] = [{ width: 900, caption: '900px — roomy: symmetric gutters, tab bar dead centre' },]+// Both actions outgrow a 1fr gutter just above @xl, so this matrix also covers the band up to where they fit.+const HEADER_WIDTHS_WITH_ACTION: typeof HEADER_WIDTHS = [+ ...HEADER_WIDTHS.filter(({ width }) => width < 576),+ { width: 576, caption: '576px — @xl boundary: actions keep their width, tab bar scrolls' },+ { width: 600, caption: '600px — logo kept, tab bar scrolls' },+ { width: 640, caption: '640px — tab bar sits off-centre to clear the actions' },+ { width: 700, caption: '700px — label is back, tab bar still off-centre' },+ { width: 800, caption: '800px — room for both: tab bar centred' },+]+function HeaderWidthMatrix({widths = HEADER_WIDTHS,children,@@ -655,15 +678,16 @@ export function ExceptionCardHeaderWidths(): JSX.Element {ExceptionCardHeaderWidths.parameters = { mockDate: HEADER_WIDTHS_MOCK_DATE }/*- * Worst case: the right-hand cell is occupied too, so the tab bar has the least room it ever gets in- * production. The action has to survive at every width — the label is the only thing allowed to go.+ * Worst case: the right-hand cell holds both actions, so the tab bar has the least room it ever gets in+ * production. The actions have to survive at every width — the label is the only thing allowed to go.*/export function ExceptionCardHeaderWidthsWithAction(): JSX.Element {- const event = asErrorEventType(TEST_EVENTS['javascript_resolved'])+ const baseEvent = asErrorEventType(TEST_EVENTS['javascript_resolved'])+ const event = { ...baseEvent, properties: { ...baseEvent.properties, $trace_id: LOGS_STORY_TRACE_ID } }return (<div className="[&_[data-attr=session-timeline-scroll-container]]:overflow-clip">- <HeaderWidthMatrix widths={HEADER_WIDTHS.filter(({ width }) => width <= 576)}>+ <HeaderWidthMatrix widths={HEADER_WIDTHS_WITH_ACTION}>{(width) => (<OpenTab tab="timeline" issueId={`header-action-${width}`}><ExceptionCard@@ -707,8 +731,10 @@ function headerActionParameters(): Record<string, unknown> {//////////////////// Logs tabconst LOGS_STORY_SESSION_ID = 'session-with-logs'-const LOGS_STORY_TRACE_ID = 'story-trace'-const LOGS_STORY_SPAN_ID = 'story-span-4'+// Hex, like stored ids: the trace link drops any id that is not.+const LOGS_STORY_TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'+const storySpanId = (index: number): string => (index + 1).toString(16).padStart(16, '0')+const LOGS_STORY_SPAN_ID = storySpanId(4)function buildStoryLogs(event: ErrorEventType): LogMessage[] {const center = new Date(event.timestamp).getTime()@@ -727,7 +753,7 @@ function buildStoryLogs(event: ErrorEventType): LogMessage[] {return lines.map(({ offsetMs, level, body }, index) => ({uuid: `story-log-${index}`,trace_id: LOGS_STORY_TRACE_ID,- span_id: `story-span-${index}`,+ span_id: storySpanId(index),resource_attributes: { 'service.name': 'posthog-web' },attributes: { sessionId: LOGS_STORY_SESSION_ID },body,diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsxindex e659b037c42e..ed787af1ec7b 100644--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx@@ -7,6 +7,8 @@ import { LemonCard } from '@posthog/lemon-ui'import { ErrorPropertiesLogicProps, errorPropertiesLogic } from 'lib/components/Errors/errorPropertiesLogic'import { ErrorEventType } from 'lib/components/Errors/types'import type { TimelineMarkerColor } from 'lib/components/SessionTimeline/SessionTimeline'+import { usableId } from 'lib/components/ViewTraceButton/usableId'+import { ViewTraceButton } from 'lib/components/ViewTraceButton/ViewTraceButton'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { Tabs, TabsList, TabsTrigger } from 'lib/ui/quill'@@ -80,7 +82,7 @@ function ExceptionCardContent({label,}: ExceptionCardContentProps): JSX.Element {const { currentTab } = useValues(exceptionCardLogic)- const { sessionId } = useValues(errorPropertiesLogic)+ const { sessionId, spanId, traceId } = useValues(errorPropertiesLogic)const { setCurrentTab } = useActions(exceptionCardLogic)const logsEnabled = useFeatureFlag('LOGS_IN_ERROR_TRACKING')const headerRef = useRef<HTMLDivElement>(null)@@ -123,13 +125,16 @@ function ExceptionCardContent({>{/* Container query, not viewport: the card sits in a resizable split pane. At @xl and up,symmetric 1fr gutters centre the tab bar; below it the gutters shrink to their content- so the tab bar keeps the slack. The container wraps the header alone — inline-size+ so the tab bar keeps the slack. Just above @xl a 1fr share is narrower than two actions,+ so the right gutter never drops below its content and the tab bar sits off-centre until+ there is room; the left gutter keeps the logomark's 1.125rem (text-lg) so the tab bar+ scrolls before the logo is cut in half. The container wraps the header alone — inline-sizecontainment zeroes an element's intrinsic width contribution, and on the card as awhole that collapses it to nothing inside a shrink-to-fit parent. */}<div className="@container/exception-card shrink-0"><divref={headerRef}- className="grid h-10 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 border-b px-2 @xl/exception-card:grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)]"+ className="grid h-10 w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 border-b px-2 @xl/exception-card:grid-cols-[minmax(1.125rem,1fr)_auto_minmax(max-content,1fr)]">{/* min-w-0 lets this track collapse, so the cell must clip: an unclipped label drawsover the tab bar. */}@@ -184,7 +189,14 @@ function ExceptionCardContent({</TabsTrigger>)}</TabsList>- <div className="flex justify-end">+ <div className="flex justify-end gap-1">+ <ViewTraceButton+ traceId={usableId(traceId)}+ spanId={usableId(spanId)}+ timestamp={timestamp}+ size="xsmall"+ data-attr="error-tracking-view-trace"+ />{sessionId && (currentTab === 'timeline' || currentTab === 'recording') ? (<ViewLogsButtonsessionId={sessionId}diff --git a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsxindex 5b722c02ae04..e7adcaf67cbc 100644--- a/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx+++ b/products/logs/frontend/components/LogsViewer/LogContextLinks/LogContextLinks.tsx@@ -3,6 +3,8 @@ import { useValues } from 'kea'import { LemonTag } from '@posthog/lemon-ui'import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { usableId } from 'lib/components/ViewTraceButton/usableId'+import { ViewTraceButton } from 'lib/components/ViewTraceButton/ViewTraceButton'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { userHasAccess } from 'lib/utils/accessControlUtils'@@ -14,8 +16,7 @@ import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'import { ParsedLogMessage } from 'products/logs/frontend/types'import { getDistinctIdWithKey, getSessionIdFromLogAttributes } from 'products/logs/frontend/utils'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'-import { ViewTraceButton } from 'products/tracing/frontend/components/ViewTraceButton'-import { type ErrorScope, usableId } from 'products/tracing/frontend/errorCorrelation'+import { type ErrorScope } from 'products/tracing/frontend/errorCorrelation'import { LogErrorCount } from './LogErrorCount'import { MissingLinkInvestigate } from './MissingLinkInvestigate'diff --git a/products/logs/frontend/components/LogsViewer/LogRowFAB/LogRowFAB.tsx b/products/logs/frontend/components/LogsViewer/LogRowFAB/LogRowFAB.tsxindex 805ef8c71a4d..44d550b07d8b 100644--- a/products/logs/frontend/components/LogsViewer/LogRowFAB/LogRowFAB.tsx+++ b/products/logs/frontend/components/LogsViewer/LogRowFAB/LogRowFAB.tsx@@ -13,6 +13,7 @@ import {import { LemonButton } from '@posthog/lemon-ui'import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { IconLink } from 'lib/lemon-ui/icons'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'@@ -30,7 +31,6 @@ import { useCellScrollControls } from 'products/logs/frontend/components/Virtualimport { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'import { ParsedLogMessage } from 'products/logs/frontend/types'import { getSessionIdFromLogAttributes } from 'products/logs/frontend/utils'-import { traceUrl } from 'products/tracing/frontend/traceLinks'import { FABGroup } from './FABGroup'diff --git a/products/logs/frontend/components/VirtualizedLogsList/cells/AttributeCell.tsx b/products/logs/frontend/components/VirtualizedLogsList/cells/AttributeCell.tsxindex c5d1e18b0ce6..92604fb80f3f 100644--- a/products/logs/frontend/components/VirtualizedLogsList/cells/AttributeCell.tsx+++ b/products/logs/frontend/components/VirtualizedLogsList/cells/AttributeCell.tsx@@ -7,6 +7,7 @@ import ViewRecordingButton, {RecordingPlayerType,ViewRecordingButtonVariant,} from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { AccessControlLevel, AccessControlResourceType, PropertyFilterType } from '~/types'@@ -18,7 +19,6 @@ import { useCellScroll } from 'products/logs/frontend/components/VirtualizedLogsimport { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'import { isDistinctIdKey, isSessionIdKey } from 'products/logs/frontend/utils'import { PersonDisplay } from 'products/persons/frontend/components/PersonDisplay'-import { traceUrl } from 'products/tracing/frontend/traceLinks'export interface AttributeCellProps {attributeKey: stringdiff --git a/products/metrics/frontend/components/MetricsSamplesPanel.tsx b/products/metrics/frontend/components/MetricsSamplesPanel.tsxindex b2b8c1011bb1..ef915be10f5f 100644--- a/products/metrics/frontend/components/MetricsSamplesPanel.tsx+++ b/products/metrics/frontend/components/MetricsSamplesPanel.tsx@@ -7,14 +7,13 @@ import { LemonButton, LemonSegmentedButton, LemonTable, LemonTabs, Link, Tooltipimport { getColorVar } from 'lib/colors'import { TZLabel } from 'lib/components/TZLabel'+import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { humanFriendlyNumber } from 'lib/utils/numbers'import { teamLogic } from 'scenes/teamLogic'import { AccessControlLevel, AccessControlResourceType } from '~/types'-import { traceUrl } from 'products/tracing/frontend/traceLinks'-import { type MetricsSeriesRow, type MetricsPanelTab, metricsSamplesLogic } from './metricsSamplesLogic'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { metricsViewerLogic } from './metricsViewerLogic'diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex a03bcc623567..749f40fe7bae 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -5,6 +5,7 @@ import { useEffect, useMemo } from 'react'import { LemonBanner, LemonButton, LemonSwitch, SpinnerOverlay } from '@posthog/lemon-ui'import { AddToDashboardModal } from 'lib/components/AddToDashboard/AddToDashboardModal'+import { traceUrl } from 'lib/components/ViewTraceButton/traceUrl'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'@@ -14,8 +15,6 @@ import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'-import { traceUrl } from 'products/tracing/frontend/traceLinks'-import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'import { MetricsHistogramQueryNode } from '../nodes/MetricsHistogramQueryNode'import { MetricsPanel } from '../panels/MetricsPanel'diff --git a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.tsindex 7ac7c02a3a92..8f2cc0981330 100644--- a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts+++ b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts@@ -2,12 +2,12 @@ import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'import { subscriptions } from 'kea-subscriptions'+import { usableId } from 'lib/components/ViewTraceButton/usableId'import { FEATURE_FLAGS } from 'lib/constants'import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'import type { TraceAiEvent } from '../../aiEventSpans'-import { usableId } from '../../errorCorrelation'import { tracingSpansTraceAiEventsRetrieve } from '../../generated/api'import type { _TracingTraceAiEventsResponseApi } from '../../generated/api.schemas'diff --git a/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.tsindex 72415c978bb1..28ee3bf39772 100644--- a/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts+++ b/products/tracing/frontend/components/TraceDrawer/traceErrorsLogic.ts@@ -2,12 +2,13 @@ import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, rimport { loaders } from 'kea-loaders'import api from 'lib/api'+import { usableId } from 'lib/components/ViewTraceButton/usableId'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'+import { type ErrorScope, sessionErrorsWindow, traceErrorsWindow } 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.diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsxindex 3445191e5a90..806fcaa8ad92 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanRowActions.test.tsx@@ -9,7 +9,11 @@ jest.mock('lib/utils/copyToClipboard', () => ({copyToClipboard: jest.fn(),}))-const span = { trace_id: 'trace-abc-123', name: 'GET /api/projects', timestamp: '2026-06-11T08:00:00.000Z' } as Span+const span = {+ trace_id: '4BF92F3577B34DA6A3CE929D0E0E4736',+ name: 'GET /api/projects',+ timestamp: '2026-06-11T08:00:00.000Z',+} as Spandescribe('SpanRowActions', () => {beforeEach(() => {@@ -33,14 +37,14 @@ describe('SpanRowActions', () => {it('copies the trace id', () => {const { container } = render(<SpanRowActions span={span} onViewTrace={jest.fn()} />)fireEvent.click(container.querySelector('[data-attr="tracing-copy-trace-id"]')!)- expect(copyToClipboard).toHaveBeenCalledWith('trace-abc-123', 'trace ID')+ expect(copyToClipboard).toHaveBeenCalledWith('4BF92F3577B34DA6A3CE929D0E0E4736', 'trace ID')})it('copies a canonical trace link carrying the ts hint', () => {const { container } = render(<SpanRowActions span={span} onViewTrace={jest.fn()} />)fireEvent.click(container.querySelector('[data-attr="tracing-copy-link"]')!)expect(copyToClipboard).toHaveBeenCalledWith(- `${window.location.origin}/tracing?trace=trace-abc-123&ts=2026-06-11T08%3A00%3A00.000Z`,+ `${window.location.origin}/tracing?trace=4BF92F3577B34DA6A3CE929D0E0E4736&ts=2026-06-11T08%3A00%3A00.000Z`,'trace link')})diff --git a/products/tracing/frontend/errorCorrelation.test.ts b/products/tracing/frontend/errorCorrelation.test.tsindex 1aa3ac8b4c7b..93b3bf6ac0cc 100644--- a/products/tracing/frontend/errorCorrelation.test.ts+++ b/products/tracing/frontend/errorCorrelation.test.ts@@ -1,4 +1,4 @@-import { sessionErrorsWindow, traceErrorsWindow, usableId } from './errorCorrelation'+import { sessionErrorsWindow, traceErrorsWindow } from './errorCorrelation'describe('errorCorrelation', () => {// A span whose timestamp the parser rejects must not widen the range to an invalid one, which@@ -24,16 +24,6 @@ describe('errorCorrelation', () => {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', () => {diff --git a/products/tracing/frontend/errorCorrelation.ts b/products/tracing/frontend/errorCorrelation.tsindex 89cc44bf599e..370a47e01527 100644--- a/products/tracing/frontend/errorCorrelation.ts+++ b/products/tracing/frontend/errorCorrelation.ts@@ -60,18 +60,3 @@ export function sessionErrorsWindow(timestamps: (string | null)[]): ErrorsWindowexport 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/spanErrorsLogic.test.ts b/products/tracing/frontend/spanErrorsLogic.test.tsindex 60f2265c6856..cbc220f86631 100644--- a/products/tracing/frontend/spanErrorsLogic.test.ts+++ b/products/tracing/frontend/spanErrorsLogic.test.ts@@ -33,6 +33,12 @@ function spanWithSession(uuid: string, sessionId: string | null): Span {})}+// Stored trace and span ids are hex, and `usableId` drops anything else.+const TRACE_A = 'a'.repeat(32)+const SPAN_1 = 'd'.repeat(16)+const SPAN_THROWER = 'b'.repeat(16)+const SPAN_QUIET = 'c'.repeat(16)+function spanWithIds(uuid: string, traceId: string, spanId: string, sessionId?: string): Span {return makeSpan({uuid,@@ -114,14 +120,14 @@ describe('spanErrorsLogic', () => {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 }],+ 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'),+ spanWithIds('row-span', TRACE_A, SPAN_THROWER),+ spanWithIds('row-trace', TRACE_A, SPAN_QUIET),spanWithSession('row-session', 'session-c'),])@@ -146,7 +152,7 @@ describe('spanErrorsLogic', () => {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 }] }+ : { ...NO_COUNTS, traceResults: [{ trace_id: TRACE_A, exceptions: trace }] })}@@ -158,7 +164,7 @@ describe('spanErrorsLogic', () => {])('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')])+ 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)@@ -178,10 +184,10 @@ describe('spanErrorsLogic', () => {// 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')])+ await loadFirstPage([spanWithIds('row-1', TRACE_A.toUpperCase(), SPAN_1.toUpperCase())])- expect(asked('traceIds')).toEqual([['trace-a']])- expect(asked('spanIds')).toEqual([['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 () => {@@ -218,7 +224,7 @@ describe('spanErrorsLogic', () => {['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')+ field === 'traceIds' ? spanWithIds('span-1', TRACE_A, SPAN_1) : spanWithSession('span-1', 'session-a')await loadFirstPage([{ ...span, timestamp: '2026-06-02T08:00:00Z' }])@@ -241,7 +247,7 @@ describe('spanErrorsLogic', () => {],])('queries nothing and scans no rows while %s', async (_name, disable) => {disable()- await loadFirstPage([spanWithIds('span-1', 'trace-a', 'span-1', 'session-a')])+ await loadFirstPage([spanWithIds('span-1', TRACE_A, SPAN_1, 'session-a')])expect(mockCountsCreate).not.toHaveBeenCalled()expect(logic.values.errorCounts.session).toEqual({})diff --git a/products/tracing/frontend/spanErrorsLogic.ts b/products/tracing/frontend/spanErrorsLogic.tsindex 675b04e2cd7a..9e8b10304c29 100644--- a/products/tracing/frontend/spanErrorsLogic.ts+++ b/products/tracing/frontend/spanErrorsLogic.ts@@ -1,10 +1,11 @@import { MakeLogicType, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { usableId } from 'lib/components/ViewTraceButton/usableId'import { chunk } from 'lib/utils/arrays'import { teamLogic } from 'scenes/teamLogic'-import { type ErrorScope, sessionErrorsWindow, traceErrorsWindow, usableId } from './errorCorrelation'+import { type ErrorScope, sessionErrorsWindow, traceErrorsWindow } from './errorCorrelation'import { tracingSpansErrorCountsCreate } from './generated/api'import type { TeamTracingConfigApi } from './generated/api.schemas'import { tracingSpansErrorCountsCreateBodySpanIdsMax } from './generated/api.zod'diff --git a/products/tracing/frontend/traceLinks.test.ts b/products/tracing/frontend/traceLinks.test.tsindex a9919c372445..ab2cb2977f4b 100644--- a/products/tracing/frontend/traceLinks.test.ts+++ b/products/tracing/frontend/traceLinks.test.ts@@ -1,21 +1,8 @@import { combineUrl } from 'kea-router'-import { traceLookupDateRange, traceUrl, tracingUrlForService } from './traceLinks'+import { traceLookupDateRange, tracingUrlForService } from './traceLinks'describe('traceLinks', () => {- it.each([- [{ traceId: 'abc123' }, '/tracing?trace=abc123'],- [{ traceId: 'abc123', spanId: 'def456' }, '/tracing?trace=abc123&span=def456'],- [- { traceId: 'abc123', spanId: 'def456', ts: '2026-06-11T08:00:00.000Z' },- '/tracing?trace=abc123&span=def456&ts=2026-06-11T08%3A00%3A00.000Z',- ],- // Null/undefined anchor and hint are simply omitted.- [{ traceId: 'abc123', spanId: null, ts: null }, '/tracing?trace=abc123'],- ])('traceUrl(%j) → %s', (params, expected) => {- expect(traceUrl(params)).toBe(expected)- })-it('traceLookupDateRange bounds the lookup to ±1h around the hint', () => {expect(traceLookupDateRange('2026-06-11T08:00:00.000Z')).toEqual({date_from: '2026-06-11T07:00:00.000Z',diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.tsindex a401147f1ef1..23b422c9131f 100644--- a/products/tracing/frontend/traceLinks.ts+++ b/products/tracing/frontend/traceLinks.ts@@ -1,34 +1,11 @@-// Canonical trace URLs (JON-33). The URL is the atomic, shareable form of a trace view:-// `/tracing?trace=<hex>` opens the drawer, `&span=<hex>` anchors a span, and the optional `&ts=<iso>`-// carries the root timestamp so a cold load can bound the ClickHouse lookup to a narrow window. A link-// without `ts` still opens the trace: the backend finds it by id through the trace_id projection.-import { combineUrl } from 'kea-router'+import { type TraceLinkParams, traceUrl } from 'lib/components/ViewTraceButton/traceUrl'import { dayjs } from 'lib/dayjs'import { urls } from 'scenes/urls'import type { DateRange } from '~/queries/schema/schema-general'-export interface TraceLinkParams {- traceId: string- spanId?: string | null- /** ISO timestamp of (any span of) the trace, used to bound the cold-load query. */- ts?: string | null-}--/** Path + query for a trace view, relative to the app root. */-export function traceUrl({ traceId, spanId, ts }: TraceLinkParams): string {- const params = new URLSearchParams({ trace: traceId })- if (spanId) {- params.set('span', spanId)- }- if (ts) {- params.set('ts', ts)- }- return `${urls.tracing()}?${params.toString()}`-}-/** Absolute, shareable URL for a trace view. */export function absoluteTraceUrl(params: TraceLinkParams): string {return urls.absolute(traceUrl(params))