diff --git a/.changeset/stacked-bar-series-limit.md b/.changeset/stacked-bar-series-limit.md new file mode 100644 index 000000000..72f8a9476 --- /dev/null +++ b/.changeset/stacked-bar-series-limit.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': patch +--- + +perf: stacked bar charts draw only as many series as fit in 1,500 bars by default, and the hidden-series warning counts series past the draw limit diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx index f889fc753..31ffb6126 100644 --- a/packages/app/src/ChartUtils.tsx +++ b/packages/app/src/ChartUtils.tsx @@ -1126,6 +1126,9 @@ export function formatResponseForTimeChart({ isSingleValueColumn, hiddenSeriesCount, renderedSeriesCount, + // Logical group of each series, for counting other subsets (e.g. the drawn + // ones) in the same unit as renderedSeriesCount. + groupKeyByDataKey, }; } diff --git a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx index 3b6c460f8..1d33202d7 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx @@ -62,6 +62,7 @@ import { getSelectedLineData, getSeriesDisplayName, getVisibleLineData, + HARD_LINES_LIMIT, hasSeriesSelection, sameActiveClickSeries, seriesClassName, @@ -124,6 +125,8 @@ export const MemoChart = memo(function MemoChart({ isClickActive, dateRange, lineData, + maxDrawnLines = HARD_LINES_LIMIT, + groupKeyByDataKey, referenceLines, referenceLineValues = EMPTY_REFERENCE_LINE_VALUES, annotations, @@ -169,6 +172,10 @@ export const MemoChart = memo(function MemoChart({ isClickActive: ActiveClickPayload | undefined; dateRange: [Date, Date] | Readonly<[Date, Date]>; lineData: LineData[]; + /** Most lines drawn; lower for stacked bars (see DBTimeChart). */ + maxDrawnLines?: number; + /** Group of each line, so the draw cap keeps or drops whole groups. */ + groupKeyByDataKey?: Map; referenceLines?: React.ReactNode; // Raw numeric value(s) backing referenceLines (pre-rendered JSX the axis // math can't read), used to size the Y-axis domain around them. @@ -283,8 +290,21 @@ export const MemoChart = memo(function MemoChart({ ); const visibleLineData = useMemo( - () => getVisibleLineData(lineData, selectedSeriesNames), - [lineData, selectedSeriesNames], + () => + getVisibleLineData( + lineData, + selectedSeriesNames, + graphResults, + maxDrawnLines, + groupKeyByDataKey, + ), + [ + lineData, + selectedSeriesNames, + graphResults, + maxDrawnLines, + groupKeyByDataKey, + ], ); // Series for the pinned tooltip's drill-down list: selection applied but NOT diff --git a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts index 8f2f7a4cf..3bf870bed 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -1036,12 +1036,12 @@ describe('getVisibleLineData', () => { it('returns all series (up to the limit) when there is no selection', () => { const lineData = [makeLine('a'), makeLine('b'), makeLine('c')]; - expect(getVisibleLineData(lineData, undefined).map(l => l.dataKey)).toEqual( - ['a', 'b', 'c'], - ); - expect(getVisibleLineData(lineData, new Set()).map(l => l.dataKey)).toEqual( - ['a', 'b', 'c'], - ); + expect( + getVisibleLineData(lineData, undefined, []).map(l => l.dataKey), + ).toEqual(['a', 'b', 'c']); + expect( + getVisibleLineData(lineData, new Set(), []).map(l => l.dataKey), + ).toEqual(['a', 'b', 'c']); }); it('keeps only the selected series (matched by display name)', () => { @@ -1050,7 +1050,11 @@ describe('getVisibleLineData', () => { makeLine('b', 'Beta'), makeLine('c', 'Gamma'), ]; - const visible = getVisibleLineData(lineData, new Set(['Alpha', 'Gamma'])); + const visible = getVisibleLineData( + lineData, + new Set(['Alpha', 'Gamma']), + [], + ); expect(visible.map(l => l.dataKey)).toEqual(['a', 'c']); }); @@ -1058,7 +1062,7 @@ describe('getVisibleLineData', () => { const lineData = Array.from({ length: HARD_LINES_LIMIT + 5 }, (_, i) => makeLine(`series-${i}`), ); - const visible = getVisibleLineData(lineData, undefined); + const visible = getVisibleLineData(lineData, undefined, []); expect(visible).toHaveLength(HARD_LINES_LIMIT); expect(visible.map(l => l.dataKey)).not.toContain( `series-${HARD_LINES_LIMIT + 2}`, @@ -1074,18 +1078,122 @@ describe('getVisibleLineData', () => { // in the legend table). const overLimitName = `series-${HARD_LINES_LIMIT + 2}`; expect( - getVisibleLineData(lineData, new Set([overLimitName])).map( + getVisibleLineData(lineData, new Set([overLimitName]), []).map( l => l.dataKey, ), ).toEqual([overLimitName]); }); + it('keeps the series with the largest peaks over the cap, in lineData order', () => { + const lineData = Array.from({ length: HARD_LINES_LIMIT + 2 }, (_, i) => + makeLine(`series-${i}`), + ); + // The last two series hold the largest values; the first two the smallest. + const row = Object.fromEntries( + lineData.map((l, i) => [l.dataKey, i < 2 ? 1 : i + 10]), + ); + const visible = getVisibleLineData(lineData, undefined, [row]); + + expect(visible).toHaveLength(HARD_LINES_LIMIT); + expect(visible.map(l => l.dataKey)).not.toContain('series-0'); + expect(visible.map(l => l.dataKey)).not.toContain('series-1'); + expect(visible.map(l => l.dataKey)).toEqual( + lineData.slice(2).map(l => l.dataKey), + ); + }); + + it('caps to a lower limit when given one', () => { + const lineData = [makeLine('a'), makeLine('b'), makeLine('c')]; + const visible = getVisibleLineData( + lineData, + undefined, + [{ a: 1, b: 3, c: 2 }], + 2, + ); + expect(visible.map(l => l.dataKey)).toEqual(['b', 'c']); + }); + + it("keeps or drops a group's lines together", () => { + // Two value columns per group: avg and max lines share a group key. + const lineData = ['a', 'b', 'c'].flatMap(g => [ + makeLine(`avg · ${g}`), + makeLine(`max · ${g}`), + ]); + const groupKeyByDataKey = new Map( + lineData.map(l => [l.dataKey, l.dataKey.slice(-1)]), + ); + const visible = getVisibleLineData( + lineData, + undefined, + [ + { + 'avg · a': 50, + 'max · a': 50, + 'avg · b': 1, + 'max · b': 1, + 'avg · c': 1, + 'max · c': 100, + }, + ], + 4, + groupKeyByDataKey, + ); + // c ranks first on its max line alone, and its small avg line comes along. + expect(visible.map(l => l.dataKey)).toEqual([ + 'avg · a', + 'max · a', + 'avg · c', + 'max · c', + ]); + }); + + it('keeps the top group even when it alone exceeds the cap', () => { + const lineData = [makeLine('avg · a'), makeLine('max · a'), makeLine('b')]; + const groupKeyByDataKey = new Map([ + ['avg · a', 'a'], + ['max · a', 'a'], + ['b', 'b'], + ]); + const visible = getVisibleLineData( + lineData, + undefined, + [{ 'avg · a': 5, 'max · a': 5, b: 1 }], + 1, + groupKeyByDataKey, + ); + expect(visible.map(l => l.dataKey)).toEqual(['avg · a', 'max · a']); + }); + + it('ranks a current/previous-period pair by their shared peak', () => { + const current = Array.from({ length: HARD_LINES_LIMIT }, (_, i) => + makeLine(`series-${i}`), + ); + const previous = current.map(l => ({ + ...l, + dataKey: l.previousPeriodKey, + isDashed: true, + })); + const lineData = current.flatMap((l, i) => [l, previous[i]]); + // Only the previous-period line of series-99 has data; it must pull its + // current-period line in with it. + const visible = getVisibleLineData(lineData, undefined, [ + { [previous[HARD_LINES_LIMIT - 1].dataKey]: 5 }, + ]); + + expect(visible.map(l => l.dataKey)).toEqual( + expect.arrayContaining([ + `series-${HARD_LINES_LIMIT - 1}`, + previous[HARD_LINES_LIMIT - 1].dataKey, + ]), + ); + }); + it('still caps an oversized manual selection to HARD_LINES_LIMIT', () => { const lineData = Array.from({ length: HARD_LINES_LIMIT + 20 }, (_, i) => makeLine(`series-${i}`), ); const everySeries = new Set(lineData.map(l => l.dataKey)); - expect(getVisibleLineData(lineData, everySeries)).toHaveLength( + expect(getVisibleLineData(lineData, everySeries, [])).toHaveLength( HARD_LINES_LIMIT, ); }); diff --git a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts index 190690d0d..1d5cd8d4f 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts @@ -57,6 +57,7 @@ const scales = (overrides: Partial = {}) => { visibleLineData: getVisibleLineData( args.lineData, args.selectedSeriesNames, + args.graphResults, ), axisNumberFormat: undefined, }), diff --git a/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts b/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts index 05e74d7e8..78c9be25f 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts @@ -135,23 +135,65 @@ export function hasSeriesSelection( } /** - * The series actually drawn on the chart. Without a selection, the first - * HARD_LINES_LIMIT of lineData. With a selection (legend isolate, checkbox - * filter, or table search), the selection is applied FIRST and then capped, so - * an explicitly chosen series always draws even if it ranks beyond the limit. - * Applying the cap first would slice out a chosen low-ranked series, leaving an - * empty chart while its stats still show in the legend table. The rendered - * lines and the drill-down click payload both derive from this same set so they - * never diverge. Exported for unit testing. + * The series actually drawn on the chart: the selection (legend isolate, + * checkbox filter, or table search) capped to `maxLines` lines. The selection + * is applied FIRST, so an explicitly chosen series always draws even if it + * ranks beyond the limit. Applying the cap first would slice out a chosen + * low-ranked series, leaving an empty chart while its stats still show in the + * legend table. + * + * Over the cap, whole groups are kept, largest peak in `graphResults` first, so + * a group's lines (one per value column, plus previous-period lines) are drawn + * or dropped together. `groupKeyByDataKey` maps each line to its group (see + * formatResponseForTimeChart); lines missing from it group by + * currentPeriodKey. Kept lines stay in lineData order so stacking and colors + * don't shift. Exported for unit testing. */ export function getVisibleLineData( lineData: LineData[], selectedSeriesNames: Set | undefined, + graphResults: Record[], + maxLines: number = HARD_LINES_LIMIT, + groupKeyByDataKey?: Map, ): LineData[] { - return getSelectedLineData(lineData, selectedSeriesNames).slice( - 0, - HARD_LINES_LIMIT, + const selected = getSelectedLineData(lineData, selectedSeriesNames); + if (selected.length <= maxLines) { + return selected; + } + const groupOf = (ld: LineData) => + groupKeyByDataKey?.get(ld.dataKey) ?? ld.currentPeriodKey; + const lineCountByGroup = new Map(); + for (const ld of selected) { + const group = groupOf(ld); + lineCountByGroup.set(group, (lineCountByGroup.get(group) ?? 0) + 1); + } + const peakByGroup = new Map(); + for (const row of graphResults) { + for (const ld of selected) { + const value = row[ld.dataKey]; + if (typeof value !== 'number' || !Number.isFinite(value)) continue; + const group = groupOf(ld); + const peak = Math.abs(value); + if (peak > (peakByGroup.get(group) ?? -1)) { + peakByGroup.set(group, peak); + } + } + } + // Map keys iterate in first-seen order, so the sort's tiebreak is lineData + // order. + const ranked = Array.from(lineCountByGroup.keys()).sort( + (a, b) => (peakByGroup.get(b) ?? 0) - (peakByGroup.get(a) ?? 0), ); + const keptGroups = new Set(); + let lineCount = 0; + for (const group of ranked) { + const groupLines = lineCountByGroup.get(group) ?? 0; + // Always keep the top group, even if it alone exceeds the cap. + if (keptGroups.size > 0 && lineCount + groupLines > maxLines) break; + keptGroups.add(group); + lineCount += groupLines; + } + return selected.filter(ld => keptGroups.has(groupOf(ld))); } /** diff --git a/packages/app/src/__tests__/ChartUtils.test.ts b/packages/app/src/__tests__/ChartUtils.test.ts index e544384c6..30df7c1e8 100644 --- a/packages/app/src/__tests__/ChartUtils.test.ts +++ b/packages/app/src/__tests__/ChartUtils.test.ts @@ -26,7 +26,11 @@ import { type LineData, } from '@/ChartUtils'; import { + DEFAULT_SERIES_LIMIT, + getStackedBarSeriesCap, + MAX_DEFAULT_STACKED_BARS, MAX_RENDERED_TIME_CHART_SERIES, + MIN_DEFAULT_STACKED_BAR_SERIES, resolveRenderedSeriesCap, } from '@/defaults'; import { COLORS, getColorFromCSSToken } from '@/utils'; @@ -1339,6 +1343,33 @@ describe('ChartUtils', () => { }); }); + describe('getStackedBarSeriesCap', () => { + it('fits the series into the bar budget for the bucket count', () => { + expect(getStackedBarSeriesCap(60)).toBe( + Math.floor(MAX_DEFAULT_STACKED_BARS / 60), + ); + }); + + it('never exceeds the draw cap with few buckets', () => { + expect(getStackedBarSeriesCap(1)).toBe(DEFAULT_SERIES_LIMIT); + }); + + it('keeps a minimum number of series with many buckets', () => { + expect(getStackedBarSeriesCap(100_000)).toBe( + MIN_DEFAULT_STACKED_BAR_SERIES, + ); + }); + + it('falls back to the draw cap for an invalid bucket count', () => { + expect(getStackedBarSeriesCap(NaN)).toBe(DEFAULT_SERIES_LIMIT); + expect(getStackedBarSeriesCap(0)).toBe(DEFAULT_SERIES_LIMIT); + // A zero-second granularity divides to Infinity. + expect(getStackedBarSeriesCap(Number.POSITIVE_INFINITY)).toBe( + DEFAULT_SERIES_LIMIT, + ); + }); + }); + describe('convertToTimeChartConfig', () => { it('should set granularity when granularity is auto', () => { const config = fromPartial({ diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 498fe93ab..62f77c69b 100644 --- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx +++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx @@ -34,7 +34,10 @@ import { import { IconHelpCircle } from '@tabler/icons-react'; import { shouldFillNullsWithZero } from '@/ChartUtils'; -import { MAX_RENDERED_TIME_CHART_SERIES } from '@/defaults'; +import { + MAX_DEFAULT_STACKED_BARS, + MAX_RENDERED_TIME_CHART_SERIES, +} from '@/defaults'; import { FormatTime } from '@/useFormatTime'; import { HeatmapScaleControl } from './DBHeatmapChart/HeatmapScaleControl'; @@ -271,6 +274,12 @@ export default function ChartDisplaySettingsDrawer({ const showSeriesLimit = isTimeChart; const isClientSideSeriesLimit = showSeriesLimit && (configType === 'sql' || configType === 'promql'); + // Stacked bars default to a bar budget rather than a fixed series count (see + // getStackedBarSeriesCap). + const isStackedBar = displayType === DisplayType.StackedBar; + const seriesLimitDefault = isStackedBar + ? `as many as fit in ${MAX_DEFAULT_STACKED_BARS.toLocaleString()} bars` + : `${MAX_RENDERED_TIME_CHART_SERIES}`; const isDistributionHeatmap = displayType === DisplayType.Heatmap && heatmapMode === 'distribution'; @@ -446,10 +455,14 @@ export default function ChartDisplaySettingsDrawer({ label="Series Limit" description={ isClientSideSeriesLimit - ? `Maximum number of series rendered, keeping those with the largest values. Leave empty for the default (${MAX_RENDERED_TIME_CHART_SERIES}); set 0 for unlimited.` - : `Maximum number of series fetched for a group-by chart, keeping those with the largest values. Leave empty for the default (${MAX_RENDERED_TIME_CHART_SERIES}); set 0 for unlimited.` + ? `Maximum number of series rendered, keeping those with the largest values. Leave empty for the default (${seriesLimitDefault}); set 0 for unlimited.` + : `Maximum number of series fetched for a group-by chart, keeping those with the largest values. Leave empty for the default (${seriesLimitDefault}); set 0 for unlimited.` + } + placeholder={ + isStackedBar + ? 'Default (auto)' + : `Default (${MAX_RENDERED_TIME_CHART_SERIES})` } - placeholder={`Default (${MAX_RENDERED_TIME_CHART_SERIES})`} min={0} allowDecimal={false} value={value ?? ''} diff --git a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx index 49f5df5a2..a828237bb 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -1,6 +1,10 @@ import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'; import { differenceInSeconds } from 'date-fns'; -import { getAlignedDateRange } from '@hyperdx/common-utils/dist/core/utils'; +import { + convertGranularityToSeconds, + getAlignedDateRange, + hasPositiveSeriesLimit, +} from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { BuilderChartConfigWithDateRange, @@ -27,10 +31,16 @@ import ChartErrorState, { import { ExemplarHoverCard } from '@/components/Exemplars'; import { DEFAULT_MAX_EXEMPLARS, + getStackedBarSeriesCap, MAX_LOADABLE_TIME_CHART_SERIES, resolveRenderedSeriesCap, } from '@/defaults'; -import { type ActiveClickPayload, MemoChart } from '@/HDXMultiSeriesTimeChart'; +import { + type ActiveClickPayload, + getVisibleLineData, + HARD_LINES_LIMIT, + MemoChart, +} from '@/HDXMultiSeriesTimeChart'; import { getMinGranularitySeconds, useQueriedChartConfig, @@ -370,6 +380,7 @@ function DBTimeChartComponent({ lineData, hiddenSeriesCount, renderedSeriesCount, + groupKeyByDataKey, } = useMemo(() => { const defaultResponse = { error: null, @@ -381,6 +392,7 @@ function DBTimeChartComponent({ isSingleValueColumn: true, hiddenSeriesCount: 0, renderedSeriesCount: 0, + groupKeyByDataKey: new Map(), }; if (data == null || !isSuccess) { @@ -464,6 +476,59 @@ function DBTimeChartComponent({ setDisplayType, ]); + // Most lines the chart draws. Stacked bars draw one rect per line per + // bucket, so by default they draw only as many as fit the bar budget for the + // time range. An explicit Series Limit (which already caps the series + // loaded) or "load all" lifts that to the regular cap. + const maxDrawnLines = useMemo(() => { + if ( + displayType !== DisplayType.StackedBar || + showAllSeries || + config.seriesLimit === 0 || + hasPositiveSeriesLimit(config.seriesLimit) + ) { + return HARD_LINES_LIMIT; + } + return getStackedBarSeriesCap( + Math.ceil( + (dateRange[1].getTime() - dateRange[0].getTime()) / + (convertGranularityToSeconds(granularity) * 1000), + ), + ); + }, [displayType, showAllSeries, dateRange, granularity, config.seriesLimit]); + + // Series drawn now, and once "load all" lifts a lower stacked bar limit, in + // the same unit as renderedSeriesCount. Ignores the legend selection: the + // hidden-series notice describes the query. + const { drawnSeriesCount, loadAllDrawCount } = useMemo(() => { + const countDrawn = (maxLines: number) => + new Set( + getVisibleLineData( + lineData, + undefined, + graphResults, + maxLines, + groupKeyByDataKey, + ).map( + line => groupKeyByDataKey.get(line.dataKey) ?? line.currentPeriodKey, + ), + ).size; + const drawn = countDrawn(maxDrawnLines); + return { + drawnSeriesCount: drawn, + loadAllDrawCount: + maxDrawnLines < HARD_LINES_LIMIT ? countDrawn(HARD_LINES_LIMIT) : drawn, + }; + }, [lineData, graphResults, maxDrawnLines, groupKeyByDataKey]); + const undrawnSeriesCount = renderedSeriesCount - drawnSeriesCount; + + // "Load all" helps when it brings back dropped series or draws more of the + // loaded ones; otherwise clicking it would change nothing. + const noticeLoadAllHandler = + hiddenSeriesCount > 0 || loadAllDrawCount > drawnSeriesCount + ? loadAllHandler + : undefined; + // The chart replaces its whole subtree — marker layer and exemplar card // included — for the loading, error and empty states. Derived here from the // same booleans the branches below use, so the two cannot drift. @@ -677,10 +742,12 @@ function DBTimeChartComponent({ exemplarNotice, handleSetDisplayType, hiddenSeriesCount, - loadAllHandler, + loadAllHandler: noticeLoadAllHandler, mvOptimizationData, queriedConfig, renderedSeriesCount, + undrawnSeriesCount, + loadAllDrawCount, showDateRangeIndicator, showDisplaySwitcher, showMVOptimizationIndicator, @@ -751,6 +818,8 @@ function DBTimeChartComponent({ graphResults={graphResults} isClickActive={activeClickPayload} lineData={lineData} + maxDrawnLines={maxDrawnLines} + groupKeyByDataKey={groupKeyByDataKey} isLoading={isLoadingOrPlaceholder} logReferenceTimestamp={logReferenceTimestamp} axisNumberFormat={axisNumberFormat} diff --git a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx index b643dca60..d8de3dfe2 100644 --- a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx +++ b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx @@ -14,6 +14,7 @@ import { } from '@/components/DBTimeChart'; import MVOptimizationIndicator from '@/components/MaterializedViews/MVOptimizationIndicator'; import { MAX_LOADABLE_TIME_CHART_SERIES } from '@/defaults'; +import { HARD_LINES_LIMIT } from '@/HDXMultiSeriesTimeChart'; import { getMinGranularitySeconds, useQueriedChartConfig, @@ -334,6 +335,133 @@ describe('DBTimeChart', () => { }, ); + describe('stacked bar draw limit', () => { + // Over the 100-series draw limit but under the 250-series load limit, so + // nothing is dropped and every warning comes from the draw limit. + const GROUP_COUNT = 120; + const groupByConfig = { ...baseTestConfig, groupBy: 'group' }; + const hoverWarning = async () => { + const icon = document.querySelector('.tabler-icon-alert-triangle'); + expect(icon).not.toBeNull(); + await userEvent.hover(icon!); + }; + + beforeEach(() => { + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: Array.from({ length: GROUP_COUNT }, (_, i) => ({ + timestamp: 1704067200, + value: i + 1, + group: `g${i}`, + })), + meta: [ + { name: 'timestamp', type: 'DateTime' }, + { name: 'value', type: 'UInt64' }, + { name: 'group', type: 'String' }, + ], + rows: GROUP_COUNT, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); + }); + + it('draws fewer series on a stacked bar chart and offers to draw more', () => { + renderWithMantine( + , + ); + + // Every series is already loaded, so the action draws more, not loads. + expect( + screen.getByRole('button', { name: 'Draw the top 100 series' }), + ).toBeInTheDocument(); + }); + + it('draws the regular limit on a line chart, without load all', async () => { + renderWithMantine( + , + ); + + // Every series is already loaded, so loading all would change nothing. + expect( + screen.queryByRole('button', { name: /load all .* series/i }), + ).not.toBeInTheDocument(); + await hoverWarning(); + expect( + await screen.findByText(/top 100 by peak value/), + ).toBeInTheDocument(); + }); + + it('counts series, not lines, when a chart has several value columns', async () => { + const SERIES = 60; + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: Array.from({ length: SERIES }, (_, i) => ({ + timestamp: 1704067200, + count: i + 1, + avg: i + 1, + group: `g${i}`, + })), + meta: [ + { name: 'timestamp', type: 'DateTime' }, + { name: 'count', type: 'UInt64' }, + { name: 'avg', type: 'Float64' }, + { name: 'group', type: 'String' }, + ], + rows: SERIES, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); + renderWithMantine( + , + ); + + // Two lines per series, so the 100-line cap fits 50 of the 60 series. + const button = screen.getByRole('button', { + name: 'Draw the top 50 series', + }); + await userEvent.hover(button); + // 48 half-hour buckets fit 31 lines, so 15 whole series. + expect( + await screen.findByText(/showing the top 15 by peak value/), + ).toBeInTheDocument(); + }); + + it('lets an explicit seriesLimit lift the stacked bar draw limit', async () => { + renderWithMantine( + , + ); + + await hoverWarning(); + expect( + await screen.findByText(/top 100 by peak value/), + ).toBeInTheDocument(); + }); + }); + describe('load-all series escape hatch', () => { // A high-cardinality group-by response: MAX_RENDERED_TIME_CHART_SERIES (250) // default cap + 50 extra groups, so 50 series are hidden and the @@ -485,6 +613,23 @@ describe('DBTimeChart', () => { ).not.toBeInTheDocument(); }); + it('warns about series past the draw cap when none are dropped', async () => { + renderWithMantine( + , + ); + + const warningIcon = document.querySelector('.tabler-icon-alert-triangle'); + expect(warningIcon).not.toBeNull(); + await userEvent.hover(warningIcon!); + expect( + await screen.findByText( + new RegExp( + `returned ${GROUP_COUNT} series\\. ${GROUP_COUNT - HARD_LINES_LIMIT} low-value .* top ${HARD_LINES_LIMIT} by peak`, + ), + ), + ).toBeInTheDocument(); + }); + it('goes passive (non-clickable) after load-all when the result still exceeds the load-all bound', async () => { // A result larger than MAX_LOADABLE_TIME_CHART_SERIES (5000): after // clicking "load all", the cap is lifted to the bound but series remain diff --git a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarPin.test.tsx b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarPin.test.tsx index c328f13c9..d09b2fbf3 100644 --- a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarPin.test.tsx +++ b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarPin.test.tsx @@ -27,6 +27,9 @@ const mockUseQueriedChartConfig = jest.fn(); // zone, so the reference has to be deferred into the call itself. jest.mock('@/HDXMultiSeriesTimeChart', () => ({ __esModule: true, + ...jest.requireActual( + '@/HDXMultiSeriesTimeChart', + ), MemoChart: (props: ChartProps) => mockChart(props), })); diff --git a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarTrace.test.tsx b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarTrace.test.tsx index da40c6b5d..8bd74fb41 100644 --- a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarTrace.test.tsx +++ b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChartExemplarTrace.test.tsx @@ -28,6 +28,9 @@ const mockRouterPush = jest.fn(); jest.mock('@/HDXMultiSeriesTimeChart', () => ({ __esModule: true, + ...jest.requireActual( + '@/HDXMultiSeriesTimeChart', + ), MemoChart: (props: ChartProps) => mockChart(props), })); diff --git a/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx b/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx index a5494126c..907c8574d 100644 --- a/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx +++ b/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx @@ -34,6 +34,10 @@ type UseChartToolbarItemsArgs = { /** Render every series, bypassing the cap; undefined when that is a no-op. */ loadAllHandler: (() => void) | undefined; renderedSeriesCount: number; + /** Rendered series past the chart's draw cap. */ + undrawnSeriesCount: number; + /** Series drawn once "load all" lifts a lower draw cap. */ + loadAllDrawCount: number; // Derived from the hook rather than hand-copied, so a change to its shape is // a type error here instead of a field that quietly stops being read. mvOptimizationData: ReturnType['data']; @@ -64,6 +68,8 @@ export function useChartToolbarItems({ loadAllHandler, mvOptimizationData, renderedSeriesCount, + undrawnSeriesCount, + loadAllDrawCount, queriedConfig, showDateRangeIndicator, showDisplaySwitcher, @@ -146,12 +152,17 @@ export function useChartToolbarItems({ ); } - if (hiddenSeriesCount > 0) { + if (hiddenSeriesCount + undrawnSeriesCount > 0) { allToolbarItems.push( 0 ? undefined : loadAllDrawCount + } // Offered only while still capped AND when load-all would actually // raise the cap (loadAllHandler is undefined otherwise), so the // notice never advertises a no-op click. @@ -202,6 +213,8 @@ export function useChartToolbarItems({ queriedConfig, hiddenSeriesCount, renderedSeriesCount, + undrawnSeriesCount, + loadAllDrawCount, loadAllHandler, ]); } diff --git a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx index a52fc4cdb..2617b39ee 100644 --- a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx +++ b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx @@ -445,6 +445,22 @@ describe('ChartDisplaySettingsDrawer', () => { ); }); + it('describes the bar-budget default for stacked bar charts', () => { + renderWithMantine( + , + ); + + expect( + screen.getByRole('textbox', { name: /series limit/i }), + ).toHaveAttribute('placeholder', 'Default (auto)'); + expect( + screen.getByText(/as many as fit in 1,500 bars/), + ).toBeInTheDocument(); + }); + it('does not show the Series Limit input for table charts', () => { renderWithMantine( { describe('PromQL (client render cap)', () => { const promqlProps = { ...baseProps, configType: 'promql' as const }; - it.each([DisplayType.Line, DisplayType.StackedBar])( + it.each([ + [DisplayType.Line, `Default (${MAX_RENDERED_TIME_CHART_SERIES})`], + [DisplayType.StackedBar, 'Default (auto)'], + ])( 'shows the Series Limit input for PromQL %s charts', - displayType => { + (displayType, placeholder) => { renderWithMantine( { ); const input = screen.getByRole('textbox', { name: /series limit/i }); - expect(input).toHaveAttribute( - 'placeholder', - `Default (${MAX_RENDERED_TIME_CHART_SERIES})`, - ); + expect(input).toHaveAttribute('placeholder', placeholder); }, ); diff --git a/packages/app/src/components/charts/HiddenSeriesIndicator.tsx b/packages/app/src/components/charts/HiddenSeriesIndicator.tsx index c5ad93859..d58cc74e9 100644 --- a/packages/app/src/components/charts/HiddenSeriesIndicator.tsx +++ b/packages/app/src/components/charts/HiddenSeriesIndicator.tsx @@ -4,8 +4,12 @@ import { IconAlertTriangle } from '@tabler/icons-react'; interface HiddenSeriesIndicatorProps { hiddenSeriesCount: number; renderedSeriesCount: number; + /** Rendered series past the chart's draw cap: loaded but not drawn. */ + undrawnSeriesCount?: number; /** Render every series, bypassing the cap. Omit to keep the notice passive. */ onLoadAll?: () => void; + /** Set when every series is loaded and `onLoadAll` only draws more, up to this many. */ + loadAllDrawCount?: number; /** How to reduce cardinality when "load all" isn't offered. Defaults to SQL advice. */ reduceCardinalityHint?: string; } @@ -15,26 +19,36 @@ const DEFAULT_REDUCE_CARDINALITY_HINT = /** * Warns that the chart returned more series than the client renders. The - * transform caps series to protect memory; this surfaces the dropped ones and, - * when `onLoadAll` is provided, lets the user render all of them anyway. + * transform caps series to protect memory and the chart caps how many it draws; + * this surfaces both and, when `onLoadAll` is provided, lets the user load all + * of them anyway. */ export default function HiddenSeriesIndicator({ hiddenSeriesCount, renderedSeriesCount, + undrawnSeriesCount = 0, onLoadAll, + loadAllDrawCount, reduceCardinalityHint = DEFAULT_REDUCE_CARDINALITY_HINT, }: HiddenSeriesIndicatorProps) { - if (hiddenSeriesCount <= 0) { + if (hiddenSeriesCount + undrawnSeriesCount <= 0) { return null; } const total = renderedSeriesCount + hiddenSeriesCount; + const shown = renderedSeriesCount - undrawnSeriesCount; + const loadAllAction = + loadAllDrawCount == null + ? `Load all ${total.toLocaleString()}` + : loadAllDrawCount >= renderedSeriesCount + ? `Draw all ${loadAllDrawCount.toLocaleString()}` + : `Draw the top ${loadAllDrawCount.toLocaleString()}`; const label = `This query returned ${total.toLocaleString()} series. ` + - `${hiddenSeriesCount.toLocaleString()} low-value series were hidden to keep the page responsive; ` + - `showing the top ${renderedSeriesCount.toLocaleString()} by peak value. ` + + `${(total - shown).toLocaleString()} low-value series were hidden to keep the page responsive; ` + + `showing the top ${shown.toLocaleString()} by peak value. ` + (onLoadAll - ? `Click to load all ${total.toLocaleString()} (may be slow).` + ? `Click to ${loadAllAction.toLowerCase()} (may be slow).` : reduceCardinalityHint); const icon = ( @@ -51,7 +65,7 @@ export default function HiddenSeriesIndicator({ // Toolbar sits in react-grid-layout's drag subtree; stop propagation // (as ChartContainer does) so a click doesn't start a tile drag. onMouseDown={e => e.stopPropagation()} - aria-label={`Load all ${total.toLocaleString()} series`} + aria-label={`${loadAllAction} series`} > {icon} diff --git a/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx b/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx index 45de750b0..6653b0ee2 100644 --- a/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx +++ b/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx @@ -43,6 +43,36 @@ describe('HiddenSeriesIndicator', () => { expect(onLoadAll).toHaveBeenCalledTimes(1); }); + it('offers to draw more instead of load all when everything is loaded', () => { + renderWithMantine( + , + ); + expect( + screen.getByRole('button', { name: 'Draw the top 100 series' }), + ).toBeInTheDocument(); + }); + + it('offers to draw all when every loaded series fits the draw limit', () => { + renderWithMantine( + , + ); + expect( + screen.getByRole('button', { name: 'Draw all 80 series' }), + ).toBeInTheDocument(); + }); + describe('passive notice copy', () => { const hoverIcon = async (container: HTMLElement) => { const icon = container.querySelector('svg'); @@ -61,6 +91,22 @@ describe('HiddenSeriesIndicator', () => { expect(await screen.findByText(/stricter GROUP BY/i)).toBeInTheDocument(); }); + it('counts series past the draw cap as hidden', async () => { + const { container } = renderWithMantine( + , + ); + await hoverIcon(container); + expect( + await screen.findByText( + /returned 121 series\. 21 low-value series were hidden .* showing the top 100 by peak value/, + ), + ).toBeInTheDocument(); + }); + it('uses reduceCardinalityHint in place of the SQL advice', async () => { const { container } = renderWithMantine(