Skip to content

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

fix(annotation-queues): Race-safety of `createAnnotationQueueForApi` (#13971)

Ben Bachem2f738af2bb17
diff --git a/web/src/__tests__/server/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.ts
index 227324d576..d1f1e195c0 100644
--- a/web/src/__tests__/server/mcp-tools-write.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-write.servertest.ts
@@ -36,6 +36,17 @@ import {
import { handleCreateTextPrompt } from "@/src/features/mcp/features/prompts/tools/createTextPrompt";
import { handleCreateChatPrompt } from "@/src/features/mcp/features/prompts/tools/createChatPrompt";
import { handleUpdatePromptLabels } from "@/src/features/mcp/features/prompts/tools/updatePromptLabels";
+import { handleCreateAnnotationQueue } from "@/src/features/mcp/features/annotationQueues/tools";
+
+const createScoreConfig = async (projectId: string) =>
+ prisma.scoreConfig.create({
+ data: {
+ id: nanoid(),
+ projectId,
+ name: `mcp-score-${nanoid()}`,
+ dataType: "NUMERIC",
+ },
+ });
describe("MCP Write Tools", () => {
describe("dataset tool schemas", () => {
@@ -54,6 +65,42 @@ describe("MCP Write Tools", () => {
});
});
+ describe("createAnnotationQueue tool", () => {
+ it("should create a basic annotation queue", async () => {
+ const { context, projectId } = await createMcpTestSetup();
+ const scoreConfig = await createScoreConfig(projectId);
+ const queueName = `mcp-queue-${nanoid()}`;
+
+ const result = (await handleCreateAnnotationQueue(
+ {
+ name: queueName,
+ description: "MCP queue",
+ scoreConfigIds: [scoreConfig.id],
+ },
+ context,
+ )) as {
+ id: string;
+ name: string;
+ description: string;
+ scoreConfigIds: string[];
+ };
+
+ expect(result.id).toBeDefined();
+ expect(result.name).toBe(queueName);
+ expect(result.description).toBe("MCP queue");
+ expect(result.scoreConfigIds).toEqual([scoreConfig.id]);
+
+ await expect(
+ prisma.annotationQueue.findUniqueOrThrow({
+ where: { id: result.id, projectId },
+ }),
+ ).resolves.toMatchObject({
+ name: queueName,
+ scoreConfigIds: [scoreConfig.id],
+ });
+ });
+ });
+
describe("createTextPrompt tool", () => {
it("should create a simple text prompt", async () => {
const { context } = await createMcpTestSetup();
diff --git a/web/src/features/annotation-queues/server/publicAnnotationQueueService.ts b/web/src/features/annotation-queues/server/publicAnnotationQueueService.ts
index 52174ebb70..e4e0d53ab1 100644
--- a/web/src/features/annotation-queues/server/publicAnnotationQueueService.ts
+++ b/web/src/features/annotation-queues/server/publicAnnotationQueueService.ts
@@ -16,6 +16,7 @@ import type {
import {
AnnotationQueueStatus,
InvalidRequestError,
+ LangfuseConflictError,
LangfuseNotFoundError,
MethodNotAllowedError,
Prisma,
@@ -96,31 +97,6 @@ const toAnnotationQueueItemApi = (item: {
updatedAt: item.updatedAt,
});
-const verifyScoreConfigsExist = async ({
- projectId,
- scoreConfigIds,
-}: {
- projectId: string;
- scoreConfigIds: string[];
-}) => {
- const scoreConfigs = await prisma.scoreConfig.findMany({
- where: {
- id: { in: scoreConfigIds },
- projectId,
- },
- select: {
- id: true,
- },
- });
-
- const scoreConfigIdSet = new Set(scoreConfigs.map((config) => config.id));
- if (scoreConfigIds.some((id) => !scoreConfigIdSet.has(id))) {
- throw new InvalidRequestError(
- "At least one of the score config IDs cannot be found for the given project.",
- );
- }
-};
-
export const getAnnotationQueueRecordOrThrow = async ({
projectId,
queueId,
@@ -195,43 +171,118 @@ export const createAnnotationQueueForApi = async ({
plan?: string;
input: CreateAnnotationQueueInput;
} & OptionalAuditScope) => {
- if (plan === "cloud:hobby") {
- const queueCount = await prisma.annotationQueue.count({
- where: { projectId },
+ const queue = await prisma
+ .$transaction(
+ async (tx) => {
+ if (plan === "cloud:hobby") {
+ const queueCount = await tx.annotationQueue.count({
+ where: { projectId },
+ });
+
+ if (queueCount >= 1) {
+ throw new MethodNotAllowedError(
+ "Maximum number of annotation queues reached on Hobby plan.",
+ );
+ }
+ }
+
+ const scoreConfigs = await tx.scoreConfig.findMany({
+ where: {
+ id: { in: input.scoreConfigIds },
+ projectId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const scoreConfigIdSet = new Set(
+ scoreConfigs.map((config) => config.id),
+ );
+ if (input.scoreConfigIds.some((id) => !scoreConfigIdSet.has(id))) {
+ throw new InvalidRequestError(
+ "At least one of the score config IDs cannot be found for the given project.",
+ );
+ }
+
+ return tx.annotationQueue.create({
+ data: {
+ projectId,
+ name: input.name,
+ description: input.description,
+ scoreConfigIds: input.scoreConfigIds,
+ },
+ });
+ },
+ { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
+ )
+ .catch(async (error) => {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ throw new InvalidRequestError("A queue with this name already exists.");
+ }
+
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2034"
+ ) {
+ const existingQueue = await prisma.annotationQueue.findFirst({
+ where: {
+ projectId,
+ name: input.name,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (existingQueue) {
+ throw new InvalidRequestError(
+ "A queue with this name already exists.",
+ );
+ }
+
+ if (plan === "cloud:hobby") {
+ const queueCount = await prisma.annotationQueue.count({
+ where: { projectId },
+ });
+
+ if (queueCount >= 1) {
+ throw new MethodNotAllowedError(
+ "Maximum number of annotation queues reached on Hobby plan.",
+ );
+ }
+ }
+
+ const scoreConfigs = await prisma.scoreConfig.findMany({
+ where: {
+ id: { in: input.scoreConfigIds },
+ projectId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ const scoreConfigIdSet = new Set(
+ scoreConfigs.map((config) => config.id),
+ );
+ if (input.scoreConfigIds.some((id) => !scoreConfigIdSet.has(id))) {
+ throw new InvalidRequestError(
+ "At least one of the score config IDs cannot be found for the given project.",
+ );
+ }
+
+ throw new LangfuseConflictError(
+ "Concurrent annotation queue creation conflict. Please retry.",
+ );
+ }
+
+ throw error;
});
- if (queueCount >= 1) {
- throw new MethodNotAllowedError(
- "Maximum number of annotation queues reached on Hobby plan.",
- );
- }
- }
-
- const existingQueue = await prisma.annotationQueue.findFirst({
- where: {
- projectId,
- name: input.name,
- },
- });
-
- if (existingQueue) {
- throw new InvalidRequestError("A queue with this name already exists.");
- }
-
- await verifyScoreConfigsExist({
- projectId,
- scoreConfigIds: input.scoreConfigIds,
- });
-
- const queue = await prisma.annotationQueue.create({
- data: {
- projectId,
- name: input.name,
- description: input.description,
- scoreConfigIds: input.scoreConfigIds,
- },
- });
-
if (auditScope) {
await auditLog({
action: "create",