Skip to content

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

fix lack of logs on flush crash

Thiago Araujo da Silva892f0252f5ec
diff --git a/backend/e2e-test/event-outbox.spec.ts b/backend/e2e-test/event-outbox.spec.ts
index afc817ea94..721df70ebb 100644
--- a/backend/e2e-test/event-outbox.spec.ts
+++ b/backend/e2e-test/event-outbox.spec.ts
@@ -157,6 +157,21 @@ describe("event outbox (postgres)", () => {
expect(failed.attempts).toBe(MAX_OUTBOX_ATTEMPTS);
});
+ test("commitResults ignores a late result for a claim the sweeper already handed back", async () => {
+ await insert([makeRow()]);
+ const [row] = await dal.claimBatch(KEY, 10);
+ await testDb(TableName.EventOutbox)
+ .where("id", row.id)
+ .update({ lockedAt: new Date(Date.now() - 60 * 60_000) });
+ await dal.recoverStaleClaims({ thresholdMs: 10 * 60_000, maxAttempts: MAX_OUTBOX_ATTEMPTS, limit: 100 });
+
+ await dal.commitResults({ delivered: [{ ids: [String(row.id)] }], retriable: [], failed: [] });
+
+ const [stored] = await rowsFor();
+ expect(stored.status).toBe(EventOutboxStatus.Retry);
+ expect(stored.attempts).toBe(1);
+ });
+
test("extendClaims refreshes only rows still processing", async () => {
await insert([makeRow(), makeRow()]);
const [claimed, released] = await dal.claimBatch(KEY, 10);
diff --git a/backend/src/services/event-outbox/event-outbox-dal.test.ts b/backend/src/services/event-outbox/event-outbox-dal.test.ts
index 38f8a6ec23..126b7bec52 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.test.ts
@@ -274,6 +274,23 @@ describe("event outbox dal", () => {
expect(calls.update.map((patch) => patch.status)).toEqual([EventOutboxStatus.Delivered, EventOutboxStatus.Failed]);
});
+ // A claim the sweeper has already handed back may belong to another worker by the time the original
+ // one reports; its late result must not clobber the new owner's.
+ test("commitResults only touches rows still held by a processing claim", async () => {
+ const { dal, calls } = buildDAL();
+
+ await dal.commitResults({
+ delivered: [{ ids: ["1"] }],
+ retriable: [{ ids: ["2"], nextRetryDelayMs: 1_000 }],
+ failed: [{ ids: ["3"] }]
+ });
+
+ expect(calls.update).toHaveLength(3);
+ expect(calls.where.filter((args) => args[0] === "status" && args[1] === EventOutboxStatus.Processing)).toHaveLength(
+ 3
+ );
+ });
+
test("recoverStaleClaims looks only at claims older than the threshold", async () => {
const { dal, calls } = buildDAL();
diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.ts
index 1cd22efc59..b1f905dbc7 100644
--- a/backend/src/services/event-outbox/event-outbox-dal.ts
+++ b/backend/src/services/event-outbox/event-outbox-dal.ts
@@ -117,6 +117,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
await tx(TableName.EventOutbox)
.whereIn("id", group.ids)
+ .where("status", EventOutboxStatus.Processing)
.update({
status: EventOutboxStatus.Delivered,
lockedAt: null,
@@ -131,6 +132,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
await tx(TableName.EventOutbox)
.whereIn("id", group.ids)
+ .where("status", EventOutboxStatus.Processing)
.update({
status: EventOutboxStatus.Retry,
attempts: db.raw('"attempts" + 1'),
@@ -147,6 +149,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {
// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes are serial
await tx(TableName.EventOutbox)
.whereIn("id", group.ids)
+ .where("status", EventOutboxStatus.Processing)
.update({
status: EventOutboxStatus.Failed,
attempts: db.raw('"attempts" + 1'),
diff --git a/backend/src/services/event-outbox/event-outbox-queue.test.ts b/backend/src/services/event-outbox/event-outbox-queue.test.ts
index 289cb0cc14..8a4fc85a24 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.test.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.test.ts
@@ -3,8 +3,17 @@ import { QueueName } from "@app/queue";
import { eventOutboxQueueFactory } from "./event-outbox-queue";
import { TOutboxFlushKey } from "./event-outbox-types";
+const loggedErrors: unknown[][] = [];
+
vi.mock("@app/lib/logger", () => ({
- logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ logger: {
+ info: () => {},
+ warn: () => {},
+ error: (...args: unknown[]) => {
+ loggedErrors.push(args);
+ },
+ debug: () => {}
+ },
initLogger: () => {}
}));
@@ -21,14 +30,22 @@ vi.mock("@app/lib/config/env", () => ({
beforeEach(() => {
config.isGeneralWorkerRunModeEnabled = true;
config.isSecondaryInstance = false;
+ loggedErrors.length = 0;
});
const KEY: TOutboxFlushKey = { consumer: "alert", resourceType: "approval.workflow", resourceId: "policy-1" };
-const buildQueue = (opts?: { keys?: TOutboxFlushKey[]; onDiscover?: () => Promise<void> }) => {
+type TFlushHandler = (job: { data: TOutboxFlushKey }) => Promise<void>;
+
+const buildQueue = (opts?: {
+ keys?: TOutboxFlushKey[];
+ onDiscover?: () => Promise<void>;
+ drain?: (key: TOutboxFlushKey) => Promise<unknown>;
+}) => {
const queued: { name: string; data: unknown; jobId?: string; attempts?: number }[] = [];
const discoveredFor: string[][] = [];
const registeredCrons: { name: string; enabled?: boolean }[] = [];
+ let flushHandler: TFlushHandler | undefined;
let discoverCalls = 0;
const factory = eventOutboxQueueFactory({
@@ -36,7 +53,9 @@ const buildQueue = (opts?: { keys?: TOutboxFlushKey[]; onDiscover?: () => Promis
queue: async (name: string, _job: string, data: unknown, options: { jobId?: string; attempts?: number }) => {
queued.push({ name, data, jobId: options.jobId, attempts: options.attempts });
},
- start: () => {}
+ start: (_name: string, handler: TFlushHandler) => {
+ flushHandler = handler;
+ }
} as never,
cronJob: {
register: (entry: { name: string; enabled?: boolean }) => {
@@ -54,13 +73,20 @@ const buildQueue = (opts?: { keys?: TOutboxFlushKey[]; onDiscover?: () => Promis
findOldestPendingAgeSeconds: async () => []
} as never,
eventOutboxService: {
- drain: async () => ({ handled: 0, exhaustedConsumer: false }),
+ drain: opts?.drain ?? (async () => ({ handled: 0, unknownConsumer: false })),
sweepStaleClaims: async () => {},
pruneTerminalRows: async () => {}
} as never
});
- return { factory, queued, discoveredFor, registeredCrons, getDiscoverCalls: () => discoverCalls };
+ return {
+ factory,
+ queued,
+ discoveredFor,
+ registeredCrons,
+ getDiscoverCalls: () => discoverCalls,
+ getFlushHandler: () => flushHandler as TFlushHandler
+ };
};
describe("event outbox relay", () => {
@@ -150,6 +176,24 @@ describe("event outbox relay", () => {
expect(getDiscoverCalls()).toBeGreaterThan(0);
});
+ // The flush job is removeOnFail with one attempt, so without this line a crashed drain leaves nothing
+ // but a counter behind.
+ test("logs and rethrows when a flush crashes so the failure is visible", async () => {
+ const boom = new Error("claimBatch: relation does not exist");
+ const { factory, getFlushHandler } = buildQueue({
+ drain: async () => {
+ throw boom;
+ }
+ });
+ factory.init();
+
+ await expect(getFlushHandler()({ data: KEY })).rejects.toBe(boom);
+
+ expect(loggedErrors).toHaveLength(1);
+ expect(loggedErrors[0][0]).toBe(boom);
+ expect(loggedErrors[0][1]).toContain("policy-1");
+ });
+
test("stops cleanly when nothing was ever started", async () => {
const { factory } = buildQueue();
diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.ts
index 85a162a2eb..232199edf7 100644
--- a/backend/src/services/event-outbox/event-outbox-queue.ts
+++ b/backend/src/services/event-outbox/event-outbox-queue.ts
@@ -108,7 +108,16 @@ export const eventOutboxQueueFactory = ({
QueueName.EventOutboxFlush,
async (job) => {
const { consumer, resourceType, resourceId } = job.data;
- await eventOutboxService.drain({ consumer, resourceType, resourceId });
+ try {
+ await eventOutboxService.drain({ consumer, resourceType, resourceId });
+ } catch (error) {
+ // The job is removeOnFail with a single attempt, so this line is the only trace it leaves.
+ logger.error(
+ error,
+ `event-outbox: flush worker crashed [consumer=${consumer}] [resourceType=${resourceType}] [resourceId=${resourceId}]`
+ );
+ throw error;
+ }
},
{ concurrency: FLUSH_WORKER_CONCURRENCY }
);