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
15 changes: 15 additions & 0 deletions .changeset/slo-api.md
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 13 additions & 3 deletions packages/api/src/controllers/slo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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) ||

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 — Saving an SLO with groupBy: '' always drops its status

SloInputSchema.groupBy is z.string().trim().nullish(), so '' passes validation and is stored as null (definition.groupBy || null). The check then compares null !== '' with ??, sees a change, and unsets status on every save, even a rename. Fix: normalise both sides the way the stored value is, with (existing.groupBy || null) !== (definition.groupBy || null).

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

JSON.stringify(existing.indicator) !== JSON.stringify(definition.indicator);
return Slo.findOneAndUpdate(
{ _id: sloId, team: teamId },
{
Expand All @@ -191,6 +200,7 @@ export async function updateSlo(
groupBy: definition.groupBy || null,
updatedBy: userId,
},
...(changed ? { $unset: { status: 1 } } : {}),
},
{ new: true },
).lean();
Expand Down
239 changes: 239 additions & 0 deletions packages/api/src/controllers/sloStatus.ts
Original file line number Diff line number Diff line change
@@ -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 } 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<void> {
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(),
},

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.

🔴 P1 — A query cut off by the refresh deadline marks the SLO as error instead of deferring it

getQueryTimeout caps each query at whatever is left of the deadline, and runSloQuery (controllers/slo.ts:84) passes that to AbortSignal.timeout. When that signal fires, the error is an AbortError/ClickHouse timeout, not a SloQueryDeadlineError, so the catch here stores state: 'error'. Example: an SLO that starts with 6s left and needs 8s is flagged error, even though the PR says work that runs out of time waits for the next run. Fix: in this catch, also return 'deferred' when Date.now() >= deadline (or when the deadline signal has aborted), so only real failures get stored as errors.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

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