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 comments
Thiago Araujo da Silvaa4e3c79ae9c4
diff --git a/backend/e2e-test/event-outbox.spec.ts b/backend/e2e-test/event-outbox.spec.tsindex a228a9f8de..5da67441fb 100644--- a/backend/e2e-test/event-outbox.spec.ts+++ b/backend/e2e-test/event-outbox.spec.ts@@ -9,11 +9,11 @@ import { EventOutboxStatus, MAX_OUTBOX_ATTEMPTS } from "@app/services/event-outbdeclare const testDb: Knex;-// The unit tests assert query shape. Only Postgres can show that the partial-index conflict target-// compiles, that two claimers never take the same row, and that the retry clock is computed in SQL.+// Unit tests only check query shape. Only real Postgres can prove the partial-index conflict target+// compiles, two claimers never grab the same row, and the retry clock is computed in SQL.const dal = eventOutboxDALFactory(testDb as never);-// Unique per run so a crashed run's leftovers can't leak into the next one's assertions.+// Unique per run so leftovers from a crashed run can't leak into the next one.const CONSUMER = `e2e-${randomUUID().slice(0, 8)}`;const ORG_ID = randomUUID();@@ -58,8 +58,7 @@ describe("event outbox (postgres)", () => {const [a, b] = await Promise.all([dal.claimBatch(KEY, 3), dal.claimBatch(KEY, 3)]);- // Ids are bigints and arrive as strings, so order has to be checked numerically: "9" sorts after- // "10" as text.+ // Ids are bigints and come back as strings, so compare numerically.const idsA = a.rows.map((row) => Number(row.id));const idsB = b.rows.map((row) => Number(row.id));expect(new Set([...idsA, ...idsB]).size).toBe(idsA.length + idsB.length);@@ -69,7 +68,6 @@ describe("event outbox (postgres)", () => {const stored = await rowsFor();expect(stored.every((row) => row.status === EventOutboxStatus.Processing && row.lockedAt)).toBe(true);- // Each claim owns its rows outright, so the two claims can't share a token.expect(a.lockToken).not.toBe(b.lockToken);expect(new Set(stored.map((row) => row.lockToken))).toEqual(new Set([a.lockToken, b.lockToken]));expect((await dal.claimBatch(KEY, 10)).rows).toEqual([]);@@ -152,7 +150,7 @@ describe("event outbox (postgres)", () => {expect(retried.attempts).toBe(1);expect(retried.lockedAt).toBeNull();expect(retried.lockToken).toBeNull();- // Not handed straight back: a consumer that hangs every time must not hold a worker slot on repeat.+ // Backoff applies here too, otherwise a consumer that always hangs gets retried instantly.expect(new Date(retried.nextRetryAt).getTime()).toBeGreaterThan(Date.now() + 20_000);expect(failed.status).toBe(EventOutboxStatus.Failed);expect(failed.attempts).toBe(MAX_OUTBOX_ATTEMPTS);@@ -182,10 +180,9 @@ describe("event outbox (postgres)", () => {expect(stored.attempts).toBe(1);});- // The race the token exists for: the sweeper recycles a claim, a second worker picks the row up, and- // only then does the first worker report. Status alone can't tell the two apart, because the second- // worker's row is 'processing' too, so without the token the late result would mark it delivered and- // the second worker's outcome would be dropped.+ // The race the token exists for: the sweeper recycles a claim, another worker picks the row up, then+ // the first worker reports late. Both claims look 'processing', so without the token the late result+ // would clobber the new owner's outcome.test("commitResults leaves a row alone once another worker has reclaimed it", async () => {await insert([makeRow()]);const first = await dal.claimBatch(KEY, 10);@@ -193,7 +190,7 @@ describe("event outbox (postgres)", () => {.where("id", first.rows[0].id).update({ lockedAt: new Date(Date.now() - 60 * 60_000) });await dal.recoverStaleClaims({ thresholdMs: 10 * 60_000, maxAttempts: MAX_OUTBOX_ATTEMPTS, limit: 100 });- // Stand in for the backoff window elapsing.+ // Fast-forward past the backoff window.await testDb(TableName.EventOutbox).where("id", first.rows[0].id).update({ nextRetryAt: new Date() });const second = await dal.claimBatch(KEY, 10);expect(second.rows.map((row) => String(row.id))).toEqual([String(first.rows[0].id)]);@@ -211,7 +208,6 @@ describe("event outbox (postgres)", () => {expect(held.lockToken).toBe(second.lockToken);expect(held.lockedAt).not.toBeNull();- // And the worker that actually holds the claim still settles it.expect(await dal.commitResults({lockToken: second.lockToken,@@ -242,8 +238,8 @@ describe("event outbox (postgres)", () => {expect(b.lockedAt).toBeNull();});- // A heartbeat from the previous owner would otherwise keep the new owner's claim looking fresh, and- // the sweeper would never recover it if that worker really is gone.+ // Otherwise a late heartbeat from the old owner keeps the new claim looking fresh, and the sweeper+ // never recovers it if that worker really is gone.test("extendClaims does not refresh a claim another worker now holds", async () => {await insert([makeRow()]);const first = await dal.claimBatch(KEY, 10);diff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.tsindex 2aa0cae868..2bcd3264de 100644--- a/backend/src/db/migrations/20260908000000_event-outbox.ts+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts@@ -22,8 +22,8 @@ export async function up(knex: Knex): Promise<void> {t.timestamps(true, true, true);});- // Backs discovery and the claim. `id` before `nextRetryAt` so the claim's ORDER BY needs no sort- // node; `nextRetryAt` is there so rows still in backoff are skipped without touching the heap.+ // Backs discovery and the claim. `id` before `nextRetryAt` so the claim's ORDER BY needs no sort;+ // `nextRetryAt` is included so rows still in backoff are skipped without hitting the heap.await knex.schema.raw(`CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"ON "${TableName.EventOutbox}" ("consumer", "id", "nextRetryAt")diff --git a/backend/src/db/migrations/20260915120000_alert-history-event-id.ts b/backend/src/db/migrations/20260915120000_alert-history-event-id.tsindex 050eaf7e9a..eb63124943 100644--- a/backend/src/db/migrations/20260915120000_alert-history-event-id.ts+++ b/backend/src/db/migrations/20260915120000_alert-history-event-id.ts@@ -5,9 +5,8 @@ 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.+ // Set on event-triggered runs so a retry can skip channels that already delivered. Null on+ // scheduled runs, which dedupe by time window instead.t.string("eventId").nullable();t.index(["alertId", "eventId"]);});diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex 45d537d437..bf26cb3ce3 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -734,8 +734,7 @@ export enum AlertDispatchOutcome {NoRecipients = "no_recipients",// Targets matched, but every one had already been alerted inside the dedup window.AllDeduped = "all_deduped",- // Event path only: the event reached the worker with no alert configured for it. Expected in steady- // state, but a rate of zero everywhere means emits are wired up and alerts are not.+ // Event path only: no alert configured for the event. Normal in steady state.NoMatchingAlert = "no_matching_alert"}@@ -754,8 +753,8 @@ export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string;};// -- Event outbox (InfisicalCore meter) ---------------------------------------------------------------// The outbox's own health, as opposed to what a consumer does with an event. The canonical canary is-// the oldest-pending-age gauge, which lives in event-outbox-queue.ts because the relay tick feeds it.+// Outbox health, not what consumers do with events. The main canary is the oldest-pending-age gauge+// in event-outbox-queue.ts, fed by the relay tick.export const eventOutboxLagHistogram = infisicalCoreMeter.createHistogram("infisical.event_outbox.lag", {description:diff --git a/backend/src/services/alert/alert-dal.test.ts b/backend/src/services/alert/alert-dal.test.tsindex 731e94bc1b..67f069bae7 100644--- a/backend/src/services/alert/alert-dal.test.ts+++ b/backend/src/services/alert/alert-dal.test.ts@@ -125,8 +125,8 @@ describe("alert dal", () => {expect(calls.where).toContainEqual([`${TableName.Alert}.enabled`, true]);});- // An empty result here is terminal for the event, so it must not come from a replica that has yet- // to see the alert commit.+ // An empty result is terminal for the event, so it can't come from a replica that hasn't seen the+ // alert commit yet.test("findEnabledForEvent reads the primary while the scheduled and list lookups keep the replica", async () => {const { dal, getReplicaReads } = buildDAL();@@ -175,8 +175,8 @@ describe("alert dal", () => {expect(calls.orWhereNull).toContainEqual(`${TableName.Alert}.projectId`);});- // An org-level identity can be watched from any project it belongs to, so an event with no project- // of its own has to reach those project-scoped alerts as well as the org-scoped one.+ // An org-level identity can be watched from any of its projects, so an event with no project has to+ // reach those project-scoped alerts too.test("findEnabledForEvent matches every alert bound to the resource when given no project", async () => {const { dal, calls } = buildDAL();diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.tsindex ec398e9079..a1fd27ffd9 100644--- a/backend/src/services/alert/alert-dal.ts+++ b/backend/src/services/alert/alert-dal.ts@@ -42,7 +42,7 @@ export const alertDALFactory = (db: TDbClient) => {}};- // Event path only. Reads the primary: an empty result is terminal for the event, and a replica may+ // Event path only. Reads the primary: an empty result marks the event delivered, and a replica may// not have the alert yet.const findEnabledForEvent = async (filter: {diff --git a/backend/src/services/alert/alert-engine.test.ts b/backend/src/services/alert/alert-engine.test.tsindex 4e1c7d3cfe..a6ff49c8b9 100644--- a/backend/src/services/alert/alert-engine.test.ts+++ b/backend/src/services/alert/alert-engine.test.ts@@ -73,8 +73,7 @@ const makeProvider = (onFindDueTargets?.();return targets;},- // Mirrors a real provider: a target deleted between the event and its delivery drops out rather- // than coming back.+ // Like a real provider, a target deleted between emit and delivery just drops out.findTargetsByIds: async ({ targetIds, payload }) => {onFindTargetsByIds?.(payload);return targets.filter((target) => targetIds.includes(target.id));@@ -549,11 +548,9 @@ describe("alert engine, event path", () => {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]);- // t2 exists but the event didn't name it.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");});@@ -568,8 +565,8 @@ describe("alert engine, event path", () => {expect(historyWrites[0].eventId).toBeUndefined();});- // The whole reason the event path exists: a daily scan rediscovers the same target tomorrow and- // needs dedup, an event doesn't. Reintroduce the dedup lookup here and this fails.+ // A daily scan rediscovers the same target tomorrow and needs dedup. An event doesn't. Reintroduce+ // the dedup lookup on this path and this fails.test("delivers the same target again even though it was just alerted on", async () => {const { engine, sentMail } = buildEngine({targets: [{ id: "t1" }],@@ -595,8 +592,8 @@ describe("alert engine, event path", () => {expect(historyWrites).toHaveLength(0);});- // 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.+ // A retry must not re-notify a channel that already succeeded. The engine works that out from its+ // own history, 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" }],@@ -647,8 +644,8 @@ describe("alert engine, event path", () => {expect(sentMail).toHaveLength(1);});- // The history row is the dedup record and the event path's skip list. Once the channels have sent,- // a retry of the insert is the only lever left that narrows the gap a transient failure opens.+ // The history row is both the dedup record and the event path's skip list. Once channels have sent,+ // retrying the insert is the only thing left that narrows the gap a transient failure opens.test("retries a failed history write and records it on a later attempt", async () => {const { engine, historyWrites, getHistoryAttempts } = buildEngine({targets: [{ id: "t1" }],@@ -663,8 +660,8 @@ describe("alert engine, event path", () => {expect(historyWrites).toHaveLength(1);});- // An empty channel read on the event path marks the event delivered for good, so it must not be- // answered by a replica that has yet to see the channel commit.+ // An empty channel read on the event path marks the event delivered for good, so it can't come from+ // a replica that hasn't seen the channel commit yet.test("reads channels from the primary on the event path and from the replica on the scheduled one", async () => {const { engine, channelLookups } = buildEngine({targets: [{ id: "t1" }],diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.tsindex 32593bc1b6..001b2657ab 100644--- a/backend/src/services/alert/alert-engine.ts+++ b/backend/src/services/alert/alert-engine.ts@@ -194,7 +194,7 @@ export const alertEngineFactory = ({logger.error(`Alert delivery failed on one or more channels [alertId=${alert.id}]: ${errorText}`);}- // Never fails the run: the channels have already sent, and a throw on the event path would re-notify.+ // Never fails the run: channels already sent, and throwing on the event path would re-notify.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 pointdiff --git a/backend/src/services/alert/alert-event-consumer.test.ts b/backend/src/services/alert/alert-event-consumer.test.tsindex 9b5a181ee4..36500b35cd 100644--- a/backend/src/services/alert/alert-event-consumer.test.ts+++ b/backend/src/services/alert/alert-event-consumer.test.ts@@ -98,8 +98,8 @@ describe("alert event consumer", () => {expect(runs[0].payload).toEqual(makePayload());});- // 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.+ // The outbox row id is stable across attempts, so it's 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();@@ -108,8 +108,8 @@ describe("alert event consumer", () => {expect(runs[0].eventId).toBe("42");});- // The alert was deleted or disabled between the gate and the worker, so nobody is owed a- // notification. That's a completed event, not something to retry forever.+ // The alert was deleted or disabled before the worker ran, so nobody is owed a notification. That's+ // done, not something to retry forever.test("marks the event delivered when no alert matches any more", async () => {const { consumer, runs } = buildConsumer({ alerts: [] });@@ -150,8 +150,8 @@ describe("alert event consumer", () => {expect(result.status).toBe(EventResultStatus.Delivered);});- // Marking a mismatched pair delivered would hide the misconfigured emit site. Failing terminally- // with both halves named is what surfaces it.+ // Marking a mismatched pair delivered would hide the broken emit site. Failing terminally and naming+ // both is what surfaces it.test("fails terminally when no provider declares the event for that resource type", async () => {const { consumer, runs, getLookups } = buildConsumer();@@ -164,8 +164,8 @@ describe("alert event consumer", () => {expect(getLookups()).toBe(0);});- // Throwing out of handle() sends the whole batch back for retry, re-notifying on events that already- // delivered, so one event's failure has to stay that event's failure.+ // Throwing out of handle() retries the whole batch and re-notifies events that already delivered, so+ // one event's failure has to stay its own.test("retries only the event whose lookup threw", async () => {let calls = 0;const { consumer, runs } = buildConsumer({@@ -204,8 +204,8 @@ describe("alert event consumer", () => {expect(getLookups()).toBe(1);});- // Events arrive in id order. Handling them concurrently would fan a whole batch of notifications out- // at once and deliver events for one resource out of order.+ // Handling events concurrently would fan a whole batch out at once and deliver one resource's events+ // out of order.test("handles events serially, in the order given", async () => {const { consumer, runs } = buildConsumer();diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.tsindex 06f6345e04..3c78b36873 100644--- a/backend/src/services/alert/alert-event-consumer.ts+++ b/backend/src/services/alert/alert-event-consumer.ts@@ -40,8 +40,8 @@ export const alertEventConsumerFactory = ({}: TAlertEventConsumerDep): IEventConsumer<TAlertEventPayload> => {const subscribesTo = (eventType: string): boolean => alertProviderRegistry.eventTriggeredKeys().has(eventType);- // subscribesTo only sees the event type, so a valid event key on the wrong resourceType gets past it.- // Fail here, terminally and naming both, instead of marking the event delivered as "no matching alert".+ // subscribesTo only sees the event type, so a valid key on the wrong resourceType slips through. Fail+ // terminally here instead of quietly marking it delivered as "no matching alert".const $isDeclaredEvent = (eventType: string, resourceType: string): boolean =>Boolean(alertProviderRegistrydiff --git a/backend/src/services/alert/alert-history-dal.test.ts b/backend/src/services/alert/alert-history-dal.test.tsindex c7b925b2b9..e5e5d8e1ff 100644--- a/backend/src/services/alert/alert-history-dal.test.ts+++ b/backend/src/services/alert/alert-history-dal.test.ts@@ -78,8 +78,8 @@ 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.+ // The skip list is per channel and only counts successes: a failed channel gets retried, and one+ // channel's success doesn't suppress another.test("findDeliveredChannelIdsForEvent scopes to the alert and event and only counts successes", async () => {const { dal, whereCalls } = buildDAL();diff --git a/backend/src/services/alert/alert-provider-registry.test.ts b/backend/src/services/alert/alert-provider-registry.test.tsindex 7f2ef49abd..55f50534c1 100644--- a/backend/src/services/alert/alert-provider-registry.test.ts+++ b/backend/src/services/alert/alert-provider-registry.test.ts@@ -23,8 +23,7 @@ describe("alert provider registry", () => {expect(() => registry.register(baseProvider({}))).toThrow("already registered");});- // Both guards fail the boot in routes/index.ts, rather than letting a dispatch silently no-op in- // production.+ // Both guards fail boot in routes/index.ts rather than letting a dispatch silently no-op in prod.test("rejects a scheduled event with no findDueTargets", () => {const registry = alertProviderRegistryFactory();diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex 5d7d057335..e73d72a16c 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -274,8 +274,8 @@ describe("alert service", () => {);});- // triggerType comes from the provider's event definition, never from the request, so an alert on an- // event-triggered key is invisible to the daily scan and reachable only from an event.+ // triggerType comes from the provider's event definition, never the request. That's what keeps+ // event-triggered alerts out of the daily scan.test("stores the trigger type its event declares", async () => {const { service, alerts } = buildService();@@ -314,8 +314,6 @@ describe("alert service", () => {test("validates the condition against the event's own schema, not a provider-wide one", async () => {const { service } = buildService();- // The event-triggered event takes no condition, so the expiry shape is rejected for it and- // an empty one is accepted.await expect(service.createAlert({ ...validCreate, eventType: "test.resource.opened", condition: { alertBefore: "30d" } })).rejects.toThrow(/Invalid alert condition/);diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex b730cee858..3f66d795b1 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -93,7 +93,7 @@ export type TFindDueTargetsInput = {asOf: Date;};-// So a provider factory can declare which discovery method it guarantees.+// Lets a provider factory declare which discovery method it guarantees.export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &Required<Pick<IResourceAlertProvider<TTarget>, "findDueTargets">>;@@ -103,7 +103,7 @@ export type IEventAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarexport interface IResourceAlertProvider<TTarget = unknown> {// Dot-namespaced, e.g. "pki.certificate", "identity.ua-secret".resourceType: string;- // Event keys this provider understands, each declaring how it fires and what its condition looks like.+ // Each event declares how it fires and what its condition looks like.events: TAlertEventDefinition[];// Resources currently due to alert for this alert's scope + condition. The engine handles dedup@@ -114,10 +114,10 @@ export interface IResourceAlertProvider<TTarget = unknown> {// Required for any Scheduled event; the registry enforces that at boot.findDueTargets?(input: TFindDueTargetsInput): Promise<TTarget[]>;- // Rehydrates the targets an event named. A missing row was deleted between emit and dispatch, so it's- // dropped, not an error. Must read the primary: the target usually commits in the same transaction as- // the event, and an empty result is terminal for it.- // Required for any Event event; the registry enforces that at boot.+ // Loads the targets an event named. A missing row was deleted between emit and dispatch, so drop it,+ // don't throw. Must read the primary: the target usually commits in the same tx as the event, and an+ // empty result is terminal.+ // Required for any Event-triggered event; the registry enforces that at boot.findTargetsByIds?(input: TFindTargetsByIdsInput): Promise<TTarget[]>;// Deep link to the alert's resource, honouring its scope (org- vs project-scoped). Resolved oncediff --git a/backend/src/services/alert/providers/identity-credential-alert-provider.test.ts b/backend/src/services/alert/providers/identity-credential-alert-provider.test.tsindex a048ed59c7..7cf1cbae46 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@@ -148,8 +148,8 @@ describe("identity credential alert provider", () => {expect(schema.safeParse({}).success).toBe(true);});- // The auth method services emit through this helper and the provider parses the schema at delivery.- // This is the one place the two are checked against each other.+ // Auth method services emit through this helper and the provider parses at delivery. This is the one+ // place the two get checked against each other.test("the emitted payload is accepted by the delivery schema", async () => {const emitted: unknown[] = [];const emitter = { emit: async (event: { payload: unknown }) => void emitted.push(event.payload) };@@ -326,7 +326,6 @@ describe("identity credential alert provider", () => {"https://app.infisical.com/x");expect(payload.summary).toBe("Token Auth token 'deploy' was revoked from machine identity 'ci-runner'");- // No credential field when the change is to the method itself.const methodOnly = provider.buildPayload(context,[diff --git a/backend/src/services/event-outbox/event-outbox-dal.test.ts b/backend/src/services/event-outbox/event-outbox-dal.test.tsindex 21ab6b6228..102c417f64 100644--- a/backend/src/services/event-outbox/event-outbox-dal.test.ts+++ b/backend/src/services/event-outbox/event-outbox-dal.test.ts@@ -3,9 +3,8 @@ import { TableName } from "@app/db/schemas";import { eventOutboxDALFactory } from "./event-outbox-dal";import { EventOutboxStatus } from "./event-outbox-types";-// These assert query *shape*, in the style of alert-dal.test.ts. Only a real database can show that-// two claimers never take the same row, so what a unit test protects is that the clauses buying that-// guarantee are still there.+// These assert query shape only. Real Postgres coverage lives in e2e-test/event-outbox.spec.ts; what+// these protect is that the clauses buying those guarantees are still there.const buildDAL = (opts?: { returning?: unknown[]; updated?: number; selected?: unknown[] }) => {const calls = {where: [] as unknown[][],@@ -23,8 +22,8 @@ const buildDAL = (opts?: { returning?: unknown[]; updated?: number; selected?: ugroupBy: [] as unknown[][]};- // knex resolves an UPDATE to the affected row count and a SELECT to rows, and commitResults reads- // that count, so the mock has to answer each with the right shape.+ // knex resolves an UPDATE to a row count and a SELECT to rows, so the mock has to answer each with+ // the right shape.let lastOp: "select" | "update" = "select";const chain: Record<string, unknown> = {};@@ -110,9 +109,8 @@ const buildDAL = (opts?: { returning?: unknown[]; updated?: number; selected?: u};describe("event outbox dal", () => {- // The conflict target repeats the index predicate because Postgres can't infer a *partial* unique- // index from a bare column list: a plain ON CONFLICT (consumer, idempotencyKey) is a 42P10 at- // runtime.+ // Postgres can't infer a partial unique index from a bare column list, so the conflict target has to+ // repeat the predicate or it's a 42P10 at runtime.test("insertEvents ignores a conflict on the partial idempotency index", async () => {const { dal, calls, tx } = buildDAL();@@ -140,8 +138,8 @@ describe("event outbox dal", () => {expect(calls.insert).toHaveLength(0);});- // SKIP LOCKED is what makes concurrent relays correct by construction, and so the reason the relay- // doesn't need the cron manager's fleet-wide exactly-once scheduling.+ // SKIP LOCKED is what makes concurrent relays safe, and why the relay doesn't need the cron manager's+ // fleet-wide exactly-once scheduling.test("claimBatch locks rows with FOR UPDATE SKIP LOCKED", async () => {const { dal, calls } = buildDAL();@@ -159,8 +157,8 @@ describe("event outbox dal", () => {expect(calls.orderBy[0]).toEqual(["id", "asc"]);});- // RETURNING hands rows back in whatever order the UPDATE touched them, while handle() is promised id- // order. Seen for real against Postgres: a 3-row claim came back 8, 7, 6.+ // RETURNING comes back in whatever order the UPDATE touched rows. Seen for real: a 3-row claim came+ // back 8, 7, 6.test("claimBatch returns the claimed rows in id order regardless of how RETURNING ordered them", async () => {const { dal } = buildDAL({ returning: [{ id: "8" }, { id: "6" }, { id: "10" }, { id: "7" }] });@@ -179,8 +177,7 @@ describe("event outbox dal", () => {expect(calls.update[0].lockedAt).toBe("NOW()");});- // Every later statement about these rows carries the token, so it has to be the one stamped on the- // rows and it has to differ per claim.+ // Every later statement on these rows fences on the token, so it has to differ per claim.test("claimBatch stamps a fresh lockToken and hands it back", async () => {const { dal, calls } = buildDAL();const key = { consumer: "alert" };@@ -193,8 +190,8 @@ describe("event outbox dal", () => {expect(second.lockToken).not.toBe(first.lockToken);});- // A row the sweeper already handed back must not be pulled into 'processing' again by a late- // heartbeat, and a heartbeat must never refresh a claim another worker now holds.+ // A late heartbeat must not drag a recycled row back into 'processing' or refresh a claim another+ // worker now holds.test("extendClaims refreshes lockedAt only on rows this claim still holds", async () => {const { dal, calls } = buildDAL();@@ -288,9 +285,8 @@ 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, and 'processing' alone doesn't tell the two claims apart: the new owner's rows are- // 'processing' too. The token is what keeps the late result off them.+ // By the time the original worker reports, the sweeper may have handed its rows to another worker,+ // and that claim is 'processing' too. The token is what keeps the late result off them.test("commitResults only touches rows still held by this exact claim", async () => {const { dal, calls } = buildDAL();@@ -308,7 +304,6 @@ describe("event outbox dal", () => {expect(calls.where.filter((args) => args[0] === "lockToken" && args[1] === "token-1")).toHaveLength(3);});- // What the service reads to tell a settled claim from one that was taken away mid-delivery.test("commitResults reports how many rows it settled", async () => {const { dal } = buildDAL({ updated: 2 });@@ -322,8 +317,8 @@ describe("event outbox dal", () => {).resolves.toBe(2);});- // The rows go back to whoever claims them next, so leaving the old owner's token on them would let a- // heartbeat that arrives even later keep refreshing a claim nobody holds.+ // Leaving the old token on recycled rows would let an even later heartbeat keep refreshing a claim+ // nobody holds.test("recoverStaleClaims clears the token along with the claim", async () => {const { dal, calls } = buildDAL({selected: [@@ -349,8 +344,8 @@ describe("event outbox dal", () => {expect(calls.andWhereRaw[0][1]).toEqual([600_000]);});- // The transaction bounds itself rather than trusting worker concurrency to keep `processing` small,- // and takes the oldest claims first so a limit never starves one.+ // Bounded so a big 'processing' backlog can't blow up one transaction, oldest first so the limit+ // never starves a claim.test("recoverStaleClaims recovers a bounded batch, oldest claim first", 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.tsindex 025e2405b9..b8f498b96d 100644--- a/backend/src/services/event-outbox/event-outbox-dal.ts+++ b/backend/src/services/event-outbox/event-outbox-dal.ts@@ -59,9 +59,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {}};- // One statement on purpose: the row locks live only as long as the UPDATE. The claim also stamps a- // fresh lockToken, which is what lets extendClaims and commitResults tell this claim apart from a- // later one over the same rows.+ // One statement on purpose so the row locks only live as long as the UPDATE. The fresh lockToken is+ // how extendClaims and commitResults tell this claim apart from a later one on the same rows.const claimBatch = async (key: TOutboxFlushKey, limit: number): Promise<TOutboxClaim> => {const lockToken = crypto.randomUUID();try {@@ -89,9 +88,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {}};- // A batch that outlives the stale threshold has to keep lockedAt fresh or the sweeper hands its rows- // to another worker mid-delivery. Scoped to the caller's own claim, so a heartbeat that comes back- // after the sweeper recycled these rows can't refresh the new owner's lock.+ // Keeps lockedAt fresh so the sweeper doesn't hand a slow batch to another worker mid-delivery.+ // Scoped to this claim's token so a late heartbeat can't refresh a lock someone else now holds.const extendClaims = async (ids: string[], lockToken: string): Promise<void> => {if (ids.length === 0) return;try {@@ -105,8 +103,8 @@ export const eventOutboxDALFactory = (db: TDbClient) => {}};- // Returns how many rows were settled, which is short of what the caller claimed when the claim was- // recycled mid-delivery and the rows now belong to another worker.+ // Returns the settled count. It comes up short when the sweeper recycled the claim mid-delivery and+ // another worker now owns the rows.const commitResults = async (input: {lockToken: string;delivered: { ids: string[] }[];diff --git a/backend/src/services/event-outbox/event-outbox-queue.test.ts b/backend/src/services/event-outbox/event-outbox-queue.test.tsindex 36fadfb1cf..697b7687cd 100644--- a/backend/src/services/event-outbox/event-outbox-queue.test.ts+++ b/backend/src/services/event-outbox/event-outbox-queue.test.ts@@ -108,8 +108,8 @@ describe("event outbox relay", () => {expect(queued[0].data).toEqual(KEY);});- // One flush per consumer at a time is what keeps drain's batches serial, and it dedupes a consumer- // the relay rediscovers while its flush is still queued.+ // One flush per consumer at a time keeps drain's batches serial and dedupes a consumer the relay+ // rediscovers while its flush is still queued.test("keys the job per consumer so two flushes for one consumer cannot overlap", async () => {const { factory, queued } = buildQueue({ keys: [KEY] });@@ -136,8 +136,8 @@ describe("event outbox relay", () => {expect(queued).toHaveLength(0);});- // Every other cron in the codebase sits behind this flag, and the docs promise a secondary region- // runs no background jobs beyond audit logs.+ // Every other cron sits behind this flag, and the docs promise a secondary region runs no+ // background jobs beyond audit logs.test("registers its crons disabled and never starts the relay on a secondary instance", async () => {vi.useFakeTimers();config.isSecondaryInstance = true;@@ -165,7 +165,7 @@ 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+ // The flush job is removeOnFail with one attempt, so without the log 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");diff --git a/backend/src/services/event-outbox/event-outbox-service.test.ts b/backend/src/services/event-outbox/event-outbox-service.test.tsindex 8a4c58e1bc..a1da7088fb 100644--- a/backend/src/services/event-outbox/event-outbox-service.test.ts+++ b/backend/src/services/event-outbox/event-outbox-service.test.ts@@ -52,8 +52,8 @@ const makeConsumer = (overrides?: Partial<IEventConsumer>): IEventConsumer =>...overrides}) as IEventConsumer;-// `tx` is a sentinel: emit has to thread the caller's transaction through untouched, since a call-// that silently opens its own connection is how the pool deadlocks.+// Sentinel: emit has to pass the caller's tx through untouched. Silently opening a second connection+// is how the pool deadlocks.const TX = { sentinel: true } as never;const buildService = (consumers: IEventConsumer[]) => {@@ -105,8 +105,8 @@ describe("event outbox emit", () => {expect(inserted[0].tx).toBe(TX);});- // A payload the consumer can't read means a statically wrong emit site, and failing loudly beats- // dropping a notification over a misspelled field.+ // An unreadable payload means a wrong emit site. Failing loudly beats dropping a notification over a+ // misspelled field.test("throws when the payload does not match the consumer's schema", async () => {const { service, inserted } = buildService([makeConsumer()]);@@ -233,7 +233,6 @@ describe("event outbox drain", () => {expect(commits[0].delivered).toEqual([{ ids: ["1"] }]);});- // A consumer that throws must not lose the batch: every row goes back for another attempt.test("retries the whole batch when the consumer throws", async () => {const { service, commits } = buildDrain({batches: [[makeRow()]],@@ -248,8 +247,8 @@ describe("event outbox drain", () => {expect(commits[0].delivered).toEqual([]);});- // Otherwise a consumer that quietly returns nothing would leave rows stuck in 'processing' until- // the stale-claim sweeper noticed, which looks identical to a crashed worker.+ // Otherwise rows the consumer forgot would sit in 'processing' until the sweeper noticed, looking+ // exactly like a crashed worker.test("retries a row the consumer returned no result for", async () => {const { service, commits } = buildDrain({ batches: [[makeRow()]], handle: async () => [] });@@ -271,8 +270,8 @@ describe("event outbox drain", () => {expect(commits[0].retriable).toEqual([]);});- // One UPDATE per distinct outcome, not one per row, so a batch of a hundred deliveries is a single- // statement. Rows on the same attempt share a retry delay, so they group too.+ // One UPDATE per distinct outcome, so a hundred deliveries is one statement. Rows on the same attempt+ // share a retry delay, so they group too.test("groups rows that share an outcome into one commit entry", async () => {const { service, commits } = buildDrain({batches: [[makeRow({ id: 1 }), makeRow({ id: 2 }), makeRow({ id: 3 }), makeRow({ id: 4 })]],@@ -292,8 +291,8 @@ describe("event outbox drain", () => {expect(commits[0].retriable[0].error).toBe("slack 502");});- // 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.+ // commitResults fences on the claim token. Reporting under a different one would write to whatever+ // worker holds the rows now.test("commits under the token the batch was claimed with", async () => {const { service, commits, claimTokens } = buildDrain({batches: [[makeRow()]],@@ -305,8 +304,8 @@ describe("event outbox drain", () => {expect((commits[0] as unknown as { lockToken: string }).lockToken).toBe(claimTokens[0]);});- // A short settle means the sweeper handed these rows to another worker while this one was still- // delivering, so the batch went out twice. Nothing else in the system can see that happened.+ // A short settle means the sweeper handed the rows to another worker mid-delivery, so the batch went+ // out twice. This log is the only place that shows up.test("reports a claim that was taken away mid-delivery", async () => {loggerWarn.mockClear();const { service } = buildDrain({@@ -333,8 +332,8 @@ describe("event outbox drain", () => {expect(loggerWarn).not.toHaveBeenCalled();});- // A batch that legitimately outlives the sweeper's threshold (a slow webhook, many rows) has to- // keep its claim fresh, or the sweeper hands its rows to a second worker mid-delivery.+ // A slow batch (slow webhook, many rows) has to keep its claim fresh or the sweeper hands it to a+ // second worker mid-delivery.test("extends the claim while the consumer is still handling a batch", async () => {vi.useFakeTimers();try {@@ -372,8 +371,8 @@ describe("event outbox drain", () => {expect(commits).toHaveLength(0);});- // By this point the consumer has already sent. Letting a transient commit failure escape would leave- // the rows to the stale sweeper and re-notify ten minutes later, so the commit itself is retried.+ // The consumer already sent by now. Letting a transient commit failure escape would leave the rows+ // to the sweeper and re-notify ten minutes later.test("retries a failed commit before giving up on it", async () => {vi.useFakeTimers();try {@@ -466,8 +465,8 @@ describe("event outbox stale sweep", () => {exhaustedMetrics.length = 0;});- // A row the sweeper gives up on is as lost as one a consumer gives up on. Without this the metric- // that promises to count every abandoned notification misses the ones caused by dead workers.+ // A row the sweeper gives up on is just as lost as one a consumer gives up on, and the exhausted+ // metric promises to count every one.test("counts events the sweeper gives up on, per consumer, on the exhausted metric", async () => {const { service } = buildSweep([{diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.tsindex 849c1b6105..cba2df809b 100644--- a/backend/src/services/event-outbox/event-outbox-service.ts+++ b/backend/src/services/event-outbox/event-outbox-service.ts@@ -31,7 +31,7 @@ const PRUNE_MAX_BATCHES = 20;const STALE_SWEEP_BATCH_SIZE = 1_000;const STALE_SWEEP_MAX_BATCHES = 10;-// A quarter of the threshold, so one missed beat doesn't let the sweeper call a live claim stale.+// A quarter of the threshold so one missed beat doesn't get a live claim swept.const CLAIM_HEARTBEAT_INTERVAL_MS = STALE_CLAIM_THRESHOLD_MS / 4;const COMMIT_ATTEMPTS = 3;@@ -72,9 +72,9 @@ export type TEventOutboxServiceFactoryDep = {export type TEventOutboxServiceFactory = ReturnType<typeof eventOutboxServiceFactory>;export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry }: TEventOutboxServiceFactoryDep) => {- // `tx` is required on purpose: the row has to commit with the business write. Nothing here reads the- // DB or calls into a consumer, and nothing is caught: a bad event is a bug at the emit site (so 500,- // not 400), and swallowing a failed insert would leave the caller with a poisoned transaction.+ // `tx` is required so the row commits with the business write. Nothing is caught on purpose: a bad+ // event is a bug at the emit site (500, not 400), and swallowing a failed insert would leave the+ // caller with a poisoned transaction.const emit = async (event: TEventInput, tx: Knex): Promise<void> => {const parsed = EventInputSchema.safeParse(event);if (!parsed.success) {diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.tsindex 6820ef0545..c846044117 100644--- a/backend/src/services/event-outbox/event-outbox-types.ts+++ b/backend/src/services/event-outbox/event-outbox-types.ts@@ -61,7 +61,7 @@ export type TEventEmitter = {emit: (event: TEventInput, tx: Knex) => Promise<void>;};-// What a consumer sees. Lock, attempt, and status columns are the outbox's business, not the consumer's.+// What a consumer sees. Lock, attempt and status columns are the outbox's business.export type TEvent = Pick<TEventOutbox, "id" | "eventType" | "payload" | "occurredAt">;export enum EventResultStatus {@@ -92,7 +92,7 @@ export interface IEventConsumer<TPayload = unknown> {// wants the event is decided later, in handle().subscribesTo(eventType: string): boolean;- // Due events for this consumer, oldest first by id. One flush runs per consumer at a time, so- // within a flush a batch is ordered; across flushes nothing is promised. Must return one result per event.+ // Events arrive oldest first by id and one flush runs per consumer at a time, so a batch is ordered+ // but nothing is promised across flushes. Must return one result per event.handle(events: TEvent[]): Promise<TEventConsumerResult[]>;}