: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 chart with explicit chart toggle (#71575)
Jon McCallum5f2bf7104ba2
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 561544109bf8..ca88d1a07d39 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -2976,6 +2976,24 @@ const api = {}> {return new ApiRequest().tracingSpans().withAction('duration-histogram').create({ signal, data: { query } })},+ async latencyHeatmap(+ query: {+ dateRange?: { date_from?: string | null; date_to?: string | null }+ serviceNames?: string[]+ statusCodes?: number[]+ filterGroup?: PropertyGroupFilter+ // true (default) buckets root spans only (a distribution of traces); false buckets+ // every matching span — pair with a span name filter for operation-scoped pages.+ rootSpans?: boolean+ },+ signal?: AbortSignal+ ): Promise<{+ // Sparse cells ordered by time then bucket. Every time bucket appears at least once —+ // empty buckets come back as a {time, bucket_ns: 0, count: 0} sentinel row.+ results: { time: string; bucket_ns: number; count: number }[]+ }> {+ return new ApiRequest().tracingSpans().withAction('latency-heatmap').create({ signal, data: { query } })+ },async aggregate(query: {dateRange?: { date_from?: string | null; date_to?: string | null }diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 39ff5d0dd986..4442a458e903 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -503,6 +503,7 @@ export const FEATURE_FLAGS = {TOOLBAR_HEATMAP_AREA_FILTER: 'toolbar-heatmap-area-filter', // owner: @pauldambra #team-replay, gates the target button that filters the toolbar heatmap/clickmap to a chosen page areaTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracing+ TRACING_LATENCY_HEATMAP: 'tracing-latency-heatmap', // owner: #team-apm — gates the latency-over-time heatmap chart in tracingTRACING_OPERATIONS_VIEW: 'tracing-operations-view', // owner: #team-apm — gates the Operations (per-operation aggregate) tab in tracingTRACING_SAVED_VIEWS: 'tracing-saved-views', // owner: #team-apm — gates saved views (saved filter sets) in tracingTRAFFIC_TYPE_VIRTUAL_PROPERTIES: 'traffic-type-virtual-properties', // owner: #team-web-analyticsdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9f410c9c334f..6ccfcbfbf60e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4452,6 +4452,9 @@ importers:'@posthog/icons':specifier: 'catalog:'+ '@posthog/quill-charts':+ specifier: workspace:*+ version: link:../../packages/quill/packages/charts'@testing-library/react':specifier: '*'diff --git a/products/tracing/frontend/TracingLatencyHeatmap.tsx b/products/tracing/frontend/TracingLatencyHeatmap.tsxnew file mode 100644index 000000000000..79ca537abc2b--- /dev/null+++ b/products/tracing/frontend/TracingLatencyHeatmap.tsx@@ -0,0 +1,82 @@+import { useCallback, useMemo } from 'react'++import { SpinnerOverlay } from '@posthog/lemon-ui'+import { Heatmap, useChartTheme } from '@posthog/quill-charts'++import { dayjs } from 'lib/dayjs'+import { shortTimeZone } from 'lib/utils/timezones'++import type { TracingLatencyHeatmapData } from './durationBuckets'++const MAX_X_TICKS = 6++interface TracingLatencyHeatmapProps {+ data: TracingLatencyHeatmapData+ loading: boolean+ displayTimezone: string+}++export function TracingLatencyHeatmap({ data, loading, displayTimezone }: TracingLatencyHeatmapProps): JSX.Element {+ const theme = useChartTheme()++ // Same tick density logic as TracingSparkline: pick a format for the window size and thin+ // the categorical axis down to ~6 labels.+ const tickFormat = useMemo(() => {+ if (!data.timeBuckets.length) {+ return 'HH:mm:ss'+ }+ const hoursDiff = dayjs(data.timeBuckets[data.timeBuckets.length - 1]).diff(dayjs(data.timeBuckets[0]), 'hours')+ if (hoursDiff <= 6) {+ return 'HH:mm:ss'+ } else if (hoursDiff <= 48) {+ return 'HH:mm'+ }+ return 'D MMM HH:mm'+ }, [data.timeBuckets])++ const tickStep = Math.max(1, Math.ceil(data.timeBuckets.length / MAX_X_TICKS))+ const xTickFormatter = useCallback(+ (label: string, index: number): string | null => {+ if (index % tickStep !== 0) {+ return null+ }+ const d = displayTimezone ? dayjs(label).tz(displayTimezone) : dayjs(label)+ return d.format(tickFormat)+ },+ [tickStep, tickFormat, displayTimezone]+ )++ const tooltipLabelFormatter = useCallback(+ (label: string): string => {+ const d = displayTimezone ? dayjs(label).tz(displayTimezone) : dayjs(label)+ const tz = displayTimezone === 'UTC' ? 'UTC' : (shortTimeZone(displayTimezone, d.toDate()) ?? 'Local')+ return `${d.format('D MMM YYYY HH:mm:ss')} ${tz}`+ },+ [displayTimezone]+ )++ const config = useMemo(+ () => ({ xTickFormatter, tooltip: { labelFormatter: tooltipLabelFormatter } }),+ [xTickFormatter, tooltipLabelFormatter]+ )++ return (+ // Flex column: the quill chart shell sizes itself with flex-1 and collapses to zero+ // height in a plain block container.+ <div className="relative h-full w-full flex flex-col">+ {data.cells.length > 0 ? (+ <Heatmap+ xLabels={data.timeBuckets}+ yLabels={data.labels}+ cells={data.cells}+ theme={theme}+ config={config}+ dataAttr="tracing-latency-heatmap"+ />+ ) : !loading ? (+ <div className="h-full text-muted flex items-center justify-center">No results matching filters</div>+ ) : null}+ {loading && <SpinnerOverlay />}+ </div>+ )+}diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 0ed5dff2cce4..0edfb1043300 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -93,6 +93,9 @@ function TracingSceneContents(): JSX.Element {durationHistogramLoading,visibleRowDurationRange,isDurationMode,+ latencyHeatmapData,+ latencyHeatmapLoading,+ showHeatmap,activeTracingTab,compareActive,} = useValues(tracingSceneLogic())@@ -109,11 +112,13 @@ function TracingSceneContents(): JSX.Element {loadMoreTraceSpans,setVisibleRowRange,setSort,+ setChartType,} = useActions(tracingSceneLogic())const { addProductIntent } = useActions(teamLogic)const { facetRailCollapsed } = useValues(tracingConfigLogic)const operationsViewEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]const facetRailEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_FACET_RAIL]+ const heatmapEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_LATENCY_HEATMAP]// Resolved aggregation window (ms) — turns span counts into a request rate.// Use sparklineWindowMs which correctly resolves relative date strings (e.g. '-1h').@@ -194,13 +199,20 @@ function TracingSceneContents(): JSX.Element {<SceneDivider /><TracingSparklinesparklineData={sparklineData}- sparklineLoading={sparklineLoading || (isDurationMode && durationHistogramLoading)}+ sparklineLoading={sparklineLoading || (isDurationMode && !showHeatmap && durationHistogramLoading)}onDateRangeChange={setDateRange}displayTimezone="UTC"compare={compareConfig}visibleRowDateRange={visibleRowDateRange}- durationHistogram={isDurationMode ? durationHistogramData : null}+ durationHistogram={isDurationMode && !showHeatmap ? durationHistogramData : null}visibleRowDurationRange={visibleRowDurationRange}+ chartType={filters.chartType}+ onChartTypeChange={heatmapEnabled ? setChartType : undefined}+ latencyHeatmap={showHeatmap ? latencyHeatmapData : null}+ latencyHeatmapLoading={latencyHeatmapLoading}+ heatmapDisabledReason={+ compareActive ? 'The heatmap is unavailable while comparing time windows' : null+ }/><div className="flex flex-row gap-2 flex-1 min-h-0">{facetRailEnabled && !facetRailCollapsed && <FacetRail />}diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsxindex 3538d0156f87..2b77e7dd0c6a 100644--- a/products/tracing/frontend/TracingSparkline.tsx+++ b/products/tracing/frontend/TracingSparkline.tsx@@ -1,7 +1,7 @@import { useCallback, useMemo, useState } from 'react'import { IconChevronDown } from '@posthog/icons'-import { LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonButton, LemonSegmentedButton, SpinnerOverlay } from '@posthog/lemon-ui'import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'import { dayjs } from 'lib/dayjs'@@ -10,9 +10,16 @@ import { shortTimeZone } from 'lib/utils/timezones'import { DateRange } from '~/queries/schema/schema-general'-import { type TracingDurationHistogramData, type VisibleDurationRange, snapDurationToBucket } from './durationBuckets'+import {+ type TracingDurationHistogramData,+ type TracingLatencyHeatmapData,+ type VisibleDurationRange,+ snapDurationToBucket,+} from './durationBuckets'import { SparklineCompareOverlay } from './SparklineCompareOverlay'import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'+import type { TracingChartType } from './tracingFiltersLogic'+import { TracingLatencyHeatmap } from './TracingLatencyHeatmap'// Duration buckets are categorical (1ms, 2ms, 5ms, ...) — the 1-2-5 series is already// log-spaced, so a plain category axis renders it evenly. Shared with OperationHistogram@@ -51,6 +58,16 @@ interface TracingSparklineProps {/** When set, render a duration histogram instead of the time series (list sorted by duration). */durationHistogram?: TracingDurationHistogramData | nullvisibleRowDurationRange?: VisibleDurationRange | null+ /** Which chart fills the slot. Omitted (or 'activity') keeps today's behavior; the chart-type+ * toggle only renders when `onChartTypeChange` is provided. */+ chartType?: TracingChartType+ onChartTypeChange?: (chartType: TracingChartType) => void+ /** When set, render the latency heatmap instead of the sparkline/histogram. The caller passes+ * it only when the heatmap should actually show (chartType 'heatmap' and no comparison). */+ latencyHeatmap?: TracingLatencyHeatmapData | null+ latencyHeatmapLoading?: boolean+ /** Disables the heatmap option with an explanation (e.g. while a comparison is active). */+ heatmapDisabledReason?: string | null}export function TracingSparkline({@@ -62,9 +79,15 @@ export function TracingSparkline({visibleRowDateRange,durationHistogram,visibleRowDurationRange,+ chartType = 'activity',+ onChartTypeChange,+ latencyHeatmap,+ latencyHeatmapLoading = false,+ heatmapDisabledReason,}: TracingSparklineProps): JSX.Element | null {const [collapsed, setCollapsed] = useState(false)- const durationMode = durationHistogram != null+ const heatmapMode = latencyHeatmap != null+ const durationMode = !heatmapMode && durationHistogram != nullconst { timeUnit, tickFormat } = useMemo(() => {if (!sparklineData.dates.length) {@@ -212,11 +235,35 @@ export function TracingSparkline({aria-controls="tracing-sparkline-content"><span className="text-xs text-muted">- {durationMode ? 'Duration distribution' : 'Volume over time'}+ {heatmapMode ? 'Latency heatmap' : durationMode ? 'Duration distribution' : 'Volume over time'}</span></LemonButton>+ {onChartTypeChange && (+ <LemonSegmentedButton+ size="xsmall"+ value={chartType}+ onChange={(value) => onChartTypeChange(value as TracingChartType)}+ options={[+ { value: 'activity', label: 'Activity' },+ {+ value: 'heatmap',+ label: 'Heatmap',+ disabledReason: heatmapDisabledReason ?? undefined,+ },+ ]}+ />+ )}</div>- {!collapsed && (+ {!collapsed && latencyHeatmap != null && (+ <div id="tracing-sparkline-content" className="relative h-32">+ <TracingLatencyHeatmap+ data={latencyHeatmap}+ loading={latencyHeatmapLoading}+ displayTimezone={displayTimezone}+ />+ </div>+ )}+ {!collapsed && !heatmapMode && (<div id="tracing-sparkline-content" className="relative h-32">{(durationHistogram ? durationHistogram.data : sparklineData.data).length > 0 ? (<Sparklinediff --git a/products/tracing/frontend/durationBuckets.test.ts b/products/tracing/frontend/durationBuckets.test.tsindex 786a229b7fc4..8f3392893a9e 100644--- a/products/tracing/frontend/durationBuckets.test.ts+++ b/products/tracing/frontend/durationBuckets.test.ts@@ -3,6 +3,7 @@ import {fillBucketSeries,formatBucketLabel,pivotDurationHistogram,+ pivotLatencyHeatmap,selectionToDurationRange,snapDurationToBucket,visibleDurationRange,@@ -88,6 +89,35 @@ describe('durationBuckets', () => {expect(selectionToDurationRange([], 0, 0)).toBeNull()})+ it('pivotLatencyHeatmap keeps sentinel-only time buckets on the x axis and fills the y series', () => {+ // Two data buckets (1ms at t0, 5ms at t2) plus a quiet t1 that only has the backend's+ // {bucket_ns: 0, count: 0} sentinel — t1 must stay on the axis with an all-zero column,+ // and the y axis must fill the missing 2ms bucket between the data rows.+ const rows = [+ { time: 't0', bucket_ns: 1 * MS, count: 3 },+ { time: 't1', bucket_ns: 0, count: 0 },+ { time: 't2', bucket_ns: 5 * MS, count: 2 },+ ]+ expect(pivotLatencyHeatmap(rows)).toEqual({+ timeBuckets: ['t0', 't1', 't2'],+ bucketsNs: [1 * MS, 2 * MS, 5 * MS],+ labels: ['1ms', '2ms', '5ms'],+ cells: [+ [3, 0, 0], // 1ms row+ [0, 0, 0], // 2ms row (gap-filled)+ [0, 0, 2], // 5ms row+ ],+ })+ })++ it('pivotLatencyHeatmap of an all-sentinel response keeps the x axis and no rows', () => {+ const rows = [+ { time: 't0', bucket_ns: 0, count: 0 },+ { time: 't1', bucket_ns: 0, count: 0 },+ ]+ expect(pivotLatencyHeatmap(rows)).toEqual({ timeBuckets: ['t0', 't1'], bucketsNs: [], labels: [], cells: [] })+ })+it('visibleDurationRange orders min/max regardless of sort direction and clamps indices', () => {const durations = [900, 500, 100] // DESC-sorted listexpect(visibleDurationRange({ startIndex: 0, stopIndex: 2 }, durations)).toEqual({ minNs: 100, maxNs: 900 })diff --git a/products/tracing/frontend/durationBuckets.ts b/products/tracing/frontend/durationBuckets.tsindex 8c719b0f1dcd..d46353ab57de 100644--- a/products/tracing/frontend/durationBuckets.ts+++ b/products/tracing/frontend/durationBuckets.ts@@ -115,6 +115,59 @@ export function pivotDurationHistogram(return { data, bucketsNs, labels: bucketsNs.map(formatBucketLabel) }}+export interface LatencyHeatmapRow {+ time: string+ bucket_ns: number+ count: number+}++export interface TracingLatencyHeatmapData {+ /** ISO start of every time bucket in the window, in order — the heatmap's x axis. */+ timeBuckets: string[]+ /** Filled 1-2-5 series, ascending — the heatmap's y axis, bottom row first. */+ bucketsNs: number[]+ labels: string[]+ /** cells[rowIndex][colIndex] counts, aligned with bucketsNs × timeBuckets. */+ cells: number[][]+}++/**+ * Pivot latency-heatmap rows into the quill Heatmap grid shape. The backend enumerates every+ * time bucket (empty ones as a {time, bucket_ns: 0, count: 0} sentinel), so the x axis comes+ * straight from the response; the y axis fills gaps along the 1-2-5 series like the histogram.+ */+export function pivotLatencyHeatmap(rows: LatencyHeatmapRow[]): TracingLatencyHeatmapData {+ const timeBuckets: string[] = []+ const timeIndex = new Map<string, number>()+ for (const row of rows) {+ if (!timeIndex.has(row.time)) {+ timeIndex.set(row.time, timeBuckets.length)+ timeBuckets.push(row.time)+ }+ }++ const dataRows = rows.filter((row) => row.count > 0)+ if (!dataRows.length) {+ return { timeBuckets, bucketsNs: [], labels: [], cells: [] }+ }++ const minBucket = Math.min(...dataRows.map((row) => row.bucket_ns))+ const maxBucket = Math.max(...dataRows.map((row) => row.bucket_ns))+ const bucketsNs = fillBucketSeries(minBucket, maxBucket)+ const bucketIndex = new Map(bucketsNs.map((bucket, index) => [bucket, index]))++ const cells = bucketsNs.map(() => timeBuckets.map(() => 0))+ for (const row of dataRows) {+ const rowIndex = bucketIndex.get(row.bucket_ns)+ const colIndex = timeIndex.get(row.time)+ if (rowIndex !== undefined && colIndex !== undefined) {+ cells[rowIndex][colIndex] += row.count+ }+ }++ return { timeBuckets, bucketsNs, labels: bucketsNs.map(formatBucketLabel), cells }+}+/** Exclusive upper edge of a 1-2-5 bucket — the next bucket on the series (1→2, 2→5, 5→10). */export function bucketUpperBound(bucketNs: number): number {return fillBucketSeries(bucketNs, bucketNs * 10)[1]diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex c3b30964f08d..af77a87378d0 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -19,7 +19,9 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { dataColorVars } from 'lib/colors'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'@@ -29,8 +31,11 @@ import type { DateRange } from '../../../frontend/src/queries/schema/schema-geneimport type { UniversalFiltersGroup } from '../../../frontend/src/types'import {type DurationHistogramRow,+ type LatencyHeatmapRow,pivotDurationHistogram,+ pivotLatencyHeatmap,type TracingDurationHistogramData,+ type TracingLatencyHeatmapData,type VisibleDurationRange,visibleDurationRange,} from './durationBuckets'@@ -110,6 +115,7 @@ export interface TracingDataLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingDataLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccompareActive: boolean // tracingFiltersLogiccurrentWindowMs: OverlayWindow // tracingFiltersLogicfilters: TracingFilters // tracingFiltersLogic@@ -140,6 +146,9 @@ export interface tracingDataLogicValues {previousEndMs: numberpreviousStartMs: number} | null+ latencyHeatmapAbortController: AbortController | null+ latencyHeatmapData: TracingLatencyHeatmapData+ latencyHeatmapLoading: booleanlistRowDurations: number[]listRows: Span[]matchingCounts: {@@ -151,8 +160,11 @@ export interface tracingDataLogicValues {nextCursor: string | nullrawDurationHistogram: DurationHistogramRow[]rawDurationHistogramLoading: boolean+ rawLatencyHeatmap: LatencyHeatmapRow[]+ rawLatencyHeatmapLoading: booleanrawSparklineData: SparklineRow[]rawSparklineDataLoading: boolean+ showHeatmap: booleanspanTree: {current: SpanTreeNode[]previous: SpanTreeNode[] | null@@ -183,6 +195,16 @@ export interface tracingDataLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingDataLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+ setChartType: (chartType: import('./tracingFiltersLogic').TracingChartType) => {+ chartType: import('./tracingFiltersLogic').TracingChartType+ } // tracingFiltersLogicsetComparison: (comparison: TimeComparison | null) => {comparison: TimeComparison | null} // tracingFiltersLogic@@ -221,6 +243,9 @@ export interface tracingDataLogicActions {cancelInProgressDurationHistogram: (controller: AbortController | null) => {controller: AbortController | null}+ cancelInProgressLatencyHeatmap: (controller: AbortController | null) => {+ controller: AbortController | null+ }cancelInProgressMatchingCounts: (controller: AbortController | null) => {controller: AbortController | null}@@ -308,6 +333,29 @@ export interface tracingDataLogicActions {}[]payload?: any}+ fetchLatencyHeatmap: () => any+ fetchLatencyHeatmapFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ fetchLatencyHeatmapSuccess: (+ rawLatencyHeatmap: {+ bucket_ns: number+ count: number+ time: string+ }[],+ payload?: any+ ) => {+ rawLatencyHeatmap: {+ bucket_ns: number+ count: number+ time: string+ }[]+ payload?: any+ }fetchMatchingCounts: () => anyfetchMatchingCountsFailure: (error: string,@@ -497,6 +545,9 @@ export interface tracingDataLogicActions {previousStartMs: number}}+ setLatencyHeatmapAbortController: (controller: AbortController | null) => {+ controller: AbortController | null+ }setMatchingCountsAbortController: (controller: AbortController | null) => {controller: AbortController | null}@@ -541,6 +592,8 @@ export interface tracingDataLogicMeta {filters: TracingFilters) => numberdurationHistogramData: (rawDurationHistogram: DurationHistogramRow[]) => TracingDurationHistogramData+ latencyHeatmapData: (rawLatencyHeatmap: LatencyHeatmapRow[]) => TracingLatencyHeatmapData+ showHeatmap: (filters: TracingFilters, compareActive: boolean, featureFlags: FeatureFlagsSet) => booleanlistRows: (spans: Span[], filters: TracingFilters) => Span[]listRowDurations: (listRows: Span[]) => number[]isDurationMode: (filters: TracingFilters, compareActive: boolean) => boolean@@ -583,6 +636,8 @@ export const tracingDataLogic = kea<tracingDataLogicType>(['compareActive','timeComparison',],+ featureFlagLogic,+ ['featureFlags'],],actions: [tracingFiltersLogic({ id }),@@ -592,10 +647,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>(['setFilterGroup','setSort','setViewMode',+ 'setChartType','setComparison','updateComparisonWindows','setFilters',],+ featureFlagLogic,+ ['setFeatureFlags'],],})),@@ -613,12 +671,14 @@ export const tracingDataLogic = kea<tracingDataLogicType>([cancelInProgressSparkline: (controller: AbortController | null) => ({ controller }),cancelInProgressMatchingCounts: (controller: AbortController | null) => ({ controller }),cancelInProgressDurationHistogram: (controller: AbortController | null) => ({ controller }),+ cancelInProgressLatencyHeatmap: (controller: AbortController | null) => ({ controller }),cancelInProgressAggregation: (controller: AbortController | null) => ({ controller }),cancelInProgressSpanTree: (controller: AbortController | null) => ({ controller }),setSpansAbortController: (controller: AbortController | null) => ({ controller }),setSparklineAbortController: (controller: AbortController | null) => ({ controller }),setMatchingCountsAbortController: (controller: AbortController | null) => ({ controller }),setDurationHistogramAbortController: (controller: AbortController | null) => ({ controller }),+ setLatencyHeatmapAbortController: (controller: AbortController | null) => ({ controller }),setAggregationAbortController: (controller: AbortController | null) => ({ controller }),setSpanTreeAbortController: (controller: AbortController | null) => ({ controller }),setHasMoreToLoad: (hasMore: boolean) => ({ hasMore }),@@ -655,6 +715,10 @@ export const tracingDataLogic = kea<tracingDataLogicType>([null as AbortController | null,{ setDurationHistogramAbortController: (_, { controller }) => controller },],+ latencyHeatmapAbortController: [+ null as AbortController | null,+ { setLatencyHeatmapAbortController: (_, { controller }) => controller },+ ],aggregationAbortController: [null as AbortController | null,{ setAggregationAbortController: (_, { controller }) => controller },@@ -706,6 +770,14 @@ export const tracingDataLogic = kea<tracingDataLogicType>([fetchDurationHistogramFailure: () => false,},],+ latencyHeatmapLoading: [+ false as boolean,+ {+ fetchLatencyHeatmap: () => true,+ fetchLatencyHeatmapSuccess: () => false,+ fetchLatencyHeatmapFailure: () => false,+ },+ ],aggregationLoading: [false as boolean,{@@ -1082,6 +1154,46 @@ export const tracingDataLogic = kea<tracingDataLogicType>([},},],+ rawLatencyHeatmap: [+ [] as LatencyHeatmapRow[],+ {+ fetchLatencyHeatmap: async () => {+ // Same scope semantics as the sparkline: the heatmap depends on the data scope+ // and the view mode (root spans vs every span), but not on sort or compare.+ // Skip the re-fetch when a sort toggle re-runs the query without changing scope.+ const scopeKey = JSON.stringify([+ values.utcDateRange,+ values.filters.serviceNames,+ values.queryFilterGroup,+ values.filters.viewMode,+ ])+ if (scopeKey === cache.latencyHeatmapScope) {+ return values.rawLatencyHeatmap+ }++ const controller = new AbortController()+ actions.cancelInProgressLatencyHeatmap(controller)++ const response = await api.tracing.latencyHeatmap(+ {+ dateRange: values.utcDateRange,+ serviceNames:+ values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,+ filterGroup: values.queryFilterGroup as PropertyGroupFilter,+ // Match the population the list shows: root spans in Traces view,+ // every matching span in Spans view.+ rootSpans: values.filters.viewMode === 'traces',+ },+ controller.signal+ )++ actions.setLatencyHeatmapAbortController(null)+ // Record the scope only after a successful fetch, so a failed/aborted request retries.+ cache.latencyHeatmapScope = scopeKey+ return response.results+ },+ },+ ],rawDurationHistogram: [[] as DurationHistogramRow[],{@@ -1172,6 +1284,22 @@ export const tracingDataLogic = kea<tracingDataLogicType>([(s) => [s.rawDurationHistogram],(rows: DurationHistogramRow[]): TracingDurationHistogramData => pivotDurationHistogram(rows, dataColorVars),],+ latencyHeatmapData: [+ (s) => [s.rawLatencyHeatmap],+ (rows: LatencyHeatmapRow[]): TracingLatencyHeatmapData => pivotLatencyHeatmap(rows),+ ],+ // Single owner of the "show the latency heatmap?" rule — gates the fetch, the rendering,+ // and the duration-histogram skip together. The feature-flag check here means a+ // ?chart=heatmap deep link with the flag off degrades to the activity chart without+ // fetching. The comparison overlay is a time-window drag surface, so the heatmap also+ // yields to the activity chart while comparing.+ showHeatmap: [+ (s) => [s.filters, s.compareActive, s.featureFlags],+ (filters: TracingFilters, compareActive: boolean, featureFlags: FeatureFlagsSet): boolean =>+ !!featureFlags[FEATURE_FLAGS.TRACING_LATENCY_HEATMAP] &&+ filters.chartType === 'heatmap' &&+ !compareActive,+ ],// The rows the list renders. 'traces' mode shows root spans only (one row per trace);// 'spans' mode shows every matching span (root and child) flat. The fetch passes flatSpans// to match, so in 'spans' mode the loaded spans are already the flat set.@@ -1259,6 +1387,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([setSort: ({ orderBy, orderDirection }) =>actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),setViewMode: ({ viewMode }) => actions.handleFilterChange('view_mode', { mode: viewMode }),+ setChartType: ({ chartType }) => actions.handleFilterChange('chart_type', { chart_type: chartType }),setComparison: ({ comparison }) =>actions.handleFilterChange('comparison', {enabled: comparison !== null,@@ -1267,6 +1396,14 @@ export const tracingDataLogic = kea<tracingDataLogicType>([}),// Bulk restores (URL params, saved views) re-query without an interaction capture.setFilters: () => actions.runQuery(),+ // Feature flags land asynchronously (posthog.js /flags), potentially after the first+ // runQuery. If that flip just made the heatmap visible (?chart=heatmap deep link with+ // the flag on), fetch the data the earlier runQuery skipped.+ setFeatureFlags: () => {+ if (values.showHeatmap && values.rawLatencyHeatmap.length === 0 && !values.latencyHeatmapLoading) {+ actions.fetchLatencyHeatmap()+ }+ },// Overlay drags only refetch the aggregation — the sparkline canvas range stays fixed// while the user moves windows around within it. The compare-flame refetch (viewer UI// state) lives in tracingViewerLogic.@@ -1278,7 +1415,11 @@ export const tracingDataLogic = kea<tracingDataLogicType>([// visually. The count endpoint feeds the "N traces/spans matching filters" label.actions.fetchSparkline()actions.fetchMatchingCounts()- if (values.isDurationMode) {+ if (values.showHeatmap) {+ actions.fetchLatencyHeatmap()+ }+ // The heatmap wins the chart slot, so skip the histogram fetch it would hide.+ if (values.isDurationMode && !values.showHeatmap) {actions.fetchDurationHistogram()}if (values.compareActive) {@@ -1311,6 +1452,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([}actions.setDurationHistogramAbortController(controller)},+ cancelInProgressLatencyHeatmap: ({ controller }) => {+ if (values.latencyHeatmapAbortController !== null) {+ values.latencyHeatmapAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)+ }+ actions.setLatencyHeatmapAbortController(controller)+ },cancelInProgressAggregation: ({ controller }) => {if (values.aggregationAbortController !== null) {values.aggregationAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)@@ -1355,6 +1502,13 @@ export const tracingDataLogic = kea<tracingDataLogicType>([lemonToast.error(`Failed to load more spans: ${error}`)}},+ // Surface a real fetch failure instead of letting the chart render an empty grid that+ // reads as "No results matching filters" — an unreachable endpoint is not an empty query.+ fetchLatencyHeatmapFailure: ({ error }) => {+ if (!isUserInitiatedError(error)) {+ lemonToast.error(`Failed to load the latency heatmap: ${error}`)+ }+ },})),events(({ values }) => ({@@ -1371,6 +1525,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([if (values.durationHistogramAbortController) {values.durationHistogramAbortController.abort('unmounting component')}+ if (values.latencyHeatmapAbortController) {+ values.latencyHeatmapAbortController.abort('unmounting component')+ }if (values.spanTreeAbortController) {values.spanTreeAbortController.abort('unmounting component')}diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.tsindex fa44696f0670..7659faa29cad 100644--- a/products/tracing/frontend/tracingFiltersLogic.ts+++ b/products/tracing/frontend/tracingFiltersLogic.ts@@ -13,6 +13,7 @@ export const DEFAULT_SERVICE_NAMES: string[] = []export const DEFAULT_ORDER_BY = 'timestamp' as constexport const DEFAULT_ORDER_DIRECTION = 'DESC' as constexport const DEFAULT_VIEW_MODE = 'traces' as const+export const DEFAULT_CHART_TYPE = 'activity' as const// Column the list is ordered by, and its direction. timestamp+DESC is "latest" (keyset paginated via// the `after` cursor); duration+DESC/ASC is slowest/fastest (offset paginated). See tracingDataLogic.@@ -23,6 +24,11 @@ export type TracingOrderDirection = 'ASC' | 'DESC'// matching span (root and child) flat — backed by the query's flatSpans param. See tracingDataLogic.export type TracingViewMode = 'traces' | 'spans'+// Which chart fills the scene's chart slot. 'activity' is today's behavior (volume bars, with the+// implicit duration-histogram flip under duration sort); 'heatmap' is the latency-over-time+// heatmap. Unavailable while a comparison is active (the compare overlay is time-window based).+export type TracingChartType = 'activity' | 'heatmap'+export interface OverlayWindow {startMs: numberendMs: number@@ -103,6 +109,7 @@ export interface TracingFilters {orderBy: TracingOrderByorderDirection: TracingOrderDirectionviewMode: TracingViewMode+ chartType: TracingChartTypecomparison: TracingComparison | null}@@ -146,6 +153,7 @@ export function combineWithPinnedFilters(// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingFiltersLogicValues {+ chartType: TracingChartTypecompareActive: booleancomparison: TracingComparison | nullcurrentWindowMs: OverlayWindow@@ -170,6 +178,9 @@ export interface tracingFiltersLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tracingFiltersLogicActions {+ setChartType: (chartType: TracingChartType) => {+ chartType: TracingChartType+ }setComparison: (comparison: TracingComparison | null) => {comparison: TimeComparison | null}@@ -221,6 +232,7 @@ export interface tracingFiltersLogicMeta {orderBy: TracingOrderBy,orderDirection: TracingOrderDirection,viewMode: TracingViewMode,+ chartType: TracingChartType,comparison: TimeComparison | null) => TracingFilterscompareActive: (comparison: TimeComparison | null) => boolean@@ -262,6 +274,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),setSort: (orderBy: TracingOrderBy, orderDirection: TracingOrderDirection) => ({ orderBy, orderDirection }),setViewMode: (viewMode: TracingViewMode) => ({ viewMode }),+ setChartType: (chartType: TracingChartType) => ({ chartType }),setComparison: (comparison: TracingComparison | null) => ({ comparison }),/*** Persist the user-dragged overlay windows ('custom' preset only). Both must be supplied.@@ -327,6 +340,13 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([setFilters: (state, { filters }) => filters.viewMode ?? state,},],+ chartType: [+ DEFAULT_CHART_TYPE as TracingChartType,+ {+ setChartType: (_, { chartType }) => chartType,+ setFilters: (state, { filters }) => filters.chartType ?? state,+ },+ ],comparison: [null as TracingComparison | null,{@@ -356,7 +376,16 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([selectors({filters: [- (s) => [s.dateRange, s.serviceNames, s.filterGroup, s.orderBy, s.orderDirection, s.viewMode, s.comparison],+ (s) => [+ s.dateRange,+ s.serviceNames,+ s.filterGroup,+ s.orderBy,+ s.orderDirection,+ s.viewMode,+ s.chartType,+ s.comparison,+ ],(dateRange: DateRange,serviceNames: string[],@@ -364,6 +393,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([orderBy: TracingOrderBy,orderDirection: TracingOrderDirection,viewMode: TracingViewMode,+ chartType: TracingChartType,comparison: TracingComparison | null): TracingFilters => ({dateRange,@@ -372,6 +402,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([orderBy,orderDirection,viewMode,+ chartType,comparison,}),],diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 3f63f5bd8761..03f78a3fb628 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -12,6 +12,7 @@ import { Breadcrumb } from '~/types'import type { AggregatedSpanRow, DateRange, SpanTreeNode } from '../../../frontend/src/queries/schema/schema-general'import type { UniversalFiltersGroup } from '../../../frontend/src/types'import type { TracingDurationHistogramData, VisibleDurationRange } from './durationBuckets'+import type { TracingLatencyHeatmapData } from './durationBuckets'import { tracingDataLogic } from './tracingDataLogic'import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'import {@@ -20,6 +21,7 @@ import {DEFAULT_ORDER_BY,DEFAULT_ORDER_DIRECTION,DEFAULT_SERVICE_NAMES,+ DEFAULT_CHART_TYPE,DEFAULT_VIEW_MODE,parseComparison,serializeComparison,@@ -50,7 +52,10 @@ export interface tracingSceneLogicValues {hasMoreToLoad: boolean // tracingDataLogichasRunQuery: boolean // tracingDataLogicisDurationMode: boolean // tracingDataLogic+ latencyHeatmapData: TracingLatencyHeatmapData // tracingDataLogic+ latencyHeatmapLoading: boolean // tracingDataLogiclistRows: Span[] // tracingDataLogic+ showHeatmap: boolean // tracingDataLogicspanTree: {current: SpanTreeNode[]previous: SpanTreeNode[] | null@@ -133,6 +138,9 @@ export interface tracingSceneLogicActions {startIndex: numberstopIndex: number} // tracingDataLogic+ setChartType: (chartType: import('./tracingFiltersLogic').TracingChartType) => {+ chartType: import('./tracingFiltersLogic').TracingChartType+ } // tracingFiltersLogicsetComparison: (comparison: TimeComparison | null) => {comparison: TimeComparison | null} // tracingFiltersLogic@@ -236,6 +244,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['durationHistogramLoading','visibleRowDurationRange','isDurationMode',+ 'latencyHeatmapData',+ 'latencyHeatmapLoading',+ 'showHeatmap',],tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs', 'compareActive'],@@ -271,6 +282,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['setFilterGroup','setSort','setViewMode',+ 'setChartType','setComparison','updateComparisonWindows','setFilters',@@ -441,6 +453,12 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([hasChanges = true}+ const chartTypeFromUrl = searchParams.chart === 'heatmap' ? 'heatmap' : DEFAULT_CHART_TYPE+ if (chartTypeFromUrl !== values.filters.chartType) {+ filtersFromUrl.chartType = chartTypeFromUrl+ hasChanges = true+ }+if (hasChanges) {actions.setFilters(filtersFromUrl)} else if (!values.hasRunQuery) {@@ -509,6 +527,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([if (values.filters.viewMode !== DEFAULT_VIEW_MODE) {searchParams.view = values.filters.viewMode}+ if (values.filters.chartType !== DEFAULT_CHART_TYPE) {+ searchParams.chart = values.filters.chartType+ }return [router.values.location.pathname, searchParams, router.values.hashParams, { replace: true }]}diff --git a/products/tracing/package.json b/products/tracing/package.jsonindex e6c6b55153c1..194a5163fc8c 100644--- a/products/tracing/package.json+++ b/products/tracing/package.json@@ -4,6 +4,7 @@"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short"},"dependencies": {+ "@posthog/quill-charts": "workspace:*","kea": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:",