: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): rework compare mode around explicit baseline presets (#69677)
Jon McCallum54945b74ff9a
diff --git a/products/tracing/frontend/SparklineCompareOverlay.tsx b/products/tracing/frontend/SparklineCompareOverlay.tsxindex 92af2f6cdc4a..8f9d92f5448b 100644--- a/products/tracing/frontend/SparklineCompareOverlay.tsx+++ b/products/tracing/frontend/SparklineCompareOverlay.tsx@@ -24,12 +24,14 @@ interface DragState {initialPrevious: Window}-const CURRENT_COLOR = 'rgba(255, 165, 0, 0.25)' // light orange-const CURRENT_BORDER = 'rgba(255, 140, 0, 0.85)'-const PREVIOUS_COLOR = 'rgba(99, 179, 237, 0.25)' // light blue-const PREVIOUS_BORDER = 'rgba(56, 145, 212, 0.85)'+// Shared with the ComparisonBar pills so "Current"/"Baseline" reads the same everywhere.+export const COMPARE_CURRENT_COLOR = 'rgba(255, 165, 0, 0.25)' // light orange+export const COMPARE_CURRENT_BORDER = 'rgba(255, 140, 0, 0.85)'+export const COMPARE_PREVIOUS_COLOR = 'rgba(99, 179, 237, 0.25)' // light blue+export const COMPARE_PREVIOUS_BORDER = 'rgba(56, 145, 212, 0.85)'const EDGE_WIDTH_PX = 6+const BORDER_WIDTH_PX = 2const MIN_DURATION_MS = 60_000function clampWindowToBounds(w: Window, fullStartMs: number, fullEndMs: number): Window {@@ -203,7 +205,8 @@ export function SparklineCompareOverlay({window: Window,kind: 'current' | 'previous',fill: string,- border: string+ border: string,+ label: string): JSX.Element | null {if (pxPerMs === 0) {return null@@ -218,17 +221,25 @@ export function SparklineCompareOverlay({left,width: w,backgroundColor: fill,- borderLeft: `1px solid ${border}`,- borderRight: `1px solid ${border}`,+ borderLeft: `${BORDER_WIDTH_PX}px solid ${border}`,+ borderRight: `${BORDER_WIDTH_PX}px solid ${border}`,pointerEvents: 'auto',cursor: 'grab',}}onMouseDown={(e) => beginDrag(`${kind}-body` as DragKind, e)}+ title={`${label} window — drag to move, drag an edge to resize`}>+ {/* Persistent label chip: the drag affordance is invisible without it. */}+ <span+ className="absolute top-0 left-0 px-1 text-[10px] font-semibold text-white leading-4 whitespace-nowrap pointer-events-none select-none rounded-br"+ style={{ backgroundColor: border }}+ >+ {label}+ </span><divclassName="absolute top-0 h-full"style={{- left: -EDGE_WIDTH_PX / 2,+ left: -EDGE_WIDTH_PX / 2 - BORDER_WIDTH_PX / 2,width: EDGE_WIDTH_PX,cursor: 'ew-resize',}}@@ -237,7 +248,7 @@ export function SparklineCompareOverlay({<divclassName="absolute top-0 h-full"style={{- right: -EDGE_WIDTH_PX / 2,+ right: -EDGE_WIDTH_PX / 2 - BORDER_WIDTH_PX / 2,width: EDGE_WIDTH_PX,cursor: 'ew-resize',}}@@ -249,8 +260,8 @@ export function SparklineCompareOverlay({return (<div ref={containerRef} className="absolute inset-0" style={{ pointerEvents: 'none' }}>- {renderWindow(effectivePrevious, 'previous', PREVIOUS_COLOR, PREVIOUS_BORDER)}- {renderWindow(effectiveCurrent, 'current', CURRENT_COLOR, CURRENT_BORDER)}+ {renderWindow(effectivePrevious, 'previous', COMPARE_PREVIOUS_COLOR, COMPARE_PREVIOUS_BORDER, 'Baseline')}+ {renderWindow(effectiveCurrent, 'current', COMPARE_CURRENT_COLOR, COMPARE_CURRENT_BORDER, 'Current')}</div>)}diff --git a/products/tracing/frontend/TraceCompareTable.tsx b/products/tracing/frontend/TraceCompareTable.tsxindex c759354a51e1..289114f97615 100644Binary files a/products/tracing/frontend/TraceCompareTable.tsx and b/products/tracing/frontend/TraceCompareTable.tsx differdiff --git a/products/tracing/frontend/TracingDisplayBar.tsx b/products/tracing/frontend/TracingDisplayBar.tsxindex e0b35392f294..a9f44cdc0cb2 100644--- a/products/tracing/frontend/TracingDisplayBar.tsx+++ b/products/tracing/frontend/TracingDisplayBar.tsx@@ -1,12 +1,13 @@import { useActions, useValues } from 'kea'import { IconChevronLeft, IconChevronRight, IconList, IconListTree } from '@posthog/icons'-import { LemonButton, LemonSegmentedButton, LemonSwitch } from '@posthog/lemon-ui'+import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { humanFriendlyNumber } from 'lib/utils/numbers'+import { CompareMenuButton } from './components/Comparison/CompareMenuButton'import { tracingConfigLogic } from './tracingConfigLogic'import { tracingFiltersLogic, type TracingViewMode } from './tracingFiltersLogic'import { tracingSceneLogic } from './tracingSceneLogic'@@ -20,9 +21,9 @@ import { tracingSceneLogic } from './tracingSceneLogic'* hidden entirely on the Operations view where neither applies.*/export function TracingDisplayBar(): JSX.Element {- const { activeTracingTab, totalMatchingFilters, filters } = useValues(tracingSceneLogic())+ const { activeTracingTab, totalMatchingFilters, filters, compareActive } = useValues(tracingSceneLogic())const { setActiveTracingTab } = useActions(tracingSceneLogic())- const { setViewMode, setCompareMode } = useActions(tracingFiltersLogic())+ const { setViewMode } = useActions(tracingFiltersLogic())const { featureFlags } = useValues(featureFlagLogic)const { facetRailCollapsed } = useValues(tracingConfigLogic)const { setFacetRailCollapsed } = useActions(tracingConfigLogic)@@ -30,7 +31,7 @@ export function TracingDisplayBar(): JSX.Element {const facetRailEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_FACET_RAIL]const operationsViewEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]const inTracesView = !operationsViewEnabled || activeTracingTab !== 'operations'- const showCount = inTracesView && !filters.compareMode && totalMatchingFilters > 0+ const showCount = inTracesView && !compareActive && totalMatchingFilters > 0return (<div className="flex items-center justify-between gap-2 flex-wrap">@@ -72,7 +73,7 @@ export function TracingDisplayBar(): JSX.Element {</div>{inTracesView && (<div className="flex items-center gap-1.5 flex-wrap">- {!filters.compareMode && (+ {!compareActive && (<LemonSegmentedButton<TracingViewMode>size="small"value={filters.viewMode}@@ -95,13 +96,7 @@ export function TracingDisplayBar(): JSX.Element {]}/>)}- <LemonSwitch- label="Compare"- checked={filters.compareMode}- onChange={setCompareMode}- bordered- size="small"- />+ <CompareMenuButton /></div>)}</div>diff --git a/products/tracing/frontend/TracingScene.tsx b/products/tracing/frontend/TracingScene.tsxindex 41d86b5d8d45..825496ed158e 100644--- a/products/tracing/frontend/TracingScene.tsx+++ b/products/tracing/frontend/TracingScene.tsx@@ -17,6 +17,7 @@ import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { ComparisonBar } from './components/Comparison/ComparisonBar'import { FacetRail } from './components/FacetRail/FacetRail'import { TracingSetupPrompt } from './components/SetupPrompt/SetupPrompt'import { TraceDrawer } from './components/TraceDrawer/TraceDrawer'@@ -89,6 +90,7 @@ function TracingSceneContents(): JSX.Element {visibleRowDurationRange,isDurationMode,activeTracingTab,+ compareActive,} = useValues(tracingSceneLogic())const { featureFlags } = useValues(featureFlagLogic)const {@@ -96,7 +98,7 @@ function TracingSceneContents(): JSX.Element {closeTrace,selectSpan,setDateRange,- setOverlayWindows,+ updateComparisonWindows,openCompareFlame,closeCompareFlame,fetchNextPage,@@ -106,7 +108,6 @@ function TracingSceneContents(): JSX.Element {} = useActions(tracingSceneLogic())const { addProductIntent } = useActions(teamLogic)const { facetRailCollapsed } = useValues(tracingConfigLogic)- const compareMode = filters.compareModeconst operationsViewEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_OPERATIONS_VIEW]const facetRailEnabled = !!featureFlags[FEATURE_FLAGS.TRACING_FACET_RAIL]@@ -128,18 +129,23 @@ function TracingSceneContents(): JSX.Element {// Anchor the overlay's coordinate space to the *fetched* sparkline data so overlay// drags never shift the canvas underfoot. The sparkline only refetches when dateRange- // changes (via the DateFilter), never via overlay interaction.+ // changes (via the DateFilter), never via overlay interaction. Only the 'custom' preset+ // shows draggable windows — named presets compare the full range, whose baseline window+ // sits outside the visible sparkline anyway.const sparklineFirstMs = sparklineData.dates.length > 0 ? new Date(sparklineData.dates[0]).valueOf() : nullconst sparklineLastMs =sparklineData.dates.length > 0 ? new Date(sparklineData.dates[sparklineData.dates.length - 1]).valueOf() : nullconst compareConfig =- compareMode && sparklineFirstMs !== null && sparklineLastMs !== null+ filters.comparison?.mode === 'time' &&+ filters.comparison.preset === 'custom' &&+ sparklineFirstMs !== null &&+ sparklineLastMs !== null? {fullStartMs: sparklineFirstMs,fullEndMs: sparklineLastMs,currentWindow: currentWindowMs,previousWindow: previousWindowMs,- onChange: setOverlayWindows,+ onChange: updateComparisonWindows,}: undefined@@ -196,6 +202,9 @@ function TracingSceneContents(): JSX.Element {{facetRailEnabled && !facetRailCollapsed && <FacetRail />}<div className="flex flex-col gap-2 flex-1 min-w-0 min-h-0"><TracingDisplayBar />+ {compareActive && (!operationsViewEnabled || activeTracingTab !== 'operations') && (+ <ComparisonBar />+ )}{operationsViewEnabled && activeTracingTab === 'operations' ? (<OperationsTablerows={aggregation.current}@@ -205,7 +214,7 @@ function TracingSceneContents(): JSX.Element {router.actions.push(urls.tracingOperation(row.service_name, row.name))}/>- ) : compareMode ? (+ ) : compareActive ? (<TraceCompareTablecurrent={aggregation.current}previous={aggregation.previous}diff --git a/products/tracing/frontend/components/Comparison/CompareMenuButton.tsx b/products/tracing/frontend/components/Comparison/CompareMenuButton.tsxnew file mode 100644index 000000000000..aa7b3f9450a0--- /dev/null+++ b/products/tracing/frontend/components/Comparison/CompareMenuButton.tsx@@ -0,0 +1,95 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from 'lib/ui/quill'++import {+ DEFAULT_CUSTOM_COMPARISON,+ TIME_COMPARE_PRESET_DEFS,+ TIME_COMPARE_PRESETS,+ type TimeComparePreset,+ tracingFiltersLogic,+} from '../../tracingFiltersLogic'++/**+ * Entry point for comparisons: a menu of baseline presets instead of a bare on/off toggle,+ * so the user picks *what* to compare against. The active comparison is described by the+ * ComparisonBar rendered above the results.+ */+export function CompareMenuButton(): JSX.Element {+ const { comparison, compareActive, sparklineWindowMs } = useValues(tracingFiltersLogic)+ const { setComparison } = useActions(tracingFiltersLogic)++ const activePreset = comparison?.mode === 'time' ? comparison.preset : null+ const rangeDurationMs = sparklineWindowMs.endMs - sparklineWindowMs.startMs++ // A preset whose shift is shorter than the selected range would produce a baseline that+ // mostly overlaps the current window — deltas near zero that read as "nothing changed".+ const presetDisabled = (preset: TimeComparePreset): boolean => {+ const shiftMs = TIME_COMPARE_PRESET_DEFS[preset].shiftMs+ return shiftMs !== null && shiftMs < rangeDurationMs+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <LemonButton+ size="small"+ type="secondary"+ active={compareActive}+ data-attr="tracing-compare-menu"+ />+ }+ >+ Compare+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-[220px]">+ <DropdownMenuRadioGroup+ value={activePreset ?? ''}+ onValueChange={(preset: string) => {+ // Re-selecting the active preset would refetch identical data and wipe+ // any dragged custom windows.+ if (preset !== activePreset) {+ setComparison({ ...DEFAULT_CUSTOM_COMPARISON, preset: preset as TimeComparePreset })+ }+ }}+ >+ <DropdownMenuLabel>Compare this time range</DropdownMenuLabel>+ {TIME_COMPARE_PRESETS.map((preset) => {+ const disabled = presetDisabled(preset)+ return (+ <DropdownMenuRadioItem+ key={preset}+ value={preset}+ disabled={disabled}+ data-attr={`tracing-compare-${preset.replace(/_/g, '-')}`}+ >+ {TIME_COMPARE_PRESET_DEFS[preset].label}+ {disabled && <span className="text-muted ml-1">(range too wide)</span>}+ </DropdownMenuRadioItem>+ )+ })}+ </DropdownMenuRadioGroup>+ {compareActive && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => setComparison(null)} data-attr="tracing-compare-exit">+ Exit comparison+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/products/tracing/frontend/components/Comparison/ComparisonBar.tsx b/products/tracing/frontend/components/Comparison/ComparisonBar.tsxnew file mode 100644index 000000000000..3ee1e9de6dcc--- /dev/null+++ b/products/tracing/frontend/components/Comparison/ComparisonBar.tsx@@ -0,0 +1,71 @@+import { useActions, useValues } from 'kea'++import { IconX } from '@posthog/icons'+import { LemonButton, LemonTag } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { COMPARE_CURRENT_BORDER, COMPARE_PREVIOUS_BORDER } from '../../SparklineCompareOverlay'+import { type OverlayWindow, TIME_COMPARE_PRESET_DEFS, tracingFiltersLogic } from '../../tracingFiltersLogic'++// Windows are absolute ms; the tracing scene displays everything in UTC (see the sparkline's+// displayTimezone), so the pills must match or the ranges look shifted vs the chart.+function formatComparisonWindow(window: OverlayWindow): string {+ const start = dayjs(window.startMs).utc()+ const end = dayjs(window.endMs).utc()+ const endFormat = start.isSame(end, 'day') ? 'HH:mm' : 'MMM D, HH:mm'+ return `${start.format('MMM D, HH:mm')} – ${end.format(endFormat)} UTC`+}++function ComparisonPill({ color, label, detail }: { color: string; label: string; detail: string }): JSX.Element {+ return (+ <LemonTag icon={<span className="inline-block size-2 rounded-full" style={{ backgroundColor: color }} />}>+ <span className="font-semibold">{label}</span>+ <span className="text-muted font-normal">{detail}</span>+ </LemonTag>+ )+}++/**+ * Spells out what an active comparison is comparing — side A (current) vs side B (baseline) —+ * so the compare table's deltas are never ambiguous. Rendered above the results while a+ * comparison is active.+ */+export function ComparisonBar(): JSX.Element | null {+ const { comparison, currentWindowMs, previousWindowMs } = useValues(tracingFiltersLogic)+ const { setComparison } = useActions(tracingFiltersLogic)++ if (comparison?.mode !== 'time') {+ return null+ }++ const presetDef = TIME_COMPARE_PRESET_DEFS[comparison.preset]++ return (+ <div className="flex items-center gap-2 flex-wrap" data-attr="tracing-comparison-bar">+ <ComparisonPill+ color={COMPARE_CURRENT_BORDER}+ label="Current"+ detail={formatComparisonWindow(currentWindowMs)}+ />+ <span className="text-muted text-xs">vs</span>+ <ComparisonPill+ color={COMPARE_PREVIOUS_BORDER}+ label="Baseline"+ detail={`${formatComparisonWindow(previousWindowMs)} (${presetDef.baselineLabel})`}+ />+ {comparison.preset === 'custom' && (+ <span className="text-muted text-xs">Drag the windows on the chart to reposition or resize</span>+ )}+ <LemonButton+ size="xsmall"+ icon={<IconX />}+ onClick={() => setComparison(null)}+ tooltip="Exit comparison"+ aria-label="Exit comparison"+ data-attr="tracing-comparison-exit"+ className="ml-auto"+ />+ </div>+ )+}diff --git a/products/tracing/frontend/savedViews/tracingViewsLogic.test.ts b/products/tracing/frontend/savedViews/tracingViewsLogic.test.tsindex e703c9069b20..84864d336a25 100644--- a/products/tracing/frontend/savedViews/tracingViewsLogic.test.ts+++ b/products/tracing/frontend/savedViews/tracingViewsLogic.test.ts@@ -52,7 +52,12 @@ describe('tracing saved views', () => {filtersLogic.actions.setViewMode('spans')filtersLogic.actions.setSort('duration', 'ASC')// Ephemeral state that must NOT be saved.- filtersLogic.actions.setCompareMode(true)+ filtersLogic.actions.setComparison({+ mode: 'time',+ preset: 'custom',+ currentWindowOverride: null,+ previousWindowOverride: null,+ })listLogic.actions.setViewName('Slow spans')await expectLogic(listLogic, () => {@@ -70,9 +75,7 @@ describe('tracing saved views', () => {orderDirection: 'ASC',viewMode: 'spans',})- expect(payload.filters).not.toHaveProperty('compareMode')- expect(payload.filters).not.toHaveProperty('currentWindowOverride')- expect(payload.filters).not.toHaveProperty('previousWindowOverride')+ expect(payload.filters).not.toHaveProperty('comparison')})it('does nothing when the name is blank', async () => {diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 5626200c4cf3..67cf1b039200 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -97,7 +97,17 @@ export const tracingDataLogic = kea<tracingDataLogicType>([connect(({ id }: TracingDataLogicProps) => ({values: [tracingFiltersLogic({ id }),- ['filters', 'orderBy', 'utcDateRange', 'queryFilterGroup', 'currentWindowMs', 'previousWindowMs'],+ [+ 'filters',+ 'orderBy',+ 'utcDateRange',+ 'queryFilterGroup',+ 'sparklineWindowMs',+ 'currentWindowMs',+ 'previousWindowMs',+ 'compareActive',+ 'timeComparison',+ ],],})),@@ -430,7 +440,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.queryFilterGroup as PropertyGroupFilter,compareFilter: {- compare: values.filters.compareMode,+ compare: values.timeComparison !== null,compare_to: new Date(previousStartMs).toISOString(),},},@@ -449,22 +459,34 @@ export const tracingDataLogic = kea<tracingDataLogicType>([aggregation: [{ current: [] as AggregatedSpanRow[], previous: null as AggregatedSpanRow[] | null },{- fetchAggregation: async () => {+ // `fullRange` (the Operations tab) ignores any active comparison: the aggregate+ // covers the whole selected range with no compare period, matching the rate+ // denominator the OperationsTable divides by.+ fetchAggregation: async (options?: { fullRange?: boolean } | null) => {const controller = new AbortController()actions.cancelInProgressAggregation(controller)+ const fullRange = options?.fullRange ?? false+ const currentWindow = fullRange ? values.sparklineWindowMs : values.currentWindowMs+ const compare = !fullRange && values.timeComparison !== null+// Snapshot the resolved windows so the drill-down flame query uses the// same absolute timestamps as this aggregation, even if the user's// relative `-1h` range has since shifted forward in time. Dispatched// BEFORE the await so a concurrent `fetchSpanTree` (e.g. fired from the- // same `setOverlayWindows` listener) reads the new window, not the old.+ // same `updateComparisonWindows` listener) reads the new window, not the+ // old. Full-range (Operations) fetches skip it — the flame drill-down+ // only exists on the traces tab and must stay aligned with the compare+ // aggregation, not the operations one.const window = {- currentStartMs: values.currentWindowMs.startMs,- currentEndMs: values.currentWindowMs.endMs,+ currentStartMs: currentWindow.startMs,+ currentEndMs: currentWindow.endMs,previousStartMs: values.previousWindowMs.startMs,previousEndMs: values.previousWindowMs.endMs,}- actions.setLastAggregationWindow(window)+ if (!fullRange) {+ actions.setLastAggregationWindow(window)+ }const response = await api.tracing.aggregate({@@ -476,7 +498,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([values.filters.serviceNames.length > 0 ? values.filters.serviceNames : undefined,filterGroup: values.queryFilterGroup as PropertyGroupFilter,compareFilter: {- compare: values.filters.compareMode,+ compare,compare_to: new Date(window.previousStartMs).toISOString(),},},@@ -672,11 +694,12 @@ export const tracingDataLogic = kea<tracingDataLogicType>([],// Single owner of the "show the duration histogram?" rule — the fetch decision, the// highlight selector, and the scene's rendering all derive from this one place.- // Compare mode replaces the span list with the aggregate table, so the histogram+ // An active comparison replaces the span list with the aggregate table, so the histogram// (which mirrors the duration-sorted list) only applies outside it.isDurationMode: [- (s) => [s.filters],- (filters: TracingFilters): boolean => filters.orderBy === 'duration' && !filters.compareMode,+ (s) => [s.filters, s.compareActive],+ (filters: TracingFilters, compareActive: boolean): boolean =>+ filters.orderBy === 'duration' && !compareActive,],// Duration range covered by the currently-visible rows — the duration-space sibling of@@ -741,7 +764,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([if (values.isDurationMode) {actions.fetchDurationHistogram()}- if (values.filters.compareMode) {+ if (values.compareActive) {actions.fetchAggregation()} else {actions.fetchSpans()diff --git a/products/tracing/frontend/tracingFiltersLogic.test.ts b/products/tracing/frontend/tracingFiltersLogic.test.tsindex 6bbd46929527..aea8159dfbef 100644--- a/products/tracing/frontend/tracingFiltersLogic.test.ts+++ b/products/tracing/frontend/tracingFiltersLogic.test.ts@@ -1,7 +1,14 @@import { initKeaTests } from '~/test/init'import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'-import { tracingFiltersLogic } from './tracingFiltersLogic'+import { DEFAULT_CUSTOM_COMPARISON, tracingFiltersLogic } from './tracingFiltersLogic'++const HOUR_MS = 60 * 60 * 1000+const DAY_MS = 24 * HOUR_MS+// Absolute range so window math is deterministic (relative ranges resolve against Date.now()).+const RANGE_START = Date.parse('2024-01-08T00:00:00Z')+const RANGE_END = RANGE_START + 4 * HOUR_MS+const ABSOLUTE_RANGE = { date_from: '2024-01-08T00:00:00Z', date_to: '2024-01-08T04:00:00Z' }const PINNED_FILTERS: UniversalFiltersGroup = {type: FilterLogicalOperator.And,@@ -47,6 +54,52 @@ describe('tracingFiltersLogic', () => {})})+ describe('comparison windows', () => {+ beforeEach(() => {+ logic.actions.setDateRange(ABSOLUTE_RANGE)+ })++ it('covers the full selected range when no comparison is active (feeds the Operations aggregate)', () => {+ expect(logic.values.comparison).toBeNull()+ expect(logic.values.currentWindowMs).toEqual({ startMs: RANGE_START, endMs: RANGE_END })+ })++ test.each([+ ['previous_period', 4 * HOUR_MS],+ ['yesterday', DAY_MS],+ ['last_week', 7 * DAY_MS],+ ] as const)('%s compares the full range against the range shifted back', (preset, shiftMs) => {+ logic.actions.setComparison({ ...DEFAULT_CUSTOM_COMPARISON, preset })+ expect(logic.values.currentWindowMs).toEqual({ startMs: RANGE_START, endMs: RANGE_END })+ expect(logic.values.previousWindowMs).toEqual({+ startMs: RANGE_START - shiftMs,+ endMs: RANGE_END - shiftMs,+ })+ })++ it('custom preset defaults to the right-aligned 40% window and the -50%-shifted baseline', () => {+ logic.actions.setComparison(DEFAULT_CUSTOM_COMPARISON)+ const windowMs = 0.4 * 4 * HOUR_MS+ expect(logic.values.currentWindowMs).toEqual({ startMs: RANGE_END - windowMs, endMs: RANGE_END })+ const previousEnd = RANGE_END - 0.5 * 4 * HOUR_MS+ expect(logic.values.previousWindowMs).toEqual({ startMs: previousEnd - windowMs, endMs: previousEnd })+ })++ it('dragged custom windows override the defaults until the date range changes', () => {+ logic.actions.setComparison(DEFAULT_CUSTOM_COMPARISON)+ const current = { startMs: RANGE_START + HOUR_MS, endMs: RANGE_START + 2 * HOUR_MS }+ const previous = { startMs: RANGE_START, endMs: RANGE_START + HOUR_MS }+ logic.actions.updateComparisonWindows(current, previous)+ expect(logic.values.currentWindowMs).toEqual(current)+ expect(logic.values.previousWindowMs).toEqual(previous)++ // A new range invalidates the absolute-ms overrides but keeps the comparison active.+ logic.actions.setDateRange({ date_from: '2024-01-09T00:00:00Z', date_to: '2024-01-09T04:00:00Z' })+ expect(logic.values.comparison).toEqual(DEFAULT_CUSTOM_COMPARISON)+ expect(logic.values.currentWindowMs.endMs).toBe(RANGE_END + DAY_MS)+ })+ })+describe('keyed instances', () => {it('holds independent state per id', () => {const a = tracingFiltersLogic({ id: 'instance-a' })diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.tsindex cb18c253cb7d..4f39258b329b 100644--- a/products/tracing/frontend/tracingFiltersLogic.ts+++ b/products/tracing/frontend/tracingFiltersLogic.ts@@ -30,6 +30,74 @@ export interface OverlayWindow {endMs: number}+// A comparison is always "A vs B". Named presets compare the full selected date range against+// the same-duration window shifted back; 'custom' exposes the two draggable sparkline windows.+export type TimeComparePreset = 'previous_period' | 'yesterday' | 'last_week' | 'custom'++const DAY_MS = 24 * 60 * 60 * 1000++// 'custom' preset default geometry: side A is the right-aligned 40% of the sparkline range,+// side B the same width with its right edge pulled back 50% of the range.+const CUSTOM_WINDOW_FRACTION = 0.4+const CUSTOM_BASELINE_SHIFT_FRACTION = 0.5++export interface TimeComparePresetDef {+ /** Menu item copy. */+ label: string+ /** How the ComparisonBar's baseline pill describes side B. */+ baselineLabel: string+ /** Baseline shift in ms; null = shift by the current window's own duration. */+ shiftMs: number | null+}++// Single home for per-preset knowledge — menu items, pill copy, window shift, and URL+// validation all derive from this table, so adding a preset means one entry (plus the type).+export const TIME_COMPARE_PRESET_DEFS: Record<TimeComparePreset, TimeComparePresetDef> = {+ previous_period: { label: 'vs previous period', baselineLabel: 'previous period', shiftMs: null },+ yesterday: { label: 'vs yesterday', baselineLabel: 'yesterday', shiftMs: DAY_MS },+ last_week: { label: 'vs same time last week', baselineLabel: 'same time last week', shiftMs: 7 * DAY_MS },+ custom: { label: 'Custom time windows', baselineLabel: 'custom window', shiftMs: null },+}++export const TIME_COMPARE_PRESETS = Object.keys(TIME_COMPARE_PRESET_DEFS) as TimeComparePreset[]++export interface TimeComparison {+ mode: 'time'+ preset: TimeComparePreset+ /** User-positioned overrides for the two compare windows ('custom' preset only). Null until dragged. */+ currentWindowOverride: OverlayWindow | null+ previousWindowOverride: OverlayWindow | null+}++// Future modes ('segment', 'trace') extend this union — see the tracing comparison rework plan.+export type TracingComparison = TimeComparison++export const DEFAULT_CUSTOM_COMPARISON: TimeComparison = {+ mode: 'time',+ preset: 'custom',+ currentWindowOverride: null,+ previousWindowOverride: null,+}++// URL round-trip for the `comparison` search param. Only mode/preset persist — dragged overlay+// windows are ephemeral absolute-ms positions. Future comparison modes extend these two+// functions; the scene logic's URL sync is shape-agnostic.+export function serializeComparison(comparison: TracingComparison | null): string | undefined {+ return comparison ? JSON.stringify({ mode: comparison.mode, preset: comparison.preset }) : undefined+}++export function parseComparison(raw: unknown): TracingComparison | null {+ try {+ const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw+ if (parsed?.mode === 'time' && TIME_COMPARE_PRESETS.includes(parsed.preset)) {+ return { ...DEFAULT_CUSTOM_COMPARISON, preset: parsed.preset }+ }+ } catch {+ // Malformed param — treat as no comparison.+ }+ return null+}+export interface TracingFilters {dateRange: DateRangeserviceNames: string[]@@ -37,10 +105,7 @@ export interface TracingFilters {orderBy: TracingOrderByorderDirection: TracingOrderDirectionviewMode: TracingViewMode- compareMode: boolean- /** User-positioned overrides for the two compare windows. Null until the overlay is dragged. */- currentWindowOverride: OverlayWindow | null- previousWindowOverride: OverlayWindow | null+ comparison: TracingComparison | null}// The /tracing scene's viewer instance. It is the props default, so uncalled wrappers@@ -93,12 +158,12 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),setSort: (orderBy: TracingOrderBy, orderDirection: TracingOrderDirection) => ({ orderBy, orderDirection }),setViewMode: (viewMode: TracingViewMode) => ({ viewMode }),- setCompareMode: (compareMode: boolean) => ({ compareMode }),+ setComparison: (comparison: TracingComparison | null) => ({ comparison }),/**- * Persist the user-dragged overlay windows. Both must be supplied. Setting these- * never touches dateRange — the sparkline range is locked once compare mode is on.+ * Persist the user-dragged overlay windows ('custom' preset only). Both must be supplied.+ * Setting these never touches dateRange — the sparkline range is locked while comparing.*/- setOverlayWindows: (current: OverlayWindow, previous: OverlayWindow) => ({ current, previous }),+ updateComparisonWindows: (current: OverlayWindow, previous: OverlayWindow) => ({ current, previous }),setFilters: (filters: Partial<TracingFilters>) => ({ filters }),// Mirror of the `pinnedFilters` prop into state so consumers can read it via// useValues without going through the kea selector input-prop machinery@@ -158,31 +223,23 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([setFilters: (state, { filters }) => filters.viewMode ?? state,},],- compareMode: [- false as boolean,- {- setCompareMode: (_, { compareMode }) => compareMode,- setFilters: (state, { filters }) => filters.compareMode ?? state,- },- ],- currentWindowOverride: [- null as OverlayWindow | null,+ comparison: [+ null as TracingComparison | null,{- setOverlayWindows: (_, { current }) => current,+ setComparison: (_, { comparison }) => comparison,+ updateComparisonWindows: (state, { current, previous }) =>+ state?.mode === 'time'+ ? { ...state, currentWindowOverride: current, previousWindowOverride: previous }+ : state,// Any date-range change invalidates user-positioned windows — they were absolute// ms positions inside the old sparkline range, meaningless in a new one.- setDateRange: () => null,- setCompareMode: () => null,- setFilters: (state, { filters }) => filters.currentWindowOverride ?? state,- },- ],- previousWindowOverride: [- null as OverlayWindow | null,- {- setOverlayWindows: (_, { previous }) => previous,- setDateRange: () => null,- setCompareMode: () => null,- setFilters: (state, { filters }) => filters.previousWindowOverride ?? state,+ setDateRange: (state) =>+ state?.mode === 'time' && (state.currentWindowOverride || state.previousWindowOverride)+ ? { ...state, currentWindowOverride: null, previousWindowOverride: null }+ : state,+ // `filters.comparison` can legitimately be null (exit comparison), so check presence+ // rather than nullish-coalescing.+ setFilters: (state, { filters }) => (filters.comparison !== undefined ? filters.comparison : state),},],pinnedFilters: [@@ -195,39 +252,26 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([selectors({filters: [- (s) => [- s.dateRange,- s.serviceNames,- s.filterGroup,- s.orderBy,- s.orderDirection,- s.viewMode,- s.compareMode,- s.currentWindowOverride,- s.previousWindowOverride,- ],- (+ (s) => [s.dateRange, s.serviceNames, s.filterGroup, s.orderBy, s.orderDirection, s.viewMode, s.comparison],+ (dateRange, serviceNames, filterGroup, orderBy, orderDirection, viewMode, comparison): TracingFilters => ({dateRange,serviceNames,filterGroup,orderBy,orderDirection,viewMode,- compareMode,- currentWindowOverride,- previousWindowOverride- ): TracingFilters => ({- dateRange,- serviceNames,- filterGroup,- orderBy,- orderDirection,- viewMode,- compareMode,- currentWindowOverride,- previousWindowOverride,+ comparison,}),],+ compareActive: [(s) => [s.comparison], (comparison: TracingComparison | null): boolean => comparison !== null],+ // Time-mode narrowing in one place: the window selectors and the fetch layer's time-shift+ // compareFilter must read this, not `compareActive`, so future non-time modes can't+ // silently inherit time-shift semantics.+ timeComparison: [+ (s) => [s.comparison],+ (comparison: TracingComparison | null): TimeComparison | null =>+ comparison?.mode === 'time' ? comparison : null,+ ],// The filter group queries must use: the user-editable filterGroup with the// embedder's pinned filters merged in. Everything that builds a request reads// this, never `filters.filterGroup` directly.@@ -250,30 +294,45 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([}),],sparklineWindowMs: [(s) => [s.dateRange], (dateRange: DateRange): OverlayWindow => resolveWindow(dateRange)],+ // Side A of the comparison (and the window every aggregation covers). Named presets — and+ // no comparison at all, e.g. the Operations tab — use the full selected range; only the+ // 'custom' preset carves out the draggable right-aligned 40% sub-window.currentWindowMs: [- (s) => [s.sparklineWindowMs, s.currentWindowOverride],- (sparklineWindowMs: OverlayWindow, override: OverlayWindow | null): OverlayWindow => {- if (override) {- return override+ (s) => [s.sparklineWindowMs, s.timeComparison],+ (sparklineWindowMs: OverlayWindow, timeComparison: TimeComparison | null): OverlayWindow => {+ if (timeComparison?.preset !== 'custom') {+ return sparklineWindowMs+ }+ if (timeComparison.currentWindowOverride) {+ return timeComparison.currentWindowOverride}- // Default: right-aligned, 40% of the sparkline duration.const duration = sparklineWindowMs.endMs - sparklineWindowMs.startMs- const windowDuration = duration * 0.4+ const windowDuration = duration * CUSTOM_WINDOW_FRACTIONreturn { startMs: sparklineWindowMs.endMs - windowDuration, endMs: sparklineWindowMs.endMs }},],+ // Side B (the baseline): the current window shifted back per the preset. Always equal in+ // duration to side A — the backend infers the compare window's end from that duration.previousWindowMs: [- (s) => [s.sparklineWindowMs, s.previousWindowOverride],- (sparklineWindowMs: OverlayWindow, override: OverlayWindow | null): OverlayWindow => {- if (override) {- return override+ (s) => [s.sparklineWindowMs, s.currentWindowMs, s.timeComparison],+ (+ sparklineWindowMs: OverlayWindow,+ currentWindowMs: OverlayWindow,+ timeComparison: TimeComparison | null+ ): OverlayWindow => {+ const preset = timeComparison?.preset ?? 'previous_period'+ if (preset === 'custom') {+ if (timeComparison?.previousWindowOverride) {+ return timeComparison.previousWindowOverride+ }+ const duration = sparklineWindowMs.endMs - sparklineWindowMs.startMs+ const windowDuration = duration * CUSTOM_WINDOW_FRACTION+ const endMs = sparklineWindowMs.endMs - duration * CUSTOM_BASELINE_SHIFT_FRACTION+ return { startMs: endMs - windowDuration, endMs }}- // Default: same 40% width, shifted -50% of sparkline duration from current's- // right edge — i.e., right edge at end - 50% of duration.- const duration = sparklineWindowMs.endMs - sparklineWindowMs.startMs- const windowDuration = duration * 0.4- const endMs = sparklineWindowMs.endMs - duration * 0.5- return { startMs: endMs - windowDuration, endMs }+ const currentDuration = currentWindowMs.endMs - currentWindowMs.startMs+ const shiftMs = TIME_COMPARE_PRESET_DEFS[preset].shiftMs ?? currentDuration+ return { startMs: currentWindowMs.startMs - shiftMs, endMs: currentWindowMs.endMs - shiftMs }},],}),diff --git a/products/tracing/frontend/tracingSceneLogic.test.ts b/products/tracing/frontend/tracingSceneLogic.test.tsnew file mode 100644index 000000000000..0efc02835abd--- /dev/null+++ b/products/tracing/frontend/tracingSceneLogic.test.ts@@ -0,0 +1,101 @@+import { router } from 'kea-router'++import api from 'lib/api'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'++import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from './tracingFiltersLogic'+import { tracingSceneLogic } from './tracingSceneLogic'++describe('tracingSceneLogic', () => {+ let logic: ReturnType<typeof tracingSceneLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })+ jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })+ jest.spyOn(api.tracing, 'count').mockResolvedValue({ count: 0, traceCount: 0 })+ jest.spyOn(api.tracing, 'aggregate').mockResolvedValue({ results: [], compare: null })+ jest.spyOn(api.tracing, 'durationHistogram').mockResolvedValue({ results: [] })+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ const mountAt = (searchParams: Record<string, string>): ReturnType<typeof tracingFiltersLogic.build> => {+ router.actions.push('/tracing', searchParams)+ logic = tracingSceneLogic()+ logic.mount()+ return tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID })+ }++ it('migrates legacy compare=true links to the custom time comparison', () => {+ const filtersLogic = mountAt({ compare: 'true' })+ expect(filtersLogic.values.comparison).toEqual({+ mode: 'time',+ preset: 'custom',+ currentWindowOverride: null,+ previousWindowOverride: null,+ })+ })++ it('reads the comparison URL param and writes it back without the legacy param', () => {+ const filtersLogic = mountAt({ comparison: JSON.stringify({ mode: 'time', preset: 'yesterday' }) })+ expect(filtersLogic.values.comparison).toMatchObject({ mode: 'time', preset: 'yesterday' })++ filtersLogic.actions.setComparison({+ mode: 'time',+ preset: 'last_week',+ currentWindowOverride: null,+ previousWindowOverride: null,+ })+ expect(JSON.parse(router.values.searchParams.comparison)).toEqual({ mode: 'time', preset: 'last_week' })+ expect(router.values.searchParams).not.toHaveProperty('compare')+ })++ it('ignores a malformed comparison param', () => {+ const filtersLogic = mountAt({ comparison: 'not-json' })+ expect(filtersLogic.values.comparison).toBeNull()+ })++ it('falls back to the legacy compare param when the comparison param is malformed', () => {+ const filtersLogic = mountAt({ comparison: '{"mode":"segment"}', compare: 'true' })+ expect(filtersLogic.values.comparison).toMatchObject({ mode: 'time', preset: 'custom' })+ })++ it('keeps the active comparison when navigating to a URL with a malformed comparison param', () => {+ const filtersLogic = mountAt({ comparison: JSON.stringify({ mode: 'time', preset: 'yesterday' }) })+ expect(filtersLogic.values.comparison).toMatchObject({ preset: 'yesterday' })++ router.actions.push('/tracing', { comparison: 'not-json' })+ expect(filtersLogic.values.comparison).toMatchObject({ preset: 'yesterday' })+ })++ // Guards the operations-tab rate denominator: on the operations tab the aggregate must always+ // cover the whole selected range (compare: false), even with a comparison active. A filter+ // change fires both the windowed aggregate (via runQuery) and the explicit full-range one, and+ // the full-range fetch must be the last one dispatched so it wins the abort race. Reorder those+ // two dispatches and the operations table would silently divide by the narrow compare sub-window.+ it('keeps the operations aggregate on the full range when a filter changes while comparing', async () => {+ silenceKeaLoadersErrors()+ const filtersLogic = mountAt({ comparison: JSON.stringify({ mode: 'time', preset: 'custom' }) })+ expect(filtersLogic.values.compareActive).toBe(true)++ const aggregateSpy = jest.spyOn(api.tracing, 'aggregate')+ logic.actions.setActiveTracingTab('operations')+ await new Promise((resolve) => setTimeout(resolve, 0))+ aggregateSpy.mockClear()++ filtersLogic.actions.setServiceNames(['svc-a'])+ await new Promise((resolve) => setTimeout(resolve, 0))++ expect(aggregateSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({ compareFilter: expect.objectContaining({ compare: false }) }),+ expect.anything()+ )+ resumeKeaLoadersErrors()+ })+})diff --git a/products/tracing/frontend/tracingSceneLogic.ts b/products/tracing/frontend/tracingSceneLogic.tsindex 2788beaae963..e14e1f52102f 100644--- a/products/tracing/frontend/tracingSceneLogic.ts+++ b/products/tracing/frontend/tracingSceneLogic.ts@@ -12,12 +12,16 @@ import { Breadcrumb } from '~/types'import { PREFETCH_SPANS, tracingDataLogic } from './tracingDataLogic'import {+ DEFAULT_CUSTOM_COMPARISON,DEFAULT_DATE_RANGE,DEFAULT_ORDER_BY,DEFAULT_ORDER_DIRECTION,DEFAULT_SERVICE_NAMES,DEFAULT_VIEW_MODE,+ parseComparison,+ serializeComparison,TRACING_SCENE_VIEWER_ID,+ type TracingComparison,tracingFiltersLogic,} from './tracingFiltersLogic'import type { tracingSceneLogicType } from './tracingSceneLogicType'@@ -54,7 +58,7 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['isDurationMode',],tracingFiltersLogic({ id: TRACING_SCENE_VIEWER_ID }),- ['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs'],+ ['filters', 'utcDateRange', 'sparklineWindowMs', 'currentWindowMs', 'previousWindowMs', 'compareActive'],],actions: [tracingDataLogic({ id: TRACING_SCENE_VIEWER_ID }),@@ -74,8 +78,8 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>(['setFilterGroup','setSort','setViewMode',- 'setCompareMode',- 'setOverlayWindows',+ 'setComparison',+ 'updateComparisonWindows','setFilters',],],@@ -206,8 +210,16 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([posthog.capture('tracing filter changed', { filter_type: filterType, ...extraProps })actions.syncUrlAndRunQuery()// Keep the Operations aggregate in sync with filters/date while that tab is active.+ // Full range: the Operations view always covers the whole selected range, even while+ // a (traces-tab) comparison is active.+ //+ // This MUST stay after syncUrlAndRunQuery. When a comparison is active, that call+ // synchronously runs runQuery, whose listener fires a windowed fetchAggregation();+ // every fetchAggregation aborts the previous one, so the last dispatched wins. Keeping+ // the full-range fetch last makes it beat the windowed one deterministically —+ // otherwise the Operations table would divide by the narrow compare sub-window.if (values.activeTracingTab === 'operations') {- actions.fetchAggregation()+ actions.fetchAggregation({ fullRange: true })}},setDateRange: () => actions.handleFilterChange('date_range'),@@ -216,8 +228,13 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([setSort: ({ orderBy, orderDirection }) =>actions.handleFilterChange('sort', { column: orderBy, direction: orderDirection }),setViewMode: ({ viewMode }) => actions.handleFilterChange('view_mode', { mode: viewMode }),- setCompareMode: ({ compareMode }) => actions.handleFilterChange('compare_mode', { enabled: compareMode }),- setOverlayWindows: () => {+ setComparison: ({ comparison }) =>+ actions.handleFilterChange('comparison', {+ enabled: comparison !== null,+ mode: comparison?.mode ?? null,+ preset: comparison?.mode === 'time' ? comparison.preset : null,+ }),+ updateComparisonWindows: () => {// Overlay drags only refetch the aggregation — the sparkline canvas range// stays fixed while the user moves windows around within it. If the compare-flame// modal is open we also refetch its tree so it doesn't display stale windows.@@ -234,6 +251,10 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([},setActiveTracingTab: ({ tab }) => {if (tab === 'operations') {+ actions.fetchAggregation({ fullRange: true })+ } else if (values.compareActive) {+ // Returning to the traces tab with a comparison active: the aggregation state+ // holds the operations full-range data — refetch the windowed compare version.actions.fetchAggregation()}},@@ -302,9 +323,28 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([}}- const compareFromUrl = searchParams.compare === 'true' || searchParams.compare === true- if (compareFromUrl !== values.filters.compareMode) {- filtersFromUrl.compareMode = compareFromUrl+ // Legacy `compare=true` links map to the custom-windows preset; everything else+ // round-trips through parse/serializeComparison so future modes don't touch this file.+ const legacyComparisonFromUrl: TracingComparison | null =+ searchParams.compare === 'true' || searchParams.compare === true ? DEFAULT_CUSTOM_COMPARISON : null+ let comparisonFromUrl = legacyComparisonFromUrl+ // A malformed (or unknown future-mode) comparison param falls back to the legacy+ // param, and failing that is ignored rather than clearing an active comparison —+ // matching how the dateRange/filterGroup handlers treat malformed JSON.+ let comparisonParamInvalid = false+ if (searchParams.comparison) {+ const parsed = parseComparison(searchParams.comparison)+ if (parsed) {+ comparisonFromUrl = parsed+ } else if (!legacyComparisonFromUrl) {+ comparisonParamInvalid = true+ }+ }+ if (+ !comparisonParamInvalid &&+ serializeComparison(comparisonFromUrl) !== serializeComparison(values.filters.comparison)+ ) {+ filtersFromUrl.comparison = comparisonFromUrlhasChanges = true}@@ -375,8 +415,9 @@ export const tracingSceneLogic = kea<tracingSceneLogicType>([if (values.filters.orderDirection !== DEFAULT_ORDER_DIRECTION) {searchParams.orderDirection = values.filters.orderDirection}- if (values.filters.compareMode) {- searchParams.compare = 'true'+ const comparisonParam = serializeComparison(values.filters.comparison)+ if (comparisonParam) {+ searchParams.comparison = comparisonParam}if (values.filters.viewMode !== DEFAULT_VIEW_MODE) {searchParams.view = values.filters.viewMode