🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(prompts): return conflict for concurrent version creation (#15923)
Max Deichmann40b18fd61894
diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.tsindex 4df48a3ace..c23e1bed3c 100644--- a/web/src/__tests__/server/prompts-trpc.servertest.ts+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts@@ -1,7 +1,7 @@import { disconnectQueues } from "@/src/__tests__/test-utils";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Prisma } from "@langfuse/shared/src/db";import {createOrgProjectAndApiKey,EntityChangeQueue,@@ -95,6 +95,39 @@ describe("prompts trpc", () => {afterAll(async () => {await disconnectQueues();});+ describe("prompts.create", () => {+ it("returns CONFLICT when concurrent requests allocate the same prompt version", async () => {+ const { project, caller } = await prepare();+ const transactionSpy = vi+ .spyOn(prisma, "$transaction")+ .mockRejectedValueOnce(+ new Prisma.PrismaClientKnownRequestError(+ "Unique constraint failed on the fields: (`project_id`,`name`,`version`)",+ {+ code: "P2002",+ clientVersion: "test",+ meta: { target: ["project_id", "name", "version"] },+ },+ ),+ );++ try {+ await expect(+ caller.prompts.create({+ projectId: project.id,+ name: `concurrent-${v4()}`,+ prompt: "test",+ type: PromptType.Text,+ labels: [],+ config: {},+ }),+ ).rejects.toMatchObject({ code: "CONFLICT" });+ } finally {+ transactionSpy.mockRestore();+ }+ });+ });+describe("prompts.all input validation", () => {it.each([{diff --git a/web/src/__tests__/server/prompts.v1.servertest.ts b/web/src/__tests__/server/prompts.v1.servertest.tsindex aa6146660c..bcf0b18715 100644--- a/web/src/__tests__/server/prompts.v1.servertest.ts+++ b/web/src/__tests__/server/prompts.v1.servertest.ts@@ -1,4 +1,4 @@-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Prisma } from "@langfuse/shared/src/db";import { makeAPICall } from "@/src/__tests__/test-utils";import { v4 as uuidv4, v4 } from "uuid";import { type Prompt, PromptType } from "@langfuse/shared";@@ -10,6 +10,7 @@ import {createOrgProjectAndApiKey,getObservationById,} from "@langfuse/shared/src/server";+import { createPromptForApi } from "@/src/features/prompts/server/prompt-api-service";describe("/api/public/prompts API Endpoint", () => {let auth: string;@@ -26,6 +27,42 @@ describe("/api/public/prompts API Endpoint", () => {projectId = setup.projectId;});+ it("keeps prompt version conflicts as invalid public API requests", async () => {+ const transactionSpy = vi+ .spyOn(prisma, "$transaction")+ .mockRejectedValueOnce(+ new Prisma.PrismaClientKnownRequestError(+ "Unique constraint failed on the fields: (`project_id`,`name`,`version`)",+ {+ code: "P2002",+ clientVersion: "test",+ meta: { target: ["project_id", "name", "version"] },+ },+ ),+ );++ try {+ await expect(+ createPromptForApi({+ context: {+ projectId,+ orgId: "test-org",+ apiKeyId: "test-api-key",+ },+ input: {+ name: "concurrent-prompt",+ prompt: "test",+ type: PromptType.Text,+ labels: [],+ config: {},+ },+ }),+ ).rejects.toMatchObject({ httpCode: 400 });+ } finally {+ transactionSpy.mockRestore();+ }+ });+it("should fetch a prompt", async () => {const promptId = uuidv4();diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.tsindex 607d117315..6ae2a90344 100644--- a/web/src/features/prompts/server/actions/createPrompt.ts+++ b/web/src/features/prompts/server/actions/createPrompt.ts@@ -1,6 +1,7 @@import { v4 as uuidv4 } from "uuid";import {InvalidRequestError,+ LangfuseConflictError,parsePromptDependencyTags,jsonSchema,type PromptDependency,@@ -10,7 +11,7 @@ import {PromptType,extractVariables,} from "@langfuse/shared";-import { type PrismaClient } from "@langfuse/shared/src/db";+import { type PrismaClient, Prisma } from "@langfuse/shared/src/db";import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/server/utils/updatePromptLabels";import { updatePromptTagsOnAllVersions } from "@/src/features/prompts/server/utils/updatePromptTags";import {@@ -51,6 +52,22 @@ type DuplicateFolderParams = {user?: { id: string; name: string | null; email: string | null };};+const isPromptVersionConflict = (error: unknown): boolean => {+ if (+ !(error instanceof Prisma.PrismaClientKnownRequestError) ||+ error.code !== "P2002"+ ) {+ return false;+ }++ const target = error.meta?.target;++ return (+ Array.isArray(target) &&+ ["project_id", "name", "version"].every((column) => target.includes(column))+ );+};+const extractChatVariableAndPlaceholderNames = (chatPrompt: Array<any>,): { variables: string[]; placeholders: string[] } => {@@ -202,10 +219,22 @@ export const createPrompt = async ({}// Create prompt and update previous prompt versions- const [createdPrompt] = (await prisma.$transaction(create)) as [- Prompt,- ...PromptDependency[],- ];+ let transactionResult: [Prompt, ...PromptDependency[]];+ try {+ transactionResult = (await prisma.$transaction(create)) as [+ Prompt,+ ...PromptDependency[],+ ];+ } catch (error) {+ if (isPromptVersionConflict(error)) {+ throw new LangfuseConflictError(+ "A prompt version was created concurrently. Please retry.",+ );+ }++ throw error;+ }+ const [createdPrompt] = transactionResult;// Once the transaction commits, side-effect failures must not report the// persisted prompt as failed and cause callers to create another version.diff --git a/web/src/features/prompts/server/prompt-api-service.ts b/web/src/features/prompts/server/prompt-api-service.tsindex f28cccfc5c..00b0a60a4b 100644--- a/web/src/features/prompts/server/prompt-api-service.ts+++ b/web/src/features/prompts/server/prompt-api-service.ts@@ -5,7 +5,11 @@ import type {GetPromptsMetaSchema,Prompt,} from "@langfuse/shared";-import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";+import {+ InvalidRequestError,+ LangfuseConflictError,+ LangfuseNotFoundError,+} from "@langfuse/shared";import type { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";@@ -50,6 +54,12 @@ export const createPromptForApi = async ({createdBy: "API",prisma,}).catch((err) => {+ const promptVersionConflictMessage = `Failed to create prompt '${input.name}' due to unique constraint failure. This is likely due to too many concurrent prompt creations for this prompt name. Please add a delay.`;++ if (err instanceof LangfuseConflictError) {+ throw new InvalidRequestError(promptVersionConflictMessage);+ }+if (typeof err === "object" &&err?.constructor.name === "PrismaClientKnownRequestError" &&@@ -57,9 +67,7 @@ export const createPromptForApi = async ({// Unique constraint failed: https://www.prisma.io/docs/orm/reference/error-reference#p2002err.code === "P2002") {- throw new InvalidRequestError(- `Failed to create prompt '${input.name}' due to unique constraint failure. This is likely due to too many concurrent prompt creations for this prompt name. Please add a delay.`,- );+ throw new InvalidRequestError(promptVersionConflictMessage);}throw err;diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex ef41c9b160..c18880505f 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -56,6 +56,7 @@ const buildPathPrefixFilter = (pathPrefix?: string): Prisma.Sql => {const escapedPathPrefix = escapeSqlLikePattern(pathPrefix);return Prisma.sql` AND (p.name LIKE ${`${escapedPathPrefix}/%`} ESCAPE '\\' OR p.name = ${pathPrefix})`;};+const PromptFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedurefilter: z.array(singleFilter),