From c892af313bcdf9e8e504cd2404a7605458c14b2d Mon Sep 17 00:00:00 2001 From: Karl Power Date: Mon, 5 Oct 2026 17:00:20 +0200 Subject: [PATCH 1/2] feat: Support series limit on PromQL time charts --- .changeset/promql-series-limit.md | 7 ++ .../components/ChartDisplaySettingsDrawer.tsx | 13 ++- .../ChartEditor/__tests__/utils.test.ts | 30 +++++ .../app/src/components/ChartEditor/utils.ts | 2 + packages/app/src/components/DBTimeChart.tsx | 8 ++ .../ChartDisplaySettingsDrawer.test.tsx | 79 +++++++++++++ .../charts/HiddenSeriesIndicator.tsx | 8 +- .../__tests__/HiddenSeriesIndicator.test.tsx | 34 ++++++ .../e2e/components/ChartEditorComponent.ts | 5 +- .../e2e/features/promql-series-limit.spec.ts | 108 ++++++++++++++++++ 10 files changed, 285 insertions(+), 9 deletions(-) create mode 100644 .changeset/promql-series-limit.md create mode 100644 packages/app/tests/e2e/features/promql-series-limit.spec.ts diff --git a/.changeset/promql-series-limit.md b/.changeset/promql-series-limit.md new file mode 100644 index 0000000000..81d7c8d53f --- /dev/null +++ b/.changeset/promql-series-limit.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/app': patch +--- + +feat: support a series limit on PromQL line and stacked bar charts + +The Display Settings drawer now offers Series Limit for PromQL time charts. It keeps the top N series by peak value in the browser; leave it empty for the default of 250, or set 0 for unlimited. diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 559f859348..02e78d93a7 100644 --- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx +++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx @@ -205,11 +205,12 @@ export default function ChartDisplaySettingsDrawer({ // Series Limit applies to every time chart. On builder group-by charts a // positive value drives the __hdx_series_limit SQL CTE (trimming what's - // fetched); on raw SQL it drives the client-side render cap in - // `formatResponseForTimeChart` (raw SQL can't inject the CTE). PromQL is - // excluded — its series come from Prometheus, not this pipeline. - const showSeriesLimit = isTimeChart && configType !== 'promql'; - const isRawSqlTimeChart = showSeriesLimit && configType === 'sql'; + // fetched); on raw SQL and PromQL it drives the client-side render cap in + // `formatResponseForTimeChart` (neither can take the CTE, and a Prometheus + // `limit` would keep an arbitrary label-sorted subset, not the top N). + const showSeriesLimit = isTimeChart; + const isClientSideSeriesLimit = + showSeriesLimit && (configType === 'sql' || configType === 'promql'); // Every PromQL display that surfaces a series name. A number tile shows one // value and a table gives each label its own column, so neither has a legend. @@ -315,7 +316,7 @@ export default function ChartDisplaySettingsDrawer({ size="xs" label="Series Limit" description={ - isRawSqlTimeChart + 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.` } diff --git a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts index 6705b5dda7..40850a4723 100644 --- a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts @@ -156,6 +156,36 @@ describe('convertFormStateToSavedChartConfig', () => { expect(result).toMatchObject({ alternateRowBackground: true }); }); + it.each([0, 5])( + 'persists seriesLimit=%s for a promql+line config', + seriesLimit => { + const form: ChartEditorFormState = { + configType: 'promql', + displayType: DisplayType.Line, + promqlExpression: 'up', + connection: 'conn-1', + seriesLimit, + series: [], + }; + const result = convertFormStateToSavedChartConfig(form, undefined); + expect(result).toMatchObject({ seriesLimit }); + }, + ); + + it('carries seriesLimit into the queried config for a promql+line config', () => { + const form: ChartEditorFormState = { + configType: 'promql', + displayType: DisplayType.Line, + promqlExpression: 'up', + connection: 'conn-1', + seriesLimit: 5, + series: [], + }; + const dateRange: [Date, Date] = [new Date(0), new Date(1000)]; + const result = convertFormStateToChartConfig(form, dateRange, undefined); + expect(result).toMatchObject({ configType: 'promql', seriesLimit: 5 }); + }); + it('returns a raw SQL config for Line displayType', () => { const form: ChartEditorFormState = { configType: 'sql', diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index 9320453535..d0740b93c7 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -267,6 +267,7 @@ export function convertFormStateToSavedChartConfig( 'fillNulls', 'alignDateRangeToGranularity', 'alternateRowBackground', + 'seriesLimit', // 'alert', // TODO: Support alerts on PromQL (HDX-4636) ]), promqlExpression: formPromqlExpressions(form), @@ -366,6 +367,7 @@ export function convertFormStateToChartConfig( 'fillNulls', 'alignDateRangeToGranularity', 'alternateRowBackground', + 'seriesLimit', ]), promqlExpression: formPromqlExpressions(form), connection: source?.connection ?? form.connection ?? '', diff --git a/packages/app/src/components/DBTimeChart.tsx b/packages/app/src/components/DBTimeChart.tsx index 6cd84278b9..be4a8f1bb7 100644 --- a/packages/app/src/components/DBTimeChart.tsx +++ b/packages/app/src/components/DBTimeChart.tsx @@ -62,6 +62,9 @@ import DisplaySwitcher from './charts/DisplaySwitcher'; import HiddenSeriesIndicator from './charts/HiddenSeriesIndicator'; import MVOptimizationIndicator from './MaterializedViews/MVOptimizationIndicator'; +const PROMQL_REDUCE_CARDINALITY_HINT = + 'Narrow the label matchers, aggregate with sum by (...), or set a series limit to reduce the number of series.'; + /** A single group column / value pair decoded from a chart series key. */ export type SeriesGroupFilter = { column: string; value: string }; @@ -953,6 +956,11 @@ function DBTimeChartComponent({ // raise the cap (loadAllHandler is undefined otherwise), so the // notice never advertises a no-op click. onLoadAll={loadAllHandler} + reduceCardinalityHint={ + isPromqlChartConfig(config) + ? PROMQL_REDUCE_CARDINALITY_HINT + : undefined + } />, ); } diff --git a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx index 2169ae3a59..b9884f5c27 100644 --- a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx +++ b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx @@ -273,6 +273,85 @@ describe('ChartDisplaySettingsDrawer', () => { ).not.toBeInTheDocument(); }); + describe('PromQL (client render cap)', () => { + const promqlProps = { ...baseProps, configType: 'promql' as const }; + + it.each([DisplayType.Line, DisplayType.StackedBar])( + 'shows the Series Limit input for PromQL %s charts', + displayType => { + renderWithMantine( + , + ); + + const input = screen.getByRole('textbox', { name: /series limit/i }); + expect(input).toHaveAttribute( + 'placeholder', + `Default (${MAX_RENDERED_TIME_CHART_SERIES})`, + ); + }, + ); + + it('describes the limit as a render cap, not a fetch cap', () => { + renderWithMantine( + , + ); + + expect( + screen.getByText(/maximum number of series rendered/i), + ).toBeInTheDocument(); + expect(screen.queryByText(/fetched/i)).not.toBeInTheDocument(); + }); + + it.each([ + DisplayType.Pie, + DisplayType.Bar, + DisplayType.Number, + DisplayType.Table, + ])( + 'does not show the Series Limit input for PromQL %s charts', + displayType => { + renderWithMantine( + , + ); + + expect( + screen.queryByRole('textbox', { name: /series limit/i }), + ).not.toBeInTheDocument(); + }, + ); + + it('calls onChange with the entered seriesLimit when applied', async () => { + const onChange = jest.fn(); + const user = userEvent.setup(); + + renderWithMantine( + , + ); + + await user.type( + screen.getByRole('textbox', { name: /series limit/i }), + '5', + ); + await user.click(screen.getByRole('button', { name: /apply/i })); + + expect(onChange).toHaveBeenCalledTimes(1); + expect(onChange.mock.calls[0][0]).toMatchObject({ seriesLimit: 5 }); + }); + }); + it('calls onChange with the entered seriesLimit when applied', async () => { const onChange = jest.fn(); const user = userEvent.setup(); diff --git a/packages/app/src/components/charts/HiddenSeriesIndicator.tsx b/packages/app/src/components/charts/HiddenSeriesIndicator.tsx index 56b77a849b..c5ad93859d 100644 --- a/packages/app/src/components/charts/HiddenSeriesIndicator.tsx +++ b/packages/app/src/components/charts/HiddenSeriesIndicator.tsx @@ -6,8 +6,13 @@ interface HiddenSeriesIndicatorProps { renderedSeriesCount: number; /** Render every series, bypassing the cap. Omit to keep the notice passive. */ onLoadAll?: () => void; + /** How to reduce cardinality when "load all" isn't offered. Defaults to SQL advice. */ + reduceCardinalityHint?: string; } +const DEFAULT_REDUCE_CARDINALITY_HINT = + 'Add a stricter GROUP BY, a WHERE filter, or a series limit to reduce cardinality.'; + /** * Warns that the chart returned more series than the client renders. The * transform caps series to protect memory; this surfaces the dropped ones and, @@ -17,6 +22,7 @@ export default function HiddenSeriesIndicator({ hiddenSeriesCount, renderedSeriesCount, onLoadAll, + reduceCardinalityHint = DEFAULT_REDUCE_CARDINALITY_HINT, }: HiddenSeriesIndicatorProps) { if (hiddenSeriesCount <= 0) { return null; @@ -29,7 +35,7 @@ export default function HiddenSeriesIndicator({ `showing the top ${renderedSeriesCount.toLocaleString()} by peak value. ` + (onLoadAll ? `Click to load all ${total.toLocaleString()} (may be slow).` - : 'Add a stricter GROUP BY, a WHERE filter, or a series limit to reduce cardinality.'); + : reduceCardinalityHint); const icon = ( diff --git a/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx b/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx index 672fe13828..45de750b05 100644 --- a/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx +++ b/packages/app/src/components/charts/__tests__/HiddenSeriesIndicator.test.tsx @@ -42,4 +42,38 @@ describe('HiddenSeriesIndicator', () => { await userEvent.click(button); expect(onLoadAll).toHaveBeenCalledTimes(1); }); + + describe('passive notice copy', () => { + const hoverIcon = async (container: HTMLElement) => { + const icon = container.querySelector('svg'); + expect(icon).not.toBeNull(); + await userEvent.hover(icon!); + }; + + it('gives SQL advice by default', async () => { + const { container } = renderWithMantine( + , + ); + await hoverIcon(container); + expect(await screen.findByText(/stricter GROUP BY/i)).toBeInTheDocument(); + }); + + it('uses reduceCardinalityHint in place of the SQL advice', async () => { + const { container } = renderWithMantine( + , + ); + await hoverIcon(container); + expect( + await screen.findByText(/narrow the label matchers/i), + ).toBeInTheDocument(); + expect(screen.queryByText(/stricter GROUP BY/i)).not.toBeInTheDocument(); + }); + }); }); diff --git a/packages/app/tests/e2e/components/ChartEditorComponent.ts b/packages/app/tests/e2e/components/ChartEditorComponent.ts index dc0670e2dc..c9532e0248 100644 --- a/packages/app/tests/e2e/components/ChartEditorComponent.ts +++ b/packages/app/tests/e2e/components/ChartEditorComponent.ts @@ -1163,8 +1163,9 @@ export class ChartEditorComponent { /** * Set the "Series Limit" value in the Display Settings drawer. On pie/bar - * builder charts this caps the number of slices/bars displayed. Opens the - * drawer, fills the input, then applies and closes. + * builder charts this caps the number of slices/bars displayed; on time + * charts it caps the number of series. Opens the drawer, fills the input, + * then applies and closes. */ async setSeriesLimit(limit: number) { await this.openDisplaySettings(); diff --git a/packages/app/tests/e2e/features/promql-series-limit.spec.ts b/packages/app/tests/e2e/features/promql-series-limit.spec.ts new file mode 100644 index 0000000000..dc0a852783 --- /dev/null +++ b/packages/app/tests/e2e/features/promql-series-limit.spec.ts @@ -0,0 +1,108 @@ +/** + * PromQL series limit: a per-tile cap on how many series a time chart renders. + * It is applied in the browser (keeping the top N by peak value), so the + * warning icon offers "load all" to bypass it. + * + * The seed gives `e2e_service_up` one series per `SERVICES` entry (10), all + * with the same value, so which series survive the cap is arbitrary. The + * assertions count series rather than name them. + */ +import { DashboardPage } from '../page-objects/DashboardPage'; +import { SERVICES } from '../seed-clickhouse'; +import { expect, test } from '../utils/base-test'; +import { E2E_PROMQL_METRIC_NAME, PROMQL_SOURCE_NAME } from '../utils/constants'; + +const ALL_SERIES = `${E2E_PROMQL_METRIC_NAME}{service!=""}`; +const SERIES_COUNT = SERVICES.length; +// The legend lists this many series before collapsing the rest into "+N more". +const LEGEND_ITEM_LIMIT = 4; +const SERIES_LIMIT = 2; + +test.describe( + 'PromQL series limit', + { tag: ['@dashboard', '@full-stack'] }, + () => { + test('caps rendered series, offers load-all, and round-trips', async ({ + page, + }) => { + test.setTimeout(120000); + + const dashboardPage = new DashboardPage(page); + const editor = dashboardPage.chartEditor; + const legend = page.locator('.recharts-legend-wrapper').first(); + // The legend middle-truncates long labels (`e2e_service_up{s..ce="x"}`), + // so match on the metric name that always survives. + const legendSeries = legend.getByText(E2E_PROMQL_METRIC_NAME); + const loadAll = page.getByRole('button', { + name: `Load all ${SERIES_COUNT} series`, + }); + + await test.step('Create a dashboard with a PromQL line tile', async () => { + await dashboardPage.goto(); + await dashboardPage.createNewDashboard(); + await dashboardPage.addTile(); + await expect(editor.nameInput).toBeVisible(); + await editor.waitForDataToLoad(); + await editor.switchToPromqlMode(); + await editor.selectSource(PROMQL_SOURCE_NAME); + await editor.setChartName('PromQL series limit tile'); + await editor.replacePromqlExpression(ALL_SERIES); + await editor.save(); + await expect(dashboardPage.getTiles()).toHaveCount(1, { + timeout: 10000, + }); + }); + + await test.step('Without a limit every series is rendered', async () => { + await expect( + legend.getByText(`+${SERIES_COUNT - LEGEND_ITEM_LIMIT} more`), + ).toBeVisible({ timeout: 30000 }); + await expect(loadAll).toHaveCount(0); + }); + + await test.step('A series limit caps the legend and warns', async () => { + await dashboardPage.editTile(0); + await expect(editor.nameInput).toBeVisible(); + await editor.setSeriesLimit(SERIES_LIMIT); + await editor.save(); + await expect(dashboardPage.getTiles()).toHaveCount(1, { + timeout: 10000, + }); + await expect(legendSeries).toHaveCount(SERIES_LIMIT, { + timeout: 30000, + }); + await expect(legend.getByText(/\+\d+ more/)).toHaveCount(0); + await expect(loadAll).toBeVisible(); + }); + + await test.step('Load all bypasses the limit', async () => { + await loadAll.click(); + await expect( + legend.getByText(`+${SERIES_COUNT - LEGEND_ITEM_LIMIT} more`), + ).toBeVisible({ timeout: 30000 }); + await expect(loadAll).toHaveCount(0); + }); + + await test.step('The saved limit applies again after a reload', async () => { + await dashboardPage.reload(); + await expect(dashboardPage.getTiles()).toHaveCount(1, { + timeout: 10000, + }); + await expect(legendSeries).toHaveCount(SERIES_LIMIT, { + timeout: 30000, + }); + await expect(loadAll).toBeVisible(); + }); + + await test.step('The limit round-trips into the editor', async () => { + await dashboardPage.editTile(0); + await expect(editor.nameInput).toBeVisible(); + await editor.openDisplaySettings(); + const drawer = page.getByRole('dialog', { name: 'Display Settings' }); + await expect(drawer.getByLabel('Series Limit')).toHaveValue( + String(SERIES_LIMIT), + ); + }); + }); + }, +); From 9506452727213afb3f2dc72cae9b7b42d3f83161 Mon Sep 17 00:00:00 2001 From: Karl Power Date: Tue, 6 Oct 2026 15:51:54 +0200 Subject: [PATCH 2/2] support promql series limit on pie and bar charts --- .changeset/promql-series-limit.md | 4 +- packages/app/src/ChartUtils.tsx | 3 +- packages/app/src/__tests__/ChartUtils.test.ts | 41 +++++++++++++++++++ .../components/ChartDisplaySettingsDrawer.tsx | 6 +-- .../ChartDisplaySettingsDrawer.test.tsx | 24 ++++++++--- .../components/__tests__/DBPieChart.test.tsx | 29 ++++++++++--- .../components/charts/CategoricalChart.tsx | 20 ++++++++- .../tests/e2e/features/promql-pie-bar.spec.ts | 26 ++++++++++-- 8 files changed, 130 insertions(+), 23 deletions(-) diff --git a/.changeset/promql-series-limit.md b/.changeset/promql-series-limit.md index 81d7c8d53f..50be3a9bc5 100644 --- a/.changeset/promql-series-limit.md +++ b/.changeset/promql-series-limit.md @@ -2,6 +2,6 @@ '@hyperdx/app': patch --- -feat: support a series limit on PromQL line and stacked bar charts +feat: support a series limit on PromQL line, stacked bar, pie and bar charts -The Display Settings drawer now offers Series Limit for PromQL time charts. It keeps the top N series by peak value in the browser; leave it empty for the default of 250, or set 0 for unlimited. +The Display Settings drawer now offers Series Limit for PromQL charts. On line and stacked bar charts it keeps the top N series by peak value (leave empty for the default of 250, or set 0 for unlimited). On pie and bar charts it keeps the N largest slices or bars (leave empty to show all). diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx index 93df38bfb5..5e26a2e16f 100644 --- a/packages/app/src/ChartUtils.tsx +++ b/packages/app/src/ChartUtils.tsx @@ -550,6 +550,7 @@ export function formatResponseForCategoricalChart( data: ResponseJSON>, getColor: (index: number, label: string) => string, applyDefaultOrder: boolean = true, + maxGroups: number = DEFAULT_MAX_CATEGORICAL_GROUPS, ): Array<{ label: string; value: number; color: string }> { if (data.meta == null) { throw new Error('No meta data found in response'); @@ -587,7 +588,7 @@ export function formatResponseForCategoricalChart( } return labelsAndValues - .slice(0, DEFAULT_MAX_CATEGORICAL_GROUPS) + .slice(0, Math.min(maxGroups, DEFAULT_MAX_CATEGORICAL_GROUPS)) .map((entry, index) => ({ ...entry, color: getColor(index, entry.label), diff --git a/packages/app/src/__tests__/ChartUtils.test.ts b/packages/app/src/__tests__/ChartUtils.test.ts index d8c2caedf5..429fc4c39c 100644 --- a/packages/app/src/__tests__/ChartUtils.test.ts +++ b/packages/app/src/__tests__/ChartUtils.test.ts @@ -1725,6 +1725,47 @@ describe('ChartUtils', () => { { label: 'svc', value: 5, color: 'color-0-svc' }, ]); }); + + describe('maxGroups', () => { + const manyGroups = (count: number) => ({ + data: Array.from({ length: count }, (_, i) => ({ + value: i, + series_name: `s${i}`, + })), + meta: [ + { name: 'value', type: 'Float64' }, + { name: 'series_name', type: 'String' }, + ], + }); + + it('keeps the largest maxGroups groups', () => { + const result = formatResponseForCategoricalChart( + manyGroups(5), + getColor, + true, + 2, + ); + expect(result.map(e => e.label)).toEqual(['s4', 's3']); + }); + + it('caps at 500 groups by default', () => { + const result = formatResponseForCategoricalChart( + manyGroups(600), + getColor, + ); + expect(result).toHaveLength(500); + }); + + it('cannot raise the 500-group cap', () => { + const result = formatResponseForCategoricalChart( + manyGroups(600), + getColor, + true, + 1000, + ); + expect(result).toHaveLength(500); + }); + }); }); describe('findNearestSeriesKey', () => { diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx index 02e78d93a7..2f868cc124 100644 --- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx +++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx @@ -220,11 +220,11 @@ export default function ChartDisplaySettingsDrawer({ displayType !== DisplayType.Table; // On pie/bar builder charts, seriesLimit becomes a plain SQL LIMIT on the - // number of slices/bars; raw SQL configs author their own LIMIT directly. + // number of slices/bars; on PromQL it trims the reduced series client-side + // in `useCategoricalChart`. Raw SQL configs author their own LIMIT directly. const isCategoricalChart = displayType === DisplayType.Pie || displayType === DisplayType.Bar; - const showCategoricalLimit = - isCategoricalChart && configType !== 'sql' && configType !== 'promql'; + const showCategoricalLimit = isCategoricalChart && configType !== 'sql'; // Table display options. Alternate Row Background is purely presentational // (it stripes rendered rows), so it applies to any table tile. Group By diff --git a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx index b9884f5c27..6bcd400664 100644 --- a/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx +++ b/packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx @@ -308,12 +308,7 @@ describe('ChartDisplaySettingsDrawer', () => { expect(screen.queryByText(/fetched/i)).not.toBeInTheDocument(); }); - it.each([ - DisplayType.Pie, - DisplayType.Bar, - DisplayType.Number, - DisplayType.Table, - ])( + it.each([DisplayType.Number, DisplayType.Table])( 'does not show the Series Limit input for PromQL %s charts', displayType => { renderWithMantine( @@ -417,6 +412,23 @@ describe('ChartDisplaySettingsDrawer', () => { }, ); + it.each([DisplayType.Pie, DisplayType.Bar])( + 'shows the Series Limit input for PromQL %s charts', + displayType => { + renderWithMantine( + , + ); + + expect( + screen.getByRole('textbox', { name: /series limit/i }), + ).toHaveAttribute('placeholder', 'Disabled (e.g. 10)'); + }, + ); + it('does not show the Series Limit input for raw SQL pie charts', () => { renderWithMantine( { expect(second).toEqual(first); }); - it('draws a slice per series, largest first', () => { + const mockThreeSeries = () => mockUseQueriedChartConfig.mockReturnValue({ data: { data: [ @@ -368,12 +368,31 @@ describe('DBPieChart', () => { isError: false, }); - renderWithMantine(); - - const labels = within(screen.getByTestId('pie-chart-legend')) + const legendLabels = () => + within(screen.getByTestId('pie-chart-legend')) .getAllByTitle(/.+/) .map(el => el.getAttribute('title')); - expect(labels).toEqual(['checkout', 'ad', 'cart']); + + it('draws a slice per series, largest first', () => { + mockThreeSeries(); + renderWithMantine(); + expect(legendLabels()).toEqual(['checkout', 'ad', 'cart']); + }); + + it('keeps only the largest seriesLimit slices', () => { + mockThreeSeries(); + renderWithMantine( + , + ); + expect(legendLabels()).toEqual(['checkout', 'ad']); + }); + + it('treats a seriesLimit of 0 as unlimited', () => { + mockThreeSeries(); + renderWithMantine( + , + ); + expect(legendLabels()).toEqual(['checkout', 'ad', 'cart']); }); }); }); diff --git a/packages/app/src/components/charts/CategoricalChart.tsx b/packages/app/src/components/charts/CategoricalChart.tsx index 6174430c12..5e839c14c9 100644 --- a/packages/app/src/components/charts/CategoricalChart.tsx +++ b/packages/app/src/components/charts/CategoricalChart.tsx @@ -1,5 +1,8 @@ import { useMemo } from 'react'; -import { hasNonEmptyOrderBy } from '@hyperdx/common-utils/dist/core/utils'; +import { + hasNonEmptyOrderBy, + hasPositiveSeriesLimit, +} from '@hyperdx/common-utils/dist/core/utils'; import { isBuilderChartConfig, isPromqlChartConfig, @@ -130,8 +133,21 @@ export function useCategoricalChart({ isBuilderChartConfig(queriedConfig) && hasNonEmptyOrderBy(queriedConfig.orderBy); + // Builder charts apply seriesLimit as a SQL LIMIT. Prometheus returns + // every series, so a PromQL limit trims the largest-first rows here. + const maxGroups = + isPromqlChartConfig(queriedConfig) && + hasPositiveSeriesLimit(queriedConfig.seriesLimit) + ? queriedConfig.seriesLimit + : undefined; + return [ - formatResponseForCategoricalChart(data, getColorProps, !hasOrderBy), + formatResponseForCategoricalChart( + data, + getColorProps, + !hasOrderBy, + maxGroups, + ), null, ]; } catch (error) { diff --git a/packages/app/tests/e2e/features/promql-pie-bar.spec.ts b/packages/app/tests/e2e/features/promql-pie-bar.spec.ts index 091e460928..e409800ef1 100644 --- a/packages/app/tests/e2e/features/promql-pie-bar.spec.ts +++ b/packages/app/tests/e2e/features/promql-pie-bar.spec.ts @@ -2,10 +2,11 @@ * PromQL pie and bar tiles draw one slice or bar per series: a range query is * reduced to one value per series, and an instant query already is one. The * series come from the expression, not from a group-by, so there is no ORDER BY - * or series limit to set. + * to set; a series limit keeps the largest N. * * The seed gives `e2e_service_up` one series per `SERVICES` entry, labelled - * `service`, one sample of 1 a minute. + * `service`, one sample of 1 a minute. With every value equal, which series a + * limit keeps is arbitrary, so the limit check counts slices. */ import { DisplayType } from '@hyperdx/common-utils/dist/types'; @@ -19,6 +20,7 @@ import { E2E_PROMQL_METRIC_NAME, PROMQL_SOURCE_NAME } from '../utils/constants'; * popup, which would otherwise cover the query type control. */ const ALL_SERIES = `${E2E_PROMQL_METRIC_NAME}{service!=""}`; +const SERIES_LIMIT = 3; test.describe( 'PromQL pie and bar tiles', @@ -61,10 +63,9 @@ test.describe( await expect(page.getByTestId('order-by-input')).toBeHidden(); }); - await test.step('Display settings offer a legend template and number format, not a series limit', async () => { + await test.step('Display settings offer a legend template and number format', async () => { await editor.setLegendTemplate('{{service}}'); await editor.openDisplaySettings(); - await expect(drawer.getByLabel('Series Limit')).toBeHidden(); await editor.setNumberFormatOutput('Currency'); await editor.applyDisplaySettings(); await editor.runQuery(false); @@ -77,6 +78,23 @@ test.describe( await expect(legend.getByText('$1.00').first()).toBeVisible(); }); + await test.step('A series limit keeps that many slices', async () => { + await editor.setSeriesLimit(SERIES_LIMIT); + await editor.runQuery(false); + await expect(legend.getByTitle(/.+/)).toHaveCount(SERIES_LIMIT, { + timeout: 30000, + }); + + // Clear it so the steps below see every series again. + await editor.openDisplaySettings(); + await drawer.getByLabel('Series Limit').fill(''); + await editor.applyDisplaySettings(); + await editor.runQuery(false); + await expect(legend.getByTitle(/.+/)).toHaveCount(SERVICES.length, { + timeout: 30000, + }); + }); + await test.step('An instant query draws the same slices, with no granularity', async () => { await editor.setPromqlQueryType('Instant'); await editor.runQuery(false);