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.

fix(tracing): re-resolve relative time ranges when refreshing (#93180)

Jon McCallum7c33abc3ccc2
diff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.ts
index dcac13620933..ee3360e5c97d 100644
--- a/products/tracing/frontend/tracingDataLogic.test.ts
+++ b/products/tracing/frontend/tracingDataLogic.test.ts
@@ -461,6 +461,45 @@ describe('tracingDataLogic', () => {
})
})
+ describe('refresh', () => {
+ // The sparkline, count and heatmap skip their fetch while the scope key is unchanged. A
+ // relative range ('-30M') holds that key identical however far the window has moved, so
+ // the refresh button reloaded the list while the chart and the "N traces" label stayed put.
+ // The default range is relative and open-ended ('-1h'), which is the case that broke.
+ it('refetches the count and sparkline when the user refreshes an unchanged relative range', async () => {
+ logic = mountWithSpans([])
+ const listSpansSpy = jest.spyOn(api.tracing, 'listSpans').mockResolvedValue({ results: [], hasMore: false })
+ const countSpy = jest.spyOn(api.tracing, 'count').mockResolvedValue({ count: 1, traceCount: 1 })
+ const sparklineSpy = jest.spyOn(api.tracing, 'sparkline').mockResolvedValue({ results: [] })
+
+ try {
+ await expectLogic(logic, () => {
+ logic.actions.runQuery()
+ }).toFinishAllListeners()
+ expect(countSpy).toHaveBeenCalled()
+ countSpy.mockClear()
+ sparklineSpy.mockClear()
+
+ // A sort or view-mode toggle re-runs the query without changing scope — still skipped.
+ await expectLogic(logic, () => {
+ logic.actions.runQuery()
+ }).toFinishAllListeners()
+ expect(countSpy).not.toHaveBeenCalled()
+ expect(sparklineSpy).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshQuery()
+ }).toFinishAllListeners()
+ expect(countSpy).toHaveBeenCalled()
+ expect(sparklineSpy).toHaveBeenCalled()
+ } finally {
+ listSpansSpy.mockRestore()
+ countSpy.mockRestore()
+ sparklineSpy.mockRestore()
+ }
+ })
+ })
+
describe('deferred filter refresh', () => {
// The trace drawer's attribute buttons call addFilter, which sets skipQuery so the list
// doesn't reload behind the open drawer. Losing that gate means every attribute click
diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.ts
index c0f3b02b1b05..680df58e5e00 100644
--- a/products/tracing/frontend/tracingDataLogic.ts
+++ b/products/tracing/frontend/tracingDataLogic.ts
@@ -210,6 +210,9 @@ export interface tracingDataLogicActions {
refreshDeferredFilters: () => {
value: true
} // tracingFiltersLogic
+ refreshWindowAnchor: () => {
+ value: true
+ } // tracingFiltersLogic
setChartType: (chartType: import('./tracingFiltersLogic').TracingChartType) => {
chartType: import('./tracingFiltersLogic').TracingChartType
} // tracingFiltersLogic
@@ -670,6 +673,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
'updateComparisonWindows',
'setFilters',
'refreshDeferredFilters',
+ 'refreshWindowAnchor',
],
featureFlagLogic,
['setFeatureFlags'],
@@ -684,9 +688,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// A completed 2D brush on the latency heatmap — maps to a date range + duration chips.
applyHeatmapBrush: (selection: HeatmapBrushSelection) => ({ selection }),
runQuery: true,
- // An explicit user refresh. Same fetches as runQuery, but the scope-skip caches below
- // are dropped first, so the charts and the count re-hit the API even though nothing
- // about the query changed.
+ // An explicit user refresh. Same fetches as runQuery, but the window is re-anchored to
+ // the clock and the scope-skip caches below are dropped first, so the charts and the
+ // count re-hit the API even though nothing about the query changed.
refreshQuery: true,
fetchNextPage: true,
loadMoreTraceSpans: true,
@@ -1453,6 +1457,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([
// state) lives in tracingViewerLogic.
updateComparisonWindows: () => actions.fetchAggregation(),
refreshQuery: () => {
+ // A relative range ('-30M') keeps the scope key identical however far the window has
+ // moved, so the refresh re-anchors the window the chart draws against as well.
+ actions.refreshWindowAnchor()
cache.sparklineScope = undefined
cache.matchingCountsScope = undefined
cache.latencyHeatmapScope = undefined
diff --git a/products/tracing/frontend/tracingFiltersLogic.test.ts b/products/tracing/frontend/tracingFiltersLogic.test.ts
index a26db4017d2a..301d770c0cf8 100644
--- a/products/tracing/frontend/tracingFiltersLogic.test.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.test.ts
@@ -240,6 +240,58 @@ describe('tracingFiltersLogic', () => {
})
})
+ describe('relative ranges', () => {
+ const NOW = Date.parse('2024-01-08T12:00:00Z')
+ const MINUTE_MS = 60 * 1000
+ let nowSpy: jest.SpyInstance<number, []>
+
+ beforeEach(() => {
+ nowSpy = jest.spyOn(Date, 'now').mockReturnValue(NOW)
+ })
+
+ afterEach(() => {
+ nowSpy.mockRestore()
+ })
+
+ // The window resolved through a unit map local to this file that had 'm' and 'M' the other
+ // way round, so the "Last 30 minutes" preset ('-30M') spanned 30 months, and 'w'/'q'/'y'
+ // matched nothing and collapsed to a zero-width window. The letters must mean what they
+ // mean everywhere else in the app.
+ it.each([
+ ['-30M', 30 * MINUTE_MS],
+ ['-3h', 3 * HOUR_MS],
+ ['-7d', 7 * DAY_MS],
+ ['-2w', 14 * DAY_MS],
+ ])('resolves %s back from now', (dateFrom, expectedSpanMs) => {
+ logic.actions.setDateRange({ date_from: dateFrom, date_to: null })
+
+ expect(logic.values.sparklineWindowMs).toEqual({ startMs: NOW - expectedSpanMs, endMs: NOW })
+ })
+
+ // Refreshing has to move an open-ended window along. Reading the clock inside the memoized
+ // selector pinned it to the moment the range was picked, so the chart never caught up.
+ it('advances an open-ended window when the anchor refreshes', () => {
+ logic.actions.setDateRange({ date_from: '-30M', date_to: null })
+ nowSpy.mockReturnValue(NOW + HOUR_MS)
+
+ logic.actions.refreshWindowAnchor()
+
+ expect(logic.values.sparklineWindowMs).toEqual({
+ startMs: NOW + HOUR_MS - 30 * MINUTE_MS,
+ endMs: NOW + HOUR_MS,
+ })
+ })
+
+ it('leaves an absolute window where it is when the anchor refreshes', () => {
+ logic.actions.setDateRange(ABSOLUTE_RANGE)
+ nowSpy.mockReturnValue(NOW + HOUR_MS)
+
+ logic.actions.refreshWindowAnchor()
+
+ expect(logic.values.sparklineWindowMs).toEqual({ startMs: RANGE_START, endMs: RANGE_END })
+ })
+ })
+
describe('refreshDeferredFilters', () => {
it('clears the deferred-refresh flag set by addFilter', () => {
logic.actions.addFilter('http.method', 'GET')
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index 32432c157666..68d24b7c2b07 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -15,6 +15,7 @@ import {
import { DEFAULT_UNIVERSAL_GROUP_FILTER } from 'lib/components/UniversalFilters/constants'
import { dayjs } from 'lib/dayjs'
+import { componentsToDayJs, dateStringToComponents } from 'lib/utils/dateFilters'
import { DateRange } from '~/queries/schema/schema-general'
import {
@@ -196,6 +197,7 @@ export interface tracingFiltersLogicValues {
date_to: string | null | undefined
}
viewMode: TracingViewMode
+ windowAnchorMs: number
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -214,6 +216,9 @@ export interface tracingFiltersLogicActions {
refreshDeferredFilters: () => {
value: true
}
+ refreshWindowAnchor: () => {
+ value: true
+ }
setChartType: (chartType: TracingChartType) => {
chartType: TracingChartType
}
@@ -288,7 +293,7 @@ export interface tracingFiltersLogicMeta {
date_from: string | null | undefined
date_to: string | null | undefined
}
- sparklineWindowMs: (dateRange: DateRange) => OverlayWindow
+ sparklineWindowMs: (dateRange: DateRange, windowAnchorMs: number) => OverlayWindow
currentWindowMs: (sparklineWindowMs: OverlayWindow, timeComparison: TimeComparison | null) => OverlayWindow
previousWindowMs: (
sparklineWindowMs: OverlayWindow,
@@ -344,6 +349,9 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
suppressAutoOpenForFilter: (filter: UniversalFiltersGroupValue) => ({ filter }),
// Fired once the trace drawer closes, if a filter was added while it was open.
refreshDeferredFilters: true,
+ // Re-reads the clock an open-ended range resolves "now" against. Dispatched by the data
+ // logic when the user refreshes.
+ refreshWindowAnchor: true,
}),
reducers({
@@ -446,6 +454,17 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
refreshDeferredFilters: () => false,
},
],
+ // A relative `date_from` ('-30M') resolves against this instead of reading the clock inside
+ // the selector — a memoized selector would keep returning the moment the range was picked.
+ // Mirrors the `dateRange` writes above, so re-picking a range still re-reads the clock.
+ windowAnchorMs: [
+ Date.now(),
+ {
+ refreshWindowAnchor: () => Date.now(),
+ setDateRange: () => Date.now(),
+ setFilters: (state, { filters }) => (filters.dateRange ? Date.now() : state),
+ },
+ ],
}),
selectors({
@@ -510,7 +529,10 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
: dateRange.date_to,
}),
],
- sparklineWindowMs: [(s) => [s.dateRange], (dateRange: DateRange): OverlayWindow => resolveWindow(dateRange)],
+ sparklineWindowMs: [
+ (s) => [s.dateRange, s.windowAnchorMs],
+ (dateRange: DateRange, windowAnchorMs: number): OverlayWindow => resolveWindow(dateRange, windowAnchorMs),
+ ],
// 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.
@@ -595,9 +617,8 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
}),
])
-function resolveWindow(dateRange: DateRange): { startMs: number; endMs: number } {
- const endMs =
- dateRange.date_to && dayjs(dateRange.date_to).isValid() ? dayjs(dateRange.date_to).valueOf() : Date.now()
+function resolveWindow(dateRange: DateRange, nowMs: number): { startMs: number; endMs: number } {
+ const endMs = dateRange.date_to && dayjs(dateRange.date_to).isValid() ? dayjs(dateRange.date_to).valueOf() : nowMs
const startMs =
dateRange.date_from && dayjs(dateRange.date_from).isValid()
? dayjs(dateRange.date_from).valueOf()
@@ -605,24 +626,16 @@ function resolveWindow(dateRange: DateRange): { startMs: number; endMs: number }
return { startMs, endMs }
}
-const RELATIVE_RE = /^-(\d+)([smhdM])$/
-
+// Delegates to the app-wide parser rather than mapping the unit letters here. A local map had 'm'
+// and 'M' the other way round, so the "Last 30 minutes" preset ('-30M') resolved to 30 months, and
+// it knew no 'w'/'q'/'y' at all, which collapsed those ranges to a zero-width window.
function resolveRelativeMs(input: string | null | undefined, anchorMs: number): number {
if (!input) {
return anchorMs
}
- const match = RELATIVE_RE.exec(input.trim())
- if (!match) {
+ const components = dateStringToComponents(input.trim())
+ if (!components) {
return anchorMs
}
- const [, nRaw, unit] = match
- const n = Number(nRaw)
- const unitMap: Record<string, dayjs.UnitType> = {
- s: 'second',
- m: 'minute',
- h: 'hour',
- d: 'day',
- M: 'month',
- }
- return dayjs(anchorMs).subtract(n, unitMap[unit]).valueOf()
+ return componentsToDayJs(components, dayjs(anchorMs)).valueOf()
}