From cfb4203cff900c8c7e185f97519695fd25c8b897 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Thu, 19 Nov 2026 17:11:36 +0300 Subject: [PATCH 1/3] perf(api): read only the last evaluation for grouped alerts that a value 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 #3508 --- .changeset/alert-history-last-evaluation.md | 7 ++ .../providers/__tests__/default.int.test.ts | 92 +++++++++++++++++++ .../tasks/checkAlerts/providers/default.ts | 21 ++++- 3 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 .changeset/alert-history-last-evaluation.md diff --git a/.changeset/alert-history-last-evaluation.md b/.changeset/alert-history-last-evaluation.md new file mode 100644 index 000000000..a24915a20 --- /dev/null +++ b/.changeset/alert-history-last-evaluation.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +perf(api): a due grouped alert that a value of 0 does not breach reads only its +last evaluation's history rows, one per group, instead of every row in the +lookback window diff --git a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts index b815587ac..044b9b465 100644 --- a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts @@ -987,6 +987,98 @@ describe('DefaultAlertProvider', () => { ); }); + it('reads only the last evaluation for a due grouped alert that a value of 0 does not breach', async () => { + const { alert } = await createValidSavedSearchAlert( + await createConnectionAndSource(), + { groupBy: 'ServiceName' }, + ); + const windowMs = 5 * 60_000; + const lastEvaluation = new Date( + currentWindowStart().getTime() - windowMs, + ); + // Older evaluations: 'old' last reported OK, so it has no row in the + // last evaluation and no state worth keeping. + for (let i = 2; i <= 4; i++) { + await AlertHistory.create({ + alert: alert._id, + createdAt: new Date(lastEvaluation.getTime() - i * windowMs), + state: AlertState.OK, + group: 'old', + }); + } + await AlertHistory.create({ + alert: alert._id, + createdAt: lastEvaluation, + state: AlertState.ALERT, + group: 'a', + fired: true, + }); + await AlertHistory.create({ + alert: alert._id, + createdAt: lastEvaluation, + state: AlertState.OK, + group: 'b', + }); + + const findSpy = jest.spyOn(AlertHistory, 'find'); + const result = await provider.getAlertTasks(); + + // One find, on the last evaluation's createdAt: no lookback scan. + expect(findSpy).toHaveBeenCalledTimes(1); + expect(findSpy.mock.calls[0][0]).toMatchObject({ + createdAt: lastEvaluation, + }); + const { previousMap } = result[0].alerts[0]; + expect([...previousMap.keys()].sort()).toEqual([ + `${alert.id}||a`, + `${alert.id}||b`, + ]); + const groupA = previousMap.get(`${alert.id}||a`); + expect(groupA?.state).toBe(AlertState.ALERT); + expect(groupA?.fired).toBe(true); + }); + + it('keeps the lookback scan for a grouped alert that a value of 0 breaches', async () => { + const { alert } = await createValidSavedSearchAlert( + await createConnectionAndSource(), + { groupBy: 'ServiceName' }, + ); + await Alert.updateOne( + { _id: alert._id }, + { $set: { thresholdType: AlertThresholdType.BELOW, threshold: 1 } }, + ); + const windowMs = 5 * 60_000; + const lastEvaluation = new Date( + currentWindowStart().getTime() - windowMs, + ); + // 'gone' stopped reporting while in ALERT. A value of 0 breaches, so + // processAlert writes no OK row for it and only the scan finds it. + await AlertHistory.create({ + alert: alert._id, + createdAt: new Date(lastEvaluation.getTime() - 2 * windowMs), + state: AlertState.ALERT, + group: 'gone', + fired: true, + }); + await AlertHistory.create({ + alert: alert._id, + createdAt: lastEvaluation, + state: AlertState.OK, + group: 'a', + }); + + const result = await provider.getAlertTasks(); + + const { previousMap } = result[0].alerts[0]; + expect([...previousMap.keys()].sort()).toEqual([ + `${alert.id}||a`, + `${alert.id}||gone`, + ]); + expect(previousMap.get(`${alert.id}||gone`)?.state).toBe( + AlertState.ALERT, + ); + }); + it('treats an alert as due when its window start cannot be computed', async () => { const { alert } = await createValidSavedSearchAlert( await createConnectionAndSource(), diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index 5399d5f51..90cef5f4e 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -30,6 +30,7 @@ import Webhook, { IWebhook } from '@/models/webhook'; import { alertHasGroupBy, computeHistoryMapKey, + doesExceedThreshold, getAlertWindowStart, getConsecutiveWindowHistories, getLatestAlertHistories, @@ -473,8 +474,18 @@ async function loadAlerts(): Promise { } } + // When a value of 0 does not breach the threshold, every group whose last + // row is ALERT or PENDING has a row in the alert's last evaluation: + // processAlert writes an OK row for each such group missing from the data. + // A previous OK row only matters for its createdAt, which the last + // evaluation also has. So these alerts read only that evaluation (below), + // one row per group, instead of scanning every row in the lookback. const [previousAlerts, recentHistoryMap] = await Promise.all([ - getPreviousAlertHistories(dueGroupedAlerts, now, historyQueryQueue), + getPreviousAlertHistories( + dueGroupedAlerts.filter(alert => doesExceedThreshold(alert, 0)), + now, + historyQueryQueue, + ), getConsecutiveWindowHistories(dueAlertsWithHistory, now, historyQueryQueue), ]); @@ -491,10 +502,10 @@ async function loadAlerts(): Promise { }); } - // A grouped alert whose latest row is older than its scan window gets no - // rows back. Read the rows of that last evaluation instead (one per group, - // all sharing its createdAt), so the evaluation still starts from it and - // every group keeps its previous state. + // Read the rows of the last evaluation (one per group, all sharing its + // createdAt) for the grouped alerts not scanned above, and for those whose + // latest row is older than their scan window, which get no rows back. The + // evaluation then starts from it and every group keeps its previous state. await Promise.all( dueGroupedAlerts.map(alert => { const latest = latestHistories.get(alert.id); From 8f9443242d0725b36619d745992d780960b08457 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Thu, 19 Nov 2026 17:35:41 +0300 Subject: [PATCH 2/3] fix(api): keep the history scan for evaluator alerts and thresholds that cannot be checked --- .../providers/__tests__/default.int.test.ts | 102 +++++++++++------- .../tasks/checkAlerts/providers/default.ts | 26 +++-- 2 files changed, 84 insertions(+), 44 deletions(-) diff --git a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts index 044b9b465..d5cfd4585 100644 --- a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts @@ -22,6 +22,10 @@ import { SavedSearch } from '@/models/savedSearch'; import { Source } from '@/models/source'; import * as checkAlertTasks from '@/tasks/checkAlerts'; import { getScheduledWindowStart } from '@/tasks/checkAlerts'; +import { + clearAlertEvaluators, + registerAlertEvaluator, +} from '@/tasks/checkAlerts/evaluators'; import { AlertProvider, AlertTaskType, @@ -746,6 +750,7 @@ describe('DefaultAlertProvider', () => { describe('history fetch gating (HDX-4791)', () => { afterEach(() => { jest.restoreAllMocks(); + clearAlertEvaluators(); }); // Alerts created by the helpers use interval '5m' with no schedule @@ -1038,46 +1043,67 @@ describe('DefaultAlertProvider', () => { expect(groupA?.fired).toBe(true); }); - it('keeps the lookback scan for a grouped alert that a value of 0 breaches', async () => { - const { alert } = await createValidSavedSearchAlert( - await createConnectionAndSource(), - { groupBy: 'ServiceName' }, - ); - await Alert.updateOne( - { _id: alert._id }, - { $set: { thresholdType: AlertThresholdType.BELOW, threshold: 1 } }, - ); - const windowMs = 5 * 60_000; - const lastEvaluation = new Date( - currentWindowStart().getTime() - windowMs, - ); - // 'gone' stopped reporting while in ALERT. A value of 0 breaches, so - // processAlert writes no OK row for it and only the scan finds it. - await AlertHistory.create({ - alert: alert._id, - createdAt: new Date(lastEvaluation.getTime() - 2 * windowMs), - state: AlertState.ALERT, - group: 'gone', - fired: true, - }); - await AlertHistory.create({ - alert: alert._id, - createdAt: lastEvaluation, - state: AlertState.OK, - group: 'a', - }); + it.each([ + [ + 'a value of 0 breaches', + { thresholdType: AlertThresholdType.BELOW, threshold: 1 }, + ], + [ + 'a registered evaluator handles', + { thresholdType: AlertThresholdType.ABOVE, threshold: 1 }, + true, + ], + [ + 'has a threshold that cannot be checked', + { thresholdType: AlertThresholdType.BETWEEN, thresholdMax: null }, + ], + ])( + 'keeps the lookback scan for a grouped alert that %s', + async (_, threshold, withEvaluator = false) => { + const { alert } = await createValidSavedSearchAlert( + await createConnectionAndSource(), + { groupBy: 'ServiceName' }, + ); + await Alert.updateOne({ _id: alert._id }, { $set: threshold }); + if (withEvaluator) { + registerAlertEvaluator({ + name: 'test', + appliesTo: a => a.id === alert.id, + evaluate: async () => {}, + }); + } + const windowMs = 5 * 60_000; + const lastEvaluation = new Date( + currentWindowStart().getTime() - windowMs, + ); + // 'gone' stopped reporting while in ALERT, and nothing guarantees + // an OK row for it in the last evaluation: only the scan finds it. + await AlertHistory.create({ + alert: alert._id, + createdAt: new Date(lastEvaluation.getTime() - 2 * windowMs), + state: AlertState.ALERT, + group: 'gone', + fired: true, + }); + await AlertHistory.create({ + alert: alert._id, + createdAt: lastEvaluation, + state: AlertState.OK, + group: 'a', + }); - const result = await provider.getAlertTasks(); + const result = await provider.getAlertTasks(); - const { previousMap } = result[0].alerts[0]; - expect([...previousMap.keys()].sort()).toEqual([ - `${alert.id}||a`, - `${alert.id}||gone`, - ]); - expect(previousMap.get(`${alert.id}||gone`)?.state).toBe( - AlertState.ALERT, - ); - }); + const { previousMap } = result[0].alerts[0]; + expect([...previousMap.keys()].sort()).toEqual([ + `${alert.id}||a`, + `${alert.id}||gone`, + ]); + expect(previousMap.get(`${alert.id}||gone`)?.state).toBe( + AlertState.ALERT, + ); + }, + ); it('treats an alert as due when its window start cannot be computed', async () => { const { alert } = await createValidSavedSearchAlert( diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index 90cef5f4e..f9ba2bfe1 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -37,6 +37,7 @@ import { getPreviousAlertHistories, type LatestAlertHistory, } from '@/tasks/checkAlerts'; +import { findAlertEvaluator } from '@/tasks/checkAlerts/evaluators'; import { type AlertDetails, type AlertProvider, @@ -475,14 +476,27 @@ async function loadAlerts(): Promise { } // When a value of 0 does not breach the threshold, every group whose last - // row is ALERT or PENDING has a row in the alert's last evaluation: - // processAlert writes an OK row for each such group missing from the data. - // A previous OK row only matters for its createdAt, which the last - // evaluation also has. So these alerts read only that evaluation (below), - // one row per group, instead of scanning every row in the lookback. + // row is ALERT or PENDING has a row in the alert's last evaluation: the + // threshold path of processAlert writes an OK row for each such group + // missing from the data. A previous OK row only matters for its createdAt, + // which the last evaluation also has. So these alerts read only that + // evaluation (below), one row per group, instead of scanning every row in + // the lookback. A registered evaluator does not run that loop, and a + // threshold that cannot be checked is left for processAlert to report, so + // both keep the scan. + const needsLookbackScan = (alert: IAlert) => { + if (findAlertEvaluator(alert)) { + return true; + } + try { + return doesExceedThreshold(alert, 0); + } catch { + return true; + } + }; const [previousAlerts, recentHistoryMap] = await Promise.all([ getPreviousAlertHistories( - dueGroupedAlerts.filter(alert => doesExceedThreshold(alert, 0)), + dueGroupedAlerts.filter(needsLookbackScan), now, historyQueryQueue, ), From 65b2c7e4e24fdcd52299b38954ca653716e34976 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Thu, 19 Nov 2026 17:47:36 +0300 Subject: [PATCH 3/3] fix(api): treat a failing evaluator lookup like a failing threshold check in the history gate --- .../providers/__tests__/default.int.test.ts | 17 +++++++++++++---- .../src/tasks/checkAlerts/providers/default.ts | 17 +++++++++-------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts index d5cfd4585..cc88bb6bc 100644 --- a/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/providers/__tests__/default.int.test.ts @@ -1047,28 +1047,37 @@ describe('DefaultAlertProvider', () => { [ 'a value of 0 breaches', { thresholdType: AlertThresholdType.BELOW, threshold: 1 }, + undefined, ], [ 'a registered evaluator handles', { thresholdType: AlertThresholdType.ABOVE, threshold: 1 }, - true, + () => true, + ], + [ + 'throws in the evaluator lookup', + { thresholdType: AlertThresholdType.ABOVE, threshold: 1 }, + () => { + throw new Error('evaluator lookup failed'); + }, ], [ 'has a threshold that cannot be checked', { thresholdType: AlertThresholdType.BETWEEN, thresholdMax: null }, + undefined, ], ])( 'keeps the lookback scan for a grouped alert that %s', - async (_, threshold, withEvaluator = false) => { + async (_, threshold, appliesTo?: () => boolean) => { const { alert } = await createValidSavedSearchAlert( await createConnectionAndSource(), { groupBy: 'ServiceName' }, ); await Alert.updateOne({ _id: alert._id }, { $set: threshold }); - if (withEvaluator) { + if (appliesTo) { registerAlertEvaluator({ name: 'test', - appliesTo: a => a.id === alert.id, + appliesTo, evaluate: async () => {}, }); } diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index f9ba2bfe1..a4be7377d 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -481,16 +481,17 @@ async function loadAlerts(): Promise { // missing from the data. A previous OK row only matters for its createdAt, // which the last evaluation also has. So these alerts read only that // evaluation (below), one row per group, instead of scanning every row in - // the lookback. A registered evaluator does not run that loop, and a - // threshold that cannot be checked is left for processAlert to report, so - // both keep the scan. + // 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) => { - if (findAlertEvaluator(alert)) { - return true; - } try { - return doesExceedThreshold(alert, 0); - } catch { + return findAlertEvaluator(alert) != null || doesExceedThreshold(alert, 0); + } catch (e) { + logger.error( + { alertId: alert.id, error: serializeError(e) }, + 'Failed to check whether a grouped alert needs the history scan', + ); return true; } };