Skip to content

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

fix(prompts): guard prompt dependency graph integrity (#14465)

Hassieb Pakzada75f6a7d6a51
diff --git a/packages/shared/src/errors/BaseError.ts b/packages/shared/src/errors/BaseError.ts
index 23c8d3b072..e3af98c8ec 100644
--- a/packages/shared/src/errors/BaseError.ts
+++ b/packages/shared/src/errors/BaseError.ts
@@ -25,3 +25,16 @@ export class BaseError extends Error {
return this.httpCode >= 400 && this.httpCode < 500;
}
}
+
+export const isBaseError = (error: unknown): error is BaseError => {
+ if (error instanceof BaseError) return true;
+ if (!(error instanceof Error)) return false;
+
+ const candidate = error as Partial<BaseError>;
+
+ return (
+ typeof candidate.httpCode === "number" &&
+ typeof candidate.isOperational === "boolean" &&
+ typeof candidate.isUserError === "function"
+ );
+};
diff --git a/packages/shared/src/errors/index.ts b/packages/shared/src/errors/index.ts
index 4834573bbc..1bf12c806d 100644
--- a/packages/shared/src/errors/index.ts
+++ b/packages/shared/src/errors/index.ts
@@ -1,4 +1,4 @@
-export { BaseError } from "./BaseError";
+export { BaseError, isBaseError } from "./BaseError";
export { LangfuseNotFoundError } from "./NotFoundError";
export { InvalidRequestError } from "./InvalidRequestError";
export { UnauthorizedError } from "./UnauthorizedError";
diff --git a/packages/shared/src/server/services/PromptService/index.ts b/packages/shared/src/server/services/PromptService/index.ts
index a7c47d4391..ab5bc882af 100644
--- a/packages/shared/src/server/services/PromptService/index.ts
+++ b/packages/shared/src/server/services/PromptService/index.ts
@@ -1,9 +1,10 @@
-import { Prompt, PrismaClient } from "@prisma/client";
import { Redis, Cluster } from "ioredis";
import { randomBytes } from "crypto";
import { env } from "../../../env";
import { logger } from "../../logger";
import { escapeRegex } from "./utils";
+import { LangfuseConflictError } from "../../../errors";
+import { type Prisma, type PrismaClient, type Prompt } from "../../../db";
import {
PromptGraph,
PromptParams,
@@ -16,6 +17,7 @@ import {
import { ParsedPromptDependencyTag } from "../../../features/prompts/parsePromptDependencyTags";
export const MAX_PROMPT_NESTING_DEPTH = 5;
+type PrismaClientOrTransaction = PrismaClient | Prisma.TransactionClient;
export class PromptService {
private cacheEnabled: boolean;
@@ -26,7 +28,7 @@ export class PromptService {
private epochTtlSeconds = 7 * 24 * 60 * 60;
constructor(
- private prisma: PrismaClient,
+ private prisma: PrismaClientOrTransaction,
private redis: Redis | Cluster | null,
private metricIncrementer?: // used for otel metrics
@@ -256,7 +258,7 @@ export class PromptService {
) => {
// Nesting depth check
if (level >= MAX_PROMPT_NESTING_DEPTH) {
- throw Error(
+ throw new LangfuseConflictError(
`Maximum nesting depth exceeded (${MAX_PROMPT_NESTING_DEPTH})`,
);
}
@@ -267,7 +269,7 @@ export class PromptService {
(currentPrompt.name === parentPrompt.name &&
currentPrompt.id !== parentPrompt.id) // ensure that the parent prompt cannot reference a prompt of the same name but different version
) {
- throw Error(
+ throw new LangfuseConflictError(
`Circular dependency detected involving prompt '${currentPrompt.name}' version ${currentPrompt.version}`,
);
}
@@ -289,15 +291,27 @@ export class PromptService {
childVersion: true,
},
})
- ).map(
- (dep) =>
- ({
+ ).map((dep) => {
+ if (dep.childVersion !== null) {
+ return {
name: dep.childName,
- ...(dep.childVersion
- ? { type: "version", version: dep.childVersion }
- : { type: "label", label: dep.childLabel }),
- }) as ParsedPromptDependencyTag,
- );
+ type: "version",
+ version: dep.childVersion,
+ } as ParsedPromptDependencyTag;
+ }
+
+ if (dep.childLabel !== null) {
+ return {
+ name: dep.childName,
+ type: "label",
+ label: dep.childLabel,
+ } as ParsedPromptDependencyTag;
+ }
+
+ throw new LangfuseConflictError(
+ `Prompt dependency is malformed: ${dep.childName}`,
+ );
+ });
}
if (promptDependencies && promptDependencies.length) {
@@ -319,9 +333,13 @@ export class PromptService {
const logName = `${dep.name} - ${dep.type} ${dep.type === "version" ? dep.version : dep.label}`;
if (!depPrompt)
- throw Error(`Prompt dependency not found: ${logName}`);
+ throw new LangfuseConflictError(
+ `Prompt dependency not found: ${logName}`,
+ );
if (depPrompt.type !== "text")
- throw Error(`Prompt dependency is not a text prompt: ${logName}`);
+ throw new LangfuseConflictError(
+ `Prompt dependency is not a text prompt: ${logName}`,
+ );
// side-effect: populate adjacency list to return later as well
graph.dependencies[currentPrompt.id] ??= []; // initializes an empty list if it does not exist yet
diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.ts
index b5dfdf1aef..f2411c8b5f 100644
--- a/web/src/__tests__/server/prompts-trpc.servertest.ts
+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts
@@ -754,6 +754,62 @@ describe("prompts trpc", () => {
);
});
});
+
+ it("should not delete an unlabeled prompt version referenced by version", async () => {
+ const { project, caller } = await prepare();
+ const childName = `test-prompt-delete-unlabeled-dependency-${v4()}`;
+ const parentName = `test-prompt-delete-unlabeled-dependent-${v4()}`;
+
+ const childPrompt = await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: childName,
+ version: 1,
+ type: "text",
+ prompt: "child content",
+ createdBy: "test-user",
+ labels: [],
+ },
+ });
+
+ const parentPrompt = await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: parentName,
+ version: 1,
+ type: "text",
+ prompt: `Depends on @@@langfusePrompt:name=${childName}|version=1@@@`,
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ });
+
+ await prisma.promptDependency.create({
+ data: {
+ projectId: project.id,
+ parentId: parentPrompt.id,
+ childName,
+ childVersion: 1,
+ },
+ });
+
+ await expect(
+ caller.prompts.deleteVersion({
+ projectId: project.id,
+ promptVersionId: childPrompt.id,
+ }),
+ ).rejects.toThrow(/depending on the prompt version/);
+
+ const remainingChild = await prisma.prompt.findUnique({
+ where: {
+ id: childPrompt.id,
+ projectId: project.id,
+ },
+ });
+ expect(remainingChild).not.toBeNull();
+ });
});
describe("prompts.duplicatePrompt", () => {
@@ -1638,5 +1694,81 @@ describe("prompts trpc", () => {
}),
).rejects.toThrow(/already exist/i);
});
+
+ it("should roll back latest-only duplication when a rewritten label dependency would be missing", async () => {
+ const { project, caller } = await prepare();
+ const folderPrefix = `dup-missing-label-${v4().slice(0, 8)}`;
+ const sourcePath = `${folderPrefix}/source`;
+ const targetPath = `${folderPrefix}/copy`;
+ const parentName = `${sourcePath}/parent`;
+ const childName = `${sourcePath}/child`;
+
+ const parentPrompt = await prisma.prompt.create({
+ data: {
+ id: v4(),
+ projectId: project.id,
+ name: parentName,
+ version: 1,
+ type: "text",
+ prompt: `Depends on @@@langfusePrompt:name=${childName}|label=cause@@@`,
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ });
+
+ await prisma.prompt.createMany({
+ data: [
+ {
+ id: v4(),
+ projectId: project.id,
+ name: childName,
+ version: 1,
+ type: "text",
+ prompt: "cause-labeled child",
+ createdBy: "test-user",
+ labels: ["cause"],
+ },
+ {
+ id: v4(),
+ projectId: project.id,
+ name: childName,
+ version: 2,
+ type: "text",
+ prompt: "latest child",
+ createdBy: "test-user",
+ labels: ["latest"],
+ },
+ ],
+ });
+
+ await prisma.promptDependency.create({
+ data: {
+ projectId: project.id,
+ parentId: parentPrompt.id,
+ childName,
+ childLabel: "cause",
+ },
+ });
+
+ await expect(
+ caller.prompts.duplicateFolder({
+ projectId: project.id,
+ sourcePath,
+ targetPath,
+ isSingleVersion: true,
+ rewritePromptReferences: true,
+ }),
+ ).rejects.toThrow(/Copy all versions or disable reference rewriting/);
+
+ const copiedPrompts = await prisma.prompt.findMany({
+ where: {
+ projectId: project.id,
+ name: {
+ startsWith: `${targetPath}/`,
+ },
+ },
+ });
+ expect(copiedPrompts).toHaveLength(0);
+ });
});
});
diff --git a/web/src/__tests__/server/prompts.v2.servertest.ts b/web/src/__tests__/server/prompts.v2.servertest.ts
index 1898ed8783..95eb5c4d1e 100644
--- a/web/src/__tests__/server/prompts.v2.servertest.ts
+++ b/web/src/__tests__/server/prompts.v2.servertest.ts
@@ -1,5 +1,7 @@
import { prisma } from "@langfuse/shared/src/db";
import { disconnectQueues, makeAPICall } from "@/src/__tests__/test-utils";
+import type { NextApiRequest, NextApiResponse } from "next";
+import { createMocks } from "node-mocks-http";
import { v4 as uuidv4, v4 } from "uuid";
import {
PromptSchema,
@@ -21,6 +23,7 @@ import {
import { randomUUID } from "node:crypto";
import waitForExpect from "wait-for-expect";
import { createPrompt } from "@/src/features/prompts/server/actions/createPrompt";
+import { promptNameHandler } from "@/src/features/prompts/server/handlers/promptNameHandler";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
const baseURI = "/api/public/v2/prompts";
@@ -1889,6 +1892,51 @@ describe("/api/public/v2/prompts API Endpoint", () => {
expect(body.prompt).toBe(parentContent);
expect(body.resolutionGraph).toBeNull();
});
+
+ it("should return 409 when resolve=true and a stored dependency is missing", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+
+ const parentPromptName = "parent-prompt-" + nanoid();
+ const missingChildName = "missing-child-prompt-" + nanoid();
+ const parentContent = `Parent: @@@langfusePrompt:name=${missingChildName}|version=1@@@`;
+
+ const parentPrompt = await createPromptInDB({
+ name: parentPromptName,
+ prompt: parentContent,
+ labels: ["production"],
+ version: 1,
+ config: {},
+ projectId,
+ createdBy: "user-1",
+ });
+
+ await prisma.promptDependency.create({
+ data: {
+ projectId,
+ parentId: parentPrompt.id,
+ childName: missingChildName,
+ childVersion: 1,
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ query: {
+ promptName: parentPromptName,
+ version: "1",
+ },
+ headers: {
+ authorization: auth,
+ },
+ });
+
+ await promptNameHandler(req, res);
+
+ expect(res._getStatusCode()).toBe(409);
+ expect(JSON.stringify(res._getJSONData())).toContain(
+ "Prompt dependency not found",
+ );
+ });
});
});
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index eada68bbf2..ef483ef3f8 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -19,6 +19,7 @@ import {
escapeSqlLikePattern,
redis,
extractPlaceholderNames,
+ type PromptResult,
} from "@langfuse/shared/src/server";
import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";
@@ -517,33 +518,105 @@ export const duplicateFolder = async ({
}
}
- await prisma.$transaction(async (tx) => {
+ if (rewritePromptReferences && isSingleVersion) {
+ for (const prompt of sourcePrompts) {
+ if (oldToNewIdMap[prompt.id] === undefined) continue;
+
+ for (const dep of prompt.PromptDependency) {
+ const duplicatedDependencyName = duplicatedPromptNames.get(
+ dep.childName,
+ );
+ if (!duplicatedDependencyName) continue;
+
+ const dependencyVersions = promptsByName.get(dep.childName);
+ const copiedSourceVersion =
+ dependencyVersions?.find((version) =>
+ version.labels.includes(LATEST_PROMPT_LABEL),
+ ) ??
+ dependencyVersions?.reduce((a, b) => (a.version > b.version ? a : b));
+
+ const originalReference =
+ dep.childVersion !== null
+ ? `${dep.childName}|version=${dep.childVersion}`
+ : `${dep.childName}|label=${dep.childLabel}`;
+
+ const throwInvalidRewrite = (): never => {
+ throw new InvalidRequestError(
+ `Cannot duplicate folder with latest-only copies and rewritten prompt references. Reference "${originalReference}" would not point to an equivalent dependency in the copied folder. Copy all versions or disable reference rewriting.`,
+ );
+ };
+
+ if (!copiedSourceVersion) {
+ throwInvalidRewrite();
+ }
+
+ const copiedVersion = copiedSourceVersion!;
+
+ if (dep.childVersion !== null) {
+ if (dep.childVersion !== copiedVersion.version) {
+ throwInvalidRewrite();
+ }
+ } else if (dep.childLabel !== null) {
+ if (!copiedVersion.labels.includes(dep.childLabel)) {
+ throwInvalidRewrite();
+ }
+ } else {
+ throwInvalidRewrite();
+ }
+ }
+ }
+ }
+
+ const promptDependenciesToCreate = sourcePrompts
+ .filter((prompt) => oldToNewIdMap[prompt.id] !== undefined)
+ .flatMap((prompt) =>
+ prompt.PromptDependency.map((dep) => {
+ const duplicatedDependencyName = rewritePromptReferences
+ ? duplicatedPromptNames.get(dep.childName)
+ : undefined;
+
+ return {
+ projectId,
+ parentId: oldToNewIdMap[prompt.id],
+ childName: duplicatedDependencyName ?? dep.childName,
+ childVersion:
+ duplicatedDependencyName &&
+ dep.childVersion !== null &&
+ isSingleVersion
+ ? 1
+ : dep.childVersion,
+ childLabel: dep.childLabel,
+ };
+ }),
+ );
+
+ const resolvedPromptsToCreate = await prisma.$transaction(async (tx) => {
await tx.prompt.createMany({
data: allPromptsToCreate,
});
- await tx.promptDependency.createMany({
- data: sourcePrompts
- .filter((prompt) => oldToNewIdMap[prompt.id] !== undefined)
- .flatMap((prompt) =>
- prompt.PromptDependency.map((dep) => {
- const duplicatedDependencyName = rewritePromptReferences
- ? duplicatedPromptNames.get(dep.childName)
- : undefined;
-
- return {
- projectId,
- parentId: oldToNewIdMap[prompt.id],
- childName: duplicatedDependencyName ?? dep.childName,
- childVersion:
- duplicatedDependencyName && dep.childVersion && isSingleVersion
- ? 1
- : dep.childVersion,
- childLabel: dep.childLabel,
- };
- }),
- ),
- });
+ if (promptDependenciesToCreate.length > 0) {
+ await tx.promptDependency.createMany({
+ data: promptDependenciesToCreate,
+ });
+ }
+
+ const promptService = new PromptService(tx, redis);
+
+ return Promise.all(
+ allPromptsToCreate.map(async (prompt): Promise<PromptResult> => {
+ const promptGraph = await promptService.buildAndResolvePromptGraph({
+ projectId,
+ parentPrompt: prompt,
+ });
+
+ return {
+ ...prompt,
+ prompt: promptGraph.resolvedPrompt,
+ resolutionGraph: promptGraph.graph,
+ } as PromptResult;
+ }),
+ );
});
const promptService = new PromptService(prisma, redis);
@@ -551,12 +624,8 @@ export const duplicateFolder = async ({
await promptService.invalidateCache({ projectId });
await Promise.all(
- allPromptsToCreate.map(async (prompt) =>
- promptChangeEventSourcing(
- await promptService.resolvePrompt(prompt),
- "created",
- user,
- ),
+ resolvedPromptsToCreate.map((prompt) =>
+ promptChangeEventSourcing(prompt, "created", user),
),
);
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index d0a4b04589..f28450847e 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -685,47 +685,48 @@ export const promptRouter = createTRPCRouter({
});
}
- if (labels.length > 0) {
- const dependents = await ctx.prisma.$queryRaw<
- {
- parent_name: string;
- parent_version: number;
- child_version: number;
- child_label: string;
- }[]
- >`
- SELECT
- p."name" AS "parent_name",
- p."version" AS "parent_version",
- pd."child_version" AS "child_version",
- pd."child_label" AS "child_label"
- FROM
- prompt_dependencies pd
- INNER JOIN prompts p ON p.id = pd.parent_id
- WHERE
- p.project_id = ${projectId}
- AND pd.project_id = ${projectId}
- AND pd.child_name = ${promptName}
- AND (
- (pd."child_version" IS NOT NULL AND pd."child_version" = ${version})
- OR
- (pd."child_label" IS NOT NULL AND pd."child_label" IN (${Prisma.join(labels)}))
- )
- `;
+ const dependents = await ctx.prisma.$queryRaw<
+ {
+ parent_name: string;
+ parent_version: number;
+ child_version: number;
+ child_label: string;
+ }[]
+ >`
+ SELECT
+ p."name" AS "parent_name",
+ p."version" AS "parent_version",
+ pd."child_version" AS "child_version",
+ pd."child_label" AS "child_label"
+ FROM
+ prompt_dependencies pd
+ INNER JOIN prompts p ON p.id = pd.parent_id
+ WHERE
+ p.project_id = ${projectId}
+ AND pd.project_id = ${projectId}
+ AND pd.child_name = ${promptName}
+ AND (
+ (pd."child_version" IS NOT NULL AND pd."child_version" = ${version})
+ ${
+ labels.length > 0
+ ? Prisma.sql`OR (pd."child_label" IS NOT NULL AND pd."child_label" IN (${Prisma.join(labels)}))`
+ : Prisma.empty
+ }
+ )
+ `;
- if (dependents.length > 0) {
- const dependencyMessages = dependents
- .map(
- (d) =>
- `${d.parent_name} v${d.parent_version} depends on ${promptName} ${d.child_version ? `v${d.child_version}` : d.child_label}`,
- )
- .join("\n");
+ if (dependents.length > 0) {
+ const dependencyMessages = dependents
+ .map(
+ (d) =>
+ `${d.parent_name} v${d.parent_version} depends on ${promptName} ${d.child_version ? `v${d.child_version}` : d.child_label}`,
+ )
+ .join("\n");
- throw new TRPCError({
- code: "CONFLICT",
- message: `Other prompts are depending on the prompt version you are trying to delete:\n\n${dependencyMessages}\n\nPlease delete the dependent prompts first.`,
- });
- }
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: `Other prompts are depending on the prompt version you are trying to delete:\n\n${dependencyMessages}\n\nPlease delete the dependent prompts first.`,
+ });
}
await auditLog(
diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.ts
index c7709d3527..4b70c5829f 100644
--- a/web/src/features/public-api/server/withMiddlewares.ts
+++ b/web/src/features/public-api/server/withMiddlewares.ts
@@ -3,7 +3,8 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { type NextApiRequest, type NextApiResponse } from "next";
import { type ZodError } from "zod";
import {
- BaseError,
+ type BaseError,
+ isBaseError,
LangfuseNotFoundError,
MethodNotAllowedError,
UnauthorizedError,
@@ -134,7 +135,7 @@ export function withMiddlewares(
}
if (options?.errorContract === unstablePublicEvalsErrorContract) {
- if (error instanceof BaseError) {
+ if (isBaseError(error)) {
logBaseError(error);
} else if (isZodError(error)) {
logger.warn(error);
@@ -142,7 +143,7 @@ export function withMiddlewares(
logger.error(error);
}
- if (error instanceof BaseError) {
+ if (isBaseError(error)) {
if (error.httpCode >= 500 && error.httpCode < 600) {
traceException(error);
}
@@ -156,7 +157,7 @@ export function withMiddlewares(
);
}
- if (error instanceof BaseError) {
+ if (isBaseError(error)) {
logBaseError(error);
if (error.httpCode >= 500 && error.httpCode < 600) {
traceException(error);
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index e3aa772286..189246eab6 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -93,7 +93,7 @@ import {
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
import { env } from "@/src/env.mjs";
-import { BaseError, parseIO } from "@langfuse/shared";
+import { isBaseError, parseIO } from "@langfuse/shared";
import { type Flag } from "@/src/features/feature-flags/types";
setUpSuperjson();
@@ -138,7 +138,7 @@ const t = initTRPC.context<typeof createTRPCContext>().create({
export const createTRPCRouter = t.router;
const resolveError = (error: TRPCError) => {
- if (error.cause instanceof BaseError) {
+ if (isBaseError(error.cause)) {
return {
code: getTRPCErrorCodeFromHTTPStatusCode(error.cause.httpCode),
httpStatus: error.cause.httpCode,