Skip to content

perf(api): read only the last evaluation for grouped alerts that a value of 0 does not breach - #3728

Open
bcanvural wants to merge 3 commits into
ClickHouse:mainfrom
bcanvural:fix/alert-history-last-evaluation
Open

bcanvural wants to merge 3 commits into
ClickHouse:mainfrom
bcanvural:fix/alert-history-last-evaluation

Conversation

@bcanvural

@bcanvural bcanvural commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #3702, for the part of #3508 it leaves. After #3702, a due grouped alert scans every history row in its lookback, at least 1 day. For a 1m alert with ~1,300 groups that is ~1.9M rows on every check.

When a value of 0 does not breach the alert's threshold, that scan reads more than the evaluation uses:

  • processAlert writes an OK row for every group that was ALERT or PENDING and is missing from the data (the missing-group loop). So every group whose latest row is ALERT or PENDING has a row in the alert's last evaluation.
  • A previous OK row is only read for its createdAt (window start and skip check). Its state and fired change nothing, and the last evaluation has the latest createdAt.

This PR:

  • passes only the grouped alerts that a value of 0 breaches to getPreviousAlertHistories. The others go to the read perf(api): bound check-alerts history lookup by alert interval #3702 added for catch-up: the rows of the last evaluation ({alert, createdAt: <last>}), one per group;
  • keeps the scan for alerts that a value of 0 breaches, because there the missing-group loop writes nothing and a group can stay ALERT without new rows.

No new index and no DISTINCT_SCAN: the read is an equality match on {alert: 1, createdAt: -1}, so it should behave the same on DocumentDB.

Known difference: if a partial write left out some rows of the last evaluation, those groups lose their previous state. The scan would have found older rows for them.

Numbers (MongoDB 5.0, one day of history for a 1m alert with 1,300 groups, 1.87M rows, find with the provider's filter and projection):

keys examined docs examined time
lookback scan (1 day) 1,872,000 1,872,000 14–20 s
last evaluation 1,300 1,300 11–21 ms

How to reproduce

Starting point: make dev-int.

On main:

  1. Add the two tests from this PR to packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts.
  2. make dev-int FILE="providers/default.int.test --testNamePattern=value.of.0": reads only the last evaluation… fails, because the scan returns the stale old group and runs a second find.

On this branch:

  1. The same command passes both tests.
  2. make dev-int FILE=checkAlerts passes (361 tests).

How to test on Vercel preview

N/A — non-UI change.

References


Note

Medium Risk
Changes alert evaluation state seeding for high-volume grouped alerts; optimized path can drop stale group state if the last evaluation write was partial, while exceptions still use the full scan.

Overview
Perf improvement for grouped alert history loading: due grouped alerts that use the standard threshold path and where 0 does not breach no longer run the full lookback getPreviousAlertHistories scan. They rely on the existing last-evaluation fetch (AlertHistory.find on the latest row’s createdAt), one document per group.

The default alert provider adds needsLookbackScan, which keeps the lookback when a custom evaluator applies, when doesExceedThreshold(alert, 0) is true (e.g. BELOW thresholds where zero breaches), when the threshold cannot be checked, or when evaluator/threshold checks throw (safe fallback). Other grouped alerts still get last-evaluation rows for catch-up when the scan returns nothing.

Integration tests cover the single last-evaluation query, preserved lookback for the exception cases, and clearAlertEvaluators in teardown. Trade-off: groups missing from a partial last evaluation may lose prior state that the old scan would have recovered.

Reviewed by Cursor Bugbot for commit 65b2c7e. Bugbot is set up for automated code reviews on this repo. Configure here.

@bcanvural
bcanvural requested a review from a team as a code owner November 19, 2026 14:27
@vercel

vercel Bot commented Nov 19, 2026

Copy link
Copy Markdown

@bcanvural is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

@changeset-bot

changeset-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 65b2c7e

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

github-actions Bot commented Nov 19, 2026 •

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/api/src/tasks/checkAlerts/providers/default.ts:498 — The rule for skipping the scan restates processAlert's missing-group condition in a second module → needsLookbackScan is only correct while the missing-group loop in processAlert (index.ts:1846-1851) writes an OK row exactly when no evaluator applies and !doesExceedThreshold(alert, 0). Nothing links the two copies: if someone later changes that loop (say, to also skip groups missing for a single window), this filter silently drops state. Fix: export one predicate from tasks/checkAlerts/index.ts, e.g. writesOkForMissingGroups(alert), and call it from both the loop and loadAlerts.

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

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

The optimization is well-reasoned: performance confirmed the equality read hits the existing {alert:1, createdAt:-1} index with no new index and ~3-orders-of-magnitude fewer rows, reliability confirmed the fail-open-to-scan error handling is correct, and the previous-comments pass confirmed all four earlier fix threads (throwing threshold check, evaluator short-circuit, evaluator-lookup throw, bare-catch logging) are addressed in the current code. The findings below cluster around one correctness invariant and its test/maintainability tail.

🔴 P0/P1 — must fix

  • packages/api/src/tasks/checkAlerts/providers/default.ts:487 — A grouped alert edited from a threshold that a value of 0 breaches to one it does not, while a group sits stale in ALERT/PENDING with no row at the last evaluation's createdAt, now skips the lookback scan and never re-seeds that group, so it is never auto-resolved and its resolve notification is silently lost; pre-diff the full scan found and resolved it.
    • Fix: Force one lookback scan after an alert's threshold, group-by, or evaluator changes via a persisted marker the next check consults, or get explicit maintainer sign-off that this behavior change is accepted and track it as a follow-up.
    • correctness, adversarial-reviewer, previous-comments

🟡 P2 — recommended

  • packages/api/src/tasks/checkAlerts/providers/default.ts:487 — The needsLookbackScan optimization silently depends on the !doesExceedThreshold(alert, 0) guard in the missing-group loop in index.ts (~line 1850) with no reciprocal pointer there, so a future edit to that guard breaks the optimization with no local or test tripwire.
    • Fix: Add a reciprocal comment at the missing-group loop pointing back to needsLookbackScan, or extract the shared condition into one named predicate called from both sites.
    • maintainability, correctness, adversarial-reviewer
  • packages/api/src/tasks/checkAlerts/providers/default.ts:535 — A tolerated partial AlertHistory write at the prior evaluation (a per-row create rejection swallowed by updateAlertState's allSettled) can leave a firing group without a row at the last createdAt, so the last-evaluation read drops it and it is never resolved.
    • Fix: When history persistence reports a failed row for an alert, force that alert onto the full-scan path on its next evaluation instead of trusting the last-evaluation read.
  • packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts:995 — The fast-path test seeds only an ALERT group and an OK group, but the optimization's correctness claim explicitly rests on PENDING groups also always having a last-evaluation row; the PENDING half of the invariant is untested.
    • Fix: Add a PENDING group to the last evaluation and assert it is seeded into previousMap with state PENDING.
🔵 P3 nitpicks (3)
  • packages/api/src/tasks/checkAlerts/providers/default.ts:489 — needsLookbackScan infers boolean | undefined because doesExceedThreshold's switch has no exhaustiveness default; .filter works only via truthiness coercion.
    • Fix: Annotate the predicate return as : boolean, or add an exhaustiveness guard to doesExceedThreshold.
  • packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts:1025 — The toHaveBeenCalledTimes(1) assertion holds only because numConsecutiveWindows defaults to 1; a multi-window grouped alert would add a consecutive-window query and is never exercised on the fast path.
    • Fix: Add a case with numConsecutiveWindows > 1 asserting the last-evaluation read still runs while the lookback scan stays skipped.
  • packages/api/src/tasks/checkAlerts/providers/default.ts:535 — The projection and row-to-AggregatedAlertHistory mapping are duplicated between this catch-up read and getPreviousAlertHistories in index.ts (pre-existing), so a tracked-field change must be made in lockstep across files.
    • Fix: Extract a shared projection constant and mapper used by both reads.

Reviewers (8): correctness, adversarial, performance, reliability, testing, maintainability, kieran-typescript, previous-comments.

Testing gaps:

  • No regression test for the threshold-flip edge case (stale ALERT group + threshold edited across the 0-breach boundary → still auto-resolves).
  • No test asserts an evaluator-backed grouped alert keeps the full lookback scan via the findAlertEvaluator(alert) != null short-circuit.
  • No test asserts filtered-out (optimized) and full-scan grouped alerts produce identical previousMap contents for the same fixtures.

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

@pulpdrew
pulpdrew requested a review from wrn14897 November 19, 2026 14:38
@bcanvural

Copy link
Copy Markdown
Contributor Author

On the deep review:

  • Throwing threshold check: fixed in f9af9e7 (see the inline thread).
  • Linking the filter to the missing-group loop: the comment on needsLookbackScan names the loop it depends on. A matching comment at the loop would mean changing index.ts, which this PR doesn't touch otherwise.
  • PENDING groups: the missing-group loop treats PENDING the same as ALERT, and the last-evaluation read returns every row whatever its state, so I didn't add a separate case.
  • toHaveBeenCalledTimes(1): the single find is what shows the lookback scan didn't run; the test also checks that its filter is the last evaluation's createdAt.

@bcanvural

Copy link
Copy Markdown
Contributor Author

On the deep review, round 2:

  • Reciprocal comment at the missing-group loop: as in round 1, that means changing index.ts, which this PR doesn't otherwise touch.
  • Threshold exactly 0, PENDING groups, multi-window alerts: whether 0 breaches is doesExceedThreshold(alert, 0), the same call the missing-group loop makes, so the boundary follows it; the loop treats PENDING like ALERT; and getConsecutiveWindowHistories still reads every due alert, so multi-window alerts are unchanged.
  • The bare catch: it now logs the error, in 57a355f.

// the lookback. A registered evaluator does not run that loop, and an
// evaluator lookup or threshold check that throws is left for processAlert
// to report, so these keep the scan.
const needsLookbackScan = (alert: IAlert) => {

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 — needsLookbackScan checks the alert's current threshold, but the invariant it relies on was built under the old threshold or evaluator. Editing an alert can leave ALERT groups that never resolve

The shortcut assumes every ALERT/PENDING group has a row in the last evaluation. That only holds if earlier evaluations ran the missing-group loop, i.e. if 0 did not breach the threshold back then and no evaluator handled the alert. Example: an alert with BELOW 1 has group G in ALERT, and G stops reporting. The missing-group loop is skipped because 0 breaches, so G gets no new rows. The user then edits the threshold to ABOVE 100. Alert updates in controllers/alerts.ts do not clear AlertHistory. Now needsLookbackScan is false, the last-evaluation read finds no row for G, and G drops out of previousMap. So the missing-group loop at index.ts:1819-1842 never writes its OK row and no resolve notification is ever sent. Before this PR, the scan found G's ALERT row and resolved it. The same happens when an evaluator stops applying to an alert, since evaluators also skip that loop. Fix: also take the scan path when the alert changed after its last evaluation's createdAt (alert.updatedAt > latest.createdAt, or a stored hash of threshold, thresholdType and evaluator). Add a test that flips the threshold from 0-breaching to non-breaching while a silent group is in ALERT.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the same issue as the two threads above. Checking alert.updatedAt doesn't work here: every alert check updates updatedAt, so it is always newer than the last evaluation. Changing that would also change what the UI and the API show. I'm leaving this for a maintainer to decide.

@bcanvural

Copy link
Copy Markdown
Contributor Author

@wrn14897 the bots have done two review rounds. One point is still open (raised in three threads):

  1. An alert's threshold is set so that a value of 0 triggers it (for example "below 1").
  2. A group is in ALERT and then stops sending data. It stays in ALERT, because 0 still triggers.
  3. Someone edits the alert so that 0 no longer triggers (for example "above 100").
  4. With this PR, that group is never resolved and never gets a resolve notification. Before this PR, the next check would have resolved it.

Fixing this needs extra information that we don't store today: either a mark on the alert when it's edited, or the alert settings saved with each check. Both mean changes outside this PR's file. Should I handle it here, or is this edge case acceptable?

@bcanvural

Copy link
Copy Markdown
Contributor Author

@wrn14897 a reminder about my question above (#3728 (comment)). The PR still merges cleanly.

I suggest we accept the edge case. It only happens in a rare mix: a threshold that 0 breaches, a group that went quiet, and a later edit to the threshold. If you want it fixed, I can do that in a follow-up PR.

@bcanvural

Copy link
Copy Markdown
Contributor Author

@karl-power would you have time to review this, or know who could? It has been waiting for an alerts review since 19-Nov and still merges cleanly. The one open question is in the comment above; I suggest accepting that edge case and fixing it in a follow-up PR if wanted.

@bcanvural

Copy link
Copy Markdown
Contributor Author

@pulpdrew you reviewed #3702, which this follows up. Would you have time to look at this one?

@bcanvural

Copy link
Copy Markdown
Contributor Author

@pulpdrew a gentle nudge on this one when you have time. It's the follow-up to #3702: for grouped alerts that a value of 0 doesn't breach, each check reads only the last evaluation instead of every history row in the lookback (about 1.9M rows per check for a 1m alert with ~1,300 groups). It still merges cleanly.

…lue of 0 does not breach

Every group whose last row is ALERT or PENDING has a row in the last
evaluation, because processAlert writes an OK row for each such group missing
from the data. Previous OK rows only matter for their createdAt. So these
alerts read one row per group instead of every row in the lookback.

Refs ClickHouse#3508
@wrn14897
wrn14897 force-pushed the fix/alert-history-last-evaluation branch from 57a355f to 65b2c7e Compare December 4, 2026 04:20
@vercel

vercel Bot commented Dec 4, 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 Dec 4, 2026 4:23am UTC
hyperdx-storybook Ready Ready Preview Dec 4, 2026 4:23am UTC

Request Review

// the lookback. A registered evaluator does not run that loop, and an
// evaluator lookup or threshold check that throws is left for processAlert
// to report, so these keep the scan.
const needsLookbackScan = (alert: IAlert) => {

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 — Groups stay in ALERT for good when the threshold is edited so that 0 stops breaching

The new path relies on the missing-group loop having run in earlier evaluations, but that loop only runs when !doesExceedThreshold(alert, 0) (index.ts:1850). updateAlert (controllers/alerts.ts:377) keeps the history when the threshold changes. Example: a grouped BELOW 1 alert has group x in ALERT. x stops reporting, so the loop writes nothing for it and its ALERT row ages out of the last evaluation. The user then changes the alert to ABOVE 100. From then on needsLookbackScan is false, so only the last evaluation is read. x never enters previousMap, never gets an OK row and never sends a resolve notification. The old scan would have found it and resolved it. The same gap appears when an evaluator stops applying to an alert. Fix: fall back to the scan for the first evaluation after a threshold or evaluator change. For example, compare alert.updatedAt with latest.createdAt, or store the 0-breaches flag on the history row and scan when it differs. Add an integration test for an edit from BELOW to ABOVE.

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

This branch was successfully deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant