:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tracing): show a trace's person and recording in the drawer (#95338)
Jimmy Zhucb1138887ab9
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.tsindex 675db2c7e1c7..5ba35ea836a8 100644--- a/products/logs/frontend/utils.test.ts+++ b/products/logs/frontend/utils.test.ts@@ -169,6 +169,22 @@ describe('logs utils', () => {undefined,null,],+ [+ // Without an own-property check these resolve to the Object.prototype member,+ // which is truthy and would be returned as though the attribute held it.+ 'a configured key naming an Object.prototype member resolves nothing',+ ['constructor'],+ { $session_id: 'builtin' },+ undefined,+ 'builtin',+ ],+ [+ 'an Object.prototype member name resolves nothing when no convention key is present',+ ['valueOf'],+ { 'http.method': 'GET' },+ undefined,+ null,+ ],])('%s', (_, configuredKeys, attributes, resourceAttributes, expected) => {expect(getSessionIdFromLogAttributes(diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsxindex 4453159f2d18..01408471988f 100644--- a/products/logs/frontend/utils.tsx+++ b/products/logs/frontend/utils.tsx@@ -146,20 +146,27 @@ const SESSION_ID_KEYS = ['posthog.session_id',]-function matchesKey(key: string, candidates: string[]): boolean {- return candidates.some((candidate) => key === candidate || key.endsWith(`.${candidate}`))+// Built once at module scope: this runs per attribute key of every log row, and per attribute+// of every span of an open trace.+const DISTINCT_ID_EXACT_KEYS = new Set(DISTINCT_ID_KEYS)+const DISTINCT_ID_SUFFIXES = DISTINCT_ID_KEYS.map((candidate) => `.${candidate}`)+const SESSION_ID_EXACT_KEYS = new Set(SESSION_ID_KEYS)+const SESSION_ID_SUFFIXES = SESSION_ID_KEYS.map((candidate) => `.${candidate}`)++function matchesKey(key: string, exactKeys: Set<string>, suffixes: string[]): boolean {+ return exactKeys.has(key) || suffixes.some((suffix) => key.endsWith(suffix))}// Configured keys (the team's `logs_distinct_id_attribute_keys` setting) match exactly;// only the built-in convention list gets dot-suffix matching.export function isDistinctIdKey(key: string, configuredKeys?: string[]): boolean {- return (configuredKeys ?? []).includes(key) || matchesKey(key, DISTINCT_ID_KEYS)+ return !!configuredKeys?.includes(key) || matchesKey(key, DISTINCT_ID_EXACT_KEYS, DISTINCT_ID_SUFFIXES)}// Configured keys (the team's `logs_session_id_attribute_keys` setting) match exactly;// only the built-in convention list gets dot-suffix matching.export function isSessionIdKey(key: string, configuredKeys?: string[]): boolean {- return (configuredKeys ?? []).includes(key) || matchesKey(key, SESSION_ID_KEYS)+ return !!configuredKeys?.includes(key) || matchesKey(key, SESSION_ID_EXACT_KEYS, SESSION_ID_SUFFIXES)}export interface LogIdentityMatch {@@ -168,6 +175,13 @@ export interface LogIdentityMatch {source: 'attribute' | 'resource_attribute'}+// A configured key is an arbitrary team setting, so read it as an own property. Bare bracket+// access resolves a key like `constructor` or `valueOf` to the Object.prototype member, which is+// truthy and would be returned as though the attribute held it.+function ownValue(attributes: Record<string, unknown> | undefined, key: string): unknown {+ return attributes && Object.hasOwn(attributes, key) ? attributes[key] : undefined+}+function getIdentityMatch(attributes: Record<string, unknown> | undefined,resourceAttributes: Record<string, unknown> | undefined,@@ -177,24 +191,26 @@ function getIdentityMatch(// Configured keys win over the built-in conventions, in list order: for each key,// attributes are checked before resource_attributes, and the first value found wins.for (const key of configuredKeys ?? []) {- const attributeValue = attributes?.[key]+ const attributeValue = ownValue(attributes, key)if (attributeValue) {return { key, value: String(attributeValue), source: 'attribute' }}- const resourceAttributeValue = resourceAttributes?.[key]+ const resourceAttributeValue = ownValue(resourceAttributes, key)if (resourceAttributeValue) {return { key, value: String(resourceAttributeValue), source: 'resource_attribute' }}}// Built-in convention fallback only — the configured-key pass already ran above, so// isConventionKey is deliberately called without the configured keys here.- for (const [key, value] of Object.entries(attributes || {})) {- if (isConventionKey(key) && value) {+ for (const key of Object.keys(attributes || {})) {+ const value = attributes?.[key]+ if (value && isConventionKey(key)) {return { key, value: String(value), source: 'attribute' }}}- for (const [key, value] of Object.entries(resourceAttributes || {})) {- if (isConventionKey(key) && value) {+ for (const key of Object.keys(resourceAttributes || {})) {+ const value = resourceAttributes?.[key]+ if (value && isConventionKey(key)) {return { key, value: String(value), source: 'resource_attribute' }}}diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 3a59021df711..b44f6994b893 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -80,6 +80,7 @@ function TracingSceneContents(): JSX.Element {sparklineData,sparklineLoading,openTraceSpans,+ traceIdentity,isLoadingFullTrace,canLoadMoreTraceSpans,traceSpansLoadingMore,@@ -288,6 +289,7 @@ function TracingSceneContents(): JSX.Element {traceId={selectedTraceId}ts={selectedTraceTs}spans={openTraceSpans}+ identity={traceIdentity}loading={isLoadingFullTrace}hasMoreSpans={canLoadMoreTraceSpans}loadingMoreSpans={traceSpansLoadingMore}diff --git a/products/tracing/frontend/__mocks__/span.ts b/products/tracing/frontend/__mocks__/span.tsnew file mode 100644index 000000000000..0f64055bf7e3--- /dev/null+++ b/products/tracing/frontend/__mocks__/span.ts@@ -0,0 +1,22 @@+import type { Span } from '../types'++export function makeSpan(overrides: Partial<Span> = {}): Span {+ return {+ uuid: 'uuid',+ trace_id: 'trace-1',+ span_id: 'span-1',+ parent_span_id: '',+ name: 'GET /checkout',+ kind: 2,+ service_name: 'checkout-api',+ status_code: 0,+ timestamp: '2026-09-03T10:00:00Z',+ end_time: '2026-09-03T10:00:01Z',+ duration_nano: 1_000_000,+ is_root_span: true,+ matched_filter: true,+ attributes: {},+ resource_attributes: {},+ ...overrides,+ }+}diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex 56ec930c1896..cbc64c374057 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -18,6 +18,7 @@ import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'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'@@ -25,6 +26,7 @@ import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'import { SpanLogsTab } from './SpanLogsTab'import { SpanMetricsTab } from './SpanMetricsTab'import { SpanSummaryHeader } from './SpanSummaryHeader'+import { TraceIdentityChips } from './TraceIdentityChips'type InspectorTab = 'attributes' | 'query' | 'logs' | 'metrics' | 'raw'@@ -38,6 +40,8 @@ export interface TraceDrawerProps {/** Timestamp hint echoed into copy-links so cold loads can bound the lookup. */ts: string | nullspans: Span[]+ /** The person and session the trace belongs to, resolved by tracingViewerLogic. */+ identity: TraceIdentityloading: boolean/** The open trace has more spans than the loaded pages — drives the waterfall's infinite scroll. */hasMoreSpans?: boolean@@ -58,6 +62,7 @@ export function TraceDrawer({traceId,ts,spans,+ identity,loading,hasMoreSpans = false,loadingMoreSpans = false,@@ -143,6 +148,7 @@ export function TraceDrawer({</div>}>+ <TraceIdentityChips identity={identity} timestamp={rootSpan?.timestamp ?? ts} /><div className="relative min-h-32 flex gap-4 items-start">{loading && <SpinnerOverlay />}<div className="flex-1 min-w-0">diff --git a/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.test.tsx b/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.test.tsxnew file mode 100644index 000000000000..80dd6413797c--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.test.tsx@@ -0,0 +1,47 @@+import '@testing-library/jest-dom'++import { render } from '@testing-library/react'++import type { TraceIdentity } from '../../traceIdentity'+import { TraceIdentityChips } from './TraceIdentityChips'++// The branch under test is which chips render for a resolved identity, not the link internals:+// both targets mount their own data-fetching logics, so they're stubbed at the boundary.+jest.mock('scenes/persons/PersonDisplay', () => ({+ PersonDisplay: ({ person }: { person: { distinct_id: string } }) => (+ <div data-attr="mock-person-display">{person.distinct_id}</div>+ ),+}))+jest.mock('lib/components/ViewRecordingButton/ViewRecordingButton', () => ({+ __esModule: true,+ default: ({ sessionId }: { sessionId: string }) => <div data-attr="mock-view-recording">{sessionId}</div>,+ RecordingPlayerType: { Modal: 'modal' },+ ViewRecordingButtonVariant: { Link: 'link' },+}))++describe('TraceIdentityChips', () => {+ function renderChips(identity: TraceIdentity): HTMLElement {+ const { container } = render(<TraceIdentityChips identity={identity} timestamp="2026-09-03T10:00:00Z" />)+ return container+ }++ // Each chip is independent, so a trace with only one half still shows that half.+ test.each<TraceIdentity>([+ { distinctId: 'user-1', sessionId: 'session-1' },+ { distinctId: null, sessionId: 'session-1' },+ { distinctId: 'user-1', sessionId: null },+ ])('renders the chips for %j', (identity) => {+ const container = renderChips(identity)++ expect(container.querySelector('[data-attr="mock-person-display"]')?.textContent ?? null).toBe(+ identity.distinctId+ )+ expect(container.querySelector('[data-attr="mock-view-recording"]')?.textContent ?? null).toBe(+ identity.sessionId+ )+ })++ it('renders nothing for a trace with no identity', () => {+ expect(renderChips({ distinctId: null, sessionId: null })).toBeEmptyDOMElement()+ })+})diff --git a/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.tsx b/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.tsxnew file mode 100644index 000000000000..d5a31764d953--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/TraceIdentityChips.tsx@@ -0,0 +1,46 @@+import { LemonTag } from '@posthog/lemon-ui'++import ViewRecordingButton, {+ RecordingPlayerType,+ ViewRecordingButtonVariant,+} from 'lib/components/ViewRecordingButton/ViewRecordingButton'+import { PersonDisplay } from 'scenes/persons/PersonDisplay'++import type { TraceIdentity } from '../../traceIdentity'++export interface TraceIdentityChipsProps {+ identity: TraceIdentity+ /** Trace start, used to seek the recording to just before the trace ran. */+ timestamp: string | null+}++// Who the open trace belongs to. The person and the recording are properties of the trace, not of+// the inspected span, so this sits above the waterfall and does not change as the user walks spans.+// Server-only traffic carries no identity, and then this renders nothing.+// Modeled on AI Observability's trace-scene PersonChip.+export function TraceIdentityChips({ identity, timestamp }: TraceIdentityChipsProps): JSX.Element | null {+ if (!identity.distinctId && !identity.sessionId) {+ return null+ }++ return (+ <div className="flex items-center gap-2 flex-wrap pb-2" data-attr="tracing-trace-identity">+ {identity.distinctId && (+ <LemonTag size="small" className="bg-surface-primary">+ <span className="sr-only">Person</span>+ <PersonDisplay person={{ distinct_id: identity.distinctId }} withIcon="sm" noEllipsis />+ </LemonTag>+ )}+ {identity.sessionId && (+ <ViewRecordingButton+ sessionId={identity.sessionId}+ timestamp={timestamp ?? undefined}+ openPlayerIn={RecordingPlayerType.Modal}+ variant={ViewRecordingButtonVariant.Link}+ checkRecordingExists+ data-attr="tracing-trace-view-recording"+ />+ )}+ </div>+ )+}diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsxindex 8e69dcaa684e..93f6cb046757 100644--- a/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx@@ -9,9 +9,7 @@ import ViewRecordingButton, {RecordingPlayerType,ViewRecordingButtonVariant,} from 'lib/components/ViewRecordingButton/ViewRecordingButton'-import { FEATURE_FLAGS } from 'lib/constants'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { PropertyFilterType, PropertyOperator } from '~/types'@@ -52,15 +50,14 @@ export function SpanAttributes({propertyType,}: SpanAttributesProps): JSX.Element {const { addFilter } = useActions(tracingFiltersLogic)- const { featureFlags } = useValues(featureFlagLogic)- const { configuredDistinctIdKeys, configuredSessionIdKeys } = useValues(tracingCorrelationConfigLogic)+ const { configuredDistinctIdKeys, configuredSessionIdKeys, correlationLinksEnabled } =+ useValues(tracingCorrelationConfigLogic)const [appliedFilter, setAppliedFilter] = useState<{ key: string; direction: FilterDirection } | null>(null)const appliedFilterTimeoutRef = useRef<number | null>(null)// Person/replay links only apply to real OTel attribute tables (propertyType set), because// the synthetic "Span details" table repeats span metadata under conventional-looking keys.- const correlationLinksEnabled =- !!featureFlags[FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS] && propertyType !== undefined+ const showCorrelationLinks = correlationLinksEnabled && propertyType !== undefineduseEffect(() => () => {@@ -147,7 +144,7 @@ export function SpanAttributes({}// The stopPropagation wrapper keeps a link click from also triggering any// ancestor row handler, matching SpanRowActions' convention.- const correlationLink = !correlationLinksEnabled ? null : isDistinctIdKey(+ const correlationLink = !showCorrelationLinks ? null : isDistinctIdKey(record.key,configuredDistinctIdKeys) ? (diff --git a/products/tracing/frontend/traceIdentity.test.ts b/products/tracing/frontend/traceIdentity.test.tsnew file mode 100644index 000000000000..f6df6081872a--- /dev/null+++ b/products/tracing/frontend/traceIdentity.test.ts@@ -0,0 +1,47 @@+import { makeSpan } from './__mocks__/span'+import { resolveTraceIdentity, type TraceIdentity } from './traceIdentity'+import type { Span } from './types'++describe('resolveTraceIdentity', () => {+ const cases: {+ name: string+ spans: Span[]+ distinctIdKeys?: string[]+ sessionIdKeys?: string[]+ expected: TraceIdentity+ }[] = [+ {+ name: 'reads an identity carried by a later span, not just the first',+ spans: [makeSpan({}), makeSpan({ attributes: { posthogDistinctId: 'user-1', sessionId: 'session-1' } })],+ expected: { distinctId: 'user-1', sessionId: 'session-1' },+ },+ {+ name: 'drops a value the spans disagree on, and keeps the one they agree on',+ spans: [+ makeSpan({ attributes: { posthogDistinctId: 'user-1', sessionId: 'session-1' } }),+ makeSpan({ attributes: { posthogDistinctId: 'user-2', sessionId: 'session-1' } }),+ ],+ expected: { distinctId: null, sessionId: 'session-1' },+ },+ {+ name: 'resolves nothing from spans that carry no correlation keys',+ spans: [makeSpan({ attributes: { 'http.method': 'GET' }, resource_attributes: { 'k8s.pod.name': 'p' } })],+ expected: { distinctId: null, sessionId: null },+ },+ {+ name: 'prefers a configured key over a convention key on the same span',+ spans: [makeSpan({ attributes: { 'user.id': 'configured-user', posthogDistinctId: 'convention-user' } })],+ distinctIdKeys: ['user.id'],+ expected: { distinctId: 'configured-user', sessionId: null },+ },+ {+ name: 'falls back to resource attributes when the span attributes carry nothing',+ spans: [makeSpan({ resource_attributes: { posthogDistinctId: 'user-1', sessionId: 'session-1' } })],+ expected: { distinctId: 'user-1', sessionId: 'session-1' },+ },+ ]++ test.each(cases)('$name', ({ spans, distinctIdKeys, sessionIdKeys, expected }) => {+ expect(resolveTraceIdentity(spans, distinctIdKeys, sessionIdKeys)).toEqual(expected)+ })+})diff --git a/products/tracing/frontend/traceIdentity.ts b/products/tracing/frontend/traceIdentity.tsnew file mode 100644index 000000000000..f51fee591925--- /dev/null+++ b/products/tracing/frontend/traceIdentity.ts@@ -0,0 +1,55 @@+// Resolve the person and session a whole trace belongs to, so the drawer can answer "who was+// this?" in its header instead of leaving the answer in a span's attribute table.++// The per-span precedence and the convention key lists are shared with Logs, because both+// products resolve the same SDK-emitted attribute keys (posthogDistinctId, sessionId, ...).+import { getDistinctIdWithKey, getSessionIdWithKey } from 'products/logs/frontend/utils'++import type { Span } from './types'++export interface TraceIdentity {+ readonly distinctId: string | null+ readonly sessionId: string | null+}++// One shared instance, so a caller that resolves nothing does not invalidate its consumers.+export const EMPTY_TRACE_IDENTITY: TraceIdentity = { distinctId: null, sessionId: null }++type IdentityResolver = typeof getDistinctIdWithKey++function singleValueAcrossSpans(+ spans: Span[],+ resolve: IdentityResolver,+ configuredKeys: string[] | undefined+): string | null {+ let resolved: string | null = null++ for (const span of spans) {+ const value = resolve(span.attributes, span.resource_attributes, configuredKeys)?.value+ if (!value) {+ continue+ }+ if (resolved !== null && resolved !== value) {+ // A trace that touches more than one identity, which a batch consumer working+ // through several users' items does. Promoting either value would state a fact the+ // trace does not support, so the span attribute table stays the only place it appears.+ return null+ }+ resolved = value+ }+ return resolved+}++export function resolveTraceIdentity(+ spans: Span[],+ configuredDistinctIdKeys: string[] | undefined,+ configuredSessionIdKeys: string[] | undefined+): TraceIdentity {+ if (spans.length === 0) {+ return EMPTY_TRACE_IDENTITY+ }+ return {+ distinctId: singleValueAcrossSpans(spans, getDistinctIdWithKey, configuredDistinctIdKeys),+ sessionId: singleValueAcrossSpans(spans, getSessionIdWithKey, configuredSessionIdKeys),+ }+}diff --git a/products/tracing/frontend/tracingCorrelationConfigLogic.ts b/products/tracing/frontend/tracingCorrelationConfigLogic.tsindex 8d28686efd2e..e002315f166c 100644--- a/products/tracing/frontend/tracingCorrelationConfigLogic.ts+++ b/products/tracing/frontend/tracingCorrelationConfigLogic.ts@@ -2,6 +2,8 @@ import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { teamLogic } from 'scenes/teamLogic'import type { PatchedTeamTracingConfigApi, TeamTracingConfigApi } from 'products/tracing/frontend/generated/api.schemas'@@ -17,9 +19,11 @@ export const DEFAULT_TRACING_SESSION_ID_ATTRIBUTE_KEYS = ['sessionId']// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingCorrelationConfigLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeamId: number | null // teamLogicconfiguredDistinctIdKeys: string[] | undefinedconfiguredSessionIdKeys: string[] | undefined+ correlationLinksEnabled: booleantracingConfig: TeamTracingConfigApi | nulltracingConfigLoading: boolean}@@ -63,6 +67,7 @@ export interface tracingCorrelationConfigLogicMeta {__keaTypeGenInternalSelectorTypes: {configuredDistinctIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefinedconfiguredSessionIdKeys: (tracingConfig: TeamTracingConfigApi | null) => string[] | undefined+ correlationLinksEnabled: (featureFlags: FeatureFlagsSet) => boolean}}@@ -75,7 +80,7 @@ export type tracingCorrelationConfigLogicType = MakeLogicType<export const tracingCorrelationConfigLogic = kea<tracingCorrelationConfigLogicType>([path(['products', 'tracing', 'frontend', 'tracingCorrelationConfigLogic']),- connect({ values: [teamLogic, ['currentTeamId']] }),+ connect({ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']] }),loaders(({ values }) => ({tracingConfig: [null as TeamTracingConfigApi | null,@@ -110,8 +115,17 @@ export const tracingCorrelationConfigLogic = kea<tracingCorrelationConfigLogicTy(tracingConfig: TeamTracingConfigApi | null): string[] | undefined =>tracingConfig?.tracing_session_id_attribute_keys,],+ // Single owner of the "link spans to persons and session replay?" rule, so the drawer+ // header and the span attribute table cannot drift apart.+ correlationLinksEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS],+ ],}),- afterMount(({ actions }) => {- actions.loadTracingConfig()+ afterMount(({ actions, values }) => {+ // This config only feeds correlation links, so skip the request when they are off.+ if (values.correlationLinksEnabled) {+ actions.loadTracingConfig()+ }}),])diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 2f196d47e229..a461d27190d5 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -16,6 +16,7 @@ import type { AggregatedSpanRow, DateRange, SpanTreeNode } from '../../../fronteimport type { UniversalFiltersGroup } from '../../../frontend/src/types'import type { TracingDurationHistogramData, VisibleDurationRange } from './durationBuckets'import type { TracingLatencyHeatmapData } from './durationBuckets'+import type { TraceIdentity } from './traceIdentity'import { tracingDataLogic } from './tracingDataLogic'import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'import {@@ -98,6 +99,7 @@ export interface tracingSceneLogicValues {selectedSpanId: string | null // tracingViewerLogicselectedTraceId: string | null // tracingViewerLogicselectedTraceTs: string | null // tracingViewerLogic+ traceIdentity: TraceIdentity // tracingViewerLogicactiveTracingTab: 'operations' | 'traces'breadcrumbs: Breadcrumb[]displayMode: TracingDisplayMode@@ -295,6 +297,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['selectedTraceTs','isTraceOpen','openTraceSpans',+ 'traceIdentity','isLoadingFullTrace','canLoadMoreTraceSpans','compareFlameSpanName',diff --git a/products/tracing/frontend/tracingViewerLogic.test.ts b/products/tracing/frontend/tracingViewerLogic.test.tsindex 38fa04793f52..bca371c85970 100644--- a/products/tracing/frontend/tracingViewerLogic.test.ts+++ b/products/tracing/frontend/tracingViewerLogic.test.ts@@ -1,31 +1,15 @@import { expectLogic } from 'kea-test-utils'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { initKeaTests } from '~/test/init'+import { makeSpan } from './__mocks__/span'import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'import { tracingFiltersLogic } from './tracingFiltersLogic'import { tracingViewerLogic } from './tracingViewerLogic'-import type { Span } from './types'--const createMockSpan = (uuid: string, traceId: string): Span => ({- uuid,- trace_id: traceId,- span_id: uuid,- parent_span_id: '',- name: 'op',- kind: 1,- service_name: 'svc',- status_code: 1,- timestamp: '2024-01-01T00:00:00Z',- end_time: '2024-01-01T00:00:00Z',- duration_nano: 1000,- is_root_span: true,- matched_filter: true,- attributes: {},- resource_attributes: {},-})describe('tracingViewerLogic', () => {let logic: ReturnType<typeof tracingViewerLogic.build>@@ -54,7 +38,9 @@ describe('tracingViewerLogic', () => {['a partial prefetch batch', 2, false],['a possibly-truncated full batch', PREFETCH_SPANS, true],])('openTrace with %s %s', (_name, spanCount, shouldFetch) => {- const spans = Array.from({ length: spanCount }, (_, i) => createMockSpan(`span-${i}`, 'trace-x'))+ const spans = Array.from({ length: spanCount }, (_, i) =>+ makeSpan({ uuid: `span-${i}`, span_id: `span-${i}`, trace_id: 'trace-x' })+ )tracingDataLogic().actions.fetchSpansSuccess(spans)logic.actions.openTrace('trace-x', { ts: '2024-01-01T00:00:00Z' })@@ -63,6 +49,69 @@ describe('tracingViewerLogic', () => {expect(getTraceSpy.mock.calls.length > 0).toBe(shouldFetch)})+ describe('traceIdentity', () => {+ // 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(() => {+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ })++ function enableCorrelationLinks(): void {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS], {+ [FEATURE_FLAGS.TRACING_SESSION_PERSON_LINKS]: true,+ })+ }++ // A partial prefetch batch is the trace's complete span set, so no fetch runs and the+ // identity resolves from it.+ function openCompleteTrace(attributes: Record<string, string>): void {+ tracingDataLogic().actions.fetchSpansSuccess([+ makeSpan({ uuid: 'span-0', span_id: 'span-0', trace_id: 'trace-x', attributes }),+ makeSpan({ uuid: 'span-1', span_id: 'span-1', trace_id: 'trace-x' }),+ ])+ logic.actions.openTrace('trace-x', { ts: '2024-01-01T00:00:00Z' })+ }++ it('resolves the person and session the open trace belongs to', () => {+ enableCorrelationLinks()++ openCompleteTrace({ posthogDistinctId: 'user-1', sessionId: 'session-1' })++ expect(logic.values.traceIdentity).toEqual({ distinctId: 'user-1', sessionId: 'session-1' })+ })++ it('resolves nothing while the flag is off', () => {+ openCompleteTrace({ posthogDistinctId: 'user-1', sessionId: 'session-1' })++ expect(logic.values.traceIdentity).toEqual({ distinctId: null, sessionId: null })+ })++ // "The spans disagree, so promote neither" can only be decided over the whole trace, so a+ // known-partial span set must resolve nothing rather than trust the page it has.+ it('resolves nothing while more spans can still load', async () => {+ enableCorrelationLinks()+ getTraceSpy.mockResolvedValue({+ results: [+ makeSpan({+ uuid: 'span-0',+ span_id: 'span-0',+ trace_id: 'trace-x',+ attributes: { posthogDistinctId: 'user-1' },+ }),+ ],+ hasMore: true,+ nextOffset: 1,+ })++ logic.actions.openTrace('trace-x', { ts: '2024-01-01T00:00:00Z' })+ await expectLogic(tracingDataLogic()).toFinishAllListeners()++ expect(logic.values.canLoadMoreTraceSpans).toBe(true)+ expect(logic.values.traceIdentity).toEqual({ distinctId: null, sessionId: null })+ })+ })+describe('closeTrace', () => {// The attribute buttons in the drawer queue their query for when the drawer closes.// Without this, closing the drawer would silently drop the filter the user just added.diff --git a/products/tracing/frontend/tracingViewerLogic.ts b/products/tracing/frontend/tracingViewerLogic.tsindex 181b74fec5aa..b928c4454783 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 { EMPTY_TRACE_IDENTITY, resolveTraceIdentity, 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'@@ -12,6 +14,9 @@ export interface TracingViewerLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingViewerLogicValues {+ configuredDistinctIdKeys: string[] | undefined // tracingCorrelationConfigLogic+ configuredSessionIdKeys: string[] | undefined // tracingCorrelationConfigLogic+ correlationLinksEnabled: boolean // tracingCorrelationConfigLogicspans: Span[] // tracingDataLogictraceSpans: Span[] // tracingDataLogictraceSpansHasMore: boolean // tracingDataLogic@@ -27,6 +32,7 @@ export interface tracingViewerLogicValues {selectedSpanId: string | nullselectedTraceId: string | nullselectedTraceTs: string | null+ traceIdentity: TraceIdentity}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -100,6 +106,14 @@ export interface tracingViewerLogicMeta {traceSpans: Span[],selectedTraceId: string | null) => boolean+ traceIdentity: (+ openTraceSpans: Span[],+ canLoadMoreTraceSpans: boolean,+ traceSpansLoading: boolean,+ configuredDistinctIdKeys: string[] | undefined,+ configuredSessionIdKeys: string[] | undefined,+ correlationLinksEnabled: boolean+ ) => TraceIdentity}}@@ -124,6 +138,8 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([['spans', 'traceSpans', 'traceSpansLoading', 'traceSpansLoadingMore', 'traceSpansHasMore'],tracingFiltersLogic({ id }),['hasDeferredFilterRefresh'],+ tracingCorrelationConfigLogic,+ ['configuredDistinctIdKeys', 'configuredSessionIdKeys', 'correlationLinksEnabled'],],actions: [tracingDataLogic({ id }),@@ -220,6 +236,36 @@ export const tracingViewerLogic = kea<tracingViewerLogicType>([!!selectedTraceId &&traceSpans.some((span: Span) => span.trace_id === selectedTraceId),],+ // The person and session the open trace belongs to.+ traceIdentity: [+ (s) => [+ s.openTraceSpans,+ s.canLoadMoreTraceSpans,+ s.traceSpansLoading,+ s.configuredDistinctIdKeys,+ s.configuredSessionIdKeys,+ s.correlationLinksEnabled,+ ],+ (+ openTraceSpans: Span[],+ canLoadMoreTraceSpans: boolean,+ traceSpansLoading: boolean,+ configuredDistinctIdKeys: string[] | undefined,+ configuredSessionIdKeys: string[] | undefined,+ correlationLinksEnabled: boolean+ ): TraceIdentity => {+ // Both guards run 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.+ if (canLoadMoreTraceSpans || traceSpansLoading) {+ return EMPTY_TRACE_IDENTITY+ }+ return resolveTraceIdentity(openTraceSpans, configuredDistinctIdKeys, configuredSessionIdKeys)+ },+ ],}),listeners(({ actions, values }) => ({