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-number-sparkline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/app': patch
'@hyperdx/common-utils': patch
---

feat: Support background sparklines on PromQL range number tiles
42 changes: 42 additions & 0 deletions packages/app/src/ChartUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import {
JSDataType,
ResponseJSON,
} from '@hyperdx/common-utils/dist/clickhouse';
import {
DEFAULT_PROMQL_REDUCER,
getQueriedPromqlSeries,
isRangeQuery,
} from '@hyperdx/common-utils/dist/core/promql';
import { isMetricChartConfig } from '@hyperdx/common-utils/dist/core/renderChartConfig';
import { SERIES_KEY_JOINER } from '@hyperdx/common-utils/dist/core/seriesNameTemplate';
import {
Expand All @@ -28,10 +33,12 @@ import {
BuilderSavedChartConfig,
ChartConfigWithDateRange,
ChartConfigWithOptDateRange,
DateRange,
DisplayType,
Filter,
isSearchableSource,
MetricsDataType as MetricsDataTypeV2,
PromqlChartConfig,
SourceKind,
SQLInterval,
TMetricSource,
Expand Down Expand Up @@ -115,6 +122,41 @@ function getTimeChartDateRange(

export const MAX_TIME_CHART_SERIES = DEFAULT_SERIES_LIMIT;

/**
* A PromQL number tile's queried config, shared by the value and the sparkline
* drawn behind it.
*/
export function convertToPromqlNumberChartConfig(
config: PromqlChartConfig & DateRange,
{ withReducer }: { withReducer: boolean },
): PromqlChartConfig & DateRange {
const granularity = getTimeChartGranularity(
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
config.granularity,
config.dateRange,
);
return {
...config,
granularity,
// Align the date range with the same buckets used by the sparkline and
// timeseries charts, when using a (bucketed) range query. Alignment is
// desirable for range queries to ensure consistent bucket boundaries
// and sizes.
dateRange: isRangeQuery(config)
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
? getTimeChartDateRange(
config.dateRange,
config.alignDateRangeToGranularity,
granularity,
)
: config.dateRange,
promqlExpression: getQueriedPromqlSeries(config).map(series => ({
...series,
reducer: withReducer
? (series.reducer ?? DEFAULT_PROMQL_REDUCER)
: undefined,
})),
};
}

export function convertToTimeChartConfig(
config: ChartConfigWithDateRange,
): ChartConfigWithDateRange {
Expand Down
123 changes: 123 additions & 0 deletions packages/app/src/__tests__/ChartUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { DEFAULT_PROMQL_REDUCER } from '@hyperdx/common-utils/dist/core/promql';
import {
BuilderChartConfigWithDateRange,
DisplayType,
PromqlReducer,
SourceKind,
TSource,
} from '@hyperdx/common-utils/dist/types';

import {
ChartKeyJoiner,
convertToNumberChartConfig,
convertToPromqlNumberChartConfig,
convertToTableChartConfig,
convertToTimeChartConfig,
findNearestSeriesKey,
Expand All @@ -20,6 +24,7 @@ import {
resolveRenderedSeriesCap,
} from '@/defaults';
import { COLORS } from '@/utils';
import { stripClientSideConfigFields } from '@/utils/chartConfig';

// Anchor info/error to concrete hexes rather than `getChartColorInfo()` /
// `getChartColorError()` so a regression that breaks the helpers can't
Expand Down Expand Up @@ -1279,6 +1284,124 @@ describe('ChartUtils', () => {
});
});

describe('convertToPromqlNumberChartConfig', () => {
const promqlConfig = {
configType: 'promql' as const,
displayType: DisplayType.Number,
connection: 'conn',
promqlExpression: [
{ expression: 'up', queryType: 'range' as const },
{ expression: 'down', queryType: 'range' as const },
],
dateRange: [
new Date('2025-11-26T00:00:14.076Z'),
new Date('2025-11-26T01:00:14.076Z'),
] as [Date, Date],
};

// Prometheus answers at `start + k * step`, so an unaligned start or an
// 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,
});

expect(result.dateRange).toEqual([
new Date('2025-11-26T00:00:00Z'),
new Date('2025-11-26T01:01:00Z'),
]);
expect(result.granularity).toBe('1 minute');
});

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 },
);

expect(result.dateRange).toEqual([
new Date('2025-11-26T00:00:14.076Z'),
new Date('2025-11-27T00:00:14.076Z'),
]);
expect(result.granularity).toBe('30 minute');
});

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

expect(result).toEqual(
expect.objectContaining({
promqlExpression: [
{
expression: 'up',
queryType: 'range',
reducer: DEFAULT_PROMQL_REDUCER,
},
],
}),
);
});

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

expect(result).toEqual(
expect.objectContaining({
promqlExpression: [
{
expression: 'up',
queryType: 'range',
reducer: PromqlReducer.Max,
},
],
}),
);
});

// 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,
});

expect(sparkline).toEqual({
...value,
promqlExpression: [
{ expression: 'up', queryType: 'range', reducer: undefined },
],
});
expect(stripClientSideConfigFields(sparkline)).toEqual(
stripClientSideConfigFields(value),
);
});
});

describe('convertToTableChartConfig', () => {
it('should remove granularity from the config', () => {
const config = {
Expand Down
10 changes: 6 additions & 4 deletions packages/app/src/components/BackgroundChartInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ const TYPE_OPTIONS = [
* "Area" set the shape. The color swatch is an optional palette-token
* override; when unset the sparkline inherits the tile's static color.
*
* `disabled` is set for raw SQL number tiles, which have no time dimension to
* bucket: the control stays visible but inert with a hint, so the option is
* discoverable rather than missing.
* `disabled` is set where the tile's query has no buckets to plot -- raw SQL,
* or a PromQL instant query. The control stays visible but inert with
* `disabledHint` explaining which, so the option stays discoverable.
*/
export function BackgroundChartInput({
value,
onChange,
disabled = false,
disabledHint = 'Available on query-builder number tiles.',
}: {
value?: BackgroundChart;
onChange: (value: BackgroundChart | undefined) => void;
disabled?: boolean;
disabledHint?: string;
}) {
return (
<Box>
Expand All @@ -51,7 +53,7 @@ export function BackgroundChartInput({
/>
{disabled ? (
<Text size="xs" c="dimmed" mt={4}>
Available on query-builder number tiles.
{disabledHint}
</Text>
) : (
value && (
Expand Down
22 changes: 16 additions & 6 deletions packages/app/src/components/ChartDisplaySettingsDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ interface ChartDisplaySettingsDrawerProps {
displayType: DisplayType;
/** 'sql' for raw SQL chart configs; anything else is treated as a builder config. */
configType?: 'sql' | 'builder' | 'promql';
/** Whether a PromQL tile's queried expression runs over a range. */
promqlUsesRange?: boolean;
previousDateRange?: [Date, Date];
onChange: (settings: ChartConfigDisplaySettings, isDirty: boolean) => void;
onClose: () => void;
Expand Down Expand Up @@ -119,6 +121,7 @@ export default function ChartDisplaySettingsDrawer({
opened,
displayType,
configType,
promqlUsesRange = false,
defaultNumberFormat,
onChange,
onClose,
Expand Down Expand Up @@ -222,13 +225,19 @@ export default function ChartDisplaySettingsDrawer({
// `select[i].color`.
const showTileColor = displayType === DisplayType.Number;

// The background sparkline is derived from a time-bucketed version of the
// tile's query, so it only applies to builder number tiles: raw SQL number
// tiles return a single value with no time dimension to bucket. On a SQL
// number tile the control is shown disabled with a hint rather than hidden,
// so the option stays discoverable.
// The sparkline needs buckets. A builder tile derives them from a
// time-bucketed version of its query; a PromQL tile reuses the buckets its
// range query fetches, so an instant one has none. Raw SQL returns a
// single value with no time dimension at all. Where it cannot apply the
// control is shown disabled with a hint rather than hidden, so the option
// stays discoverable.
const showBackgroundChart = displayType === DisplayType.Number;
const isBackgroundChartDisabled = configType === 'sql';
const isBackgroundChartDisabled =
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
configType === 'sql' || (configType === 'promql' && !promqlUsesRange);
const backgroundChartDisabledHint =
configType === 'promql'
? 'Available on PromQL range queries.'
: 'Available on query-builder number tiles.';

return (
<Drawer
Expand Down Expand Up @@ -430,6 +439,7 @@ export default function ChartDisplaySettingsDrawer({
value={value}
onChange={onChange}
disabled={isBackgroundChartDisabled}
disabledHint={backgroundChartDisabledHint}
/>
)}
/>
Expand Down
28 changes: 28 additions & 0 deletions packages/app/src/components/ChartEditor/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ describe('convertFormStateToSavedChartConfig', () => {
expect(result).toMatchObject({ alternateRowBackground: true });
});

it('persists backgroundChart for a promql+number config', () => {
const form: ChartEditorFormState = {
configType: 'promql',
displayType: DisplayType.Number,
promqlExpression: 'up',
connection: 'conn-1',
backgroundChart: { type: 'area' },
series: [],
};
const result = convertFormStateToSavedChartConfig(form, undefined);
expect(result).toMatchObject({ backgroundChart: { type: 'area' } });
});

it('persists alternateRowBackground for a promql+table config', () => {
const form: ChartEditorFormState = {
configType: 'promql',
Expand Down Expand Up @@ -409,6 +422,21 @@ describe('convertFormStateToChartConfig', () => {
expect(result).toMatchObject({ alternateRowBackground: true });
});

// The sparkline only renders if the rendered config carries this, and the
// promql branch builds its config from an explicit pick list.
it('threads backgroundChart into the rendered promql+number config', () => {
const form: ChartEditorFormState = {
configType: 'promql',
displayType: DisplayType.Number,
promqlExpression: 'up',
connection: 'conn-1',
backgroundChart: { type: 'area' },
series: [],
};
const result = convertFormStateToChartConfig(form, dateRange, undefined);
expect(result).toMatchObject({ backgroundChart: { type: 'area' } });
});

it('threads alternateRowBackground into the rendered promql+table config', () => {
const form: ChartEditorFormState = {
configType: 'promql',
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/components/ChartEditor/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ export function convertFormStateToSavedChartConfig(
'numberFormat',
'color',
'colorRules',
'backgroundChart',
'granularity',
'compareToPreviousPeriod',
'fillNulls',
Expand Down Expand Up @@ -299,6 +300,7 @@ export function convertFormStateToChartConfig(
'numberFormat',
'color',
'colorRules',
'backgroundChart',
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
'granularity',
'compareToPreviousPeriod',
'fillNulls',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { tcFromSource } from '@hyperdx/common-utils/dist/core/metadata';
import { isReducibleRangeQuery } from '@hyperdx/common-utils/dist/core/promql';
import {
displayTypeSupportsBuilderAlerts,
displayTypeSupportsRawSqlAlerts,
Expand Down Expand Up @@ -267,6 +268,7 @@ export default function EditTimeChartForm({
const markdown = useWatch({ control, name: 'markdown' });
const granularity = useWatch({ control, name: 'granularity' });
const configType = useWatch({ control, name: 'configType' });
const promqlExpressions = useWatch({ control, name: 'promqlExpressions' });

const chartConfigAlert = chartConfig.alert;
const isRawSqlInput =
Expand Down Expand Up @@ -1113,6 +1115,10 @@ export default function EditTimeChartForm({
previousDateRange={!dashboardId ? previousDateRange : undefined}
displayType={displayType}
configType={configType}
promqlUsesRange={isReducibleRangeQuery({
promqlExpression: promqlExpressions,
displayType,
})}
onChange={handleUpdateDisplaySettings}
onClose={closeDisplaySettings}
isPerSeriesNumberFormatAllowed={configType !== 'sql'}
Expand Down
Loading
Loading