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
feat: implement concurrency on the consumer and add retry later on the approval decision consumer
adilson1d0711c74146
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3d704bd58c..0249da637f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -197,12 +197,12 @@ differs from the one stored for the request; the provider keeps the first tokenanother, so a mismatch is unrecoverable. The provider calls `POST /api/v1/delegated-approvals/callback` (unauthenticated, IP rate limited)with the token in the `Infisical-Approval-Token` header and a body naming the event and the provider's record id;the body carries no decision, which a later worker reads back from the provider. The route finds the row by-`providerRequestId` (404 when none), checks the token, and only then counts the callback in `callbackAttempts`; on+`providerRequestId`, checks the token, and only then counts the callback in `callbackAttempts`; onthe sixth callback with a valid token it sets the row `failed` with a readable `statusReason` and cancels theattached approval request in the same transaction, so the policy is freed and the UI stops offering Cancel. Arefused callback is never counted: the limit closes the request, so counting it would let anyone who knows therecord id cancel the request, and the token is 256 random bits, so there is nothing to brute force. Every other-refusal (bad or missing token, request not `waiting_approval`)+refusal (no row for the record id, bad or missing token, request not `waiting_approval`)gets one neutral 403 while the reason goes to the log. An accepted callback only emits an outbox event, andonly when it wins `claimDecisionRead`: a conditional update of `decisionReadRequestedAt`, in the emit'stransaction, that one of any number of concurrent callbacks wins. A repeat while a read-back is still in@@ -211,9 +211,12 @@ flight gets the same 200 and emits nothing; a claim older than `DELEGATED_APPROVran out of retries still starts one. `eventType` is thebody's event and `idempotencyKey` is the delegated request id plus the attempt count. The`delegated-approval-decision` consumer (`backend/src/services/delegated-approval-decision/`, a thin outbox-adapter over `delegatedApprovalDecisionService.applyDecision`) then reads the decision back through the+adapter over `delegatedApprovalDecisionService.applyDecision` that, like dispatch, reads up to 10 different+requests at once and one request's events serially) then reads the decision back through thepolicy's app connection: `TDelegatedApprovalProvider.fetchDecision` returns `pending` or a decision with-the permissions the provider holds, and the consumer answers `Retry` for `pending`, compares the approved+the permissions the provider holds, and the consumer answers `Retry` for `pending` (on the last attempt, `Failed`+with the request left open and a `statusReason` saying Infisical stopped checking and the callback has to be+sent again, which the claim TTL lets start a new read-back), compares the approvedpermissions with the ones it dispatched after both go through `normalizeDelegatedApprovalPermissions` (setcomparison: padding, order, duplicates and case never count as a change), and finalizes in one transactionthat locks the approval request, moves the delegated row `waiting_approval` → `approved` / `rejected`, anddiff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 86e9720357..b52bb5d9a6 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -842,7 +842,9 @@ await someDAL.transaction(async (tx) => {- **Don't let one event's failure escape `handle`.** The outbox retries the whole batch when `handle`throws. Catch per event and report `Retry` for that event alone: `runEventsSerially` and`parseEventPayload` in `event-outbox-fns.ts` are that loop and the payload check, and every consumer- uses them rather than its own copy.+ uses them rather than its own copy. A consumer that calls a third party per event uses+ `runEventsConcurrentlyByKey` instead, so one slow tenant cannot hold up the batch while events for one+ resource still run one at a time (both delegated approval consumers key it on the delegated request).- **BullMQ owns latency, not correctness.** `attempts: 1` on the flush job is intentional; retry liveson 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 SKIPdiff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.tsindex 68ff989e51..ecaa9142c1 100644--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts@@ -10,7 +10,7 @@ vi.mock("@app/lib/logger", () => ({}));// eslint-disable-next-line import/first-import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { ForbiddenRequestError } from "@app/lib/errors";// eslint-disable-next-line import/firstimport { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";// eslint-disable-next-line import/first@@ -193,10 +193,10 @@ describe("handleCallback", () => {...overrides});- test("returns 404 when no request has the external ID", async () => {+ test("refuses an external ID no request has with the same 403 as any other refusal", async () => {const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService({ delegatedRequest: null });- await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(NotFoundError);+ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);expect(delegatedApprovalRequestDAL.findByProviderRequestId).toHaveBeenCalledWith(EXTERNAL_ID);expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();expect(eventEmitter.emit).not.toHaveBeenCalled();diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.tsindex 68a5bf293b..b814369d35 100644--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts@@ -1,5 +1,4 @@import { getConfig } from "@app/lib/config/env";-import { NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { DelegatedApprovalRequestStatus } from "@app/services/delegated-approval/delegated-approval-enums";import { failDelegatedApprovalRequest } from "@app/services/delegated-approval/delegated-approval-request-fns";@@ -64,9 +63,7 @@ export const delegatedApprovalCallbackServiceFactory = ({const handleCallback = async ({ token, event, externalId }: THandleDelegatedApprovalCallbackDTO) => {const delegatedRequest = await delegatedApprovalRequestDAL.findByProviderRequestId(externalId);if (!delegatedRequest) {- throw new NotFoundError({- message: `No delegated approval request matches external ID '${externalId}'`- });+ throw rejectApprovalCallback("no request matches the external ID", { externalId });}const logContext = { delegatedRequestId: delegatedRequest.id, externalId };diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.tsindex bf96eaa113..e0c391db51 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts@@ -1,4 +1,10 @@+import { MAX_OUTBOX_ATTEMPTS } from "@app/services/event-outbox/event-outbox-types";+export const DELEGATED_APPROVAL_DECISION_CONSUMER = "delegated-approval-decision";+export const DELEGATED_APPROVAL_DECISION_CONCURRENCY = 10;+export const DELEGATED_APPROVAL_DECISION_RETRY_HINT ="Infisical will check again automatically. If this does not change, send the decision again from the delegated approval system.";++export const DELEGATED_APPROVAL_DECISION_STOPPED_HINT = `Infisical stopped checking after ${MAX_OUTBOX_ATTEMPTS} attempts and will not check again on its own. Send the callback to Infisical again from the delegated approval system to finish the request.`;diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.tsindex 19f7eb1f85..09eebc1f25 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts@@ -11,9 +11,17 @@ import { TDelegatedApprovalRequestDetails } from "@app/services/delegated-approvimport { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-enums";import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";-import { EventOutboxStatus, EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";+import {+ EventOutboxStatus,+ EventResultStatus,+ MAX_OUTBOX_ATTEMPTS,+ TEvent+} from "@app/services/event-outbox/event-outbox-types";-import { DELEGATED_APPROVAL_DECISION_RETRY_HINT } from "./delegated-approval-decision-constants";+import {+ DELEGATED_APPROVAL_DECISION_RETRY_HINT,+ DELEGATED_APPROVAL_DECISION_STOPPED_HINT+} from "./delegated-approval-decision-constants";import { delegatedApprovalDecisionConsumerFactory } from "./delegated-approval-decision-consumer";import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";import { delegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";@@ -146,7 +154,16 @@ const buildConsumer = ({findById: vi.fn(async () => approval),findByIdForUpdate: vi.fn(async () => approval),updateById,- transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(TX))+ // Rolls back on a throw, as Postgres would, so a failed finalize leaves both rows as they were.+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => {+ const snapshot = { row, approval };+ try {+ return await fn(TX);+ } catch (error) {+ ({ row, approval } = snapshot);+ throw error;+ }+ })},appConnectionDAL: { findById: vi.fn().mockResolvedValue(connection) },membershipDAL: { isUserProjectMember: vi.fn().mockResolvedValue(isRequesterProjectMember) },@@ -485,6 +502,133 @@ describe("delegatedApprovalDecisionConsumer", () => {expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);});+ test("stops checking on the last attempt without closing a request that has no decision yet", async () => {+ fetchDecision.mockResolvedValueOnce({ status: "pending", reason: "ServiceNow has not recorded a decision yet." });+ const { consumer, row, approval, createAuditLog } = buildConsumer();++ const results = await consumer.handle([makeEvent({ isFinalAttempt: true })]);++ expect(results).toEqual([+ { id: "1", status: EventResultStatus.Failed, error: "ServiceNow has not recorded a decision yet." }+ ]);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ details: {+ statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`+ }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);+ expect(createAuditLog).not.toHaveBeenCalled();+ });++ test("stops checking on the last attempt after a transient read failure, keeping the request open", async () => {+ fetchDecision.mockRejectedValueOnce(new Error("ServiceNow could not be reached."));+ const { consumer, row, approval } = buildConsumer();++ const [result] = await consumer.handle([makeEvent({ isFinalAttempt: true })]);++ expect(result).toEqual({ id: "1", status: EventResultStatus.Failed, error: "ServiceNow could not be reached." });+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);+ expect(row()?.details.statusReason).toBe(+ `ServiceNow could not be reached. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`+ );+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);+ });++ test.each([+ { isFinalAttempt: false, status: EventResultStatus.Retry, statusReason: null },+ {+ isFinalAttempt: true,+ status: EventResultStatus.Failed,+ statusReason: `The grant could not be written. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}`+ }+ ])(+ "rolls back a decision that could not be applied, and explains it once attempts run out (final=$isFinalAttempt)",+ async ({ isFinalAttempt, status, statusReason }) => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer();+ postApprovalTxRoutine.mockRejectedValueOnce(new Error("The grant could not be written."));++ const [result] = await consumer.handle([makeEvent({ isFinalAttempt })]);++ expect(result).toEqual({ id: "1", status, error: "The grant could not be written." });+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);+ expect(row()?.details.statusReason).toBe(statusReason);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);+ expect(createAuditLog).not.toHaveBeenCalled();+ }+ );++ test("reads different requests together", async () => {+ const otherRequestId = "44444444-4444-4444-4444-444444444444";+ let releaseFirst: () => void = () => {};+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });++ fetchDecision.mockImplementation(async (input: { delegatedRequestId: string }) => {+ if (input.delegatedRequestId === DELEGATED_REQUEST_ID) await firstHeld;+ return { status: "pending", reason: "Not yet." };+ });++ const { consumer } = buildConsumer();+ const { payload } = makeEvent();+ const pending = consumer.handle([+ makeEvent({ id: 1 }),+ makeEvent({ id: 2, payload: { ...(payload as Record<string, unknown>), delegatedRequestId: otherRequestId } })+ ]);++ try {+ await vi.waitFor(() => expect(fetchDecision).toHaveBeenCalledTimes(2));+ } finally {+ releaseFirst();+ }++ await expect(pending).resolves.toEqual([+ { id: "1", status: EventResultStatus.Retry, error: "Not yet." },+ { id: "2", status: EventResultStatus.Retry, error: "Not yet." }+ ]);+ });++ test("reads a second event for the same request only after the first settles", async () => {+ let releaseFirst: () => void = () => {};+ const firstHeld = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ let firstSettledAt = 0;+ let secondStartedAt = 0;++ fetchDecision.mockImplementation(async () => {+ if (fetchDecision.mock.calls.length === 1) {+ await firstHeld;+ firstSettledAt = Date.now();+ throw new Error("ServiceNow did not respond.");+ }+ secondStartedAt = Date.now();+ return decided(DelegatedApprovalDecision.Approved);+ });++ const { consumer } = buildConsumer();+ const pending = consumer.handle([makeEvent({ id: 1 }), makeEvent({ id: 2 })]);++ try {+ await vi.waitFor(() => expect(fetchDecision).toHaveBeenCalledTimes(1));+ await new Promise((resolve) => {+ setTimeout(resolve, 30);+ });+ expect(fetchDecision).toHaveBeenCalledTimes(1);+ } finally {+ releaseFirst();+ }++ const results = await pending;++ expect(fetchDecision).toHaveBeenCalledTimes(2);+ expect(firstSettledAt).toBeGreaterThan(0);+ expect(secondStartedAt).toBeGreaterThanOrEqual(firstSettledAt);+ expect(results.map((result) => result.status)).toEqual([EventResultStatus.Retry, EventResultStatus.Delivered]);+ });+test("fails an unreadable payload terminally", async () => {const { consumer } = buildConsumer();@@ -590,4 +734,34 @@ describe("delegatedApprovalDecisionConsumer through the outbox", () => {expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);expect(fetchDecision).toHaveBeenCalledTimes(2);});++ test("leaves the request open and asks for the callback again once the outbox has used up its attempts", async () => {+ fetchDecision.mockResolvedValue({ status: "pending", reason: "Not yet." });+ const built = buildConsumer();+ const { service, rows, elapseBackoff } = buildOutbox(built.consumer);+ const { payload } = makeEvent();++ await service.emit({+ eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,+ payload: payload as Record<string, unknown>+ });++ for (let attempt = 1; attempt < MAX_OUTBOX_ATTEMPTS; attempt += 1) {+ // eslint-disable-next-line no-await-in-loop -- one drain per attempt+ await service.drain({ consumer: built.consumer.name });+ expect(rows[0].status).toBe(EventOutboxStatus.Retry);+ expect(built.row()?.details.statusReason).toBe(`Not yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`);+ elapseBackoff();+ }++ await service.drain({ consumer: built.consumer.name });++ expect(fetchDecision).toHaveBeenCalledTimes(MAX_OUTBOX_ATTEMPTS);+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Failed, attempts: MAX_OUTBOX_ATTEMPTS });+ expect(built.row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ details: { statusReason: `Not yet. ${DELEGATED_APPROVAL_DECISION_STOPPED_HINT}` }+ });+ expect(built.approval()?.status).toBe(ApprovalRequestStatus.Pending);+ });});diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.tsindex 76590849d5..cfaae9a71c 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts@@ -3,10 +3,13 @@ import {isDelegatedApprovalCallbackEvent,TDelegatedApprovalCallbackEventPayload} from "@app/services/delegated-approval-callback/delegated-approval-callback-events";-import { parseEventPayload, runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";+import { parseEventPayload, runEventsConcurrentlyByKey } from "@app/services/event-outbox/event-outbox-fns";import { IEventConsumer, TEvent, TEventConsumerResult } from "@app/services/event-outbox/event-outbox-types";-import { DELEGATED_APPROVAL_DECISION_CONSUMER } from "./delegated-approval-decision-constants";+import {+ DELEGATED_APPROVAL_DECISION_CONCURRENCY,+ DELEGATED_APPROVAL_DECISION_CONSUMER+} from "./delegated-approval-decision-constants";import { TDelegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";type TDelegatedApprovalDecisionConsumerDep = {@@ -27,7 +30,11 @@ export const delegatedApprovalDecisionConsumerFactory = ({if (failure) return failure;const { delegatedRequestId, externalId } = data;- const outcome = await delegatedApprovalDecisionService.applyDecision({ delegatedRequestId, externalId });+ const outcome = await delegatedApprovalDecisionService.applyDecision({+ delegatedRequestId,+ externalId,+ isFinalAttempt: event.isFinalAttempt+ });return { id, ...outcome };};@@ -35,6 +42,11 @@ export const delegatedApprovalDecisionConsumerFactory = ({name: DELEGATED_APPROVAL_DECISION_CONSUMER,payloadSchema: DelegatedApprovalCallbackEventPayloadSchema,subscribesTo: isDelegatedApprovalCallbackEvent,- handle: (events) => runEventsSerially(events, $handleEvent)+ handle: (events) =>+ runEventsConcurrentlyByKey(events, {+ keyOf: (event) => DelegatedApprovalCallbackEventPayloadSchema.safeParse(event.payload).data?.delegatedRequestId,+ concurrency: DELEGATED_APPROVAL_DECISION_CONCURRENCY,+ handleEvent: $handleEvent+ })};};diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.tsindex a3acd72de9..1bab4d3028 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts@@ -31,7 +31,10 @@ import {} from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-fns";import { EventResultStatus } from "@app/services/event-outbox/event-outbox-types";-import { DELEGATED_APPROVAL_DECISION_RETRY_HINT } from "./delegated-approval-decision-constants";+import {+ DELEGATED_APPROVAL_DECISION_RETRY_HINT,+ DELEGATED_APPROVAL_DECISION_STOPPED_HINT+} from "./delegated-approval-decision-constants";import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";import {describeDelegatedApprovalPermissions,@@ -102,15 +105,16 @@ export const delegatedApprovalDecisionServiceFactory = ({}};- const $keepWaiting = async (delegatedRequestId: string, reason: string) => {+ const $retryLater = async (+ delegatedRequestId: string,+ reason: string,+ isFinalAttempt: boolean+ ): Promise<TApplyDelegatedApprovalDecisionResult> => {+ const hint = isFinalAttempt ? DELEGATED_APPROVAL_DECISION_STOPPED_HINT : DELEGATED_APPROVAL_DECISION_RETRY_HINT;try {await delegatedApprovalRequestDAL.updateWithDetails({ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.WaitingApproval },- {- details: {- statusReason: toDelegatedApprovalStatusReason(`${reason} ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`)- }- }+ { details: { statusReason: toDelegatedApprovalStatusReason(`${reason} ${hint}`) } });} catch (error) {logger.error(@@ -118,6 +122,14 @@ export const delegatedApprovalDecisionServiceFactory = ({`Failed to record why the delegated approval decision is still pending [delegatedRequestId=${delegatedRequestId}]`);}++ if (isFinalAttempt) {+ logger.error(+ `Delegated approval decision attempts ran out, request left waiting for a new callback [delegatedRequestId=${delegatedRequestId}] [reason=${reason}]`+ );+ return { status: EventResultStatus.Failed, error: reason };+ }+ return { status: EventResultStatus.Retry, error: reason };};const $terminal = async (@@ -213,10 +225,11 @@ export const delegatedApprovalDecisionServiceFactory = ({// Reads the decision back from the delegated approval system and finalizes the request. Retry// means the system has not recorded a decision yet and the caller should try again later; Failed- // means the request was closed and nothing can retry it.+ // means the request was closed, or the last attempt ran out and only a new callback can read it again.const applyDecision = async ({delegatedRequestId,- externalId+ externalId,+ isFinalAttempt}: TApplyDelegatedApprovalDecisionDTO): Promise<TApplyDelegatedApprovalDecisionResult> => {const delegatedApprovalContext = await loadDelegatedApprovalContext(delegatedRequestId, {delegatedApprovalRequestDAL,@@ -337,11 +350,12 @@ export const delegatedApprovalDecisionServiceFactory = ({);if (result.status === "pending") {- await $keepWaiting(delegatedRequestId, result.reason);- logger.info(- `Delegated approval decision not recorded yet, will check again [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`- );- return { status: EventResultStatus.Retry, error: result.reason };+ if (!isFinalAttempt) {+ logger.info(+ `Delegated approval decision not recorded yet, will check again [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`+ );+ }+ return await $retryLater(delegatedRequestId, result.reason, isFinalAttempt);}if (result.approvalRequestId && result.approvalRequestId !== approvalRequest.id) {@@ -372,15 +386,26 @@ export const delegatedApprovalDecisionServiceFactory = ({const { terminal: isTerminal, message, logContext } = toDelegatedApprovalFailure(error);if (isTerminal) return $terminal(context, message);- await $keepWaiting(delegatedRequestId, message);logger.warn(logContext,- `Failed to read the delegated approval decision, will retry [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`+ `Failed to read the delegated approval decision [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [isFinalAttempt=${isFinalAttempt}]`);- return { status: EventResultStatus.Retry, error: message };+ return $retryLater(delegatedRequestId, message, isFinalAttempt);}- const finalized = await $finalize(context, decided, postApprovalTxRoutine);+ let finalized: TDelegatedApprovalFinalizeOutcome;+ try {+ finalized = await $finalize(context, decided, postApprovalTxRoutine);+ } catch (error) {+ if (!isFinalAttempt) throw error;++ const { message, logContext } = toDelegatedApprovalFailure(error);+ logger.error(+ logContext,+ `Failed to apply the delegated approval decision [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`+ );+ return $retryLater(delegatedRequestId, message, isFinalAttempt);+ }if (finalized.kind === "applied") {const notify = isDelegatedApprovalSupportedPolicyType(approvalRequest.type)? decisionNotifiers[approvalRequest.type]diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.tsindex 81f776477a..921bb201aa 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts@@ -76,6 +76,7 @@ export type TDelegatedApprovalDecisionContext = {export type TApplyDelegatedApprovalDecisionDTO = {delegatedRequestId: string;externalId: string;+ isFinalAttempt: boolean;};export type TApplyDelegatedApprovalDecisionResult = {@@ -83,5 +84,8 @@ export type TApplyDelegatedApprovalDecisionResult = {error?: string;};-export type TDelegatedApprovalFinalizeOutcome = // this feels weird to me honestly- { kind: "applied" } | { kind: "late"; reason: string } | { kind: "gone" } | { kind: "raced" };+export type TDelegatedApprovalFinalizeOutcome =+ | { kind: "applied" }+ | { kind: "late"; reason: string }+ | { kind: "gone" }+ | { kind: "raced" };diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.tsindex b23528486c..ec38f5f870 100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts@@ -1,5 +1,4 @@import { UnrecoverableError } from "bullmq";-import pLimit from "p-limit";import { ProjectType } from "@app/db/schemas";import { logger } from "@app/lib/logger";@@ -8,7 +7,7 @@ import { decryptAppConnection } from "@app/services/app-connection/app-connectioimport { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";-import { parseEventPayload, runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";+import { parseEventPayload, runEventsConcurrentlyByKey } from "@app/services/event-outbox/event-outbox-fns";import {EventResultStatus,IEventConsumer,@@ -301,36 +300,13 @@ export const delegatedApprovalDispatchConsumerFactory = ({return { id: String(event.id), ...(await $dispatch(data.delegatedRequestId, event.isFinalAttempt)) };};- // Unreadable payloads have no request id, so each one is its own group and cannot block another request.- const $groupByRequest = (events: TEvent[]): TEvent[][] => {- const groups: TEvent[][] = [];- const indexByRequest = new Map<string, number>();-- events.forEach((event) => {- const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);- const key = payload.success ? payload.data.delegatedRequestId : `event:${String(event.id)}`;- const existing = indexByRequest.get(key);- if (existing === undefined) {- indexByRequest.set(key, groups.length);- groups.push([event]);- } else {- groups[existing].push(event);- }- });-- return groups;- };-// Events for one request run serially, so two of them cannot both pass the providerRequestId check.- const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> => {- const limit = pLimit(DELEGATED_APPROVAL_DISPATCH_CONCURRENCY);-- const groupResults = await Promise.all(- $groupByRequest(events).map((group) => limit(() => runEventsSerially(group, $handleEvent)))- );-- return groupResults.flat();- };+ const handle = (events: TEvent[]): Promise<TEventConsumerResult[]> =>+ runEventsConcurrentlyByKey(events, {+ keyOf: (event) => DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload).data?.delegatedRequestId,+ concurrency: DELEGATED_APPROVAL_DISPATCH_CONCURRENCY,+ handleEvent: $handleEvent+ });return {name: DELEGATED_APPROVAL_DISPATCH_CONSUMER,diff --git a/backend/src/services/event-outbox/event-outbox-fns.ts b/backend/src/services/event-outbox/event-outbox-fns.tsindex 29f5b40f8d..94bc771217 100644--- a/backend/src/services/event-outbox/event-outbox-fns.ts+++ b/backend/src/services/event-outbox/event-outbox-fns.ts@@ -1,3 +1,4 @@+import pLimit from "p-limit";import { z } from "zod";import { EventResultStatus, TEvent, TEventConsumerResult } from "./event-outbox-types";@@ -44,3 +45,34 @@ export const runEventsSerially = async (return results;};++export const runEventsConcurrentlyByKey = async (+ events: TEvent[],+ {+ keyOf,+ concurrency,+ handleEvent+ }: {+ keyOf: (event: TEvent) => string | undefined;+ concurrency: number;+ handleEvent: (event: TEvent) => Promise<TEventConsumerResult>;+ }+): Promise<TEventConsumerResult[]> => {+ const groups: TEvent[][] = [];+ const indexByKey = new Map<string, number>();++ events.forEach((event) => {+ const key = keyOf(event) ?? `event:${String(event.id)}`;+ const existing = indexByKey.get(key);+ if (existing === undefined) {+ indexByKey.set(key, groups.length);+ groups.push([event]);+ } else {+ groups[existing].push(event);+ }+ });++ const limit = pLimit(concurrency);+ const groupResults = await Promise.all(groups.map((group) => limit(() => runEventsSerially(group, handleEvent))));+ return groupResults.flat();+};diff --git a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdxindex 66d407bf24..1ace20a2a0 100644--- a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx+++ b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx@@ -149,7 +149,7 @@ Both sides keep their own record. In ServiceNow, the access request record carri| Record created but nothing happens | No active flow matches the record. Verify your flow is activated and its trigger condition matches the record's field values. || Approvers see duplicate approvals | Two flows match the same record. Make the trigger conditions mutually exclusive and deactivate the one you no longer want. || State stuck at Notifying Infisical | The callback is in flight or the flow errored mid-step. Check the flow's execution details. |-| Callback Failed with HTTP 403 | Infisical already closed this request, or ServiceNow notified Infisical about it more than five times. Check the request's status in Infisical, and create the request again if the requester still needs access. |+| Callback Failed with HTTP 403 | Infisical already closed this request, the request was deleted along with its project, or ServiceNow notified Infisical about the request more than five times. Check the request's status in Infisical, and create the request again if the requester still needs access. || Callback Failed with a connection error | The ServiceNow instance can't reach the **Callback URL** on the record. Fix the instance's outbound firewall rules, then select **Resend to Infisical** on the request in the **Admin Console**. If the URL itself is wrong, correct `SITE_URL` and create the request again. || Request expired before approval | The policy's request expiration elapsed while the request sat in ServiceNow. Extend it, or shorten your approval SLA. || Infisical says the request couldn't be completed in ServiceNow | Infisical couldn't apply the decision. The reason is shown under the request status: the **Permissions** field was changed in ServiceNow, the record was deleted, or ServiceNow rejected the integration user's credentials. Fix the cause and create the request again. |