Skip to content

feat(common-utils): SLO counts query - #3791

Open
alex-fedotyev wants to merge 1 commit into
alex/HDX-3001-slo-03-alert-targetsfrom
alex/HDX-3001-slo-04-counts-query
Open

alex-fedotyev wants to merge 1 commit into
alex/HDX-3001-slo-03-alert-targetsfrom
alex/HDX-3001-slo-04-counts-query

Conversation

@alex-fedotyev

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

Copy link
Copy Markdown
Contributor

Summary

Adds the one query every SLO number comes from
(buildSloCountsChartConfig): eligible and good counts over a range, per
bucket, for one group, or by group (the 100 groups with the most events,
plus one to tell when there are more, and a distinct group count). It is
built with buildSearchChartConfig, the builder Search uses, so a
drill-down with the same where clause and filters sees the same events.
Bad is eligible minus good, so an event whose good condition is NULL
counts as bad. The burn rules read 5-minute buckets over the last 6
hours, ending on a 5-minute boundary.

Also adds the bad-events search for drill-downs, the parsers for the
query rows, describeFilter (moved here so the API and the app share it)
and an "slo" query attribution surface.

Stack

Part 4 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 (this PR)
  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
  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__/slo.test.ts: the counts, burn and group queries, the row parsers and the bad-events search are covered, and a snapshot pins the rendered counts SQL.

Test plan

  • unit: core/__tests__/slo.test.ts (counts, burn and group queries, parsers, bad-events search, rendered SQL snapshot)
  • 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.

[as-cast: allow] The cast check matches the word "as" in comments and strings here; the diff has no as casts.

Adds the one query every SLO number comes from
(buildSloCountsChartConfig): eligible and good counts over a range, per
bucket, for one group, or by group (the 100 groups with the most events,
plus one to tell when there are more, and a distinct group count). It is
built with buildSearchChartConfig, the builder Search uses, so a
drill-down with the same where clause and filters sees the same events.
Bad is eligible minus good, so an event whose good condition is NULL
counts as bad. The burn rules read 5-minute buckets over the last 6
hours, ending on a 5-minute boundary.

Also adds the bad-events search for drill-downs, the parsers for the
query rows, describeFilter (moved here so the API and the app share it)
and an "slo" query attribution surface.

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: 0913099

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:35pm UTC
hyperdx-storybook Ready Ready Preview Nov 24, 2026 6:35pm 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 • 1357s

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-3 Standard — full human review required label Nov 24, 2026
@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: 531 production lines changed (Tier 2 max: < 250)

Additional context: touches the query rendering engine lightly (1 lines, under the 150-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: 3
  • Production lines changed: 531 (+ 320 in test files, excluded from tier calculation)
  • Branch: alex/HDX-3001-slo-04-counts-query
  • 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.

}

// `slo_group` is SLO_GROUP_ALIAS, the group's column in a query by group.
const groupValueSchema = z.object({ slo_group: z.coerce.string() });

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 — A NULL group value turns into the string "null", so that group's own queries and drill-downs match nothing

z.coerce.string() turns a NULL slo_group (for example toString of a Nullable or JSON subcolumn) into "null", and a missing column into "undefined". getSloGroupFilter then filters on toString(x) = 'null', which matches no rows, so the group's scoped counts, burn and bad-events drill-down come back empty. Coercion also means safeParse can never fail, so the !parsed.success branches are dead code. Fix: use z.union([z.string(), z.number()]).transform(String) so null and undefined are rejected, or wrap the group expression as ifNull(toString(...), '') in getSloGroupExpression.

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

* Per group: the SLO_MAX_GROUPS busiest plus one, which tells the caller
* there are more, or the given groups.
*/
| { byGroup: true; groups?: string[] };

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 — { byGroup: true } with a granularity and no groups returns every group, with no limit

The limit of SLO_MAX_GROUPS + 1 only applies when granularity == null. So buildSloBurnChartConfig({ scope: { byGroup: true } }), or a bucketed counts query, returns rows for every distinct group times 72 buckets, which can be unbounded on a high-cardinality group-by. The SloGroupScope type allows this, but the docs don't describe it. Fix: make the bucketed by-group variant require groups (for example { byGroup: true; groups: string[] } for bucketed queries), or apply a limit there as well.

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.

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

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

🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/common-utils/src/filters.ts:617 — describeFilter was copied, not moved: the original in the API is still there → The PR says it moved describeFilter, but the identical private copy at packages/api/src/tasks/checkAlerts/template.ts:120 is still there, and the same expression is inlined at packages/app/src/DBSearchPage.tsx:667. Delete the API copy and import from @hyperdx/common-utils/dist/filters, and use it in DBSearchPage too, so there is one source of truth.
  • 🔵 P3 packages/common-utils/src/core/__tests__/slo.test.ts:131 — Several new query builders and helpers have no tests → No test renders buildSloGroupCountChartConfig (count_distinct over toString(groupBy)), buildSloSourceTotalChartConfig, buildSloAvailabilityCondition (trace versus log severity branches), getSloBurnRule, getSloHistoryGranularity or the empty-groups '0' filter. The PR says the group queries are covered, but only the by-group counts are. Add render and snapshot tests for each, including a log source with a tableFilterExpression.

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. This is a new, well-structured, well-commented query layer in packages/common-utils, with no in-diff callers (consumers land in later stack PRs). No P0/P1: the sharpest risks are latent contracts in the new builders that only fail if a future caller misuses them, so they land as P2. Security cleared the SQL construction (escapeSqlString is correct and complete; the raw groupBy expression interpolation matches the codebase's existing trusted-author SQL model).

🟡 P2 — recommended

  • packages/common-utils/src/core/slo.ts:249 — the byGroup + granularity path (the burn/history query) applies the GROUP BY but skips both the ORDER BY slo_eligible DESC and the LIMIT SLO_MAX_GROUPS + 1, so scope: { byGroup: true } without an explicit groups list produces an unbounded per-group scan over ~72 five-minute buckets, re-run every evaluation.
    • Fix: Require groups for any byGroup query when granularity is set (throw when omitted), or always bound the grouped query with a LIMIT/group filter.
    • adversarial, performance, correctness
  • packages/common-utils/src/core/slo.ts:452 — getSloBurnCounts recomputes each window as end - windowMs from an end passed separately, while getSloBurnQueryRange floors now to a 5-minute boundary internally and discards it; a caller that threads raw now instead of the floored range end shifts every window off the bucket grid and drops the boundary bucket, skewing burn-rate and min-events math at alert thresholds.
    • Fix: Derive end inside getSloBurnCounts from the same floored boundary, or assert end is a 5-minute multiple.
    • adversarial, correctness
  • packages/common-utils/src/core/slo.ts:332 — count = z.coerce.number().catch(0) on every field combined with .parse(rows[0] ?? {}) means the single-row parsers can never throw, so a malformed/garbage count silently becomes a real 0, feeding SLI and burn-rate math as a healthy/no_data SLO rather than surfacing the query failure.
    • Fix: Distinguish an absent row (legitimate "no data") from an unparseable value; drop the dead throwing-.parse() pretense by returning SloCounts | undefined via safeParse where "no data" vs error matters.
    • kieran-typescript, correctness
  • packages/common-utils/src/core/slo.ts:512 — buildSloAvailabilityCondition has four untested branches (trace with/without statusCodeExpression, log with severityTextExpression, neither) and it produces the default good condition, so a regression here silently changes which events count as good.
    • Fix: Add tests covering all four branches and their exact emitted SQL.
    • testing
  • packages/common-utils/src/core/slo.ts:281 — several new exported builders/parsers have no direct tests: buildSloGroupCountChartConfig, buildSloSourceTotalChartConfig (deliberately bypasses the eligibility where), parseSloTotalRow, and the new describeFilter export (packages/common-utils/src/filters.ts:617, consumed by alert templating).
    • Fix: Add render/parse tests asserting each builder's emitted SQL and each parser's string-coercion and empty-row fallback.
    • testing, api-contract
🔵 P3 nitpicks (8)
  • packages/common-utils/src/filters.ts:617 — the new shared describeFilter is byte-identical to a private copy at packages/api/src/tasks/checkAlerts/template.ts:120, which this PR does not switch to the shared export, so the two can drift.
    • Fix: In a stack PR, replace the local describeFilter in template.ts with an import of the shared one.
    • api-contract, project-standards
  • packages/common-utils/src/core/slo.ts:382 — groupValueSchema uses z.coerce.string() for slo_group, so a NULL or missing group column coerces to the literal string "null"/"undefined" and merges semantically distinct groups into one SLI/state bucket.
    • Fix: Use a non-coercing z.string() with safeParse so null/absent group rows are dropped rather than renamed.
    • kieran-typescript, adversarial
  • packages/common-utils/src/core/slo.ts:238 — the top-N group query orders only by slo_eligible DESC with no tie-break, so which groups land inside SLO_MAX_GROUPS + 1 flaps between evaluations when eligible counts tie, flapping per-group state and alerts.
    • Fix: Add a stable secondary ordering (e.g. the group expression) to the orderBy.
    • adversarial, correctness
  • packages/common-utils/src/core/slo.ts:299 — buildSloGroupCountChartConfig interpolates slo.groupBy directly via getSloGroupExpression instead of routing through getSloGroupBy, so an empty/whitespace groupBy renders toString() (invalid SQL) rather than being treated as ungrouped.
    • Fix: Normalize through getSloGroupBy or guard against an empty group expression.
  • packages/common-utils/src/core/slo.ts:235 — the comment "The busiest groups first, with one row more than are tracked." sits on the orderBy, but the "+1" (SLO_MAX_GROUPS + 1) is applied in the limit block at lines 249-251.
    • Fix: Keep "busiest first" on orderBy and move the "+1" note onto the limit.
  • packages/common-utils/src/core/slo.ts:474 — buildSloBadEventsSearch(slo, defaultSelect?, group?) uses trailing positional optionals, inconsistent with the options-object style of the sibling builders, forcing undefined placeholders at call sites that only need group.
    • Fix: Take a single destructured options object to match the other builders.
  • packages/common-utils/src/core/slo.ts:35 — SloQueryDefinition re-declares groupBy by hand instead of Pick<SloDefinition, 'indicator' | 'groupBy'>, so the type can silently drift from the schema if SloDefinition.groupBy changes.
    • Fix: Derive groupBy via Pick, or add a type-level assignability assertion.
  • packages/common-utils/src/core/slo.ts:211 — the byGroup decision is spread across four conditionals (filter push, groupBy select, orderBy, limit) with the byGroup && granularity == null guard duplicated, so a grouping-semantics change must stay in sync across all of them.
    • Fix: Hoist a single const rankByGroup = byGroup && granularity == null reused by the orderBy and limit branches.

Reviewers (12): correctness, adversarial, security, testing, maintainability, performance, api-contract, kieran-typescript, project-standards, agent-native, learnings-researcher, previous-comments.

Testing gaps:

  • Burn-window boundary cases: now already on a 5-minute boundary, empty buckets, and an end that is not the floored range end.
  • byGroup scope matrix (ungrouped / group / byGroup / groups: [] match-nothing) crossed with granularity present vs absent, asserting the resulting groupBy/orderBy/limit.
  • Parser empty-row and malformed-value fallbacks (rows[0] ?? {} + .catch(0)), and the 'slo' round-trip through the attribution.ts QuerySurface schema.

Other notes:

  • Security cleared the diff; residual check for maintainers — confirm SLO create/update authorization matches the Search/SQL-query authorization level, since groupBy/good/eligible.where are trusted author-written SQL.
  • The builders accept a raw SloIndicator/SloQueryDefinition without re-running the schema; an unvalidated availability indicator with good: '' yields NOT ifNull((), 0) (invalid SQL). Unreachable through schema-validated input, but undefended at this layer.
  • Bucket timestamp parsing (new Date(bucket)) depends on the ClickHouse client emitting ISO/Z-suffixed UTC strings; a future query path with different settings would offset burn windows by the session timezone. getSloBurnCounts/sumSloBuckets also do not dedupe buckets by ts.
  • Learnings: no prior art in docs/solutions/ for this domain — a good candidate to capture post-merge (SQL-escaping convention, 64-bit-ints-as-strings coercion, 5-minute bucket boundary handling). Agent-native: PASS — pure functions, serializable I/O, injected clock.
  • No changeset in this PR is a documented, release-owned stack deferral (ships in part 6); not treated as a code finding.

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 — 0913099a Deployed Nov 24, 2026 by vercel[bot]
Preview – hyperdx-storybook — 0913099a 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