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
19 changes: 19 additions & 0 deletions .changeset/slo-alerts.md
Original file line number Diff line number Diff line change
@@ -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.
57 changes: 56 additions & 1 deletion packages/api/src/controllers/sloStatus.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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
Expand All @@ -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<SloBurnNumbers>,
now: Date,
): Promise<SloStatus | null> {
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'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Error state outlives a successful burn check because the alert keeps evaluatedAt fresh

An ungrouped SLO's fast burn alert sets evaluatedAt to now every 5 minutes, but keeps state: 'error' when it is already error. The refresh only reruns when evaluatedAt is 5 minutes old or the window is 30 minutes old (SLO_WINDOW_MAX_AGE_MS). So a passing burn error keeps the SLO showing 'error' for up to 30 minutes, even though each alert check's burn query against the same source succeeds. Fix: when the burn numbers are fresh, re-derive the state, or clear the error if it came from the burn query, or skip updating evaluatedAt while state is 'error' so the refresh stays due.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

? 'error'
: groups != null
? deriveGroupedSloState(overall, groups)
: deriveSloState(overall),
};
await Slo.updateOne(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Alert's burn write-back can overwrite a newer refresh snapshot with stale window numbers

CheckAlertTask.execute (tasks/checkAlerts/index.ts:2458) starts refreshDueSloStatuses() at the same time as getAlertTasks(), so each alert holds a copy of slo.status read before the refresh wrote. recordSloAlertBurn then writes {...previous, burn} through $set: { status }. The only guard is updatedAt, which status writes never change (timestamps: false). The result is that a refresh's new window, groups, windowEvaluatedAt, or a just-cleared error gets reverted to the older copy. Fix: guard the update on the snapshot the alert read, e.g. add 'status.windowEvaluatedAt': previous.windowEvaluatedAt and 'status.state': previous.state to the filter. Better still, $set only status.burn, status.evaluatedAt, status.state and the per-group burn/state fields, so the window part is never rewritten.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

{ _id: slo._id, updatedAt: slo.updatedAt },
{ $set: { status } },
{ timestamps: false },
);
return status;
}

const getErrorMessage = (e: unknown) =>
e instanceof Error ? e.message : String(e);

Expand Down
75 changes: 74 additions & 1 deletion packages/api/src/routers/api/__tests__/slos.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ describe('CheckAlertTask', () => {
asyncDispose: jest.fn(),
buildChartLink: jest.fn(),
buildChartExplorerLink: jest.fn(),
buildSloLink: jest.fn(),
buildLogSearchLink: jest.fn(),
getClickHouseClient: jest
.fn()
Expand Down
Loading
Loading