: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
fix(tracing): only open hex trace ids from the tracing url (#116904)
Paul D'Ambrace41a1cbde93
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.tsindex 89a272abba3d..2caeb931ee8b 100644--- a/frontend/src/lib/api.test.ts+++ b/frontend/src/lib/api.test.ts@@ -668,6 +668,14 @@ describe('API helper', () => {})})+ describe('tracing', () => {+ it('sends the trace id as one path segment', async () => {+ await api.tracing.getTrace('a/b?c')++ expect(fakeFetch.mock.calls[0][0]).toEqual('/api/projects/2/tracing/spans/trace/a%2Fb%3Fc/')+ })+ })+describe('tasks', () => {it.each([['task/id', 'projects/2/tasks/task%2Fid'],diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 0fd8fff400ad..411fde81efbf 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2825,7 +2825,7 @@ const api = {): Promise<{ results: Record<string, any>[]; hasMore: boolean; nextOffset?: number | null }> {return new ApiRequest().tracingSpans()- .withAction(`trace/${traceId}`)+ .withAction(`trace/${encodeURIComponent(traceId)}`).create({ signal, data: { ...query } })},async sparkline(diff --git a/frontend/src/lib/components/ViewTraceButton/traceUrl.ts b/frontend/src/lib/components/ViewTraceButton/traceUrl.tsindex 2260a55d1872..a573f2f9ced8 100644--- a/frontend/src/lib/components/ViewTraceButton/traceUrl.ts+++ b/frontend/src/lib/components/ViewTraceButton/traceUrl.ts@@ -16,7 +16,7 @@ export interface TraceLinkParams {// 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 {+export function inApiCase(id: string): string {return usableId(id) ? id.toUpperCase() : id}diff --git a/products/tracing/frontend/tracingSceneLogic.test.ts b/products/tracing/frontend/tracingSceneLogic.test.tsindex 8580db120e32..3ddb1798e6a4 100644--- a/products/tracing/frontend/tracingSceneLogic.test.ts+++ b/products/tracing/frontend/tracingSceneLogic.test.ts@@ -42,6 +42,65 @@ describe('tracingSceneLogic', () => {featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]: true })}+ it.each([+ ['an uppercase hex trace id', '4BF92F3577B34DA6A3CE929D0E0E4736', '4BF92F3577B34DA6A3CE929D0E0E4736'],+ ['a lowercase hex trace id', '4bf92f3577b34da6a3ce929d0e0e4736', '4BF92F3577B34DA6A3CE929D0E0E4736'],+ ['a trace id with path characters', 'a/b', null],+ ])('opens the trace drawer from the URL only for %s', (_name, traceId, expected) => {+ jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({ results: [], hasMore: false })+ mountAt({ trace: traceId })+ expect(logic.values.selectedTraceId).toBe(expected)+ })++ const LOWER_TRACE_ID = '4bf92f3577b34da6a3ce929d0e0e4736'+ const UPPER_TRACE_ID = '4BF92F3577B34DA6A3CE929D0E0E4736'++ it.each([+ ['a lowercase trace id', null, { trace: LOWER_TRACE_ID }, UPPER_TRACE_ID],+ [+ 'a lowercase trace id next to a filter',+ null,+ { trace: LOWER_TRACE_ID, dateRange: JSON.stringify({ date_from: '-7d', date_to: null }) },+ UPPER_TRACE_ID,+ ],+ ['a trace id with path characters', UPPER_TRACE_ID, { trace: 'a/b' }, undefined],+ ])('cleans up %s in the URL without adding a back step', (_name, openTraceId, urlParams, expected) => {+ jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({ results: [], hasMore: false })+ mountAt(openTraceId ? { trace: openTraceId } : {})+ router.actions.push('/tracing', urlParams)+ expect(router.values.searchParams.trace).toBe(expected)+ expect(router.values.lastMethod).toBe('REPLACE')+ })++ it.each([+ [+ 'a lowercase span id with the trace',+ null,+ { trace: LOWER_TRACE_ID, span: '00f067aa0ba902b7' },+ '00F067AA0BA902B7',+ ],+ [+ 'a lowercase span id in an open trace',+ UPPER_TRACE_ID,+ { trace: UPPER_TRACE_ID, span: '00f067aa0ba902b7' },+ '00F067AA0BA902B7',+ ],+ ['an AI span id', null, { trace: LOWER_TRACE_ID, span: 'ai:AbC-123' }, 'ai:AbC-123'],+ ])('selects %s from the URL in the case the trace API returns', (_name, openTraceId, urlParams, expected) => {+ jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({ results: [], hasMore: false })+ mountAt(openTraceId ? { trace: openTraceId } : {})+ router.actions.push('/tracing', urlParams)+ expect(logic.values.selectedSpanId).toBe(expected)+ })++ it('opens a lowercase trace id from code only once', () => {+ const getTrace = jest.spyOn(api.tracing, 'getTrace').mockResolvedValue({ results: [], hasMore: false })+ mountAt({})+ logic.actions.openTrace(LOWER_TRACE_ID)+ expect(router.values.searchParams.trace).toBe(UPPER_TRACE_ID)+ expect(getTrace).toHaveBeenCalledTimes(1)+ })+it('migrates legacy compare=true links to the custom time comparison', () => {const filtersLogic = mountAt({ compare: 'true' })expect(filtersLogic.values.comparison).toEqual({diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex e462783b51b1..7eae0c8ad6fc 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -5,6 +5,7 @@ import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'+import { usableId } from 'lib/components/ViewTraceButton/usableId'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'@@ -60,6 +61,10 @@ const DEFAULT_SCENE_TAB: TracingSceneTab = 'viewer'export const getTracingSqlEditorTabId = (id: string): string => `tracing-sql-editor-${id}`+// Uppercase, because the trace API returns ids that way and the viewer matches them exactly.+const traceIdFromUrl = (searchParams: Params): string | null =>+ usableId(typeof searchParams.trace === 'string' ? searchParams.trace : null)?.toUpperCase() ?? null+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingSceneLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -581,7 +586,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([},})),- urlToAction(({ actions, values }) => ({+ urlToAction(({ actions, values, cache }) => ({'/tracing': (_, searchParams) => {const filtersFromUrl: Record<string, any> = {}let hasChanges = false@@ -710,19 +715,24 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([// Drawer params. Guarded on a state/URL mismatch so the actionToUrl writes below don't// loop back through here, and so back/forward opens/closes the drawer correctly.- const traceFromUrl = typeof searchParams.trace === 'string' ? searchParams.trace : null+ const traceFromUrl = traceIdFromUrl(searchParams)const spanFromUrl = typeof searchParams.span === 'string' ? searchParams.span : null- if (traceFromUrl && traceFromUrl !== values.selectedTraceId) {- actions.openTrace(traceFromUrl, {- spanId: spanFromUrl,- ts: typeof searchParams.ts === 'string' ? searchParams.ts : null,- })- } else if (traceFromUrl && spanFromUrl !== values.selectedSpanId) {- // Same trace already open, but the URL's span anchor changed (e.g. a shared span- // link to a trace the user already has open) — move the selection, don't reopen.- actions.selectSpan(spanFromUrl)- } else if (!traceFromUrl && values.selectedTraceId) {- actions.closeTrace()+ cache.drawerChangeFromUrl = true+ try {+ if (traceFromUrl && traceFromUrl !== values.selectedTraceId) {+ actions.openTrace(traceFromUrl, {+ spanId: spanFromUrl,+ ts: typeof searchParams.ts === 'string' ? searchParams.ts : null,+ })+ } else if (traceFromUrl && spanFromUrl !== values.selectedSpanId) {+ // Same trace already open, but the URL's span anchor changed (e.g. a shared span+ // link to a trace the user already has open) — move the selection, don't reopen.+ actions.selectSpan(spanFromUrl)+ } else if (!traceFromUrl && values.selectedTraceId) {+ actions.closeTrace()+ }+ } finally {+ cache.drawerChangeFromUrl = false}if (sceneTabsDisabled && searchParams.tab !== undefined) {@@ -731,7 +741,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([},})),- trackedActionToUrl(({ values }) => {+ trackedActionToUrl(({ values, cache }) => {// The drawer params (trace/span/ts) live alongside the filter params. They're written by// their own handlers below (which must NOT re-run the list query), and preserved by// buildUrl so a filter change doesn't silently strip an open drawer from the URL.@@ -798,11 +808,15 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([]}+ // A drawer change that the URL started only cleans up the trace param, so it replaces: Back must+ // not stop on a lowercase or malformed spelling, or on a URL a filter restore already rewrote.+ const drawerChangeUrl = (): ReturnType<typeof drawerUrl> => drawerUrl(!!cache.drawerChangeFromUrl)+return {syncUrl: () => buildUrl(),- openTrace: () => drawerUrl(false),+ openTrace: () => drawerChangeUrl(),selectSpan: () => drawerUrl(true),- closeTrace: () => drawerUrl(false),+ closeTrace: () => drawerChangeUrl(),}}),])diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.tsindex 5de4b1fa5718..9a145107944b 100644--- a/products/tracing/frontend/tracingViewerLogic.ts+++ b/products/tracing/frontend/tracingViewerLogic.ts@@ -1,6 +1,8 @@import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'+import { inApiCase } from 'lib/components/ViewTraceButton/traceUrl'+import type { ErrorScope } from './errorCorrelation'import {EMPTY_TRACE_IDENTITY,@@ -215,14 +217,14 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([errorsScope?: ErrorScope | null}) => ({- traceId,- spanId: options?.spanId ?? null,+ traceId: inApiCase(traceId),+ spanId: options?.spanId ? inApiCase(options.spanId) : null,ts: options?.ts ?? null,tab: options?.tab ?? null,errorsScope: options?.errorsScope ?? null,}),selectInspectorTab: (tab: SpanInspectorTab) => ({ tab }),- selectSpan: (spanId: string | null) => ({ spanId }),+ selectSpan: (spanId: string | null) => ({ spanId: spanId ? inApiCase(spanId) : null }),closeTrace: true,openCompareFlame: (spanName: string, serviceName: string) => ({ spanName, serviceName }),closeCompareFlame: true,