Skip to content

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

prune old entries

Thiago Araujo da Silvae017b5ab7e56
diff --git a/backend/src/db/migrations/20260714120000_add-alerts.ts b/backend/src/db/migrations/20260714120000_add-alerts.ts
index ee3cbe8a23..d6599de6f2 100644
--- a/backend/src/db/migrations/20260714120000_add-alerts.ts
+++ b/backend/src/db/migrations/20260714120000_add-alerts.ts
@@ -119,6 +119,9 @@ export async function up(knex: Knex): Promise<void> {
// status column (success | partial | failed) is audit-only; per-(channel, target) success
// filtering happens on alert_history_target, so status is not part of this index.
t.index(["alertId", "triggeredAt"]);
+ // Serves the retention sweep, which selects the oldest expired runs across every alert. The
+ // index above is leftmost on alertId, so it can't answer an alert-agnostic triggeredAt range.
+ t.index("triggeredAt");
});
await createOnUpdateTrigger(knex, TableName.AlertHistory);
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 091034ad41..f7a261ef7e 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1057,6 +1057,7 @@ export const registerRoutes = async (
cronJob,
queueService,
alertDAL,
+ alertHistoryDAL,
alertProviderRegistry,
alertEngine
});
diff --git a/backend/src/services/alert/alert-history-dal.test.ts b/backend/src/services/alert/alert-history-dal.test.ts
index 33360ff6fd..a3a0175013 100644
--- a/backend/src/services/alert/alert-history-dal.test.ts
+++ b/backend/src/services/alert/alert-history-dal.test.ts
@@ -25,6 +25,49 @@ const buildDAL = () => {
return { dal: alertHistoryDALFactory(db), whereCalls };
};
+// Drives the retention sweep with a scripted per-batch delete count so we can assert the batching
+// contract without a database. Each `del()` returns the next scripted count.
+const buildPruneDAL = (deletesPerBatch: number[]) => {
+ const rawStatements: string[] = [];
+ const whereCalls: unknown[][] = [];
+ const limits: number[] = [];
+ let batch = 0;
+
+ const chain = () => {
+ const link = {
+ select: () => link,
+ where: (...args: unknown[]) => {
+ whereCalls.push(args);
+ return link;
+ },
+ orderBy: () => link,
+ limit: (size: number) => {
+ limits.push(size);
+ return link;
+ },
+ whereIn: () => link,
+ del: async () => {
+ const removed = deletesPerBatch[batch] ?? 0;
+ batch += 1;
+ return removed;
+ }
+ };
+ return link;
+ };
+
+ const tx = Object.assign(() => chain(), {
+ raw: async (sql: string) => {
+ rawStatements.push(sql);
+ }
+ });
+ const db = Object.assign(() => chain(), {
+ replicaNode: () => () => chain(),
+ transaction: async (cb: (trx: unknown) => Promise<number>) => cb(tx)
+ }) as never;
+
+ return { dal: alertHistoryDALFactory(db), rawStatements, whereCalls, limits };
+};
+
describe("alert history dal", () => {
test("findRecentlyAlertedTargets only counts successful deliveries", async () => {
const { dal, whereCalls } = buildDAL();
@@ -43,4 +86,43 @@ describe("alert history dal", () => {
expect(result).toEqual([]);
expect(whereCalls).toHaveLength(0);
});
+
+ test("deleteExpiredHistory prunes on the cutoff and stops once a batch comes back short", async () => {
+ const { dal, whereCalls, limits } = buildPruneDAL([2, 2, 1]);
+ const before = new Date("2026-04-27T00:00:00.000Z");
+
+ const result = await dal.deleteExpiredHistory({ before, batchSize: 2, maxBatches: 10 });
+
+ expect(result).toEqual({ deleted: 5, hasMore: false });
+ // Three batches ran, then the short one ended the sweep instead of burning the remaining budget.
+ expect(limits).toEqual([2, 2, 2]);
+ expect(whereCalls).toEqual([
+ ["triggeredAt", "<", before],
+ ["triggeredAt", "<", before],
+ ["triggeredAt", "<", before]
+ ]);
+ });
+
+ test("deleteExpiredHistory reports hasMore when the per-tick batch cap is reached", async () => {
+ const { dal } = buildPruneDAL([2, 2, 2]);
+
+ const result = await dal.deleteExpiredHistory({
+ before: new Date("2026-04-27T00:00:00.000Z"),
+ batchSize: 2,
+ maxBatches: 2
+ });
+
+ // Backlog left for the next cron tick rather than draining it all in one handler.
+ expect(result).toEqual({ deleted: 4, hasMore: true });
+ });
+
+ test("deleteExpiredHistory bounds every batch with a transaction-local statement timeout", async () => {
+ const { dal, rawStatements } = buildPruneDAL([1]);
+
+ await dal.deleteExpiredHistory({ before: new Date("2026-04-27T00:00:00.000Z"), batchSize: 2 });
+
+ // SET LOCAL, so the bound reverts on commit and can't leak to a pooled connection.
+ expect(rawStatements).toHaveLength(1);
+ expect(rawStatements[0]).toMatch(/^SET LOCAL statement_timeout = \d+$/);
+ });
});
diff --git a/backend/src/services/alert/alert-history-dal.ts b/backend/src/services/alert/alert-history-dal.ts
index 844d43c9f7..ef4805aac6 100644
--- a/backend/src/services/alert/alert-history-dal.ts
+++ b/backend/src/services/alert/alert-history-dal.ts
@@ -18,6 +18,10 @@ export type TAlertTargetDelivery = {
export type TRecentlyAlertedTarget = { channelId: string; targetId: string };
+const ALERT_HISTORY_PRUNE_BATCH_SIZE = 5_000;
+const ALERT_HISTORY_PRUNE_MAX_BATCHES = 20;
+const ALERT_HISTORY_PRUNE_TIMEOUT_MS = 30_000;
+
export const alertHistoryDALFactory = (db: TDbClient) => {
const alertHistoryOrm = ormify(db, TableName.AlertHistory);
@@ -79,9 +83,49 @@ export const alertHistoryDALFactory = (db: TDbClient) => {
}
};
+ const deleteExpiredHistory = async ({
+ before,
+ batchSize = ALERT_HISTORY_PRUNE_BATCH_SIZE,
+ maxBatches = ALERT_HISTORY_PRUNE_MAX_BATCHES
+ }: {
+ before: Date;
+ batchSize?: number;
+ maxBatches?: number;
+ }): Promise<{ deleted: number; hasMore: boolean }> => {
+ try {
+ let deleted = 0;
+
+ for (let batch = 0; batch < maxBatches; batch += 1) {
+ // eslint-disable-next-line no-await-in-loop -- batches must run serially to stay paced
+ const removed = await db.transaction(async (tx): Promise<number> => {
+ await tx.raw(`SET LOCAL statement_timeout = ${ALERT_HISTORY_PRUNE_TIMEOUT_MS}`);
+
+ return tx(TableName.AlertHistory)
+ .whereIn(
+ "id",
+ tx(TableName.AlertHistory)
+ .select("id")
+ .where("triggeredAt", "<", before)
+ .orderBy("triggeredAt", "asc")
+ .limit(batchSize)
+ )
+ .del();
+ });
+
+ deleted += removed;
+ if (removed < batchSize) return { deleted, hasMore: false };
+ }
+
+ return { deleted, hasMore: true };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteExpiredHistory" });
+ }
+ };
+
return {
...alertHistoryOrm,
createWithTargets,
- findRecentlyAlertedTargets
+ findRecentlyAlertedTargets,
+ deleteExpiredHistory
};
};
diff --git a/backend/src/services/alert/alert-queue.ts b/backend/src/services/alert/alert-queue.ts
index 65ae3aabd9..110a1f0966 100644
--- a/backend/src/services/alert/alert-queue.ts
+++ b/backend/src/services/alert/alert-queue.ts
@@ -6,12 +6,15 @@ import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TAlertDALFactory } from "./alert-dal";
import { TAlertEngine } from "./alert-engine";
+import { TAlertHistoryDALFactory } from "./alert-history-dal";
import { TAlertProviderRegistry } from "./alert-provider-registry";
+import { ALERT_HISTORY_RETENTION_DAYS } from "./alert-types";
type TAlertQueueServiceFactoryDep = {
cronJob: TCronJobFactory;
queueService: TQueueServiceFactory;
alertDAL: Pick<TAlertDALFactory, "findEnabledByResourceType" | "findActiveById">;
+ alertHistoryDAL: Pick<TAlertHistoryDALFactory, "deleteExpiredHistory">;
alertProviderRegistry: TAlertProviderRegistry;
alertEngine: Pick<TAlertEngine, "runAlert">;
};
@@ -22,6 +25,7 @@ export const alertQueueServiceFactory = ({
cronJob,
queueService,
alertDAL,
+ alertHistoryDAL,
alertProviderRegistry,
alertEngine
}: TAlertQueueServiceFactoryDep) => {
@@ -51,6 +55,15 @@ export const alertQueueServiceFactory = ({
}
};
+ const pruneExpiredHistory = async () => {
+ const before = new Date(Date.now() - ALERT_HISTORY_RETENTION_DAYS * 24 * 60 * 60 * 1000);
+ const { deleted, hasMore } = await alertHistoryDAL.deleteExpiredHistory({ before });
+
+ logger.info(
+ `cron[daily-alert-processing]: pruned alert history older than ${ALERT_HISTORY_RETENTION_DAYS} days [deleted=${deleted}] [hasMore=${hasMore}]`
+ );
+ };
+
const init = () => {
queueService.start(
QueueName.AlertDispatch,
@@ -86,8 +99,6 @@ export const alertQueueServiceFactory = ({
cronJob.register({
name: CronJobName.DailyAlertProcessing,
- // Cadence is coupled to ALERT_SCAN_LEAD_* (alert-types.ts): providers scan one period ahead to
- // guarantee "at least alertBefore" lead. If this pattern changes, revisit that constant.
pattern: appCfg.isDevelopmentMode ? "*/5 * * * *" : "0 0 * * *",
runHashTtlS: 60 * 60 * 24,
enabled: !appCfg.isSecondaryInstance,
@@ -95,6 +106,8 @@ export const alertQueueServiceFactory = ({
logger.info("cron[daily-alert-processing]: enqueueing enabled alerts");
await enqueueEnabledAlerts();
logger.info("cron[daily-alert-processing]: enqueue complete");
+
+ await pruneExpiredHistory();
}
});
};
diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.ts
index 8d62e78f7f..158bf50440 100644
--- a/backend/src/services/alert/alert-types.ts
+++ b/backend/src/services/alert/alert-types.ts
@@ -44,6 +44,10 @@ export const ALERT_SCAN_LEAD_INTERVAL = "1 day";
export const MAX_CHANNELS_PER_ALERT = 10;
export const MAX_RECIPIENTS_PER_CHANNEL = 20;
+export const ALERT_HISTORY_RETENTION_DAYS = 90;
+
+export const MAX_DEDUP_WINDOW_HOURS = (ALERT_HISTORY_RETENTION_DAYS - 1) * 24;
+
export type TAlertContext = {
id: string;
name: string;
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts
index 0422bf5d9f..7b6a11a5f2 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts
@@ -1,7 +1,12 @@
import { createMongoAbility } from "@casl/ability";
import { vi } from "vitest";
-import { AlertPermissionAction, TAlertContext } from "../alert-types";
+import {
+ ALERT_HISTORY_RETENTION_DAYS,
+ AlertPermissionAction,
+ MAX_DEDUP_WINDOW_HOURS,
+ TAlertContext
+} from "../alert-types";
import { TExpiringUaClientSecret } from "./identity-credential-alert-dal";
import {
IDENTITY_AUTHENTICATION_EXPIRY_EVENT,
@@ -219,13 +224,20 @@ describe("identity credential alert provider", () => {
test("dedup window spans alertBefore + the scan lead (30d -> 744h, 1d -> 48h) with a 24h floor", () => {
const provider = buildProvider();
expect(provider.dedupWindowHours?.({ alertBefore: "30d" })).toBe(744);
- expect(provider.dedupWindowHours?.({ alertBefore: "90d" })).toBe(2184);
expect(provider.dedupWindowHours?.({ alertBefore: "1d" })).toBe(48);
// Falls back to the default when the condition can't be parsed.
expect(provider.dedupWindowHours?.({ alertBefore: "bad" })).toBe(24);
expect(provider.dedupWindowHours?.({ alertBefore: "91d" })).toBe(24);
});
+ test("dedup window never outruns history retention, so it can't read rows the prune has deleted", () => {
+ const provider = buildProvider();
+ // 90d + the 1d scan lead would be 2184h, past the 90-day retention: capped so the dedup lookup
+ // always lands on rows that still exist.
+ expect(provider.dedupWindowHours?.({ alertBefore: "90d" })).toBe(MAX_DEDUP_WINDOW_HOURS);
+ expect(MAX_DEDUP_WINDOW_HOURS).toBeLessThan(ALERT_HISTORY_RETENTION_DAYS * 24);
+ });
+
test("assertPermission allows read but denies create when only read is granted (org scope)", async () => {
const provider = buildProvider({ abilityRules: [{ action: "read", subject: "identity" }] });
await expect(
diff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
index f13699f098..c1c952c306 100644
--- a/backend/src/services/alert/providers/identity-credential-alert-provider.ts
+++ b/backend/src/services/alert/providers/identity-credential-alert-provider.ts
@@ -16,6 +16,7 @@ import {
AlertPermissionAction,
DEFAULT_DEDUP_WINDOW_HOURS,
IResourceAlertProvider,
+ MAX_DEDUP_WINDOW_HOURS,
TAlertContext,
TAlertPermissionInput,
TFindDueTargetsInput
@@ -273,10 +274,9 @@ export const identityCredentialAlertProviderFactory = ({
const parsed = IdentityCredentialConditionSchema.safeParse(condition);
if (!parsed.success) return DEFAULT_DEDUP_WINDOW_HOURS;
if (parsed.data.dailyReminder) return DAILY_REPEAT_DEDUP_WINDOW_HOURS;
- // Span the widened scan window (alertBefore + the scan lead) so a target still fires only once.
- return Math.max(
- DEFAULT_DEDUP_WINDOW_HOURS,
- (alertBeforeDays(parsed.data.alertBefore) + ALERT_SCAN_LEAD_DAYS) * 24
+ return Math.min(
+ MAX_DEDUP_WINDOW_HOURS,
+ Math.max(DEFAULT_DEDUP_WINDOW_HOURS, (alertBeforeDays(parsed.data.alertBefore) + ALERT_SCAN_LEAD_DAYS) * 24)
);
},
assertPermission,