Skip to content

feat(api): refresh SLO statuses in the check-alerts task - #3795

Open
alex-fedotyev wants to merge 2 commits into
alex/HDX-3001-slo-07-api-definitionsfrom
alex/HDX-3001-slo-08-api-refresh
Open

alex-fedotyev wants to merge 2 commits into
alex/HDX-3001-slo-07-api-definitionsfrom
alex/HDX-3001-slo-08-api-refresh

Conversation

@alex-fedotyev

@alex-fedotyev alex-fedotyev commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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.

Stack

Part 8 of 27 PRs in a GitHub stack (stack #3815). The header says this PR merges into the branch below it, but the stack's base is main: merging a PR lands it and every PR below it on main, one squashed commit each. Each diff is only its own change, and CI runs as if each PR targets main.

  1. feat(common-utils): SLO definition schema #3788 common-utils: SLO definition schema
  2. feat(common-utils): SLO fast and slow burn rules #3789 common-utils: SLO fast and slow burn rules
  3. feat(common-utils): SLO alert targets and status types #3790 common-utils: SLO alert targets and status types
  4. feat(common-utils): SLO counts query #3791 common-utils: SLO counts query
  5. feat(common-utils): SLO stats and state #3792 common-utils: SLO stats and state
  6. feat(common-utils): SLO history and ordering #3793 common-utils: SLO history and ordering
  7. feat(api): SLO definitions behind ENABLE_SLOS #3794 api: SLO definitions behind ENABLE_SLOS
  8. feat(api): refresh SLO statuses in the check-alerts task #3795 api: refresh SLO statuses in the check-alerts task (this PR)
  9. feat(api): SLO burn alerts as their own alert source #3796 api: SLO burn alerts as their own alert source
  10. feat(api): keep SLO alerts out of the external alerts API #3797 api: keep SLO alerts out of the external alerts API
  11. feat(api): evaluate SLO burn alerts and notify #3798 api: evaluate SLO burn alerts and notify
  12. feat(api): clickstack_get_slo MCP tool #3799 api: clickstack_get_slo MCP tool
  13. feat(api): SLO preview, save and delete MCP tools #3800 api: SLO preview, save and delete MCP tools
  14. feat(app): SLO list page behind NEXT_PUBLIC_ENABLE_SLOS #3801 app: SLO list page behind NEXT_PUBLIC_ENABLE_SLOS
  15. feat(app): search, filter, sort and delete SLOs in the list #3802 app: search, filter, sort and delete SLOs in the list
  16. feat(app): SLO builder for a new SLO #3803 app: SLO builder for a new SLO
  17. feat(app): SLO objective, details and editing in the builder #3804 app: SLO objective, details and editing in the builder
  18. feat(app): eligible-event filters and the latency template in the builder #3805 app: eligible-event filters and the latency template in the builder
  19. feat(app): preview an SLO in the builder before saving it #3806 app: preview an SLO in the builder before saving it
  20. feat(app): create an SLO from a search, and duplicate an SLO #3807 app: create an SLO from a search, and duplicate an SLO
  21. feat(app): SLO detail page #3808 app: SLO detail page
  22. feat(app): bad events flyout on the SLO page #3809 app: bad events flyout on the SLO page
  23. feat(app): SLI, error budget and burn rate charts on the SLO page #3810 app: SLI, error budget and burn rate charts on the SLO page
  24. feat(app): fast and slow burn alerts in the SLO builder, list and page #3811 app: fast and slow burn alerts in the SLO builder, list and page
  25. feat(app): SLO alerts on the Alerts page #3812 app: SLO alerts on the Alerts page
  26. feat(app): group-by in the SLO builder #3813 app: group-by in the SLO builder
  27. feat(app): grouped SLOs in the list and on the SLO page #3814 app: grouped SLOs in the list and on the SLO page

Parts 1 to 6 are shared code, 7 to 13 the API and its MCP tools, and 14 to 27 the app. Everything ships behind ENABLE_SLOS (API) and NEXT_PUBLIC_ENABLE_SLOS (app), both off by default.

Known limits

  • Windows are rolling 7 or 30 days; calendar windows and reports are not part of this.
  • The SLI and error budget come from a query over the whole window every 30 minutes. Storing counts per bucket would make that incremental; I'd like that before GA.
  • The window can't reach past the source's retention (30 days by default), so a 30-day SLO on default retention covers what is retained.

How to reproduce

Starting point: a checkout of this branch with Docker (make dev-int starts ClickHouse and Mongo for the integration tests).

On main: nothing to compare; this is new code.

On this branch:

  1. make dev-int FILE=slos: the refresh stores a status (NULL good conditions count as bad), recomputes burn numbers every 5 minutes and window numbers every 30, tracks each group of a grouped SLO, and drops the status when what the SLO measures changes.
  2. cd packages/api && npx jest src/tasks/checkAlerts/__tests__/checkAlertsTask.test.ts: the refresh starts after the provider connects, and the connection closes only after it, even when the run fails.

Test plan

  • integration: routers/api/__tests__/slos.int.test.ts (refresh, NULL as bad, cadence, groups, snapshot dropped on change)
  • unit: tasks/checkAlerts/__tests__/checkAlertsTask.test.ts (refresh ordering)
  • typecheck and knip at this commit, for every package

How to test on Vercel preview

N/A, non-UI change.

References

  • Linear Issue: HDX-3001
  • Related PRs: the rest of this stack, listed above

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 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 24, 2026 7:02pm UTC
hyperdx-storybook Ready Ready Preview Nov 24, 2026 7:02pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 03dd230

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@hyperdx/api Patch
@hyperdx/app Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 107 in total (1.11%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 479 passed • 1 skipped • 1144s

Status Count
✅ Passed 479
❌ Failed 0
⚠️ Flaky 9
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

🟡 Tier 3 — Standard

Introduces new logic, modifies core functionality, or touches areas with non-trivial risk.

Why this tier:

  • Diff size: 497 production lines changed (Tier 2 max: < 250)

Additional context: touches background tasks or the delivery pipeline lightly (12 lines, under the 30-line bar for Tier 4)

Review process: Full human review — logic, architecture, edge cases.
SLA: First-pass feedback within 1 business day.

Stats
  • Production files changed: 4
  • Production lines changed: 497 (+ 234 in test files, excluded from tier calculation)
  • Branch: alex/HDX-3001-slo-08-api-refresh
  • Author: alex-fedotyev

To override this classification, remove the review/tier-3 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

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

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

@github-actions

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

5 finding(s): 🔴 1 P0/P1 · 🟡 2 P2 · 🔵 2 P3

2 posted as inline comment(s) on the changed lines. 1 listed below. 2 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/api/src/controllers/sloStatus.ts:240 — An SLO whose window refresh keeps failing is retried on every run, not every 5 minutes → The error snapshot keeps the old windowEvaluatedAt, so the status.windowEvaluatedAt < now-30m branch of the $or in refreshDueSloStatuses matches it again on every one-minute tick, and its full 7/30-day window query reruns each minute while it fails. The comment at line 273 says failures should not be retried every run. Fix: rate-limit errored SLOs on evaluatedAt, e.g. require status.evaluatedAt < before(SLO_BURN_MAX_AGE_MS) whenever status.state === 'error'.
🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/controllers/sloStatus.ts:205 — if (window == null) return 'deferred' can never run → window is null only when windowDue is true, and then it is replaced by computeSloWindow, which returns Promise<SloWindowNumbers> (never null) or throws. Running out of time already comes out as a thrown SloQueryDeadlineError. Remove the branch, or narrow with window ??= await computeSloWindow(...).
  • 🔵 P3 packages/api/src/routers/api/__tests__/slos.int.test.ts:637 — No test covers a failed refresh or running out of deadline → The new tests only cover successful refreshes. Nothing checks that a failure keeps the last numbers with state: 'error' and lastSuccessAt, or that an SLO stopped by the deadline is left untouched. A regression in the catch branch of refreshSloStatus, such as the abort-as-error case above, would still pass. Add an integration test that refreshes once, makes the source or query fail (e.g. delete the source), refreshes again, and asserts the preserved numbers and the error state. Add another that passes a near-expired deadline and asserts the status is not written.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. No data loss, injection, auth, or guaranteed-crash defects. The one adversarial lead — an updateSlo/refresh race resurrecting a stale snapshot — was traced and confirmed safe: the { _id, updatedAt } optimistic guard no-ops the write when an edit lands mid-refresh. Everything new is gated behind the off-by-default ENABLE_SLOS flag, which bounds the blast radius of the P2 items below.

🟡 P2 — recommended

  • packages/api/src/controllers/slo.ts:64 — getSloQueryContext builds a new ClickhouseClient (keep-alive socket pool) per SLO and never calls .close(); the refresh loop runs this up to SLO_REFRESH_BATCH_LIMIT (200) times per ~60s task cadence, churning HTTP agents released only by GC and idle-socket TTL.
    • Fix: Wrap each SLO's context use in try/finally and await ctx.clickhouseClient.close(), or reuse one client per (team, source, connection) across the batch.
    • reliability, performance, correctness
  • packages/api/src/controllers/sloStatus.ts:186 — the due-query's $or includes a status.windowEvaluatedAt clause, but the Slo model indexes only status.evaluatedAt (models/slo.ts:64); an unindexed $or branch forces a full collection scan plus a blocking in-memory sort on every task run.
    • Fix: Add an index covering status.windowEvaluatedAt (or a compound/partial index serving all three $or branches) and verify with explain().
    • performance
  • packages/api/src/controllers/sloStatus.ts:166 — Slo.updateOne sits outside refreshSloStatus's try/catch, so a thrown write returns before outcome is assigned and refreshCounter.add (line 220) never runs; the two outer .catch log handlers also emit no metric, so write-time failures are counted as neither success, error, nor deferred — the error metric understates reliability problems exactly when Mongo is degraded.
    • Fix: Record an error outcome on the write/outer-catch paths (finally or catch) so every refresh attempt increments the counter.
    • reliability, project-standards
  • packages/api/src/controllers/sloStatus.ts:140 — the error branch hand-reconstructs a full SloStatus literal field-by-field (paralleling getStoredWindow, getStoredBurn, and buildSloStatus); a new optional field added to SloStatus compiles cleanly but is silently dropped from the degraded snapshot and the stored projections.
    • Fix: Build the degraded status by spreading previous (with an explicit first-failure default path), and derive the stored projections from the shared Pick types so a new field forces an update in one place.
    • maintainability, kieran-typescript
  • packages/api/src/controllers/sloStatus.ts:193 — a deferred return (deadline hit) happens before the updateOne, so status.evaluatedAt never advances; SLOs whose whole-window query consistently exceeds the per-query timeout re-sort to the front of the stalest-first queue every run and re-consume the 40s deadline, starving other due SLOs from ever refreshing.
    • Fix: Record an attempt/backoff timestamp on deferral, or cap consecutive deferrals, so persistently-slow SLOs are deprioritized instead of monopolizing the queue.
    • adversarial
  • packages/api/src/controllers/sloStatus.ts:126 — the PR's two stated safety guarantees — a failed evaluation keeps prior numbers and marks state:'error' (never reads healthy), and a deadline yields deferred with no write — have no test; the integration tests drive only the happy path and the unit tests fully mock refreshDueSloStatuses.
    • Fix: Add tests that force a non-deadline query error (assert state:'error', prior numbers and lastSuccessAt retained) and a near/expired deadline (assert deferred and no updateOne).
    • testing, correctness, reliability
🔵 P3 nitpicks (6)
  • packages/api/src/controllers/slo.ts:192 — changed compares groupBy with ?? null while the write normalizes with || null, so an edit sending groupBy: '' spuriously marks the SLO changed and $unsets the status (transient, self-healing on next refresh).
    • Fix: Use (existing.groupBy || null) !== (definition.groupBy || null) to match the write normalization.
    • correctness, kieran-typescript
  • packages/api/src/controllers/slo.ts:193 — changed detects indicator edits via JSON.stringify equality, which is key-order-sensitive and works only because both sides currently flow through the same Zod parse; a future nested-schema or default-field change would make every edit look changed.
    • Fix: Compare the Zod-normalized shapes or use a structural deep-equal.
    • kieran-typescript, correctness
  • packages/api/src/controllers/sloStatus.ts:137 — a single transient non-deadline error (one-off ClickHouse 5xx, reset) overwrites a healthy state with error for up to a full burn cadence, with no N-consecutive-failures tolerance.
    • Fix: Promote to error only after K consecutive failures, or distinguish a stale state from error.
    • adversarial
  • packages/api/src/controllers/sloStatusQueries.ts:34 — SLO_QUERY_TIMEOUT_MS (30s, per-query abort) and SLO_REFRESH_CLIENT_TIMEOUT_MS (30s, client request timeout in sloStatus.ts) encode the same budget in two files and can drift apart.
    • Fix: Export one shared constant, or derive the client timeout from the query timeout.
    • maintainability
  • packages/api/src/controllers/sloStatus.ts:160 — the stored-error cap getErrorMessage(e).slice(0, 2000) hard-codes a magic number.
    • Fix: Extract a named constant such as SLO_ERROR_MESSAGE_MAX_LEN.
    • maintainability
  • packages/api/src/routers/api/__tests__/slos.int.test.ts:761 — the grouped-SLO test anchors spans to Math.floor(Date.now()/300_000)*300_000 but later calls refreshDueSloStatuses() with a fresh new Date(), so crossing a 5-minute boundary between setup and refresh can shift burn-window alignment and flake the exact burn[0] assertions.
    • Fix: Pass an explicit now derived from the same end anchor into refreshDueSloStatuses().
    • testing

Reviewers (10): correctness, reliability, performance, adversarial, kieran-typescript, testing, maintainability, project-standards, agent-native, learnings-researcher.

Testing gaps:

  • Optimistic-concurrency no-op: an updateSlo edit landing between the .lean() fetch and the { _id, updatedAt } write should persist nothing — untested.
  • Exact staleness boundaries (inclusive >= at 5min burn / 30min window) — tests probe only 6min/31min.
  • Grouped SLO with more than SLO_MAX_GROUPS (100) groups, exercising the separate groupCount recount query — untested.
  • IS_SLOS_ENABLED=false branch (refresh never started, sloRefresh stays resolved) — not explicitly asserted.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 03dd2305 Deployed Nov 24, 2026 by vercel[bot]
Preview – hyperdx-storybook — 03dd2305 Deployed Nov 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant