: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): click an activity bar to filter to that bucket (#102553)
Daniel Visca599161df449c
diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex b44f6994b893..88d6adfaec27 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -128,7 +128,7 @@ function TracingSceneContents(): JSX.Element {// Resolved aggregation window (ms) — turns span counts into a request rate.// Use sparklineWindowMs which correctly resolves relative date strings (e.g. '-1h').- const { sparklineWindowMs } = useValues(tracingFiltersLogic)+ const { sparklineWindowMs, utcDateRange } = useValues(tracingFiltersLogic)const operationsWindowMs = sparklineWindowMs.endMs - sparklineWindowMs.startMsconst onDocsLinkClick = (): void => {@@ -208,7 +208,9 @@ function TracingSceneContents(): JSX.Element {sparklineLoading={sparklineLoading || (isDurationMode && !showHeatmap && durationHistogramLoading)}onDateRangeChange={setDateRange}displayTimezone={TRACING_DISPLAY_TIMEZONE}+ currentDateTo={utcDateRange.date_to}compare={compareConfig}+ compareActive={compareActive}visibleRowDateRange={visibleRowDateRange}durationHistogram={isDurationMode && !showHeatmap ? durationHistogramData : null}visibleRowDurationRange={visibleRowDurationRange}diff --git a/products/tracing/frontend/TracingSparkline.test.tsx b/products/tracing/frontend/TracingSparkline.test.tsxnew file mode 100644index 000000000000..b812d8751605--- /dev/null+++ b/products/tracing/frontend/TracingSparkline.test.tsx@@ -0,0 +1,108 @@+import { cleanup, render } from '@testing-library/react'++import { clickAtIndex, getHogChart, setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'++import { initKeaTests } from '~/test/init'++import type { TracingSparklineData } from './tracingDataLogic'+import { TracingSparkline } from './TracingSparkline'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ initKeaTests()+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++const DATES = [+ '2024-01-01T00:00:00.000Z',+ '2024-01-01T01:00:00.000Z',+ '2024-01-01T02:00:00.000Z',+ '2024-01-01T03:00:00.000Z',+]+const SPARKLINE_DATA: TracingSparklineData = {+ dates: DATES,+ labels: DATES,+ data: [+ { name: 'checkout', values: [4, 5, 6, 7], color: 'data-color-1' },+ { name: 'search', values: [1, 2, 3, 4], color: 'data-color-2' },+ ],+}++const COMPARE = {+ fullStartMs: Date.parse(DATES[0]),+ fullEndMs: Date.parse(DATES[3]),+ currentWindow: { startMs: Date.parse(DATES[2]), endMs: Date.parse(DATES[3]) },+ previousWindow: { startMs: Date.parse(DATES[0]), endMs: Date.parse(DATES[1]) },+ onChange: jest.fn(),+}++function renderChart(props: Partial<React.ComponentProps<typeof TracingSparkline>> = {}): {+ element: HTMLElement+ onDateRangeChange: jest.Mock+} {+ const onDateRangeChange = jest.fn()+ const { container } = render(+ <TracingSparkline+ sparklineData={SPARKLINE_DATA}+ sparklineLoading={false}+ onDateRangeChange={onDateRangeChange}+ displayTimezone="UTC"+ {...props}+ />+ )+ return { element: getHogChart(container).element, onDateRangeChange }+}++describe('TracingSparkline', () => {+ describe('bar click', () => {+ it('narrows the range to the clicked bucket only', async () => {+ const { element, onDateRangeChange } = renderChart()++ await clickAtIndex(element, 1, DATES.length)++ expect(onDateRangeChange).toHaveBeenCalledWith(+ { date_from: DATES[1], date_to: DATES[2] },+ 'sparkline_bar_click'+ )+ })++ it('ends the last bucket on the queried window, not on the next bucket', async () => {+ const currentDateTo = '2024-01-01T04:00:00.000Z'+ const { element, onDateRangeChange } = renderChart({ currentDateTo })++ await clickAtIndex(element, DATES.length - 1, DATES.length)++ expect(onDateRangeChange).toHaveBeenCalledWith(+ { date_from: DATES[3], date_to: currentDateTo },+ 'sparkline_bar_click'+ )+ })++ it('does nothing while comparing time windows', async () => {+ const { element, onDateRangeChange } = renderChart({ compare: COMPARE, compareActive: true })++ await clickAtIndex(element, 1, DATES.length)++ expect(onDateRangeChange).not.toHaveBeenCalled()+ })++ it('does nothing while a comparison is active even without a custom window overlay', async () => {+ // Named time presets (previous period, yesterday, ...) have no draggable overlay, so+ // `compare` is undefined — the click must still be disabled via `compareActive`.+ const { element, onDateRangeChange } = renderChart({ compareActive: true })++ await clickAtIndex(element, 1, DATES.length)++ expect(onDateRangeChange).not.toHaveBeenCalled()+ })+ })+})diff --git a/products/tracing/frontend/TracingSparkline.tsx b/products/tracing/frontend/TracingSparkline.tsxindex 8c38f6c2b4f6..f0a21e0f9567 100644--- a/products/tracing/frontend/TracingSparkline.tsx+++ b/products/tracing/frontend/TracingSparkline.tsx@@ -9,6 +9,7 @@ import {DefaultTooltip,type HeatmapBrushData,HighlightedRange,+ type PointClickData,type Series,TimeSeriesBarChart,type TimeSeriesBarChartConfig,@@ -32,6 +33,7 @@ import {snapDurationToBucket,} from './durationBuckets'import { SparklineCompareOverlay } from './SparklineCompareOverlay'+import { bucketRangeToDateRange, type TracingDateRangeSource } from './sparklineSelection'import type { TracingSparklineData, VisibleSpanTimeRange } from './tracingDataLogic'import type { TracingChartType } from './tracingFiltersLogic'import { TracingLatencyHeatmap } from './TracingLatencyHeatmap'@@ -47,9 +49,16 @@ interface CompareConfig {interface TracingSparklineProps {sparklineData: TracingSparklineDatasparklineLoading: boolean- onDateRangeChange: (dateRange: DateRange) => void+ onDateRangeChange: (dateRange: DateRange, source: TracingDateRangeSource) => voiddisplayTimezone: string+ /** End of the queried window, used as `date_to` when the selection runs to the last bucket+ * (which has no following bucket to end on). */+ currentDateTo?: string | nullcompare?: CompareConfig+ /** True while any time comparison is active (named preset or custom). Disables drag/click+ * range selection — the draggable overlay only exists for the custom preset, so `compare`+ * alone can't gate interactions for named presets. */+ compareActive?: booleanvisibleRowDateRange?: VisibleSpanTimeRange | null/** When set, render a duration histogram instead of the time series (list sorted by duration). */durationHistogram?: TracingDurationHistogramData | null@@ -73,7 +82,9 @@ export function TracingSparkline({sparklineLoading,onDateRangeChange,displayTimezone,+ currentDateTo,compare,+ compareActive = false,visibleRowDateRange,durationHistogram,visibleRowDurationRange,@@ -167,17 +178,29 @@ export function TracingSparkline({return { start: sparklineData.dates[startIndex], end: sparklineData.dates[endIndex] }}, [compare, visibleRowDateRange, sparklineData.dates])- // Drag-select sets the date range — the drag is the only way to narrow the list, so it's wired+ // Both gestures narrow the list to the buckets they cover, so they share one mapping. 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 })+ const selectBuckets = useCallback(+ (startIndex: number, endIndex: number, source: TracingDateRangeSource): void => {+ const dateRange = bucketRangeToDateRange(sparklineData.dates, startIndex, endIndex, currentDateTo)+ if (dateRange) {+ onDateRangeChange(dateRange, source)}},- [sparklineData.dates, onDateRangeChange]+ [sparklineData.dates, currentDateTo, onDateRangeChange]+ )++ const onDateRangeZoom = useCallback(+ ({ startIndex, endIndex }: DateRangeZoomData): void => selectBuckets(startIndex, endIndex, 'sparkline_drag'),+ [selectBuckets]+ )++ // Clicking a single bar is the discoverable shorthand for dragging across it. Quill routes a+ // click here only once it has ruled out a drag, so a drag-select does not also fire this.+ // Setting the handler is what turns the cursor into a pointer over the bars.+ const onPointClick = useCallback(+ ({ dataIndex }: PointClickData): void => selectBuckets(dataIndex, dataIndex, 'sparkline_bar_click'),+ [selectBuckets])const renderTooltip = useCallback(@@ -257,7 +280,8 @@ export function TracingSparkline({labels={sparklineData.dates}theme={theme}config={timeConfig}- onDateRangeZoom={compare ? undefined : onDateRangeZoom}+ onDateRangeZoom={compareActive ? undefined : onDateRangeZoom}+ onPointClick={compareActive ? undefined : onPointClick}tooltip={renderTooltip}>{activityHighlight && (diff --git a/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts b/products/tracing/frontend/components/FacetRail/facetValuesLogic.tsindex 7749df8f9664..1a30a2f11e2d 100644--- a/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts+++ b/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts@@ -32,7 +32,7 @@ export interface facetValuesLogicValues {serviceNames: string[] // tracingFiltersLogicutcDateRange: {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string} // tracingFiltersLogiccollapsed: booleanfacetSearch: string@@ -83,7 +83,7 @@ export interface facetValuesLogicMeta {scopeSignature: (utcDateRange: {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string},serviceNames: string[],queryFilterGroup: UniversalFiltersGroup,diff --git a/products/tracing/frontend/sparklineSelection.test.ts b/products/tracing/frontend/sparklineSelection.test.tsnew file mode 100644index 000000000000..d1c8a86f13f3--- /dev/null+++ b/products/tracing/frontend/sparklineSelection.test.ts@@ -0,0 +1,30 @@+import { bucketRangeToDateRange } from './sparklineSelection'++const DATES = ['2024-01-01T00:00:00.000Z', '2024-01-01T01:00:00.000Z', '2024-01-01T02:00:00.000Z']++describe('bucketRangeToDateRange', () => {+ it('ends the range on the start of the bucket after the last selected one', () => {+ expect(bucketRangeToDateRange(DATES, 0, 1)).toEqual({ date_from: DATES[0], date_to: DATES[2] })+ })++ it('falls back to the queried end when the selection reaches the last bucket', () => {+ const currentDateTo = '2024-01-01T02:30:00.000Z'+ expect(bucketRangeToDateRange(DATES, 1, 2, currentDateTo)).toEqual({+ date_from: DATES[1],+ date_to: currentDateTo,+ })+ })++ it('ends a relative window on the resolved window end rather than staying open', () => {+ // utcDateRange.date_to is resolved (never null) precisely so this fallback stays concrete.+ const resolvedEnd = '2024-01-01T02:30:00.000Z'+ expect(bucketRangeToDateRange(DATES, 2, 2, resolvedEnd)).toEqual({+ date_from: DATES[2],+ date_to: resolvedEnd,+ })+ })++ it('returns null when the selection starts past the rendered buckets', () => {+ expect(bucketRangeToDateRange(DATES, 3, 4)).toBeNull()+ })+})diff --git a/products/tracing/frontend/sparklineSelection.ts b/products/tracing/frontend/sparklineSelection.tsnew file mode 100644index 000000000000..bc950ff56c43--- /dev/null+++ b/products/tracing/frontend/sparklineSelection.ts@@ -0,0 +1,29 @@+// Pure mapping from a selection on the activity chart onto a date range. Kept out of the+// component so the bucket-edge convention is unit-testable on its own, like heatmapBrush.ts.++import { DateRange } from '~/queries/schema/schema-general'++/** How the user picked the range on the activity chart — reported with the filter-change event. */+export type TracingDateRangeSource = 'sparkline_drag' | 'sparkline_bar_click'++/**+ * Date range spanned by an inclusive run of sparkline buckets, or null when the run starts past+ * the rendered buckets.+ *+ * Buckets are anchored at their start, so the range ends at the START of the bucket after the+ * last selected one. The final bucket has no successor — fall back to the window's own end, the+ * same convention `heatmapBrushToFilters` uses, so selecting the last bar can't stretch an+ * absolute window forward to now.+ */+export function bucketRangeToDateRange(+ dates: string[],+ startIndex: number,+ endIndex: number,+ currentDateTo?: string | null+): DateRange | null {+ const dateFrom = dates[startIndex]+ if (!dateFrom) {+ return null+ }+ return { date_from: dateFrom, date_to: dates[endIndex + 1] ?? currentDateTo ?? null }+}diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 680df58e5e00..2c52d0820227 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -131,7 +131,7 @@ export interface tracingDataLogicValues {timeComparison: TimeComparison | null // tracingFiltersLogicutcDateRange: {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string} // tracingFiltersLogicaggregation: {current: AggregatedSpanRow[]@@ -219,8 +219,12 @@ export interface tracingDataLogicActions {setComparison: (comparison: TimeComparison | null) => {comparison: TimeComparison | null} // tracingFiltersLogic- setDateRange: (dateRange: DateRange) => {+ setDateRange: (+ dateRange: DateRange,+ source?: import('./sparklineSelection').TracingDateRangeSource | undefined+ ) => {dateRange: DateRange+ source: import('./sparklineSelection').TracingDateRangeSource | undefined} // tracingFiltersLogicsetFilterGroup: (filterGroup: UniversalFiltersGroup,@@ -1398,7 +1402,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([posthog.capture('tracing filter changed', { filter_type: filterType, ...extraProps })actions.runQuery()},- setDateRange: () => actions.handleFilterChange('date_range'),+ setDateRange: ({ source }) => actions.handleFilterChange('date_range', source ? { source } : undefined),setServiceNames: () => actions.handleFilterChange('service_names'),// skipQuery: the trace drawer's attribute buttons update the filter chips immediately but// queue the actual re-query for when the drawer closes — see refreshDeferredFilters.diff --git a/products/tracing/frontend/tracingFiltersLogic.test.ts b/products/tracing/frontend/tracingFiltersLogic.test.tsindex 301d770c0cf8..3bf71eab4536 100644--- a/products/tracing/frontend/tracingFiltersLogic.test.ts+++ b/products/tracing/frontend/tracingFiltersLogic.test.ts@@ -54,6 +54,23 @@ describe('tracingFiltersLogic', () => {})})+ describe('utcDateRange', () => {+ it('passes absolute bounds through as ISO strings', () => {+ logic.actions.setDateRange(ABSOLUTE_RANGE)+ expect(logic.values.utcDateRange).toEqual({+ date_from: '2024-01-08T00:00:00.000Z',+ date_to: '2024-01-08T04:00:00.000Z',+ })+ })++ it('resolves an open relative window to the anchored end instead of null', () => {+ jest.useFakeTimers().setSystemTime(Date.parse('2024-01-08T12:00:00Z'))+ logic.actions.setDateRange({ date_from: '-1h', date_to: null })+ expect(logic.values.utcDateRange.date_to).toBe('2024-01-08T12:00:00.000Z')+ jest.useRealTimers()+ })+ })+describe('comparison windows', () => {beforeEach(() => {logic.actions.setDateRange(ABSOLUTE_RANGE)diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.tsindex 68d24b7c2b07..12d67eb7552f 100644--- a/products/tracing/frontend/tracingFiltersLogic.ts+++ b/products/tracing/frontend/tracingFiltersLogic.ts@@ -28,6 +28,8 @@ import {import { mergeSpanFilter } from 'products/tracing/frontend/spanFilterAdd'+import type { TracingDateRangeSource } from './sparklineSelection'+export const DEFAULT_DATE_RANGE: DateRange = { date_from: '-1h', date_to: null }export const DEFAULT_TIMEZONE: string = 'UTC'export const DEFAULT_SERVICE_NAMES: string[] = []@@ -194,7 +196,7 @@ export interface tracingFiltersLogicValues {timezone: stringutcDateRange: {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string}viewMode: TracingViewModewindowAnchorMs: number@@ -225,8 +227,12 @@ export interface tracingFiltersLogicActions {setComparison: (comparison: TracingComparison | null) => {comparison: TimeComparison | null}- setDateRange: (dateRange: DateRange) => {+ setDateRange: (+ dateRange: DateRange,+ source?: TracingDateRangeSource+ ) => {dateRange: DateRange+ source: TracingDateRangeSource | undefined}setFilterGroup: (filterGroup: UniversalFiltersGroup,@@ -289,9 +295,12 @@ export interface tracingFiltersLogicMeta {filterGroup: UniversalFiltersGroup,pinnedFilters: UniversalFiltersGroup | undefined) => UniversalFiltersGroup- utcDateRange: (dateRange: DateRange) => {+ utcDateRange: (+ dateRange: DateRange,+ sparklineWindowMs: OverlayWindow+ ) => {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string}sparklineWindowMs: (dateRange: DateRange, windowAnchorMs: number) => OverlayWindowcurrentWindowMs: (sparklineWindowMs: OverlayWindow, timeComparison: TimeComparison | null) => OverlayWindow@@ -316,7 +325,7 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([path((key) => ['products', 'tracing', 'frontend', 'tracingFiltersLogic', key]),actions({- setDateRange: (dateRange: DateRange) => ({ dateRange }),+ setDateRange: (dateRange: DateRange, source?: TracingDateRangeSource) => ({ dateRange, source }),setTimezone: (timezone: string) => ({ timezone }),setServiceNames: (serviceNames: string[]) => ({ serviceNames }),setFilterGroup: (filterGroup: UniversalFiltersGroup, skipQuery: boolean = false) => ({@@ -518,15 +527,18 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([pinnedFilters: UniversalFiltersGroup | undefined): UniversalFiltersGroup => combineWithPinnedFilters(filterGroup, pinnedFilters),],+ // `date_to` falls back to the resolved window end (windowAnchorMs for an open relative+ // range) rather than staying null — a null `date_to` re-sent as a filter reads as "now",+ // so a sparkline selection on the last bucket would keep growing past the queried window.utcDateRange: [- (s) => [s.dateRange],- (dateRange: DateRange) => ({+ (s) => [s.dateRange, s.sparklineWindowMs],+ (dateRange: DateRange, sparklineWindowMs: OverlayWindow) => ({date_from: dayjs(dateRange.date_from).isValid()? dayjs(dateRange.date_from).toISOString(): dateRange.date_from,date_to: dayjs(dateRange.date_to).isValid()? dayjs(dateRange.date_to).toISOString()- : dateRange.date_to,+ : new Date(sparklineWindowMs.endMs).toISOString(),}),],sparklineWindowMs: [diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex a461d27190d5..93afc1955b2b 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -88,7 +88,7 @@ export interface tracingSceneLogicValues {sparklineWindowMs: OverlayWindow // tracingFiltersLogicutcDateRange: {date_from: string | null | undefined- date_to: string | null | undefined+ date_to: string} // tracingFiltersLogiccanLoadMoreTraceSpans: boolean // tracingViewerLogiccompareFlameServiceName: string | null // tracingViewerLogic@@ -158,8 +158,12 @@ export interface tracingSceneLogicActions {setComparison: (comparison: TimeComparison | null) => {comparison: TimeComparison | null} // tracingFiltersLogic- setDateRange: (dateRange: DateRange) => {+ setDateRange: (+ dateRange: DateRange,+ source?: import('./sparklineSelection').TracingDateRangeSource | undefined+ ) => {dateRange: DateRange+ source: import('./sparklineSelection').TracingDateRangeSource | undefined} // tracingFiltersLogicsetFilterGroup: (filterGroup: UniversalFiltersGroup,