Skip to content

: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.

feat(tracing): render volume and duration charts with quill charts (#86154)

Sam Penningtond6c6fb570bab
diff --git a/products/tracing/frontend/OperationHistogram.tsx b/products/tracing/frontend/OperationHistogram.tsx
index 80224d32be01..5e0a5f0dfc03 100644
--- a/products/tracing/frontend/OperationHistogram.tsx
+++ b/products/tracing/frontend/OperationHistogram.tsx
@@ -1,8 +1,18 @@
import { useCallback, useMemo } from 'react'
import { LemonButton, SpinnerOverlay } from '@posthog/lemon-ui'
+import {
+ BarChart,
+ type BarChartConfig,
+ type DateRangeZoomData,
+ DefaultTooltip,
+ HighlightedRange,
+ type Series,
+} from '@posthog/quill-charts'
-import { Sparkline } from 'lib/components/Sparkline'
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import {
formatBucketLabel,
@@ -11,7 +21,6 @@ import {
type TracingDurationHistogramData,
} from './durationBuckets'
import type { DurationRange } from './operationFilters'
-import { categoryDurationXScale } from './TracingSparkline'
interface OperationHistogramProps {
data: TracingDurationHistogramData
@@ -34,8 +43,22 @@ export function OperationHistogram({
samplesLoading = false,
actions,
}: OperationHistogramProps): JSX.Element {
+ const theme = useChartTheme()
+ const config = useChartConfig<BarChartConfig>(() => ({}), [])
+
+ const series = useMemo<Series[]>(
+ () =>
+ data.data.map((s) => ({
+ key: s.name,
+ label: s.name,
+ data: s.values,
+ color: getColorVar(s.color),
+ })),
+ [data.data]
+ )
+
const onSelectionChange = useCallback(
- ({ startIndex, endIndex }: { startIndex: number; endIndex: number }): void => {
+ ({ startIndex, endIndex }: DateRangeZoomData): void => {
const range = selectionToDurationRange(data.bucketsNs, startIndex, endIndex)
if (range) {
onSelect(range)
@@ -54,16 +77,13 @@ export function OperationHistogram({
const startIndexRaw = bucketsNs.indexOf(snapDurationToBucket(selection.minNs))
// maxNs is the exclusive upper edge — the highlight ends at the bar before it.
const endIndexRaw = bucketsNs.indexOf(snapDurationToBucket(selection.maxNs))
- // An off-axis edge clamps toward its near end; a selection entirely off the axis
- // (e.g. persisted before a date change reshaped the distribution) collapses to
- // start >= end and renders no highlight.
const startIndex = startIndexRaw !== -1 ? startIndexRaw : selection.minNs <= bucketsNs[0] ? 0 : bucketsNs.length
const endIndex =
endIndexRaw !== -1 ? endIndexRaw : selection.maxNs > bucketsNs[bucketsNs.length - 1] ? bucketsNs.length : 0
if (startIndex >= endIndex) {
return null
}
- return { xMin: labels[startIndex], xMax: labels[endIndex] ?? labels[labels.length - 1] }
+ return { start: labels[startIndex], end: labels[endIndex - 1] ?? labels[labels.length - 1] }
}, [selection, data])
return (
@@ -89,20 +109,27 @@ export function OperationHistogram({
)}
{actions && <div className="ml-auto">{actions}</div>}
</div>
- <div className="relative h-32">
+ <div className="relative h-32 flex flex-col">
{data.data.length > 0 ? (
- <Sparkline
+ <BarChart
+ series={series}
labels={data.labels}
- data={data.data}
- className="w-full h-full"
- onSelectionChange={onSelectionChange}
- withXScale={categoryDurationXScale}
- renderLabel={(label) => label}
- tooltipRowCutoff={100}
- hideZerosInTooltip
- sortTooltipByCount
- highlightedRange={highlightedRange}
- />
+ theme={theme}
+ config={config}
+ onDateRangeZoom={onSelectionChange}
+ tooltip={(ctx) => (
+ <DefaultTooltip
+ {...ctx}
+ hideZeroRows
+ sortedByValue
+ valueFormatter={(value) => humanFriendlyNumber(value)}
+ />
+ )}
+ >
+ {highlightedRange && (
+ <HighlightedRange start={highlightedRange.start} end={highlightedRange.end} />
+ )}
+ </BarChart>
) : !loading ? (
<div className="h-full text-muted flex items-center justify-center">No spans in this range</div>
) : null}
diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsx
index 15ac0b17129d..21dcc2ad9364 100644
--- a/products/tracing/frontend/TracingSparkline.tsx
+++ b/products/tracing/frontend/TracingSparkline.tsx
@@ -2,11 +2,25 @@ import { useCallback, useMemo, useState } from 'react'
import { IconChevronDown } from '@posthog/icons'
import { LemonButton, LemonSegmentedButton, SpinnerOverlay } from '@posthog/lemon-ui'
-import type { HeatmapBrushData } from '@posthog/quill-charts'
+import {
+ BarChart,
+ type BarChartConfig,
+ createXAxisTickCallback,
+ type DateRangeZoomData,
+ DefaultTooltip,
+ type HeatmapBrushData,
+ HighlightedRange,
+ type Series,
+ TimeSeriesBarChart,
+ type TimeSeriesBarChartConfig,
+ type TooltipContext,
+} from '@posthog/quill-charts'
-import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { shortTimeZone } from 'lib/utils/timezones'
import { DateRange } from '~/queries/schema/schema-general'
@@ -22,25 +36,6 @@ import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLo
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
-// so the two duration histograms render identically.
-export function categoryDurationXScale(scale: AnyScaleOptions): AnyScaleOptions {
- return {
- ...scale,
- type: 'category',
- ticks: {
- display: true,
- maxRotation: 0,
- maxTicksLimit: 8,
- font: {
- size: 10,
- lineHeight: 1,
- },
- },
- } as AnyScaleOptions
-}
-
interface CompareConfig {
fullStartMs: number
fullEndMs: number
@@ -90,84 +85,49 @@ export function TracingSparkline({
heatmapDisabledReason,
}: TracingSparklineProps): JSX.Element | null {
const [collapsed, setCollapsed] = useState(false)
+ const theme = useChartTheme()
const heatmapMode = latencyHeatmap != null
const durationMode = !heatmapMode && durationHistogram != null
- const { timeUnit, tickFormat } = useMemo(() => {
- if (!sparklineData.dates.length) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm:ss' }
- }
- const firstDate = dayjs(sparklineData.dates[0])
- const lastDate = dayjs(sparklineData.dates[sparklineData.dates.length - 1])
- const hoursDiff = lastDate.diff(firstDate, 'hours')
-
- if (hoursDiff <= 1) {
- return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }
- } else if (hoursDiff <= 6) {
- return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }
- } else if (hoursDiff <= 48) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
- }
- return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }
- }, [sparklineData.dates])
+ const seriesSource = durationMode ? durationHistogram!.data : sparklineData.data
+ const series = useMemo<Series[]>(
+ () =>
+ seriesSource.map((s) => ({
+ key: s.name,
+ label: s.name,
+ data: s.values,
+ color: getColorVar(s.color),
+ })),
+ [seriesSource]
+ )
- const withXScale = useCallback(
- (scale: AnyScaleOptions): AnyScaleOptions => {
- if (durationMode) {
- return categoryDurationXScale(scale)
- }
- return {
- ...scale,
- type: 'timeseries',
- ticks: {
- display: true,
- maxRotation: 0,
- maxTicksLimit: 6,
- font: {
- size: 10,
- lineHeight: 1,
- },
- callback: function (value: string | number) {
- const d = displayTimezone ? dayjs(value).tz(displayTimezone) : dayjs(value)
- return d.format(tickFormat)
- },
- },
- time: {
- unit: timeUnit,
- },
- } as AnyScaleOptions
- },
- [durationMode, timeUnit, tickFormat, displayTimezone]
+ // Duration mode is categorical (1ms, 2ms, ...); activity mode is a time axis keyed on ISO dates.
+ const timeConfig = useChartConfig<TimeSeriesBarChartConfig>(
+ () => ({
+ xAxis: {
+ tickFormatter: createXAxisTickCallback({ allDays: sparklineData.dates, timezone: displayTimezone }),
+ },
+ }),
+ [sparklineData.dates, displayTimezone]
)
+ const durationConfig = useChartConfig<BarChartConfig>(() => ({}), [])
- const renderLabel = useCallback(
+ const tooltipLabelFormatter = useCallback(
(label: string): string => {
- if (durationMode) {
- return label // bucket labels ("2ms") are already human-readable
- }
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}`
},
- [durationMode, displayTimezone]
+ [displayTimezone]
)
- const sparklineLabels = useMemo(() => {
- if (durationHistogram) {
- return durationHistogram.labels
- }
- return sparklineData.dates.map((date: string) => dayjs(date).toISOString())
- }, [durationHistogram, sparklineData.dates])
-
// Map the visible rows' duration range onto histogram bucket indices: snap each edge onto
// the same 1-2-5 series the backend bucketed with, then find those buckets on the axis.
- const durationHighlightedRange = useMemo(() => {
+ const durationHighlight = useMemo(() => {
if (!durationHistogram || !visibleRowDurationRange || durationHistogram.bucketsNs.length === 0) {
return null
}
const { bucketsNs, labels } = durationHistogram
- // An edge missing from the axis can only mean it's outside the rendered range (the axis
- // spans the data's min..max bucket), so clamp it to the nearest end.
const startIndexRaw = bucketsNs.indexOf(snapDurationToBucket(visibleRowDurationRange.minNs))
const endIndexRaw = bucketsNs.indexOf(snapDurationToBucket(visibleRowDurationRange.maxNs))
const startIndex = startIndexRaw === -1 ? 0 : startIndexRaw
@@ -175,13 +135,13 @@ export function TracingSparkline({
if (startIndex > endIndex) {
return null
}
- return { xMin: labels[startIndex], xMax: labels[endIndex + 1] ?? labels[endIndex] }
+ return { start: labels[startIndex], end: labels[endIndex] }
}, [visibleRowDurationRange, durationHistogram])
// Map the visible-row date range onto bucket indices in `dates`. Buckets are anchored at
// their start time; the date_to edge belongs to the bucket whose start is the last one
// <= date_to. Suppressed in compare mode, where the list (and its window) isn't shown.
- const highlightedRange = useMemo(() => {
+ const activityHighlight = useMemo(() => {
if (compare || !visibleRowDateRange || sparklineData.dates.length === 0) {
return null
}
@@ -206,27 +166,37 @@ export function TracingSparkline({
if (endIndex === -1 || endIndex < startIndex) {
return null
}
- return { xMin: sparklineLabels[startIndex], xMax: sparklineLabels[endIndex + 1] ?? sparklineLabels[endIndex] }
- }, [compare, visibleRowDateRange, sparklineData.dates, sparklineLabels])
-
- const onSelectionChange = useCallback(
- (selection: { startIndex: number; endIndex: number }): void => {
- const dates = sparklineData.dates
- const dateFrom = dates[selection.startIndex]
- const dateTo = dates[selection.endIndex + 1]
+ return { start: sparklineData.dates[startIndex], end: sparklineData.dates[endIndex] }
+ }, [compare, visibleRowDateRange, sparklineData.dates])
- if (!dateFrom) {
- return
+ // Drag-select sets the date range — the drag is the only way to narrow the list, so it's wired
+ // directly rather than through the drag-to-zoom flag. Meaningless on a duration axis.
+ const onDateRangeZoom = useCallback(
+ ({ startIndex, endIndex }: DateRangeZoomData): void => {
+ const dateFrom = sparklineData.dates[startIndex]
+ const dateTo = sparklineData.dates[endIndex + 1]
+ if (dateFrom) {
+ onDateRangeChange({ date_from: dateFrom, date_to: dateTo })
}
-
- onDateRangeChange({
- date_from: dateFrom,
- date_to: dateTo,
- })
},
[sparklineData.dates, onDateRangeChange]
)
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext): JSX.Element => (
+ <DefaultTooltip
+ {...ctx}
+ hideZeroRows
+ sortedByValue
+ valueFormatter={(value) => humanFriendlyNumber(value)}
+ labelFormatter={durationMode ? undefined : tooltipLabelFormatter}
+ />
+ ),
+ [durationMode, tooltipLabelFormatter]
+ )
+
+ const hasData = seriesSource.length > 0
+
return (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between">
@@ -269,22 +239,34 @@ export function TracingSparkline({
</div>
)}
{!collapsed && !heatmapMode && (
- <div id="tracing-sparkline-content" className="relative h-32">
- {(durationHistogram ? durationHistogram.data : sparklineData.data).length > 0 ? (
- <Sparkline
- labels={sparklineLabels}
- data={durationHistogram ? durationHistogram.data : sparklineData.data}
- className="w-full h-full"
- // Drag-select sets the date range — meaningless on a duration axis, so
- // disabled in duration mode (a duration-range filter is a later idea).
- onSelectionChange={compare || durationMode ? undefined : onSelectionChange}
- withXScale={withXScale}
- renderLabel={renderLabel}
- tooltipRowCutoff={100}
- hideZerosInTooltip
- sortTooltipByCount
- highlightedRange={durationMode ? durationHighlightedRange : highlightedRange}
- />
+ <div id="tracing-sparkline-content" className="relative h-32 flex flex-col">
+ {hasData ? (
+ durationMode ? (
+ <BarChart
+ series={series}
+ labels={durationHistogram!.labels}
+ theme={theme}
+ config={durationConfig}
+ tooltip={renderTooltip}
+ >
+ {durationHighlight && (
+ <HighlightedRange start={durationHighlight.start} end={durationHighlight.end} />
+ )}
+ </BarChart>
+ ) : (
+ <TimeSeriesBarChart
+ series={series}
+ labels={sparklineData.dates}
+ theme={theme}
+ config={timeConfig}
+ onDateRangeZoom={compare ? undefined : onDateRangeZoom}
+ tooltip={renderTooltip}
+ >
+ {activityHighlight && (
+ <HighlightedRange start={activityHighlight.start} end={activityHighlight.end} />
+ )}
+ </TimeSeriesBarChart>
+ )
) : !sparklineLoading ? (
<div className="h-full text-muted flex items-center justify-center">
No results matching filters