Skip to content

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

fix(prompt-management): cache concurrency safety (#12363)

Hassieb Pakzad5d2427a4dbd6
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 0804dd2209..5bee7f4d1b 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -53,7 +53,7 @@ const EnvSchema = z.object({
LANGFUSE_CACHE_MODEL_MATCH_ENABLED: z.enum(["true", "false"]).default("true"),
LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS: z.coerce.number().default(86400), // 24 hours
LANGFUSE_CACHE_PROMPT_ENABLED: z.enum(["true", "false"]).default("true"),
- LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(300), // 5 minutes
+ LANGFUSE_CACHE_PROMPT_TTL_SECONDS: z.coerce.number().default(3600), // 1h
CLICKHOUSE_URL: z.string().url(),
CLICKHOUSE_READ_ONLY_URL: z.string().url().optional(),
CLICKHOUSE_EVENTS_READ_ONLY_URL: z.string().url().optional(),
diff --git a/packages/shared/src/server/services/PromptService/index.ts b/packages/shared/src/server/services/PromptService/index.ts
index 58e416090b..b2cb0a3f53 100644
--- a/packages/shared/src/server/services/PromptService/index.ts
+++ b/packages/shared/src/server/services/PromptService/index.ts
@@ -1,9 +1,9 @@
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 { safeMultiDel } from "../../redis/redis";
import {
PromptGraph,
PromptParams,
@@ -22,6 +22,10 @@ export class PromptService {
private cacheEnabled: boolean;
private ttlSeconds: number;
+ // Epoch keys live much longer than cache entries. 7 days gives inactive
+ // projects plenty of time while still cleaning up eventually.
+ private epochTtlSeconds = 7 * 24 * 60 * 60;
+
constructor(
private prisma: PrismaClient,
private redis: Redis | Cluster | null,
@@ -42,7 +46,7 @@ export class PromptService {
}
public async getPrompt(params: PromptParams): Promise<PromptResult | null> {
- if (await this.shouldUseCache(params)) {
+ if (this.cacheEnabled) {
const cachedPrompt = await this.getCachedPrompt(params);
this.incrementMetric(
@@ -60,7 +64,7 @@ export class PromptService {
const dbPrompt = await this.getDbPrompt(params);
- if ((await this.shouldUseCache(params)) && dbPrompt) {
+ if (this.cacheEnabled && dbPrompt) {
await this.cachePrompt({ ...params, prompt: dbPrompt });
this.logDebug("Successfully cached prompt for params", params);
@@ -126,24 +130,14 @@ export class PromptService {
};
}
- private async shouldUseCache(params: PromptParams): Promise<boolean> {
- if (!this.cacheEnabled) return false;
-
- const isLocked = await this.isCacheLocked(params);
-
- if (isLocked) {
- this.logInfo("Cache is locked for params", params);
- }
-
- return !isLocked;
- }
-
private async getCachedPrompt(
params: PromptParams,
): Promise<PromptResult | null> {
try {
- const key = this.getCacheKey(params);
- const value = await this.redis?.getex(key, "EX", this.ttlSeconds);
+ const key = await this.getCacheKey(params);
+ if (!key) return null;
+
+ const value = await this.redis?.get(key);
if (value) return JSON.parse(value) as PromptResult;
} catch (e) {
@@ -155,120 +149,72 @@ export class PromptService {
private async cachePrompt(params: PromptParams & { prompt: PromptResult }) {
try {
- const keyIndexKey = this.getKeyIndexKey(params);
- const key = this.getCacheKey(params);
+ const key = await this.getCacheKey(params);
+ if (!key) return;
+
const value = JSON.stringify(params.prompt);
- await this.redis?.sadd(keyIndexKey, key);
await this.redis?.set(key, value, "EX", this.ttlSeconds);
} catch (e) {
this.logError("Error caching prompt", e);
}
}
- /**
- * 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> {
- if (!this.cacheEnabled) return;
-
- const lockKey = this.getLockKey(params);
-
- try {
- await this.redis?.setex(lockKey, 30, "locked");
- } catch (e) {
- this.logError("Error locking cache key prefix", lockKey, e);
-
- throw e;
- }
- }
-
- public async unlockCache(
- params: Pick<PromptParams, "projectId" | "promptName">,
+ public async invalidateCache(
+ params: Pick<PromptParams, "projectId">,
): Promise<void> {
if (!this.cacheEnabled) return;
- const lockKey = this.getLockKey(params);
-
- try {
- await this.redis?.del(lockKey);
- } catch (e) {
- this.logError("Error unlocking cache key prefix", lockKey, e);
-
- // Don't re-throw error as lock TTL is short and it's not critical
- }
+ // Rotate the epoch token to move all prompt reads/writes to a fresh namespace.
+ // Old keys remain untouched and naturally expire via TTL.
+ await this.redis?.set(
+ this.getEpochKey(params),
+ this.newEpochToken(),
+ "EX",
+ this.epochTtlSeconds,
+ );
}
- private async isCacheLocked(
- params: Pick<PromptParams, "projectId" | "promptName">,
- ): Promise<boolean> {
- const lockKey = this.getLockKey(params);
+ private async getCacheKey(params: PromptParams): Promise<string | null> {
+ const epoch = await this.getOrCreateEpoch(params);
+ if (!epoch) return null;
- try {
- return Boolean(await this.redis?.exists(lockKey));
- } catch (e) {
- this.logError("Error checking if cache is locked", lockKey, e);
+ const prefix = this.getCacheKeyPrefix(params, epoch);
- return false;
- }
+ return `${prefix}:${params.version ?? params.label}`;
}
- private getLockKey(
+ private getCacheKeyPrefix(
params: Pick<PromptParams, "projectId" | "promptName">,
+ epoch: string,
): string {
- // Important to *pre*fix LOCK as otherwise it would be deleted by deleteKeysByPrefix
- return `LOCK:prompt:${params.projectId}`;
+ return `prompt:${params.projectId}:${epoch}:${params.promptName}`;
}
- public async invalidateCache(
- params: Pick<PromptParams, "projectId" | "promptName">,
- ): Promise<void> {
- if (!this.cacheEnabled) return;
+ private getEpochKey(params: Pick<PromptParams, "projectId">): string {
+ // Important: epoch is project-scoped (not prompt-scoped) because resolved prompts
+ // can include transitive dependencies across multiple prompt names.
+ return `prompt_cache_epoch:${params.projectId}`;
+ }
- const keyIndexKey = this.getKeyIndexKey(params);
- const keys = await this.redis?.smembers(keyIndexKey);
-
- /*
- * Previously, the cache key index was based on both projectId and promptName.
- * Now with prompt composability, we only use projectId for the key index.
- * When invalidating the cache, we delete all keys for a projectId.
- * For backwards compatibility, we also clear any existing entries in the old
- * key index format (projectId + promptName) to ensure consistent caching.
- */
- const legacyKeyIndexKey = `${keyIndexKey}:${params.promptName}`;
- const legacyKeys = await this.redis?.smembers(legacyKeyIndexKey);
-
- // Delete all keys for the prefix and the key index using safe multi-delete
- const keysToDelete = [
- ...(keys ?? []),
- keyIndexKey,
- ...(legacyKeys ?? []),
- legacyKeyIndexKey,
- ];
- await safeMultiDel(this.redis, keysToDelete);
+ private newEpochToken(): string {
+ // 48 bits of entropy in a compact URL-safe string (8 chars).
+ return randomBytes(6).toString("base64url");
}
- private getCacheKey(params: PromptParams): string {
- const prefix = this.getCacheKeyPrefix(params);
+ private async getOrCreateEpoch(
+ params: Pick<PromptParams, "projectId">,
+ ): Promise<string | null> {
+ const epochKey = this.getEpochKey(params);
- return `${prefix}:${params.version ?? params.label}`;
- }
+ const currentEpoch = await this.redis?.get(epochKey);
+ if (currentEpoch) return currentEpoch;
- private getCacheKeyPrefix(
- params: Pick<PromptParams, "projectId" | "promptName">,
- ): string {
- return `prompt:${params.projectId}:${params.promptName}`;
- }
+ const newEpoch = this.newEpochToken();
+ await this.redis?.set(epochKey, newEpoch, "EX", this.epochTtlSeconds, "NX");
- private getKeyIndexKey(
- params: Pick<PromptParams, "projectId" | "promptName">,
- ): string {
- return `prompt_key_index:${params.projectId}`;
+ // Return the winner value in case multiple requests initialize concurrently.
+ return (await this.redis?.get(epochKey)) ?? newEpoch;
}
public async buildAndResolvePromptGraph(params: {
@@ -422,10 +368,6 @@ export class PromptService {
logger.error(`[PromptService] ${message}`, ...args);
}
- private logInfo(message: string, ...args: any[]) {
- logger.info(`[PromptService] ${message}`, ...args);
- }
-
private logDebug(message: string, ...args: any[]) {
logger.debug(`[PromptService] ${message}`, ...args);
}
diff --git a/web/src/__e2e__/api.servertest.ts b/web/src/__e2e__/api.servertest.ts
index 70d3eadb1a..3979899c32 100644
--- a/web/src/__e2e__/api.servertest.ts
+++ b/web/src/__e2e__/api.servertest.ts
@@ -298,8 +298,13 @@ describe("Prompts endpoint", () => {
expect(validatedPrompt.name).toBe(promptName);
- const redisKey = `prompt:7a88fb47-b4e2-43b8-a06c-a5ce950dc53a:${promptName}:${validatedPrompt.labels[0]}`;
- const redisValue = await redis?.get(redisKey);
+ const pattern = `prompt:7a88fb47-b4e2-43b8-a06c-a5ce950dc53a:*:${promptName}:${validatedPrompt.labels[0]}`;
+ const keys = await redis?.keys(pattern);
+ expect(keys?.length).toBe(1);
+
+ const key = keys?.[0] as string;
+
+ const redisValue = await redis?.get(key);
expect(redisValue).not.toBeNull();
if (!redisValue) {
diff --git a/web/src/__tests__/server/promptCache.servertest.ts b/web/src/__tests__/server/promptCache.servertest.ts
index 7091314687..6c4d6e38d6 100644
--- a/web/src/__tests__/server/promptCache.servertest.ts
+++ b/web/src/__tests__/server/promptCache.servertest.ts
@@ -38,14 +38,9 @@ describe("PromptService", () => {
} as unknown as jest.Mocked<PrismaClient>;
mockRedis = {
- getex: jest.fn(),
+ get: jest.fn().mockResolvedValue("epoch-1"),
set: jest.fn(),
- setex: jest.fn(),
del: jest.fn(),
- exists: jest.fn(),
- eval: jest.fn(),
- sadd: jest.fn(),
- smembers: jest.fn(),
} as unknown as jest.Mocked<Redis>;
mockMetricIncrementer = jest.fn();
@@ -60,8 +55,8 @@ describe("PromptService", () => {
describe("getPrompt", () => {
it("should return cached prompt if available", async () => {
- mockRedis.exists.mockResolvedValue(0);
- mockRedis.getex.mockResolvedValue(JSON.stringify(mockPrompt));
+ mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch
+ mockRedis.get.mockResolvedValueOnce(JSON.stringify(mockPrompt)); // cache read
const result = await promptService.getPrompt({
projectId: "project1",
@@ -75,9 +70,10 @@ describe("PromptService", () => {
});
it("should fetch from database if not in cache", async () => {
- mockRedis.exists.mockResolvedValue(0);
- mockRedis.getex.mockResolvedValue(null);
+ mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch for cache read
+ mockRedis.get.mockResolvedValueOnce(null); // cache miss
mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
+ mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch for cache write
const result = await promptService.getPrompt({
projectId: "project1",
@@ -94,75 +90,25 @@ describe("PromptService", () => {
);
expect(mockRedis.set).toHaveBeenCalledWith(
- "prompt:project1:testPrompt:1",
+ "prompt:project1:epoch-1:testPrompt:1",
JSON.stringify(mockPrompt),
"EX",
- 300,
- );
-
- expect(mockRedis.sadd).toHaveBeenCalledWith(
- "prompt_key_index:project1",
- "prompt:project1:testPrompt:1",
- );
- });
-
- it("should not use cache if locked", async () => {
- mockRedis.exists.mockResolvedValue(1);
- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
-
- const result = await promptService.getPrompt({
- projectId: "project1",
- promptName: "testPrompt",
- version: 1,
- label: undefined,
- });
-
- expect(result).toEqual(mockPrompt);
- expect(mockRedis.getex).not.toHaveBeenCalled();
- expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
- });
- });
-
- describe("lockCache", () => {
- it("should set a lock in Redis", async () => {
- await promptService.lockCache({
- projectId: "project1",
- promptName: "testPrompt",
- });
-
- expect(mockRedis.setex).toHaveBeenCalledWith(
- "LOCK:prompt:project1",
- 30,
- "locked",
+ expect.any(Number),
);
});
});
- describe("unlockCache", () => {
- it("should remove the lock from Redis", async () => {
- await promptService.unlockCache({
- projectId: "project1",
- promptName: "testPrompt",
- });
-
- expect(mockRedis.del).toHaveBeenCalledWith("LOCK:prompt:project1");
- });
- });
-
describe("invalidateCache", () => {
- it("should call deleteKeysByPrefix with correct prefix", async () => {
+ it("should rotate the epoch token for the project with TTL", async () => {
await promptService.invalidateCache({
projectId: "project1",
- promptName: "testPrompt",
});
- // Legacy index
- expect(mockRedis.smembers).toHaveBeenCalledWith(
- "prompt_key_index:project1:testPrompt",
- );
-
- expect(mockRedis.smembers).toHaveBeenCalledWith(
- "prompt_key_index:project1",
+ expect(mockRedis.set).toHaveBeenCalledWith(
+ "prompt_cache_epoch:project1",
+ expect.any(String),
+ "EX",
+ 7 * 24 * 60 * 60,
);
});
});
@@ -188,7 +134,6 @@ describe("PromptService", () => {
});
expect(result).toEqual(mockPrompt);
- expect(mockRedis.getex).not.toHaveBeenCalled();
expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
expect(mockMetricIncrementer).not.toHaveBeenCalled();
});
@@ -220,28 +165,8 @@ describe("PromptService", () => {
});
describe("getPrompt with Redis errors", () => {
- it("should fallback to database if Redis.exists throws an error", async () => {
- mockRedis.exists.mockRejectedValue(new Error("Redis error"));
- mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
-
- const result = await promptService.getPrompt({
- projectId: "project1",
- promptName: "testPrompt",
- version: 1,
- label: undefined,
- });
-
- expect(result).toEqual(mockPrompt);
- expect(mockPrisma.prompt.findFirst).toHaveBeenCalled();
- expect(mockMetricIncrementer).toHaveBeenCalledWith(
- "prompt_cache_miss",
- 1,
- );
- });
-
- it("should fallback to database if Redis.getex throws an error", async () => {
- mockRedis.exists.mockResolvedValue(0);
- mockRedis.getex.mockRejectedValue(new Error("Redis error"));
+ it("should fallback to database if Redis.get throws an error", async () => {
+ mockRedis.get.mockRejectedValue(new Error("Redis error"));
mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
const result = await promptService.getPrompt({
@@ -260,8 +185,8 @@ describe("PromptService", () => {
});
it("should not cache if Redis.set throws an error after database fetch", async () => {
- mockRedis.exists.mockResolvedValue(0);
- mockRedis.getex.mockResolvedValue(null);
+ mockRedis.get.mockResolvedValueOnce("epoch-1"); // getOrCreateEpoch
+ mockRedis.get.mockResolvedValueOnce(null); // cache miss
mockPrisma.prompt.findFirst.mockResolvedValue(mockPrompt);
mockRedis.set.mockRejectedValue(new Error("Redis error"));
@@ -281,38 +206,13 @@ describe("PromptService", () => {
});
});
- describe("lockCache with Redis errors", () => {
- it("should throw an error if Redis.setex fails", async () => {
- mockRedis.setex.mockRejectedValue(new Error("Redis error"));
-
- await expect(
- promptService.lockCache({
- projectId: "project1",
- promptName: "testPrompt",
- }),
- ).rejects.toThrow("Redis error");
- });
- });
-
- describe("unlockCache with Redis errors", () => {
- it("should log error but not throw if Redis.del fails", async () => {
- mockRedis.del.mockRejectedValue(new Error("Redis error"));
-
- await promptService.unlockCache({
- projectId: "project1",
- promptName: "testPrompt",
- });
- });
- });
-
describe("invalidateCache with Redis errors", () => {
- it("should throw an error if Redis.eval fails", async () => {
- mockRedis.smembers.mockRejectedValue(new Error("Redis error"));
+ it("should throw an error if Redis.set fails", async () => {
+ mockRedis.set.mockRejectedValue(new Error("Redis error"));
await expect(
promptService.invalidateCache({
projectId: "project1",
- promptName: "testPrompt",
}),
).rejects.toThrow("Redis error");
});
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index 321a7b083a..b2517ad0ec 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -187,18 +187,14 @@ export const createPrompt = async ({
create.push(...updatesTags);
}
- // Lock and invalidate cache for _all_ versions and labels of the prompt name
- await promptService.lockCache({ projectId, promptName: name });
- await promptService.invalidateCache({ projectId, promptName: name });
-
// Create prompt and update previous prompt versions
const [createdPrompt] = (await prisma.$transaction(create)) as [
Prompt,
...PromptDependency[],
];
- // Unlock cache
- await promptService.unlockCache({ projectId, promptName: name });
+ // Rotate cache epoch only after successful commit.
+ await promptService.invalidateCache({ projectId });
const updatedPrompts = await prisma.prompt.findMany({
where: {
diff --git a/web/src/features/prompts/server/actions/deletePrompt.ts b/web/src/features/prompts/server/actions/deletePrompt.ts
index d5727e66a0..d245bae997 100644
--- a/web/src/features/prompts/server/actions/deletePrompt.ts
+++ b/web/src/features/prompts/server/actions/deletePrompt.ts
@@ -1,6 +1,6 @@
import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";
import { prisma, type Prompt } from "@langfuse/shared/src/db";
-import { PromptService, redis, logger } from "@langfuse/shared/src/server";
+import { PromptService, redis } from "@langfuse/shared/src/server";
export type DeletePromptParams = {
promptName: string;
@@ -93,42 +93,35 @@ export const deletePrompt = async (params: DeletePromptParams) => {
const promptService = new PromptService(prisma, redis);
- try {
- await promptService.lockCache({ projectId, promptName });
- await promptService.invalidateCache({ projectId, promptName });
+ const deletingLatest = promptVersions.some((p) =>
+ p.labels.includes("latest"),
+ );
+ const latestRemainsAfterDeletion = remainingVersions.some((v) =>
+ v.labels.includes("latest"),
+ );
- const deletingLatest = promptVersions.some((p) =>
- p.labels.includes("latest"),
- );
- const latestRemainsAfterDeletion = remainingVersions.some((v) =>
- v.labels.includes("latest"),
+ // reattach "latest" to highest remaining version
+ if (
+ deletingLatest &&
+ !latestRemainsAfterDeletion &&
+ remainingVersions.length > 0
+ ) {
+ const highestRemainingVersion = remainingVersions.reduce((max, v) =>
+ v.version > max.version ? v : max,
);
- // reattach "latest" to highest remaining version
- if (
- deletingLatest &&
- !latestRemainsAfterDeletion &&
- remainingVersions.length > 0
- ) {
- const highestRemainingVersion = remainingVersions.reduce((max, v) =>
- v.version > max.version ? v : max,
- );
-
- await prisma.prompt.update({
- where: { id: highestRemainingVersion.id },
- data: {
- labels: [...new Set([...highestRemainingVersion.labels, "latest"])],
- },
- });
- }
-
- await prisma.prompt.deleteMany({
- where: { projectId, id: { in: promptVersions.map((p) => p.id) } },
+ await prisma.prompt.update({
+ where: { id: highestRemainingVersion.id },
+ data: {
+ labels: [...new Set([...highestRemainingVersion.labels, "latest"])],
+ },
});
- } catch (err) {
- logger.error("Failed to delete prompt", err);
- throw err;
- } finally {
- await promptService.unlockCache({ projectId, promptName });
}
+
+ await prisma.prompt.deleteMany({
+ where: { projectId, id: { in: promptVersions.map((p) => p.id) } },
+ });
+
+ // Rotate cache epoch only after successful commit.
+ await promptService.invalidateCache({ projectId });
};
diff --git a/web/src/features/prompts/server/actions/updatePrompts.ts b/web/src/features/prompts/server/actions/updatePrompts.ts
index 73c5a37105..fa56268826 100644
--- a/web/src/features/prompts/server/actions/updatePrompts.ts
+++ b/web/src/features/prompts/server/actions/updatePrompts.ts
@@ -20,21 +20,18 @@ export const updatePrompt = async (params: UpdatePromptParams) => {
`Updating prompt ${promptName} in project ${projectId} version ${promptVersion} with labels ${newLabels}`,
);
const promptService = new PromptService(prisma, redis);
- try {
- const touchedPromptIds: string[] = [];
-
- await promptService.lockCache({ projectId, promptName: promptName });
-
- const result = await prisma.$transaction(async (tx) => {
- const prompt = (
- await tx.$queryRaw<
- Array<{
- id: string;
- name: string;
- version: number;
- labels: string[];
- }>
- >`
+ const touchedPromptIds: string[] = [];
+
+ const result = await prisma.$transaction(async (tx) => {
+ const prompt = (
+ await tx.$queryRaw<
+ Array<{
+ id: string;
+ name: string;
+ version: number;
+ labels: string[];
+ }>
+ >`
SELECT
*
FROM
@@ -45,34 +42,34 @@ export const updatePrompt = async (params: UpdatePromptParams) => {
AND version = ${promptVersion}
FOR UPDATE -- Important! This will lock the row for concurrent updates
`
- )[0];
+ )[0];
- if (!prompt) {
- throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);
- }
+ if (!prompt) {
+ throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);
+ }
- touchedPromptIds.push(prompt.id);
+ touchedPromptIds.push(prompt.id);
- 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 tx.$queryRaw<
- {
- parent_name: string;
- parent_version: number;
- child_version: number;
- child_label: string;
- }[]
- >`
+ }
+
+ 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",
@@ -88,90 +85,82 @@ export const updatePrompt = async (params: UpdatePromptParams) => {
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 (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),
- )}`,
- );
+ logger.info(
+ `Setting labels for prompt: ${prompt.id}, ${prompt.name}, ${prompt.version}, ${JSON.stringify(
+ Array.from(newLabelsSet),
+ )}`,
+ );
- const {
- touchedPromptIds: labelsTouchedPromptIds,
- updates: labelUpdates,
- } = await removeLabelsFromPreviousPromptVersions({
+ const { touchedPromptIds: labelsTouchedPromptIds, updates: labelUpdates } =
+ await removeLabelsFromPreviousPromptVersions({
prisma: tx,
projectId,
promptName,
labelsToRemove: [...new Set(newLabels)],
});
- touchedPromptIds.push(...labelsTouchedPromptIds);
-
- const result = await Promise.all([
- // Remove labels from other prompts
- ...labelUpdates,
- // Update prompt
- tx.prompt.update({
- where: {
- id: prompt.id,
- projectId,
- },
- data: {
- labels: {
- set: Array.from(newLabelsSet),
- },
+ touchedPromptIds.push(...labelsTouchedPromptIds);
+
+ const result = await Promise.all([
+ // Remove labels from other prompts
+ ...labelUpdates,
+ // Update prompt
+ tx.prompt.update({
+ where: {
+ id: prompt.id,
+ projectId,
+ },
+ data: {
+ labels: {
+ set: Array.from(newLabelsSet),
},
- }),
- ]);
+ },
+ }),
+ ]);
- return result[result.length - 1];
- });
+ return result[result.length - 1];
+ });
- await promptService.invalidateCache({ projectId, promptName: promptName });
- await promptService.unlockCache({ projectId, promptName: promptName });
+ await promptService.invalidateCache({ projectId });
- // For updates, we need the before state, but we don't have it easily accessible here
- // This updatePrompt function only handles label updates, so the main content doesn't change
- // We'll pass undefined for now since label changes don't need before state for webhooks
+ // For updates, we need the before state, but we don't have it easily accessible here
+ // This updatePrompt function only handles label updates, so the main content doesn't change
+ // We'll pass undefined for now since label changes don't need before state for webhooks
- const updatedPrompts = await prisma.prompt.findMany({
- where: {
- id: { in: touchedPromptIds },
- projectId,
- },
- });
+ const updatedPrompts = await prisma.prompt.findMany({
+ where: {
+ id: { in: touchedPromptIds },
+ projectId,
+ },
+ });
- logger.info(
- `Triggering webhook for ${updatedPrompts.length} prompts for project ${projectId}, touchedPromptIds: ${JSON.stringify(touchedPromptIds)}`,
- );
+ logger.info(
+ `Triggering webhook for ${updatedPrompts.length} prompts for project ${projectId}, touchedPromptIds: ${JSON.stringify(touchedPromptIds)}`,
+ );
- await Promise.all(
- updatedPrompts.map(async (prompt) =>
- promptChangeEventSourcing(
- await promptService.resolvePrompt(prompt),
- "updated",
- user,
- ),
+ await Promise.all(
+ updatedPrompts.map(async (prompt) =>
+ promptChangeEventSourcing(
+ await promptService.resolvePrompt(prompt),
+ "updated",
+ user,
),
- );
-
- return result;
- } catch (e) {
- await promptService.unlockCache({ projectId, promptName: promptName });
+ ),
+ );
- throw e;
- }
+ return result;
};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 088e00a88b..0ed0a923c0 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -536,15 +536,9 @@ export const promptRouter = createTRPCRouter({
);
}
- // Lock and invalidate cache for all prompts
const promptService = new PromptService(ctx.prisma, redis);
const promptNames = [...new Set(prompts.map((p) => p.name))];
- for (const name of promptNames) {
- await promptService.lockCache({ projectId, promptName: name });
- await promptService.invalidateCache({ projectId, promptName: name });
- }
-
// Delete all prompts with the given id
await ctx.prisma.prompt.deleteMany({
where: {
@@ -555,10 +549,7 @@ export const promptRouter = createTRPCRouter({
},
});
- // Unlock cache
- for (const name of promptNames) {
- await promptService.unlockCache({ projectId, promptName: name });
- }
+ promptService.invalidateCache({ projectId });
// Trigger webhooks for prompt deletion
await Promise.all(
@@ -714,16 +705,12 @@ export const promptRouter = createTRPCRouter({
}
}
- // Lock and invalidate cache for _all_ versions and labels of the prompt
const promptService = new PromptService(ctx.prisma, redis);
- await promptService.lockCache({ projectId, promptName });
- await promptService.invalidateCache({ projectId, promptName });
// Execute transaction
await ctx.prisma.$transaction(transaction);
-
- // Unlock cache
- await promptService.unlockCache({ projectId, promptName });
+ // Rotate cache epoch only after successful commit.
+ await promptService.invalidateCache({ projectId });
// Trigger webhooks for prompt version deletion
await promptChangeEventSourcing(
@@ -901,16 +888,12 @@ export const promptRouter = createTRPCRouter({
);
});
- // Lock and invalidate cache for _all_ versions and labels of the prompt
const promptService = new PromptService(ctx.prisma, redis);
- await promptService.lockCache({ projectId, promptName });
- await promptService.invalidateCache({ projectId, promptName });
// Execute transaction
await ctx.prisma.$transaction(toBeExecuted);
-
- // Unlock cache
- await promptService.unlockCache({ projectId, promptName });
+ // Rotate cache epoch only after successful commit.
+ await promptService.invalidateCache({ projectId });
// Trigger webhooks for prompt label update
const updatedPrompts = await ctx.prisma.prompt.findMany({
@@ -1048,10 +1031,7 @@ export const promptRouter = createTRPCRouter({
after: input.tags,
});
- // Lock and invalidate cache for _all_ versions and labels of the prompt
const promptService = new PromptService(ctx.prisma, redis);
- await promptService.lockCache({ projectId, promptName });
- await promptService.invalidateCache({ projectId, promptName });
await ctx.prisma.prompt.updateMany({
where: {
@@ -1065,8 +1045,8 @@ export const promptRouter = createTRPCRouter({
},
});
- // Unlock cache
- await promptService.unlockCache({ projectId, promptName });
+ // Rotate cache epoch only after successful commit.
+ await promptService.invalidateCache({ projectId });
// Trigger webhooks for prompt tag update