Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore: improve webhook retries (#8098)

Max Deichmann85f75a5e8edc
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index 9a9ad81a31..548cb48e45 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -58,6 +58,7 @@ export const WebhookActionConfigSchema = z.object({
apiVersion: AvailableWebhookApiSchema,
secretKey: z.string(),
displaySecretKey: z.string(),
+ lastFailingExecutionId: z.string().nullish(),
});
export const SafeWebhookActionConfigSchema = WebhookActionConfigSchema.omit({
diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.ts
index 0468c82a5f..9b237f2b3e 100644
--- a/packages/shared/src/server/repositories/automation-repository.ts
+++ b/packages/shared/src/server/repositories/automation-repository.ts
@@ -2,6 +2,7 @@ import {
Action,
ActionExecutionStatus,
JobConfigState,
+ Prisma,
prisma,
Trigger,
} from "../../db";
@@ -60,6 +61,7 @@ export const getActionByIdWithSecrets = async ({
apiVersion: config.apiVersion,
displaySecretKey: config.displaySecretKey,
secretKey: config.secretKey,
+ lastFailingExecutionId: config.lastFailingExecutionId,
},
};
};
@@ -156,6 +158,7 @@ const convertActionToDomain = (action: Action): ActionDomain => {
displayHeaders: getDisplayHeaders(config),
apiVersion: config.apiVersion,
displaySecretKey: config.displaySecretKey,
+ lastFailingExecutionId: config.lastFailingExecutionId,
} as SafeWebhookActionConfig,
};
};
@@ -229,28 +232,46 @@ export const getConsecutiveAutomationFailures = async ({
automationId: string;
projectId: string;
}): Promise<number> => {
- // First get the automation to extract triggerId and actionId
- const automation = await prisma.automation.findFirst({
- where: {
- id: automationId,
- projectId,
- },
+ const automation = await getAutomationById({
+ automationId,
+ projectId,
});
if (!automation) {
return 0;
}
- const { triggerId, actionId } = automation;
- const executions = await prisma.automationExecution.findMany({
- where: {
- triggerId,
- actionId,
- projectId,
- status: {
- in: [ActionExecutionStatus.ERROR, ActionExecutionStatus.COMPLETED],
- },
+ // Build where clause - if lastFailingExecutionId is set, only consider executions newer than it
+ const whereClause: Prisma.AutomationExecutionWhereInput = {
+ triggerId: automation.trigger.id,
+ actionId: automation.action.id,
+ projectId,
+ status: {
+ in: [ActionExecutionStatus.ERROR, ActionExecutionStatus.COMPLETED],
},
+ };
+
+ // If there's a lastFailingExecutionId, we need to get executions that are newer than that execution
+ if (automation.action.config.lastFailingExecutionId) {
+ // First get the timestamp of the last failing execution
+ const lastFailingExecution = await prisma.automationExecution.findUnique({
+ where: {
+ id: automation.action.config.lastFailingExecutionId,
+ },
+ select: {
+ createdAt: true,
+ },
+ });
+
+ if (lastFailingExecution) {
+ whereClause.createdAt = {
+ gt: lastFailingExecution.createdAt,
+ };
+ }
+ }
+
+ const executions = await prisma.automationExecution.findMany({
+ where: whereClause,
orderBy: {
createdAt: "desc",
},
diff --git a/web/src/__tests__/async/automations-trpc.servertest.ts b/web/src/__tests__/async/automations-trpc.servertest.ts
index bb1225b167..a126c97384 100644
--- a/web/src/__tests__/async/automations-trpc.servertest.ts
+++ b/web/src/__tests__/async/automations-trpc.servertest.ts
@@ -1780,6 +1780,199 @@ describe("automations trpc", () => {
expect(response.count).toBe(3);
});
+
+ it("should return 0 consecutive failures when lastFailingExecutionId is set", async () => {
+ const { project, caller } = await prepare();
+
+ // Create automation
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.INACTIVE, // Disabled due to failures
+ },
+ });
+
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ type: "WEBHOOK",
+ config: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ lastFailingExecutionId: "some-failing-execution-id", // This simulates a webhook that was disabled
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Test Automation",
+ },
+ });
+
+ // Create failed executions that occurred BEFORE the lastFailingExecutionId
+ await prisma.automationExecution.create({
+ data: {
+ id: "some-failing-execution-id",
+ automationId: automation.id,
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { iteration: 0 },
+ error: "Old failure",
+ createdAt: new Date(Date.now() - 60000), // 1 minute ago
+ },
+ });
+
+ // Create more failed executions that occurred BEFORE the lastFailingExecutionId
+ for (let i = 1; i < 5; i++) {
+ await prisma.automationExecution.create({
+ data: {
+ id: v4(),
+ automationId: automation.id,
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { iteration: i },
+ error: `Old failure ${i}`,
+ createdAt: new Date(Date.now() - (60000 + i * 1000)), // Before the lastFailingExecutionId
+ },
+ });
+ }
+
+ const response = await caller.automations.getCountOfConsecutiveFailures({
+ projectId: project.id,
+ automationId: automation.id,
+ });
+
+ // Should return 0 because all failures occurred before the lastFailingExecutionId
+ expect(response.count).toBe(0);
+ });
+
+ it("should count failures after lastFailingExecutionId correctly", async () => {
+ const { project, caller } = await prepare();
+
+ // Create automation
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ eventSource: "prompt",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const lastFailingExecutionId = v4();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ type: "WEBHOOK",
+ config: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ requestHeaders: {
+ "Content-Type": { secret: false, value: "application/json" },
+ },
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ lastFailingExecutionId,
+ },
+ },
+ });
+
+ const automation = await prisma.automation.create({
+ data: {
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: "Test Automation",
+ },
+ });
+
+ // Create the lastFailingExecution
+ await prisma.automationExecution.create({
+ data: {
+ id: lastFailingExecutionId,
+ automationId: automation.id,
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { iteration: 0 },
+ error: "Last failing execution",
+ createdAt: new Date(Date.now() - 60000), // 1 minute ago
+ },
+ });
+
+ // Create old failures that should be ignored
+ for (let i = 0; i < 3; i++) {
+ await prisma.automationExecution.create({
+ data: {
+ id: v4(),
+ automationId: automation.id,
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { iteration: i },
+ error: `Old failure ${i}`,
+ createdAt: new Date(Date.now() - (120000 + i * 1000)), // Before the lastFailingExecutionId
+ },
+ });
+ }
+
+ // Create new failures AFTER the lastFailingExecutionId
+ for (let i = 0; i < 2; i++) {
+ await prisma.automationExecution.create({
+ data: {
+ id: v4(),
+ automationId: automation.id,
+ projectId: project.id,
+ triggerId: trigger.id,
+ actionId: action.id,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { iteration: i },
+ error: `New failure ${i}`,
+ createdAt: new Date(Date.now() - (30000 - i * 1000)), // After the lastFailingExecutionId
+ },
+ });
+ }
+
+ const response = await caller.automations.getCountOfConsecutiveFailures({
+ projectId: project.id,
+ automationId: automation.id,
+ });
+
+ // Should return 2 because only the 2 new failures after lastFailingExecutionId should be counted
+ expect(response.count).toBe(2);
+ });
});
describe("automations.regenerateWebhookSecret", () => {
diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.ts
index cfc20dc34f..dc72902b5f 100644
--- a/web/src/features/automations/server/router.ts
+++ b/web/src/features/automations/server/router.ts
@@ -320,7 +320,6 @@ export const automationsRouter = createTRPCRouter({
};
}),
- // Update an existing automation
updateAutomation: protectedProjectProcedure
.input(UpdateAutomationInputSchema)
.mutation(async ({ ctx, input }) => {
@@ -389,7 +388,6 @@ export const automationsRouter = createTRPCRouter({
},
});
- // Get the updated automation
const automation = await tx.automation.findFirst({
where: {
id: input.automationId,
diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.ts
index e9996bb650..bfef83120c 100644
--- a/web/src/features/automations/server/webhookHelpers.ts
+++ b/web/src/features/automations/server/webhookHelpers.ts
@@ -23,16 +23,6 @@ interface WebhookConfigOptions {
projectId: string;
}
-/**
- * Processes webhook action configuration by:
- * 1. Merging legacy headers with new requestHeaders
- * 2. Handling header removal (headers not in input are removed)
- * 3. Preserving existing values when empty values are submitted
- * 4. Encrypting secret headers based on secret flag
- * 5. Generating display values for secret headers
- * 6. Generating or preserving webhook secrets
- * 7. Encrypting secrets for storage
- */
export async function processWebhookActionConfig({
actionConfig,
actionId,
@@ -60,7 +50,6 @@ export async function processWebhookActionConfig({
actionConfig,
existingAction?.config as WebhookActionConfigWithSecrets | undefined,
);
-
return {
finalActionConfig: {
...finalActionConfig,
@@ -156,6 +145,7 @@ function processWebhookHeaders(
displayHeaders: createDisplayHeaders(finalRequestHeaders),
secretKey: "", // will be overwritten by the caller
displaySecretKey: "", // will be overwritten by the caller
+ lastFailingExecutionId: existingConfig?.lastFailingExecutionId,
};
}
diff --git a/worker/package.json b/worker/package.json
index e9ce561662..bf2292a1d0 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -8,7 +8,7 @@
"node": "20"
},
"scripts": {
- "test": "dotenv -e ../.env -- vitest run --reporter=basic --pool=forks --poolOptions.forks.singleFork=true",
+ "test": "dotenv -e ../.env -- vitest run --pool=forks --poolOptions.forks.singleFork=true",
"coverage": "vitest run --coverage",
"start": "dotenv -e ../.env -- node dist/index.js",
"build": "tsc",
diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.ts
index 88c7a13ff2..2116ab8a89 100644
--- a/worker/src/__tests__/webhooks.test.ts
+++ b/worker/src/__tests__/webhooks.test.ts
@@ -18,6 +18,7 @@ import {
import {
WebhookInput,
createOrgProjectAndApiKey,
+ getActionByIdWithSecrets,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import {
@@ -421,7 +422,7 @@ describe("Webhook Integration Tests", () => {
});
});
- it("should disable trigger after 5 consecutive failures", async () => {
+ it("should disable trigger after 5 consecutive failures and store lastFailingExecutionId", async () => {
const fullPrompt = await prisma.prompt.findUnique({
where: { id: promptId },
});
@@ -497,6 +498,14 @@ describe("Webhook Integration Tests", () => {
where: { id: triggerId },
});
expect(trigger?.status).toBe(JobConfigState.INACTIVE);
+
+ // Verify lastFailingExecutionId was stored in action config
+ const updatedAction = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+ const config = updatedAction?.config as any;
+ expect(config.lastFailingExecutionId).toBeDefined();
+ expect(typeof config.lastFailingExecutionId).toBe("string");
});
it("should execute webhook with secret headers correctly", async () => {
@@ -951,5 +960,200 @@ describe("Webhook Integration Tests", () => {
});
expect(execution).toBeNull();
});
+
+ it("should reset failure count correctly with lastFailingExecutionId", async () => {
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const action = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ // Set a lastFailingExecutionId in the action config
+ const lastFailingExecutionId = v4();
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ lastFailingExecutionId,
+ },
+ },
+ });
+
+ // Create the execution that matches the lastFailingExecutionId
+ await prisma.automationExecution.create({
+ data: {
+ id: lastFailingExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.ERROR,
+ sourceId: v4(),
+ input: { test: "old failing execution" },
+ error: "Old failure",
+ createdAt: new Date(Date.now() - 60000), // 1 minute ago
+ },
+ });
+
+ // Import the function to test it directly
+ const { getConsecutiveAutomationFailures } = await import(
+ "@langfuse/shared/src/server"
+ );
+
+ // Check that consecutive failures is 0 since there are no executions after the lastFailingExecutionId
+ const failures = await getConsecutiveAutomationFailures({
+ automationId,
+ projectId,
+ });
+
+ expect(failures).toBe(0);
+ });
+
+ it(
+ "should reset failure count when webhook is re-enabled after being disabled",
+ { timeout: 20000 },
+ async () => {
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const action = await getActionByIdWithSecrets({
+ projectId,
+ actionId,
+ });
+
+ if (!action) {
+ throw new Error("Action not found");
+ }
+
+ // Update action to point to error endpoint
+ await prisma.action.update({
+ where: { id: actionId },
+ data: {
+ config: {
+ ...(action.config as WebhookActionConfigWithSecrets),
+ url: "https://webhook-error.example.com/test",
+ },
+ },
+ });
+
+ const executionIds: string[] = [];
+
+ // Execute webhook 5 times to trigger disable
+ for (let i = 0; i < 5; i++) {
+ const executionId = v4();
+ executionIds.push(executionId);
+
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: v4(),
+ input: {
+ promptName: "test-prompt",
+ promptVersion: 1,
+ action: "created",
+ type: "prompt-version",
+ },
+ },
+ });
+
+ const webhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await executeWebhook(webhookInput);
+ }
+
+ // Verify trigger was disabled and lastFailingExecutionId was stored
+ const trigger = await prisma.trigger.findUnique({
+ where: { id: triggerId },
+ });
+ expect(trigger?.status).toBe(JobConfigState.INACTIVE);
+
+ const actionAfterDisable = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+ const configAfterDisable = actionAfterDisable?.config as any;
+ expect(configAfterDisable.lastFailingExecutionId).toBe(executionIds[4]);
+
+ // Re-enable the trigger (simulates user action)
+ await prisma.trigger.update({
+ where: { id: triggerId },
+ data: { status: JobConfigState.ACTIVE },
+ });
+
+ // Create 5 more failing executions to trigger disable again
+ const newExecutionIds: string[] = [];
+ for (let i = 0; i < 5; i++) {
+ const newExecutionId = v4();
+ newExecutionIds.push(newExecutionId);
+
+ await prisma.automationExecution.create({
+ data: {
+ id: newExecutionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: v4(),
+ input: {
+ promptName: "test-prompt",
+ promptVersion: 1,
+ action: "created",
+ type: "prompt-version",
+ },
+ },
+ });
+
+ const newWebhookInput: WebhookInput = {
+ projectId,
+ automationId,
+ executionId: newExecutionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ await executeWebhook(newWebhookInput);
+ }
+
+ // Verify trigger was disabled again and lastFailingExecutionId was updated
+ const triggerAfterSecondDisable = await prisma.trigger.findUnique({
+ where: { id: triggerId },
+ });
+ expect(triggerAfterSecondDisable?.status).toBe(JobConfigState.INACTIVE);
+
+ const actionAfterSecondDisable = await prisma.action.findUnique({
+ where: { id: actionId },
+ });
+ const configAfterSecondDisable =
+ actionAfterSecondDisable?.config as any;
+ expect(configAfterSecondDisable.lastFailingExecutionId).toBe(
+ newExecutionIds[4],
+ );
+ },
+ );
});
});
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index dc367c2a46..8ae4228df9 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -229,6 +229,17 @@ export const executeWebhook = async (input: WebhookInput) => {
throw error;
}
+ // Get action config for updating in case of failure
+ const failureActionConfig = await getActionByIdWithSecrets({
+ projectId,
+ actionId: automation.action.id,
+ });
+
+ if (!failureActionConfig) {
+ logger.error("Action config not found for failure handling");
+ return;
+ }
+
// Update action execution status and check if we should disable trigger
await prisma.$transaction(async (tx) => {
// Update execution status
@@ -265,11 +276,23 @@ export const executeWebhook = async (input: WebhookInput) => {
// Check if trigger should be disabled (this is the 5th failure, looking for 4 in the past.)
if (consecutiveFailures >= 4) {
+ // Update trigger to inactive status
await tx.trigger.update({
where: { id: automation.trigger.id, projectId },
data: { status: JobConfigState.INACTIVE },
});
+ // Update action config to store the failing execution ID
+ await tx.action.update({
+ where: { id: automation.action.id, projectId },
+ data: {
+ config: {
+ ...failureActionConfig.config,
+ lastFailingExecutionId: executionId,
+ },
+ },
+ });
+
logger.warn(
`Automation ${automation.trigger.id} disabled after ${consecutiveFailures} consecutive failures in project ${projectId}`,
);