Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(audit-log-stream): alert on stale-claim drops and clear the failing flag without trusting a replica read
Calvind3bfe817d294
diff --git a/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts b/backend/e2e-test/audit-log-stream-outbox.integration.spec.tsindex 033f20a471..a98c084894 100644--- a/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts+++ b/backend/e2e-test/audit-log-stream-outbox.integration.spec.ts@@ -195,6 +195,28 @@ describe("audit log stream outbox (postgres)", () => {});});+ describe("sweepStaleClaims", () => {+ test("dropping an exhausted stale claim flags the stream and emits one event", async () => {+ const stream = await createStream("http://127.0.0.1:1/");+ const lockedAt = new Date(Date.now() - 11 * 60_000);+ const rowIds = [+ await seedRow(stream.id, { attempts: LAST_ATTEMPT, status: AuditLogStreamOutboxStatus.Processing, lockedAt }),+ await seedRow(stream.id, { attempts: LAST_ATTEMPT, status: AuditLogStreamOutboxStatus.Processing, lockedAt })+ ];++ await service.sweepStaleClaims();++ expect(await Promise.all(rowIds.map(outboxRow))).toEqual([undefined, undefined]);+ const health = await streamHealth(stream.id);+ expect(health?.failingSince).toBeInstanceOf(Date);+ expect(health?.lastDeliveryError).toContain("delivery worker stopped");++ const emitted = await events();+ expect(emitted).toHaveLength(1);+ expect(emitted[0].payload).toMatchObject({ targetIds: [stream.id], droppedCount: 2 });+ });+ });+describe("drainStream against a real receiver", () => {let receiver: TFakeWebhookServer;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.tsindex 75d73ab1d8..9e3e5bb96d 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@@ -170,66 +170,65 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {// emits a metric for the dropped count.const recoverStaleClaims = async (thresholdMs: number,- maxAttempts: number+ maxAttempts: number,+ tx: Knex): Promise<{ retried: number; dropped: { streamId: string; orgId: string; provider: string | null }[] }> => {try {- return await db.transaction(async (tx) => {- const staleRows = await tx(TableName.AuditLogStreamOutbox)- .where("status", AuditLogStreamOutboxStatus.Processing)- .andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])- .forUpdate()- .skipLocked()- .select<TAuditLogStreamOutboxRow[]>("*");+ const staleRows = await tx(TableName.AuditLogStreamOutbox)+ .where("status", AuditLogStreamOutboxStatus.Processing)+ .andWhereRaw(`"lockedAt" < NOW() - (? || ' milliseconds')::INTERVAL`, [thresholdMs])+ .forUpdate()+ .skipLocked()+ .select<TAuditLogStreamOutboxRow[]>("*");- if (staleRows.length === 0) return { retried: 0, dropped: [] };+ if (staleRows.length === 0) return { retried: 0, dropped: [] };- const exhausted: TAuditLogStreamOutboxRow[] = [];- const retriable: TAuditLogStreamOutboxRow[] = [];- for (const row of staleRows) {- if (row.attempts + 1 >= maxAttempts) {- exhausted.push(row);- } else {- retriable.push(row);- }+ const exhausted: TAuditLogStreamOutboxRow[] = [];+ const retriable: TAuditLogStreamOutboxRow[] = [];+ for (const row of staleRows) {+ if (row.attempts + 1 >= maxAttempts) {+ exhausted.push(row);+ } else {+ retriable.push(row);}+ }- if (retriable.length > 0) {- await tx(TableName.AuditLogStreamOutbox)- .whereIn(- "id",- retriable.map((row) => row.id)- )- .update({- status: AuditLogStreamOutboxStatus.Retry,- attempts: db.raw('"attempts" + 1'),- nextRetryAt: tx.fn.now(),- lockedAt: null- });- }-- if (exhausted.length === 0) return { retried: retriable.length, dropped: [] };-+ if (retriable.length > 0) {await tx(TableName.AuditLogStreamOutbox).whereIn("id",- exhausted.map((row) => row.id)+ retriable.map((row) => row.id))- .del();+ .update({+ status: AuditLogStreamOutboxStatus.Retry,+ attempts: db.raw('"attempts" + 1'),+ nextRetryAt: tx.fn.now(),+ lockedAt: null+ });+ }- const streams = await tx(TableName.AuditLogStream)- .whereIn("id", [...new Set(exhausted.map((row) => row.streamId))])- .select<{ id: string; provider: string }[]>("id", "provider");- const providerByStreamId = new Map(streams.map((stream) => [stream.id, stream.provider]));+ if (exhausted.length === 0) return { retried: retriable.length, dropped: [] };- return {- retried: retriable.length,- dropped: exhausted.map((row) => ({- streamId: row.streamId,- orgId: row.orgId,- provider: providerByStreamId.get(row.streamId) ?? null- }))- };- });+ await tx(TableName.AuditLogStreamOutbox)+ .whereIn(+ "id",+ exhausted.map((row) => row.id)+ )+ .del();++ const streams = await tx(TableName.AuditLogStream)+ .whereIn("id", [...new Set(exhausted.map((row) => row.streamId))])+ .select<{ id: string; provider: string }[]>("id", "provider");+ const providerByStreamId = new Map(streams.map((stream) => [stream.id, stream.provider]));++ return {+ retried: retriable.length,+ dropped: exhausted.map((row) => ({+ streamId: row.streamId,+ orgId: row.orgId,+ provider: providerByStreamId.get(row.streamId) ?? null+ }))+ };} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: recoverStaleClaims" });}@@ -309,9 +308,13 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {}};+ // Called after every clean batch, so the whereNotNull keeps it from writing to a healthy stream.const clearStreamFailing = async (streamId: string, tx: Knex) => {try {- await tx(TableName.AuditLogStream).where("id", streamId).update({ failingSince: null, lastDeliveryError: null });+ await tx(TableName.AuditLogStream)+ .where("id", streamId)+ .whereNotNull("failingSince")+ .update({ failingSince: null, lastDeliveryError: null });} catch (error) {throw new DatabaseError({ error, name: "AuditLogStreamOutbox: clearStreamFailing" });}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.tsindex a4871ab8ff..5f7b472852 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@@ -107,7 +107,6 @@ const createService = () => {orgId: string;encryptedCredentials: Buffer;streamMode: StreamMode;- failingSince?: Date | null;}> => ({id: STREAM_ID,provider: PROVIDER,@@ -205,6 +204,31 @@ describe("audit-log-stream-outbox-service drainStream failure handling", () => {expect(call.exhaustedIds).toEqual([]);});+ test("clears the failing flag after a clean batch even when the stream was read as healthy", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();++ auditLogStreamOutboxDAL.claimBatchForStream.mockResolvedValueOnce([buildRow()]).mockResolvedValueOnce([]);+ batchStreamLog.mockResolvedValueOnce(undefined);++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(auditLogStreamOutboxDAL.clearStreamFailing).toHaveBeenCalledWith(STREAM_ID, expect.anything());+ });++ test("does not clear the failing flag when any row in the batch failed", async () => {+ const { service, auditLogStreamOutboxDAL } = createService();++ getProviderBatchLimit.mockReturnValue({ maxLogs: 1, maxBytes: 4 * 1024 * 1024 });+ auditLogStreamOutboxDAL.claimBatchForStream+ .mockResolvedValueOnce([buildRow({ id: 1, auditLogId: "log-1" }), buildRow({ id: 2, auditLogId: "log-2" })])+ .mockResolvedValueOnce([]);+ batchStreamLog.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error(FAILURE_MESSAGE));++ await service.drainStream({ streamId: STREAM_ID, orgId: ORG_ID, provider: PROVIDER });++ expect(auditLogStreamOutboxDAL.clearStreamFailing).not.toHaveBeenCalled();+ });+test("stops draining after the first failed batch — does not claim another batch", async () => {const { service, auditLogStreamOutboxDAL } = createService();@@ -562,12 +586,31 @@ describe("audit-log-stream-outbox-service sweepStaleClaims", () => {});const sweepWith = async (dropped: { streamId: string; orgId: string; provider: string | null }[], retried = 0) => {- const { service, auditLogStreamOutboxDAL } = createService();+ const { service, auditLogStreamOutboxDAL, eventEmitter } = createService();auditLogStreamOutboxDAL.recoverStaleClaims = vi.fn(async () => ({ retried, dropped })) as never;await service.sweepStaleClaims();- return auditLogStreamOutboxDAL;+ return { auditLogStreamOutboxDAL, eventEmitter };};+ test("emits one alert per stream with drops, carrying that stream's own count", async () => {+ const { eventEmitter } = await sweepWith([+ { streamId: "stream-a", orgId: ORG_ID, provider: LogProvider.Datadog },+ { streamId: "stream-a", orgId: ORG_ID, provider: LogProvider.Datadog },+ { streamId: "stream-b", orgId: ORG_ID, provider: LogProvider.Splunk }+ ]);++ const payloads = eventEmitter.emit.mock.calls.map(+ ([event]) => (event as { payload: { targetIds: string[]; droppedCount: number } }).payload+ );+ expect(payloads).toHaveLength(2);+ expect(payloads).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ targetIds: ["stream-a"], droppedCount: 2 }),+ expect.objectContaining({ targetIds: ["stream-b"], droppedCount: 1 })+ ])+ );+ });+test("labels a drop with the stream's provider so sum by(provider) accounts for it", async () => {await sweepWith([{ streamId: STREAM_ID, orgId: ORG_ID, provider: LogProvider.Datadog }]);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.tsindex 59a3a42d24..ecae61bb2a 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@@ -50,6 +50,8 @@ const BACKOFF_BASE_MS = 30_000;// hold time is MAX_BATCHES_PER_JOB × AUDIT_LOG_STREAM_BATCH_TIMEOUT ≈ 5 min.// Anything older than this can't be a live worker.export const STALE_CLAIM_THRESHOLD_MS = 10 * 60_000;+// Shown to customers in the delivery-failed alert, where a stale claim has no provider error to report.+const STALE_CLAIM_DROP_MESSAGE = "Events were dropped because the delivery worker stopped during their final attempt.";// 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),@@ -263,9 +265,6 @@ export const auditLogStreamOutboxServiceFactory = ({// else gets a JSON array per request. Single mode treats each row as its own chunk.const isSingleMode = stream.streamMode === StreamMode.Single;- // Whether the stream row is currently marked failing, as last read or written by this job.- let streamMarkedFailing = Boolean(stream.failingSince);-for (let batchIdx = 0; batchIdx < MAX_BATCHES_PER_JOB; batchIdx += 1) {// eslint-disable-next-line no-await-in-loopconst claimed = await auditLogStreamOutboxDAL.claimBatchForStream(streamId, BATCH_SIZE);@@ -373,8 +372,10 @@ export const auditLogStreamOutboxServiceFactory = ({// The state flip and the alert event commit with the drop itself, so an alert is never lost// or sent for rows that are still retrying.+ // The clear runs on every clean batch rather than when the stream was read as failing: that+ // read comes from a replica and can lag, and a missed clear would silence the next outage.const droppedRows = exhausted.length > 0;- const shouldClearFailing = streamMarkedFailing && streamFail.length === 0 && streamSuccess.length > 0;+ const shouldClearFailing = streamFail.length === 0 && streamSuccess.length > 0;// eslint-disable-next-line no-await-in-loopawait auditLogStreamOutboxDAL.transaction(async (tx) => {await auditLogStreamOutboxDAL.commitDeliveryResult(@@ -394,7 +395,6 @@ export const auditLogStreamOutboxServiceFactory = ({await auditLogStreamOutboxDAL.clearStreamFailing(streamId, tx);}});- if (shouldClearFailing) streamMarkedFailing = false;if (streamFail.length > 0) {// Each failed chunk is already logged with its error above; the rows are@@ -427,32 +427,45 @@ export const auditLogStreamOutboxServiceFactory = ({// - claimBatchForStream's FOR UPDATE SKIP LOCKED + atomic flip to 'processing'// so even concurrent workers claim disjoint rows.const sweepStaleClaims = async () => {- const { retried, dropped } = await auditLogStreamOutboxDAL.recoverStaleClaims(- STALE_CLAIM_THRESHOLD_MS,- MAX_ATTEMPTS- );- if (retried > 0 || dropped.length > 0) {- logger.warn(- `audit-log-stream-outbox: recovered stale claims [retried=${retried}] [dropped=${dropped.length}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`- );- }- if (dropped.length > 0) {- // Stale claims that used up their attempts are dropped (no DLQ); count them alongside- // delivery-path exhaustions so both losses show up on the same counter, keyed the same way.- // The provider is resolved by the DAL and is null only when the stream itself is already gone,- // which is one of the reasons a claim goes stale.- const droppedCountByStream = new Map<string, { provider: string | null; count: number }>();- for (const { streamId, provider } of dropped) {- const existing = droppedCountByStream.get(streamId);+ // Stale claims that used up their attempts are dropped (no DLQ), so they flag the stream and emit+ // the alert event in the same transaction as the delete, exactly like a drop on the delivery path.+ // The provider is resolved by the DAL and is null only when the stream itself is already gone,+ // which is one of the reasons a claim goes stale; markStreamFailing then matches no row and+ // nothing is emitted.+ const { retried, droppedByStream } = await auditLogStreamOutboxDAL.transaction(async (tx) => {+ const recovered = await auditLogStreamOutboxDAL.recoverStaleClaims(STALE_CLAIM_THRESHOLD_MS, MAX_ATTEMPTS, tx);++ const grouped = new Map<string, { orgId: string; provider: string | null; count: number }>();+ for (const { streamId, orgId, provider } of recovered.dropped) {+ const existing = grouped.get(streamId);if (existing) existing.count += 1;- else droppedCountByStream.set(streamId, { provider, count: 1 });+ else grouped.set(streamId, { orgId, provider, count: 1 });}- for (const [streamId, { provider, count }] of droppedCountByStream) {- auditLogStreamDeliveryExhaustedCounter.add(count, {- "audit_log_stream.id": streamId,- ...(provider && { "audit_log_stream.provider": provider })- });++ for (const [streamId, { orgId, provider, count }] of grouped) {+ // eslint-disable-next-line no-await-in-loop+ await flagStreamFailing(+ { streamId, orgId, provider, errorMessage: STALE_CLAIM_DROP_MESSAGE, droppedCount: count },+ tx+ );}++ return { retried: recovered.retried, droppedByStream: grouped };+ });++ const droppedTotal = Array.from(droppedByStream.values()).reduce((sum, { count }) => sum + count, 0);+ if (retried > 0 || droppedTotal > 0) {+ logger.warn(+ `audit-log-stream-outbox: recovered stale claims [retried=${retried}] [dropped=${droppedTotal}] [thresholdMs=${STALE_CLAIM_THRESHOLD_MS}]`+ );+ }+ // Counted alongside delivery-path exhaustions so both losses show up on the same counter, keyed+ // the same way.+ for (const [streamId, { provider, count }] of droppedByStream) {+ auditLogStreamDeliveryExhaustedCounter.add(count, {+ "audit_log_stream.id": streamId,+ ...(provider && { "audit_log_stream.provider": provider })+ });}const overdueStreams = await auditLogStreamOutboxDAL.findStreamsWithOverdueRows();diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogStreamAlertsCard.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/components/AuditLogStreamAlertAction.tsxsimilarity index 100%rename from frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogStreamAlertsCard.tsxrename to frontend/src/pages/organization/AuditLogsPage/components/AuditLogStreamTab/components/AuditLogStreamAlertAction.tsx