Skip to content

feat(common-utils): SLO stats and state - #3792

Open
alex-fedotyev wants to merge 1 commit into
alex/HDX-3001-slo-04-counts-queryfrom
alex/HDX-3001-slo-05-stats
Open

alex-fedotyev wants to merge 1 commit into
alex/HDX-3001-slo-04-counts-queryfrom
alex/HDX-3001-slo-05-stats

Conversation

@alex-fedotyev

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

Copy link
Copy Markdown
Contributor

Summary

Adds the math that turns the counts query's rows into SLO numbers: the SLI,
the error budget and how much of it is left, the burn rate of each window,
and the fast and slow burn conditions. An SLO is breached when its budget is
spent, burning when either condition holds, and healthy otherwise. A group
of a grouped SLO needs 100 events in the window for a state of its own, and
the SLO takes the state of its worst group.

Stack

Part 5 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 (this PR)
  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
  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.

How to reproduce

Starting point: a checkout of this branch.

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

On this branch:

  1. cd packages/common-utils && npx jest src/core/__tests__/sloStats.test.ts: bad is eligible minus good, the burn rate is a multiple of the allowed bad rate, a condition needs both windows and enough events, and a grouped SLO takes its worst group with enough events.

Test plan

  • unit: core/__tests__/sloStats.test.ts (stats, burn rule, groups)
  • 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

[no-changeset: allow] The changeset for this piece is in part 6.

Adds the math that turns the counts query's rows into SLO numbers: the SLI,
the error budget and how much of it is left, the burn rate of each window,
and the fast and slow burn conditions. An SLO is breached when its budget is
spent, burning when either condition holds, and healthy otherwise. A group
of a grouped SLO needs 100 events in the window for a state of its own, and
the SLO takes the state of its worst group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@changeset-bot

changeset-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: d7afdf7

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@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 6:37pm UTC
hyperdx-storybook Ready Ready Preview Nov 24, 2026 6:37pm UTC

Request Review

@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

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 475 passed • 1 skipped • 1122s

Status Count
✅ Passed 475
❌ Failed 0
⚠️ Flaky 13
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@alex-fedotyev
alex-fedotyev marked this pull request as ready for review November 24, 2026 18:52
@alex-fedotyev
alex-fedotyev requested a review from a team as a code owner November 24, 2026 18:52
@github-actions github-actions Bot added the review/tier-2 Low risk — AI review + quick human skim label Nov 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔵 Tier 2 — Low Risk

Small, isolated change with no API route or data model modifications.

Why this tier:

  • Standard feature/fix — introduces new logic or modifies core functionality

Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns.
SLA: Resolve within 4 business hours.

Stats
  • Production files changed: 1
  • Production lines changed: 232 (+ 246 in test files, excluded from tier calculation)
  • Branch: alex/HDX-3001-slo-05-stats
  • Author: alex-fedotyev

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

worst = state;
}
}
return worst ?? deriveSloState(overall);

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 — Grouped SLO state ignores the overall numbers once any group has 100+ events, so a breached or burning SLO can report 'healthy'

Once any group qualifies, deriveGroupedSloState returns worst and never looks at overall. The groups don't cover everything: groups under SLO_GROUP_MIN_EVENTS are skipped, and SloStatus.groups keeps only the busiest SLO_MAX_GROUPS (packages/common-utils/src/slo.ts). So the bad events behind an overspent overall budget can sit in those small or untracked groups. Example: one healthy group with 10k events plus 500 groups of 50 events, each fully bad. The status then shows state: 'healthy' next to a negative overall budgetRemaining, and the SLO never burns or breaches. Fix: return the worse of worst and deriveSloState(overall) (stateSeverity already ranks them), and add a test where the overall SLO is breached and every qualifying group is healthy.

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

@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.

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

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

🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/common-utils/src/core/__tests__/sloStats.test.ts:218 — The row-based burn helpers barely tested: computeSloBurnFromRows has no test, and the grouped test skips the short window and 6h condition → The grouped test feeds 12 identical buckets and checks only burn.get('checkout')[0]'s long-window eligible/bad/burnRate. So a wrong short-window range (5m/30m), an off-by-one at the end bucket boundary, or a swapped 6h condition would all still pass. Add a test for computeSloBurnFromRows. Use buckets that differ inside vs outside the last 5 minutes and before/after end, and assert shortBurnRate and burn[1] too.

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. The correctness and adversarial passes traced the math against the shared helpers and found no logic bugs introduced by this diff: target is schema-validated to (0,100) so errorBudget > 0 whenever eligible > 0 (the breached guard is never short-circuited), bad clamps with Math.max(0, …) for late good > eligible rows, and the getSloBurnSeverity floor-to-two-decimals boundary holds. The recommendations below are missing-test and maintainability items.

🟡 P2 -- recommended

  • packages/common-utils/src/core/sloStats.ts:67 -- computeSloBurnFromRows is exported with real parse→count→stats logic but has zero test coverage, while its sibling computeSloGroupBurnFromRows is tested.
    • Fix: Add a single-SLO burn-from-rows test mirroring the grouped fixture, asserting the 1h condition's eligible, bad, and burnRate.
    • testing, maintainability, kieran-typescript
  • packages/common-utils/src/core/sloStats.ts:123 -- The new budgetRemainingEvents field (errorBudget - bad) is set on every computeSloStats result but never asserted in any test, including its negative overspent case.
    • Fix: Assert budgetRemainingEvents in the existing bad-events and burning tests, covering a positive and a negative value.
    • testing, correctness, kieran-typescript
  • packages/common-utils/src/core/sloStats.ts:133 -- The eligibility/burn predicate eligible >= minEvents && burnRate != null && shortBurnRate != null is duplicated in isSloBurnConditionMet and getSloBurnSeverity, so a future change to the gate can silently diverge between the two.
    • Fix: Extract one helper returning the condition's ratio (or null) and define both functions in terms of it.
    • maintainability
  • packages/common-utils/src/core/sloStats.ts:177 -- stateSeverity's switch has no exhaustiveness guard, and the package's tsconfig sets noImplicitReturns: false, so the : number return annotation does not catch a missing case; a future SloState variant would return undefined and silently mis-order groups.
    • Fix: Add a default branch assigning state to a never-typed constant so a new variant becomes a compile error.
    • kieran-typescript
🔵 P3 nitpicks (5)
  • packages/common-utils/src/core/sloStats.ts:163 -- Math.floor(severity * 100) / 100 can drop a non-boundary closeness value by 0.01 due to binary-float error (e.g. 0.29 → 0.28); the downward bias at 1.0 is intentional, the sub-cent drift elsewhere is not.
    • Fix: Round the scaled value before flooring, or document that sub-cent downward drift is acceptable for this indicator.
  • packages/common-utils/src/core/sloStats.ts:47 -- The counts.at(i) ?? { eligible: 0, good: 0, shortEligible: 0, shortGood: 0 } fallback inlines an untyped zero SloBurnCounts whose four defaults are re-declared in the test helper.
    • Fix: Extract a typed EMPTY_SLO_BURN_COUNTS constant and reuse it in both places.
  • packages/common-utils/src/core/sloStats.ts:67 -- computeSloBurnFromRows and computeSloGroupBurnFromRows run the same rule→range→counts→stats pipeline independently.
    • Fix: Express both over a shared internal (rule, end, buckets) => SloBurnStats[] closure, or leave as-is if the single-SLO path is meant to stay independent.
  • packages/common-utils/src/core/sloStats.ts:138 -- For a low-traffic SLO, a severe sustained 1h burn produces no burning state when the trailing short window happens to have zero eligible events (shortBurnRate is null), since the short window has no minEvents floor; this matches the documented resolve semantics but can miss or flap fast-burn alerts.
    • Fix: Add a test pinning this empty-short-window behavior and confirm the suppression is intended for sparse traffic.
  • packages/common-utils/src/core/sloStats.ts:197 -- A group that has fully overspent its budget but sits just below SLO_GROUP_MIN_EVENTS is treated as insufficient_data and skipped by deriveGroupedSloState, so a chronically bad low-volume group can be masked by healthy larger groups; this is documented-intended but surfaces as a silently masked breach.
    • Fix: Add a test for the sub-threshold-breached-group-masked case and confirm the threshold behavior is acceptable.

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

Testing gaps:

  • sli/budgetRemaining null branches and the errorBudget === 0 path are not pinned for the eligible === 0 case.
  • computeSloBurnRate with target = 100 (zero error budget → null) is untested.
  • deriveGroupedSloState/compareSloGroupsWorstFirst are untested for an error group state and for the equal-severity tie-break (NaN-guarded null budgets).

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 — d7afdf73 Deployed Nov 24, 2026 by vercel[bot]
Preview – hyperdx-storybook — d7afdf73 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-2 Low risk — AI review + quick human skim

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant