: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): add latency heatmap view to the operation detail page (#71581)
Jon McCallum66c7c6a1ddf8
diff --git a/products/tracing/frontend/OperationHistogram.tsx b/products/tracing/frontend/OperationHistogram.tsxindex 834f39491b07..80224d32be01 100644--- a/products/tracing/frontend/OperationHistogram.tsx+++ b/products/tracing/frontend/OperationHistogram.tsx@@ -21,6 +21,8 @@ interface OperationHistogramProps {onClear: () => void/** Clearing the selection refetches samples — disable the button while that's in flight. */samplesLoading?: boolean+ /** Extra header content, right-aligned (e.g. the histogram/heatmap chart toggle). */+ actions?: React.ReactNode}export function OperationHistogram({@@ -30,6 +32,7 @@ export function OperationHistogram({onSelect,onClear,samplesLoading = false,+ actions,}: OperationHistogramProps): JSX.Element {const onSelectionChange = useCallback(({ startIndex, endIndex }: { startIndex: number; endIndex: number }): void => {@@ -84,6 +87,7 @@ export function OperationHistogram({) : (<span className="text-xs text-muted italic">Drag to select a duration range</span>)}+ {actions && <div className="ml-auto">{actions}</div>}</div><div className="relative h-32">{data.data.length > 0 ? (diff --git a/products/tracing/frontend/TracingOperationScene.tsx b/products/tracing/frontend/TracingOperationScene.tsxindex dd496e648205..b65091639645 100644--- a/products/tracing/frontend/TracingOperationScene.tsx+++ b/products/tracing/frontend/TracingOperationScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconChevronLeft, IconChevronRight } from '@posthog/icons'-import { LemonButton, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonButton, LemonSegmentedButton, LemonTag, Link, SpinnerOverlay } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'@@ -14,10 +14,16 @@ import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { formatBucketLabel } from './durationBuckets'import { OperationHistogram } from './OperationHistogram'import { errorRate, formatErrorRate } from './OperationsTable'import { formatDuration, TraceWaterfallView } from './TraceWaterfallView'-import { tracingOperationSceneLogic, type TracingOperationSceneLogicProps } from './tracingOperationSceneLogic'+import { TracingLatencyHeatmap } from './TracingLatencyHeatmap'+import {+ type OperationChartType,+ tracingOperationSceneLogic,+ type TracingOperationSceneLogicProps,+} from './tracingOperationSceneLogic'export const scene: SceneExport<TracingOperationSceneLogicProps> = {component: TracingOperationScene,@@ -29,6 +35,26 @@ export const scene: SceneExport<TracingOperationSceneLogicProps> = {productKey: ProductKey.TRACING,}+function OperationChartToggle({+ chartType,+ onChange,+}: {+ chartType: OperationChartType+ onChange: (chartType: OperationChartType) => void+}): JSX.Element {+ return (+ <LemonSegmentedButton+ size="xsmall"+ value={chartType}+ onChange={(value) => onChange(value as OperationChartType)}+ options={[+ { value: 'histogram', label: 'Histogram' },+ { value: 'heatmap', label: 'Heatmap' },+ ]}+ />+ )+}+function StatBlock({ label, value }: { label: string; value: string }): JSX.Element {return (<div className="flex flex-col">@@ -55,8 +81,13 @@ export function TracingOperationScene(): JSX.Element {sampleTraceSpansLoading,selectedSpanId,operationStats,+ chartType,+ latencyHeatmapData,+ rawLatencyHeatmapLoading,+ heatmapEnabled,} = useValues(tracingOperationSceneLogic)- const { setDateRange, setDurationSelection, setSampleIndex, selectSpan } = useActions(tracingOperationSceneLogic)+ const { setDateRange, setDurationSelection, setSampleIndex, selectSpan, setChartType, applyHeatmapBrush } =+ useActions(tracingOperationSceneLogic)if (!spanName || !serviceName) {return (@@ -99,14 +130,56 @@ export function TracingOperationScene(): JSX.Element {<StatBlock label="p99" value={formatDuration(operationStats.p99_duration_nano)} /></div>)}- <OperationHistogram- data={histogramData}- loading={rawHistogramLoading}- selection={durationSelection}- onSelect={setDurationSelection}- onClear={() => setDurationSelection(null)}- samplesLoading={samplesLoading}- />+ {heatmapEnabled && chartType === 'heatmap' ? (+ <div className="flex flex-col gap-1">+ <div className="flex items-center gap-2 min-h-6">+ <span className="text-xs text-muted">Latency heatmap</span>+ {durationSelection ? (+ <>+ <span className="text-xs font-mono">+ {formatBucketLabel(durationSelection.minNs)} –{' '}+ {formatBucketLabel(durationSelection.maxNs)}+ </span>+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => setDurationSelection(null)}+ disabledReason={samplesLoading ? 'Loading samples…' : undefined}+ >+ Clear+ </LemonButton>+ </>+ ) : (+ <span className="text-xs text-muted italic">+ Drag to select a time window and duration range+ </span>+ )}+ <div className="ml-auto">+ <OperationChartToggle chartType={chartType} onChange={setChartType} />+ </div>+ </div>+ <div className="relative h-32">+ <TracingLatencyHeatmap+ data={latencyHeatmapData}+ loading={rawLatencyHeatmapLoading}+ displayTimezone="UTC"+ onBrush={applyHeatmapBrush}+ />+ </div>+ </div>+ ) : (+ <OperationHistogram+ data={histogramData}+ loading={rawHistogramLoading}+ selection={durationSelection}+ onSelect={setDurationSelection}+ onClear={() => setDurationSelection(null)}+ samplesLoading={samplesLoading}+ actions={+ heatmapEnabled ? <OperationChartToggle chartType={chartType} onChange={setChartType} /> : null+ }+ />+ )}<SceneDivider />{samples.length === 0 && samplesLoading ? (<div className="relative min-h-32">diff --git a/products/tracing/frontend/tracingOperationSceneLogic.test.ts b/products/tracing/frontend/tracingOperationSceneLogic.test.tsindex 056ad581fff9..574ab20ec18d 100644--- a/products/tracing/frontend/tracingOperationSceneLogic.test.ts+++ b/products/tracing/frontend/tracingOperationSceneLogic.test.ts@@ -101,6 +101,66 @@ describe('tracingOperationSceneLogic', () => {expect(logic.values.sampleIndex).toBe(0)})+ it('a heatmap brush zooms the date range at bucket edges and applies the duration selection', () => {+ const MS = 1_000_000+ logic.actions.fetchLatencyHeatmapSuccess([+ { time: '2024-01-01T00:00:00Z', bucket_ns: 1 * MS, count: 1 },+ { time: '2024-01-01T00:10:00Z', bucket_ns: 2 * MS, count: 1 },+ { time: '2024-01-01T00:20:00Z', bucket_ns: 5 * MS, count: 1 },+ ])++ logic.actions.applyHeatmapBrush({ x: { startIndex: 0, endIndex: 1 }, y: { startIndex: 1, endIndex: 1 } })+ // date_to is the START of the bucket after the last selected column; the 2ms row covers [2ms, 5ms).+ expect(logic.values.dateRange).toEqual({+ date_from: '2024-01-01T00:00:00Z',+ date_to: '2024-01-01T00:20:00Z',+ })+ expect(logic.values.durationSelection).toEqual({ minNs: 2 * MS, maxNs: 5 * MS })+ })++ it('a full-height heatmap brush is a time zoom that leaves the duration selection alone', () => {+ const MS = 1_000_000+ logic.actions.setDurationSelection({ minNs: 1 * MS, maxNs: 2 * MS })+ logic.actions.fetchLatencyHeatmapSuccess([+ { time: '2024-01-01T00:00:00Z', bucket_ns: 1 * MS, count: 1 },+ { time: '2024-01-01T00:10:00Z', bucket_ns: 5 * MS, count: 1 },+ ])++ logic.actions.applyHeatmapBrush({ x: { startIndex: 1, endIndex: 1 }, y: { startIndex: 0, endIndex: 2 } })+ expect(logic.values.dateRange.date_from).toBe('2024-01-01T00:10:00Z')+ expect(logic.values.durationSelection).toEqual({ minNs: 1 * MS, maxNs: 2 * MS })+ })++ it('preserves a completed empty heatmap instead of refetching it on every chart switch', () => {+ const heatmapSpy = jest.spyOn(api.tracing, 'latencyHeatmap').mockResolvedValue({ results: [] })+ // A completed fetch that returned no rows still counts as loaded.+ logic.actions.fetchLatencyHeatmapSuccess([])+ expect(logic.values.latencyHeatmapLoaded).toBe(true)++ logic.actions.setChartType('heatmap')+ expect(heatmapSpy).not.toHaveBeenCalled()+ })++ it('ignores a heatmap brush while a date-range refresh is still loading', async () => {+ const MS = 1_000_000+ const heatmapSpy = jest.spyOn(api.tracing, 'latencyHeatmap').mockResolvedValue({ results: [] })+ logic.actions.fetchLatencyHeatmapSuccess([+ { time: '2024-01-01T00:00:00Z', bucket_ns: 1 * MS, count: 1 },+ { time: '2024-01-01T00:10:00Z', bucket_ns: 2 * MS, count: 1 },+ { time: '2024-01-01T00:20:00Z', bucket_ns: 5 * MS, count: 1 },+ ])+ // A refresh is in flight: the grid on screen is now stale, so brushes must be ignored.+ logic.actions.fetchLatencyHeatmap()+ expect(logic.values.rawLatencyHeatmapLoading).toBe(true)++ logic.actions.applyHeatmapBrush({ x: { startIndex: 0, endIndex: 1 }, y: { startIndex: 1, endIndex: 1 } })+ expect(logic.values.durationSelection).toBeNull()++ // Settle the in-flight fetch so it can't resolve after the test ends.+ await logic.asyncActions.fetchLatencyHeatmap()+ expect(heatmapSpy).toHaveBeenCalled()+ })+// A trace longer than the ±1h lookup window can share a trace_id with the loaded waterfall yet// omit spans that fell outside it — reuse must be gated on the span actually being present.it.each([diff --git a/products/tracing/frontend/tracingOperationSceneLogic.ts b/products/tracing/frontend/tracingOperationSceneLogic.tsindex fa2befd4f4c5..de17cebb174b 100644--- a/products/tracing/frontend/tracingOperationSceneLogic.ts+++ b/products/tracing/frontend/tracingOperationSceneLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'@@ -6,10 +6,21 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { dataColorVars } from 'lib/colors'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { AggregatedSpanRow, DateRange } from '~/queries/schema/schema-general'-import { type DurationHistogramRow, pivotDurationHistogram, type TracingDurationHistogramData } from './durationBuckets'+import {+ type DurationHistogramRow,+ type LatencyHeatmapRow,+ pivotDurationHistogram,+ pivotLatencyHeatmap,+ selectionToDurationRange,+ type TracingDurationHistogramData,+ type TracingLatencyHeatmapData,+} from './durationBuckets'+import type { HeatmapBrushSelection } from './heatmapBrush'import { type DurationRange, operationFilterGroup } from './operationFilters'import { traceLookupDateRange } from './traceLinks'import { isUserInitiatedError, NEW_QUERY_STARTED_ERROR_MESSAGE } from './tracingDataLogic'@@ -21,18 +32,28 @@ export interface TracingOperationSceneLogicProps {spanName: string}+// Which chart shows the operation's latency: the static distribution or the over-time heatmap.+export type OperationChartType = 'histogram' | 'heatmap'+const SAMPLE_LIMIT = 100// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingOperationSceneLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ chartType: OperationChartTypecurrentSample: Span | nulldateRange: DateRangedurationSelection: DurationRange | null+ heatmapEnabled: booleanhistogramData: TracingDurationHistogramData+ latencyHeatmapData: TracingLatencyHeatmapData+ latencyHeatmapLoaded: booleanoperationStats: AggregatedSpanRow | nulloperationStatsLoading: booleanrawHistogram: DurationHistogramRow[]rawHistogramLoading: boolean+ rawLatencyHeatmap: LatencyHeatmapRow[]+ rawLatencyHeatmapLoading: booleansampleIndex: numbersampleTraceSpans: Span[]sampleTraceSpansLoading: boolean@@ -46,6 +67,16 @@ export interface tracingOperationSceneLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingOperationSceneLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+ applyHeatmapBrush: (selection: HeatmapBrushSelection) => {+ selection: HeatmapBrushSelection+ }fetchHistogram: (_: void) => voidfetchHistogramFailure: (error: string,@@ -69,6 +100,29 @@ export interface tracingOperationSceneLogicActions {}[]payload?: void}+ fetchLatencyHeatmap: (_: void) => void+ fetchLatencyHeatmapFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ fetchLatencyHeatmapSuccess: (+ rawLatencyHeatmap: {+ bucket_ns: number+ count: number+ time: string+ }[],+ payload?: void+ ) => {+ rawLatencyHeatmap: {+ bucket_ns: number+ count: number+ time: string+ }[]+ payload?: void+ }fetchSampleTrace: ({ sample }: { sample: Span }) => {sample: Span}@@ -126,6 +180,9 @@ export interface tracingOperationSceneLogicActions {selectSpan: (spanId: string | null) => {spanId: string | null}+ setChartType: (chartType: OperationChartType) => {+ chartType: OperationChartType+ }setDateRange: (dateRange: DateRange) => {dateRange: DateRange}@@ -146,7 +203,9 @@ export interface tracingOperationSceneLogicMeta {__keaTypeGenInternalSelectorTypes: {serviceName: (arg: any) => stringspanName: (arg: any) => string+ heatmapEnabled: (featureFlags: FeatureFlagsSet) => booleanhistogramData: (rawHistogram: DurationHistogramRow[]) => TracingDurationHistogramData+ latencyHeatmapData: (rawLatencyHeatmap: LatencyHeatmapRow[]) => TracingLatencyHeatmapDatacurrentSample: (samples: Span[], sampleIndex: number) => Span | null}}@@ -179,6 +238,11 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([key(({ serviceName, spanName }) => `${serviceName}//${spanName}`),path((key) => ['products', 'tracing', 'frontend', 'tracingOperationSceneLogic', key]),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ actions: [featureFlagLogic, ['setFeatureFlags']],+ })),+actions({setDateRange: (dateRange: DateRange) => ({ dateRange }),setDurationSelection: (selection: DurationRange | null) => ({ selection }),@@ -186,6 +250,9 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([selectSpan: (spanId: string | null) => ({ spanId }),setSamplesHaveMore: (hasMore: boolean) => ({ hasMore }),loadCurrentSampleTrace: true,+ setChartType: (chartType: OperationChartType) => ({ chartType }),+ // A completed 2D brush on the heatmap: x → date range, y → duration selection.+ applyHeatmapBrush: (selection: HeatmapBrushSelection) => ({ selection }),}),loaders(({ props, values, actions, cache }) => ({@@ -210,6 +277,23 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([},},],+ rawLatencyHeatmap: [+ [] as LatencyHeatmapRow[],+ {+ fetchLatencyHeatmap: async (_: void, breakpoint) => {+ await breakpoint(100)+ const response = await api.tracing.latencyHeatmap({+ dateRange: values.dateRange,+ serviceNames: [props.serviceName],+ filterGroup: operationFilterGroup(props.spanName, null),+ // Span-level, like the histogram — operations are often child spans.+ rootSpans: false,+ })+ breakpoint()+ return response.results+ },+ },+ ],samples: [[] as Span[],{@@ -276,6 +360,7 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([reducers({dateRange: [DEFAULT_DATE_RANGE as DateRange, { setDateRange: (_, { dateRange }) => dateRange }],durationSelection: [null as DurationRange | null, { setDurationSelection: (_, { selection }) => selection }],+ chartType: ['histogram' as OperationChartType, { setChartType: (_, { chartType }) => chartType }],sampleIndex: [0,{@@ -284,6 +369,15 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([setDateRange: () => 0,},],+ // Distinguishes "heatmap fetch completed" (possibly empty) from "never fetched". A date+ // change invalidates it so a later switch back to the heatmap refetches for the new range.+ latencyHeatmapLoaded: [+ false,+ {+ fetchLatencyHeatmapSuccess: () => true,+ setDateRange: () => false,+ },+ ],selectedSpanId: [null as string | null, { selectSpan: (_, { spanId }) => spanId }],samplesHaveMore: [false, { setSamplesHaveMore: (_, { hasMore }) => hasMore }],// A stale waterfall must not linger under a new (or empty) sample set.@@ -293,10 +387,18 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([selectors({serviceName: [() => [(_, props) => props.serviceName], (serviceName: string): string => serviceName],spanName: [() => [(_, props) => props.spanName], (spanName: string): string => spanName],+ heatmapEnabled: [+ (s) => [s.featureFlags],+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_LATENCY_HEATMAP],+ ],histogramData: [(s) => [s.rawHistogram],(rows: DurationHistogramRow[]): TracingDurationHistogramData => pivotDurationHistogram(rows, dataColorVars),],+ latencyHeatmapData: [+ (s) => [s.rawLatencyHeatmap],+ (rows: LatencyHeatmapRow[]): TracingLatencyHeatmapData => pivotLatencyHeatmap(rows),+ ],currentSample: [(s) => [s.samples, s.sampleIndex],(samples: Span[], sampleIndex: number): Span | null => samples[sampleIndex] ?? null,@@ -311,6 +413,57 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([actions.fetchHistogram()actions.fetchSamples()actions.fetchStats()+ if (values.chartType === 'heatmap') {+ actions.fetchLatencyHeatmap()+ }+ },+ setChartType: ({ chartType }) => {+ // Fetch lazily on first switch; date-range changes keep it fresh while active. Gate on+ // "has it ever loaded" rather than row count, so an operation with no data doesn't+ // refetch the same empty result every time the user flips back to the heatmap.+ if (chartType === 'heatmap' && !values.latencyHeatmapLoaded && !values.rawLatencyHeatmapLoading) {+ actions.fetchLatencyHeatmap()+ }+ },+ // Feature flags land asynchronously (posthog.js /flags), potentially after the URL+ // restore ran with the flag still off. Re-apply a ?chart=heatmap deep link once the+ // flag makes the heatmap available.+ setFeatureFlags: () => {+ if (+ values.heatmapEnabled &&+ router.values.searchParams.chart === 'heatmap' &&+ values.chartType !== 'heatmap'+ ) {+ actions.setChartType('heatmap')+ }+ },+ applyHeatmapBrush: ({ selection }) => {+ // While a date-range refetch is in flight the rendered heatmap still shows the+ // previous query's buckets. Ignore brushes until it settles so the selection maps+ // against the grid on screen rather than a stale one (mirrors the shared scene).+ if (values.rawLatencyHeatmapLoading) {+ return+ }+ const data = values.latencyHeatmapData+ const dateFrom = data.timeBuckets[selection.x.startIndex]+ if (!dateFrom) {+ return+ }+ // y first: setDateRange's listener refetches the samples, so the selection must be+ // in place when it fires. A full-height brush is a plain time zoom — selection kept.+ const spansAllRows = selection.y.startIndex <= 0 && selection.y.endIndex >= data.bucketsNs.length - 1+ if (!spansAllRows) {+ const range = selectionToDurationRange(data.bucketsNs, selection.y.startIndex, selection.y.endIndex)+ if (range) {+ actions.setDurationSelection(range)+ }+ }+ // Same bucket-edge convention as the main scene: date_to is the start of the bucket+ // after the last selected column, falling back to the current range end.+ actions.setDateRange({+ date_from: dateFrom,+ date_to: data.timeBuckets[selection.x.endIndex + 1] ?? values.dateRange.date_to ?? null,+ })},loadCurrentSampleTrace: () => {const sample = values.currentSample@@ -386,7 +539,7 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([actionToUrl(({ values }) => {const withSelectionParams = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {- const { min, max, sample, ...rest } = router.values.searchParams+ const { min, max, sample, chart, ...rest } = router.values.searchParamsconst params: Record<string, any> = { ...rest }if (values.durationSelection) {params.min = values.durationSelection.minNs@@ -395,11 +548,15 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([if (values.sampleIndex > 0) {params.sample = values.sampleIndex}+ if (values.chartType !== 'histogram') {+ params.chart = values.chartType+ }return [router.values.location.pathname, params, router.values.hashParams, { replace: true }]}return {setDurationSelection: withSelectionParams,setSampleIndex: withSelectionParams,+ setChartType: withSelectionParams,}}),@@ -418,6 +575,13 @@ export const tracingOperationSceneLogic = kea<tracingOperationSceneLogicType>([if (!isNaN(sample) && sample >= 0 && sample !== values.sampleIndex) {actions.setSampleIndex(sample)}+ // With the flag off a ?chart=heatmap deep link degrades to the histogram (and never+ // fetches heatmap data — this restore is the only non-toggle entry point).+ const chartFromUrl: OperationChartType =+ searchParams.chart === 'heatmap' && values.heatmapEnabled ? 'heatmap' : 'histogram'+ if (chartFromUrl !== values.chartType) {+ actions.setChartType(chartFromUrl)+ }},})),