Skip to content

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

fix(prompts-api): make updates via API concurrency safe (#7287)

Hassieb Pakzad346e78778402
diff --git a/packages/shared/src/server/services/PromptService/index.ts b/packages/shared/src/server/services/PromptService/index.ts
index fcd208754c..ef4a0f8afa 100644
--- a/packages/shared/src/server/services/PromptService/index.ts
+++ b/packages/shared/src/server/services/PromptService/index.ts
@@ -157,6 +157,12 @@ export class PromptService {
}
}
+ /**
+ * Lock the cache so reads will go to the database and not to Redis
+ *
+ * This is useful in order to return consistent data during the
+ * invalidation of the cache where we are looping through the relevant cache keys
+ */
public async lockCache(
params: Pick<PromptParams, "projectId" | "promptName">,
): Promise<void> {
diff --git a/web/src/features/prompts/server/actions/updatePrompts.ts b/web/src/features/prompts/server/actions/updatePrompts.ts
index a27ab8c9a7..588b9a534c 100644
--- a/web/src/features/prompts/server/actions/updatePrompts.ts
+++ b/web/src/features/prompts/server/actions/updatePrompts.ts
@@ -21,101 +21,119 @@ export const updatePrompt = async (params: UpdatePromptParams) => {
try {
await promptService.lockCache({ projectId, promptName: promptName });
- const prompt = await promptService.getPrompt({
- projectId,
- promptName,
- version: promptVersion,
- label: undefined,
- });
-
- if (!prompt) {
- throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);
- }
+ const result = prisma.$transaction(async (tx) => {
+ const prompt = (
+ await tx.$queryRaw<
+ Array<{
+ id: string;
+ name: string;
+ version: number;
+ labels: string[];
+ }>
+ >`
+ SELECT
+ *
+ FROM
+ prompts
+ WHERE
+ project_id = ${projectId}
+ AND name = ${promptName}
+ AND version = ${promptVersion}
+ FOR UPDATE -- Important! This will lock the row for concurrent updates
+ `
+ )[0];
+
+ if (!prompt) {
+ throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);
+ }
- const newLabelsSet = new Set([...newLabels, ...prompt.labels]);
- const removedLabels = [];
+ const newLabelsSet = new Set([...newLabels, ...prompt.labels]);
+ const removedLabels = [];
- // Prompt labels cannot be removed here since the newLabelsSet includes the old labels
- // Keeping this dependent check below as a safeguard in case the above changes
- for (const oldLabel of prompt.labels) {
- if (!newLabelsSet.has(oldLabel)) {
- removedLabels.push(oldLabel);
+ // Prompt labels cannot be removed here since the newLabelsSet includes the old labels
+ // Keeping this dependent check below as a safeguard in case the above changes
+ for (const oldLabel of prompt.labels) {
+ if (!newLabelsSet.has(oldLabel)) {
+ removedLabels.push(oldLabel);
+ }
}
- }
-
- if (removedLabels.length > 0) {
- const dependents = await 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_label" IS NOT NULL AND pd."child_label" IN (${Prisma.join(removedLabels)})
- `;
-
- 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 InvalidRequestError(
- `Other prompts are depending on the prompt label you are trying to remove:\n\n${dependencyMessages}\n\nPlease delete the dependent prompts first.`,
- );
+
+ if (removedLabels.length > 0) {
+ const dependents = await tx.$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_label" IS NOT NULL AND pd."child_label" IN (${Prisma.join(removedLabels)})
+ `;
+
+ 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 InvalidRequestError(
+ `Other prompts are depending on the prompt label you are trying to remove:\n\n${dependencyMessages}\n\nPlease delete the dependent prompts first.`,
+ );
+ }
}
- }
-
- logger.info(
- `Setting labels for prompt: ${prompt.id}, ${prompt.name}, ${prompt.version}, ${JSON.stringify(
- Array.from(newLabelsSet),
- )}`,
- );
-
- const tx = [
- ...(await removeLabelsFromPreviousPromptVersions({
- prisma,
- projectId,
- promptName,
- labelsToRemove: [...new Set(newLabels)],
- })),
- prisma.prompt.update({
- where: {
- id: prompt.id,
+
+ logger.info(
+ `Setting labels for prompt: ${prompt.id}, ${prompt.name}, ${prompt.version}, ${JSON.stringify(
+ Array.from(newLabelsSet),
+ )}`,
+ );
+
+ const result = await Promise.all([
+ // Remove labels from other prompts
+ ...(await removeLabelsFromPreviousPromptVersions({
+ prisma: tx,
projectId,
- },
- data: {
- labels: {
- set: Array.from(newLabelsSet),
+ promptName,
+ labelsToRemove: [...new Set(newLabels)],
+ })),
+ // Update prompt
+ tx.prompt.update({
+ where: {
+ id: prompt.id,
+ projectId,
},
- },
- }),
- ];
-
- await promptService.invalidateCache({ projectId, promptName: promptName });
+ data: {
+ labels: {
+ set: Array.from(newLabelsSet),
+ },
+ },
+ }),
+ ]);
- const res = await prisma.$transaction(tx);
+ return result[result.length - 1];
+ });
+ await promptService.invalidateCache({ projectId, promptName: promptName });
await promptService.unlockCache({ projectId, promptName: promptName });
- return res[res.length - 1];
+ return result;
} catch (e) {
await promptService.unlockCache({ projectId, promptName: promptName });
+
throw e;
}
};
diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
index 6b61c540bb..018490ede6 100644
--- a/web/src/features/prompts/server/handlers/promptVersionHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
@@ -37,6 +37,7 @@ export const promptVersionHandler = withMiddlewares({
projectId: auth.scope.projectId,
orgId: auth.scope.orgId,
apiKeyId: auth.scope.apiKeyId,
+ after: prompt,
});
logger.info(`Prompt updated ${JSON.stringify(prompt)}`);
diff --git a/web/src/features/prompts/server/utils/updatePromptLabels.ts b/web/src/features/prompts/server/utils/updatePromptLabels.ts
index d751ff16a0..0925f52034 100644
--- a/web/src/features/prompts/server/utils/updatePromptLabels.ts
+++ b/web/src/features/prompts/server/utils/updatePromptLabels.ts
@@ -6,7 +6,10 @@ export const removeLabelsFromPreviousPromptVersions = async ({
promptName,
labelsToRemove,
}: {
- prisma: PrismaClient;
+ prisma: Omit<
+ PrismaClient,
+ "$connect" | "$disconnect" | "$on" | "$transaction" | "$use" | "$extends"
+ >;
projectId: string;
promptName: string;
labelsToRemove: string[];