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
6 changes: 6 additions & 0 deletions packages/app/src/components/Slos/SloDefinitionFields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEdito
import { SloEligibleFilters } from './SloEligibleFilters';
import type { SloFormValues } from './sloForm';
import { SloFormRow } from './SloFormLayout';
import { SloGroupByField } from './SloGroupByField';
import { SloLatencyFields } from './SloLatencyFields';
import { formatSloWindow } from './sloUtils';

Expand Down Expand Up @@ -155,6 +156,11 @@ export function SloIndicatorFields({
<Input.Error mt={4}>{errors.indicator?.good?.message}</Input.Error>
</SloFormRow>
)}
<SloGroupByField
control={control}
sourceId={sourceId}
tableConnection={tableConnection}
/>
</>
);
}
Expand Down
7 changes: 4 additions & 3 deletions packages/app/src/components/Slos/SloEditorPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import { SloPreviewPanel } from './SloPreviewPanel';
const PREVIEW_FIELDS: FieldPath<SloFormValues>[] = [
'source',
'indicator',
'groupBy',
'target',
'window',
];
Expand Down Expand Up @@ -93,9 +94,9 @@ function SloEditorPage() {
resolver: sloFormResolver,
});
const { errors } = useFormState({ control, name: 'name' });
const [sourceId, indicator, target, sloWindow] = useWatch({
const [sourceId, indicator, groupBy, target, sloWindow] = useWatch({
control,
name: ['source', 'indicator', 'target', 'window'],
name: ['source', 'indicator', 'groupBy', 'target', 'window'],
});
const { data: source } = useSource({ id: sourceId || undefined });

Expand Down Expand Up @@ -127,7 +128,7 @@ function SloEditorPage() {
const isPreviewStale =
preview != null &&
getSloPreviewKey(
{ source: sourceId, indicator, window: sloWindow },
{ source: sourceId, indicator, groupBy, window: sloWindow },
source,
) !== preview.key;

Expand Down
38 changes: 38 additions & 0 deletions packages/app/src/components/Slos/SloGroupByField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { type Control, useFormState } from 'react-hook-form';
import type { TableConnection } from '@hyperdx/common-utils/dist/core/metadata';
import { SLO_MAX_GROUPS } from '@hyperdx/common-utils/dist/slo';
import { Input } from '@mantine/core';

import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';

import type { SloFormValues } from './sloForm';
import { SloFormRow } from './SloFormLayout';

/** The optional expression whose values each get their own numbers. */
export function SloGroupByField({
control,
sourceId,
tableConnection,
}: {
control: Control<SloFormValues>;
sourceId: string;
tableConnection: TableConnection;
}) {
const { errors } = useFormState({ control, name: 'groupBy' });
return (
<SloFormRow
label="Group by"
helpText={`Optional. Each value of this SQL expression gets its own SLI, error budget and alerts. The ${SLO_MAX_GROUPS} values with the most events are tracked.`}
>
<SQLInlineEditorControlled
tableConnection={tableConnection}
sourceId={sourceId}
control={control}
name="groupBy"
placeholder="For example ServiceName"
size="sm"
/>
<Input.Error mt={4}>{errors.groupBy?.message}</Input.Error>
</SloFormRow>
);
}
34 changes: 33 additions & 1 deletion packages/app/src/components/Slos/SloPreviewPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {
parseSloCountsRow,
parseSloGroupCountRow,
parseSloTotalRow,
} from '@hyperdx/common-utils/dist/core/slo';
import { computeSloStats } from '@hyperdx/common-utils/dist/core/sloStats';
import { SLO_MAX_GROUPS } from '@hyperdx/common-utils/dist/slo';
import {
Accordion,
Alert,
Expand Down Expand Up @@ -71,7 +73,12 @@ function SloPreviewResults({
}) {
const counts = useQueriedChartConfig(request.counts, PREVIEW_QUERY_OPTIONS);
const total = useQueriedChartConfig(request.total, PREVIEW_QUERY_OPTIONS);
const error = counts.error;
// Runs only with a group-by; the config stands in otherwise.
const groups = useQueriedChartConfig(request.groups ?? request.total, {
...PREVIEW_QUERY_OPTIONS,
enabled: request.groups != null,
});
const error = counts.error ?? (request.groups ? groups.error : null);

if (error) {
return (
Expand All @@ -91,6 +98,10 @@ function SloPreviewResults({
const excluded = total.data
? Math.max(0, parseSloTotalRow(total.data.data) - stats.eligible)
: undefined;
const groupCount =
request.groups && groups.data
? parseSloGroupCountRow(groups.data.data)
: undefined;
return (
<Stack gap="sm">
<SimpleGrid cols={3} spacing="xs">
Expand Down Expand Up @@ -120,9 +131,22 @@ function SloPreviewResults({
value={formatBudget(stats.budgetRemaining)}
color={budgetColorVar(stats.budgetRemaining)}
/>
{request.groups && (
<PreviewStat
label="Groups"
value={
groupCount != null && groupCount > SLO_MAX_GROUPS
? `${SLO_MAX_GROUPS} of ${formatCount(groupCount)}`
: formatCount(groupCount)
}
testId="slo-preview-groups"
/>
)}
</SimpleGrid>
<Text size="xs" c="dimmed">
Excluded events are in the source but outside the eligible events.
{request.groups &&
` The numbers are for all groups together; each group gets its own once the SLO is saved.`}
</Text>
<Accordion variant="contained" chevronPosition="left">
<Accordion.Item value="sql">
Expand All @@ -136,6 +160,14 @@ function SloPreviewResults({
All rows, for the excluded count
</Text>
<ChartSQLPreview config={request.total} enableCopy />
{request.groups && (
<>
<Text size="xs" c="dimmed">
Distinct groups
</Text>
<ChartSQLPreview config={request.groups} enableCopy />
</>
)}
</Stack>
</Accordion.Panel>
</Accordion.Item>
Expand Down
28 changes: 28 additions & 0 deletions packages/app/src/components/Slos/__tests__/sloForm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,14 @@ describe('SLO form', () => {
});
});

it('saves an empty group-by as none', () => {
expect(toSloInput(valid).groupBy).toBeNull();
expect(toSloInput({ ...valid, groupBy: ' ServiceName ' }).groupBy).toBe(
'ServiceName',
);
expect(sloToFormValues({ ...savedSlo, groupBy: null }).groupBy).toBe('');
});

it('marks a preview stale when its counts would change, not the target', () => {
const key = getSloPreviewKey(valid, traceSource);
const retargeted: SloFormValues = { ...valid, target: 95 };
Expand All @@ -224,6 +232,9 @@ describe('SLO form', () => {
);
// The latency settings play no part in an availability SLO.
expect(getSloPreviewKey(latency('Duration'), traceSource)).not.toBe(key);
expect(
getSloPreviewKey({ ...valid, groupBy: 'ServiceName' }, traceSource),
).not.toBe(key);
expect(
getSloPreviewKey(
{
Expand All @@ -246,5 +257,22 @@ describe('SLO form', () => {
new Date('2026-11-08T00:00:00Z'),
]);
expect(request?.total.dateRange).toEqual(request?.counts.dateRange);
expect(request?.groups).toBeUndefined();
});

it('counts the groups of a group-by in the preview', () => {
const now = Date.parse('2026-11-08T00:00:00Z');
const request = buildSloPreviewRequest(
{ ...valid, groupBy: 'ServiceName' },
traceSource,
now,
);
expect(request?.groups?.dateRange).toEqual(request?.counts.dateRange);
expect(request?.groups?.select).toEqual([
expect.objectContaining({
aggFn: 'count_distinct',
valueExpression: 'toString(ServiceName)',
}),
]);
});
});
26 changes: 21 additions & 5 deletions packages/app/src/components/Slos/sloForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Resolver } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
buildSloCountsChartConfig,
buildSloGroupCountChartConfig,
buildSloSourceTotalChartConfig,
getSloWindowRange,
} from '@hyperdx/common-utils/dist/core/slo';
Expand All @@ -24,13 +25,14 @@ import type {
* The builder edits the API input directly, so schema errors land on the
* fields they belong to. The form keeps the good condition and the latency
* settings side by side while the user switches templates; toSloInput keeps
* the one the template uses.
* the one the template uses. An empty group-by means none.
*/
export type SloFormValues = Omit<SloInput, 'indicator'> & {
export type SloFormValues = Omit<SloInput, 'indicator' | 'groupBy'> & {
indicator: Omit<SloInput['indicator'], 'good' | 'latency'> & {
good: string;
latency: Omit<SloLatency, 'numeric'>;
};
groupBy: string;
};

const DEFAULT_LATENCY: SloFormValues['indicator']['latency'] = {
Expand All @@ -52,6 +54,7 @@ export const DEFAULT_SLO_FORM_VALUES: SloFormValues = {
good: '',
latency: DEFAULT_LATENCY,
},
groupBy: '',
target: 99.9,
window: '30d',
// Off until the user turns one on and picks where it notifies.
Expand All @@ -76,8 +79,7 @@ export function sloToFormValues(slo: SloApiResponse): SloFormValues {
good: good ?? '',
latency: latency ?? DEFAULT_LATENCY,
},
// Kept as saved, so editing a grouped SLO keeps its groups.
groupBy: slo.groupBy,
groupBy: slo.groupBy ?? '',
target: slo.target,
window: slo.window,
alerts: {
Expand Down Expand Up @@ -168,6 +170,7 @@ export function toSloInput(values: SloFormValues, source?: TSource): SloInput {
return {
...values,
indicator: toSloIndicator(values.indicator, source),
groupBy: values.groupBy.trim() || null,
};
}

Expand All @@ -176,17 +179,20 @@ export type SloPreviewRequest = {
key: string;
counts: BuilderChartConfigWithDateRange;
total: BuilderChartConfigWithDateRange;
/** With a group-by: how many groups the window has. */
groups?: BuilderChartConfigWithDateRange;
};

/** What a preview's counts depend on. The target only changes the math. */
export function getSloPreviewKey(
values: Pick<SloFormValues, 'source' | 'indicator' | 'window'>,
values: Pick<SloFormValues, 'source' | 'indicator' | 'window' | 'groupBy'>,
source?: TSource,
): string {
return JSON.stringify([
values.source,
values.window,
toSloIndicator(values.indicator, source),
values.groupBy.trim(),
]);
}

Expand All @@ -201,6 +207,7 @@ export function buildSloPreviewRequest(
);
if (!indicator.success) return undefined;
const dateRange = getSloWindowRange(values.window, new Date(nowMs));
const groupBy = values.groupBy.trim();
return {
key: getSloPreviewKey(values, source),
counts: buildSloCountsChartConfig({
Expand All @@ -209,6 +216,15 @@ export function buildSloPreviewRequest(
dateRange,
}),
total: buildSloSourceTotalChartConfig({ source, dateRange }),
...(groupBy
? {
groups: buildSloGroupCountChartConfig({
slo: { indicator: indicator.data, groupBy },
source,
dateRange,
}),
}
: {}),
};
}

Expand Down
Loading