Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .changeset/promql-pie-bar-tiles.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/common-utils': patch
'@hyperdx/app': patch
---

feat: Support pie and bar tiles on PromQL sources
32 changes: 25 additions & 7 deletions packages/app/src/ChartUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -147,21 +147,39 @@ function getAlignedRangeAndGranularity(
}

/**
* A PromQL number tile's queried config, shared by the value and the sparkline
* drawn behind it.
* Converts the given config into one that is suitable for a tile that shows
* 1 value per series (number, pie, and bar tiles). The reducer defaults to
* the last value.
*/
export function convertToPromqlNumberChartConfig(
export function convertToReducedPromqlChartConfig(
config: PromqlChartConfig & DateRange,
{ withReducer }: { withReducer: boolean },
): PromqlChartConfig & DateRange {
return {
...config,
...getAlignedRangeAndGranularity(config),
promqlExpression: getQueriedPromqlSeries(config).map(series => ({
...series,
reducer: withReducer
? (series.reducer ?? DEFAULT_PROMQL_REDUCER)
: undefined,
reducer: series.reducer ?? DEFAULT_PROMQL_REDUCER,
})),
};
}

/**
* The config for the sparkline behind a PromQL number tile: the tile's query
* with no reducer, so the buckets are plotted rather than collapsed.
*
* Intentionally matches convertToReducedPromqlChartConfig except for the reducer,
* so that react-query keys remain consistent between the reduced and sparkline versions.
*/
export function convertToPromqlSparklineChartConfig(
config: PromqlChartConfig & DateRange,
): PromqlChartConfig & DateRange {
const reduced = convertToReducedPromqlChartConfig(config);
return {
...reduced,
promqlExpression: getQueriedPromqlSeries(reduced).map(series => ({
...series,
reducer: undefined,
})),
};
}
Expand Down
63 changes: 25 additions & 38 deletions packages/app/src/__tests__/ChartUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import {
import {
ChartKeyJoiner,
convertToNumberChartConfig,
convertToPromqlNumberChartConfig,
convertToPromqlSparklineChartConfig,
convertToPromqlTableChartConfig,
convertToReducedPromqlChartConfig,
convertToTableChartConfig,
convertToTimeChartConfig,
findNearestSeriesKey,
Expand Down Expand Up @@ -1318,7 +1319,7 @@ describe('ChartUtils', () => {
});
});

describe('convertToPromqlNumberChartConfig', () => {
describe('convertToReducedPromqlChartConfig and convertToPromqlSparklineChartConfig', () => {
const promqlConfig = {
configType: 'promql' as const,
displayType: DisplayType.Number,
Expand All @@ -1337,9 +1338,7 @@ describe('ChartUtils', () => {
// unresolved step puts the samples between the buckets the sparkline plots
// on -- which the empty-bucket filler then fills with zeros.
it('aligns the date range and resolves the granularity', () => {
const result = convertToPromqlNumberChartConfig(promqlConfig, {
withReducer: true,
});
const result = convertToReducedPromqlChartConfig(promqlConfig);

expect(result.dateRange).toEqual([
new Date('2025-11-26T00:00:00Z'),
Expand All @@ -1349,17 +1348,14 @@ describe('ChartUtils', () => {
});

it('leaves the date range unaligned for an instant query', () => {
const result = convertToPromqlNumberChartConfig(
{
...promqlConfig,
promqlExpression: [{ expression: 'up', queryType: 'instant' }],
dateRange: [
new Date('2025-11-26T00:00:14.076Z'),
new Date('2025-11-27T00:00:14.076Z'),
],
},
{ withReducer: true },
);
const result = convertToReducedPromqlChartConfig({
...promqlConfig,
promqlExpression: [{ expression: 'up', queryType: 'instant' }],
dateRange: [
new Date('2025-11-26T00:00:14.076Z'),
new Date('2025-11-27T00:00:14.076Z'),
],
});

expect(result.dateRange).toEqual([
new Date('2025-11-26T00:00:14.076Z'),
Expand All @@ -1369,9 +1365,7 @@ describe('ChartUtils', () => {
});

it('names the reducer, defaulting it, and queries one expression', () => {
const result = convertToPromqlNumberChartConfig(promqlConfig, {
withReducer: true,
});
const result = convertToReducedPromqlChartConfig(promqlConfig);

expect(result).toEqual(
expect.objectContaining({
Expand All @@ -1387,19 +1381,16 @@ describe('ChartUtils', () => {
});

it('keeps a chosen reducer', () => {
const result = convertToPromqlNumberChartConfig(
{
...promqlConfig,
promqlExpression: [
{
expression: 'up',
queryType: 'range' as const,
reducer: PromqlReducer.Max,
},
],
},
{ withReducer: true },
);
const result = convertToReducedPromqlChartConfig({
...promqlConfig,
promqlExpression: [
{
expression: 'up',
queryType: 'range' as const,
reducer: PromqlReducer.Max,
},
],
});

expect(result).toEqual(
expect.objectContaining({
Expand All @@ -1417,12 +1408,8 @@ describe('ChartUtils', () => {
// Without a reducer named, the hook leaves the buckets alone -- which is
// how the sparkline reads the same response as the value.
it('names no reducer for the sparkline, otherwise matching the value', () => {
const value = convertToPromqlNumberChartConfig(promqlConfig, {
withReducer: true,
});
const sparkline = convertToPromqlNumberChartConfig(promqlConfig, {
withReducer: false,
});
const value = convertToReducedPromqlChartConfig(promqlConfig);
const sparkline = convertToPromqlSparklineChartConfig(promqlConfig);

expect(sparkline).toEqual({
...value,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,12 @@ export default function PromqlQueryTypeControls({
name: `promqlExpressions.${index}.reducer`,
});
const queryTypeValue = queryType.value ?? DEFAULT_PROMQL_QUERY_TYPE;
const isRange = queryTypeValue === 'range';
const showReducer = isRange && isReducerSupported;
const reducerValue = reducer.value ?? DEFAULT_PROMQL_REDUCER;
const reducerLabel = REDUCER_OPTIONS.find(
o => o.value === reducerValue,
)?.label;
const summary = isRange
? `Settings: Range${showReducer ? ` / ${reducerLabel}` : ''}`
: 'Settings: Instant';
const queryTypeLabel = queryTypeValue === 'range' ? 'Range' : 'Instant';
const summary = `Settings: ${queryTypeLabel}${isReducerSupported ? ` / ${reducerLabel}` : ''}`;

return (
<>
Expand All @@ -75,7 +72,7 @@ export default function PromqlQueryTypeControls({
}}
data-testid={`promql-query-type-input-${index}`}
/>
{showReducer && (
{isReducerSupported && (
<>
<Text size="xxs" c="dimmed">
Reduced to
Expand All @@ -87,7 +84,7 @@ export default function PromqlQueryTypeControls({
value={reducerValue}
allowDeselect={false}
comboboxProps={{ withinPortal: false }}
aria-label="PromQL range reducer"
aria-label="PromQL reducer"
onChange={next => {
if (next == null) return;
reducer.onChange(next);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,26 @@ describe('buildRenderedPromqlExpression', () => {
).toBe('rate(up[60s])');
});

it.each([DisplayType.Pie, DisplayType.Bar])(
'expands macros with the aligned range a %s tile queries with',
displayType => {
const unaligned: [Date, Date] = [
new Date('2024-01-01T00:00:14Z'),
new Date('2024-01-01T01:10:14Z'),
];
expect(
buildRenderedPromqlExpression({
...promqlConfig({
displayType,
granularity: 'auto',
promqlExpression: [{ expression: 'up[$__interval] / $__range' }],
}),
dateRange: unaligned,
})?.expressions?.[0].expression,
).toBe('up[60s] / 4260s');
},
);

it('reports a substitution failure instead of an expression', () => {
const result = buildRenderedPromqlExpression(
promqlConfig({
Expand Down
11 changes: 7 additions & 4 deletions packages/app/src/components/DBEditTimeChartForm/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import {
TableConnection,
TableConnectionChoice,
} from '@hyperdx/common-utils/dist/core/metadata';
import { getQueriedPromqlSeries } from '@hyperdx/common-utils/dist/core/promql';
import {
displayTypeSupportsReducer,
getQueriedPromqlSeries,
} from '@hyperdx/common-utils/dist/core/promql';
import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils';
import {
configConsumesBroadcastFilters,
Expand Down Expand Up @@ -38,8 +41,8 @@ import { filterReferencedVariables } from '@hyperdx/common-utils/dist/variables'
import {
convertToCategoricalChartConfig,
convertToNumberChartConfig,
convertToPromqlNumberChartConfig,
convertToPromqlTableChartConfig,
convertToReducedPromqlChartConfig,
convertToTableChartConfig,
convertToTimeChartConfig,
tryExpandConfigVariables,
Expand Down Expand Up @@ -274,8 +277,8 @@ export type RenderedPromqlExpression =
function toQueriedPromqlConfig(
config: PromqlChartConfig & DateRange,
): PromqlChartConfig & DateRange {
if (config.displayType === DisplayType.Number) {
return convertToPromqlNumberChartConfig(config, { withReducer: false });
if (displayTypeSupportsReducer(config)) {
return convertToReducedPromqlChartConfig(config);
}
if (config.displayType === DisplayType.Table) {
return convertToPromqlTableChartConfig(config);
Expand Down
23 changes: 9 additions & 14 deletions packages/app/src/components/DBNumberChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { Flex, Text } from '@mantine/core';
import {
buildMVDateRangeIndicator,
convertToNumberChartConfig,
convertToPromqlNumberChartConfig,
convertToReducedPromqlChartConfig,
} from '@/ChartUtils';
import { useQueriedChartConfig } from '@/hooks/useChartConfig';
import { useMVOptimizationExplanation } from '@/hooks/useMVOptimizationExplanation';
Expand Down Expand Up @@ -226,7 +226,7 @@ export default function DBNumberChart({
const queriedConfig = useMemo(() => {
if (isBuilderChartConfig(config)) return convertToNumberChartConfig(config);
if (isPromqlChartConfig(config)) {
return convertToPromqlNumberChartConfig(config, { withReducer: true });
return convertToReducedPromqlChartConfig(config);
}
return config;
}, [config]);
Expand Down Expand Up @@ -255,18 +255,16 @@ export default function DBNumberChart({
)
: error;

const promqlRows = isPromqlChartConfig(queriedConfig)
? (data?.data ?? [])
: [];
const promqlValueCount = promqlRows.length;
const promqlSeriesCount = new Set(
promqlRows.map((row: Record<string, unknown>) => row.series_name),
).size;
// The reducer leaves one row per series.
const promqlSeriesCount = isPromqlChartConfig(queriedConfig)
? (data?.data?.length ?? 0)
: 0;

// Several series leave the value ambiguous (see the warning) and the tile
// shows whichever came first, so a trend behind it would mislead. Whether
// the config can be bucketed at all is the sparkline's own call.
const showSparkline = config.backgroundChart != null && promqlValueCount <= 1;
const showSparkline =
config.backgroundChart != null && promqlSeriesCount <= 1;

const resolvedNumberFormat = useSingleSeriesNumberFormat(queriedConfig);

Expand Down Expand Up @@ -328,14 +326,12 @@ export default function DBNumberChart({
allToolbarItems.push(...toolbarPrefix);
}

if (promqlValueCount > 1 || promqlSeriesCount > 1) {
if (promqlSeriesCount > 1) {
allToolbarItems.push(
<MultipleValuesIndicator
key="db-number-chart-multiple-values"
valueCount={promqlValueCount}
seriesCount={promqlSeriesCount}
multipleSeriesHint="Aggregate the expression, for example with sum() or sum by (...), to return a single series."
multipleValuesHint="Wrap any range selectors in a function to return an instant vector, for example rate(metric[5m]) rather than metric[5m]."
/>,
);
}
Expand Down Expand Up @@ -373,7 +369,6 @@ export default function DBNumberChart({
mvOptimizationData,
queriedConfig,
builderQueriedConfig,
promqlValueCount,
promqlSeriesCount,
]);

Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/components/NumberTileBackgroundChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from '@hyperdx/common-utils/dist/types';

import {
convertToPromqlNumberChartConfig,
convertToPromqlSparklineChartConfig,
convertToTimeChartConfig,
formatResponseForTimeChart,
shouldFillNullsWithZero,
Expand Down Expand Up @@ -69,7 +69,7 @@ export function buildSparklineQueryConfig(
// A PromQL tile shares the same (range) query as the number chart, without a reducer.
// This ensures that the sparkline can re-use the same react-query cache entry.
if (isPromqlChartConfig(config)) {
return convertToPromqlNumberChartConfig(config, { withReducer: false });
return convertToPromqlSparklineChartConfig(config);
}

// Display-only fields are dropped to avoid refetching identical time-series
Expand Down
17 changes: 0 additions & 17 deletions packages/app/src/components/__tests__/DBNumberChart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -830,23 +830,6 @@ describe('DBNumberChart', () => {
expect(screen.getByTestId('number-chart-value')).toHaveTextContent('1');
});

// Several values under one name is the other failure: the expression is
// returning a range rather than a single sample per series.
it('warns differently when one series carries several values', () => {
setInstantRows([
{ series_name: 'up', value: 1 },
{ series_name: 'up', value: 2 },
]);
mockFormatNumber.mockReturnValue('1');

renderWithMantine(<DBNumberChart config={promqlConfig} />);

expect(screen.getByTestId('multiple-values-indicator')).toHaveAttribute(
'aria-label',
'Query returned 2 values for one series',
);
});

it('does not warn for a non-PromQL config with several rows', () => {
mockUseQueriedChartConfig.mockReturnValue({
data: {
Expand Down
Loading
Loading