From 8cca8b29ed5b103d80b62e562fab893e5aa9dd1f Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:58:08 +0000 Subject: [PATCH] feat(api): evaluate SLO burn alerts and notify Adds a built-in evaluator for SLO alerts. Each check runs one query that counts eligible and good events in 5-minute buckets over the last 6 hours, from a materialized view when one covers it, and computes both burn rules from it. Fast burn fires when 2% of the error budget is spent within an hour, slow burn when 5% is spent within six hours, and each also needs its last 5 or 30 minutes to burn as fast, so it resolves soon after a burn stops. Fast burn is checked every 5 minutes, slow burn every 15. Each alert notifies once when it starts firing (or on the first check after a silence ends) and once when it resolves. The title and message name the rule and state the numbers, and link to the SLO page with the bad events of the window. A title reads like this: SLO "Checkout" (ServiceName:frontend): slow burn, 17.2% of the 7-day budget spent in the last 6 hours A grouped SLO's alerts fire and resolve for each group with at least 100 events in the window, and resolve groups the SLO no longer tracks. Each check also stores its burn numbers on the SLO, so the SLO list shows the alerts' own verdict. SLO alerts only run while SLOs are enabled. Co-Authored-By: Claude Opus 5.5 --- .changeset/slo-alerts.md | 19 + packages/api/src/controllers/sloStatus.ts | 57 ++- .../routers/api/__tests__/slos.int.test.ts | 75 ++- .../__tests__/checkAlertsTask.test.ts | 1 + .../__tests__/renderAlertTemplate.int.test.ts | 203 ++++++++ .../__tests__/sloEvaluator.test.ts | 478 ++++++++++++++++++ .../api/src/tasks/checkAlerts/evaluators.ts | 19 +- packages/api/src/tasks/checkAlerts/index.ts | 55 +- .../tasks/checkAlerts/providers/default.ts | 70 ++- .../src/tasks/checkAlerts/providers/index.ts | 19 + .../api/src/tasks/checkAlerts/sloEvaluator.ts | 262 ++++++++++ .../api/src/tasks/checkAlerts/template.ts | 156 +++++- 12 files changed, 1395 insertions(+), 19 deletions(-) create mode 100644 .changeset/slo-alerts.md create mode 100644 packages/api/src/tasks/checkAlerts/__tests__/sloEvaluator.test.ts create mode 100644 packages/api/src/tasks/checkAlerts/sloEvaluator.ts diff --git a/.changeset/slo-alerts.md b/.changeset/slo-alerts.md new file mode 100644 index 0000000000..b4a0cfc8c9 --- /dev/null +++ b/.changeset/slo-alerts.md @@ -0,0 +1,19 @@ +--- +'@hyperdx/api': patch +'@hyperdx/common-utils': patch +--- + +feat: SLO fast and slow burn alerts as their own alert source + +An SLO can have a fast burn and a slow burn alert, each an alert with the +new `slo` source and its own channels, kept in sync with the SLO. Fast burn +fires when 2% of the error budget is spent within an hour, slow burn when +5% is spent within six hours, and each needs its last 5 or 30 minutes to +burn as fast, so it resolves soon after a burn stops. Each notifies once +when it starts firing and once when it resolves, and its message names the +rule and states the numbers. A grouped SLO's alerts fire and resolve for +each group with enough events, and their notifications name the group and +link to it. Each check also stores the burn rates on the SLO, so the SLO +list shows the alerts' own verdict. SLO alerts are changed from their SLO, +stay out of the external alerts API, and only run while SLOs are enabled. +Deleting one from the Alerts page turns that alert off on its SLO. diff --git a/packages/api/src/controllers/sloStatus.ts b/packages/api/src/controllers/sloStatus.ts index f42680e8f0..58bb30556c 100644 --- a/packages/api/src/controllers/sloStatus.ts +++ b/packages/api/src/controllers/sloStatus.ts @@ -1,6 +1,12 @@ import PQueue from '@esm2cjs/p-queue'; import { withQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node'; import { getSloWindowRange } from '@hyperdx/common-utils/dist/core/slo'; +import { + compareSloGroupsWorstFirst, + deriveGroupedSloState, + deriveSloGroupState, + deriveSloState, +} from '@hyperdx/common-utils/dist/core/sloStats'; import type { SloStatus } from '@hyperdx/common-utils/dist/slo'; import { getSloQueryContext } from '@/controllers/slo'; @@ -21,7 +27,12 @@ import { } from '@/utils/instrumentation'; import logger from '@/utils/logger'; -/** How old the burn numbers get before the refresh recomputes them. */ +/** + * How old the burn numbers get before the refresh recomputes them. Each + * check of an ungrouped SLO's burn alerts writes them too, so the refresh + * fills in only when no alert check did in the last 5 minutes. A grouped + * SLO's alerts write only their groups' numbers. + */ const SLO_BURN_MAX_AGE_MS = 5 * 60 * 1000; /** * How old the window numbers (SLI, budget) get. Their query reads the whole @@ -43,6 +54,50 @@ const refreshCounter = getCounter('hyperdx.slo.refresh', { description: 'SLO status refreshes, by outcome', }); +/** + * Stores the burn numbers an SLO's alert check computed, so the list shows + * the alert's own verdict: for an ungrouped SLO its burn numbers, for a + * grouped one each group's. The window numbers stay as the refresh stored + * them; until it has, there is nothing to add to. Returns the stored + * snapshot. + */ +export async function recordSloAlertBurn( + slo: ISlo, + burn: Partial, + now: Date, +): Promise { + const previous = slo.status; + if (previous?.windowEvaluatedAt == null) return null; + const groups = previous.groups + ?.map(group => { + const groupBurn = burn.groups?.get(group.value); + if (groupBurn == null) return group; + const next = { ...group, burn: groupBurn }; + return { ...next, state: deriveSloGroupState(next) }; + }) + .sort(compareSloGroupsWorstFirst); + const overall = { ...previous, burn: burn.burn ?? previous.burn }; + const status: SloStatus = { + ...overall, + // Only new overall burn numbers make the snapshot's burn part fresh. + evaluatedAt: burn.burn != null ? now.toISOString() : previous.evaluatedAt, + ...(groups != null ? { groups } : {}), + // A failing window query keeps its error until the refresh clears it. + state: + previous.state === 'error' + ? 'error' + : groups != null + ? deriveGroupedSloState(overall, groups) + : deriveSloState(overall), + }; + await Slo.updateOne( + { _id: slo._id, updatedAt: slo.updatedAt }, + { $set: { status } }, + { timestamps: false }, + ); + return status; +} + const getErrorMessage = (e: unknown) => e instanceof Error ? e.message : String(e); diff --git a/packages/api/src/routers/api/__tests__/slos.int.test.ts b/packages/api/src/routers/api/__tests__/slos.int.test.ts index a390524547..f3ba0a2512 100644 --- a/packages/api/src/routers/api/__tests__/slos.int.test.ts +++ b/packages/api/src/routers/api/__tests__/slos.int.test.ts @@ -2,7 +2,10 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import * as config from '@/config'; -import { refreshDueSloStatuses } from '@/controllers/sloStatus'; +import { + recordSloAlertBurn, + refreshDueSloStatuses, +} from '@/controllers/sloStatus'; import { bulkInsertData, DEFAULT_DATABASE, @@ -233,6 +236,76 @@ describe('SLO router', () => { }); }); + it("keeps an alert check's burn numbers beside the refresh's window numbers", async () => { + // Thirty good spans: the window alone is healthy. + const service = `${SERVICE}-alert`; + const now = Date.now(); + await bulkInsertData( + `${DEFAULT_DATABASE}.${DEFAULT_TRACES_TABLE}`, + Array.from({ length: 30 }, (_, i) => ({ + Timestamp: new Date(now - (i + 1) * 60_000), + TraceId: `${service}-trace-${i}`, + SpanId: `${service}-span-${i}`, + ParentSpanId: '', + SpanName: 'POST /checkout', + SpanKind: 'Server', + ServiceName: service, + Duration: 100 * 1e6, + StatusCode: 'Ok', + StatusMessage: '', + SpanAttributes: {}, + ResourceAttributes: {}, + })), + ); + const created = await agent + .post('/slos') + .send( + definition({ + indicator: { + template: 'availability', + eligible: { + where: `ServiceName = '${service}'`, + whereLanguage: 'sql', + }, + good: "StatusCode != 'Error'", + }, + }), + ) + .expect(200); + const burn = [ + { + rule: 'fastBurn' as const, + window: '1h' as const, + shortWindow: '5m' as const, + budgetSpent: 0.02, + minEvents: 20, + threshold: 14.4, + eligible: 100, + bad: 50, + burnRate: 50, + shortBurnRate: 50, + }, + ]; + const at = new Date(now + 60_000); + // Nothing to add to before the refresh stored window numbers. + const before = await Slo.findById(created.body.id).lean(); + expect(await recordSloAlertBurn(before!, { burn }, at)).toBeNull(); + + await refreshDueSloStatuses(); + const slo = await Slo.findById(created.body.id).lean(); + expect(slo?.status?.state).toBe('healthy'); + await recordSloAlertBurn(slo!, { burn }, at); + const { body } = await agent.get(`/slos/${created.body.id}`).expect(200); + expect(body.status).toMatchObject({ + burn, + evaluatedAt: at.toISOString(), + windowEvaluatedAt: slo!.status!.windowEvaluatedAt, + eligible: 30, + // The alert's burn numbers turn the healthy window into burning. + state: 'burning', + }); + }); + it('tracks each group of a grouped SLO, the worst first', async () => { // One service with every span good, one with a third of them bad, and // one with too few spans to judge. diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts index c9d2123950..3fc91fe696 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts @@ -179,6 +179,7 @@ describe('CheckAlertTask', () => { asyncDispose: jest.fn(), buildChartLink: jest.fn(), buildChartExplorerLink: jest.fn(), + buildSloLink: jest.fn(), buildLogSearchLink: jest.fn(), getClickHouseClient: jest .fn() diff --git a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts index 266af03eee..f1598e6d7b 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts @@ -1,3 +1,5 @@ +import { computeSloStats } from '@hyperdx/common-utils/dist/core/sloStats'; +import type { SloBurnStats, SloStatus } from '@hyperdx/common-utils/dist/slo'; import { AlertState, AlertThresholdType, @@ -16,6 +18,7 @@ import { RAW_SQL_ALERT_TEMPLATE, } from '@/fixtures'; import { AlertSource } from '@/models/alert'; +import type { ISlo } from '@/models/slo'; import type { IWebhook } from '@/models/webhook'; import { NotificationDispatcher, @@ -24,6 +27,7 @@ import { import { loadProvider } from '@/tasks/checkAlerts/providers'; import { AlertMessageTemplateDefaultView, + buildAlertMessageTemplateHdxLink, buildAlertMessageTemplateTitle, renderAlertTemplate, } from '@/tasks/checkAlerts/template'; @@ -1223,3 +1227,202 @@ describe('notification targets are resolved once per webhook', () => { expect(String(failures[0].error)).toContain('not a webhook channel'); }); }); + +describe('SLO alerts', () => { + const sloId = new mongoose.Types.ObjectId(); + + /** Both rules' numbers, with each long and short window at its rate. */ + const burn = (fastRate: number, slowRate = 1): SloBurnStats[] => [ + { + rule: 'fastBurn', + window: '1h', + shortWindow: '5m', + budgetSpent: 0.02, + minEvents: 20, + threshold: 14.4, + eligible: 1000, + bad: fastRate * 5, + burnRate: fastRate, + shortBurnRate: fastRate, + }, + { + rule: 'slowBurn', + window: '6h', + shortWindow: '30m', + budgetSpent: 0.05, + minEvents: 100, + threshold: 6, + eligible: 6000, + bad: slowRate * 30, + burnRate: slowRate, + shortBurnRate: slowRate, + }, + ]; + + /** + * Stats over 100,000 events against a 0.5% budget (500 bad events), with + * `budgetRemaining` of it left. + */ + const stats = (budgetRemaining: number, rate: number) => + computeSloStats( + { eligible: 100_000, good: 100_000 - (1 - budgetRemaining) * 500 }, + burn(rate), + 99.5, + ); + + const status: SloStatus = { + ...stats(0.9, 1), + state: 'healthy', + evaluatedAt: endTime.toISOString(), + windowStart: startTime.toISOString(), + windowEnd: endTime.toISOString(), + durationMs: 0, + rowsRead: 0, + }; + + const slo: ISlo = { + _id: sloId, + team: new mongoose.Types.ObjectId(), + source: new mongoose.Types.ObjectId(), + version: 1, + name: 'Checkout availability', + tags: [], + indicator: { + template: 'availability', + eligible: { where: "SpanKind = 'Server'", whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, + target: 99.5, + window: '30d', + alerts: {}, + status, + createdAt: startTime, + updatedAt: startTime, + }; + + const groupedSlo: ISlo = { + ...slo, + groupBy: 'ServiceName', + status: { + ...status, + groups: [ + { ...stats(0.25, 40), value: 'checkout', state: 'burning' }, + { ...stats(1, 0), value: 'cart', state: 'healthy' }, + ], + }, + }; + + const makeSloView = ( + overrides: Partial = {}, + rule: 'fastBurn' | 'slowBurn' = 'fastBurn', + ): AlertMessageTemplateDefaultView => ({ + alert: { + source: AlertSource.SLO, + sloRule: rule, + displayName: 'Checkout availability', + thresholdType: AlertThresholdType.ABOVE, + threshold: 1, + channel: { type: null }, + interval: rule === 'slowBurn' ? '15m' : '5m', + }, + attributes: {}, + endTime, + granularity: '5 minute', + isGroupedAlert: false, + slo, + startTime, + value: 1.38, + ...overrides, + }); + + const checkout = { + slo: groupedSlo, + group: 'ServiceName:checkout', + isGroupedAlert: true, + }; + + it('states what the fast burn alert saw and when it fires', async () => { + const view = makeSloView({ sloBurn: burn(20) }); + const body = await render(view, AlertState.ALERT); + expect(body).not.toContain('Group:'); + // 20x for an hour of a 30-day window: 20 / 720 of the budget. + expect(body).toContain( + 'Fast burn: 2.8% of the 30-day error budget was spent in the last ' + + 'hour (20x the allowed rate), and the last 5 minutes burned at 20x. ' + + 'It fires when 2% of the 30-day error budget is spent within 1 hour ' + + '(14.4x the allowed rate) and the last 5 minutes burn as fast. ' + + 'Error budget left: 90%.', + ); + expect( + buildAlertMessageTemplateTitle({ view, state: AlertState.ALERT }), + ).toBe( + 'SLO "Checkout availability": fast burn, 2.8% of the 30-day budget spent in the last hour', + ); + }); + + it('states the slow burn of the slow burn alert', async () => { + const overspent: ISlo = { + ...slo, + status: { ...status, ...stats(-0.2, 1) }, + }; + const view = makeSloView( + { slo: overspent, sloBurn: burn(1, 7) }, + 'slowBurn', + ); + const body = await render(view, AlertState.ALERT); + expect(body).toContain( + 'Slow burn: 5.8% of the 30-day error budget was spent in the last 6 ' + + 'hours (7x the allowed rate), and the last 30 minutes burned at 7x. ' + + 'It fires when 5% of the 30-day error budget is spent within 6 ' + + 'hours (6x the allowed rate) and the last 30 minutes burn as fast. ' + + 'The error budget for the window is spent.', + ); + expect( + buildAlertMessageTemplateTitle({ view, state: AlertState.ALERT }), + ).toBe( + 'SLO "Checkout availability": slow burn, 5.8% of the 30-day budget spent in the last 6 hours', + ); + }); + + it("names the group of a grouped SLO and states the group's numbers", async () => { + const view = makeSloView({ ...checkout, sloBurn: burn(40) }); + const body = await render(view, AlertState.ALERT); + expect(body).toContain('Group: "ServiceName:checkout"'); + expect(body).toContain('Fast burn: 5.6% of the 30-day error budget'); + expect(body).toContain('Error budget left: 25%.'); + expect( + buildAlertMessageTemplateTitle({ view, state: AlertState.ALERT }), + ).toBe( + 'SLO "Checkout availability" (ServiceName:checkout): fast burn, 5.6% of the 30-day budget spent in the last hour', + ); + expect( + buildAlertMessageTemplateTitle({ + view: makeSloView(checkout), + state: AlertState.OK, + }), + ).toBe( + 'SLO "Checkout availability" (ServiceName:checkout): fast burn resolved', + ); + }); + + it('links to the bad events of the window, for the group', () => { + const link = new URL( + buildAlertMessageTemplateHdxLink(alertProvider, makeSloView(checkout)), + ); + expect(link.pathname).toBe(`/slos/${sloId}`); + expect(Object.fromEntries(link.searchParams)).toEqual({ + bad: 'custom', + from: String(startTime.getTime()), + to: String(endTime.getTime()), + group: 'checkout', + }); + // A group of what the SLO was grouped by before links to the whole SLO. + const stale = new URL( + buildAlertMessageTemplateHdxLink( + alertProvider, + makeSloView({ ...checkout, group: 'SpanName:GET /cart' }), + ), + ); + expect(stale.searchParams.has('group')).toBe(false); + }); +}); diff --git a/packages/api/src/tasks/checkAlerts/__tests__/sloEvaluator.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/sloEvaluator.test.ts new file mode 100644 index 0000000000..78b1b4eb71 --- /dev/null +++ b/packages/api/src/tasks/checkAlerts/__tests__/sloEvaluator.test.ts @@ -0,0 +1,478 @@ +import { tryOptimizeConfigWithMaterializedView } from '@hyperdx/common-utils/dist/core/materializedViews'; +import { Types } from 'mongoose'; + +import { recordSloAlertBurn } from '@/controllers/sloStatus'; +import { AlertState } from '@/models/alert'; +import { processAlert } from '@/tasks/checkAlerts'; +import { findAlertEvaluator } from '@/tasks/checkAlerts/evaluators'; +import { AlertTaskType } from '@/tasks/checkAlerts/providers'; +import { SLO_BURN_RATE_EVALUATOR_NAME } from '@/tasks/checkAlerts/sloEvaluator'; +import * as template from '@/tasks/checkAlerts/template'; + +jest.mock('@hyperdx/common-utils/dist/core/materializedViews', () => ({ + tryOptimizeConfigWithMaterializedView: jest.fn( + async (config: Record) => ({ ...config, optimized: true }), + ), +})); + +// The stored snapshot is the refresh's; here it only echoes the burn numbers. +jest.mock('@/controllers/sloStatus', () => ({ + recordSloAlertBurn: jest.fn( + async (_slo: unknown, numbers: { burn?: unknown }) => ({ + burn: numbers.burn, + budgetRemaining: 0.5, + }), + ), +})); + +const source: any = { + _id: 'source-1', + id: 'source-1', + kind: 'trace', + connection: 'connection-1', + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', +}; + +const slo: any = { + _id: new Types.ObjectId(), + name: 'Checkout availability', + target: 99.5, + window: '30d', + alerts: { + fastBurn: { channels: [{ type: 'webhook', webhookId: 'w' }] }, + slowBurn: { channels: [{ type: 'webhook', webhookId: 'w' }] }, + }, + indicator: { + template: 'availability', + eligible: { where: "SpanKind = 'Server'", whereLanguage: 'sql' }, + good: "StatusCode != 'Error'", + }, +}; + +const makeAlert = (rule: 'fastBurn' | 'slowBurn' = 'fastBurn'): any => ({ + id: new Types.ObjectId().toString(), + team: new Types.ObjectId(), + source: 'slo', + slo: slo._id, + sloRule: rule, + // syncSloAlerts names the alert after its SLO. + displayName: 'Checkout availability', + interval: rule === 'slowBurn' ? '15m' : '5m', + threshold: 1, + thresholdType: 'above', + channel: { type: 'webhook', webhookId: 'w' }, + channels: [{ type: 'webhook', webhookId: 'w' }], +}); + +/** Where the burn query's range ends for a check at 01:07. */ +const END = Date.parse('2025-01-01T01:05:00Z'); + +/** 5-minute bucket rows that end at END, newest last. */ +const buckets = (counts: [eligible: number, good: number][]) => + counts.map(([eligible, good], i) => ({ + __hdx_time_bucket: new Date( + END - (counts.length - i) * 5 * 60_000, + ).toISOString(), + slo_eligible: String(eligible), + slo_good: String(good), + })); + +const repeat = (n: number, counts: [number, number]) => + Array.from({ length: n }, () => counts); + +/** Evaluates one SLO alert against the burn query's rows. */ +const evaluate = async ( + rows: Record[] | Error, + { + alert = makeAlert(), + alertSource = source, + previousMap = new Map(), + }: { + alert?: any; + alertSource?: any; + previousMap?: Map; + } = {}, +) => { + const provider: any = { + updateAlertState: jest.fn().mockResolvedValue(undefined), + recordAlertErrors: jest.fn().mockResolvedValue(undefined), + buildSloLink: jest.fn().mockReturnValue('http://app/slos/1'), + }; + const client: any = { + queryChartConfig: + rows instanceof Error + ? jest.fn().mockRejectedValue(rows) + : jest.fn().mockResolvedValue({ data: rows }), + requestTimeoutMs: 1000, + }; + await processAlert( + new Date('2025-01-01T01:07:00Z'), + { + alert, + previousMap, + taskType: AlertTaskType.SLO, + source: alertSource, + slo, + }, + client, + 'connection-1', + provider, + new Map(), + ); + const records = provider.updateAlertState.mock.calls[0]?.[1]; + return { client, provider, records }; +}; + +describe('SLO burn-rate evaluator', () => { + let render: jest.SpyInstance; + + beforeEach(() => { + slo.status = undefined; + jest.mocked(recordSloAlertBurn).mockClear(); + render = jest.spyOn(template, 'renderAlertTemplate').mockResolvedValue({ + body: '', + failures: [], + timings: [], + dispatchDurationMs: 0, + }); + }); + + afterEach(() => render.mockRestore()); + + it('is built in and owns SLO alerts', () => { + expect(findAlertEvaluator(makeAlert())?.name).toBe( + SLO_BURN_RATE_EVALUATOR_NAME, + ); + }); + + it('counts 5-minute buckets over the longest burn window, ending where the scheduled window ends', async () => { + const { client } = await evaluate(buckets([[1000, 1000]])); + const { config } = client.queryChartConfig.mock.calls[0][0]; + expect(config.dateRange).toEqual([ + new Date('2024-12-31T19:05:00Z'), + new Date('2025-01-01T01:05:00Z'), + ]); + expect(config.granularity).toBe('5 minute'); + }); + + it('fires a fast burn alert when an hour spends 2% of the budget', async () => { + // 10 bad of 100 per bucket against a 0.5% budget: a 20x burn, over the + // 14.4x of the fast burn. The value is how far over: 20 / 14.4. + const { records } = await evaluate(buckets(repeat(12, [100, 90]))); + expect(records).toEqual([ + expect.objectContaining({ + state: AlertState.ALERT, + fired: true, + lastValues: [expect.objectContaining({ count: 1.38 })], + }), + ]); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + state: AlertState.ALERT, + // 20x for an hour of a 30-day window: 20 / 720 of the budget. + title: + 'SLO "Checkout availability": fast burn, 2.8% of the 30-day budget spent in the last hour', + // The notification covers the rule's window. + view: expect.objectContaining({ + startTime: new Date('2025-01-01T00:05:00Z'), + }), + }), + ); + // The SLO list shows this check's verdict. + expect(recordSloAlertBurn).toHaveBeenCalledWith( + slo, + { + burn: [ + expect.objectContaining({ + window: '1h', + burnRate: expect.closeTo(20), + }), + expect.objectContaining({ + window: '6h', + burnRate: expect.closeTo(20), + }), + ], + }, + expect.any(Date), + ); + }); + + it('fires the slow burn alert, and only it, when a slower burn lasts', async () => { + // 3.5 bad of 100 for 6 hours: 7x, under the fast burn's 14.4x and over + // the slow burn's 6x. + const rows = buckets(repeat(72, [1000, 965])); + const slow = await evaluate(rows, { alert: makeAlert('slowBurn') }); + expect(slow.records).toEqual([ + expect.objectContaining({ + state: AlertState.ALERT, + lastValues: [expect.objectContaining({ count: 1.16 })], + }), + ]); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + title: + 'SLO "Checkout availability": slow burn, 5.8% of the 30-day budget spent in the last 6 hours', + // Checked every 15 minutes, so the window ends at 01:00. + view: expect.objectContaining({ + startTime: new Date('2024-12-31T19:00:00Z'), + }), + }), + ); + render.mockClear(); + const fast = await evaluate(rows, { alert: makeAlert('fastBurn') }); + expect(fast.records).toEqual([ + expect.objectContaining({ state: AlertState.OK }), + ]); + expect(render).not.toHaveBeenCalled(); + }); + + it('notifies once when a burn starts, not on every check', async () => { + const alert = makeAlert(); + const firing = (fired: boolean) => + new Map([ + [ + alert.id, + { + state: AlertState.ALERT, + fired, + createdAt: new Date('2025-01-01T01:00:00Z'), + }, + ], + ]); + const rows = buckets(repeat(12, [100, 90])); + const { records } = await evaluate(rows, { + alert, + previousMap: firing(true), + }); + expect(records).toEqual([ + expect.objectContaining({ state: AlertState.ALERT, fired: true }), + ]); + expect(render).not.toHaveBeenCalled(); + // A silence kept the start from notifying: the first check after it + // ends does. + await evaluate(rows, { alert, previousMap: firing(false) }); + expect(render).toHaveBeenCalledTimes(1); + }); + + it('states its burn numbers before the SLO has a stored snapshot', async () => { + // Right after a save, the refresh may not have stored window numbers. + jest.mocked(recordSloAlertBurn).mockResolvedValueOnce(null); + await evaluate(buckets(repeat(12, [100, 90]))); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + title: + 'SLO "Checkout availability": fast burn, 2.8% of the 30-day budget spent in the last hour', + }), + ); + }); + + it('lets a materialized view of the source serve its query', async () => { + const withView = { + ...source, + materializedViews: [ + { databaseName: 'otel', tableName: 'otel_traces_1m' }, + ], + }; + const { client } = await evaluate(buckets([[1000, 1000]]), { + alertSource: withView, + }); + expect(tryOptimizeConfigWithMaterializedView).toHaveBeenCalled(); + expect(client.queryChartConfig.mock.calls[0][0].config).toEqual( + expect.objectContaining({ optimized: true }), + ); + }); + + it('stays OK once the short windows stop burning', async () => { + // A burn in the first half of the hour: both long windows still remember + // it, the last 5 and 30 minutes are clean. + const { records } = await evaluate( + buckets([...repeat(6, [100, 80]), ...repeat(6, [100, 100])]), + ); + expect(records).toEqual([ + expect.objectContaining({ state: AlertState.OK }), + ]); + expect(render).not.toHaveBeenCalled(); + }); + + it('records a failed query as a query error, leaving the state alone', async () => { + const { provider, records } = await evaluate( + new Error('Unknown expression identifier `StatusCod`'), + ); + expect(records).toBeUndefined(); + expect(provider.recordAlertErrors).toHaveBeenCalledWith( + expect.any(String), + [ + expect.objectContaining({ + type: 'QUERY_ERROR', + message: expect.stringContaining('StatusCod'), + }), + ], + ); + }); + + it('stays OK below the thresholds or with too few events', async () => { + // 2 bad of 100 for 6 hours: 4x, under both thresholds. + const slow = await evaluate(buckets(repeat(72, [100, 98]))); + expect(slow.records).toEqual([ + expect.objectContaining({ state: AlertState.OK }), + ]); + // 5 of 10 bad is a 100x burn, but under the 20-event minimum for 1h and + // the 100-event minimum for 6h. + const quiet = await evaluate(buckets([[10, 5]])); + expect(quiet.records).toEqual([ + expect.objectContaining({ state: AlertState.OK }), + ]); + }); + describe('for a grouped SLO', () => { + /** Rows of the burn query by group, for one group. */ + const groupBuckets = ( + value: string, + counts: [eligible: number, good: number][], + ) => buckets(counts).map(row => ({ ...row, slo_group: value })); + + /** A group the status refresh tracks, with its window events. */ + const tracked = (value: string, eligible = 10_000) => ({ + value, + eligible, + good: eligible, + burn: [], + state: 'healthy', + }); + + /** A history of the previous check, which alerted. */ + const alerted = (groupValues?: { key: string; value: string }[]) => ({ + state: AlertState.ALERT, + fired: true, + createdAt: new Date('2025-01-01T01:00:00Z'), + ...(groupValues ? { groupValues } : {}), + }); + + beforeEach(() => { + slo.groupBy = 'ServiceName'; + slo.status = { + groups: [tracked('checkout'), tracked('cart'), tracked('canary', 50)], + }; + }); + + afterEach(() => { + slo.groupBy = undefined; + }); + + it('waits until the status refresh has picked the groups', async () => { + slo.status = undefined; + const { client, provider, records } = await evaluate( + groupBuckets('checkout', repeat(12, [100, 90])), + ); + expect(client.queryChartConfig).not.toHaveBeenCalled(); + expect(records).toBeUndefined(); + expect(provider.recordAlertErrors).toHaveBeenCalledWith( + expect.any(String), + [], + ); + }); + + it('fires for each burning group with enough events, naming the group', async () => { + const { client, records } = await evaluate([ + // 20x, as above. + ...groupBuckets('checkout', repeat(12, [100, 90])), + ...groupBuckets('cart', repeat(12, [100, 100])), + // 100x, but too few events in the window to judge. + ...groupBuckets('canary', repeat(12, [100, 50])), + ]); + // By group, for the tracked groups only. + const { config } = client.queryChartConfig.mock.calls[0][0]; + expect(config.filters).toContainEqual({ + type: 'sql', + condition: "toString(ServiceName) IN ('checkout', 'cart', 'canary')", + }); + expect(records).toHaveLength(3); + expect(records).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + group: 'ServiceName:checkout', + state: AlertState.ALERT, + groupValues: [{ key: 'ServiceName', value: 'checkout' }], + }), + expect.objectContaining({ + group: 'ServiceName:cart', + state: AlertState.OK, + }), + expect.objectContaining({ + group: 'ServiceName:canary', + state: AlertState.OK, + }), + ]), + ); + expect(render).toHaveBeenCalledTimes(1); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + title: + 'SLO "Checkout availability" (ServiceName:checkout): fast burn, 2.8% of the 30-day budget spent in the last hour', + view: expect.objectContaining({ + group: 'ServiceName:checkout', + isGroupedAlert: true, + attributes: { ServiceName: 'checkout' }, + }), + }), + ); + // Each tracked group's burn numbers go to the SLO list. + const [, stored] = jest.mocked(recordSloAlertBurn).mock.calls[0]; + expect([...(stored.groups?.keys() ?? [])]).toEqual([ + 'checkout', + 'cart', + 'canary', + ]); + expect(stored.burn).toBeUndefined(); + }); + + it('resolves a group that alerted and is no longer tracked', async () => { + const alert = makeAlert(); + const { records } = await evaluate( + groupBuckets('cart', repeat(12, [100, 100])), + { + alert, + previousMap: new Map([ + [ + `${alert.id}||ServiceName:retired`, + alerted([{ key: 'ServiceName', value: 'retired' }]), + ], + ]), + }, + ); + expect(records).toContainEqual( + expect.objectContaining({ + group: 'ServiceName:retired', + state: AlertState.OK, + }), + ); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + state: AlertState.OK, + title: + 'SLO "Checkout availability" (ServiceName:retired): fast burn resolved', + view: expect.objectContaining({ + attributes: { ServiceName: 'retired' }, + }), + }), + ); + }); + + it('resolves the whole SLO once it is grouped', async () => { + const alert = makeAlert(); + const { records } = await evaluate( + groupBuckets('cart', repeat(12, [100, 100])), + { alert, previousMap: new Map([[alert.id, alerted()]]) }, + ); + expect(records).toContainEqual( + expect.objectContaining({ group: undefined, state: AlertState.OK }), + ); + expect(render).toHaveBeenCalledWith( + expect.objectContaining({ + state: AlertState.OK, + title: 'SLO "Checkout availability": fast burn resolved', + }), + ); + }); + }); +}); diff --git a/packages/api/src/tasks/checkAlerts/evaluators.ts b/packages/api/src/tasks/checkAlerts/evaluators.ts index c2504fffdb..d07fb42697 100644 --- a/packages/api/src/tasks/checkAlerts/evaluators.ts +++ b/packages/api/src/tasks/checkAlerts/evaluators.ts @@ -1,5 +1,6 @@ import type { ClickhouseClient } from '@hyperdx/common-utils/dist/clickhouse/node'; import type { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; +import type { SloBurnStats } from '@hyperdx/common-utils/dist/slo'; import type { ChartConfigWithOptDateRange } from '@hyperdx/common-utils/dist/types'; import { registerExtensions } from '@/extensions'; @@ -14,6 +15,7 @@ import type { AlertDetails, AlertProvider, } from '@/tasks/checkAlerts/providers'; +import { sloBurnRateEvaluator } from '@/tasks/checkAlerts/sloEvaluator'; /** * Internal extension point, not a stable API: members follow processAlert and @@ -53,6 +55,8 @@ export interface AlertEvaluationContext { group: string; startTime?: Date; attributes?: Record; + /** SLO alerts: this check's burn numbers, which the message states. */ + sloBurn?: SloBurnStats[]; }) => Promise; sendNotificationIfResolved: ( previousHistory: AggregatedAlertHistory | undefined, @@ -125,13 +129,22 @@ const ensureExtensionsRegistered = () => { extensionsRegistered = true; }; -/** The registered evaluator for this alert, or undefined for the threshold - * path. */ +/** + * Evaluators that ship with the API, checked before extensions. Built on + * call: the SLO evaluator imports the task module, which imports this one, + * so a list built at load time could catch it half loaded. + */ +const builtInEvaluators = (): AlertEvaluator[] => [sloBurnRateEvaluator]; + +/** The evaluator for this alert, or undefined for the threshold path. */ export const findAlertEvaluator = ( alert: IAlert, ): AlertEvaluator | undefined => { ensureExtensionsRegistered(); - return evaluators.find(e => e.appliesTo(alert)); + return ( + builtInEvaluators().find(e => e.appliesTo(alert)) ?? + evaluators.find(e => e.appliesTo(alert)) + ); }; /** @internal Test helper. Extensions are not registered again afterwards. */ diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 4e1f06eebf..26c4c8d2c9 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -22,6 +22,10 @@ import { ALERT_COUNT_DEFAULT_SELECT, buildSearchChartConfig, } from '@hyperdx/common-utils/dist/core/searchChartConfig'; +import { + buildSloBurnChartConfig, + getSloGroupBy, +} from '@hyperdx/common-utils/dist/core/slo'; import { aliasMapToWithClauses, displayTypeSupportsBuilderAlerts, @@ -36,6 +40,7 @@ import { isRawSqlChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import type { SloBurnStats } from '@hyperdx/common-utils/dist/slo'; import { ALERT_NOTIFICATION_TARGETS_LIMIT, AlertErrorType, @@ -70,6 +75,7 @@ import AlertHistory, { } from '@/models/alertHistory'; import { IDashboard } from '@/models/dashboard'; import { ISavedSearch } from '@/models/savedSearch'; +import { ISlo } from '@/models/slo'; import { ISource } from '@/models/source'; import { IWebhook } from '@/models/webhook'; import { @@ -157,6 +163,10 @@ export const alertHasGroupBy = ( // AlertChartConfig members are the tile config types minus the embedded // alert field, so they're assignable to SavedChartConfig (which the // chart-config guards narrow on). + // A grouped SLO's alert keeps a state for each group the SLO tracks. + if (details.taskType === AlertTaskType.SLO) { + return getSloGroupBy(details.slo) != null; + } const savedConfig: SavedChartConfig | undefined = details.taskType === AlertTaskType.TILE ? details.tile.config @@ -249,7 +259,7 @@ const QUERY_TIMEOUT_RETRY_NOTE = * (client request timeout/abort, server-side TIMEOUT_EXCEEDED, socket * timeouts) separately from other query errors so the message is actionable. */ -const makeQueryAlertError = ( +export const makeQueryAlertError = ( e: unknown, requestTimeoutMs: number, ): IAlertError => { @@ -504,6 +514,8 @@ const fireChannelEvent = async ({ isGroupedAlert, metadata, savedSearch, + slo, + sloBurn, source, startTime, state, @@ -522,6 +534,8 @@ const fireChannelEvent = async ({ isGroupedAlert: boolean; metadata: Metadata; savedSearch?: ISavedSearch | null; + slo?: ISlo | null; + sloBurn?: SloBurnStats[] | null; source?: ISource | null; startTime: Date; state: AlertState; @@ -568,6 +582,8 @@ const fireChannelEvent = async ({ thresholdMax: alert.thresholdMax, thresholdType: alert.thresholdType, tileId: alert.tileId, + // SLO alerts: which of the SLO's burn alerts sent the message. + sloRule: alert.sloRule, // Inline alerts: the persisted config, used to build the explorer link // and the default notification title. chartConfig: alert.chartConfig, @@ -579,6 +595,8 @@ const fireChannelEvent = async ({ group, isGroupedAlert, savedSearch, + slo, + sloBurn, source, startTime, value: totalCount, @@ -589,7 +607,7 @@ const fireChannelEvent = async ({ clickhouseClient, metadata, state, - title: buildAlertMessageTemplateTitle({ view: templateView }), + title: buildAlertMessageTemplateTitle({ view: templateView, state }), template: alert.message, view: templateView, teamId, @@ -631,7 +649,10 @@ export const computeHistoryMapKey = ( * Safely handles group names that may contain colons or other special characters * by using the alert ID prefix with the delimiter to identify the split point. */ -const extractGroupKeyFromMapKey = (mapKey: string, alertId: string): string => { +export const extractGroupKeyFromMapKey = ( + mapKey: string, + alertId: string, +): string => { const alertIdPrefix = getAlertKeyPrefix(alertId); return mapKey.startsWith(alertIdPrefix) ? mapKey.substring(alertIdPrefix.length) @@ -910,6 +931,23 @@ const getChartConfigFromAlert = ( if (config != null) { return config; } + } else if (details.taskType === AlertTaskType.SLO) { + // SLO alerts count eligible and good events per 5 minutes over the + // burn rule's longest window, ending where the scheduled window ends; + // the SLO evaluator sums each condition's windows from the buckets. A + // grouped SLO's alert counts by group, for the groups the SLO tracks. + const { slo, source } = details; + const scope = + getSloGroupBy(slo) != null + ? { + byGroup: true as const, + groups: slo.status?.groups?.map(g => g.value) ?? [], + } + : undefined; + return { + ...buildSloBurnChartConfig({ slo, source, now: dateRange[1], scope }), + connection, + }; } else if (details.taskType === AlertTaskType.INLINE) { // Inline alerts have no dashboard, so no variables are declared. const config = buildAlertChartConfigFromSavedConfig({ @@ -1349,12 +1387,14 @@ export const processAlert = async ( state, startTime = nowInMinsRoundDown, attributes = {}, + sloBurn, }: { state: AlertState; totalCount: number; group: string; startTime?: Date; attributes?: Record; + sloBurn?: SloBurnStats[]; }): Promise => { // KNOWN LIMITATION: Alert data (including silenced state) is fetched when // the task is queued via AlertProvider, not when it processes. If a user @@ -1397,11 +1437,18 @@ export const processAlert = async ( clickhouseClient, dashboard: (details as any).dashboard, startTime, - endTime: fns.addMinutes(startTime, windowSizeInMins), + // An SLO alert's window is the burn window, which ends where the + // scheduled window ends. + endTime: + details.taskType === AlertTaskType.SLO + ? dateRange[1] + : fns.addMinutes(startTime, windowSizeInMins), group, isGroupedAlert: hasGroupBy, metadata, savedSearch: (details as any).savedSearch, + slo: details.taskType === AlertTaskType.SLO ? details.slo : null, + sloBurn, source, state, totalCount, diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index 6375960d5c..d8306077f2 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -29,6 +29,7 @@ import AlertHistory, { import Connection, { IConnection } from '@/models/connection'; import Dashboard from '@/models/dashboard'; import { type ISavedSearch, SavedSearch } from '@/models/savedSearch'; +import Slo from '@/models/slo'; import { type ISource, Source } from '@/models/source'; import Webhook, { IWebhook } from '@/models/webhook'; import { @@ -354,6 +355,42 @@ async function getInlineAlertDetails( ]; } +async function getSloAlertDetails( + alert: IAlert, +): Promise<[IConnection, PartialAlertDetails] | []> { + const slo = await Slo.findOne({ _id: alert.slo, team: alert.team }).lean(); + if (!slo) { + logger.error({ message: 'SLO not found for SLO alert', alertId: alert.id }); + return []; + } + const source = await Source.findOne({ + _id: slo.source, + team: alert.team, + }).populate & { connection: IConnection }>({ + path: 'connection', + match: { team: alert.team }, + select: '+password', + }); + if (!source?.connection) { + logger.error({ + message: 'source or connection not found for SLO alert', + alertId: alert.id, + sourceId: slo.source, + }); + return []; + } + const connection = source.connection; + return [ + connection, + { + alert, + source: { ...source.toObject(), connection: connection.id }, + taskType: AlertTaskType.SLO, + slo, + }, + ]; +} + async function resolveAlertDetails( alert: IAlert, ): Promise<[IConnection, PartialAlertDetails]> { @@ -382,6 +419,10 @@ async function resolveAlertDetails( [conn, details] = await getInlineAlertDetails(alert); break; + case AlertSource.SLO: + [conn, details] = await getSloAlertDetails(alert); + break; + default: throw new Error(`unsupported source: ${alert.source}`); } @@ -400,9 +441,11 @@ async function resolveAlertDetails( async function loadAlerts(): Promise { const groupedTasks = new Map(); - // SLO alerts are not evaluated yet: skip them rather than fail to load - // them. - const alerts = await Alert.find({ source: { $ne: AlertSource.SLO } }); + // SLO alerts only run while SLOs are enabled: turning the feature off + // also stops their notifications. + const alerts = await Alert.find( + config.IS_SLOS_ENABLED ? {} : { source: { $ne: AlertSource.SLO } }, + ); const now = new Date(); @@ -636,6 +679,27 @@ export default class DefaultAlertProvider implements AlertProvider { return url.toString(); } + buildSloLink({ + sloId, + startTime, + endTime, + group, + }: { + sloId: string; + startTime: Date; + endTime: Date; + group?: string; + }): string { + const url = new URL(`${config.FRONTEND_URL}/slos/${sloId}`); + url.search = new URLSearchParams({ + bad: 'custom', + from: startTime.getTime().toString(), + to: endTime.getTime().toString(), + ...(group != null ? { group } : {}), + }).toString(); + return url.toString(); + } + buildChartExplorerLink({ chartConfig, endTime, diff --git a/packages/api/src/tasks/checkAlerts/providers/index.ts b/packages/api/src/tasks/checkAlerts/providers/index.ts index 96071696ed..0e07e37ce6 100644 --- a/packages/api/src/tasks/checkAlerts/providers/index.ts +++ b/packages/api/src/tasks/checkAlerts/providers/index.ts @@ -8,6 +8,7 @@ import { IAlertHistory, IAlertHistoryAnalytics } from '@/models/alertHistory'; import { IConnection } from '@/models/connection'; import { IDashboard } from '@/models/dashboard'; import { ISavedSearch } from '@/models/savedSearch'; +import { ISlo } from '@/models/slo'; import { ISource } from '@/models/source'; import { IWebhook } from '@/models/webhook'; import { AggregatedAlertHistory } from '@/tasks/checkAlerts'; @@ -18,6 +19,7 @@ export enum AlertTaskType { SAVED_SEARCH, TILE, INLINE, + SLO, } // Discriminated union of possible alert channel types with populated channel data @@ -57,6 +59,12 @@ export type AlertDetails = { source?: ISource; chartConfig: AlertChartConfig; } + | { + // Burn-rate alerts an SLO owns: the query comes from the SLO. + taskType: AlertTaskType.SLO; + source: ISource; + slo: ISlo; + } ); // AlertTask instances can carry metadata, of type T, for the provider that created @@ -88,6 +96,17 @@ export interface AlertProvider { tileId?: string; }): string; + /** + * Link for SLO alerts: the SLO page with the bad events of the window, for + * one group of a grouped SLO. + */ + buildSloLink(params: { + sloId: string; + startTime: Date; + endTime: Date; + group?: string; + }): string; + /** * Link for inline alerts (which have no saved search or dashboard to open): * the chart explorer with the alert's persisted config over the alerting diff --git a/packages/api/src/tasks/checkAlerts/sloEvaluator.ts b/packages/api/src/tasks/checkAlerts/sloEvaluator.ts new file mode 100644 index 0000000000..c231c9c1b8 --- /dev/null +++ b/packages/api/src/tasks/checkAlerts/sloEvaluator.ts @@ -0,0 +1,262 @@ +import { tryOptimizeConfigWithMaterializedView } from '@hyperdx/common-utils/dist/core/materializedViews'; +import { + getSloBurnQueryRange, + getSloGroupBy, + getSloGroupKey, +} from '@hyperdx/common-utils/dist/core/slo'; +import { + computeSloBurnFromRows, + computeSloGroupBurnFromRows, + getSloBurnSeverity, + isSloBurnConditionMet, +} from '@hyperdx/common-utils/dist/core/sloStats'; +import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; +import { + getSloBurnCondition, + getSloBurnWindowMs, + SLO_BURN_CONDITIONS, + SLO_GROUP_MIN_EVENTS, + type SloAlertRule, + type SloBurnStats, + type SloBurnWindow, +} from '@hyperdx/common-utils/dist/slo'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { performance } from 'perf_hooks'; +import { serializeError } from 'serialize-error'; + +import { recordSloAlertBurn } from '@/controllers/sloStatus'; +import type { SloBurnNumbers } from '@/controllers/sloStatusQueries'; +import { AlertSource, AlertState } from '@/models/alert'; +import { attributesToGroupValues, IAlertHistory } from '@/models/alertHistory'; +import type { ISlo } from '@/models/slo'; +import type { ISource } from '@/models/source'; +import { + computeHistoryMapKey, + extractGroupKeyFromMapKey, + makeQueryAlertError, +} from '@/tasks/checkAlerts'; +import type { + AlertEvaluationContext, + AlertEvaluator, +} from '@/tasks/checkAlerts/evaluators'; +import { AlertTaskType } from '@/tasks/checkAlerts/providers'; +import logger from '@/utils/logger'; + +export const SLO_BURN_RATE_EVALUATOR_NAME = 'slo_burn_rate'; + +/** What one check judges: the whole SLO, or one group of a grouped SLO. */ +type SloBurnCheck = { + /** The alert history key: empty for the whole SLO. */ + key: string; + burn: SloBurnStats[]; + /** False for a group with too few events in the window to judge. */ + alertable: boolean; + attributes: Record; +}; + +/** + * Runs the burn query, from a materialized view of the source when one + * covers it, as the SLO's other queries do: the context's config is + * unoptimized. A failure is recorded as a query error or timeout, as for + * threshold alerts, and returns null. + */ +async function queryBurnRows(ctx: AlertEvaluationContext, source: ISource) { + const queryStartedAt = performance.now(); + try { + const mvSource = + source.kind === SourceKind.Log || source.kind === SourceKind.Trace + ? source + : undefined; + const config = + isBuilderChartConfig(ctx.chartConfig) && + mvSource?.materializedViews?.length + ? await tryOptimizeConfigWithMaterializedView( + ctx.chartConfig, + ctx.metadata, + ctx.clickhouseClient, + undefined, + mvSource, + ) + : ctx.chartConfig; + const result = await ctx.clickhouseClient.queryChartConfig({ + config, + metadata: ctx.metadata, + querySettings: source.querySettings, + }); + return result.data; + } catch (e) { + ctx.executionErrors.push( + makeQueryAlertError(e, ctx.clickhouseClient.requestTimeoutMs), + ); + return null; + } finally { + ctx.evaluationAnalytics.queryDurationMs = Math.round( + performance.now() - queryStartedAt, + ); + } +} + +/** The checks for this run, with the burn numbers to store on the SLO. */ +function getSloBurnChecks( + slo: ISlo, + rows: Record[], + now: Date, +): { checks: SloBurnCheck[]; burn: Partial } { + const groupBy = getSloGroupBy(slo); + if (groupBy == null) { + const burn = computeSloBurnFromRows(rows, slo, now); + return { + checks: [{ key: '', burn, alertable: true, attributes: {} }], + burn: { burn }, + }; + } + const tracked = slo.status?.groups ?? []; + const groups = computeSloGroupBurnFromRows( + rows, + slo, + now, + tracked.map(g => g.value), + ); + return { + checks: tracked.map(group => ({ + key: getSloGroupKey(groupBy, group.value), + burn: groups.get(group.value) ?? [], + // The SLO shows such a group as insufficient data, and so it waits. + alertable: group.eligible >= SLO_GROUP_MIN_EVENTS, + attributes: { [groupBy]: group.value }, + })), + burn: { groups }, + }; +} + +/** The start of a burn window that ends at `end`. */ +const getBurnStart = ( + end: Date, + window: SloBurnWindow = SLO_BURN_CONDITIONS[0].window, +) => new Date(end.getTime() - getSloBurnWindowMs(window)); + +/** + * Records one check of this alert's rule, notifies when a burn starts, and + * returns the check's history. A burn that goes on notifies once, not on + * every check; the resolve notification follows the threshold path. + */ +async function runSloBurnCheck( + ctx: AlertEvaluationContext, + rule: SloAlertRule, + { key, burn, alertable, attributes }: SloBurnCheck, + end: Date, +): Promise { + // The burn numbers cover both rules; this alert fires on its own. + const condition = burn.find(c => c.rule === rule); + const value = condition ? getSloBurnSeverity([condition]) : 0; + const met = + alertable && condition != null && isSloBurnConditionMet(condition); + // The rule's long window is the period the notification links to. + const startTime = getBurnStart(end, getSloBurnCondition(rule).window); + const history = ctx.getOrCreateHistory(key); + history.lastValues.push({ count: value, startTime }); + const previous = ctx.previousMap.get(computeHistoryMapKey(ctx.alert.id, key)); + if (met) { + history.counts += 1; + history.state = AlertState.ALERT; + // A resolve names the group from the last history that alerted. + history.groupValues = attributesToGroupValues(attributes); + // Sent when the burn starts, or on the first check after a silence that + // held it back has ended. + const notified = + previous?.state === AlertState.ALERT && previous.fired === true; + history.fired = + notified || + (await ctx.trySendNotification({ + state: AlertState.ALERT, + group: key, + totalCount: value, + startTime, + attributes, + sloBurn: burn, + })); + } + await ctx.sendNotificationIfResolved(previous, history, key); + return history; +} + +/** + * Resolves what alerted before and is not checked now: a group the SLO no + * longer tracks, or the whole SLO's state once it is grouped (and each + * group's once it is not). + */ +async function resolveUnchecked( + ctx: AlertEvaluationContext, + checked: Set, + end: Date, +): Promise { + const histories: IAlertHistory[] = []; + for (const [mapKey, previous] of ctx.previousMap) { + const key = extractGroupKeyFromMapKey(mapKey, ctx.alert.id); + if ( + checked.has(key) || + // Not this alert's history. + mapKey !== computeHistoryMapKey(ctx.alert.id, key) || + (previous.state !== AlertState.ALERT && + previous.state !== AlertState.PENDING) + ) { + continue; + } + const history = ctx.getOrCreateHistory(key); + history.lastValues.push({ count: 0, startTime: getBurnStart(end) }); + await ctx.sendNotificationIfResolved(previous, history, key); + histories.push(history); + } + return histories; +} + +/** + * Evaluation of the fast and slow burn alerts an SLO owns. The chart config + * the provider builds counts eligible and good events per 5 minutes over the + * slow burn's 6 hours, by group for a grouped SLO, so each check computes + * both rules' numbers. The alert fires when its own rule's condition holds, + * for the SLO or for each of its groups with enough events, and resolves + * soon after the short window stops burning. Each check also stores the + * burn numbers on the SLO, so the SLO list shows the alerts' own verdict. + */ +export const sloBurnRateEvaluator: AlertEvaluator = { + name: SLO_BURN_RATE_EVALUATOR_NAME, + appliesTo: alert => alert.source === AlertSource.SLO, + evaluate: async ctx => { + const { alert, details } = ctx; + if (details.taskType !== AlertTaskType.SLO) { + throw new Error('SLO alert without SLO details'); + } + const { slo, source } = details; + // A grouped SLO's alert checks the groups its status tracks; until the + // status refresh has picked them, there is nothing to check. + if (getSloGroupBy(slo) != null && !slo.status?.groups?.length) return; + const rows = await queryBurnRows(ctx, source); + if (rows == null) return; + const now = ctx.chartConfig.dateRange?.[1] ?? ctx.dateRange[1]; + const end = getSloBurnQueryRange(now)[1]; + const { checks, burn } = getSloBurnChecks(slo, rows, now); + + try { + const status = await recordSloAlertBurn(slo, burn, new Date()); + // A resolve message reads the SLO's numbers, so they are this check's. + if (status != null) slo.status = status; + } catch (e) { + // The SLO list catches up on its next refresh; alerting goes on. + logger.error( + { error: serializeError(e), alertId: alert.id }, + 'Failed to store SLO burn numbers', + ); + } + + const rule = alert.sloRule ?? 'fastBurn'; + const histories: IAlertHistory[] = []; + for (const check of checks) { + histories.push(await runSloBurnCheck(ctx, rule, check, end)); + } + const checked = new Set(checks.map(c => c.key)); + histories.push(...(await resolveUnchecked(ctx, checked, end))); + ctx.evaluationAnalytics.backfilledBuckets = 0; + await ctx.persistHistories(histories); + }, +}; diff --git a/packages/api/src/tasks/checkAlerts/template.ts b/packages/api/src/tasks/checkAlerts/template.ts index 6f8507f68f..55d092e94b 100644 --- a/packages/api/src/tasks/checkAlerts/template.ts +++ b/packages/api/src/tasks/checkAlerts/template.ts @@ -3,21 +3,32 @@ import { Metadata } from '@hyperdx/common-utils/dist/core/metadata'; import { getPromqlSeries } from '@hyperdx/common-utils/dist/core/promql'; import { renderChartConfig } from '@hyperdx/common-utils/dist/core/renderChartConfig'; import { buildSearchChartConfig } from '@hyperdx/common-utils/dist/core/searchChartConfig'; +import { getSloGroupValue } from '@hyperdx/common-utils/dist/core/slo'; import { formatDate, objectHash, UTC_TIME_ZONE, } from '@hyperdx/common-utils/dist/core/utils'; +import { describeFilter } from '@hyperdx/common-utils/dist/filters'; import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { + describeSloAlertRule, + describeSloLastWindow, + formatSloWindowAdjective, + getSloAlertRuleLabel, + getSloBurnCondition, + getSloBurnWindowMs, + getSloWindowMs, + type SloBurnStats, +} from '@hyperdx/common-utils/dist/slo'; import { AlertChannelType, AlertThresholdType, BuilderChartConfigWithOptDateRange, ChartConfigWithOptDateRange, - Filter, isRangeThresholdType, SavedChartConfig, SourceKind, @@ -38,6 +49,7 @@ import { } from '@/models/alert'; import { IDashboard } from '@/models/dashboard'; import { ISavedSearch } from '@/models/savedSearch'; +import { ISlo } from '@/models/slo'; import { ISource } from '@/models/source'; import { IWebhook } from '@/models/webhook'; import { @@ -117,11 +129,6 @@ const describeThreshold = (alert: AlertInput): string => { : `${alert.threshold}`; }; -const describeFilter = (filter: Filter): string => - filter.type === 'sql_ast' - ? `${filter.left} ${filter.operator} ${filter.right}` - : filter.condition; - const joinConditions = (...parts: (string | undefined)[]): string => { const present = parts .map(part => part?.trim()) @@ -163,7 +170,18 @@ const describeSourceQuery = ( alert: AlertInput, savedSearch?: ISavedSearch | null, dashboard?: IDashboard | null, + slo?: ISlo | null, ): string => { + if (alert.source === AlertSource.SLO) { + // The eligible events; the burn rate is the share of them that is bad. + const eligible = slo?.indicator.eligible; + return eligible + ? joinConditions( + eligible.where, + ...(eligible.filters ?? []).map(describeFilter), + ) + : ''; + } if (alert.source === AlertSource.INLINE) { return alert.chartConfig ? describeChartConfigQuery(alert.chartConfig) : ''; } @@ -257,11 +275,93 @@ export type AlertMessageTemplateDefaultView = { group?: string; isGroupedAlert: boolean; savedSearch?: ISavedSearch | null; + /** SLO alerts: the SLO that owns the alert. */ + slo?: ISlo | null; + /** SLO alerts: the burn numbers of the check that sent the message. */ + sloBurn?: SloBurnStats[] | null; source?: ISource | null; startTime: Date; value: number; }; +const formatBurnRate = (rate: number | null) => + rate == null ? 'no events' : `${Math.round(rate * 100) / 100}x`; + +type SloMessageNumbers = { + burn: SloBurnStats[]; + budgetRemaining: number | null; +}; + +/** + * The numbers to state, for the group the message is about or the whole + * SLO: the check's own burn numbers, or the SLO's last stored ones when the + * message did not bring any (a resolve). + */ +const getSloMessageNumbers = ( + view: AlertMessageTemplateDefaultView, +): SloMessageNumbers => { + const status = view.slo?.status; + const group = + view.slo != null ? getSloGroupValue(view.slo, view.group) : undefined; + const numbers = + group != null ? status?.groups?.find(g => g.value === group) : status; + return { + burn: view.sloBurn ?? numbers?.burn ?? [], + budgetRemaining: numbers?.budgetRemaining ?? null, + }; +}; + +const formatShare = (share: number) => `${Math.round(share * 1000) / 10}%`; + +/** + * The burn alert that sent the message, and its rule's numbers: the share + * of the SLO window's budget spent in the rule's long window, at its burn + * rate. + */ +const getSloRuleMessage = (view: AlertMessageTemplateDefaultView) => { + const rule = view.alert.sloRule ?? 'fastBurn'; + const { burn, budgetRemaining } = getSloMessageNumbers(view); + const condition = burn.find(c => c.rule === rule); + const spent = + condition?.burnRate != null && view.slo != null + ? (condition.burnRate * getSloBurnWindowMs(condition.window)) / + getSloWindowMs(view.slo.window) + : null; + return { rule, condition, spent, budgetRemaining }; +}; + +/** What the burn alert saw, and when it fires. */ +const describeSloBurn = ( + slo: ISlo, + { + rule, + condition, + spent, + budgetRemaining, + }: ReturnType, +) => { + const { window, shortWindow } = getSloBurnCondition(rule); + const budget = `${formatSloWindowAdjective(slo.window)} error budget`; + return [ + condition != null && spent != null + ? `${getSloAlertRuleLabel(rule)}: ${formatShare(spent)} of the ` + + `${budget} was spent in ${describeSloLastWindow(window)} ` + + `(${formatBurnRate(condition.burnRate)} the allowed rate), and ` + + `${describeSloLastWindow(shortWindow)} burned at ` + + `${formatBurnRate(condition.shortBurnRate)}.` + : null, + `It fires when ${describeSloAlertRule(rule, slo.window)} and ` + + `${describeSloLastWindow(shortWindow)} burn as fast.`, + budgetRemaining == null + ? null + : budgetRemaining > 0 + ? `Error budget left: ${formatShare(budgetRemaining)}.` + : 'The error budget for the window is spent.', + ] + .filter(part => part != null) + .join(' '); +}; + export const isAlertResolved = (state?: AlertState): boolean => { return state === AlertState.OK; }; @@ -303,10 +403,23 @@ export const buildAlertMessageTemplateHdxLink = ( dashboard, endTime, granularity, + group, savedSearch, + slo, startTime, }: AlertMessageTemplateDefaultView, ) => { + if (alert.source === AlertSource.SLO) { + if (slo == null) { + throw new Error(`Source is ${alert.source} but slo is null`); + } + return alertProvider.buildSloLink({ + sloId: slo._id.toString(), + endTime, + startTime, + group: getSloGroupValue(slo, group), + }); + } if (alert.source === AlertSource.SAVED_SEARCH) { if (savedSearch == null) { throw new Error(`Source is ${alert.source} but savedSearch is null`); @@ -346,8 +459,11 @@ export const buildAlertMessageTemplateHdxLink = ( export const buildAlertMessageTemplateTitle = ({ view, + state, }: { view: AlertMessageTemplateDefaultView; + /** SLO titles follow the alert's state: its rule is not the value alone. */ + state?: AlertState; }) => { const { alert, dashboard, savedSearch, value } = view; const handlebars = createHandlebarsWithHelpers(); @@ -369,6 +485,25 @@ export const buildAlertMessageTemplateTitle = ({ dashboard, }); + if (alert.source === AlertSource.SLO) { + const { rule, spent } = getSloRuleMessage(view); + // A grouped SLO's message is about one of its groups. + const subject = + `SLO "${displayName}"${view.group ? ` (${view.group})` : ''}: ` + + getSloAlertRuleLabel(rule).toLowerCase(); + const { window } = getSloBurnCondition(rule); + return ( + renderedTemplate ?? + (state != null && isAlertResolved(state) + ? `${subject} resolved` + : subject + + (spent != null && view.slo != null + ? `, ${formatShare(spent)} of the ` + + `${formatSloWindowAdjective(view.slo.window)} budget spent in ` + + describeSloLastWindow(window) + : '')) + ); + } if (alert.source === AlertSource.SAVED_SEARCH) { if (savedSearch == null) { throw new Error(`Source is ${alert.source} but savedSearch is null`); @@ -764,7 +899,7 @@ export const renderAlertTemplate = async ({ groupKey: group ?? '', groupValues: groupValues ?? {}, sourceQuery: truncateString( - describeSourceQuery(alert, savedSearch, dashboard), + describeSourceQuery(alert, savedSearch, dashboard, view.slo), MAX_SOURCE_QUERY_LENGTH, ), teamId, @@ -936,6 +1071,13 @@ ${targetTemplate} \`\`\` {{{__hdx_query_results__}}} \`\`\``; + } else if (alert.source === AlertSource.SLO) { + if (view.slo == null) { + throw new Error(`Source is ${alert.source} but slo is null`); + } + rawTemplateBody = `{{#if group}}Group: "{{{group}}}" +{{/if}}${describeSloBurn(view.slo, getSloRuleMessage(view))}\n${timeRangeMessage} +${targetTemplate}`; } else if ( alert.source === AlertSource.TILE || alert.source === AlertSource.INLINE