Skip to content

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

add delivered state so rows are kept for a short period and reruns do not dup

Thiago Araujo da Silvab1b53c55491f
diff --git a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
index 3501a96184..d578d6b4c7 100644
--- a/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
+++ b/backend/src/db/migrations/20260522191822_audit-log-stream-outbox.ts
@@ -12,7 +12,7 @@ export async function up(knex: Knex): Promise<void> {
t.uuid("auditLogId").notNullable();
t.jsonb("payload").notNullable();
t.string("status").notNullable().defaultTo("pending");
- t.check(`"status" IN ('pending', 'processing', 'retry')`);
+ t.check(`"status" IN ('pending', 'processing', 'retry', 'delivered')`);
t.integer("attempts").notNullable().defaultTo(0);
t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
t.timestamp("lockedAt", { useTz: true });
@@ -39,6 +39,13 @@ export async function up(knex: Knex): Promise<void> {
ON "${TableName.AuditLogStreamOutbox}" ("lockedAt")
WHERE status = 'processing'
`);
+
+ // Cleanup cron: prune delivered rows past the retention window.
+ await knex.schema.raw(`
+ CREATE INDEX IF NOT EXISTS "${TableName.AuditLogStreamOutbox}_delivered_idx"
+ ON "${TableName.AuditLogStreamOutbox}" ("updatedAt")
+ WHERE status = 'delivered'
+ `);
}
await createOnUpdateTrigger(knex, TableName.AuditLogStreamOutbox);
@@ -59,6 +66,8 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
t.index(["streamId", "failedAt"]);
t.index(["orgId", "failedAt"]);
+ // Cleanup cron scans by failedAt only — the per-stream/per-org composites above don't help.
+ t.index(["failedAt"]);
});
}
}
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
index 00d39e497f..e46569d876 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
@@ -86,12 +86,17 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
};
- const deleteByIds = async (ids: number[], tx?: Knex) => {
+ const markBatchAsDelivered = async (ids: number[], tx?: Knex) => {
if (ids.length === 0) return;
try {
- await (tx || db)(TableName.AuditLogStreamOutbox).whereIn("id", ids).del();
+ await (tx || db)(TableName.AuditLogStreamOutbox).whereIn("id", ids).update({
+ status: AuditLogStreamOutboxStatus.Delivered,
+ lockedAt: null,
+ workerId: null,
+ lastError: null
+ });
} catch (error) {
- throw new DatabaseError({ error, name: "AuditLogStreamOutbox: deleteByIds" });
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: markBatchAsDelivered" });
}
};
@@ -152,7 +157,9 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// Commit the outcome of a chunked delivery for a single claimed batch in one
// transaction:
- // - successIds: rows that reached the provider — delete them.
+ // - successIds: rows that reached the provider — flip to 'delivered' (kept
+ // around as the dedup guard against a re-fanout from a
+ // retried ingest tick; pruned later by the cleanup cron).
// - retriable: rows whose chunk failed but can still retry — flip to 'retry'
// with attempt+1 and lastError = the chunk's error.
// - exhausted: rows whose chunk failed and used up MAX_ATTEMPTS — move to DLQ.
@@ -162,10 +169,10 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
// group so each row's lastError reflects what actually broke for it.
//
// Folding all three outcomes into a single transaction means a crash between
- // the delete and the retry/DLQ writes can't leave the claim half-applied
- // (e.g. delivered rows deleted but retriable rows still 'processing'); either
- // every write commits or none do, and the stale-claim sweeper picks up an
- // un-applied claim on the next pass.
+ // the writes can't leave the claim half-applied (e.g. some rows flipped to
+ // 'delivered' but retriable rows still 'processing'); either every write
+ // commits or none do, and the stale-claim sweeper picks up an un-applied
+ // claim on the next pass.
const commitDeliveryResult = async (input: {
successIds: number[];
retriable: { rows: TFailedStreamRow[]; nextRetryAt: Date } | null;
@@ -176,7 +183,7 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
try {
await db.transaction(async (tx) => {
if (input.successIds.length > 0) {
- await deleteByIds(input.successIds, tx);
+ await markBatchAsDelivered(input.successIds, tx);
}
if (input.retriable && retriableRows.length > 0) {
const idsByError = new Map<string, number[]>();
@@ -267,6 +274,57 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
};
+ const deleteDeliveredOlderThan = async (
+ retentionMs: number,
+ batchSize = 10_000,
+ maxBatches = 100
+ ): Promise<number> => {
+ try {
+ let total = 0;
+ for (let i = 0; i < maxBatches; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const deleted = await db(TableName.AuditLogStreamOutbox)
+ .whereIn("id", function selectExpiredIds() {
+ void this.from(TableName.AuditLogStreamOutbox)
+ .select("id")
+ .where("status", AuditLogStreamOutboxStatus.Delivered)
+ .andWhereRaw(`"updatedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [retentionMs])
+ .limit(batchSize);
+ })
+ .del();
+
+ total += deleted;
+ if (deleted < batchSize) break;
+ }
+ return total;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: deleteDeliveredOlderThan" });
+ }
+ };
+
+ const deleteDlqOlderThan = async (retentionMs: number, batchSize = 10_000, maxBatches = 100): Promise<number> => {
+ try {
+ let total = 0;
+ for (let i = 0; i < maxBatches; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const deleted = await db(TableName.AuditLogStreamOutboxDlq)
+ .whereIn("id", function selectExpiredIds() {
+ void this.from(TableName.AuditLogStreamOutboxDlq)
+ .select("id")
+ .whereRaw(`"failedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [retentionMs])
+ .limit(batchSize);
+ })
+ .del();
+
+ total += deleted;
+ if (deleted < batchSize) break;
+ }
+ return total;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: deleteDlqOlderThan" });
+ }
+ };
+
const findStreamsWithOverdueRows = async (): Promise<{ streamId: string; orgId: string; provider: string }[]> => {
try {
return await db(`${TableName.AuditLogStreamOutbox} as o`)
@@ -286,6 +344,8 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
claimBatchForStream,
commitDeliveryResult,
recoverStaleClaims,
- findStreamsWithOverdueRows
+ findStreamsWithOverdueRows,
+ deleteDeliveredOlderThan,
+ deleteDlqOlderThan
};
};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
index 61e97faa7f..2282a603bf 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
@@ -10,10 +10,18 @@ import { TAuditLogStreamOutboxServiceFactory } from "./audit-log-stream-outbox-s
const STALE_CLAIM_SWEEPER_CRON = "*/5 * * * *";
const STALE_CLAIM_SWEEPER_RUN_HASH_TTL_S = 60 * 60;
+// Cleanup cadence. Runs hourly to prune both 'delivered' outbox rows and DLQ
+// entries past their respective retention windows
+const CLEANUP_CRON = "0 * * * *";
+const CLEANUP_RUN_HASH_TTL_S = 24 * 60 * 60;
+
export type TAuditLogStreamOutboxQueueDep = {
queueService: TQueueServiceFactory;
cronJob: TCronJobFactory;
- auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "drainStream" | "sweepStaleClaims">;
+ auditLogStreamOutboxService: Pick<
+ TAuditLogStreamOutboxServiceFactory,
+ "drainStream" | "sweepStaleClaims" | "pruneDeliveredRows" | "pruneDlqEntries"
+ >;
};
// Boots one BullMQ worker per provider so a slow upstream (e.g. a wedged
@@ -44,8 +52,6 @@ export const auditLogStreamOutboxQueueFactory = ({
registerWorker(QueueName.AuditLogStreamDatadog, LogProvider.Datadog);
registerWorker(QueueName.AuditLogStreamSplunk, LogProvider.Splunk);
- // Stale-claim sweeper. Registered separately via init() so it lands in the
- // cron startup batch alongside the other cron registrations in routes/index.ts.
const init = () => {
cronJob.register({
name: CronJobName.AuditLogStreamOutboxStaleClaimSweeper,
@@ -55,6 +61,23 @@ export const auditLogStreamOutboxQueueFactory = ({
await auditLogStreamOutboxService.sweepStaleClaims();
}
});
+
+ cronJob.register({
+ name: CronJobName.AuditLogStreamOutboxDeliveredCleanup,
+ pattern: CLEANUP_CRON,
+ runHashTtlS: CLEANUP_RUN_HASH_TTL_S,
+ handler: async () => {
+ const results = await Promise.allSettled([
+ auditLogStreamOutboxService.pruneDeliveredRows(),
+ auditLogStreamOutboxService.pruneDlqEntries()
+ ]);
+ for (const result of results) {
+ if (result.status === "rejected") {
+ logger.error(result.reason as Error, "audit-log-stream-outbox: cleanup prune failed");
+ }
+ }
+ }
+ });
};
return { init };
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
index 1f1369b0ab..3212154277 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.test.ts
@@ -69,7 +69,10 @@ const createService = () => {
batchInsert: vi.fn(async () => undefined),
claimBatchForStream: vi.fn<(...args: unknown[]) => Promise<TAuditLogStreamOutboxRow[]>>(async () => []),
commitDeliveryResult: vi.fn<(input: unknown) => Promise<void>>(async () => undefined),
- recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 }))
+ recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 })),
+ findStreamsWithOverdueRows: vi.fn(async () => []),
+ deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0),
+ deleteDlqOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)
};
const auditLogStreamDAL = {
@@ -216,7 +219,9 @@ describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {
batchInsert: vi.fn<(rows: unknown[]) => Promise<void>>(async () => undefined),
claimBatchForStream: vi.fn(async () => []),
commitDeliveryResult: vi.fn(async () => undefined),
- recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 }))
+ recoverStaleClaims: vi.fn(async () => ({ retried: 0, movedToDlq: 0 })),
+ findStreamsWithOverdueRows: vi.fn(async () => []),
+ deleteDeliveredOlderThan: vi.fn<(retentionMs: number) => Promise<number>>(async () => 0)
};
const auditLogStreamDAL = {
@@ -295,3 +300,32 @@ describe("audit-log-stream-outbox-service enqueueForLogs batch fanout", () => {
expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();
});
});
+
+describe("audit-log-stream-outbox-service pruneDeliveredRows", () => {
+ test("delegates to DAL with the configured retention", async () => {
+ const { service, auditLogStreamOutboxDAL } = createService();
+ auditLogStreamOutboxDAL.deleteDeliveredOlderThan.mockResolvedValueOnce(42);
+
+ await service.pruneDeliveredRows();
+
+ expect(auditLogStreamOutboxDAL.deleteDeliveredOlderThan).toHaveBeenCalledTimes(1);
+ const [retentionMs] = auditLogStreamOutboxDAL.deleteDeliveredOlderThan.mock.calls[0];
+ // Retention must be positive and at least an hour — guards against accidental
+ // tightening that would defeat the dedup-window purpose of keeping delivered rows.
+ expect(retentionMs).toBeGreaterThanOrEqual(60 * 60_000);
+ });
+});
+
+describe("audit-log-stream-outbox-service pruneDlqEntries", () => {
+ test("delegates to DAL with the configured retention", async () => {
+ const { service, auditLogStreamOutboxDAL } = createService();
+ auditLogStreamOutboxDAL.deleteDlqOlderThan.mockResolvedValueOnce(7);
+
+ await service.pruneDlqEntries();
+
+ expect(auditLogStreamOutboxDAL.deleteDlqOlderThan).toHaveBeenCalledTimes(1);
+ const [retentionMs] = auditLogStreamOutboxDAL.deleteDlqOlderThan.mock.calls[0];
+ // DLQ retention should give operators at least a day to triage.
+ expect(retentionMs).toBeGreaterThanOrEqual(24 * 60 * 60_000);
+ });
+});
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
index e42463fc8b..0ef2c6707d 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
@@ -37,6 +37,18 @@ const BACKOFF_MAX_MS = 15 * 60_000;
// Anything older than this can't be a live worker.
export const STALE_CLAIM_THRESHOLD_MS = 10 * 60_000;
+// Retention for 'delivered' outbox rows. The row is the dedup guard against a
+// re-fanout from the ingest consumer (e.g. after a Redis streamTrim failure),
+// so the retention only needs to outlive how long an ingest-stream entry can
+// stay un-trimmed in practice. 1h is comfortably above that for any realistic
+// Redis/DB blip; the cleanup cron runs hourly so rows live ~1–2h in steady state.
+export const DELIVERED_RETENTION_MS = 60 * 60_000;
+
+// Retention for DLQ entries. Long enough for an operator to notice + triage a
+// wedged provider via dashboard, short enough that the table doesn't grow
+// without bound. Same cron prunes these alongside delivered rows.
+export const DLQ_RETENTION_MS = 24 * 60 * 60_000;
+
const PROVIDER_QUEUE_MAP: Record<LogProvider, QueueName> = {
[LogProvider.Azure]: QueueName.AuditLogStreamAzure,
[LogProvider.Cribl]: QueueName.AuditLogStreamCribl,
@@ -92,6 +104,8 @@ export type TAuditLogStreamOutboxServiceFactory = {
enqueueForLogs: (auditLogs: TAuditLogs[]) => Promise<void>;
drainStream: (data: TAuditLogStreamFlushJobData) => Promise<void>;
sweepStaleClaims: () => Promise<void>;
+ pruneDeliveredRows: () => Promise<void>;
+ pruneDlqEntries: () => Promise<void>;
};
export const auditLogStreamOutboxServiceFactory = ({
@@ -308,9 +322,27 @@ export const auditLogStreamOutboxServiceFactory = ({
logger.info(`audit-log-stream-outbox: swept overdue streams [overdue=${overdueStreams.length}] [woken=${woken}]`);
};
+ const pruneDeliveredRows = async () => {
+ const deleted = await auditLogStreamOutboxDAL.deleteDeliveredOlderThan(DELIVERED_RETENTION_MS);
+ if (deleted > 0) {
+ logger.info(
+ `audit-log-stream-outbox: pruned delivered rows [deleted=${deleted}] [retentionMs=${DELIVERED_RETENTION_MS}]`
+ );
+ }
+ };
+
+ const pruneDlqEntries = async () => {
+ const deleted = await auditLogStreamOutboxDAL.deleteDlqOlderThan(DLQ_RETENTION_MS);
+ if (deleted > 0) {
+ logger.info(`audit-log-stream-outbox: pruned dlq entries [deleted=${deleted}] [retentionMs=${DLQ_RETENTION_MS}]`);
+ }
+ };
+
return {
enqueueForLogs,
drainStream,
- sweepStaleClaims
+ sweepStaleClaims,
+ pruneDeliveredRows,
+ pruneDlqEntries
};
};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
index d10968ad23..30f2a14dde 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types.ts
@@ -5,7 +5,8 @@ import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";
export enum AuditLogStreamOutboxStatus {
Pending = "pending",
Processing = "processing",
- Retry = "retry"
+ Retry = "retry",
+ Delivered = "delivered"
}
export type TAuditLogStreamOutboxRow = {
@@ -30,9 +31,6 @@ export type TAuditLogStreamFlushJobData = {
provider: LogProvider;
};
-// Pairs an outbox row with the error its chunk hit during delivery. Different
-// chunks of one claim can fail with different errors, so the worker collects
-// these and the DAL groups by message when writing back to retry / DLQ.
export type TFailedStreamRow = {
row: TAuditLogStreamOutboxRow;
errorMessage: string;
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 30b0774c6d..10633e5976 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -36,7 +36,8 @@ export const CronJobName = {
CaCrlRotation: "ca-crl-rotation",
SignerDailyAutoRenewal: "signer-daily-auto-renewal",
SignerIssuancePolling: "signer-issuance-polling",
- AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper"
+ AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper",
+ AuditLogStreamOutboxDeliveredCleanup: "audit-log-stream-outbox-delivered-cleanup"
} as const;
// ── tuning constants ──────────────────────────────────────────────────────────