Skip to content

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

feat(automations): narrow getAutomations by event source and event (#13779)

Mark Salpeter300b564b2639
diff --git a/packages/shared/package.json b/packages/shared/package.json
index f708443354..fda871c186 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -63,7 +63,7 @@
"dev": "tsc --watch",
"lint": "eslint . --cache --cache-location dist/.eslintcache --max-warnings 0",
"lint:fix": "eslint . --cache --cache-location dist/.eslintcache --fix",
- "test": "vitest run",
+ "test": "dotenv -e ../../.env -- vitest run",
"db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev",
"db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push",
"db:reset": "dotenv -e ../../.env npx -- prisma migrate reset",
diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.ts
index 396459efca..7452b9395c 100644
--- a/packages/shared/src/domain/automations.ts
+++ b/packages/shared/src/domain/automations.ts
@@ -4,13 +4,17 @@ import { z } from "zod";
export enum TriggerEventSource {
Prompt = "prompt",
+ Monitor = "monitor",
}
export const EventActionSchema = z.enum(["created", "updated", "deleted"]);
export type TriggerEventAction = z.infer<typeof EventActionSchema>;
-export const TriggerEventSourceSchema = z.enum([TriggerEventSource.Prompt]);
+export const TriggerEventSourceSchema = z.enum([
+ TriggerEventSource.Prompt,
+ TriggerEventSource.Monitor,
+]);
export type TriggerDomain = Omit<
Trigger,
diff --git a/packages/shared/src/server/automations.test.ts b/packages/shared/src/server/automations.test.ts
new file mode 100644
index 0000000000..50e7f1989c
--- /dev/null
+++ b/packages/shared/src/server/automations.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from "vitest";
+import { matchesTriggerFilter } from "./automations";
+import type { FilterState } from "../types";
+
+describe("matchesTriggerFilter", () => {
+ describe("filter conditions", () => {
+ it("returns true when the filter is empty and eventActions is empty", () => {
+ expect(
+ matchesTriggerFilter(
+ { Name: "anything" },
+ { filter: [], eventActions: [] },
+ ),
+ ).toBe(true);
+ });
+
+ it("returns true when data satisfies a string filter", () => {
+ const filter: FilterState = [
+ { type: "string", column: "Name", operator: "=", value: "p95" },
+ ];
+ expect(
+ matchesTriggerFilter({ Name: "p95" }, { filter, eventActions: [] }),
+ ).toBe(true);
+ });
+
+ it("returns false when data does not satisfy a string filter", () => {
+ const filter: FilterState = [
+ { type: "string", column: "Name", operator: "=", value: "p95" },
+ ];
+ expect(
+ matchesTriggerFilter(
+ { Name: "error rate" },
+ { filter, eventActions: [] },
+ ),
+ ).toBe(false);
+ });
+
+ it("returns false when data is missing the column referenced by the filter", () => {
+ const filter: FilterState = [
+ { type: "string", column: "Name", operator: "=", value: "p95" },
+ ];
+ expect(matchesTriggerFilter({}, { filter, eventActions: [] })).toBe(
+ false,
+ );
+ });
+ });
+
+ describe("eventActions merge", () => {
+ it("matches when data.action is in eventActions", () => {
+ expect(
+ matchesTriggerFilter(
+ { action: "created" },
+ { filter: [], eventActions: ["created", "updated"] },
+ ),
+ ).toBe(true);
+ });
+
+ it("rejects when data.action is not in eventActions", () => {
+ expect(
+ matchesTriggerFilter(
+ { action: "deleted" },
+ { filter: [], eventActions: ["created", "updated"] },
+ ),
+ ).toBe(false);
+ });
+
+ it("rejects when data has no action and eventActions is non-empty", () => {
+ expect(
+ matchesTriggerFilter({}, { filter: [], eventActions: ["created"] }),
+ ).toBe(false);
+ });
+
+ it("ignores eventActions when the array is empty", () => {
+ // No synthetic condition appended, so data without an action still matches.
+ expect(
+ matchesTriggerFilter(
+ { action: "anything" },
+ { filter: [], eventActions: [] },
+ ),
+ ).toBe(true);
+ });
+
+ it("evaluates both the user filter and the synthetic action condition", () => {
+ const filter: FilterState = [
+ { type: "string", column: "Name", operator: "=", value: "p95" },
+ ];
+
+ expect(
+ matchesTriggerFilter(
+ { Name: "p95", action: "created" },
+ { filter, eventActions: ["created"] },
+ ),
+ ).toBe(true);
+
+ // Filter matches but action doesn't → rejected
+ expect(
+ matchesTriggerFilter(
+ { Name: "p95", action: "updated" },
+ { filter, eventActions: ["created"] },
+ ),
+ ).toBe(false);
+
+ // Action matches but filter doesn't → rejected
+ expect(
+ matchesTriggerFilter(
+ { Name: "other", action: "created" },
+ { filter, eventActions: ["created"] },
+ ),
+ ).toBe(false);
+ });
+ });
+});
diff --git a/packages/shared/src/server/automations.ts b/packages/shared/src/server/automations.ts
new file mode 100644
index 0000000000..9659359a0b
--- /dev/null
+++ b/packages/shared/src/server/automations.ts
@@ -0,0 +1,27 @@
+import { type TriggerDomain } from "../domain/automations";
+import { FilterState } from "../types";
+import { InMemoryFilterService } from "./services/InMemoryFilterService";
+
+/** matchesTriggerFilter returns true when data satisfies a trigger's filter, treating `trigger.eventActions` as a synthetic "action" condition appended to the filter. */
+export const matchesTriggerFilter = (
+ data: Record<string, unknown>,
+ trigger: Pick<TriggerDomain, "filter" | "eventActions">,
+): boolean => {
+ const mergedFilter: FilterState =
+ trigger.eventActions.length > 0
+ ? [
+ ...trigger.filter,
+ {
+ column: "action",
+ operator: "any of",
+ type: "stringOptions",
+ value: trigger.eventActions,
+ },
+ ]
+ : trigger.filter;
+ return InMemoryFilterService.evaluateFilter(
+ data,
+ mergedFilter,
+ (d, column) => (d as Record<string, unknown>)[column],
+ );
+};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 87053886fe..3a0f1f2ec4 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -14,6 +14,7 @@ export * from "./services/PromptService";
export * from "./services/PromptService/types";
export * from "./services/traces-ui-table-service";
export * from "./services/InMemoryFilterService";
+export * from "./automations";
export * from "./services/DatasetService";
export * from "./services/commentFilterService";
export * from "./datasets/schemaValidation";
diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.ts
index 8271859b7e..ca1a5b92b0 100644
--- a/packages/shared/src/server/repositories/automation-repository.ts
+++ b/packages/shared/src/server/repositories/automation-repository.ts
@@ -21,6 +21,7 @@ import {
} from "../../domain/automations";
import { FilterState } from "../../types";
import { decryptSecretHeaders, mergeHeaders } from "../utils/headerUtils";
+import { matchesTriggerFilter } from "../automations";
export const getActionByIdWithSecrets = async ({
projectId,
@@ -210,16 +211,21 @@ export const getAutomations = async ({
projectId,
triggerId,
actionId,
+ eventSource,
+ matches,
}: {
projectId: string;
triggerId?: string;
actionId?: string;
+ eventSource?: TriggerEventSource;
+ matches?: Record<string, unknown>;
}): Promise<AutomationDomain[]> => {
const automations = await prisma.automation.findMany({
where: {
projectId,
...(triggerId ? { triggerId } : {}),
...(actionId ? { actionId } : {}),
+ ...(eventSource ? { trigger: { eventSource } } : {}),
},
include: {
action: true,
@@ -230,12 +236,17 @@ export const getAutomations = async ({
},
});
- return automations.map((automation) => ({
+ const domains = automations.map((automation) => ({
id: automation.id,
name: automation.name,
trigger: convertTriggerToDomain(automation.trigger),
action: convertActionToDomain(automation.action),
}));
+
+ if (!matches) return domains;
+ return domains.filter((automation) =>
+ matchesTriggerFilter(matches, automation.trigger),
+ );
};
export const getConsecutiveAutomationFailures = async ({
diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.ts
index e56a28d892..9dc6de2213 100644
--- a/web/src/__tests__/server/automations-trpc.servertest.ts
+++ b/web/src/__tests__/server/automations-trpc.servertest.ts
@@ -291,6 +291,205 @@ describe("automations trpc", () => {
expect(response).toEqual([]);
});
+
+ describe("eventSource + matches narrowing", () => {
+ async function createAutomation(opts: {
+ projectId: string;
+ name: string;
+ eventSource: "prompt" | "monitor";
+ filter: unknown[];
+ eventActions?: string[];
+ }) {
+ const trigger = await prisma.trigger.create({
+ data: {
+ id: v4(),
+ projectId: opts.projectId,
+ eventSource: opts.eventSource,
+ eventActions: opts.eventActions ?? [],
+ filter: opts.filter as object,
+ status: JobConfigState.ACTIVE,
+ },
+ });
+ const { secretKey, displaySecretKey } = generateWebhookSecret();
+ const action = await prisma.action.create({
+ data: {
+ id: v4(),
+ projectId: opts.projectId,
+ type: "WEBHOOK",
+ config: {
+ type: "WEBHOOK",
+ url: "https://example.com/webhook",
+ apiVersion: { prompt: "v1" },
+ secretKey: encrypt(secretKey),
+ displaySecretKey,
+ },
+ },
+ });
+ await prisma.automation.create({
+ data: {
+ projectId: opts.projectId,
+ triggerId: trigger.id,
+ actionId: action.id,
+ name: opts.name,
+ },
+ });
+ }
+
+ it("filters by eventSource at the DB layer", async () => {
+ const { project, caller } = await prepare();
+
+ await createAutomation({
+ projectId: project.id,
+ name: "prompt-automation",
+ eventSource: "prompt",
+ filter: [],
+ });
+ await createAutomation({
+ projectId: project.id,
+ name: "monitor-automation",
+ eventSource: "monitor",
+ filter: [],
+ });
+
+ const monitor = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "monitor",
+ });
+ expect(monitor.map((a) => a.name)).toEqual(["monitor-automation"]);
+
+ const prompt = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "prompt",
+ });
+ expect(prompt.map((a) => a.name)).toEqual(["prompt-automation"]);
+ });
+
+ it("merges trigger.eventActions into the filter as a synthetic action condition", async () => {
+ const { project, caller } = await prepare();
+
+ await createAutomation({
+ projectId: project.id,
+ name: "created-only-automation",
+ eventSource: "prompt",
+ filter: [],
+ eventActions: ["created"],
+ });
+
+ const created = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "prompt",
+ matches: { action: "created" },
+ });
+ expect(created.map((a) => a.name)).toEqual(["created-only-automation"]);
+
+ const updated = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "prompt",
+ matches: { action: "updated" },
+ });
+ expect(updated).toEqual([]);
+ });
+
+ it("returns triggers as-is when matches is omitted", async () => {
+ const { project, caller } = await prepare();
+
+ await createAutomation({
+ projectId: project.id,
+ name: "monitor-automation",
+ eventSource: "monitor",
+ filter: [
+ {
+ type: "string",
+ column: "severity",
+ operator: "=",
+ value: "warning",
+ },
+ ],
+ });
+
+ const response = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "monitor",
+ });
+
+ expect(response.map((a) => a.name)).toEqual(["monitor-automation"]);
+ });
+
+ it.each([
+ {
+ label: "severity",
+ filter: {
+ type: "string",
+ column: "severity",
+ operator: "=",
+ value: "warning",
+ },
+ matching: { severity: "warning" },
+ nonMatching: { severity: "ok" },
+ },
+ {
+ label: "monitorId",
+ filter: {
+ type: "string",
+ column: "monitorId",
+ operator: "=",
+ value: "monitor-123",
+ },
+ matching: { monitorId: "monitor-123" },
+ nonMatching: { monitorId: "monitor-999" },
+ },
+ {
+ label: "monitorName",
+ filter: {
+ type: "string",
+ column: "monitorName",
+ operator: "contains",
+ value: "p95",
+ },
+ matching: { monitorName: "API p95 latency" },
+ nonMatching: { monitorName: "error rate" },
+ },
+ {
+ label: "tags",
+ filter: {
+ type: "arrayOptions",
+ column: "tags",
+ operator: "any of",
+ value: ["prod", "edge"],
+ },
+ matching: { tags: ["prod"] },
+ nonMatching: { tags: ["staging"] },
+ },
+ ])(
+ "monitor: $label filter matches and rejects",
+ async ({ filter, matching, nonMatching }) => {
+ const { project, caller } = await prepare();
+
+ await createAutomation({
+ projectId: project.id,
+ name: "filtered-monitor-automation",
+ eventSource: "monitor",
+ filter: [filter],
+ });
+
+ const matched = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "monitor",
+ matches: matching,
+ });
+ expect(matched.map((a) => a.name)).toEqual([
+ "filtered-monitor-automation",
+ ]);
+
+ const rejected = await caller.automations.getAutomations({
+ projectId: project.id,
+ eventSource: "monitor",
+ matches: nonMatching,
+ });
+ expect(rejected).toEqual([]);
+ },
+ );
+ });
});
describe("automations.getAutomation", () => {
diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.ts
index eb38dae724..0111ba7c60 100644
--- a/web/src/features/automations/server/router.ts
+++ b/web/src/features/automations/server/router.ts
@@ -11,6 +11,7 @@ import {
convertToSafeWebhookConfig,
isGitHubDispatchAction,
convertToSafeGitHubDispatchConfig,
+ TriggerEventSourceSchema,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { v4 } from "uuid";
@@ -139,7 +140,13 @@ export const automationsRouter = createTRPCRouter({
}),
getAutomations: protectedProjectProcedure
- .input(z.object({ projectId: z.string() }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ eventSource: TriggerEventSourceSchema.optional(),
+ matches: z.record(z.string(), z.unknown()).optional(),
+ }),
+ )
.query(async ({ ctx, input }) => {
// Check if user has at least read access to automations
throwIfNoProjectAccess({
@@ -150,6 +157,8 @@ export const automationsRouter = createTRPCRouter({
return await getAutomations({
projectId: input.projectId,
+ eventSource: input.eventSource,
+ matches: input.matches,
});
}),
diff --git a/worker/src/features/entityChange/promptVersionProcessor.ts b/worker/src/features/entityChange/promptVersionProcessor.ts
index 77dd3b2c44..77b78fe34f 100644
--- a/worker/src/features/entityChange/promptVersionProcessor.ts
+++ b/worker/src/features/entityChange/promptVersionProcessor.ts
@@ -1,6 +1,5 @@
import {
type TriggerEventAction,
- type FilterState,
jsonSchemaNullable,
InternalServerError,
} from "@langfuse/shared";
@@ -11,7 +10,7 @@ import {
WebhookQueue,
QueueName,
QueueJobs,
- InMemoryFilterService,
+ matchesTriggerFilter,
type PromptResult,
getAutomations,
EntityChangeEventType,
@@ -51,46 +50,9 @@ export const promptVersionProcessor = async (
// Process each trigger
for (const trigger of triggers) {
try {
- // Create a unified data object that includes both prompt data and the action
- const eventData = {
- ...event.prompt,
- action: event.action,
- };
-
- // Create a field mapper for all data including action
- const fieldMapper = (data: typeof eventData, column: string) => {
- switch (column) {
- case "action":
- return data.action;
- case "Name":
- return data.name;
- default:
- return undefined;
- }
- };
-
- // Merge eventActions into the filter so InMemoryFilterService handles
- // everything in one place. Done here rather than in convertTriggerToDomain
- // because that function also serves the UI — injecting a synthetic condition
- // there would corrupt the edit form and write it back to the DB on save.
- const mergedFilter: FilterState =
- trigger.eventActions.length > 0
- ? [
- ...trigger.filter,
- {
- column: "action",
- operator: "any of",
- type: "stringOptions",
- value: trigger.eventActions,
- },
- ]
- : trigger.filter;
-
- // Use InMemoryFilterService for all filtering including actions
- const eventMatches = InMemoryFilterService.evaluateFilter(
- eventData,
- mergedFilter,
- fieldMapper,
+ const eventMatches = matchesTriggerFilter(
+ { Name: event.prompt.name, action: event.action },
+ trigger,
);
if (!eventMatches) {