: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(metrics): extrapolate and dash the in-progress last bucket (#117052)
Frank Hamand6b2142567546
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 749f40fe7bae..8978ed2a6c1c 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -62,6 +62,7 @@ export const MetricsViewer = (): JSX.Element => {metricsDisplay,heatmapEligible,histogramQueryNode,+ metricsQueryNode,} = useValues(logic)const {setLiveRefresh,@@ -308,6 +309,7 @@ export const MetricsViewer = (): JSX.Element => {fallbackName={formula || metricName || (language === 'promql' ? queryText : 'metric')}display={metricsDisplay}exemplars={chartMarkers}+ query={metricsQueryNode ?? undefined}/>) : !queryLoading ? (<div className="h-full flex items-center justify-center text-secondary text-sm">diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsxindex becc5a306707..96f1f28ceda1 100644--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx@@ -152,7 +152,12 @@ function MetricsQueryResults({ dataKey: key, ...props }: MetricsQueryNodeProps &</LemonBanner></div>) : hasPoints ? (- <MetricsPanel series={series} fallbackName={fallbackName} display={props.query.display} />+ <MetricsPanel+ series={series}+ fallbackName={fallbackName}+ display={props.query.display}+ query={props.query}+ />) : !responseLoading ? (<div className="flex-1 flex items-center justify-center text-secondary text-sm">No data for this metric in the selected range.diff --git a/products/metrics/frontend/panels/MetricsPanel.tsx b/products/metrics/frontend/panels/MetricsPanel.tsxindex 0c9bf82e7119..64fbc4e4028a 100644--- a/products/metrics/frontend/panels/MetricsPanel.tsx+++ b/products/metrics/frontend/panels/MetricsPanel.tsx@@ -4,6 +4,7 @@ import type { MetricsExemplar } from '../components/MetricsExemplarMarkers'import type { MetricsChartSeries } from '../components/metricsSeries'import { BarGaugePanel } from './BarGaugePanel'import { GaugePanel } from './GaugePanel'+import type { MetricsPartialBucketQuery } from './metricsPartialBucket'import { seriesUnit } from './metricsReduce'import { resolvePanelType } from './registry'import { StatPanel } from './StatPanel'@@ -30,11 +31,14 @@ export function MetricsPanel({display,fallbackName,exemplars,+ query,}: {series: MetricsChartSeries[]display?: MetricsDisplaySettingsfallbackName: stringexemplars?: MetricsExemplar[]+ /** Lets the time-series panel tell counter series apart, to extrapolate a partial last bucket. */+ query?: MetricsPartialBucketQuery}): JSX.Element {const type = resolvePanelType(display)const resolvedSeries = withResolvedUnits(series, display?.unit)@@ -58,6 +62,7 @@ export function MetricsPanel({display={display ?? {}}fallbackName={fallbackName}exemplars={exemplars}+ query={query}/>)}diff --git a/products/metrics/frontend/panels/TimeSeriesPanel.tsx b/products/metrics/frontend/panels/TimeSeriesPanel.tsxindex 45fe6621d028..03ee27fc8c87 100644--- a/products/metrics/frontend/panels/TimeSeriesPanel.tsx+++ b/products/metrics/frontend/panels/TimeSeriesPanel.tsx@@ -17,6 +17,12 @@ import { teamLogic } from 'scenes/teamLogic'import { buildMetricsChartConfig } from '../components/metricsChartConfig'import { MetricsExemplarMarkers, type MetricsExemplar } from '../components/MetricsExemplarMarkers'import { formatSeriesNames, seriesColor } from '../components/metricsSeries'+import {+ extrapolatePartialValue,+ isExtrapolatable,+ type MetricsPartialBucketQuery,+ partialBucketFraction,+} from './metricsPartialBucket'import type { MetricsPanelProps } from './registry'const AREA_FILL_OPACITY = 0.2@@ -26,32 +32,48 @@ const AREA_FILL_OPACITY = 0.2** A null bucket is a gap (a non-representable aggregate). quill's `Series.data` is `number[]`* (no null), so a gap renders as 0 until quill takes null data; `display.nullMode` is read by- * the chart config only, not here. */+ * the chart config only, not here.+ *+ * A last bucket still in progress draws as a dashed segment. Counter series show it scaled up to+ * the full bucket, so the partial window does not read as a sudden drop. */export function TimeSeriesPanel({series,display,fallbackName,exemplars,-}: MetricsPanelProps & { exemplars?: MetricsExemplar[] }): JSX.Element {+ query,+}: MetricsPanelProps & { exemplars?: MetricsExemplar[]; query?: MetricsPartialBucketQuery }): JSX.Element {const { timezone } = useValues(teamLogic)const theme = useChartTheme()const isBar = display?.type === 'bar'const isArea = display?.type === 'area'+ const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])+ const partialFraction = useMemo(+ () => (isBar ? null : partialBucketFraction(labels, query, timezone)),+ [labels, isBar, query, timezone]+ )+const chartSeries = useMemo<Series[]>(() => {const names = formatSeriesNames(series.map((s) => ({ labels: s.labels, metric_name: s.metricName ?? undefined, clause: s.clause })),fallbackName)- return series.map((s, index) => ({- key: `${index}`,- label: names[index],- data: s.points.map((p) => p.value ?? 0),- color: getColorVar(seriesColor(index)),- ...(isArea ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),- }))- }, [series, fallbackName, isArea])- const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])+ return series.map((s, index) => {+ const data = s.points.map((p) => p.value ?? 0)+ if (partialFraction !== null && isExtrapolatable(s, query)) {+ data[data.length - 1] = extrapolatePartialValue(data[data.length - 1], partialFraction)+ }+ return {+ key: `${index}`,+ label: names[index],+ data,+ color: getColorVar(seriesColor(index)),+ ...(isArea ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),+ ...(partialFraction !== null ? { stroke: { partial: { fromIndex: data.length - 1 } } } : {}),+ }+ })+ }, [series, fallbackName, isArea, partialFraction, query])// `MetricsPanel` gives every series the same resolved unit, so the first series speaks for the chart.const unit = series[0]?.unit ?? undefinedconst plottedValues = useMemo(() => chartSeries.flatMap((s) => s.data), [chartSeries])@@ -62,11 +84,16 @@ export function TimeSeriesPanel({display,xAxis: { timezone },seriesCount: chartSeries.length,- labelFormatter: (label: string) => dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss'),+ labelFormatter: (label: string) => {+ const formatted = dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss')+ return partialFraction !== null && label === labels[labels.length - 1]+ ? `${formatted} (in progress)`+ : formatted+ },unit,values: plottedValues,}),- [timezone, chartSeries.length, display, unit, plottedValues]+ [timezone, chartSeries.length, display, unit, plottedValues, partialFraction, labels])const markers = exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : nulldiff --git a/products/metrics/frontend/panels/metricsPartialBucket.test.ts b/products/metrics/frontend/panels/metricsPartialBucket.test.tsnew file mode 100644index 000000000000..0238819d733b--- /dev/null+++ b/products/metrics/frontend/panels/metricsPartialBucket.test.ts@@ -0,0 +1,120 @@+import { dayjs } from 'lib/dayjs'++import type { MetricsQueryClause } from '~/queries/schema/schema-general'++import type { MetricsChartSeries } from '../components/metricsSeries'+import {+ extrapolatePartialValue,+ isExtrapolatable,+ type MetricsPartialBucketQuery,+ partialBucketFraction,+} from './metricsPartialBucket'++const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']++const series = (clause: string): MetricsChartSeries => ({ labels: {}, points: [], clause })+const clause = (name: string, extra: Partial<MetricsQueryClause> = {}): MetricsQueryClause => ({+ name,+ metricName: 'http.requests',+ ...extra,+})+const query = (+ clauses: MetricsQueryClause[],+ extra: Partial<MetricsPartialBucketQuery> = {}+): MetricsPartialBucketQuery => ({+ clauses,+ ...extra,+})++describe('partialBucketFraction', () => {+ const hourly = query([], { interval: 'hour' })++ it.each([+ ['quarter into the last bucket', '2026-08-01T12:15:00Z', 0.25],+ ['last bucket complete', '2026-08-01T13:00:00Z', null],+ ['now before the last bucket', '2026-08-01T11:30:00Z', null],+ ])('%s', (_, now, expected) => {+ expect(partialBucketFraction(BUCKETS, hourly, 'UTC', dayjs(now))).toBe(expected)+ })++ it('uses the query interval, not the spacing of sparse buckets', () => {+ const sparse = ['2026-08-01T10:00:00Z', '2026-08-01T12:00:00Z']+ expect(partialBucketFraction(sparse, hourly, 'UTC', dayjs('2026-08-01T13:00:00Z'))).toBeNull()+ expect(partialBucketFraction(sparse, hourly, 'UTC', dayjs('2026-08-01T12:30:00Z'))).toBe(0.5)+ })++ it('picks the interval from the range when the query does not set one', () => {+ const fifteenMinutes = ['2026-08-01T11:45:00Z', '2026-08-01T12:00:00Z']+ const auto = query([], { dateRange: { date_from: '2026-08-01T00:00:00Z' } })+ expect(partialBucketFraction(fifteenMinutes, auto, 'UTC', dayjs('2026-08-01T12:05:00Z'))).toBeCloseTo(1 / 3)+ })++ it('treats a relative range start as a rolling window, like the backend', () => {+ const halfHours = ['2026-08-01T11:30:00Z', '2026-08-01T12:00:00Z']+ const lastDay = query([], { dateRange: { date_from: '-1d' } })+ expect(partialBucketFraction(halfHours, lastDay, 'UTC', dayjs('2026-08-01T12:05:00Z'))).toBeCloseTo(1 / 6)+ })++ it.each([+ ['a fixed range end', query([], { interval: 'hour', dateRange: { date_to: '2026-08-01T12:15:00Z' } })],+ ['buckets closer than the query interval', query([], { interval: 'day' })],+ ['no query', undefined],+ ])('stays solid for %s', (_, q) => {+ expect(partialBucketFraction(BUCKETS, q, 'UTC', dayjs('2026-08-01T12:15:00Z'))).toBeNull()+ })+})++describe('isExtrapolatable', () => {+ it.each([+ ['rate range function', clause('a', { rangeFunction: 'rate', aggregation: 'sum' }), true],+ ['increase aggregation', clause('a', { aggregation: 'increase' }), true],+ ['gauge average', clause('a', { aggregation: 'avg' }), false],+ ['sum of latest values', clause('a', { aggregation: 'sum' }), false],+ ['count of series reporting a rate', clause('a', { rangeFunction: 'rate', aggregation: 'count' }), false],+ ])('%s', (_, c, expected) => {+ expect(isExtrapolatable(series('a'), query([c]))).toBe(expected)+ })++ it.each([+ ['a + b', true],+ ['(a - b) + a', true],+ ['a / b', false],+ ['a * 100', false],+ ['a + 100', false],+ ])('formula %s', (formula, expected) => {+ const counters = [clause('a', { rangeFunction: 'increase' }), clause('b', { rangeFunction: 'increase' })]+ expect(isExtrapolatable(series('formula'), query(counters, { formula }))).toBe(expected)+ })++ it('ignores clauses the formula does not use', () => {+ const clauses = [+ clause('a', { rangeFunction: 'increase' }),+ clause('b', { rangeFunction: 'increase' }),+ clause('c', { aggregation: 'avg' }),+ ]+ expect(isExtrapolatable(series('formula'), query(clauses, { formula: 'a + b' }))).toBe(true)+ })++ it('does not extrapolate a formula over a gauge', () => {+ const clauses = [clause('a', { rangeFunction: 'increase' }), clause('b', { aggregation: 'avg' })]+ expect(isExtrapolatable(series('formula'), query(clauses, { formula: 'a + b' }))).toBe(false)+ })++ it.each(['promql', 'sql'] as const)('does not extrapolate %s queries', (language) => {+ expect(isExtrapolatable(series('a'), query([clause('a', { rangeFunction: 'rate' })], { language }))).toBe(false)+ })++ it('does not extrapolate without a query', () => {+ expect(isExtrapolatable(series('a'), undefined)).toBe(false)+ })+})++describe('extrapolatePartialValue', () => {+ it('scales the value to the full bucket', () => {+ expect(extrapolatePartialValue(25, 0.25)).toBe(100)+ })++ it('keeps the real value early in the bucket', () => {+ expect(extrapolatePartialValue(2, 0.05)).toBe(2)+ })+})diff --git a/products/metrics/frontend/panels/metricsPartialBucket.ts b/products/metrics/frontend/panels/metricsPartialBucket.tsnew file mode 100644index 000000000000..00b2344a1a5a--- /dev/null+++ b/products/metrics/frontend/panels/metricsPartialBucket.ts@@ -0,0 +1,121 @@+import { dayjs } from 'lib/dayjs'+import { componentsToDayJs, dateStringToComponents, dateStringToDayJs } from 'lib/utils/dateFilters'++import type { MetricsAggregation, MetricsQuery, MetricsQueryClause } from '~/queries/schema/schema-general'++import type { MetricsChartSeries } from '../components/metricsSeries'++export type MetricsPartialBucketQuery = Pick<+ MetricsQuery,+ 'clauses' | 'formula' | 'language' | 'dateRange' | 'interval'+>++/** Below this share of the bucket, scaling up a few samples is mostly noise, so the real value stays. */+export const MIN_EXTRAPOLATION_FRACTION = 0.1++const DEFAULT_DATE_FROM = '-24h'+const MINUTE_MS = 60_000+/** Mirrors `_INTERVAL_LADDER`, `_TARGET_BUCKET_COUNT` and `_MAX_BUCKET_COUNT` in backend/metric_query_runner.py. */+const INTERVAL_LADDER: [string, number][] = [+ ['second_15', 15_000],+ ['second_30', 30_000],+ ['minute', MINUTE_MS],+ ['minute_5', 5 * MINUTE_MS],+ ['minute_15', 15 * MINUTE_MS],+ ['minute_30', 30 * MINUTE_MS],+ ['hour', 60 * MINUTE_MS],+ ['hour_6', 360 * MINUTE_MS],+ ['day', 1440 * MINUTE_MS],+ ['week', 10080 * MINUTE_MS],+]+const TARGET_BUCKET_COUNT = 60+const MAX_BUCKET_COUNT = 500++const COUNTER_FUNCTIONS: ReadonlySet<MetricsAggregation> = new Set(['rate', 'increase'])+const FORMULA_OPERATORS = /[\s()+-]+/++// The backend resolves the range with `exact_timerange`, so a relative date is a rolling window from now.+function resolveDateFrom(dateFrom: string, now: dayjs.Dayjs, timezone: string): dayjs.Dayjs | null {+ const components = dateStringToComponents(dateFrom)+ return components ? componentsToDayJs(components, now, timezone) : dateStringToDayJs(dateFrom, timezone)+}++function resolvedIntervalMs(query: MetricsPartialBucketQuery, now: dayjs.Dayjs, timezone: string): number | null {+ const from = resolveDateFrom(query.dateRange?.date_from ?? DEFAULT_DATE_FROM, now, timezone)+ if (!from) {+ return null+ }+ const span = now.diff(from)+ let index: number+ if (query.interval) {+ index = INTERVAL_LADDER.findIndex(([name]) => name === query.interval)+ if (index === -1) {+ return null+ }+ } else {+ const pick = INTERVAL_LADDER.findIndex(([, step]) => span / step <= TARGET_BUCKET_COUNT)+ index = pick === -1 ? INTERVAL_LADDER.length - 1 : pick+ }+ while (index < INTERVAL_LADDER.length - 1 && span / INTERVAL_LADDER[index][1] > MAX_BUCKET_COUNT) {+ index+++ }+ return INTERVAL_LADDER[index][1]+}++/** How much of the last bucket has elapsed, when the range ends now and that bucket is still in progress. */+export function partialBucketFraction(+ times: string[],+ query: MetricsPartialBucketQuery | undefined,+ timezone: string = 'UTC',+ now: dayjs.Dayjs = dayjs()+): number | null {+ if (!query || query.dateRange?.date_to || times.length === 0) {+ return null+ }+ const length = resolvedIntervalMs(query, now, timezone)+ if (!length) {+ return null+ }+ const starts = times.map((time) => dayjs(time))+ // Closer buckets mean the chart's range differs from the query's, e.g. a dashboard date override.+ if (starts.some((start, i) => i > 0 && start.diff(starts[i - 1]) < length)) {+ return null+ }+ const elapsed = now.diff(starts[starts.length - 1])+ if (elapsed <= 0 || elapsed >= length) {+ return null+ }+ return elapsed / length+}++function isCounterClause(clause: MetricsQueryClause): boolean {+ if (clause.aggregation && COUNTER_FUNCTIONS.has(clause.aggregation)) {+ return true+ }+ // `count` counts reporting series, which does not grow with elapsed time.+ return !!clause.rangeFunction && COUNTER_FUNCTIONS.has(clause.rangeFunction) && clause.aggregation !== 'count'+}++/** Whether a series' partial bucket grows with elapsed time, so scaling it to the full bucket is correct. */+export function isExtrapolatable(series: MetricsChartSeries, query: MetricsPartialBucketQuery | undefined): boolean {+ if (!query || (query.language && query.language !== 'builder')) {+ return false+ }+ if (series.clause === 'formula') {+ // Only a sum or difference of counter aliases scales linearly. A constant term does not grow with elapsed time.+ const operands = (query.formula ?? '').split(FORMULA_OPERATORS).filter(Boolean)+ return (+ operands.length > 0 &&+ operands.every((alias) => {+ const clause = query.clauses.find((c) => c.name === alias)+ return !!clause && isCounterClause(clause)+ })+ )+ }+ const clause = query.clauses.find((c) => c.name === series.clause)+ return !!clause && isCounterClause(clause)+}++export function extrapolatePartialValue(value: number, fraction: number): number {+ return fraction >= MIN_EXTRAPOLATION_FRACTION ? value / fraction : value+}