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 Silva5c6a4f231d9e
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 846000f5b6..af77e01f92 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -622,9 +622,9 @@ That's it — CRUD routes, channel creation/rotation, recipient resolution, KMS`alertProviderRegistry.register` asserts that pairing at boot, so a provider that declares an event trigger without `findTargetsByIds` fails the process rather than silently no-op'ing in production. `triggerType` is derived from the provider's event definition inside `createAlert` and is never accepted from a request.-**Every read on the event path goes to the primary, and `findTargetsByIds` must too.** An empty read there is terminal: "no matching alert", "no channels" and "targets gone" all mark the event delivered and nothing ever asks again, so a replica that has not caught up with a commit loses the notification outright. `findEnabledForEvent` and the engine's channel lookup (`readFromPrimary: true`) already do this; a provider's `findTargetsByIds` has to as well, because the target usually commits in the same transaction as the event that names it and the engine cannot tell "not replicated yet" from "deleted". The scheduled path keeps the replica because tomorrow's scan asks again. These reads run once per batch in the worker and are indexed point lookups, so the primary costs nothing measurable.+**Event-path reads go to the primary, `findTargetsByIds` included.** An empty read there is terminal (the event is marked delivered and never asked about again), so a replica that hasn't seen the commit loses the notification. `findEnabledForEvent` and the engine's channel lookup already do this; a provider's `findTargetsByIds` must too, since the target usually commits in the same transaction as the event. The scheduled path keeps the replica because tomorrow's scan asks again.-**The history write is retried, then logged, never thrown.** By the time `createWithTargets` runs, the channels have delivered, so a throw cannot undo anything: on the event path it would re-notify on retry, and on the scheduled path it only fails the job while leaving the same dedup gap behind. A few in-process attempts are the only lever that actually narrows the gap; after that it is a `logger.error` and the run reports its delivery outcome.+**The history write is retried, then logged, never thrown.** The channels have already sent by then, so a throw can't undo anything and would re-notify on the event path.Invariants worth knowing before extending it:@@ -640,17 +640,13 @@ Invariants worth knowing before extending it:### Event Outbox (transactional and generic; alerting is its first consumer)-`src/services/event-outbox/` records "this happened" as a row written **inside the caller's own-transaction**, so an event is exactly as durable as the business write that produced it. Redis cannot-participate in a Postgres commit, so enqueueing after commit instead loses the event whenever the pod-dies or Redis is unreachable in that window, with nothing but a log line to show for it.+`src/services/event-outbox/` writes "this happened" as a row inside the caller's own transaction, so+an event is exactly as durable as the business write. Enqueueing to Redis after commit loses the event+whenever the pod dies or Redis is down in that window. It's not alert-specific:+`alert-event-consumer.ts` is one consumer on the shared registry, and anything else that needs+at-least-once delivery of a domain event registers next to it.-It is deliberately **not** alert-specific. `src/services/alert/alert-event-consumer.ts` is one consumer-on the shared registry; anything else needing at-least-once delivery of a domain event registers-alongside it.--**To emit:** `eventOutboxService.emit(event, tx)`. `tx` is required, not optional: that is the whole-point, and there is deliberately no weaker path to reach for.+**Emitting:** `eventOutboxService.emit(event, tx)`. `tx` is required on purpose.```tsawait someDAL.transaction(async (tx) => {@@ -669,95 +665,53 @@ await someDAL.transaction(async (tx) => {});```-**Only `subscribesTo(eventType)` is consulted before a row is written**, a pure in-memory check for-"is this event type handled at all". Whether a customer configured anything for *this* resource is-settled later, in the worker, so `emit` adds exactly one statement to the caller's transaction and-never calls back into a consumer. The cost is a throwaway row when nobody was listening, which `handle`-marks `Delivered` and the prune reaps within the day. If a high-volume event type ever makes that-amplification matter, cache the answer *inside the consumer* rather than adding a read to the emit path.--**Nothing in `emit` is caught.** A swallowed insert failure would hand the caller a poisoned-transaction (`25P02` on its next statement) instead of the real error, and a row that cannot be written-means the operation did not happen. A payload that fails its consumer's `payloadSchema` throws too:-that emit site is statically wrong and fails on the first request in dev, which beats dropping a-notification over a misspelled field. Both checks run before any database access, so neither can poison-the transaction.--**The row owns the retry state machine** (`attempts`, `nextRetryAt`, backoff, terminal `failed`) and the-outbox owns the lag and exhausted metrics. `consumer.handle` owns delivery and what "delivered" means,-reporting per row: `Delivered` / `Retry` / `Failed` plus `progress`. Backoff is exponential with jitter-from a 30s base, and `MAX_OUTBOX_ATTEMPTS` is sized so the last attempt lands about an hour after the-first: a `failed` row is a notification the customer never receives and nothing replays it, so the-horizon has to outlast a realistic outage of the endpoint being delivered to. The stale sweeper applies-the same backoff rather than handing rows straight back, so a consumer that hangs every time cannot hold-a worker slot for the full threshold on repeat. To replay `failed` rows by hand, flip them to-`status = 'retry', attempts = 0, nextRetryAt = now()`; the next relay tick picks them up.--**A claim is a lease, and `drain` keeps it alive.** The sweeper treats any `processing` row whose-`lockedAt` is older than `STALE_CLAIM_THRESHOLD_MS` as a dead worker and hands it back out. A batch can-legitimately outlive that (one slow webhook endpoint timing out on every row of a resource), so `drain`-refreshes `lockedAt` on the claimed ids every quarter of the threshold while `handle` runs. Without it-the sweeper re-queues rows a live worker is still delivering and the customer is notified twice.--**Discovery is scoped to the consumers this process has registered.** `findDueFlushKeys` takes-`eventOutboxRegistry.names()`, and that filter is load-bearing: rows for a name nobody here can drain (a-renamed consumer, a rolling deploy) stay `pending` forever, are never pruned, and sort first on every-tick, so without it they would fill the discovery limit and hide every real key behind them. They now-wait harmlessly and show up on the oldest-pending gauge instead.--**A consumer must not let one row's failure escape `handle`.** The outbox retries the whole batch when-`handle` throws, because it cannot know which rows already delivered. A consumer that processes rows one-at a time catches per row and reports `Retry` for that row alone; see `alert-event-consumer.ts`. The-batch-level catch in `drain` is the backstop, not the plan.--**BullMQ owns latency here, never correctness.** `attempts: 1` on the flush job is intentional: retry-lives on the outbox row, where an operator can query it and where it survives a Redis flush. A failed-enqueue leaves the row `pending` for the next relay tick, so a lost job costs one interval.--**The relay is a `setInterval`, not a cron registration**, which bends the rule above that all recurring-work goes through the cron manager. That rule exists to prevent duplicate execution, which the cron-manager buys with slot election plus redlocks. This relay does not need exactly-once, because-`claimBatch`'s `FOR UPDATE SKIP LOCKED` plus the flush `jobId` make concurrent pollers correct by-construction. What it does need is a sub-minute cadence, and the cron manager's floor is sixty seconds.-Every pod polling is the shape the outbox pattern assumes.--**Ordering is per resource, and the claim must sort by `id`.** The flush `jobId` is keyed on-`(consumer, resourceType, resourceId)`, so at most one flush per aggregate runs at a time: never-parallelize publishing within one aggregate, even though `SKIP LOCKED` makes it safe across different-ones. Within a claim, `nextRetryAt` is a *filter*, not a sort key. A fresh row's `nextRetryAt` is its-insert time, so it sorts ahead of a retried row's future one and a later event overtakes an earlier one-that happened to fail once. `event_outbox_drain_idx` is shaped-`(consumer, resourceType, resourceId, id, nextRetryAt)` so the id ordering comes from the index with no-sort node.--One gap remains by choice: a row inside its backoff window is not eligible, so a later row for the same-resource can be delivered first. Closing it would mean blocking the whole aggregate behind its oldest-undelivered row, trading a rare reorder for one failing event stalling everything behind it. For-notifications that is the wrong trade, so do not promise callers strict ordering.--**Delivery is at-least-once.** A send that succeeds and whose `commitResults` then fails is redelivered.-The commit is retried a few times in-process first, since by then the consumer has already sent and the-alternative is the sweeper re-notifying ten minutes later. Consumers narrow what is left with `progress`-(alerting stores the channels that already succeeded and skips them on the retry), and an emitter that-needs to dedupe its own retries passes an `idempotencyKey`.--**`claimBatch` sorts what `RETURNING` gives it.** The subquery picks rows in id order, but-`UPDATE ... RETURNING` hands them back in whatever order it touched them (seen for real: 8, 7, 6), and-`handle` is promised id order. The `e2e-test/event-outbox.spec.ts` suite runs these queries against-Postgres because that is the only place this class of bug shows up.--**Watch `infisical.event_outbox.oldest_pending_age`.** It is the canonical canary, the one signal that-catches a dead relay, a wedged consumer and a stuck claim alike. Alarm when it exceeds a small multiple-of the relay interval. `infisical.event_outbox.lag` and `infisical.event_outbox.exhausted.count` are-recorded by the outbox itself as it commits results, labelled by consumer, so a new consumer gets them-without writing any telemetry code.--**Adding an event-triggered alert** needs no outbox code at all. The provider declares the event with-`triggerType: AlertTriggerType.Event` and implements `findTargetsByIds`; the emitter calls-`eventOutbox.emit` with `resourceType` equal to the provider's and `payload: { targetIds }`. When the-emitted `resourceType` does not declare that `eventType`, the alert consumer fails the row terminally-with both halves named, so a mismatched emit site shows up in the logs on its first event rather than-being marked delivered as "no matching alert".+- Only `subscribesTo(eventType)` runs before the insert, in memory. Whether a customer configured+ anything for this resource is decided in the worker; a row nobody wanted is marked `Delivered` and+ pruned within a day. If that ever matters for a hot event type, cache inside the consumer rather than+ adding a read to the emit path.+- Nothing is caught. A swallowed insert failure hands the caller a poisoned transaction (`25P02` on its+ next statement), and a payload that fails the consumer's `payloadSchema` is a bug at the emit site.+ Both checks run before any DB access.++**How delivery works:**++- **The row owns retry state** (`attempts`, `nextRetryAt`, backoff, terminal `failed`); the consumer+ owns what "delivered" means and reports `Delivered` / `Retry` / `Failed` plus `progress` per row.+ Backoff is exponential with jitter from 30s, and `MAX_OUTBOX_ATTEMPTS` puts the last attempt about an+ hour after the first, because a `failed` row is a notification nobody will receive. To replay failed+ rows by hand: `status = 'retry', attempts = 0, nextRetryAt = now()`.+- **A claim is a lease.** The sweeper hands back any `processing` row whose `lockedAt` is older than+ `STALE_CLAIM_THRESHOLD_MS`, with the same backoff as a normal failure, and counts exhausted rows on the+ same metric. `drain` refreshes `lockedAt` while `handle` runs so a slow batch isn't delivered twice.+- **Discovery only looks at consumers registered in this process.** Rows for any other name would sort+ first forever and, past the limit, hide every real key. They wait and show up on the oldest-pending+ gauge instead.+- **Don't let one row's failure escape `handle`.** The outbox retries the whole batch when `handle`+ throws. Catch per row and report `Retry` for that row alone (see `alert-event-consumer.ts`).+- **BullMQ owns latency, not correctness.** `attempts: 1` on the flush job is intentional; retry lives+ on the row. A lost job costs one relay interval.+- **The relay is a `setInterval`, not a cron job.** It doesn't need exactly-once (`FOR UPDATE SKIP+ LOCKED` plus the flush `jobId` make concurrent pollers safe) and it needs a sub-minute cadence the+ cron manager can't give.+- **Ordering is per resource and best-effort.** The flush `jobId` is keyed on+ `(consumer, resourceType, resourceId)` so one flush per aggregate runs at a time, and `claimBatch`+ sorts by `id` (re-sorting what `RETURNING` gives back, which is arbitrary). A row inside its backoff+ window is skipped, so a later row can overtake it. That's deliberate: blocking an aggregate behind its+ oldest failing row is the wrong trade for notifications. Don't promise strict ordering.+- **Delivery is at-least-once.** `commitResults` is retried in-process, since by then the consumer has+ already sent; what's left is narrowed by `progress` and by the emitter's `idempotencyKey`.++**Watch `infisical.event_outbox.oldest_pending_age`.** It catches a dead relay, a wedged consumer and a+stuck claim alike. `lag` and `exhausted.count` are recorded by the outbox, labelled by consumer, so a+new consumer gets them for free.++**Adding an event-triggered alert** needs no outbox code: declare the event with+`triggerType: AlertTriggerType.Event`, implement `findTargetsByIds`, and emit with the provider's+`resourceType` and `payload: { targetIds }`. A `resourceType` that doesn't declare the `eventType` fails+the row terminally with both named, so a bad emit site shows up in the logs on its first event.++The DAL is covered by `e2e-test/event-outbox.spec.ts` against real Postgres; the unit tests only check+query shape.### Soft-Delete + Async Cleanupdiff --git a/backend/src/db/migrations/20260908000000_event-outbox.ts b/backend/src/db/migrations/20260908000000_event-outbox.tsindex f1e1a433cc..2300ad85f5 100644--- a/backend/src/db/migrations/20260908000000_event-outbox.ts+++ b/backend/src/db/migrations/20260908000000_event-outbox.ts@@ -29,9 +29,8 @@ export async function up(knex: Knex): Promise<void> {t.timestamps(true, true, true);});- // Backs both the relay's discovery query and the per-resource claim. `id` comes before- // `nextRetryAt` so the claim's ORDER BY needs no sort node, and discovery's MIN() still gets- // answered from the index.+ // Backs discovery and the per-resource claim. `id` before `nextRetryAt` so the claim's ORDER BY+ // needs no sort node.await knex.schema.raw(`CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"ON "${TableName.EventOutbox}" ("consumer", "resourceType", "resourceId", "id", "nextRetryAt")@@ -44,9 +43,7 @@ export async function up(knex: Knex): Promise<void> {WHERE status = 'processing'`);- // Backs the oldest-pending health gauge, which runs on every relay tick forever. Without it the- // gauge seq-scans the whole table for a handful of rows, at a cost that tracks the delivered- // backlog rather than the work outstanding.+ // Backs the oldest-pending gauge, which runs on every relay tick; without it that's a seq scan.await knex.schema.raw(`CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_undelivered_idx"ON "${TableName.EventOutbox}" ("consumer", "occurredAt")diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.tsindex bc02fe4306..2b02847cba 100644--- a/backend/src/services/alert/alert-dal.ts+++ b/backend/src/services/alert/alert-dal.ts@@ -42,8 +42,8 @@ export const alertDALFactory = (db: TDbClient) => {}};- // The event path's counterpart to findEnabledByResourceType, narrowed to one resource and one- // event key. Runs in the outbox worker only; the emit path never touches the alerts table.+ // Event path only. Reads the primary: an empty result is terminal for the event, and a replica may+ // not have the alert yet.const findEnabledForEvent = async (filter: {orgId: string;@@ -78,8 +78,7 @@ export const alertDALFactory = (db: TDbClient) => {.where(`${TableName.AlertChannel}.enabled`, true));- // A resource in a project can be watched by a project-scoped alert and by an org-wide one, so- // both are in scope; without a projectId only the org-scoped row can match.+ // A project resource can be watched by a project-scoped alert and by an org-wide one.if (filter.projectId) {void query.where((builder) =>diff --git a/backend/src/services/alert/alert-engine.ts b/backend/src/services/alert/alert-engine.tsindex 4f1ae23289..cda19715d3 100644--- a/backend/src/services/alert/alert-engine.ts+++ b/backend/src/services/alert/alert-engine.ts@@ -195,8 +195,7 @@ export const alertEngineFactory = ({logger.error(`Alert delivery failed on one or more channels [alertId=${alert.id}]: ${errorText}`);}- // Deliberately not allowed to fail the run: the event path may retry, and a throw after channels- // have already sent would re-notify.+ // Never fails the run: the channels have already sent, and a throw 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 point@@ -298,6 +297,7 @@ export const alertEngineFactory = ({}const skip = new Set(input.skipChannelIds ?? []);+ // Primary: an empty read here is terminal for the event, and a replica may not have the channel yet.const channels = (await alertChannelDAL.findByAlertId(alert.id, { enabled: true, readFromPrimary: true })).filter((channel) => !skip.has(channel.id));@@ -311,7 +311,7 @@ export const alertEngineFactory = ({condition: alert.condition,targetIds: input.targetIds});- // The rows were deleted between the event being recorded and delivered, so there is nothing to say.+ // Deleted between emit and dispatch, so nothing to say.if (resolved.length === 0) return { outcome: AlertDispatchOutcome.NoDueTargets, deliveredChannelIds: [] };const targets = resolved.map((target) => ({ target, id: provider.targetId(target) }));@@ -320,9 +320,8 @@ export const alertEngineFactory = ({const definition = ALERT_CHANNEL_REGISTRY[channel.channelType as AlertChannelType];const cap = definition?.maxTargetsPerRun;if (cap && targets.length > cap) {- // The scheduled path defers the tail to tomorrow's run, but an event has no next run, so this- // is a real drop. MAX_TARGET_IDS_PER_EVENT sits at or below every channel cap to keep it- // unreachable, and the log names what was lost if that ever stops holding.+ // Unlike the scheduled path there is no next run, so this is a real drop. MAX_TARGET_IDS_PER_EVENT+ // sits at or below every channel cap to keep it unreachable; the log names what was lost if not.logger.warn(`Alert ${channel.channelType} channel caps at ${cap} targets; dropping ${targets.length - cap} from this event [alertId=${alert.id}] [channelId=${channel.id}] [dropped=${targets.slice(cap)diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.tsindex 84cedf5702..39b59ab45a 100644--- a/backend/src/services/alert/alert-event-consumer.ts+++ b/backend/src/services/alert/alert-event-consumer.ts@@ -15,9 +15,8 @@ import { AlertTriggerType, MAX_TARGET_IDS_PER_EVENT } from "./alert-types";export const ALERT_OUTBOX_CONSUMER = "alert";-// The contract every event-triggered alert shares: the emitter names targets by id and the provider-// rehydrates them at delivery time. Keeping the payload to identifiers is what lets one consumer-// serve every provider without knowing their shapes.+// Emitters name targets by id and the provider rehydrates them at delivery. Keeping the payload to+// ids is what lets one consumer serve every provider.export const AlertEventPayloadSchema = z.object({targetIds: z.array(z.string().trim().min(1).max(255)).min(1).max(MAX_TARGET_IDS_PER_EVENT)});@@ -41,9 +40,8 @@ export const alertEventConsumerFactory = ({}: TAlertEventConsumerDep): IEventOutboxConsumer<z.infer<typeof AlertEventPayloadSchema>> => {const subscribesTo = (eventType: string): boolean => alertProviderRegistry.eventTriggeredKeys().has(eventType);- // subscribesTo only sees the event type, so an emitter pairing a valid event key with the wrong- // resourceType gets past the gate. Failing it here, terminally and naming both halves, is what- // stops that row from being marked delivered as "no matching alert".+ // 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 row delivered as "no matching alert".const $isDeclaredEvent = (row: TEventOutboxRow): boolean =>Boolean(alertProviderRegistry@@ -118,8 +116,7 @@ export const alertEventConsumerFactory = ({};const handle = async (rows: TEventOutboxRow[]): Promise<TOutboxRowResult[]> => {- // A batch shares one resource, so rows differ at most by event type and scope. Resolving once- // per combination keeps a burst of events from repeating the same lookup for every row.+ // A batch shares one resource, so a burst of rows would repeat the same lookup.const alertsByScope = new Map<string, ReturnType<TAlertLookup>>();const findAlerts: TAlertLookup = (filter) => {const key = `${filter.orgId}|${filter.projectId ?? ""}|${filter.eventType}`;@@ -138,8 +135,7 @@ export const alertEventConsumerFactory = ({// eslint-disable-next-line no-await-in-loop -- ordering is the pointresults.push(await $handleRow(row, findAlerts));} catch (error) {- // Contained to this row: throwing out of handle() sends the whole batch back for retry, which- // re-notifies on every row that already delivered ahead of this one.+ // Throwing out of handle() retries the whole batch, which re-notifies the rows that already sent.results.push({id: String(row.id),status: EventOutboxStatus.Retry,diff --git a/backend/src/services/alert/alert-types.ts b/backend/src/services/alert/alert-types.tsindex e955952e4e..1ac3764053 100644--- a/backend/src/services/alert/alert-types.ts+++ b/backend/src/services/alert/alert-types.ts@@ -91,8 +91,7 @@ export type TFindDueTargetsInput = {asOf: Date;};-// Lets a provider's factory declare which discovery method it guarantees, instead of leaving callers-// to assert it.+// So a provider factory can declare which discovery method it guarantees.export type IScheduledAlertProvider<TTarget = unknown> = IResourceAlertProvider<TTarget> &Required<Pick<IResourceAlertProvider<TTarget>, "findDueTargets">>;@@ -115,12 +114,9 @@ export interface IResourceAlertProvider<TTarget = unknown> {// Required for any Scheduled event; the registry enforces that at boot.findDueTargets?(input: TFindDueTargetsInput): Promise<TTarget[]>;- // Rehydrate the targets an event named, by id. Nothing is scanned for: this exists so the row is- // read at delivery time rather than copied into the event. A target whose row is gone was deleted- // between emit and dispatch, so it's dropped rather than an error.- // Must read from the primary, never a replica: the target usually commits in the same transaction- // as the event that names it, and the engine cannot tell "not replicated yet" from "deleted". An- // empty result is terminal for the event, so a stale replica here loses the notification outright.+ // 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.findTargetsByIds?(input: TFindTargetsByIdsInput): Promise<TTarget[]>;diff --git a/backend/src/services/event-outbox/event-outbox-dal.ts b/backend/src/services/event-outbox/event-outbox-dal.tsindex deaeffc7a5..1cd22efc59 100644--- a/backend/src/services/event-outbox/event-outbox-dal.ts+++ b/backend/src/services/event-outbox/event-outbox-dal.ts@@ -59,8 +59,7 @@ export const eventOutboxDALFactory = (db: TDbClient) => {}};- // One statement, no explicit transaction: the row locks live only as long as the UPDATE, and a- // claim costs one round trip instead of four.+ // One statement on purpose: the row locks live only as long as the UPDATE.const claimBatch = async (key: TOutboxFlushKey, limit: number): Promise<TEventOutboxRow[]> => {try {const claimed = await db(TableName.EventOutbox)@@ -79,14 +78,15 @@ export const eventOutboxDALFactory = (db: TDbClient) => {.update({ status: EventOutboxStatus.Processing, lockedAt: db.fn.now() }).returning("*");+ // RETURNING order is arbitrary, and handle() is promised id order.return (claimed as unknown as TEventOutboxRow[]).sort((a, b) => (BigInt(a.id) < BigInt(b.id) ? -1 : 1));} catch (error) {throw new DatabaseError({ error, name: "EventOutbox: claimBatch" });}};- // The sweeper reads a claim older than its threshold as a dead worker and hands the rows back out,- // so a batch that legitimately runs that long has to keep lockedAt fresh or it delivers twice.+ // A batch that outlives the stale threshold has to keep lockedAt fresh or the sweeper hands its rows+ // to another worker mid-delivery.const extendClaims = async (ids: string[]): Promise<void> => {if (ids.length === 0) return;try {diff --git a/backend/src/services/event-outbox/event-outbox-queue.ts b/backend/src/services/event-outbox/event-outbox-queue.tsindex 834eea7748..ff8e96c1ea 100644--- a/backend/src/services/event-outbox/event-outbox-queue.ts+++ b/backend/src/services/event-outbox/event-outbox-queue.ts@@ -63,9 +63,6 @@ export const eventOutboxQueueFactory = ({});};- // BullMQ rejects a custom id containing ':' and resourceId is any string, so it gets percent-encoded- // (injectively, so two keys can't collide on one job id). consumer and resourceType are already- // restricted to [a-z0-9._-] by the emit schema.const $enqueueFlush = async (key: TOutboxFlushKey) =>queueService.queue(QueueName.EventOutboxFlush, QueueJobs.EventOutboxFlush, key, {jobId: `outbox-flush-${key.consumer}-${key.resourceType}-${encodeURIComponent(key.resourceId)}`,diff --git a/backend/src/services/event-outbox/event-outbox-service.ts b/backend/src/services/event-outbox/event-outbox-service.tsindex 4bcdc37d03..26ecdfc3cb 100644--- a/backend/src/services/event-outbox/event-outbox-service.ts+++ b/backend/src/services/event-outbox/event-outbox-service.ts@@ -30,8 +30,7 @@ const PRUNE_MAX_BATCHES = 20;const STALE_SWEEP_BATCH_SIZE = 1_000;const STALE_SWEEP_MAX_BATCHES = 10;-// Frequent enough that one missed beat (a slow query, a paused event loop) doesn't let the sweeper-// call a live claim stale.+// A quarter of the threshold, so one missed beat doesn't let the sweeper call a live claim stale.const CLAIM_HEARTBEAT_INTERVAL_MS = STALE_CLAIM_THRESHOLD_MS / 4;const COMMIT_ATTEMPTS = 3;@@ -72,17 +71,9 @@ export type TEventOutboxServiceFactoryDep = {export type TEventOutboxServiceFactory = ReturnType<typeof eventOutboxServiceFactory>;export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry }: TEventOutboxServiceFactoryDep) => {- // `tx` is required, not optional: the row has to commit with the business write, so there is- // deliberately no weaker path to reach for.- //- // Nothing here reads the database. Validation and consumer matching are in-memory, so this adds a- // single insert to the caller's transaction and never calls back into a consumer. Whether anyone- // actually wants the event is settled later in the worker, where guessing wrong only costs a row- // that gets marked delivered and pruned.- //- // Nothing is caught either. A bad event is a bug at the emit site rather than something the API- // caller can act on (hence 500, not 400), and swallowing a failed insert would hand the caller a- // poisoned transaction instead of the real error.+ // `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.const emit = async (event: TOutboxEvent, tx: Knex): Promise<void> => {const parsed = OutboxEventSchema.safeParse(event);if (!parsed.success) {@@ -168,8 +159,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistryfor (const row of rows) {const id = String(row.id);- // A consumer that returned nothing for a row left it unaccounted for; retry rather than- // silently marking it delivered.+ // No result means unaccounted for, not delivered.const result = byId.get(id) ?? {id,status: EventOutboxStatus.Retry as const,@@ -219,8 +209,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry}};- // The heartbeat is what lets a batch legitimately outlive STALE_CLAIM_THRESHOLD_MS (a slow webhook- // endpoint, many rows) without the sweeper handing its rows to a second worker mid-delivery.+ // The heartbeat lets a slow batch outlive STALE_CLAIM_THRESHOLD_MS without being delivered twice.const $handleClaimed = async (consumer: IEventOutboxConsumer,key: TOutboxFlushKey,@@ -250,8 +239,7 @@ export const eventOutboxServiceFactory = ({ eventOutboxDAL, eventOutboxRegistry}};- // Bounded so one wedged resource can't hold a worker indefinitely; whatever is left over gets- // picked up by the relay's next tick.+ // Bounded so one busy resource can't hold a worker forever; the relay's next tick picks up the rest.const drain = async (key: TOutboxFlushKey): Promise<{ handled: number; unknownConsumer: boolean }> => {const consumer = eventOutboxRegistry.get(key.consumer);if (!consumer) {diff --git a/backend/src/services/event-outbox/event-outbox-types.ts b/backend/src/services/event-outbox/event-outbox-types.tsindex 193fa1f816..c23fe2b8a4 100644--- a/backend/src/services/event-outbox/event-outbox-types.ts+++ b/backend/src/services/event-outbox/event-outbox-types.ts@@ -68,7 +68,7 @@ export type TOutboxRowResult = {id: string;status: EventOutboxStatus.Delivered | EventOutboxStatus.Retry | EventOutboxStatus.Failed;error?: string;- // Handed back on the next attempt so a retry can resume instead of repeating. Opaque to the outbox.+ // Opaque to the outbox; handed back on the next attempt so a retry can skip what already landed.progress?: Record<string, unknown> | null;};@@ -82,14 +82,12 @@ export interface IEventOutboxConsumer<TPayload = unknown> {// Stored on every row and part of the flush job id, so renaming it orphans in-flight rows.name: string;- // Parsed at emit, so a malformed event fails at its source instead of in a worker later. Must not- // be `.strict()`: one event can feed several consumers, so a schema has to tolerate fields it- // doesn't care about.+ // Checked at emit. Don't make it `.strict()`: one event can feed several consumers, so each schema+ // has to tolerate fields it doesn't care about.payloadSchema: z.ZodType<TPayload>;// Runs on the request path for every emit, so keep it pure and in-memory. Whether anyone actually- // wants the event is decided later in handle(), off the caller's transaction, where guessing wrong- // costs a throwaway row rather than the business write.+ // wants the event is decided later, in handle().subscribesTo(eventType: string): boolean;// Rows for a single (resourceType, resourceId), in id order. Must return one result per row.