From ba6f7dea37d953e4cd8b6880dfef2e03e2d7abac Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Mon, 30 Nov 2026 14:19:40 +0100 Subject: [PATCH 1/3] feat(alerts): add an opt-in re-notify interval for firing alerts An alert can set renotifyIntervalMinutes: while it keeps firing, it notifies at most once every that many minutes. Unset keeps notifying on every evaluation. Each history record carries lastNotifiedAt forward, so the check in trySendNotification only reads the previous evaluation. Closes #2464 Co-authored-by: Niladri Adhikary --- .changeset/alert-renotify-interval.md | 7 ++ packages/api/openapi.json | 7 ++ packages/api/src/controllers/alerts.ts | 1 + .../api/src/mcp/tools/alerts/saveAlert.ts | 12 +- packages/api/src/mcp/tools/alerts/schemas.ts | 10 ++ packages/api/src/models/alert.ts | 8 ++ packages/api/src/models/alertHistory.ts | 5 + packages/api/src/routers/api/alerts.ts | 1 + .../external-api/__tests__/alerts.int.test.ts | 37 ++++++ .../api/src/routers/external-api/v2/alerts.ts | 6 + .../__tests__/checkAlerts.int.test.ts | 106 ++++++++++++++++++ packages/api/src/tasks/checkAlerts/index.ts | 30 ++++- packages/api/src/utils/externalApi.ts | 2 + packages/api/src/utils/zod.ts | 2 + packages/app/src/DBSearchPageAlertModal.tsx | 10 ++ .../src/components/AlertScheduleFields.tsx | 48 +++++++- .../DBEditTimeChartForm/TileAlertEditor.tsx | 6 + .../alerts/AlertPropertiesSummary.tsx | 9 ++ .../src/components/alerts/EditAlertModal.tsx | 9 ++ .../alerts/EditInlineAlertModal.tsx | 1 + packages/common-utils/src/types.ts | 9 ++ 21 files changed, 320 insertions(+), 6 deletions(-) create mode 100644 .changeset/alert-renotify-interval.md diff --git a/.changeset/alert-renotify-interval.md b/.changeset/alert-renotify-interval.md new file mode 100644 index 0000000000..b8d46b1965 --- /dev/null +++ b/.changeset/alert-renotify-interval.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/app': minor +'@hyperdx/api': minor +--- + +feat: alerts get an opt-in "Re-notify every N minutes" setting (`renotifyIntervalMinutes`). While an alert keeps firing it notifies at most once per interval; unset keeps today's behaviour of notifying on every evaluation. Resolve notifications are unchanged. diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 735ea5c34f..44388fca75 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -419,6 +419,13 @@ "nullable": true, "description": "Fire the alert only after its condition has been met for this many consecutive evaluation windows. While the condition is met but fewer than this many consecutive windows have violated, the alert is in the PENDING state.", "example": 3 + }, + "renotifyIntervalMinutes": { + "type": "integer", + "minimum": 1, + "nullable": true, + "description": "While the alert keeps firing, repeat its notification at most once every this many minutes. Omit or set to null to notify on every evaluation. A resolve notification is always sent when the alert returns to OK.", + "example": 60 } } }, diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index e51887ec8d..ef7c43dc31 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -336,6 +336,7 @@ export const makeAlert = ( // Multi-window alerting numConsecutiveWindows: alert.numConsecutiveWindows ?? null, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? null, }; }; diff --git a/packages/api/src/mcp/tools/alerts/saveAlert.ts b/packages/api/src/mcp/tools/alerts/saveAlert.ts index 24883dc011..b188d8498a 100644 --- a/packages/api/src/mcp/tools/alerts/saveAlert.ts +++ b/packages/api/src/mcp/tools/alerts/saveAlert.ts @@ -56,8 +56,9 @@ export function registerSaveAlert({ '(webhook IDs come from clickstack_get_webhook). Updates replace the ' + 'alert configuration rather than merging it: channels you do not resend are ' + 'removed, omitted name and message are cleared, and omitted displayName ' + - 'and tags are re-derived from the source. Omitted note and ' + - 'numConsecutiveWindows keep their stored values. Omitting both ' + + 'and tags are re-derived from the source. Omitted note, ' + + 'numConsecutiveWindows and renotifyIntervalMinutes keep their stored ' + + 'values. Omitting both ' + 'scheduleStartAt and scheduleOffsetMinutes keeps the stored schedule; ' + 'clearing scheduleStartAt without an offset resets the offset to 0. Read the alert with ' + 'clickstack_get_alert first and resend every field you want to keep.', @@ -123,7 +124,8 @@ export function registerSaveAlert({ scheduleStartAt: input.scheduleStartAt, name: input.name, message: input.message, - // Unlike name and message, an omitted note or window count keeps the + // Unlike name and message, an omitted note, window count or re-notify + // interval keeps the // stored value: callers written before this tool accepted them would // otherwise wipe what was set in the UI. null still clears. note: input.note === undefined ? existing?.note : input.note, @@ -131,6 +133,10 @@ export function registerSaveAlert({ input.numConsecutiveWindows === undefined ? existing?.numConsecutiveWindows : input.numConsecutiveWindows, + renotifyIntervalMinutes: + input.renotifyIntervalMinutes === undefined + ? existing?.renotifyIntervalMinutes + : input.renotifyIntervalMinutes, displayName: input.displayName, tags: input.tags, groupBy: input.groupBy, diff --git a/packages/api/src/mcp/tools/alerts/schemas.ts b/packages/api/src/mcp/tools/alerts/schemas.ts index b9c019f16a..788ae2b6f4 100644 --- a/packages/api/src/mcp/tools/alerts/schemas.ts +++ b/packages/api/src/mcp/tools/alerts/schemas.ts @@ -234,6 +234,16 @@ export const mcpSaveAlertSchema = z.object({ 'boundary. Must be less than the interval. Ignored when ' + 'scheduleStartAt is set.', ), + renotifyIntervalMinutes: z + .number() + .int() + .min(1) + .nullish() + .describe( + 'While the alert keeps firing, repeat its notification at most once ' + + 'every N minutes. null notifies on every evaluation; omitting it ' + + 'keeps the stored value. A resolve notification is always sent.', + ), scheduleStartAt: z .string() .datetime() diff --git a/packages/api/src/models/alert.ts b/packages/api/src/models/alert.ts index 3e62d19eab..e88422b222 100644 --- a/packages/api/src/models/alert.ts +++ b/packages/api/src/models/alert.ts @@ -127,6 +127,9 @@ export interface IAlert { // Multi-window alerting: fire only after N violations in M consecutive windows numConsecutiveWindows?: number | null; + // While firing, notify at most every N minutes; unset notifies on every evaluation. + renotifyIntervalMinutes?: number | null; + // Errors recorded during the most recent execution executionErrors?: IAlertError[]; createdAt: Date; @@ -256,6 +259,11 @@ const AlertSchema = new Schema( required: false, min: 1, }, + renotifyIntervalMinutes: { + type: Number, + required: false, + min: 1, + }, silenced: { required: false, type: { diff --git a/packages/api/src/models/alertHistory.ts b/packages/api/src/models/alertHistory.ts index 203fbe074e..2ca609b2f8 100644 --- a/packages/api/src/models/alertHistory.ts +++ b/packages/api/src/models/alertHistory.ts @@ -74,6 +74,7 @@ export interface IAlertHistory { errors?: IAlertError[]; /** Diagnostics for the evaluation that wrote this record. */ analytics?: IAlertHistoryAnalytics; + lastNotifiedAt?: Date; } const AlertHistorySchema = new Schema({ @@ -162,6 +163,10 @@ const AlertHistorySchema = new Schema({ required: false, default: undefined, }, + lastNotifiedAt: { + type: Date, + required: false, + }, }); AlertHistorySchema.index( diff --git a/packages/api/src/routers/api/alerts.ts b/packages/api/src/routers/api/alerts.ts index a6264db351..f53ab70928 100644 --- a/packages/api/src/routers/api/alerts.ts +++ b/packages/api/src/routers/api/alerts.ts @@ -123,6 +123,7 @@ const formatAlertResponse = ( 'updatedAt', 'executionErrors', 'numConsecutiveWindows', + 'renotifyIntervalMinutes', ]), tileId: alert.tileId ?? undefined, groupBy: alert.groupBy ?? undefined, diff --git a/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts b/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts index a0f93373a3..a775062c31 100644 --- a/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/alerts.int.test.ts @@ -512,6 +512,7 @@ describe('External API Alerts', () => { message: 'This is a test alert for format verification', note: null, numConsecutiveWindows: null, + renotifyIntervalMinutes: null, threshold: 123, interval: '15m', source: AlertSource.TILE, @@ -3173,6 +3174,42 @@ describe('External API Alerts', () => { expect(getResponse.body.data.numConsecutiveWindows).toBeNull(); }); }); + describe('Re-notification interval (renotifyIntervalMinutes)', () => { + it('should create an alert with renotifyIntervalMinutes and return it on GET', async () => { + const { alert } = await createTestAlert({ renotifyIntervalMinutes: 60 }); + expect(alert.renotifyIntervalMinutes).toBe(60); + + const getResponse = await authRequest( + 'get', + `${ALERTS_BASE_URL}/${alert.id}`, + ).expect(200); + expect(getResponse.body.data.renotifyIntervalMinutes).toBe(60); + }); + + it('should update an alert to set and then clear renotifyIntervalMinutes', async () => { + const { alert, alertInput } = await createTestAlert(); + expect(alert.renotifyIntervalMinutes).toBeNull(); + + const getRenotify = async () => + (await authRequest('get', `${ALERTS_BASE_URL}/${alert.id}`).expect(200)) + .body.data.renotifyIntervalMinutes; + + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: 30 }) + .expect(200); + expect(await getRenotify()).toBe(30); + + // Unset already means every evaluation, so 0 has no meaning. + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: 0 }) + .expect(400); + + await authRequest('put', `${ALERTS_BASE_URL}/${alert.id}`) + .send({ ...alertInput, renotifyIntervalMinutes: null }) + .expect(200); + expect(await getRenotify()).toBeNull(); + }); + }); describe('Multiple notification channels', () => { const makeWebhookNamed = async (name: string) => await Webhook.findOneAndUpdate( diff --git a/packages/api/src/routers/external-api/v2/alerts.ts b/packages/api/src/routers/external-api/v2/alerts.ts index f4abc4c2c5..a1a0a92d5f 100644 --- a/packages/api/src/routers/external-api/v2/alerts.ts +++ b/packages/api/src/routers/external-api/v2/alerts.ts @@ -329,6 +329,12 @@ function toInternalAlertInput(body: ExternalAlertInput): InternalAlertInput { * nullable: true * description: Fire the alert only after its condition has been met for this many consecutive evaluation windows. While the condition is met but fewer than this many consecutive windows have violated, the alert is in the PENDING state. * example: 3 + * renotifyIntervalMinutes: + * type: integer + * minimum: 1 + * nullable: true + * description: While the alert keeps firing, repeat its notification at most once every this many minutes. Omit or set to null to notify on every evaluation. A resolve notification is always sent when the alert returns to OK. + * example: 60 * * AlertResponse: * allOf: diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts index 2fe606d236..b5c8d2ddb6 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -11508,6 +11508,112 @@ describe('checkAlerts', () => { ); }); + describe('re-notification (renotifyIntervalMinutes)', () => { + // Breaching rows in the given 5m windows; evaluations run 2m after each + // window closes. + const runBreaches = async ( + windows: string[], + evaluations: string[], + renotifyIntervalMinutes?: number, + ) => { + const { + team, + webhook, + connection, + source, + savedSearch, + teamWebhooksById, + clickhouseClient, + } = await setupSavedSearchAlertTest(); + + jest + .spyOn(slack, 'postMessageToWebhook') + .mockResolvedValue({ text: 'ok' }); + + const details = await createAlertDetails( + team, + source, + { + source: AlertSource.SAVED_SEARCH, + channel: { type: 'webhook', webhookId: webhook._id.toString() }, + interval: '5m', + thresholdType: AlertThresholdType.ABOVE, + threshold: 1, + savedSearchId: savedSearch.id, + renotifyIntervalMinutes, + }, + { taskType: AlertTaskType.SAVED_SEARCH, savedSearch }, + ); + + await bulkInsertLogs( + windows.map(time => ({ + ServiceName: 'api', + Timestamp: new Date(`2024-01-01T${time}Z`), + SeverityText: 'error', + Body: 'err', + })), + ); + + const notificationCounts: number[] = []; + for (const time of evaluations) { + await processAlertAtTime( + new Date(`2024-01-01T${time}Z`), + details, + clickhouseClient, + connection, + alertProvider, + teamWebhooksById, + ); + notificationCounts.push( + jest.mocked(slack.postMessageToWebhook).mock.calls.length, + ); + } + + const histories = await AlertHistory.find({ + alert: details.alert.id, + }).sort({ createdAt: 1 }); + return { notificationCounts, histories }; + }; + + const SUSTAINED = ['00:05:00', '00:10:00', '00:15:00', '00:20:00']; + const EVALUATIONS = ['00:12:00', '00:17:00', '00:22:00', '00:27:00']; + + it('notifies on every evaluation when unset', async () => { + const { notificationCounts } = await runBreaches( + SUSTAINED, + EVALUATIONS, + ); + expect(notificationCounts).toEqual([1, 2, 3, 4]); + }); + + it('re-notifies only once the interval has passed', async () => { + // 10m interval, 5m windows: notify, skip, notify, skip. + const { notificationCounts, histories } = await runBreaches( + SUSTAINED, + EVALUATIONS, + 10, + ); + expect(notificationCounts).toEqual([1, 1, 2, 2]); + expect(histories.map(h => h.lastNotifiedAt?.toISOString())).toEqual([ + '2024-01-01T00:10:00.000Z', + '2024-01-01T00:10:00.000Z', + '2024-01-01T00:20:00.000Z', + '2024-01-01T00:20:00.000Z', + ]); + }); + + it('notifies a new incident after a resolve, inside the interval', async () => { + // ALERT, OK (resolve notification), ALERT again. + const { notificationCounts, histories } = await runBreaches( + ['00:05:00', '00:15:00'], + ['00:12:00', '00:17:00', '00:22:00'], + 60, + ); + expect(histories.map(h => h.state)).toEqual(['ALERT', 'OK', 'ALERT']); + expect(notificationCounts).toEqual([1, 2, 3]); + }); + }); + describe('multi-window alerting (numConsecutiveWindows)', () => { it('fires on the first violation when numConsecutiveWindows=1', async () => { const { diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 404108a7f1..7976efc1fe 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -1340,7 +1340,7 @@ export const processAlert = async ( // Resolves true when a dispatch was attempted (even if delivery later // fails — failures surface via executionErrors, mirroring the threshold // path which marks history.fired before dispatching), and false when the - // send was suppressed entirely (silenced). + // send was suppressed entirely (silenced, or inside the re-notify interval). const trySendNotification = async ({ group, totalCount, @@ -1372,6 +1372,28 @@ export const processAlert = async ( return false; } + // Opt-in: a group that was already firing re-notifies only once its + // interval has passed. Every record carries the time forward, so the + // previous evaluation is all this needs to read. + if (state === AlertState.ALERT && alert.renotifyIntervalMinutes) { + const previous = previousMap.get(computeHistoryMapKey(alert.id, group)); + const lastNotifiedAt = + previous?.state === AlertState.ALERT + ? previous.lastNotifiedAt + : undefined; + const history = getOrCreateHistory(group); + if ( + lastNotifiedAt && + nowInMinsRoundDown < + fns.addMinutes(lastNotifiedAt, alert.renotifyIntervalMinutes) + ) { + history.lastNotifiedAt = lastNotifiedAt; + alertEvaluationsCounter.add(1, { outcome: 'skipped_renotify' }); + return false; + } + history.lastNotifiedAt = nowInMinsRoundDown; + } + alertEvaluationsCounter.add(1, { outcome: state === AlertState.ALERT ? 'fired' : 'resolved', }); @@ -1865,7 +1887,8 @@ export const processAlert = async ( const hitAlertThisRun = latestAlertContext.has(groupKey); - // If it hit ALERT during this run, send the notification (re-notifying every tick if it continuously breaches) + // If it hit ALERT during this run, send the notification (re-notifying every tick + // if it continuously breaches, unless renotifyIntervalMinutes spaces them out) if (hitAlertThisRun) { const context = latestAlertContext.get(groupKey); if (context) { @@ -1959,6 +1982,7 @@ export interface AggregatedAlertHistory { state: AlertState; group?: string; fired?: boolean; + lastNotifiedAt?: Date; groupValues?: GroupValue[] | null; } @@ -2133,6 +2157,7 @@ export const getPreviousAlertHistories = async ( state: 1, createdAt: 1, fired: 1, + lastNotifiedAt: 1, groupValues: 1, }, ) @@ -2153,6 +2178,7 @@ export const getPreviousAlertHistories = async ( state: row.state, group: row.group, fired: row.fired, + lastNotifiedAt: row.lastNotifiedAt, groupValues: row.groupValues, }); } diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index c445cb5746..23f71dcd55 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -350,6 +350,7 @@ export type ExternalAlert = { scheduleOffsetMinutes?: number; scheduleStartAt?: string | null; numConsecutiveWindows?: number | null; + renotifyIntervalMinutes?: number | null; thresholdType: AlertThresholdType; source?: string; state: AlertState; @@ -523,6 +524,7 @@ export function translateAlertDocumentToExternalAlert( }), scheduleStartAt: transformScheduleStartAt(alertObj.scheduleStartAt), numConsecutiveWindows: alertObj.numConsecutiveWindows ?? null, + renotifyIntervalMinutes: alertObj.renotifyIntervalMinutes ?? null, thresholdType: alertObj.thresholdType, source: alertObj.source, state: alertObj.state, diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 3ab00b89f2..94390f3718 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -9,6 +9,7 @@ import { alertDisplayNameSchema, alertNoteSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, alertTagsSchema, AlertThresholdType, BackgroundChartSchema, @@ -1311,6 +1312,7 @@ const alertBaseSchema = z.object({ displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); // External v2 alert schema. Inline alerts carry their chart config in the diff --git a/packages/app/src/DBSearchPageAlertModal.tsx b/packages/app/src/DBSearchPageAlertModal.tsx index 2c540742f5..ad2b1d7c9d 100644 --- a/packages/app/src/DBSearchPageAlertModal.tsx +++ b/packages/app/src/DBSearchPageAlertModal.tsx @@ -15,6 +15,7 @@ import { alertDisplayNameSchema, AlertIntervalSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, AlertSource, alertTagsSchema, AlertThresholdType, @@ -93,6 +94,7 @@ const SavedSearchAlertFormSchema = z displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }) .passthrough() .superRefine(validateAlertScheduleOffsetMinutes) @@ -212,6 +214,8 @@ const AlertForm = ({ // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: defaultValues.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: + defaultValues.renotifyIntervalMinutes ?? undefined, } : { interval: '5m', @@ -240,6 +244,10 @@ const AlertForm = ({ control, name: 'numConsecutiveWindows', }); + const renotifyIntervalMinutes = useWatch({ + control, + name: 'renotifyIntervalMinutes', + }); const maxScheduleOffsetMinutes = Math.max( intervalToMinutes(interval ?? '5m') - 1, 0, @@ -383,6 +391,8 @@ const AlertForm = ({ offsetWindowLabel={`from each ${intervalLabel} window`} numConsecutiveWindowsName="numConsecutiveWindows" numConsecutiveWindows={numConsecutiveWindows ?? undefined} + renotifyIntervalName="renotifyIntervalMinutes" + renotifyIntervalMinutes={renotifyIntervalMinutes ?? undefined} /> grouped by diff --git a/packages/app/src/components/AlertScheduleFields.tsx b/packages/app/src/components/AlertScheduleFields.tsx index 774baca58a..ff5b52615b 100644 --- a/packages/app/src/components/AlertScheduleFields.tsx +++ b/packages/app/src/components/AlertScheduleFields.tsx @@ -38,6 +38,8 @@ type AlertScheduleFieldsProps = { offsetWindowLabel: string; numConsecutiveWindowsName?: FieldPath; numConsecutiveWindows?: number; + renotifyIntervalName?: FieldPath; + renotifyIntervalMinutes?: number; }; export function AlertScheduleFields({ @@ -50,6 +52,8 @@ export function AlertScheduleFields({ offsetWindowLabel, numConsecutiveWindowsName, numConsecutiveWindows, + renotifyIntervalName, + renotifyIntervalMinutes, }: AlertScheduleFieldsProps) { const showScheduleOffsetInput = maxScheduleOffsetMinutes > 0; const scheduleStartAtValue = useWatch({ @@ -60,7 +64,8 @@ export function AlertScheduleFields({ const hasAdvancedScheduleValues = (scheduleOffsetMinutes ?? 0) > 0 || hasScheduleStartAtAnchor || - (numConsecutiveWindows ?? 1) > 1; + (numConsecutiveWindows ?? 1) > 1 || + renotifyIntervalMinutes != null; const [opened, setOpened] = useState(hasAdvancedScheduleValues); useEffect(() => { @@ -149,6 +154,47 @@ export function AlertScheduleFields({ )} + {renotifyIntervalName && ( + + + + Re-notify every + + + + + + + + ( + + field.onChange(typeof v === 'number' ? v : undefined) + } + min={1} + allowDecimal={false} + allowNegative={false} + size="xs" + w={90} + /> + )} + /> + + minutes + + + )} {showScheduleOffsetInput && ( <> diff --git a/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx b/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx index 5b3c225464..28dafe87a8 100644 --- a/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/TileAlertEditor.tsx @@ -97,6 +97,10 @@ export function TileAlertEditor({ control, name: 'alert.numConsecutiveWindows', }); + const alertRenotifyIntervalMinutes = useWatch({ + control, + name: 'alert.renotifyIntervalMinutes', + }); const maxAlertScheduleOffsetMinutes = alert?.interval ? Math.max(intervalToMinutes(alert.interval) - 1, 0) : 0; @@ -292,6 +296,8 @@ export function TileAlertEditor({ } numConsecutiveWindowsName="alert.numConsecutiveWindows" numConsecutiveWindows={alertnumConsecutiveWindows ?? undefined} + renotifyIntervalName="alert.renotifyIntervalMinutes" + renotifyIntervalMinutes={alertRenotifyIntervalMinutes ?? undefined} /> Send to diff --git a/packages/app/src/components/alerts/AlertPropertiesSummary.tsx b/packages/app/src/components/alerts/AlertPropertiesSummary.tsx index 233b082ebc..2bccb0062b 100644 --- a/packages/app/src/components/alerts/AlertPropertiesSummary.tsx +++ b/packages/app/src/components/alerts/AlertPropertiesSummary.tsx @@ -204,6 +204,15 @@ export function AlertPropertiesSummary({ )} + {alert.renotifyIntervalMinutes != null && ( + <> + · + + Re-notifies every {alert.renotifyIntervalMinutes} min while + firing + + + )} )} · diff --git a/packages/app/src/components/alerts/EditAlertModal.tsx b/packages/app/src/components/alerts/EditAlertModal.tsx index 31be03de44..c755a6b309 100644 --- a/packages/app/src/components/alerts/EditAlertModal.tsx +++ b/packages/app/src/components/alerts/EditAlertModal.tsx @@ -8,6 +8,7 @@ import { alertDisplayNameSchema, AlertIntervalSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, AlertSource, alertTagsSchema, AlertThresholdType, @@ -76,6 +77,7 @@ const EditAlertFormSchema = z displayName: alertDisplayNameSchema, tags: alertTagsSchema, numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }) .passthrough() .superRefine(validateAlertChannelSelection) @@ -114,6 +116,7 @@ function alertToFormValues(alert: AlertsPageItem): Alert { tags: alert.tags, // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: alert.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? undefined, }; if (alert.source === AlertSource.TILE) { @@ -215,6 +218,10 @@ export function EditAlertModal({ control, name: 'numConsecutiveWindows', }); + const renotifyIntervalMinutes = useWatch({ + control, + name: 'renotifyIntervalMinutes', + }); const maxScheduleOffsetMinutes = Math.max( intervalToMinutes(interval ?? '5m') - 1, @@ -418,6 +425,8 @@ export function EditAlertModal({ offsetWindowLabel={`from each ${intervalLabel} window`} numConsecutiveWindowsName="numConsecutiveWindows" numConsecutiveWindows={numConsecutiveWindows ?? undefined} + renotifyIntervalName="renotifyIntervalMinutes" + renotifyIntervalMinutes={renotifyIntervalMinutes ?? undefined} /> {!isChartAlert && ( <> diff --git a/packages/app/src/components/alerts/EditInlineAlertModal.tsx b/packages/app/src/components/alerts/EditInlineAlertModal.tsx index 98dbc95907..a21fe20796 100644 --- a/packages/app/src/components/alerts/EditInlineAlertModal.tsx +++ b/packages/app/src/components/alerts/EditInlineAlertModal.tsx @@ -56,6 +56,7 @@ export function inlineAlertToChartConfig( note: alert.note ?? null, // Persisted null -> undefined for the NumberInput. numConsecutiveWindows: alert.numConsecutiveWindows ?? undefined, + renotifyIntervalMinutes: alert.renotifyIntervalMinutes ?? undefined, }, }; } diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 44ed622ceb..7ccf713a85 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1109,6 +1109,13 @@ export const alertNumConsecutiveWindowsSchema = z .min(1) .nullish(); +// Unset notifies on every evaluation while the alert fires. +export const alertRenotifyIntervalMinutesSchema = z + .number() + .int() + .min(1) + .nullish(); + export const MAX_ALERT_DISPLAY_NAME_LENGTH = 512; export const alertDisplayNameSchema = z .string() @@ -1148,6 +1155,7 @@ export const AlertBaseObjectSchema = z.object({ }) .optional(), numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); // Keep AlertBaseSchema as a ZodObject for backwards compatibility with @@ -3295,6 +3303,7 @@ export const AlertsPageItemSchema = z.object({ .optional(), executionErrors: z.array(AlertErrorSchema).optional(), numConsecutiveWindows: alertNumConsecutiveWindowsSchema, + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema, }); export type AlertsPageItem = z.infer; From 29fc30baea669f97008c77ab8bcbdd8f2f3eb6e5 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Mon, 30 Nov 2026 14:34:00 +0100 Subject: [PATCH 2/3] fix(alerts): carry lastNotifiedAt through the provider's history loaders Ungrouped alerts and stale grouped alerts get their previous state from getLatestAlertHistories and the last-evaluation fallback, not from getPreviousAlertHistories, so the re-notify interval never applied to them. Also tests a grouped alert's per-group interval and the MCP save rules, and documents the new false return for evaluators. --- .../api/src/mcp/__tests__/alerts.int.test.ts | 21 +++++++++-- .../__tests__/checkAlerts.int.test.ts | 35 +++++++++++++++---- .../api/src/tasks/checkAlerts/evaluators.ts | 5 ++- packages/api/src/tasks/checkAlerts/index.ts | 4 ++- .../providers/__tests__/default.int.test.ts | 4 +++ .../tasks/checkAlerts/providers/default.ts | 11 +++++- 6 files changed, 68 insertions(+), 12 deletions(-) diff --git a/packages/api/src/mcp/__tests__/alerts.int.test.ts b/packages/api/src/mcp/__tests__/alerts.int.test.ts index 8350abd54c..9121c75de3 100644 --- a/packages/api/src/mcp/__tests__/alerts.int.test.ts +++ b/packages/api/src/mcp/__tests__/alerts.int.test.ts @@ -1388,7 +1388,7 @@ describe('MCP Alert Tools', () => { expect(updatedAlert?.tileId).toBeNull(); }); - describe('note and numConsecutiveWindows', () => { + describe('note, numConsecutiveWindows and renotifyIntervalMinutes', () => { async function saveExisting( alertId: string, savedSearchId: string, @@ -1412,6 +1412,7 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( @@ -1425,6 +1426,8 @@ describe('MCP Alert Tools', () => { expect(output.threshold).toBe(200); expect(output.note).toBe('Set in the UI'); expect(output.numConsecutiveWindows).toBe(4); + const persisted = await Alert.findById(alert._id); + expect(persisted?.renotifyIntervalMinutes).toBe(30); }); it('replaces the stored values when provided', async () => { @@ -1432,19 +1435,25 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( alert._id.toString(), alert.savedSearch!.toString(), webhook._id.toString(), - { note: 'Updated note', numConsecutiveWindows: 2 }, + { + note: 'Updated note', + numConsecutiveWindows: 2, + renotifyIntervalMinutes: 60, + }, ); expect(result.isError).toBeFalsy(); const persisted = await Alert.findById(alert._id); expect(persisted?.note).toBe('Updated note'); expect(persisted?.numConsecutiveWindows).toBe(2); + expect(persisted?.renotifyIntervalMinutes).toBe(60); }); it('clears the stored values when sent as null', async () => { @@ -1452,19 +1461,25 @@ describe('MCP Alert Tools', () => { const alert = await createTestAlert({ note: 'Set in the UI', numConsecutiveWindows: 4, + renotifyIntervalMinutes: 30, }); const result = await saveExisting( alert._id.toString(), alert.savedSearch!.toString(), webhook._id.toString(), - { note: null, numConsecutiveWindows: null }, + { + note: null, + numConsecutiveWindows: null, + renotifyIntervalMinutes: null, + }, ); expect(result.isError).toBeFalsy(); const persisted = await Alert.findById(alert._id); expect(persisted?.note).toBeNull(); expect(persisted?.numConsecutiveWindows).toBeNull(); + expect(persisted?.renotifyIntervalMinutes).toBeNull(); }); }); diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts index b5c8d2ddb6..195dc9eed5 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -11509,12 +11509,13 @@ describe('checkAlerts', () => { }); describe('re-notification (renotifyIntervalMinutes)', () => { - // Breaching rows in the given 5m windows; evaluations run 2m after each - // window closes. + // Breaching rows in the given 5m windows (service 'api' unless given as + // [time, service]); evaluations run 2m after each window closes. const runBreaches = async ( - windows: string[], + windows: (string | [string, string])[], evaluations: string[], renotifyIntervalMinutes?: number, + groupBy?: string, ) => { const { team, @@ -11541,14 +11542,17 @@ describe('checkAlerts', () => { threshold: 1, savedSearchId: savedSearch.id, renotifyIntervalMinutes, + groupBy, }, { taskType: AlertTaskType.SAVED_SEARCH, savedSearch }, ); await bulkInsertLogs( - windows.map(time => ({ - ServiceName: 'api', - Timestamp: new Date(`2024-01-01T${time}Z`), + windows.map(w => ({ + ServiceName: typeof w === 'string' ? 'api' : w[1], + Timestamp: new Date( + `2024-01-01T${typeof w === 'string' ? w : w[0]}Z`, + ), SeverityText: 'error', Body: 'err', })), @@ -11612,6 +11616,25 @@ describe('checkAlerts', () => { expect(histories.map(h => h.state)).toEqual(['ALERT', 'OK', 'ALERT']); expect(notificationCounts).toEqual([1, 2, 3]); }); + + it('keeps a separate interval for each group', async () => { + // a breaches from 00:05, b from 00:10; both every window after that. + const { histories } = await runBreaches( + [ + ...SUSTAINED.map((t): [string, string] => [t, 'a']), + ...SUSTAINED.slice(1).map((t): [string, string] => [t, 'b']), + ], + EVALUATIONS, + 10, + 'ServiceName', + ); + const notifiedAt = (service: string) => + histories + .filter(h => h.group === `ServiceName:${service}`) + .map(h => h.lastNotifiedAt?.toISOString().slice(11, 16)); + expect(notifiedAt('a')).toEqual(['00:10', '00:10', '00:20', '00:20']); + expect(notifiedAt('b')).toEqual(['00:15', '00:15', '00:25']); + }); }); describe('multi-window alerting (numConsecutiveWindows)', () => { diff --git a/packages/api/src/tasks/checkAlerts/evaluators.ts b/packages/api/src/tasks/checkAlerts/evaluators.ts index c2504fffdb..3f6c075a12 100644 --- a/packages/api/src/tasks/checkAlerts/evaluators.ts +++ b/packages/api/src/tasks/checkAlerts/evaluators.ts @@ -46,7 +46,10 @@ export interface AlertEvaluationContext { /** Errors collected so far (e.g. failed notification targets). */ executionErrors: IAlertError[]; getOrCreateHistory: (groupKey: string) => IAlertHistory; - /** Resolves false when the send was suppressed (the alert is silenced). */ + /** + * Resolves false when the send was suppressed: the alert is silenced, or it + * is still firing inside its re-notify interval (so `fired` stays true). + */ trySendNotification: (args: { state: AlertState; totalCount: number; diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 7976efc1fe..1f81a9071d 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -2021,7 +2021,7 @@ export const getAlertHistoryLookbackMs = (interval: AlertInterval): number => { /** Latest AlertHistory row per alert, minus the fat `lastValues` array. */ export type LatestAlertHistory = Pick< AggregatedAlertHistory, - 'createdAt' | 'state' | 'group' | 'fired' + 'createdAt' | 'state' | 'group' | 'fired' | 'lastNotifiedAt' >; /** @@ -2067,6 +2067,7 @@ export const getLatestAlertHistories = async ( state: 1, group: 1, fired: 1, + lastNotifiedAt: 1, }, ) .sort({ createdAt: -1 }) @@ -2087,6 +2088,7 @@ export const getLatestAlertHistories = async ( state: latest.state, group: latest.group, fired: latest.fired, + lastNotifiedAt: latest.lastNotifiedAt, } : null, ]), 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 81d7a76896..b815587ace 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 @@ -847,6 +847,7 @@ describe('DefaultAlertProvider', () => { state: AlertState.ALERT, group: '', fired: true, + lastNotifiedAt: new Date(base - 3 * windowMs), }); const findSpy = jest.spyOn(AlertHistory, 'find'); @@ -865,6 +866,7 @@ describe('DefaultAlertProvider', () => { expect(previous!.createdAt).toEqual(newest.createdAt); expect(previous!.state).toBe(AlertState.ALERT); expect(previous!.fired).toBe(true); + expect(previous!.lastNotifiedAt).toEqual(newest.lastNotifiedAt); }); it('skips the per-group history fetch for alerts with no history at all', async () => { @@ -942,6 +944,7 @@ describe('DefaultAlertProvider', () => { state: AlertState.ALERT, group: 'ServiceName:a', fired: true, + lastNotifiedAt: twoDaysAgo, groupValues: [{ key: 'ServiceName', value: 'a' }], }); await AlertHistory.create({ @@ -975,6 +978,7 @@ describe('DefaultAlertProvider', () => { expect(groupA?.createdAt).toEqual(twoDaysAgo); expect(groupA?.state).toBe(AlertState.ALERT); expect(groupA?.fired).toBe(true); + expect(groupA?.lastNotifiedAt).toEqual(twoDaysAgo); expect(groupA?.groupValues).toEqual([ { key: 'ServiceName', value: 'a' }, ]); diff --git a/packages/api/src/tasks/checkAlerts/providers/default.ts b/packages/api/src/tasks/checkAlerts/providers/default.ts index bed6d52109..892a6f1a96 100644 --- a/packages/api/src/tasks/checkAlerts/providers/default.ts +++ b/packages/api/src/tasks/checkAlerts/providers/default.ts @@ -491,6 +491,7 @@ async function loadAlerts(): Promise { state: latest.state, group: latest.group, fired: latest.fired, + lastNotifiedAt: latest.lastNotifiedAt, }); } @@ -515,7 +516,14 @@ async function loadAlerts(): Promise { createdAt: latest.createdAt, state: { $ne: AlertState.ERROR }, }, - { group: 1, state: 1, createdAt: 1, fired: 1, groupValues: 1 }, + { + group: 1, + state: 1, + createdAt: 1, + fired: 1, + lastNotifiedAt: 1, + groupValues: 1, + }, ).lean(); for (const row of rows) { previousAlerts.set(computeHistoryMapKey(alert.id, row.group || ''), { @@ -524,6 +532,7 @@ async function loadAlerts(): Promise { state: row.state, group: row.group, fired: row.fired, + lastNotifiedAt: row.lastNotifiedAt, groupValues: row.groupValues, }); } From c563d7c805cb992f82eb7a73f85ec0b4d1b74093 Mon Sep 17 00:00:00 2001 From: Baris Can Vural Date: Mon, 30 Nov 2026 14:44:43 +0100 Subject: [PATCH 3/3] fix(alerts): keep the re-notify time across a silence A silenced evaluation returned before the re-notify check and wrote no lastNotifiedAt, so a silence shorter than the interval made the alert notify again as soon as it ended. The time is now carried forward first. The MCP schema reuses alertRenotifyIntervalMinutesSchema. --- packages/api/src/mcp/tools/alerts/schemas.ts | 16 ++++------- .../__tests__/checkAlerts.int.test.ts | 20 ++++++++++++- packages/api/src/tasks/checkAlerts/index.ts | 28 +++++++++++-------- 3 files changed, 41 insertions(+), 23 deletions(-) diff --git a/packages/api/src/mcp/tools/alerts/schemas.ts b/packages/api/src/mcp/tools/alerts/schemas.ts index 788ae2b6f4..759434ce2c 100644 --- a/packages/api/src/mcp/tools/alerts/schemas.ts +++ b/packages/api/src/mcp/tools/alerts/schemas.ts @@ -4,6 +4,7 @@ import { type AlertInterval, alertNoteSchema, alertNumConsecutiveWindowsSchema, + alertRenotifyIntervalMinutesSchema, checkAlertChannelSelection, isRangeThresholdType, MAX_ALERT_CHANNELS, @@ -234,16 +235,11 @@ export const mcpSaveAlertSchema = z.object({ 'boundary. Must be less than the interval. Ignored when ' + 'scheduleStartAt is set.', ), - renotifyIntervalMinutes: z - .number() - .int() - .min(1) - .nullish() - .describe( - 'While the alert keeps firing, repeat its notification at most once ' + - 'every N minutes. null notifies on every evaluation; omitting it ' + - 'keeps the stored value. A resolve notification is always sent.', - ), + renotifyIntervalMinutes: alertRenotifyIntervalMinutesSchema.describe( + 'While the alert keeps firing, repeat its notification at most once ' + + 'every N minutes. null notifies on every evaluation; omitting it ' + + 'keeps the stored value. A resolve notification is always sent.', + ), scheduleStartAt: z .string() .datetime() diff --git a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts index 195dc9eed5..59f69cb107 100644 --- a/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts +++ b/packages/api/src/tasks/checkAlerts/__tests__/checkAlerts.int.test.ts @@ -11516,6 +11516,7 @@ describe('checkAlerts', () => { evaluations: string[], renotifyIntervalMinutes?: number, groupBy?: string, + silencedEvaluations: number[] = [], ) => { const { team, @@ -11559,7 +11560,10 @@ describe('checkAlerts', () => { ); const notificationCounts: number[] = []; - for (const time of evaluations) { + for (const [i, time] of evaluations.entries()) { + details.alert.silenced = silencedEvaluations.includes(i) + ? { at: new Date(), until: new Date(Date.now() + 3600000) } + : undefined; await processAlertAtTime( new Date(`2024-01-01T${time}Z`), details, @@ -11617,6 +11621,20 @@ describe('checkAlerts', () => { expect(notificationCounts).toEqual([1, 2, 3]); }); + it('keeps the interval across a short silence', async () => { + const { notificationCounts, histories } = await runBreaches( + SUSTAINED, + EVALUATIONS, + 30, + undefined, + [1], + ); + expect(notificationCounts).toEqual([1, 1, 1, 1]); + expect(histories.map(h => h.lastNotifiedAt?.toISOString())).toEqual( + Array(4).fill('2024-01-01T00:10:00.000Z'), + ); + }); + it('keeps a separate interval for each group', async () => { // a breaches from 00:05, b from 00:10; both every window after that. const { histories } = await runBreaches( diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 1f81a9071d..7837d02587 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -1360,6 +1360,19 @@ export const processAlert = async ( // execution may still send a notification. Subsequent alert checks will // respect the silenced state. This trade-off maintains architectural // separation from direct database access. + // Opt-in re-notify interval: a group that was already firing carries its + // last notification time forward, silenced or not, so the previous + // evaluation is all this needs to read. + const renotifyMinutes = + state === AlertState.ALERT ? alert.renotifyIntervalMinutes : undefined; + if (renotifyMinutes) { + const previous = previousMap.get(computeHistoryMapKey(alert.id, group)); + getOrCreateHistory(group).lastNotifiedAt = + previous?.state === AlertState.ALERT + ? previous.lastNotifiedAt + : undefined; + } + if ((alert.silenced?.until?.getTime() ?? 0) > Date.now()) { alertEvaluationsCounter.add(1, { outcome: 'skipped_silenced' }); logger.info( @@ -1372,22 +1385,13 @@ export const processAlert = async ( return false; } - // Opt-in: a group that was already firing re-notifies only once its - // interval has passed. Every record carries the time forward, so the - // previous evaluation is all this needs to read. - if (state === AlertState.ALERT && alert.renotifyIntervalMinutes) { - const previous = previousMap.get(computeHistoryMapKey(alert.id, group)); - const lastNotifiedAt = - previous?.state === AlertState.ALERT - ? previous.lastNotifiedAt - : undefined; + if (renotifyMinutes) { const history = getOrCreateHistory(group); if ( - lastNotifiedAt && + history.lastNotifiedAt && nowInMinsRoundDown < - fns.addMinutes(lastNotifiedAt, alert.renotifyIntervalMinutes) + fns.addMinutes(history.lastNotifiedAt, renotifyMinutes) ) { - history.lastNotifiedAt = lastNotifiedAt; alertEvaluationsCounter.add(1, { outcome: 'skipped_renotify' }); return false; }