From ded82092a9d4825a27bb8ef630bae32e052bc1d5 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:53:41 +0000 Subject: [PATCH 1/2] feat(api): refresh SLO statuses in the check-alerts task Each SLO stores a status snapshot so lists read it without querying. The check-alerts task refreshes the snapshots beside the alert evaluation: burn rates every 5 minutes from a 6-hour query in 5-minute buckets, and the SLI and error budget every 30 minutes, since that query reads the whole 7 or 30 day window. A grouped SLO also stores the numbers of its 100 busiest groups and how many groups there are, and takes the state of its worst group. Queries use a materialized view of the source when one covers them, and every query is bounded by a 40 second deadline, so a slow SLO never holds up alerts; what is left waits for the next run. A failed refresh keeps the last numbers and marks the SLO as an error. Changing what an SLO measures drops its snapshot, and a refresh never changes updatedAt. Co-Authored-By: Claude Opus 5.5 --- .changeset/slo-api.md | 15 ++ packages/api/src/controllers/slo.ts | 16 +- packages/api/src/controllers/sloStatus.ts | 239 ++++++++++++++++++ .../api/src/controllers/sloStatusQueries.ts | 230 +++++++++++++++++ .../routers/api/__tests__/slos.int.test.ts | 184 ++++++++++++++ .../__tests__/checkAlertsTask.test.ts | 50 ++++ packages/api/src/tasks/checkAlerts/index.ts | 12 + 7 files changed, 743 insertions(+), 3 deletions(-) create mode 100644 .changeset/slo-api.md create mode 100644 packages/api/src/controllers/sloStatus.ts create mode 100644 packages/api/src/controllers/sloStatusQueries.ts diff --git a/.changeset/slo-api.md b/.changeset/slo-api.md new file mode 100644 index 0000000000..14a88b5b3c --- /dev/null +++ b/.changeset/slo-api.md @@ -0,0 +1,15 @@ +--- +'@hyperdx/api': patch +--- + +feat: SLO definitions with a background status refresh, behind ENABLE_SLOS + +Adds the SLO model and a /slos API for creating, listing, updating and +deleting SLOs. Saving runs the SLO's query over the last minute, so a +condition ClickHouse rejects fails the save with ClickHouse's message. +The check-alerts task refreshes each SLO's stored status for lists: burn +rates every 5 minutes from a 6-hour query in 5-minute buckets, and the SLI +and error budget every 30 minutes. A grouped SLO also stores the numbers +of its 100 busiest groups and how many groups there are. Queries use a +materialized view of the source when one covers them, and every query is +bounded by the refresh deadline so alert evaluation is never delayed. diff --git a/packages/api/src/controllers/slo.ts b/packages/api/src/controllers/slo.ts index 7cc8eaca07..9b45b36cfe 100644 --- a/packages/api/src/controllers/slo.ts +++ b/packages/api/src/controllers/slo.ts @@ -27,7 +27,7 @@ import Slo, { ISlo } from '@/models/slo'; import { getClickHouseErrorType } from '@/utils/clickhouseErrors'; import { Api400Error } from '@/utils/errors'; -type SloQueryContext = { +export type SloQueryContext = { source: TSource; clickhouseClient: BaseClickhouseClient; metadata: Metadata; @@ -47,7 +47,7 @@ async function getSloSource(teamId: string, sourceId: string) { return source; } -async function getSloQueryContext( +export async function getSloQueryContext( teamId: string, sourceId: string, timeoutMs: number, @@ -75,7 +75,7 @@ async function getSloQueryContext( * it, as charts and alerts do; otherwise from the source's table. A timeout * ends the query sooner than the client's own. */ -async function runSloQuery( +export async function runSloQuery( ctx: SloQueryContext, config: BuilderChartConfigWithDateRange, timeoutMs?: number, @@ -162,6 +162,7 @@ export async function createSlo( throw new Api400Error(`A team can have at most ${SLO_MAX_PER_TEAM} SLOs`); } await checkSloQuery(teamId, definition); + // The status refresh picks up an SLO without a snapshot on its next run. return ( await Slo.create({ ...definition, @@ -182,6 +183,14 @@ export async function updateSlo( const existing = await getSlo(teamId, sloId); if (!existing) return null; await checkSloQuery(teamId, definition); + // Every input of the stored numbers: a change makes the snapshot wrong, + // and the refresh recomputes it on its next run. + const changed = + existing.source.toString() !== definition.source || + existing.target !== definition.target || + existing.window !== definition.window || + (existing.groupBy ?? null) !== (definition.groupBy ?? null) || + JSON.stringify(existing.indicator) !== JSON.stringify(definition.indicator); return Slo.findOneAndUpdate( { _id: sloId, team: teamId }, { @@ -191,6 +200,7 @@ export async function updateSlo( groupBy: definition.groupBy || null, updatedBy: userId, }, + ...(changed ? { $unset: { status: 1 } } : {}), }, { new: true }, ).lean(); diff --git a/packages/api/src/controllers/sloStatus.ts b/packages/api/src/controllers/sloStatus.ts new file mode 100644 index 0000000000..9f5bf84a03 --- /dev/null +++ b/packages/api/src/controllers/sloStatus.ts @@ -0,0 +1,239 @@ +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 type { SloStatus } from '@hyperdx/common-utils/dist/slo'; + +import { getSloQueryContext, SloQueryContext } from '@/controllers/slo'; +import { + buildSloStatus, + computeSloBurn, + computeSloWindow, + hasSloQueryTime, + type SloBurnNumbers, + SloQueryDeadlineError, + type SloWindowNumbers, +} from '@/controllers/sloStatusQueries'; +import Slo, { ISlo } from '@/models/slo'; +import { + getCounter, + setBusinessContext, + withSpan, +} from '@/utils/instrumentation'; +import logger from '@/utils/logger'; + +/** How old the burn numbers get before the refresh recomputes them. */ +const SLO_BURN_MAX_AGE_MS = 5 * 60 * 1000; +/** + * How old the window numbers (SLI, budget) get. Their query reads the whole + * 7 or 30 day window, and a budget that long barely moves in minutes. + */ +const SLO_WINDOW_MAX_AGE_MS = 30 * 60 * 1000; + +/** + * Limits for one refresh run. It runs beside the alert evaluation in the + * check-alerts task, so every query ends by the deadline, well within the + * task's one-minute cadence; whatever is left waits for the next run. + */ +const SLO_REFRESH_DEADLINE_MS = 40_000; +const SLO_REFRESH_CLIENT_TIMEOUT_MS = 30_000; +const SLO_REFRESH_CONCURRENCY = 4; +const SLO_REFRESH_BATCH_LIMIT = 200; + +const refreshCounter = getCounter('hyperdx.slo.refresh', { + description: 'SLO status refreshes, by outcome', +}); + +const getErrorMessage = (e: unknown) => + e instanceof Error ? e.message : String(e); + +function getStoredWindow( + status: SloStatus | null | undefined, +): SloWindowNumbers | null { + if (status?.windowEvaluatedAt == null) return null; + return { + eligible: status.eligible, + good: status.good, + windowStart: status.windowStart, + windowEnd: status.windowEnd, + windowEvaluatedAt: status.windowEvaluatedAt, + durationMs: status.durationMs, + rowsRead: status.rowsRead, + ...(status.groups != null + ? { + groups: status.groups.map(({ value, eligible, good }) => ({ + value, + eligible, + good, + })), + groupCount: status.groupCount, + } + : {}), + }; +} + +function getStoredBurn( + status: SloStatus | null | undefined, +): SloBurnNumbers | null { + if (status?.burn == null) return null; + return { + burn: status.burn, + ...(status.groups != null + ? { groups: new Map(status.groups.map(g => [g.value, g.burn])) } + : {}), + }; +} + +const isOlderThan = (iso: string | null | undefined, now: Date, ms: number) => + iso == null || now.getTime() - Date.parse(iso) >= ms; + +/** + * Computes and stores one snapshot: the window numbers and the burn numbers + * that are due, keeping the stored ones that are not. The window comes + * first, since it decides which groups a grouped SLO tracks. A failed + * evaluation keeps the last known numbers, marks the state as error and + * records when it last succeeded, so an SLO that cannot be evaluated never + * reads as healthy. + */ +async function refreshSloStatus( + slo: ISlo, + now: Date, + deadline: number, +): Promise<'success' | 'error' | 'deferred'> { + const previous = slo.status; + let status: SloStatus; + let outcome: 'success' | 'error' = 'success'; + try { + const ctx = await getSloQueryContext( + slo.team.toString(), + slo.source.toString(), + SLO_REFRESH_CLIENT_TIMEOUT_MS, + ); + let window = getStoredWindow(previous); + const windowDue = + window == null || + isOlderThan(previous?.windowEvaluatedAt, now, SLO_WINDOW_MAX_AGE_MS); + if (windowDue) window = await computeSloWindow(slo, ctx, now, deadline); + if (window == null) return 'deferred'; + let burn = getStoredBurn(previous); + let evaluatedAt = previous?.evaluatedAt ?? now.toISOString(); + // New window numbers can bring new groups, which need burn numbers too. + if ( + burn == null || + windowDue || + isOlderThan(previous?.evaluatedAt, now, SLO_BURN_MAX_AGE_MS) + ) { + burn = await computeSloBurn( + slo, + ctx, + now, + window.groups?.map(g => g.value), + deadline, + ); + evaluatedAt = now.toISOString(); + } + status = buildSloStatus(slo, window, burn, evaluatedAt, now); + } catch (e) { + // Out of time mid-way: nothing is stored, and the next run retries. + if (e instanceof SloQueryDeadlineError) return 'deferred'; + outcome = 'error'; + const windowRange = getSloWindowRange(slo.window, now); + status = { + eligible: previous?.eligible ?? 0, + good: previous?.good ?? 0, + bad: previous?.bad ?? 0, + sli: previous?.sli ?? null, + errorBudget: previous?.errorBudget ?? 0, + budgetRemaining: previous?.budgetRemaining ?? null, + budgetRemainingEvents: previous?.budgetRemainingEvents ?? 0, + burn: previous?.burn ?? [], + windowStart: previous?.windowStart ?? windowRange[0].toISOString(), + windowEnd: previous?.windowEnd ?? windowRange[1].toISOString(), + windowEvaluatedAt: previous?.windowEvaluatedAt ?? null, + durationMs: previous?.durationMs ?? 0, + rowsRead: previous?.rowsRead ?? 0, + ...(previous?.groups != null + ? { groups: previous.groups, groupCount: previous.groupCount } + : {}), + lastSuccessAt: previous?.lastSuccessAt ?? null, + state: 'error', + evaluatedAt: now.toISOString(), + error: getErrorMessage(e).slice(0, 2000), + }; + } + // Matching updatedAt drops the snapshot when the SLO was edited while it + // was computed, and not touching timestamps keeps updatedAt meaning the + // last edit rather than the last refresh. + await Slo.updateOne( + { _id: slo._id, updatedAt: slo.updatedAt }, + { $set: { status } }, + { timestamps: false }, + ); + return outcome; +} + +/** + * Refreshes snapshots whose burn numbers are older than SLO_BURN_MAX_AGE_MS + * or whose window numbers are older than SLO_WINDOW_MAX_AGE_MS, new SLOs and + * then the stalest first, with a few queries at a time. Every query is + * bounded by what is left of the deadline, so the run ends by it. Never + * throws: a failure is recorded on the SLO it belongs to. + */ +export async function refreshDueSloStatuses(now = new Date()): Promise { + await withSpan('sloRefreshBatch', async span => { + const before = (ms: number) => new Date(now.getTime() - ms).toISOString(); + // A snapshot without window numbers (its first refresh failed) is + // retried with its burn numbers, not on every run. + const due = await Slo.find({ + $or: [ + { 'status.evaluatedAt': { $exists: false } }, + { 'status.evaluatedAt': { $lt: before(SLO_BURN_MAX_AGE_MS) } }, + { 'status.windowEvaluatedAt': { $lt: before(SLO_WINDOW_MAX_AGE_MS) } }, + ], + }) + .sort({ 'status.evaluatedAt': 1 }) + .limit(SLO_REFRESH_BATCH_LIMIT) + .lean(); + span.setAttribute('hyperdx.slo.refresh.due', due.length); + + const deadline = Date.now() + SLO_REFRESH_DEADLINE_MS; + const queue = new PQueue({ concurrency: SLO_REFRESH_CONCURRENCY }); + let deferred = 0; + for (const slo of due) { + void queue.add(async () => { + if (!hasSloQueryTime(deadline)) { + deferred++; + return; + } + await withSpan( + 'sloRefresh', + async sloSpan => { + setBusinessContext({ teamId: slo.team.toString() }); + const outcome = await withQueryAttribution( + { + surface: 'slo', + label: slo._id.toString(), + source: slo.source.toString(), + }, + () => refreshSloStatus(slo, now, deadline), + ); + sloSpan.setAttribute('hyperdx.slo.refresh.outcome', outcome); + refreshCounter.add(1, { outcome }); + }, + { + attributes: { + 'hyperdx.slo.id': slo._id.toString(), + 'hyperdx.team.id': slo.team.toString(), + }, + }, + ).catch(e => + logger.error({ error: getErrorMessage(e) }, 'SLO refresh failed'), + ); + }); + } + await queue.onIdle(); + if (deferred > 0) refreshCounter.add(deferred, { outcome: 'deferred' }); + span.setAttribute('hyperdx.slo.refresh.deferred', deferred); + }).catch(e => + logger.error({ error: getErrorMessage(e) }, 'SLO refresh batch failed'), + ); +} diff --git a/packages/api/src/controllers/sloStatusQueries.ts b/packages/api/src/controllers/sloStatusQueries.ts new file mode 100644 index 0000000000..cc22c09056 --- /dev/null +++ b/packages/api/src/controllers/sloStatusQueries.ts @@ -0,0 +1,230 @@ +import { + buildSloBurnChartConfig, + buildSloCountsChartConfig, + buildSloGroupCountChartConfig, + getSloBurnRule, + getSloGroupBy, + getSloWindowRange, + parseSloCountsRow, + parseSloGroupCountRow, + parseSloGroupRows, + type SloCounts, +} from '@hyperdx/common-utils/dist/core/slo'; +import { + compareSloGroupsWorstFirst, + computeSloBurnFromRows, + computeSloBurnStats, + computeSloGroupBurnFromRows, + computeSloStats, + deriveGroupedSloState, + deriveSloGroupState, + deriveSloState, +} from '@hyperdx/common-utils/dist/core/sloStats'; +import { + SLO_MAX_GROUPS, + type SloBurnStats, + type SloGroupStatus, + type SloStatus, +} from '@hyperdx/common-utils/dist/slo'; + +import { runSloQuery, SloQueryContext } from '@/controllers/slo'; +import type { ISlo } from '@/models/slo'; + +/** Longest a status query may run, and the least time worth starting one. */ +const SLO_QUERY_TIMEOUT_MS = 30_000; +const SLO_MIN_QUERY_MS = 5_000; + +type SloDefinitionFields = Pick< + ISlo, + 'indicator' | 'target' | 'window' | 'groupBy' +>; + +/** The part of a snapshot the window queries produce. */ +export type SloWindowNumbers = Pick< + SloStatus, + | 'eligible' + | 'good' + | 'windowStart' + | 'windowEnd' + | 'windowEvaluatedAt' + | 'durationMs' + | 'rowsRead' + | 'groupCount' +> & { + /** Grouped SLOs: the tracked groups' counts, busiest first. */ + groups?: (SloCounts & { value: string })[]; +}; + +/** The part of a snapshot the burn queries produce. */ +export type SloBurnNumbers = { + burn: SloBurnStats[]; + /** Grouped SLOs: each tracked group's burn numbers. */ + groups?: Map; +}; + +/** No time is left before the deadline for the next query. */ +export class SloQueryDeadlineError extends Error {} + +/** Time is left before the deadline for at least one more query. */ +export function hasSloQueryTime(deadline: number): boolean { + return ( + Math.min(SLO_QUERY_TIMEOUT_MS, deadline - Date.now()) >= SLO_MIN_QUERY_MS + ); +} + +/** Timeout for the next query, bounded by the deadline when there is one. */ +function getQueryTimeout(deadline: number | undefined): number | undefined { + if (deadline == null) return undefined; + if (!hasSloQueryTime(deadline)) throw new SloQueryDeadlineError(); + return Math.min(SLO_QUERY_TIMEOUT_MS, deadline - Date.now()); +} + +/** + * Eligible and good events over the SLO window, overall and, for a grouped + * SLO, for its busiest groups, with what the queries cost. + */ +export async function computeSloWindow( + slo: SloDefinitionFields, + ctx: SloQueryContext, + now: Date, + deadline?: number, +): Promise { + const { source } = ctx; + const dateRange = getSloWindowRange(slo.window, now); + const cost = { durationMs: 0, rowsRead: 0 }; + const run = async (config: Parameters[1]) => { + const result = await runSloQuery(ctx, config, getQueryTimeout(deadline)); + cost.durationMs += result.durationMs; + cost.rowsRead += result.rowsRead; + return result.rows; + }; + const { eligible, good } = parseSloCountsRow( + await run(buildSloCountsChartConfig({ slo, source, dateRange })), + ); + const groupBy = getSloGroupBy(slo); + let groups: SloWindowNumbers['groups']; + let groupCount: number | undefined; + if (groupBy != null) { + const rows = parseSloGroupRows( + await run( + buildSloCountsChartConfig({ + slo, + source, + dateRange, + scope: { byGroup: true }, + }), + ), + ); + groups = rows.slice(0, SLO_MAX_GROUPS); + groupCount = rows.length; + // One row more than the cap: count them all, to show how many are left. + if (rows.length > SLO_MAX_GROUPS) { + groupCount = parseSloGroupCountRow( + await run( + buildSloGroupCountChartConfig({ + slo: { ...slo, groupBy }, + source, + dateRange, + }), + ), + ); + } + } + return { + eligible, + good, + windowStart: dateRange[0].toISOString(), + windowEnd: dateRange[1].toISOString(), + windowEvaluatedAt: now.toISOString(), + ...cost, + ...(groups != null ? { groups, groupCount } : {}), + }; +} + +/** Burn numbers overall and, for a grouped SLO, for the given groups. */ +export async function computeSloBurn( + slo: SloDefinitionFields, + ctx: SloQueryContext, + now: Date, + groupValues: string[] | undefined, + deadline?: number, +): Promise { + const { source } = ctx; + const overall = await runSloQuery( + ctx, + buildSloBurnChartConfig({ slo, source, now }), + getQueryTimeout(deadline), + ); + const burn = computeSloBurnFromRows(overall.rows, slo, now); + if (getSloGroupBy(slo) == null || !groupValues?.length) return { burn }; + const grouped = await runSloQuery( + ctx, + buildSloBurnChartConfig({ + slo, + source, + now, + scope: { byGroup: true, groups: groupValues }, + }), + getQueryTimeout(deadline), + ); + return { + burn, + groups: computeSloGroupBurnFromRows(grouped.rows, slo, now, groupValues), + }; +} + +/** Each tracked group with its numbers and state, worst first. */ +function buildSloGroups( + slo: SloDefinitionFields, + groups: NonNullable, + groupsBurn: Map | undefined, +): SloGroupStatus[] { + // A group the burn numbers lack has no events in the burn windows. + const noBurn = computeSloBurnStats( + [], + getSloBurnRule(slo.window), + slo.target, + ); + return groups + .map(({ value, eligible, good }) => { + const stats = computeSloStats( + { eligible, good }, + groupsBurn?.get(value) ?? noBurn, + slo.target, + ); + return { ...stats, value, state: deriveSloGroupState(stats) }; + }) + .sort(compareSloGroupsWorstFirst); +} + +/** A snapshot from window numbers and burn numbers taken at `evaluatedAt`. */ +export function buildSloStatus( + slo: SloDefinitionFields, + window: SloWindowNumbers, + burn: SloBurnNumbers, + evaluatedAt: string, + now: Date, +): SloStatus { + const { groups: windowGroups, ...windowFields } = window; + const stats = computeSloStats( + { eligible: window.eligible, good: window.good }, + burn.burn, + slo.target, + ); + const groups = + windowGroups != null + ? buildSloGroups(slo, windowGroups, burn.groups) + : undefined; + return { + ...windowFields, + ...stats, + state: + groups != null + ? deriveGroupedSloState(stats, groups) + : deriveSloState(stats), + evaluatedAt, + lastSuccessAt: now.toISOString(), + ...(groups != null ? { groups } : {}), + error: null, + }; +} 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 f30e9c9a8b..a390524547 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,9 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import * as config from '@/config'; +import { refreshDueSloStatuses } from '@/controllers/sloStatus'; import { + bulkInsertData, DEFAULT_DATABASE, DEFAULT_TRACES_TABLE, getLoggedInAgent, @@ -151,4 +153,186 @@ describe('SLO router', () => { expect((await agent.get('/slos').expect(200)).body).toEqual([]); expect(await Slo.exists({ _id: id })).toBeTruthy(); }); + + it('computes the status in the background, counting a NULL condition as bad', async () => { + // Seven good spans, two bad, and one whose condition is NULL. + const ok = [...Array(7).fill('1'), '0', '0', undefined]; + const now = Date.now(); + await bulkInsertData( + `${DEFAULT_DATABASE}.${DEFAULT_TRACES_TABLE}`, + ok.map((value, 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: value == null ? {} : { ok: value }, + ResourceAttributes: {}, + })), + ); + const created = await agent + .post('/slos') + .send( + definition({ + indicator: { + template: 'availability', + eligible: { + where: `ServiceName = '${SERVICE}'`, + whereLanguage: 'sql', + }, + good: "toUInt8OrNull(SpanAttributes['ok']) = 1", + }, + }), + ) + .expect(200); + + await refreshDueSloStatuses(); + + const { body } = await agent.get(`/slos/${created.body.id}`).expect(200); + expect(body.status).toEqual( + expect.objectContaining({ + eligible: 10, + good: 7, + bad: 3, + state: 'breached', + error: null, + }), + ); + // A refresh is not an edit. + expect(body.updatedAt).toBe(created.body.updatedAt); + }); + + it('refreshes the burn numbers every few minutes and the window numbers less often', async () => { + const created = await agent.post('/slos').send(definition()).expect(200); + const t0 = Date.now(); + const iso = (minutes: number) => + new Date(t0 + minutes * 60_000).toISOString(); + const statusAt = async (minutes: number) => { + await refreshDueSloStatuses(new Date(t0 + minutes * 60_000)); + return (await agent.get(`/slos/${created.body.id}`).expect(200)).body + .status; + }; + + expect(await statusAt(0)).toMatchObject({ + evaluatedAt: iso(0), + windowEvaluatedAt: iso(0), + }); + // Burn numbers are due after 5 minutes, window numbers after 30. + expect(await statusAt(6)).toMatchObject({ + evaluatedAt: iso(6), + windowEvaluatedAt: iso(0), + }); + expect(await statusAt(31)).toMatchObject({ + evaluatedAt: iso(31), + windowEvaluatedAt: iso(31), + }); + }); + + 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. + const base = `${SERVICE}-group`; + // Before the last 5-minute boundary, where the burn windows end. + const end = Math.floor(Date.now() / 300_000) * 300_000; + const spans = (service: string, count: number, bad: number) => + Array.from({ length: count }, (_, i) => ({ + Timestamp: new Date(end - (i + 1) * 20_000), + TraceId: `${service}-trace-${i}`, + SpanId: `${service}-span-${i}`, + ParentSpanId: '', + SpanName: 'POST /checkout', + SpanKind: 'Server', + ServiceName: service, + Duration: 100 * 1e6, + StatusCode: i < bad ? 'Error' : 'Ok', + StatusMessage: '', + SpanAttributes: {}, + ResourceAttributes: {}, + })); + await bulkInsertData(`${DEFAULT_DATABASE}.${DEFAULT_TRACES_TABLE}`, [ + ...spans(`${base}-a`, 150, 0), + ...spans(`${base}-b`, 120, 40), + ...spans(`${base}-c`, 10, 0), + ]); + const created = await agent + .post('/slos') + .send( + definition({ + indicator: { + template: 'availability', + eligible: { + where: `startsWith(ServiceName, '${base}-')`, + whereLanguage: 'sql', + }, + good: "StatusCode != 'Error'", + }, + groupBy: 'ServiceName', + }), + ) + .expect(200); + expect(created.body.groupBy).toBe('ServiceName'); + + await refreshDueSloStatuses(); + + const { body } = await agent.get(`/slos/${created.body.id}`).expect(200); + expect(body.status).toMatchObject({ + eligible: 280, + good: 240, + groupCount: 3, + // As bad as its worst group with enough events. + state: 'breached', + }); + expect(body.status.groups).toEqual([ + expect.objectContaining({ + value: `${base}-b`, + eligible: 120, + good: 80, + state: 'breached', + }), + expect.objectContaining({ + value: `${base}-a`, + eligible: 150, + good: 150, + state: 'healthy', + }), + expect.objectContaining({ + value: `${base}-c`, + eligible: 10, + state: 'insufficient_data', + }), + ]); + // Each group has its own burn numbers: the bad spans are the latest. + expect(body.status.groups[0].burn[0]).toMatchObject({ + window: '1h', + eligible: 120, + bad: 40, + }); + expect(body.status.groups[1].burn[0]).toMatchObject({ bad: 0 }); + }); + + it('drops the status when what it measures changes, not when the name does', async () => { + const created = await agent.post('/slos').send(definition()).expect(200); + const id = created.body.id; + await refreshDueSloStatuses(); + const statusOf = async () => + (await agent.get(`/slos/${id}`).expect(200)).body.status; + expect(await statusOf()).not.toBeNull(); + + await agent + .put(`/slos/${id}`) + .send(definition({ name: 'Renamed' })) + .expect(200); + expect(await statusOf()).not.toBeNull(); + + await agent + .put(`/slos/${id}`) + .send(definition({ name: 'Renamed', target: 95 })) + .expect(200); + expect(await statusOf()).toBeNull(); + }); }); diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts index 4bee904862..c9d2123950 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts @@ -3,6 +3,7 @@ import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import * as config from '@/config'; +import { refreshDueSloStatuses } from '@/controllers/sloStatus'; import { ObjectId } from '@/models'; import { AlertSource, @@ -26,6 +27,10 @@ import { } from '@/tasks/checkAlerts/providers'; import { CheckAlertsTaskArgs, TaskName } from '@/tasks/types'; +jest.mock('@/controllers/sloStatus', () => ({ + refreshDueSloStatuses: jest.fn(), +})); + jest.mock('@/tasks/checkAlerts/providers', () => { return { ...jest.requireActual('@/tasks/checkAlerts/providers'), @@ -219,6 +224,51 @@ describe('CheckAlertTask', () => { expect(mockProcessAlert).not.toHaveBeenCalled(); }); + // Each run opens the database connection in init and closes it at the + // end, so the SLO refresh can only start once init is done. + it('starts the SLO refresh once the provider has connected', async () => { + const slosEnabled = jest.replaceProperty(config, 'IS_SLOS_ENABLED', true); + const calls: string[] = []; + mockAlertProvider.init.mockImplementation(async () => { + calls.push('init'); + }); + jest.mocked(refreshDueSloStatuses).mockImplementation(async () => { + calls.push('slo refresh'); + }); + mockAlertProvider.getAlertTasks.mockResolvedValue([]); + + try { + await new CheckAlertTask({ taskName: TaskName.CHECK_ALERTS }).execute(); + } finally { + slosEnabled.restore(); + } + + expect(calls).toEqual(['init', 'slo refresh']); + }); + + it('closes the connection only after the SLO refresh, even when the run fails', async () => { + const slosEnabled = jest.replaceProperty(config, 'IS_SLOS_ENABLED', true); + const calls: string[] = []; + jest.mocked(refreshDueSloStatuses).mockImplementation(async () => { + await new Promise(resolve => setTimeout(resolve, 10)); + calls.push('slo refresh done'); + }); + mockAlertProvider.getAlertTasks.mockRejectedValue(new Error('no alerts')); + mockAlertProvider.asyncDispose.mockImplementation(async () => { + calls.push('dispose'); + }); + + const task = new CheckAlertTask({ taskName: TaskName.CHECK_ALERTS }); + try { + await expect(task.execute()).rejects.toThrow('no alerts'); + await task.asyncDispose(); + } finally { + slosEnabled.restore(); + } + + expect(calls).toEqual(['slo refresh done', 'dispose']); + }); + it('should execute successfully with custom provider', async () => { const args: CheckAlertsTaskArgs = { taskName: TaskName.CHECK_ALERTS, diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 404108a7f1..4e1f06eebf 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -57,7 +57,9 @@ import ms from 'ms'; import { performance } from 'perf_hooks'; import { serializeError } from 'serialize-error'; +import { IS_SLOS_ENABLED } from '@/config'; import { ALERT_HISTORY_QUERY_CONCURRENCY } from '@/controllers/alertHistory'; +import { refreshDueSloStatuses } from '@/controllers/sloStatus'; import { AlertState, IAlert, IAlertError } from '@/models/alert'; import AlertHistory, { attributesToGroupValues, @@ -2287,6 +2289,7 @@ export const getConsecutiveWindowHistories = async ( export default class CheckAlertTask implements HdxTask { private provider!: AlertProvider; private task_queue: PQueue; + private sloRefresh: Promise = Promise.resolve(); constructor(private args: CheckAlertsTaskArgs) { const concurrency = this.args.concurrency; @@ -2402,6 +2405,11 @@ export default class CheckAlertTask implements HdxTask { 'finished provider initialization', ); + // SLO snapshots refresh beside the alert evaluation, under their own + // deadline, so a slow SLO query never holds up alerts. Started after + // init, which opens the database connection each run closes. + if (IS_SLOS_ENABLED) this.sloRefresh = refreshDueSloStatuses(); + const alertTasks = partitionPreviousMapsByAlert( await this.provider.getAlertTasks(), ); @@ -2451,6 +2459,7 @@ export default class CheckAlertTask implements HdxTask { // functions to execute. if not, execute will terminate without // executing all checks await this.task_queue.onIdle(); + await this.sloRefresh; logger.info( { args: this.args, @@ -2466,6 +2475,9 @@ export default class CheckAlertTask implements HdxTask { } async asyncDispose(): Promise { + // The refresh writes through the connection the provider closes, even + // when execute stopped early. + await this.sloRefresh; if (this.provider) { await this.provider.asyncDispose(); } From 03dd23052f92a28e5762a1c2bbe5c04d7844370f Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:55:13 +0000 Subject: [PATCH 2/2] fix(api): drop an unused import from the SLO refresh Co-Authored-By: Claude Opus 5.5 --- packages/api/src/controllers/sloStatus.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/api/src/controllers/sloStatus.ts b/packages/api/src/controllers/sloStatus.ts index 9f5bf84a03..f42680e8f0 100644 --- a/packages/api/src/controllers/sloStatus.ts +++ b/packages/api/src/controllers/sloStatus.ts @@ -3,7 +3,7 @@ import { withQueryAttribution } from '@hyperdx/common-utils/dist/clickhouse/node import { getSloWindowRange } from '@hyperdx/common-utils/dist/core/slo'; import type { SloStatus } from '@hyperdx/common-utils/dist/slo'; -import { getSloQueryContext, SloQueryContext } from '@/controllers/slo'; +import { getSloQueryContext } from '@/controllers/slo'; import { buildSloStatus, computeSloBurn,