Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

abstract progress to engine

Thiago Araujo da Silvaf1bfd918375b
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 0c29c77b9f..04dcd31a80 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -728,7 +728,10 @@ await someDAL.transaction(async (tx) => {
**How delivery works:**
- **The row owns retry state** (`attempts`, `nextRetryAt`, backoff, terminal `failed`); the consumer
- owns what "delivered" means and reports `Delivered` / `Retry` / `Failed` plus `progress` per event.
+ owns what "delivered" means and reports `Delivered` / `Retry` / `Failed` per event. The outbox keeps
+ no per-event state for a consumer: what a retry should skip is recorded wherever the consumer already
+ keeps delivery records, keyed by `TEvent.id` (stable across attempts). The alert consumer files each
+ run under that id in `alert_history.eventId` and the engine skips channels already recorded there.
Backoff is exponential with jitter from 30s, and `MAX_OUTBOX_ATTEMPTS` puts the last attempt about an
hour after the first, because a `failed` row is a notification nobody will receive. To replay failed
rows by hand: `status = 'retry', attempts = 0, nextRetryAt = now()`.
@@ -763,9 +766,10 @@ await someDAL.transaction(async (tx) => {
its backoff window is skipped, so a later row can overtake it. That's deliberate: blocking a consumer
behind its oldest failing row is the wrong trade for notifications. Don't promise strict ordering, and
don't add a partition key back until a consumer needs one: no consumer today depends on the order two
- events for one resource arrive in, and each event is idempotent on its own through `progress`.
+ events for one resource arrive in, and each event is idempotent on its own through alert history.
- **Delivery is at-least-once.** `commitResults` is retried in-process, since by then the consumer has
- already sent; what's left is narrowed by `progress` and by the emitter's `idempotencyKey`.
+ already sent; what's left is narrowed by the consumer's own delivery records and by the emitter's
+ `idempotencyKey`.
**Watch `infisical.event_outbox.oldest_pending_age`.** It catches a dead relay, a wedged consumer and a
stuck claim alike. `lag` and `exhausted.count` are recorded by the outbox, labelled by consumer, so a
diff --git a/backend/e2e-test/event-outbox.spec.ts b/backend/e2e-test/event-outbox.spec.ts
index bd84531e62..a228a9f8de 100644
--- a/backend/e2e-test/event-outbox.spec.ts
+++ b/backend/e2e-test/event-outbox.spec.ts
@@ -96,7 +96,7 @@ describe("event outbox (postgres)", () => {
const settled = await dal.commitResults({
lockToken,
- delivered: [{ ids: [String(d.id)], progress: { deliveredChannelIds: ["c-1"] } }],
+ delivered: [{ ids: [String(d.id)] }],
retriable: [{ ids: [String(r.id)], nextRetryDelayMs: 30 * 60_000, error: "slack 502" }],
failed: [{ ids: [String(f.id)], error: "bad payload" }]
});
@@ -106,7 +106,6 @@ describe("event outbox (postgres)", () => {
expect(delivered.status).toBe(EventOutboxStatus.Delivered);
expect(delivered.lockedAt).toBeNull();
expect(delivered.lockToken).toBeNull();
- expect(delivered.progress).toEqual({ deliveredChannelIds: ["c-1"] });
expect(retry.status).toBe(EventOutboxStatus.Retry);
expect(retry.attempts).toBe(1);
diff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.ts
index e1fb858103..2aa0cae868 100644
--- a/backend/src/db/migrations/20260908000000_event-outbox.ts
+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts
@@ -18,7 +18,6 @@ export async function up(knex: Knex): Promise<void> {
t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
t.timestamp("lockedAt", { useTz: true });
t.uuid("lockToken");
- t.jsonb("progress");
t.text("lastError");
t.timestamps(true, true, true);
});
diff --git a/backend/src/db/migrations/20260915120000_alert-history-event-id.ts b/backend/src/db/migrations/20260915120000_alert-history-event-id.ts
new file mode 100644
index 0000000000..050eaf7e9a
--- /dev/null
+++ b/backend/src/db/migrations/20260915120000_alert-history-event-id.ts
@@ -0,0 +1,24 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.AlertHistory, "eventId"))) {
+ await knex.schema.alterTable(TableName.AlertHistory, (t) => {
+ // Set on runs the event outbox triggered. A retry of the same event reads the successful
+ // deliveries recorded under it and skips those channels, so a channel that already notified is
+ // never notified twice. Null on scheduled runs, which dedupe by time window instead.
+ t.string("eventId").nullable();
+ t.index(["alertId", "eventId"]);
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasColumn(TableName.AlertHistory, "eventId")) {
+ await knex.schema.alterTable(TableName.AlertHistory, (t) => {
+ t.dropIndex(["alertId", "eventId"]);
+ t.dropColumn("eventId");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/alert-history.ts b/backend/src/db/schemas/alert-history.ts
index 58d6097513..74d0f9413a 100644
--- a/backend/src/db/schemas/alert-history.ts
+++ b/backend/src/db/schemas/alert-history.ts
@@ -12,6 +12,7 @@ export const AlertHistorySchema = z.object({
alertId: z.string().uuid(),
triggeredAt: z.date().nullable().optional(),
status: z.string(),
+ eventId: z.string().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/db/schemas/event-outbox.ts b/backend/src/db/schemas/event-outbox.ts
index 66bacf9a4b..8fac8bfc82 100644
--- a/backend/src/db/schemas/event-outbox.ts
+++ b/backend/src/db/schemas/event-outbox.ts
@@ -19,7 +19,6 @@ export const EventOutboxSchema = z.object({
nextRetryAt: z.date(),
lockedAt: z.date().nullable().optional(),
lockToken: z.string().uuid().nullable().optional(),
- progress: z.unknown().nullable().optional(),
lastError: z.string().nullable().optional(),
createdAt: z.date(),
updatedAt: z.date()
diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.ts
index 04ed96025d..4e1c7d3cfe 100644
--- a/backend/src/services/alert/alert-engine.test.ts
+++ b/backend/src/services/alert/alert-engine.test.ts
@@ -118,6 +118,7 @@ const buildEngine = (opts: {
targets: TTarget[];
channels: Array<{ id: string; channelType: string; encryptedConfig: Buffer; enabled: boolean }>;
recentlyAlerted?: Array<{ channelId: string; targetId: string }>;
+ deliveredForEvent?: string[];
recipients?: Array<{ userId: string; email: string; firstName?: string | null }>;
failEmail?: boolean;
failEmailFor?: string;
@@ -138,7 +139,8 @@ const buildEngine = (opts: {
);
const sentMail: Array<{ recipients: string[] }> = [];
- const historyWrites: Array<{ deliveries: TDelivery[]; status: string }> = [];
+ const historyWrites: Array<{ deliveries: TDelivery[]; status: string; eventId?: string }> = [];
+ const eventLookups: Array<{ alertId: string; eventId: string }> = [];
const channelLookups: Array<{ enabled?: boolean; readFromPrimary?: boolean } | undefined> = [];
let historyAttempts = 0;
// Tracks the peak number of overlapping sendMail calls so a test can assert the
@@ -170,12 +172,20 @@ const buildEngine = (opts: {
},
alertHistoryDAL: {
findRecentlyAlertedTargets: async () => opts.recentlyAlerted ?? [],
- createWithTargets: async (_alertId: string, options: { status: string }, deliveries: TDelivery[]) => {
+ findDeliveredChannelIdsForEvent: async (alertId: string, eventId: string) => {
+ eventLookups.push({ alertId, eventId });
+ return opts.deliveredForEvent ?? [];
+ },
+ createWithTargets: async (
+ _alertId: string,
+ options: { status: string; eventId?: string },
+ deliveries: TDelivery[]
+ ) => {
historyAttempts += 1;
if (opts.failHistoryWrite || historyAttempts <= (opts.failHistoryWriteTimes ?? 0)) {
throw new Error("history table unavailable");
}
- historyWrites.push({ deliveries, status: options.status });
+ historyWrites.push({ deliveries, status: options.status, eventId: options.eventId });
return {} as never;
}
},
@@ -210,6 +220,7 @@ const buildEngine = (opts: {
sentMail,
historyWrites,
channelLookups,
+ eventLookups,
eventPayloads,
getHistoryAttempts: () => historyAttempts,
getPeakConcurrentSends: () => peakConcurrentSends,
@@ -519,18 +530,22 @@ describe("alert engine", () => {
describe("alert engine, event path", () => {
const eventAlert = () => ({ ...makeAlert(), triggerType: "event", eventType: "test.resource.opened" });
- const EVENT = { eventType: "test.resource.opened", targetIds: ["t1"], payload: { targetIds: ["t1"], note: "x" } };
+ const EVENT = {
+ eventId: "7",
+ eventType: "test.resource.opened",
+ targetIds: ["t1"],
+ payload: { targetIds: ["t1"], note: "x" }
+ };
- test("delivers the targets the event named", async () => {
+ test("delivers the targets the event named and files the run under the event id", async () => {
const { engine, sentMail, historyWrites, eventPayloads } = buildEngine({
targets: [{ id: "t1" }, { id: "t2" }],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
- expect(result.deliveredChannelIds).toEqual(["c-email"]);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(sentMail).toHaveLength(1);
// The provider gets the emitter's whole payload, so an event can carry more than ids.
expect(eventPayloads).toEqual([EVENT.payload]);
@@ -538,6 +553,19 @@ describe("alert engine, event path", () => {
expect(historyWrites[0].deliveries).toEqual([
{ targetId: "t1", channelId: "c-email", channelType: "email", status: AlertRunStatus.SUCCESS }
]);
+ // The event id on the row is what a retry of this same event looks up.
+ expect(historyWrites[0].eventId).toBe("7");
+ });
+
+ test("leaves the event id off history for scheduled runs", async () => {
+ const { engine, historyWrites } = buildEngine({
+ targets: [{ id: "t1" }],
+ channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
+ });
+
+ await engine.runAlert(makeAlert());
+
+ expect(historyWrites[0].eventId).toBeUndefined();
});
// The whole reason the event path exists: a daily scan rediscovers the same target tomorrow and
@@ -549,9 +577,9 @@ describe("alert engine, event path", () => {
recentlyAlerted: [{ channelId: "c-email", targetId: "t1" }]
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(sentMail).toHaveLength(1);
});
@@ -561,18 +589,18 @@ describe("alert engine, event path", () => {
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.NoDueTargets);
- expect(result.deliveredChannelIds).toEqual([]);
+ expect(outcome).toBe(AlertDispatchOutcome.NoDueTargets);
expect(historyWrites).toHaveLength(0);
});
- // A retry must not re-notify a channel that already succeeded. That's what makes retrying an event
- // safe with no dedup behind it.
- test("skips channels a previous attempt already delivered to", async () => {
- const { engine, sentMail, historyWrites } = buildEngine({
+ // A retry must not re-notify a channel that already succeeded. The engine reads its own history for
+ // this alert and event to know which those are, so the outbox carries no state for it.
+ test("skips channels a previous attempt of the same event already delivered to", async () => {
+ const { engine, sentMail, historyWrites, eventLookups } = buildEngine({
targets: [{ id: "t1" }],
+ deliveredForEvent: ["c-email"],
channels: [
{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true },
{
@@ -584,10 +612,10 @@ describe("alert engine, event path", () => {
]
});
- const result = await engine.runAlertForEvent(eventAlert(), { ...EVENT, skipChannelIds: ["c-email"] });
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
- expect(result.deliveredChannelIds).toEqual(["c-slack"]);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(eventLookups).toEqual([{ alertId: "alert-1", eventId: "7" }]);
expect(sentMail).toHaveLength(0);
expect(historyWrites[0].deliveries.map((d) => d.channelId)).toEqual(["c-slack"]);
});
@@ -595,12 +623,13 @@ describe("alert engine, event path", () => {
test("returns NoChannels when every channel was already delivered to", async () => {
const { engine } = buildEngine({
targets: [{ id: "t1" }],
+ deliveredForEvent: ["c-email"],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }]
});
- const result = await engine.runAlertForEvent(eventAlert(), { ...EVENT, skipChannelIds: ["c-email"] });
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.NoChannels);
+ expect(outcome).toBe(AlertDispatchOutcome.NoChannels);
});
// A history write that fails after the sends must not turn a delivered event into a retry, or the
@@ -612,9 +641,9 @@ describe("alert engine, event path", () => {
failHistoryWrite: true
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(sentMail).toHaveLength(1);
});
@@ -627,9 +656,9 @@ describe("alert engine, event path", () => {
failHistoryWriteTimes: 1
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliverySuccess);
expect(getHistoryAttempts()).toBe(2);
expect(historyWrites).toHaveLength(1);
});
@@ -649,16 +678,15 @@ describe("alert engine, event path", () => {
expect(channelLookups[1]).toEqual({ enabled: true });
});
- test("reports failure and no delivered channels when every channel fails", async () => {
+ test("reports failure when every channel fails", async () => {
const { engine } = buildEngine({
targets: [{ id: "t1" }],
channels: [{ id: "c-email", channelType: "email", encryptedConfig: encConfig({}), enabled: true }],
failEmail: true
});
- const result = await engine.runAlertForEvent(eventAlert(), EVENT);
+ const outcome = await engine.runAlertForEvent(eventAlert(), EVENT);
- expect(result.outcome).toBe(AlertDispatchOutcome.DeliveryFailed);
- expect(result.deliveredChannelIds).toEqual([]);
+ expect(outcome).toBe(AlertDispatchOutcome.DeliveryFailed);
});
});
diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.ts
index 66520194ea..32593bc1b6 100644
--- a/backend/src/services/alert/alert-engine.ts
+++ b/backend/src/services/alert/alert-engine.ts
@@ -31,11 +31,6 @@ type TChannelWork = {
due: { target: unknown; id: string }[];
};
-export type TDispatchResult = {
- outcome: AlertDispatchOutcome;
- deliveredChannelIds: string[];
-};
-
type TChannelDispatchResult = {
channelId: string;
channelType: string;
@@ -49,7 +44,10 @@ type TChannelDispatchResult = {
export type TAlertEngineDep = {
alertChannelDAL: Pick<TAlertChannelDALFactory, "findByAlertId">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "findByChannelIds">;
- alertHistoryDAL: Pick<TAlertHistoryDALFactory, "createWithTargets" | "findRecentlyAlertedTargets">;
+ alertHistoryDAL: Pick<
+ TAlertHistoryDALFactory,
+ "createWithTargets" | "findRecentlyAlertedTargets" | "findDeliveredChannelIdsForEvent"
+ >;
alertProviderRegistry: TAlertProviderRegistry;
alertRecipientResolver: Pick<TAlertRecipientResolver, "resolveMany">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -70,8 +68,9 @@ export const alertEngineFactory = ({
const $dispatchChannelWork = async (
alert: TAlerts,
provider: IResourceAlertProvider,
- channelWork: TChannelWork[]
- ): Promise<TDispatchResult> => {
+ channelWork: TChannelWork[],
+ eventId?: string
+ ): Promise<AlertDispatchOutcome> => {
const alertContext: TAlertContext = {
id: alert.id,
name: alert.name,
@@ -171,7 +170,7 @@ export const alertEngineFactory = ({
);
const dispatched = channelResults.filter((result) => !result.skipped);
- if (dispatched.length === 0) return { outcome: AlertDispatchOutcome.NoRecipients, deliveredChannelIds: [] };
+ if (dispatched.length === 0) return AlertDispatchOutcome.NoRecipients;
const deliveries = dispatched.flatMap((result) => {
const perTarget = new Map<string, boolean>((result.targetResults ?? []).map((t) => [t.targetId, t.success]));
@@ -199,7 +198,7 @@ export const alertEngineFactory = ({
for (let attempt = 1; attempt <= HISTORY_WRITE_ATTEMPTS; attempt += 1) {
try {
// eslint-disable-next-line no-await-in-loop -- retrying the same insert is the point
- await alertHistoryDAL.createWithTargets(alert.id, { status }, deliveries);
+ await alertHistoryDAL.createWithTargets(alert.id, { status, eventId }, deliveries);
break;
} catch (err) {
if (attempt === HISTORY_WRITE_ATTEMPTS) {
@@ -212,16 +211,10 @@ export const alertEngineFactory = ({
}
}
- const deliveredChannelIds = dispatched.filter((result) => result.success).map((result) => result.channelId);
-
- if (status === AlertRunStatus.SUCCESS) {
- return { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds };
- }
- return {
- outcome:
- status === AlertRunStatus.PARTIAL ? AlertDispatchOutcome.DeliveryPartial : AlertDispatchOutcome.DeliveryFailed,
- deliveredChannelIds
- };
+ if (status === AlertRunStatus.SUCCESS) return AlertDispatchOutcome.DeliverySuccess;
+ return status === AlertRunStatus.PARTIAL
+ ? AlertDispatchOutcome.DeliveryPartial
+ : AlertDispatchOutcome.DeliveryFailed;
};
const $buildChannelWork = (
@@ -297,22 +290,23 @@ export const alertEngineFactory = ({
const channelWork = $buildChannelWork(alert, channels, targets, alertedSet);
if (channelWork.length === 0) return AlertDispatchOutcome.AllDeduped;
- const { outcome } = await $dispatchChannelWork(alert, provider, channelWork);
- return outcome;
+ return $dispatchChannelWork(alert, provider, channelWork);
};
const runAlertForEvent = async (
alert: TAlerts,
- input: { eventType: string; targetIds: string[]; payload: Record<string, unknown>; skipChannelIds?: string[] }
- ): Promise<TDispatchResult> => {
+ input: { eventId: string; eventType: string; targetIds: string[]; payload: Record<string, unknown> }
+ ): Promise<AlertDispatchOutcome> => {
const provider = $getProvider(alert, "findTargetsByIds");
- if (!provider?.findTargetsByIds) return { outcome: AlertDispatchOutcome.NoProvider, deliveredChannelIds: [] };
-
- const skip = new Set(input.skipChannelIds ?? []);
- const channels = (await alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true })).filter(
- (channel) => !skip.has(channel.id)
- );
- if (channels.length === 0) return { outcome: AlertDispatchOutcome.NoChannels, deliveredChannelIds: [] };
+ if (!provider?.findTargetsByIds) return AlertDispatchOutcome.NoProvider;
+
+ const [enabledChannels, alreadyDelivered] = await Promise.all([
+ alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true }),
+ alertHistoryDAL.findDeliveredChannelIdsForEvent(alert.id, input.eventId)
+ ]);
+ const skip = new Set(alreadyDelivered);
+ const channels = enabledChannels.filter((channel) => !skip.has(channel.id));
+ if (channels.length === 0) return AlertDispatchOutcome.NoChannels;
const resolved = await provider.findTargetsByIds({
orgId: alert.orgId,
@@ -323,11 +317,11 @@ export const alertEngineFactory = ({
targetIds: input.targetIds,
payload: input.payload
});
- if (resolved.length === 0) return { outcome: AlertDispatchOutcome.NoDueTargets, deliveredChannelIds: [] };
+ if (resolved.length === 0) return AlertDispatchOutcome.NoDueTargets;
const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));
- return $dispatchChannelWork(alert, provider, $buildChannelWork(alert, channels, targets));
+ return $dispatchChannelWork(alert, provider, $buildChannelWork(alert, channels, targets), input.eventId);
};
return { runAlert, runAlertForEvent };
diff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.ts
index 21b100bc9b..9b5a181ee4 100644
--- a/backend/src/services/alert/alert-event-consumer.test.ts
+++ b/backend/src/services/alert/alert-event-consumer.test.ts
@@ -29,23 +29,22 @@ const makeEvent = (overrides?: Partial<TEvent>): TEvent =>
eventType: EVENT_TYPE,
payload: makePayload(),
occurredAt: new Date(),
- progress: null,
...overrides
}) as TEvent;
const buildConsumer = (opts?: {
alerts?: unknown[];
- results?: { outcome: AlertDispatchOutcome; deliveredChannelIds: string[] }[];
+ results?: AlertDispatchOutcome[];
eventKeys?: string[];
findAlerts?: () => Promise<unknown[]>;
}) => {
const runs: {
alertId: string;
+ eventId: string;
targetIds: string[];
payload?: Record<string, unknown>;
- skipChannelIds?: string[];
}[] = [];
- const results = opts?.results ?? [{ outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-1"] }];
+ const results = opts?.results ?? [AlertDispatchOutcome.DeliverySuccess];
let runIdx = 0;
let lookups = 0;
const eventKeys = opts?.eventKeys ?? [EVENT_TYPE];
@@ -60,14 +59,9 @@ const buildConsumer = (opts?: {
alertEngine: {
runAlertForEvent: async (
alert: { id: string },
- input: { targetIds: string[]; payload: Record<string, unknown>; skipChannelIds?: string[] }
+ input: { eventId: string; targetIds: string[]; payload: Record<string, unknown> }
) => {
- runs.push({
- alertId: alert.id,
- targetIds: input.targetIds,
- payload: input.payload,
- skipChannelIds: input.skipChannelIds
- });
+ runs.push({ alertId: alert.id, eventId: input.eventId, targetIds: input.targetIds, payload: input.payload });
const result = results[Math.min(runIdx, results.length - 1)];
runIdx += 1;
return result;
@@ -102,7 +96,16 @@ describe("alert event consumer", () => {
expect(runs[0].targetIds).toEqual(["req-1"]);
// The provider sees everything the emitter wrote, not only the ids the consumer validated.
expect(runs[0].payload).toEqual(makePayload());
- expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
+ });
+
+ // The outbox row id is what the engine files each channel's outcome under, and it is the same on
+ // every attempt, so it is the only key a retry can use to find what already went out.
+ test("hands the engine the event id so a retry can skip channels that already delivered", async () => {
+ const { consumer, runs } = buildConsumer();
+
+ await consumer.handle([makeEvent({ id: 42 })]);
+
+ expect(runs[0].eventId).toBe("42");
});
// The alert was deleted or disabled between the gate and the worker, so nobody is owed a
@@ -116,23 +119,13 @@ describe("alert event consumer", () => {
expect(runs).toHaveLength(0);
});
- test("retries and records what already delivered when a channel fails", async () => {
- const { consumer } = buildConsumer({
- results: [{ outcome: AlertDispatchOutcome.DeliveryPartial, deliveredChannelIds: ["c-1"] }]
- });
+ test("retries the event when a channel fails", async () => {
+ const { consumer } = buildConsumer({ results: [AlertDispatchOutcome.DeliveryPartial] });
const [result] = await consumer.handle([makeEvent()]);
expect(result.status).toBe(EventResultStatus.Retry);
- expect(result.progress).toEqual({ deliveredChannelIds: ["c-1"] });
- });
-
- test("skips the channels a previous attempt already delivered to", async () => {
- const { consumer, runs } = buildConsumer();
-
- await consumer.handle([makeEvent({ progress: { deliveredChannelIds: ["c-1"] } })]);
-
- expect(runs[0].skipChannelIds).toEqual(["c-1"]);
+ expect(result.error).toContain(AlertDispatchOutcome.DeliveryPartial);
});
// Retrying can't fix a payload the consumer can't read, so don't burn every attempt on it first.
@@ -148,16 +141,13 @@ describe("alert event consumer", () => {
test("runs every matching alert in a scope", async () => {
const { consumer, runs } = buildConsumer({
alerts: [makeAlert("alert-project"), makeAlert("alert-org")],
- results: [
- { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-1"] },
- { outcome: AlertDispatchOutcome.DeliverySuccess, deliveredChannelIds: ["c-2"] }
- ]
+ results: [AlertDispatchOutcome.DeliverySuccess, AlertDispatchOutcome.DeliverySuccess]
});
const [result] = await consumer.handle([makeEvent()]);
expect(runs.map((run) => run.alertId)).toEqual(["alert-project", "alert-org"]);
- expect(result.progress).toEqual({ deliveredChannelIds: ["c-1", "c-2"] });
+ expect(result.status).toBe(EventResultStatus.Delivered);
});
// Marking a mismatched pair delivered would hide the misconfigured emit site. Failing terminally
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index 8b3ee344c4..06f6345e04 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -25,10 +25,6 @@ export const AlertEventPayloadSchema = z.object({
type TAlertEventPayload = z.infer<typeof AlertEventPayloadSchema>;
-const AlertEventProgressSchema = z.object({
- deliveredChannelIds: z.array(z.string()).default([])
-});
-
export type TAlertEventConsumerDep = {
alertDAL: Pick<TAlertDALFactory, "findEnabledForEvent">;
alertEngine: Pick<TAlertEngine, "runAlertForEvent">;
@@ -74,9 +70,6 @@ export const alertEventConsumerFactory = ({
};
}
- const progress = AlertEventProgressSchema.safeParse(event.progress ?? {});
- const delivered = new Set(progress.success ? progress.data.deliveredChannelIds : []);
-
const alerts = await findAlerts({
orgId,
projectId,
@@ -94,28 +87,23 @@ export const alertEventConsumerFactory = ({
for (const alert of alerts) {
// eslint-disable-next-line no-await-in-loop -- at most a project- and an org-scoped alert
- const result = await alertEngine.runAlertForEvent(alert, {
+ const outcome = await alertEngine.runAlertForEvent(alert, {
+ eventId: id,
eventType: event.eventType,
targetIds,
- payload: (event.payload ?? {}) as Record<string, unknown>,
- skipChannelIds: [...delivered]
+ payload: (event.payload ?? {}) as Record<string, unknown>
});
- result.deliveredChannelIds.forEach((channelId) => delivered.add(channelId));
- recordAlertDispatchOutcomeMetric({ resourceType: alert.resourceType, outcome: result.outcome });
-
- if (
- result.outcome === AlertDispatchOutcome.DeliveryFailed ||
- result.outcome === AlertDispatchOutcome.DeliveryPartial
- ) {
- errors.push(`alert ${alert.id}: ${result.outcome}`);
+ recordAlertDispatchOutcomeMetric({ resourceType: alert.resourceType, outcome });
+
+ if (outcome === AlertDispatchOutcome.DeliveryFailed || outcome === AlertDispatchOutcome.DeliveryPartial) {
+ errors.push(`alert ${alert.id}: ${outcome}`);
}
}
- const outcome = { id, progress: { deliveredChannelIds: [...delivered] } };
if (errors.length > 0) {
- return { ...outcome, status: EventResultStatus.Retry, error: errors.join("; ") };
+ return { id, status: EventResultStatus.Retry, error: errors.join("; ") };
}
- return { ...outcome, status: EventResultStatus.Delivered };
+ return { id, status: EventResultStatus.Delivered };
};
const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> => {
diff --git a/backend/src/services/alert/alert-history-dal.test.ts b/backend/src/services/alert/alert-history-dal.test.ts
index a3a0175013..c7b925b2b9 100644
--- a/backend/src/services/alert/alert-history-dal.test.ts
+++ b/backend/src/services/alert/alert-history-dal.test.ts
@@ -78,6 +78,18 @@ describe("alert history dal", () => {
expect(whereCalls).toContainEqual(["hist.alertId", "alert-1"]);
});
+ // A channel that failed on the first attempt must be retried, and a success on one channel must not
+ // suppress delivery on another, so the skip list is per channel and only counts successes.
+ test("findDeliveredChannelIdsForEvent scopes to the alert and event and only counts successes", async () => {
+ const { dal, whereCalls } = buildDAL();
+
+ await dal.findDeliveredChannelIdsForEvent("alert-1", "42");
+
+ expect(whereCalls).toContainEqual(["hist.alertId", "alert-1"]);
+ expect(whereCalls).toContainEqual(["hist.eventId", "42"]);
+ expect(whereCalls).toContainEqual(["tgt.status", AlertRunStatus.SUCCESS]);
+ });
+
test("findRecentlyAlertedTargets short-circuits on empty target list without querying", async () => {
const { dal, whereCalls } = buildDAL();
diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.ts
index ef4805aac6..6f6bc16659 100644
--- a/backend/src/services/alert/alert-history-dal.ts
+++ b/backend/src/services/alert/alert-history-dal.ts
@@ -27,12 +27,14 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
const createWithTargets = async (
alertId: string,
- options: { status: string },
+ options: { status: string; eventId?: string },
deliveries: TAlertTargetDelivery[]
): Promise<TAlertHistory> => {
try {
return await db.transaction(async (tx) => {
- const [history] = await tx(TableName.AlertHistory).insert({ alertId, status: options.status }).returning("*");
+ const [history] = await tx(TableName.AlertHistory)
+ .insert({ alertId, status: options.status, eventId: options.eventId ?? null })
+ .returning("*");
if (deliveries.length > 0) {
await tx(TableName.AlertHistoryTarget).insert(
@@ -83,6 +85,23 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
}
};
+ const findDeliveredChannelIdsForEvent = async (alertId: string, eventId: string): Promise<string[]> => {
+ try {
+ const rows = (await db(`${TableName.AlertHistory} as hist`)
+ .join(`${TableName.AlertHistoryTarget} as tgt`, "hist.id", "tgt.alertHistoryId")
+ .where("hist.alertId", alertId)
+ .where("hist.eventId", eventId)
+ .where("tgt.status", AlertRunStatus.SUCCESS)
+ .whereNotNull("tgt.channelId")
+ .distinct("tgt.channelId")
+ .select("tgt.channelId")) as { channelId: string }[];
+
+ return rows.map((row) => row.channelId);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindDeliveredChannelIdsForEvent" });
+ }
+ };
+
const deleteExpiredHistory = async ({
before,
batchSize = ALERT_HISTORY_PRUNE_BATCH_SIZE,
@@ -126,6 +145,7 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
...alertHistoryOrm,
createWithTargets,
findRecentlyAlertedTargets,
+ findDeliveredChannelIdsForEvent,
deleteExpiredHistory
};
};
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
index 8c7dc8f79d..025e2405b9 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -109,8 +109,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
// recycled mid-delivery and the rows now belong to another worker.
const commitResults = async (input: {
lockToken: string;
- delivered: { ids: string[]; progress?: Record<string, unknown> | null }[];
- retriable: { ids: string[]; nextRetryDelayMs: number; progress?: Record<string, unknown> | null; error?: string }[];
+ delivered: { ids: string[] }[];
+ retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];
failed: { ids: string[]; error?: string }[];
}): Promise<number> => {
const total =
@@ -130,12 +130,9 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
.update({ lockedAt: null, lockToken: null, ...values });
};
- const progressOf = (group: { progress?: Record<string, unknown> | null }) =>
- group.progress !== undefined ? { progress: JSON.stringify(group.progress) } : {};
-
for (const group of input.delivered) {
// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
- await settle(group.ids, { status: EventOutboxStatus.Delivered, lastError: null, ...progressOf(group) });
+ await settle(group.ids, { status: EventOutboxStatus.Delivered, lastError: null });
}
for (const group of input.retriable) {
@@ -144,8 +141,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
status: EventOutboxStatus.Retry,
attempts: db.raw('"attempts" + 1'),
nextRetryAt: db.raw(`NOW() + (? || ' milliseconds')::INTERVAL`, [group.nextRetryDelayMs]),
- lastError: group.error ?? null,
- ...progressOf(group)
+ lastError: group.error ?? null
});
}
diff --git a/backend/src/services/event-outbox/event-outbox-service.test.ts b/backend/src/services/event-outbox/event-outbox-service.test.ts
index c0bc2079d5..8a4c58e1bc 100644
--- a/backend/src/services/event-outbox/event-outbox-service.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts
@@ -163,7 +163,6 @@ describe("event outbox drain", () => {
attempts: 0,
nextRetryAt: new Date(),
lockedAt: new Date(),
- progress: null,
lastError: null,
createdAt: new Date(),
updatedAt: new Date(),
@@ -180,7 +179,7 @@ describe("event outbox drain", () => {
registry.register(makeConsumer({ name: opts.consumerName ?? "alert", handle: opts.handle }));
const commits: {
- delivered: { ids: string[]; progress?: unknown }[];
+ delivered: { ids: string[] }[];
retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];
failed: { ids: string[]; error?: string }[];
}[] = [];
@@ -231,7 +230,7 @@ describe("event outbox drain", () => {
const result = await service.drain(KEY);
expect(result.handled).toBe(1);
- expect(commits[0].delivered).toEqual([{ ids: ["1"], progress: undefined }]);
+ expect(commits[0].delivered).toEqual([{ ids: ["1"] }]);
});
// A consumer that throws must not lose the batch: every row goes back for another attempt.
@@ -287,28 +286,12 @@ describe("event outbox drain", () => {
await service.drain(KEY);
- expect(commits[0].delivered).toEqual([{ ids: ["1", "2"], progress: undefined }]);
+ expect(commits[0].delivered).toEqual([{ ids: ["1", "2"] }]);
expect(commits[0].retriable).toHaveLength(1);
expect(commits[0].retriable[0].ids).toEqual(["3", "4"]);
expect(commits[0].retriable[0].error).toBe("slack 502");
});
- test("keeps rows with different progress in separate commit entries", async () => {
- const { service, commits } = buildDrain({
- batches: [[makeRow({ id: 1 }), makeRow({ id: 2 })]],
- handle: async (rows) =>
- rows.map((row) => ({
- id: String(row.id),
- status: EventResultStatus.Delivered,
- progress: { deliveredChannelIds: [`c-${row.id}`] }
- }))
- });
-
- await service.drain(KEY);
-
- expect(commits[0].delivered.map((group) => group.ids)).toEqual([["1"], ["2"]]);
- });
-
// The token the rows were claimed under is what commitResults fences on, so a claim that reports
// under a different one would write to whatever worker holds the rows now.
test("commits under the token the batch was claimed with", async () => {
diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.ts
index a08cf531a6..849c1b6105 100644
--- a/backend/src/services/event-outbox/event-outbox-service.ts
+++ b/backend/src/services/event-outbox/event-outbox-service.ts
@@ -147,13 +147,8 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
const byId = new Map(results.map((result) => [result.id, result]));
const now = Date.now();
- const delivered: { id: string; progress?: Record<string, unknown> | null }[] = [];
- const retriable: {
- id: string;
- nextRetryDelayMs: number;
- progress?: Record<string, unknown> | null;
- error?: string;
- }[] = [];
+ const delivered: { id: string }[] = [];
+ const retriable: { id: string; nextRetryDelayMs: number; error?: string }[] = [];
const failed: { id: string; error?: string }[] = [];
const backoffByAttempt = new Map<number, number>();
@@ -170,7 +165,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
let finalStatus: EventOutboxStatus;
if (result.status === EventResultStatus.Delivered) {
finalStatus = EventOutboxStatus.Delivered;
- delivered.push({ id, progress: result.progress });
+ delivered.push({ id });
} else if (result.status === EventResultStatus.Failed || attempts >= MAX_OUTBOX_ATTEMPTS) {
finalStatus = EventOutboxStatus.Failed;
failed.push({ id, error: result.error });
@@ -181,7 +176,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
nextRetryDelayMs = computeBackoffMs(attempts);
backoffByAttempt.set(attempts, nextRetryDelayMs);
}
- retriable.push({ id, nextRetryDelayMs, progress: result.progress, error: result.error });
+ retriable.push({ id, nextRetryDelayMs, error: result.error });
}
recordEventOutboxLagMetric({
@@ -193,10 +188,8 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry
const settled = await $commitWithRetry(rows[0], {
lockToken,
- delivered: groupByOutcome(delivered, (item) => JSON.stringify(item.progress ?? null)),
- retriable: groupByOutcome(retriable, (item) =>
- JSON.stringify([item.nextRetryDelayMs, item.error ?? null, item.progress ?? null])
- ),
+ delivered: groupByOutcome(delivered, () => ""),
+ retriable: groupByOutcome(retriable, (item) => JSON.stringify([item.nextRetryDelayMs, item.error ?? null])),
failed: groupByOutcome(failed, (item) => item.error ?? "")
});
diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.ts
index 0286662e99..6820ef0545 100644
--- a/backend/src/services/event-outbox/event-outbox-types.ts
+++ b/backend/src/services/event-outbox/event-outbox-types.ts
@@ -62,7 +62,7 @@ export type TEventEmitter = {
};
// What a consumer sees. Lock, attempt, and status columns are the outbox's business, not the consumer's.
-export type TEvent = Pick<TEventOutbox, "id" | "eventType" | "payload" | "progress" | "occurredAt">;
+export type TEvent = Pick<TEventOutbox, "id" | "eventType" | "payload" | "occurredAt">;
export enum EventResultStatus {
Delivered = "delivered",
@@ -74,8 +74,6 @@ export type TEventConsumerResult = {
id: string;
status: EventResultStatus;
error?: string;
- // Opaque to the outbox; handed back on the next attempt so a retry can skip what already landed.
- progress?: Record<string, unknown> | null;
};
export type TOutboxFlushKey = {