From e0168899b596545820693298013fe59d53d016b7 Mon Sep 17 00:00:00 2001 From: Karl Power Date: Thu, 3 Dec 2026 18:00:46 +0100 Subject: [PATCH 1/2] perf(dashboard): limit stacked bar series by bar count Stacked bars draw one rect per series per time bucket, so 100 series over 60 buckets renders 6,000 bars and takes ~4x longer than 25 series. The 100-series draw cap also kept the first series alphabetically and dropped the rest with no notice. - By default, draw as many stacked bar series as fit in 1,500 bars (10-100). An explicit seriesLimit or "load all" lifts it to 100. - Keep the highest-peak series when the draw cap trims, preserving lineData order so stacking and colors don't shift. - Count series past the draw cap in the hidden-series notice; only offer "load all" when it would show more. - Describe the stacked bar default in the Series Limit setting. --- .changeset/stacked-bar-series-limit.md | 5 + packages/app/src/ChartUtils.tsx | 3 + .../src/HDXMultiSeriesTimeChart/MemoChart.tsx | 14 ++- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 77 +++++++++++-- .../__tests__/useChartScales.test.ts | 1 + .../src/HDXMultiSeriesTimeChart/chartData.ts | 46 ++++++-- packages/app/src/__tests__/ChartUtils.test.ts | 38 +++++++ .../components/ChartDisplaySettingsDrawer.tsx | 21 +++- .../components/DBTimeChart/DBTimeChart.tsx | 65 ++++++++++- .../__tests__/DBTimeChart.test.tsx | 102 ++++++++++++++++++ .../__tests__/DBTimeChartExemplarPin.test.tsx | 3 + .../DBTimeChartExemplarTrace.test.tsx | 3 + .../DBTimeChart/useChartToolbarItems.tsx | 14 ++- .../ChartDisplaySettingsDrawer.test.tsx | 28 +++-- .../charts/HiddenSeriesIndicator.tsx | 28 +++-- .../__tests__/HiddenSeriesIndicator.test.tsx | 46 ++++++++ packages/app/src/defaults.ts | 35 +++++- 17 files changed, 482 insertions(+), 47 deletions(-) create mode 100644 .changeset/stacked-bar-series-limit.md diff --git a/.changeset/stacked-bar-series-limit.md b/.changeset/stacked-bar-series-limit.md new file mode 100644 index 0000000000..72f8a94761 --- /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 f889fc753e..31ffb6126e 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 3b6c460f8e..b49aac8c43 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,7 @@ export const MemoChart = memo(function MemoChart({ isClickActive, dateRange, lineData, + maxDrawnSeries = HARD_LINES_LIMIT, referenceLines, referenceLineValues = EMPTY_REFERENCE_LINE_VALUES, annotations, @@ -169,6 +171,8 @@ export const MemoChart = memo(function MemoChart({ isClickActive: ActiveClickPayload | undefined; dateRange: [Date, Date] | Readonly<[Date, Date]>; lineData: LineData[]; + /** Most series drawn; lower for stacked bars (see DBTimeChart). */ + maxDrawnSeries?: number; 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 +287,14 @@ export const MemoChart = memo(function MemoChart({ ); const visibleLineData = useMemo( - () => getVisibleLineData(lineData, selectedSeriesNames), - [lineData, selectedSeriesNames], + () => + getVisibleLineData( + lineData, + selectedSeriesNames, + graphResults, + maxDrawnSeries, + ), + [lineData, selectedSeriesNames, graphResults, maxDrawnSeries], ); // 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 8f2f7a4cff..b763f498b0 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,71 @@ 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('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 190690d0da..1d5cd8d4f3 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 05e74d7e8e..3da9dff739 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts @@ -135,23 +135,47 @@ 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 `maxSeries`. 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, the series with the largest peak in + * `graphResults` are kept (lineData is in color order, not value order), and + * kept series 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[], + maxSeries: number = HARD_LINES_LIMIT, ): LineData[] { - return getSelectedLineData(lineData, selectedSeriesNames).slice( - 0, - HARD_LINES_LIMIT, + const selected = getSelectedLineData(lineData, selectedSeriesNames); + if (selected.length <= maxSeries) { + return selected; + } + // Keyed by currentPeriodKey so a current/previous-period pair ranks together. + 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 peak = Math.abs(value); + if (peak > (peakByGroup.get(ld.currentPeriodKey) ?? -1)) { + peakByGroup.set(ld.currentPeriodKey, peak); + } + } + } + const peakOf = (ld: LineData) => peakByGroup.get(ld.currentPeriodKey) ?? 0; + const keptKeys = new Set( + selected + .map((ld, index) => ({ ld, index })) + .sort((a, b) => peakOf(b.ld) - peakOf(a.ld) || a.index - b.index) + .slice(0, maxSeries) + .map(({ ld }) => ld.dataKey), ); + return selected.filter(ld => keptKeys.has(ld.dataKey)); } /** diff --git a/packages/app/src/__tests__/ChartUtils.test.ts b/packages/app/src/__tests__/ChartUtils.test.ts index e544384c60..a386851bd3 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'; @@ -1337,6 +1341,40 @@ describe('ChartUtils', () => { MAX_RENDERED_TIME_CHART_SERIES, ); }); + + it('uses the given default cap only when no valid limit is set', () => { + expect(resolveRenderedSeriesCap(null, 25)).toBe(25); + expect(resolveRenderedSeriesCap(NaN, 25)).toBe(25); + expect(resolveRenderedSeriesCap(80, 25)).toBe(80); + expect(resolveRenderedSeriesCap(0, 25)).toBe(Number.POSITIVE_INFINITY); + }); + }); + + 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', () => { diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 498fe93ab1..62f77c69b4 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 49f5df5a2c..d2538a877c 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -1,6 +1,9 @@ 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, +} from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { BuilderChartConfigWithDateRange, @@ -27,10 +30,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 +379,7 @@ function DBTimeChartComponent({ lineData, hiddenSeriesCount, renderedSeriesCount, + groupKeyByDataKey, } = useMemo(() => { const defaultResponse = { error: null, @@ -381,6 +391,7 @@ function DBTimeChartComponent({ isSingleValueColumn: true, hiddenSeriesCount: 0, renderedSeriesCount: 0, + groupKeyByDataKey: new Map(), }; if (data == null || !isSuccess) { @@ -464,6 +475,52 @@ function DBTimeChartComponent({ setDisplayType, ]); + // Most series the chart draws. Stacked bars draw one rect per series per + // bucket, so by default they draw only as many as fit the bar budget for the + // time range. A Series Limit or "load all" lifts that to the regular cap. + const maxDrawnSeries = useMemo(() => { + if (displayType !== DisplayType.StackedBar || showAllSeries) { + return HARD_LINES_LIMIT; + } + const bucketCount = Math.ceil( + (dateRange[1].getTime() - dateRange[0].getTime()) / + (convertGranularityToSeconds(granularity) * 1000), + ); + return Math.min( + HARD_LINES_LIMIT, + resolveRenderedSeriesCap( + config.seriesLimit, + getStackedBarSeriesCap(bucketCount), + ), + ); + }, [displayType, showAllSeries, dateRange, granularity, config.seriesLimit]); + + // Loaded series past the draw limit, counted in the same unit as + // renderedSeriesCount. Ignores the legend selection: the hidden-series notice + // describes the query. + const undrawnSeriesCount = useMemo(() => { + const drawnGroups = new Set( + getVisibleLineData(lineData, undefined, graphResults, maxDrawnSeries).map( + line => groupKeyByDataKey.get(line.dataKey) ?? line.dataKey, + ), + ); + return renderedSeriesCount - drawnGroups.size; + }, [ + lineData, + graphResults, + maxDrawnSeries, + groupKeyByDataKey, + renderedSeriesCount, + ]); + + // "Load all" helps when it brings back dropped series or lifts a stacked bar + // chart's draw limit; otherwise clicking it would change nothing. + const noticeLoadAllHandler = + hiddenSeriesCount > 0 || + (undrawnSeriesCount > 0 && maxDrawnSeries < HARD_LINES_LIMIT) + ? 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 +734,11 @@ function DBTimeChartComponent({ exemplarNotice, handleSetDisplayType, hiddenSeriesCount, - loadAllHandler, + loadAllHandler: noticeLoadAllHandler, mvOptimizationData, queriedConfig, renderedSeriesCount, + undrawnSeriesCount, showDateRangeIndicator, showDisplaySwitcher, showMVOptimizationIndicator, @@ -751,6 +809,7 @@ function DBTimeChartComponent({ graphResults={graphResults} isClickActive={activeClickPayload} lineData={lineData} + maxDrawnSeries={maxDrawnSeries} 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 b643dca606..f92cd3ddd9 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,90 @@ 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('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 +570,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 c328f13c93..d09b2fbf33 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 da40c6b5de..8bd74fb41d 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 a5494126cc..1411cf08d4 100644 --- a/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx +++ b/packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx @@ -18,6 +18,7 @@ import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import DisplaySwitcher from '@/components/charts/DisplaySwitcher'; import HiddenSeriesIndicator from '@/components/charts/HiddenSeriesIndicator'; import MVOptimizationIndicator from '@/components/MaterializedViews/MVOptimizationIndicator'; +import { HARD_LINES_LIMIT } from '@/HDXMultiSeriesTimeChart'; import { useMVOptimizationExplanation } from '@/hooks/useMVOptimizationExplanation'; const PROMQL_REDUCE_CARDINALITY_HINT = @@ -34,6 +35,8 @@ 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; // 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 +67,7 @@ export function useChartToolbarItems({ loadAllHandler, mvOptimizationData, renderedSeriesCount, + undrawnSeriesCount, queriedConfig, showDateRangeIndicator, showDisplaySwitcher, @@ -146,12 +150,19 @@ export function useChartToolbarItems({ ); } - if (hiddenSeriesCount > 0) { + if (hiddenSeriesCount + undrawnSeriesCount > 0) { allToolbarItems.push( 0 + ? undefined + : Math.min(HARD_LINES_LIMIT, renderedSeriesCount) + } // 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,7 @@ export function useChartToolbarItems({ queriedConfig, hiddenSeriesCount, renderedSeriesCount, + undrawnSeriesCount, loadAllHandler, ]); } diff --git a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx index a52fc4cdbc..2617b39eee 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 c5ad93859d..d58cc74e94 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 45de750b05..6653b0ee2c 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( Date: Thu, 3 Dec 2026 18:35:40 +0100 Subject: [PATCH 2/2] fix(dashboard): keep a series' lines together under the draw cap The draw cap ranked and counted individual lines, while the notice and seriesLimit count series. On charts with several value columns this split a series' lines, offered "Draw all N" for more series than fit, and turned an explicit seriesLimit into a line cap. - Rank series by peak and keep or drop all of a series' lines together, still bounded by the line cap. - Lift the stacked bar budget for an explicit seriesLimit instead of capping lines to it. - Count drawn and "load all" series in the notice's unit. --- .../src/HDXMultiSeriesTimeChart/MemoChart.tsx | 20 +++-- .../__tests__/HDXMultiSeriesTimeChart.test.ts | 51 ++++++++++++ .../src/HDXMultiSeriesTimeChart/chartData.ts | 54 ++++++++----- packages/app/src/__tests__/ChartUtils.test.ts | 7 -- .../components/DBTimeChart/DBTimeChart.tsx | 80 +++++++++++-------- .../__tests__/DBTimeChart.test.tsx | 43 ++++++++++ .../DBTimeChart/useChartToolbarItems.tsx | 11 +-- packages/app/src/defaults.ts | 7 +- 8 files changed, 199 insertions(+), 74 deletions(-) diff --git a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx index b49aac8c43..1d33202d7f 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx +++ b/packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx @@ -125,7 +125,8 @@ export const MemoChart = memo(function MemoChart({ isClickActive, dateRange, lineData, - maxDrawnSeries = HARD_LINES_LIMIT, + maxDrawnLines = HARD_LINES_LIMIT, + groupKeyByDataKey, referenceLines, referenceLineValues = EMPTY_REFERENCE_LINE_VALUES, annotations, @@ -171,8 +172,10 @@ export const MemoChart = memo(function MemoChart({ isClickActive: ActiveClickPayload | undefined; dateRange: [Date, Date] | Readonly<[Date, Date]>; lineData: LineData[]; - /** Most series drawn; lower for stacked bars (see DBTimeChart). */ - maxDrawnSeries?: number; + /** 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. @@ -292,9 +295,16 @@ export const MemoChart = memo(function MemoChart({ lineData, selectedSeriesNames, graphResults, - maxDrawnSeries, + maxDrawnLines, + groupKeyByDataKey, ), - [lineData, selectedSeriesNames, graphResults, maxDrawnSeries], + [ + 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 b763f498b0..3bf870bed1 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/__tests__/HDXMultiSeriesTimeChart.test.ts @@ -1113,6 +1113,57 @@ describe('getVisibleLineData', () => { 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}`), diff --git a/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts b/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts index 3da9dff739..78c9be25f8 100644 --- a/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts +++ b/packages/app/src/HDXMultiSeriesTimeChart/chartData.ts @@ -136,46 +136,64 @@ export function hasSeriesSelection( /** * The series actually drawn on the chart: the selection (legend isolate, - * checkbox filter, or table search) capped to `maxSeries`. The selection + * 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, the series with the largest peak in - * `graphResults` are kept (lineData is in color order, not value order), and - * kept series stay in lineData order so stacking and colors don't shift. - * Exported for unit testing. + * 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[], - maxSeries: number = HARD_LINES_LIMIT, + maxLines: number = HARD_LINES_LIMIT, + groupKeyByDataKey?: Map, ): LineData[] { const selected = getSelectedLineData(lineData, selectedSeriesNames); - if (selected.length <= maxSeries) { + if (selected.length <= maxLines) { return selected; } - // Keyed by currentPeriodKey so a current/previous-period pair ranks together. + 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(ld.currentPeriodKey) ?? -1)) { - peakByGroup.set(ld.currentPeriodKey, peak); + if (peak > (peakByGroup.get(group) ?? -1)) { + peakByGroup.set(group, peak); } } } - const peakOf = (ld: LineData) => peakByGroup.get(ld.currentPeriodKey) ?? 0; - const keptKeys = new Set( - selected - .map((ld, index) => ({ ld, index })) - .sort((a, b) => peakOf(b.ld) - peakOf(a.ld) || a.index - b.index) - .slice(0, maxSeries) - .map(({ ld }) => ld.dataKey), + // 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), ); - return selected.filter(ld => keptKeys.has(ld.dataKey)); + 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 a386851bd3..30df7c1e8d 100644 --- a/packages/app/src/__tests__/ChartUtils.test.ts +++ b/packages/app/src/__tests__/ChartUtils.test.ts @@ -1341,13 +1341,6 @@ describe('ChartUtils', () => { MAX_RENDERED_TIME_CHART_SERIES, ); }); - - it('uses the given default cap only when no valid limit is set', () => { - expect(resolveRenderedSeriesCap(null, 25)).toBe(25); - expect(resolveRenderedSeriesCap(NaN, 25)).toBe(25); - expect(resolveRenderedSeriesCap(80, 25)).toBe(80); - expect(resolveRenderedSeriesCap(0, 25)).toBe(Number.POSITIVE_INFINITY); - }); }); describe('getStackedBarSeriesCap', () => { diff --git a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx index d2538a877c..a828237bb3 100644 --- a/packages/app/src/components/DBTimeChart/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart/DBTimeChart.tsx @@ -3,6 +3,7 @@ import { differenceInSeconds } from 'date-fns'; import { convertGranularityToSeconds, getAlignedDateRange, + hasPositiveSeriesLimit, } from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { @@ -475,49 +476,56 @@ function DBTimeChartComponent({ setDisplayType, ]); - // Most series the chart draws. Stacked bars draw one rect per series per + // 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. A Series Limit or "load all" lifts that to the regular cap. - const maxDrawnSeries = useMemo(() => { - if (displayType !== DisplayType.StackedBar || showAllSeries) { + // 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; } - const bucketCount = Math.ceil( - (dateRange[1].getTime() - dateRange[0].getTime()) / - (convertGranularityToSeconds(granularity) * 1000), - ); - return Math.min( - HARD_LINES_LIMIT, - resolveRenderedSeriesCap( - config.seriesLimit, - getStackedBarSeriesCap(bucketCount), + return getStackedBarSeriesCap( + Math.ceil( + (dateRange[1].getTime() - dateRange[0].getTime()) / + (convertGranularityToSeconds(granularity) * 1000), ), ); }, [displayType, showAllSeries, dateRange, granularity, config.seriesLimit]); - // Loaded series past the draw limit, counted in the same unit as - // renderedSeriesCount. Ignores the legend selection: the hidden-series notice - // describes the query. - const undrawnSeriesCount = useMemo(() => { - const drawnGroups = new Set( - getVisibleLineData(lineData, undefined, graphResults, maxDrawnSeries).map( - line => groupKeyByDataKey.get(line.dataKey) ?? line.dataKey, - ), - ); - return renderedSeriesCount - drawnGroups.size; - }, [ - lineData, - graphResults, - maxDrawnSeries, - groupKeyByDataKey, - renderedSeriesCount, - ]); + // 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 lifts a stacked bar - // chart's draw limit; otherwise clicking it would change nothing. + // "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 || - (undrawnSeriesCount > 0 && maxDrawnSeries < HARD_LINES_LIMIT) + hiddenSeriesCount > 0 || loadAllDrawCount > drawnSeriesCount ? loadAllHandler : undefined; @@ -739,6 +747,7 @@ function DBTimeChartComponent({ queriedConfig, renderedSeriesCount, undrawnSeriesCount, + loadAllDrawCount, showDateRangeIndicator, showDisplaySwitcher, showMVOptimizationIndicator, @@ -809,7 +818,8 @@ function DBTimeChartComponent({ graphResults={graphResults} isClickActive={activeClickPayload} lineData={lineData} - maxDrawnSeries={maxDrawnSeries} + 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 f92cd3ddd9..d8de3dfe2a 100644 --- a/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx +++ b/packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx @@ -401,6 +401,49 @@ describe('DBTimeChart', () => { ).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( ['data']; @@ -68,6 +69,7 @@ export function useChartToolbarItems({ mvOptimizationData, renderedSeriesCount, undrawnSeriesCount, + loadAllDrawCount, queriedConfig, showDateRangeIndicator, showDisplaySwitcher, @@ -157,11 +159,9 @@ export function useChartToolbarItems({ hiddenSeriesCount={hiddenSeriesCount} renderedSeriesCount={renderedSeriesCount} undrawnSeriesCount={undrawnSeriesCount} - // With nothing dropped, load all only lifts a lower draw limit. + // With nothing dropped, load all only draws more of the loaded series. loadAllDrawCount={ - hiddenSeriesCount > 0 - ? undefined - : Math.min(HARD_LINES_LIMIT, renderedSeriesCount) + hiddenSeriesCount > 0 ? undefined : loadAllDrawCount } // Offered only while still capped AND when load-all would actually // raise the cap (loadAllHandler is undefined otherwise), so the @@ -214,6 +214,7 @@ export function useChartToolbarItems({ hiddenSeriesCount, renderedSeriesCount, undrawnSeriesCount, + loadAllDrawCount, loadAllHandler, ]); } diff --git a/packages/app/src/defaults.ts b/packages/app/src/defaults.ts index ddabd43022..f386c314b4 100644 --- a/packages/app/src/defaults.ts +++ b/packages/app/src/defaults.ts @@ -66,14 +66,13 @@ export function getStackedBarSeriesCap(bucketCount: number): number { /** * Resolve the effective client-side render cap from a tile's `seriesLimit` - * (see SharedChartSettingsSchema): null/undefined → `defaultCap`, exactly 0 → + * (see SharedChartSettingsSchema): null/undefined → the default cap, exactly 0 → * unlimited (Infinity), a positive integer N → N. Anything else (NaN, negative, * non-integer — possible via the Mixed Mongo field or unvalidated form state) - * falls back to `defaultCap` so a bad value can't silently disable the guard. + * falls back to the default cap so a bad value can't silently disable the guard. */ export function resolveRenderedSeriesCap( seriesLimit: number | null | undefined, - defaultCap: number = MAX_RENDERED_TIME_CHART_SERIES, ): number { if (seriesLimit === 0) { return Number.POSITIVE_INFINITY; @@ -83,7 +82,7 @@ export function resolveRenderedSeriesCap( !Number.isInteger(seriesLimit) || seriesLimit < 0 ) { - return defaultCap; + return MAX_RENDERED_TIME_CHART_SERIES; } return seriesLimit; }