🪢 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
chore: double-check that a project still exists before starting potentially expensive DELETE (#11456)
Valery Meleshkin43b271ea4cd2
diff --git a/.env.dev.example b/.env.dev.exampleindex a940b8e57a..e88ac72456 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -148,3 +148,4 @@ LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-haiku-20240307-v1:0"LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS=trueLANGFUSE_ENABLE_EVENTS_TABLE_FLAGS=trueLANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS=true+LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE=truediff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 23bf13d265..5ef5926333 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -422,6 +422,18 @@ jobs:pnpm run db:migratepnpm run db:seedpnpm run --filter=shared ch:up+ - name: Download and extract ClickHouse client for dev-tables setup+ if: matrix.deploy-mode == ''+ run: |+ CH_VERSION="24.9.3.128"+ ARCH="amd64"+ wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb+ dpkg-deb -x clickhouse-client.deb ch_client_dir+ sudo cp ch_client_dir/usr/bin/clickhouse /usr/local/bin/+ - name: Setup Dev Tables+ if: matrix.deploy-mode == ''+ run: |+ pnpm --filter=shared ch:dev-tables- name: Buildrun: pnpm --filter=worker... run build- name: run testsdiff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 3e48b082e6..140e719361 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -1690,11 +1690,40 @@ export const deleteEventsByTraceIds = async (});};+export const hasAnyEvent = async (projectId: string) => {+ const query = `+ SELECT 1+ FROM events+ WHERE project_id = {projectId: String}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: { projectId },+ tags: {+ feature: "tracing",+ type: "events",+ kind: "hasAny",+ projectId,+ },+ });++ return rows.length > 0;+};+/*** Delete all events for a project* Used when an entire project is deleted*/-export const deleteEventsByProjectId = async (projectId: string) => {+export const deleteEventsByProjectId = async (+ projectId: string,+): Promise<boolean> => {+ const hasData = await hasAnyEvent(projectId);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM eventsWHERE project_id = {projectId: String};@@ -1717,6 +1746,37 @@ export const deleteEventsByProjectId = async (projectId: string) => {send_logs_level: "trace",},});++ return true;+};++export const hasAnyEventOlderThan = async (+ projectId: string,+ beforeDate: Date,+) => {+ const query = `+ SELECT 1+ FROM events+ WHERE project_id = {projectId: String}+ AND start_time < {cutoffDate: DateTime64(3)}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {+ projectId,+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),+ },+ tags: {+ feature: "tracing",+ type: "events",+ kind: "hasAnyOlderThan",+ projectId,+ },+ });++ return rows.length > 0;};/**@@ -1726,7 +1786,12 @@ export const deleteEventsByProjectId = async (projectId: string) => {export const deleteEventsOlderThanDays = async (projectId: string,beforeDate: Date,-) => {+): Promise<boolean> => {+ const hasData = await hasAnyEventOlderThan(projectId, beforeDate);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM eventsWHERE project_id = {projectId: String}@@ -1748,6 +1813,8 @@ export const deleteEventsOlderThanDays = async (projectId,},});++ return true;};export const getObservationsBatchIOFromEventsTable = async (opts: {diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 21887fe488..d633204e0d 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -1249,7 +1249,36 @@ export const deleteObservationsByTraceIds = async (});};-export const deleteObservationsByProjectId = async (projectId: string) => {+export const hasAnyObservation = async (projectId: string) => {+ const query = `+ SELECT 1+ FROM observations+ WHERE project_id = {projectId: String}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: { projectId },+ tags: {+ feature: "tracing",+ type: "observation",+ kind: "hasAny",+ projectId,+ },+ });++ return rows.length > 0;+};++export const deleteObservationsByProjectId = async (+ projectId: string,+): Promise<boolean> => {+ const hasData = await hasAnyObservation(projectId);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM observationsWHERE project_id = {projectId: String};@@ -1269,12 +1298,48 @@ export const deleteObservationsByProjectId = async (projectId: string) => {},tags,});++ return true;};-export const deleteObservationsOlderThanDays = async (+export const hasAnyObservationOlderThan = async (projectId: string,beforeDate: Date,) => {+ const query = `+ SELECT 1+ FROM observations+ WHERE project_id = {projectId: String}+ AND start_time < {cutoffDate: DateTime64(3)}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {+ projectId,+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),+ },+ tags: {+ feature: "tracing",+ type: "observation",+ kind: "hasAnyOlderThan",+ projectId,+ },+ });++ return rows.length > 0;+};++export const deleteObservationsOlderThanDays = async (+ projectId: string,+ beforeDate: Date,+): Promise<boolean> => {+ const hasData = await hasAnyObservationOlderThan(projectId, beforeDate);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM observationsWHERE project_id = {projectId: String}@@ -1296,6 +1361,8 @@ export const deleteObservationsOlderThanDays = async (projectId,},});++ return true;};export const getObservationsWithPromptName = async (diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 1d6be8e1be..fbddc276d5 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -1202,7 +1202,14 @@ export const deleteScoresByTraceIds = async (});};-export const deleteScoresByProjectId = async (projectId: string) => {+export const deleteScoresByProjectId = async (+ projectId: string,+): Promise<boolean> => {+ const hasData = await hasAnyScore(projectId);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM scoresWHERE project_id = {projectId: String};@@ -1222,12 +1229,48 @@ export const deleteScoresByProjectId = async (projectId: string) => {},tags,});++ return true;};-export const deleteScoresOlderThanDays = async (+export const hasAnyScoreOlderThan = async (projectId: string,beforeDate: Date,) => {+ const query = `+ SELECT 1+ FROM scores+ WHERE project_id = {projectId: String}+ AND timestamp < {cutoffDate: DateTime64(3)}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {+ projectId,+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),+ },+ tags: {+ feature: "tracing",+ type: "score",+ kind: "hasAnyOlderThan",+ projectId,+ },+ });++ return rows.length > 0;+};++export const deleteScoresOlderThanDays = async (+ projectId: string,+ beforeDate: Date,+): Promise<boolean> => {+ const hasData = await hasAnyScoreOlderThan(projectId, beforeDate);+ if (!hasData) {+ return false;+ }+const query = `DELETE FROM scoresWHERE project_id = {projectId: String}@@ -1249,6 +1292,8 @@ export const deleteScoresOlderThanDays = async (projectId,},});++ return true;};export const getNumericScoreHistogram = async (diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 7abe81a425..f9059f0aea 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -897,10 +897,44 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {});};-export const deleteTracesOlderThanDays = async (+export const hasAnyTraceOlderThan = async (projectId: string,beforeDate: Date,) => {+ const query = `+ SELECT 1+ FROM traces+ WHERE project_id = {projectId: String}+ AND timestamp < {cutoffDate: DateTime64(3)}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {+ projectId,+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),+ },+ tags: {+ feature: "tracing",+ type: "trace",+ kind: "hasAnyOlderThan",+ projectId,+ },+ });++ return rows.length > 0;+};++export const deleteTracesOlderThanDays = async (+ projectId: string,+ beforeDate: Date,+): Promise<boolean> => {+ const hasData = await hasAnyTraceOlderThan(projectId, beforeDate);+ if (!hasData) {+ return false;+ }+await measureAndReturn({operationName: "deleteTracesOlderThanDays",projectId,@@ -932,9 +966,18 @@ export const deleteTracesOlderThanDays = async (});},});++ return true;};-export const deleteTracesByProjectId = async (projectId: string) => {+export const deleteTracesByProjectId = async (+ projectId: string,+): Promise<boolean> => {+ const hasData = await hasAnyTrace(projectId);+ if (!hasData) {+ return false;+ }+await measureAndReturn({operationName: "deleteTracesByProjectId",projectId,@@ -965,6 +1008,8 @@ export const deleteTracesByProjectId = async (projectId: string) => {});},});++ return true;};export const hasAnyUser = async (projectId: string) => {diff --git a/worker/src/__tests__/projectDeletionProcessing.test.ts b/worker/src/__tests__/projectDeletionProcessing.test.tsindex 55d40cf208..083d3462bf 100644--- a/worker/src/__tests__/projectDeletionProcessing.test.ts+++ b/worker/src/__tests__/projectDeletionProcessing.test.ts@@ -16,6 +16,14 @@ import {StorageService,StorageServiceFactory,upsertTrace,+ deleteTracesByProjectId,+ deleteObservationsByProjectId,+ deleteScoresByProjectId,+ deleteEventsByProjectId,+ deleteTracesOlderThanDays,+ deleteObservationsOlderThanDays,+ deleteScoresOlderThanDays,+ deleteEventsOlderThanDays,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { Job } from "bullmq";@@ -26,6 +34,9 @@ describe("ProjectDeletionProcessingJob", () => {let s3Prefix: string | null = null;const orgId = "seed-org-id";+ const maybeEventsIt =+ env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true" ? it : it.skip;+beforeAll(() => {storageService = StorageServiceFactory.getInstance({accessKeyId: env.LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID,@@ -163,45 +174,48 @@ describe("ProjectDeletionProcessingJob", () => {expect(score).toBeUndefined();});- it("should delete event data from S3 for the project", async () => {- // Setup- const projectId = randomUUID();- await prisma.project.create({- data: {- id: projectId,- orgId,- name: `Project-${randomUUID()}`,- },- });+ maybeEventsIt(+ "should delete event data from S3 for the project",+ async () => {+ // Setup+ const projectId = randomUUID();+ await prisma.project.create({+ data: {+ id: projectId,+ orgId,+ name: `Project-${randomUUID()}`,+ },+ });- // Use upsertTrace here as this also creates an S3 event record- const baseId = randomUUID();- await upsertTrace({- id: `${baseId}-trace`,- project_id: projectId,- timestamp: convertDateToClickhouseDateTime(new Date()),- created_at: convertDateToClickhouseDateTime(new Date()),- updated_at: convertDateToClickhouseDateTime(new Date()),- });+ // Use upsertTrace here as this also creates an S3 event record+ const baseId = randomUUID();+ await upsertTrace({+ id: `${baseId}-trace`,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(new Date()),+ created_at: convertDateToClickhouseDateTime(new Date()),+ updated_at: convertDateToClickhouseDateTime(new Date()),+ });- // When- await projectDeleteProcessor({- data: { payload: { projectId, orgId } },- } as Job);+ // When+ await projectDeleteProcessor({+ data: { payload: { projectId, orgId } },+ } as Job);- // Then- const files = await storageService.listFiles("");- expect(files.some((file) => file.file.includes(`${baseId}-trace`))).toBe(- false,- );+ // Then+ const files = await storageService.listFiles("");+ expect(files.some((file) => file.file.includes(`${baseId}-trace`))).toBe(+ false,+ );- const eventLogRecord = await getBlobStorageByProjectAndEntityId(- projectId,- "trace",- `${baseId}-trace`,- );- expect(eventLogRecord).toHaveLength(0);- });+ const eventLogRecord = await getBlobStorageByProjectAndEntityId(+ projectId,+ "trace",+ `${baseId}-trace`,+ );+ expect(eventLogRecord).toHaveLength(0);+ },+ );it("should delete all media assets for the project", async () => {// Setup@@ -269,4 +283,313 @@ describe("ProjectDeletionProcessingJob", () => {});expect(traceMedia).toBeNull();});++ describe("delete functions with hasAny probe", () => {+ it("should return false when no traces exist for project", async () => {+ const emptyProjectId = randomUUID();+ const result = await deleteTracesByProjectId(emptyProjectId);+ expect(result).toBe(false);+ });++ it("should return false when no observations exist for project", async () => {+ const emptyProjectId = randomUUID();+ const result = await deleteObservationsByProjectId(emptyProjectId);+ expect(result).toBe(false);+ });++ it("should return false when no scores exist for project", async () => {+ const emptyProjectId = randomUUID();+ const result = await deleteScoresByProjectId(emptyProjectId);+ expect(result).toBe(false);+ });++ maybeEventsIt(+ "should return false when no events exist for project",+ async () => {+ const emptyProjectId = randomUUID();+ const result = await deleteEventsByProjectId(emptyProjectId);+ expect(result).toBe(false);+ },+ );++ it("should return true and delete when traces exist", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();++ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const traceBefore = await getTraceById({ traceId, projectId });+ expect(traceBefore).toBeDefined();++ const result = await deleteTracesByProjectId(projectId);+ expect(result).toBe(true);++ const traceAfter = await getTraceById({ traceId, projectId });+ expect(traceAfter).toBeUndefined();+ });++ it("should return true and delete when observations exist", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const observationId = randomUUID();++ await createObservationsCh([+ createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: projectId,+ }),+ ]);++ await expect(+ getObservationById({ id: observationId, projectId }),+ ).toBeDefined();++ const result = await deleteObservationsByProjectId(projectId);+ expect(result).toBe(true);++ await expect(+ getObservationById({ id: observationId, projectId }),+ ).rejects.toThrowError("not found");+ });++ it("should return true and delete when scores exist", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const scoreId = randomUUID();++ await createScoresCh([+ createTraceScore({+ id: scoreId,+ trace_id: traceId,+ project_id: projectId,+ }),+ ]);++ const scoreBefore = await getScoreById({ projectId, scoreId });+ expect(scoreBefore).toBeDefined();++ const result = await deleteScoresByProjectId(projectId);+ expect(result).toBe(true);++ const scoreAfter = await getScoreById({ projectId, scoreId });+ expect(scoreAfter).toBeUndefined();+ });+ });++ describe("delete OlderThanDays functions with hasAny probe", () => {+ it("should return false when no traces older than cutoff exist and retain newer traces", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago++ // Create a trace that is NEWER than cutoff (should be retained)+ await createTracesCh([+ createTrace({+ id: traceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // No traces older than cutoff exist, so should return false+ const result = await deleteTracesOlderThanDays(projectId, cutoffDate);+ expect(result).toBe(false);++ // Verify the newer trace is still there (retained)+ const trace = await getTraceById({ traceId, projectId });+ expect(trace).toBeDefined();+ });++ it("should return true, delete old traces, and retain newer traces", async () => {+ const projectId = randomUUID();+ const oldTraceId = randomUUID();+ const newTraceId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago+ const oldDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000); // 14 days ago++ // Create an OLD trace (should be deleted)+ await createTracesCh([+ createTrace({+ id: oldTraceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(oldDate),+ }),+ ]);++ // Create a NEW trace (should be retained)+ await createTracesCh([+ createTrace({+ id: newTraceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // Should return true since old data exists+ const result = await deleteTracesOlderThanDays(projectId, cutoffDate);+ expect(result).toBe(true);++ // Verify old trace is deleted+ const oldTrace = await getTraceById({ traceId: oldTraceId, projectId });+ expect(oldTrace).toBeUndefined();++ // Verify new trace is retained+ const newTrace = await getTraceById({ traceId: newTraceId, projectId });+ expect(newTrace).toBeDefined();+ });++ it("should return false when no observations older than cutoff exist and retain newer observations", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const observationId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago++ // Create an observation that is NEWER than cutoff (should be retained)+ await createObservationsCh([+ createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: projectId,+ start_time: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // No observations older than cutoff exist, so should return false+ const result = await deleteObservationsOlderThanDays(+ projectId,+ cutoffDate,+ );+ expect(result).toBe(false);++ // Verify the newer observation is still there (retained)+ const observation = await getObservationById({+ id: observationId,+ projectId,+ });+ expect(observation).toBeDefined();+ });++ it("should return true, delete old observations, and retain newer observations", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const oldObservationId = randomUUID();+ const newObservationId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago+ const oldDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000); // 14 days ago++ // Create an OLD observation (should be deleted)+ await createObservationsCh([+ createObservation({+ id: oldObservationId,+ trace_id: traceId,+ project_id: projectId,+ start_time: convertDateToClickhouseDateTime(oldDate),+ }),+ ]);++ // Create a NEW observation (should be retained)+ await createObservationsCh([+ createObservation({+ id: newObservationId,+ trace_id: traceId,+ project_id: projectId,+ start_time: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // Should return true since old data exists+ const result = await deleteObservationsOlderThanDays(+ projectId,+ cutoffDate,+ );+ expect(result).toBe(true);++ // Verify old observation is deleted+ await expect(+ getObservationById({ id: oldObservationId, projectId }),+ ).rejects.toThrowError("not found");++ // Verify new observation is retained+ const newObservation = await getObservationById({+ id: newObservationId,+ projectId,+ });+ expect(newObservation).toBeDefined();+ });++ it("should return false when no scores older than cutoff exist and retain newer scores", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const scoreId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago++ // Create a score that is NEWER than cutoff (should be retained)+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ trace_id: traceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // No scores older than cutoff exist, so should return false+ const result = await deleteScoresOlderThanDays(projectId, cutoffDate);+ expect(result).toBe(false);++ // Verify the newer score is still there (retained)+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ });++ it("should return true, delete old scores, and retain newer scores", async () => {+ const projectId = randomUUID();+ const traceId = randomUUID();+ const oldScoreId = randomUUID();+ const newScoreId = randomUUID();+ const now = new Date();+ const cutoffDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); // 7 days ago+ const oldDate = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000); // 14 days ago++ // Create an OLD score (should be deleted)+ await createScoresCh([+ createTraceScore({+ id: oldScoreId,+ trace_id: traceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(oldDate),+ }),+ ]);++ // Create a NEW score (should be retained)+ await createScoresCh([+ createTraceScore({+ id: newScoreId,+ trace_id: traceId,+ project_id: projectId,+ timestamp: convertDateToClickhouseDateTime(now),+ }),+ ]);++ // Should return true since old data exists+ const result = await deleteScoresOlderThanDays(projectId, cutoffDate);+ expect(result).toBe(true);++ // Verify old score is deleted+ const oldScore = await getScoreById({ projectId, scoreId: oldScoreId });+ expect(oldScore).toBeUndefined();++ // Verify new score is retained+ const newScore = await getScoreById({ projectId, scoreId: newScoreId });+ expect(newScore).toBeDefined();+ });+ });});