Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stacked-bar-series-limit.md
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions packages/app/src/ChartUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}

Expand Down
24 changes: 22 additions & 2 deletions packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
getSelectedLineData,
getSeriesDisplayName,
getVisibleLineData,
HARD_LINES_LIMIT,
hasSeriesSelection,
sameActiveClickSeries,
seriesClassName,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, string>;
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.
Expand Down Expand Up @@ -283,8 +290,21 @@ export const MemoChart = memo(function MemoChart({
);

const visibleLineData = useMemo(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — The visible-line cap now scans every bucket × line on each selection change and runs up to three times per data change

Before this PR, getVisibleLineData was a slice. It now loops over graphResults × selected (up to 5,000 loaded series after "load all" × every bucket). It runs in MemoChart whenever selectedSeriesNames changes, for example on each keystroke in the legend table search. It also runs once or twice more in DBTimeChart's countDrawn (DBTimeChart.tsx:503-522), with the same unselected inputs MemoChart then repeats. The existing scan in ChartUtils.tsx:1002 avoids this by visiting only populated cells. Fix: precompute a peak rank per group once per result, as in the previous finding. The cap then becomes a linear walk, and DBTimeChart can pass the drawn set down instead of recomputing it.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

() => 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)', () => {
Expand All @@ -1050,15 +1050,19 @@ 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']);
});

it('caps to HARD_LINES_LIMIT when there is no selection', () => {
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}`,
Expand All @@ -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,
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const scales = (overrides: Partial<typeof baseArgs> = {}) => {
visibleLineData: getVisibleLineData(
args.lineData,
args.selectedSeriesNames,
args.graphResults,
),
axisNumberFormat: undefined,
}),
Expand Down
64 changes: 53 additions & 11 deletions packages/app/src/HDXMultiSeriesTimeChart/chartData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> | undefined,
graphResults: Record<string, unknown>[],
maxLines: number = HARD_LINES_LIMIT,
groupKeyByDataKey?: Map<string, string>,
): 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<string, number>();
for (const ld of selected) {
const group = groupOf(ld);
lineCountByGroup.set(group, (lineCountByGroup.get(group) ?? 0) + 1);
}
const peakByGroup = new Map<string, number>();
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<string>();
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)));
}

/**
Expand Down
31 changes: 31 additions & 0 deletions packages/app/src/__tests__/ChartUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<BuilderChartConfigWithDateRange>({
Expand Down
Loading
Loading