From 2ebfd1a54f47dfbf79b3bcc9978578477f875690 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:48:30 +0000 Subject: [PATCH] feat(app): SLI, error budget and burn rate charts on the SLO page Adds three charts to the SLO page over the window, from the same bucketed query as the numbers above them, so both describe the same moment: the SLI per bucket against the target, with the periods below it shaded; the error budget left, with the overspent part shaded; and the burn rate over the trailing hour, with buckets at or over the fast burn threshold in red. The axis starts where data starts, and clicking a bucket opens its bad events. A definition panel below says what the SLO counts (source, eligible events and filters, good events or the latency rule, objective) and when the stored copy the list uses was last updated. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/components/Slos/SloChart.tsx | 196 ++++++++++++++++++ .../app/src/components/Slos/SloCharts.tsx | 183 ++++++++++++++++ .../app/src/components/Slos/SloDetailPage.tsx | 28 ++- .../src/components/Slos/SloDetailPanels.tsx | 99 ++++++++- .../src/components/Slos/useSloLiveStatus.ts | 5 +- 5 files changed, 505 insertions(+), 6 deletions(-) create mode 100644 packages/app/src/components/Slos/SloChart.tsx create mode 100644 packages/app/src/components/Slos/SloCharts.tsx diff --git a/packages/app/src/components/Slos/SloChart.tsx b/packages/app/src/components/Slos/SloChart.tsx new file mode 100644 index 000000000..0e96e2372 --- /dev/null +++ b/packages/app/src/components/Slos/SloChart.tsx @@ -0,0 +1,196 @@ +import { useMemo } from 'react'; +import { Label, ReferenceArea, ReferenceLine } from 'recharts'; +import type { SloHistoryPoint } from '@hyperdx/common-utils/dist/core/sloStats'; +import { DisplayType, NumberFormat } from '@hyperdx/common-utils/dist/types'; +import { Center, Text } from '@mantine/core'; + +import type { LineData } from '@/ChartUtils'; +import { ChartCard } from '@/components/charts/ChartCard'; +import ChartContainer from '@/components/charts/ChartContainer'; +import ChartEmptyState from '@/components/charts/ChartEmptyState'; +import { MemoChart } from '@/HDXMultiSeriesTimeChart'; + +export const TS_KEY = 'ts'; + +export const PERCENT_FORMAT: NumberFormat = { output: 'percent', mantissa: 2 }; +export const RATE_FORMAT: NumberFormat = { + output: 'number', + mantissa: 2, + unit: 'x', +}; + +// Translucent enough that the series and threshold stay readable on top. +const BAD_FILL_OPACITY = 0.12; + +// A dashed line rather than a shaded area: shading everything below a 99.9% +// target would cover the whole plot and pin the axis at zero. +export function thresholdLine(value: number, label: string, color: string) { + return ( + + + ); +} + +/** + * Runs of consecutive buckets where `isBad` holds, as [start, end] in seconds + * on the chart's time axis. Each bucket covers its start plus one bucket. + */ +export function badPeriods( + points: SloHistoryPoint[], + bucketSeconds: number, + isBad: (point: SloHistoryPoint) => boolean, +): [number, number][] { + const periods: [number, number][] = []; + for (const point of points) { + if (!isBad(point)) continue; + const start = point.ts / 1000; + const last = periods[periods.length - 1]; + if (last != null && start <= last[1]) { + last[1] = start + bucketSeconds; + } else { + periods.push([start, start + bucketSeconds]); + } + } + return periods; +} + +/** Shaded columns for the periods a series spent in a bad state. */ +export function badPeriodAreas(periods: [number, number][], color: string) { + return periods.map(([x1, x2]) => ( + + )); +} + +/** + * Shades everything below zero, where an error budget is overspent, once the + * budget gets there. The lower edge reaches past the lowest value and is + * clipped to the plot, so the shading runs to the bottom of the axis. + */ +export function overspentZone(points: SloHistoryPoint[], color: string) { + const lowest = Math.min(...points.map(p => p.budgetRemaining ?? 0), 0); + if (lowest >= 0) return null; + return ( + + + ); +} + +export function seriesLine(key: string, name: string, color: string): LineData { + return { + dataKey: key, + currentPeriodKey: key, + previousPeriodKey: `${key}__previous`, + displayName: name, + valueColumnName: key, + groupValues: [], + color, + }; +} + +/** + * One SLO history chart. Clicking a bucket reports its start, for the + * bad events of that bucket. + */ +export function SloChart({ + title, + rows, + lines, + dateRange, + granularity, + numberFormat, + referenceLines, + referenceLineValues, + fitYAxisToData, + isLoading, + error, + onBucketClick, + displayType = DisplayType.Line, +}: { + title: string; + rows: Record[]; + lines: LineData[]; + dateRange: [Date, Date]; + granularity: string; + numberFormat: NumberFormat; + referenceLines?: React.ReactNode; + referenceLineValues?: number[]; + fitYAxisToData?: boolean; + isLoading: boolean; + error?: Error | null; + onBucketClick: (bucketStartMs: number) => void; + displayType?: DisplayType; +}) { + const formats = useMemo( + () => new Map(lines.map(line => [line.dataKey, numberFormat])), + [lines, numberFormat], + ); + const chart = error ? ( +
+ + Could not load the history: {error.message} + +
+ ) : !isLoading && rows.length === 0 ? ( + + ) : ( + { + if (payload) onBucketClick(Number(payload.activeLabel) * 1000); + }} + tooltipNumberFormatsByKey={formats} + axisNumberFormat={numberFormat} + referenceLines={referenceLines} + referenceLineValues={referenceLineValues} + showLegend={false} + fitYAxisToData={fitYAxisToData} + compactXAxisLabels + displayType={displayType} + dateRangeEndInclusive={false} + /> + ); + return ( + + {chart} + + ); +} diff --git a/packages/app/src/components/Slos/SloCharts.tsx b/packages/app/src/components/Slos/SloCharts.tsx new file mode 100644 index 000000000..83d41484d --- /dev/null +++ b/packages/app/src/components/Slos/SloCharts.tsx @@ -0,0 +1,183 @@ +import { useMemo } from 'react'; +import { getSloBurnRule } from '@hyperdx/common-utils/dist/core/slo'; +import { computeSloHistory } from '@hyperdx/common-utils/dist/core/sloStats'; +import { convertGranularityToSeconds } from '@hyperdx/common-utils/dist/core/utils'; +import { + getSloBurnWindowMs, + type SloApiResponse, +} from '@hyperdx/common-utils/dist/slo'; +import { DisplayType, type TSource } from '@hyperdx/common-utils/dist/types'; +import { SimpleGrid, Stack, Text } from '@mantine/core'; + +import { useFormatTime } from '@/useFormatTime'; +import { + getChartColorError, + getChartColorInfo, + getChartColorWarning, +} from '@/utils'; + +import { + badPeriodAreas, + badPeriods, + overspentZone, + PERCENT_FORMAT, + RATE_FORMAT, + seriesLine, + SloChart, + thresholdLine, + TS_KEY, +} from './SloChart'; +import { describeBurnWindow, formatSloWindow } from './sloUtils'; +import { useSloHistory } from './useSloLiveStatus'; + +/** "hour" or "30 minutes", for "per ..." titles. */ +const describeBucket = (granularity: string) => + granularity === '1 hour' ? 'hour' : granularity.replace('minute', 'minutes'); + +/** + * SLI, budget burndown and burn rate over the SLO window, from bucketed + * counts queried in the browser like any chart. The window ends at `now`, + * as the numbers above the charts do, so both describe the same moment. + * Clicking a bucket opens its bad events. + */ +export function SloCharts({ + slo, + source, + now, + onBucketSelect, +}: { + slo: SloApiResponse; + source: TSource; + now: Date; + onBucketSelect: (start: Date, end: Date) => void; +}) { + const formatTime = useFormatTime(); + const { config, granularity, buckets, isLoading, error } = useSloHistory( + slo, + source, + now, + ); + const bucketMs = convertGranularityToSeconds(granularity) * 1000; + // The burn chart follows the rule's 1h condition, the one that pages first. + const burn = getSloBurnRule(slo.window)[0]; + const points = useMemo( + () => + computeSloHistory(buckets, { + target: slo.target, + bucketMs, + burnWindowMs: getSloBurnWindowMs(burn.window), + }), + [buckets, slo.target, bucketMs, burn.window], + ); + // Start the axis where data starts: a source younger than the SLO window + // would otherwise squeeze every point against the right edge. + const dateRange = useMemo<[Date, Date]>(() => { + const [start, end] = config.dateRange; + const firstBucket = buckets[0]?.ts ?? start.getTime(); + return [new Date(Math.max(start.getTime(), firstBucket)), end]; + }, [config, buckets]); + + const rows = useMemo( + () => + points.map(p => ({ + [TS_KEY]: p.ts / 1000, + sli: p.sli, + budget: p.budgetRemaining, + // Two series, so buckets at or over the threshold stand out in red. + burn: + p.burnRate != null && p.burnRate < burn.threshold ? p.burnRate : null, + burn_high: + p.burnRate != null && p.burnRate >= burn.threshold + ? p.burnRate + : null, + })), + [points, burn.threshold], + ); + // Chart colors come from CSS variables, so series are built on mount to + // follow the theme, and kept stable for the memoized charts. + const lines = useMemo( + () => ({ + sli: [seriesLine('sli', 'SLI', getChartColorInfo())], + budget: [seriesLine('budget', 'Budget left', getChartColorWarning())], + burn: [ + seriesLine('burn', 'Burn rate', getChartColorInfo()), + seriesLine( + 'burn_high', + 'Burn rate at or over the threshold', + getChartColorError(), + ), + ], + }), + [], + ); + const belowTarget = badPeriods( + points, + bucketMs / 1000, + p => p.sli != null && p.sli * 100 < slo.target, + ); + + const common = { + dateRange, + granularity, + isLoading, + error, + onBucketClick: (start: number) => + onBucketSelect(new Date(start), new Date(start + bucketMs)), + }; + const bucket = describeBucket(granularity); + + return ( + + + The last {formatSloWindow(slo.window)} + {buckets.length > 0 && dateRange[0] > config.dateRange[0] + ? `, with data from ${formatTime(dateRange[0], { format: 'short' })}` + : ''} + . Click a bucket to see its bad events. + + + + {badPeriodAreas(belowTarget, getChartColorError())} + {thresholdLine( + slo.target / 100, + `Target ${slo.target}%`, + getChartColorWarning(), + )} + + } + referenceLineValues={[slo.target / 100]} + fitYAxisToData + /> + + + + + ); +} diff --git a/packages/app/src/components/Slos/SloDetailPage.tsx b/packages/app/src/components/Slos/SloDetailPage.tsx index cdb74ace5..9f04f7b23 100644 --- a/packages/app/src/components/Slos/SloDetailPage.tsx +++ b/packages/app/src/components/Slos/SloDetailPage.tsx @@ -1,4 +1,4 @@ -import { useMemo } from 'react'; +import { useCallback, useMemo } from 'react'; import dynamic from 'next/dynamic'; import Head from 'next/head'; import Link from 'next/link'; @@ -25,6 +25,8 @@ import { withAppNavForSurface } from '@/layout'; import { useSlo, useSlosEnabledGuard } from '@/slo'; import { useSource } from '@/source'; +import { SloCharts } from './SloCharts'; +import { SloDefinitionPanel } from './SloDetailPanels'; import { SloEventsDrawer, type SloEventsRange, @@ -43,11 +45,13 @@ import { function SloDetailView({ slo, source, + now, live, liveError, }: { slo: SloApiResponse; source?: TSource; + now?: Date; live?: SloLiveStatus; liveError?: Error | null; }) { @@ -74,6 +78,11 @@ function SloDetailView({ const [from, to] = getSloEventsRange(slo, range, Date.now()); void setBadEvents({ bad: range, from, to }); }; + const onBucketSelect = useCallback( + (start: Date, end: Date) => + setBadEvents({ bad: 'custom', from: start.getTime(), to: end.getTime() }), + [setBadEvents], + ); const state = live?.state ?? getSloDisplayState(slo); return ( @@ -125,6 +134,15 @@ function SloDetailView({ live={live} liveError={liveError} /> + {source && now && ( + + )} + + ); } diff --git a/packages/app/src/components/Slos/SloDetailPanels.tsx b/packages/app/src/components/Slos/SloDetailPanels.tsx index 272eea8ea..5b38fe8f9 100644 --- a/packages/app/src/components/Slos/SloDetailPanels.tsx +++ b/packages/app/src/components/Slos/SloDetailPanels.tsx @@ -1,10 +1,15 @@ -import { getSloBurnRule } from '@hyperdx/common-utils/dist/core/slo'; +import { formatDistanceToNowStrict } from 'date-fns'; +import { + getSloBurnRule, + getSloGoodSql, +} from '@hyperdx/common-utils/dist/core/slo'; +import { describeFilter } from '@hyperdx/common-utils/dist/filters'; import type { SloApiResponse, SloState, SloStats, } from '@hyperdx/common-utils/dist/slo'; -import { Paper, SimpleGrid, Text } from '@mantine/core'; +import { Code, Group, Paper, SimpleGrid, Stack, Text } from '@mantine/core'; import { budgetColorVar, @@ -104,3 +109,93 @@ export function SloStatsGrid({ ); } + +export function SloDefinitionPanel({ + slo, + sourceName, +}: { + slo: SloApiResponse; + sourceName?: string; +}) { + const { eligible, template, latency } = slo.indicator; + const filters = eligible.filters ?? []; + const status = slo.status; + return ( + + + Definition + + + + + Source:{' '} + + {sourceName ?? slo.source} + + + + Eligible events:{' '} + + {eligible.where ? ( + <> + {eligible.where} ( + {eligible.whereLanguage === 'sql' ? 'SQL' : 'Lucene'}) + + ) : filters.length > 0 ? ( + 'every event matching the filters below' + ) : ( + 'every event in the source' + )} + + {filters.length > 0 && ( + + + Filters: + + {filters.map(filter => ( + {describeFilter(filter)} + ))} + + )} + + + Good events:{' '} + + {template === 'latency' && latency ? ( + <> + {latency.expression} (stored in {latency.unit}) + within {latency.thresholdMs} ms + {!latency.numeric && + (latency.requireDuration + ? '; events without a duration are left out' + : '; events without a duration count as bad')} + . Counted as {getSloGoodSql(slo.indicator)} + + ) : ( + {slo.indicator.good} + )} + + + + Objective:{' '} + + {formatTarget(slo.target)} of eligible events are good over a rolling{' '} + {formatSloWindow(slo.window)} + + {status && ( + + The SLO list uses a copy updated in the background: burn rate{' '} + {formatDistanceToNowStrict(new Date(status.evaluatedAt))} ago + {status.windowEvaluatedAt + ? `, SLI and budget ${formatDistanceToNowStrict(new Date(status.windowEvaluatedAt))} ago (${status.durationMs} ms, ${formatCount(status.rowsRead)} rows read)` + : ''} + {status.state === 'error' && status.lastSuccessAt + ? `. Last successful update ${formatDistanceToNowStrict(new Date(status.lastSuccessAt))} ago` + : ''} + . + + )} + + + ); +} diff --git a/packages/app/src/components/Slos/useSloLiveStatus.ts b/packages/app/src/components/Slos/useSloLiveStatus.ts index b99f553c4..947266b0e 100644 --- a/packages/app/src/components/Slos/useSloLiveStatus.ts +++ b/packages/app/src/components/Slos/useSloLiveStatus.ts @@ -36,9 +36,10 @@ export function useSloNow(): Date { /** * Eligible and good events per bucket over the SLO window that ends at - * `end`. + * `end`. The charts and the numbers above them share this query, so they + * describe the same moment and the page reads the window once. */ -function useSloHistory(slo: SloApiResponse, source: TSource, end: Date) { +export function useSloHistory(slo: SloApiResponse, source: TSource, end: Date) { const granularity = getSloHistoryGranularity(slo.window); const config = useMemo( () =>