🪢 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
perf(clickhouse): prune blob storage cleanup by primary key during trace deletion (#14892)
Valery Meleshkinfeb2a8ba34a8
diff --git a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts b/packages/shared/src/server/data-deletion/ingestionFileDeletion.tsindex f8ba581500..87faae86a3 100644--- a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts+++ b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts@@ -28,10 +28,15 @@ export const deleteIngestionEventsFromS3AndClickhouseForScores = async (p: {};export const removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces =- async (p: { projectId: string; traceIds: string[] }) => {+ async (p: {+ projectId: string;+ traceIds: string[];+ includeEventsTable?: boolean;+ }) => {const stream = getBlobStorageByProjectIdAndTraceIds(p.projectId,p.traceIds,+ { includeEventsTable: p.includeEventsTable ?? false },);return removeIngestionEventsFromS3AndDeleteClickhouseRefs({diff --git a/packages/shared/src/server/repositories/blobStorageLog.ts b/packages/shared/src/server/repositories/blobStorageLog.tsindex d06bee2fe1..bcd88cc807 100644--- a/packages/shared/src/server/repositories/blobStorageLog.ts+++ b/packages/shared/src/server/repositories/blobStorageLog.ts@@ -99,50 +99,73 @@ export const getBlobStorageByProjectIdAndEntityIds = (export const getBlobStorageByProjectIdAndTraceIds = (projectId: string,traceIds: string[],+ opts?: { includeEventsTable?: boolean },): AsyncGenerator<BlobStorageFileRefRecordReadType> => {+ const includeEventsTable = opts?.includeEventsTable ?? false;++ // In v4 events_only write mode spans live only in events_core, not in the+ // observations table. Include an events_core branch so their blob refs are+ // cleaned up too. Gated behind a flag because events_core is a dev/v4-only+ // table (created by clickhouse/scripts/dev-tables.sh, not by migrations) and+ // self-hosters on legacy write mode may not have it. When disabled the query+ // must not reference events_core at all.+ const filteredEventsCoreCte = includeEventsTable+ ? `, filtered_events_core as (+ select+ span_id as entity_id,+ 'observation' as entity_type+ from events_core+ where project_id = {projectId: String}+ and trace_id in ({traceIds: Array(String)})+ )`+ : "";+ const filteredEventsCoreUnion = includeEventsTable+ ? `+ union all+ select * from filtered_events_core`+ : "";++ // We filter the blob log with a tuple `(entity_type, entity_id) IN (subquery)`+ // predicate rather than a JOIN. A prepared-set IN predicate on the leading+ // primary-key columns participates in primary-index analysis, so ClickHouse+ // can prune granules down to the target entities. A JOIN key does not, which+ // forced a FINAL scan of the whole project's blob log. The trace entity ids+ // are exactly the input traceIds, so we build them with arrayJoin instead of+ // reading the traces table (which is both wasted work and, in events_only+ // mode where the trace has no traces row, a coverage bug that leaked files).const query = `with filtered_traces as (- select distinct- id as entity_id,- project_id as project_id,+ select+ arrayJoin({traceIds: Array(String)}) as entity_id,'trace' as entity_type- from traces- where project_id = {projectId: String}- and id in ({traceIds: Array(String)})), filtered_observations as (- select distinct+ selectid as entity_id,- project_id as project_id,'observation' as entity_typefrom observationswhere project_id = {projectId: String}and trace_id in ({traceIds: Array(String)})), filtered_scores as (- select distinct+ selectid as entity_id,- project_id as project_id,'score' as entity_typefrom scoreswhere project_id = {projectId: String}and trace_id in ({traceIds: Array(String)})- ), filtered_events as (- select *- from filtered_traces+ )${filteredEventsCoreCte}, filtered_entities as (+ select * from filtered_tracesunion all- select *- from filtered_observations+ select * from filtered_observationsunion all- select *- from filtered_scores+ select * from filtered_scores${filteredEventsCoreUnion})- -- We use a semi join because we only use the 'filtered_events' as a filter.- -- There is no need to build the cartesian product (i.e. the combination) between the event log and the events.select el.*from blob_storage_file_log el FINAL- left semi join filtered_events fe- on el.project_id = fe.project_id and el.entity_id = fe.entity_id and el.entity_type = fe.entity_typewhere el.project_id = {projectId: String}+ and (el.entity_type, el.entity_id) in (+ select entity_type, entity_id from filtered_entities+ )`;return queryClickhouseStream<BlobStorageFileRefRecordReadType>({diff --git a/worker/src/__tests__/traceDeletion.test.ts b/worker/src/__tests__/traceDeletion.test.tsindex d8ba43d1ee..c9d7eae52c 100644--- a/worker/src/__tests__/traceDeletion.test.ts+++ b/worker/src/__tests__/traceDeletion.test.ts@@ -1,6 +1,9 @@import { expect, describe, it, beforeAll, afterEach, vi } from "vitest";+import waitForExpect from "wait-for-expect";import {clickhouseClient,+ createEvent,+ createEventsCh,createObservation,createObservationsCh,createOrgProjectAndApiKey,@@ -12,6 +15,8 @@ import {getObservationsForTrace,getScoresForTraces,getTracesByIds,+ queryClickhouse,+ removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces,StorageService,StorageServiceFactory,} from "@langfuse/shared/src/server";@@ -19,6 +24,7 @@ import { randomUUID } from "crypto";import { processClickhouseTraceDelete } from "../features/traces/processClickhouseTraceDelete";import { env } from "../env";import { prisma } from "@langfuse/shared/src/db";+import { skipUnlessClickhouseTablesExist } from "./helpers/clickhouseTables";describe("trace deletion", () => {let eventStorageService: StorageService;@@ -474,4 +480,243 @@ describe("trace deletion", () => {const files = await eventStorageService.listFiles(projectId);expect(files).toHaveLength(0);});++ it("should clean up a trace blob ref that has no row in the traces table", async () => {+ // Setup: a blob ref for a trace whose `traces` row does not exist (e.g. a+ // project in v4 events_only write mode where traces are not written to the+ // legacy `traces` table). The old query joined against `traces`, so this+ // ref was missed and the S3 file leaked.+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const bucketPath = `${projectId}/traces/${traceId}-trace.json`;++ await eventStorageService.uploadFile({+ fileName: bucketPath,+ fileType: "application/json",+ data: JSON.stringify({ hello: "world" }),+ });++ await clickhouseClient().insert({+ table: "blob_storage_file_log",+ format: "JSONEachRow",+ values: [+ {+ id: randomUUID(),+ project_id: projectId,+ entity_type: "trace",+ entity_id: traceId,+ event_id: randomUUID(),+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: bucketPath,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ },+ ],+ });++ // When: no traces/observations/scores rows exist at all+ await removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces({+ projectId,+ traceIds: [traceId],+ includeEventsTable: false,+ });++ // Then: blob ref soft-deleted (invisible under FINAL) and S3 file gone+ const eventLog = getBlobStorageByProjectId(projectId);+ for await (const _ of eventLog) {+ expect(true).toBe(false);+ }++ const files = await eventStorageService.listFiles(projectId);+ expect(files).toHaveLength(0);+ });++ it("should clean up an events-only observation blob ref when includeEventsTable is true", async (ctx) => {+ await skipUnlessClickhouseTablesExist(+ ctx,+ ["events_core"],+ "events ClickHouse tables are not enabled",+ );++ // Setup: a span that exists only in the events pipeline (events_full →+ // events_core via MV), with no row in the legacy `observations` table.+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const spanId = randomUUID();+ const eventTime = Date.now() * 1000; // micros++ await createEventsCh([+ createEvent({+ id: spanId,+ span_id: spanId,+ trace_id: traceId,+ project_id: projectId,+ start_time: eventTime,+ created_at: eventTime,+ updated_at: eventTime,+ event_ts: eventTime,+ }),+ ]);++ // The events_core materialized view populates asynchronously; wait for the+ // span to land before deleting so the query can prune to it.+ await waitForExpect(async () => {+ const rows = await queryClickhouse<{ count: string }>({+ query: `+ select count(*) as count+ from events_core+ where project_id = {projectId: String}+ and trace_id in ({traceIds: Array(String)})+ `,+ params: { projectId, traceIds: [traceId] },+ });+ expect(Number(rows[0]?.count ?? 0)).toBe(1);+ }, 20_000);++ const bucketPath = `${projectId}/observation/${spanId}-observation.json`;+ await eventStorageService.uploadFile({+ fileName: bucketPath,+ fileType: "application/json",+ data: JSON.stringify({ hello: "world" }),+ });++ await clickhouseClient().insert({+ table: "blob_storage_file_log",+ format: "JSONEachRow",+ values: [+ {+ id: randomUUID(),+ project_id: projectId,+ entity_type: "observation",+ entity_id: spanId,+ event_id: randomUUID(),+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: bucketPath,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ },+ ],+ });++ // When+ await removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces({+ projectId,+ traceIds: [traceId],+ includeEventsTable: true,+ });++ // Then: blob ref soft-deleted and S3 file removed+ const eventLog = getBlobStorageByProjectId(projectId);+ for await (const _ of eventLog) {+ expect(true).toBe(false);+ }++ const files = await eventStorageService.listFiles(projectId);+ expect(files).toHaveLength(0);+ });++ it("should clean up legacy trace/observation/score blob refs with includeEventsTable false", async () => {+ // Gating: with the events branch disabled, legacy data backed by the+ // traces/observations/scores tables must be cleaned exactly as before.+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = randomUUID();+ const observationId = randomUUID();+ const scoreId = randomUUID();++ await createTracesCh([createTrace({ id: traceId, project_id: projectId })]);+ await createObservationsCh([+ createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: projectId,+ }),+ ]);+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ trace_id: traceId,+ project_id: projectId,+ }),+ ]);++ const fileType = "application/json";+ const data = JSON.stringify({ hello: "world" });++ await Promise.all([+ eventStorageService.uploadFile({+ fileName: `${projectId}/traces/${traceId}-trace.json`,+ fileType,+ data,+ }),+ eventStorageService.uploadFile({+ fileName: `${projectId}/observation/${observationId}-observation.json`,+ fileType,+ data,+ }),+ eventStorageService.uploadFile({+ fileName: `${projectId}/score/${scoreId}-score.json`,+ fileType,+ data,+ }),+ ]);++ await clickhouseClient().insert({+ table: "blob_storage_file_log",+ format: "JSONEachRow",+ values: [+ {+ id: randomUUID(),+ project_id: projectId,+ entity_type: "trace",+ entity_id: traceId,+ event_id: randomUUID(),+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: `${projectId}/traces/${traceId}-trace.json`,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ },+ {+ id: randomUUID(),+ project_id: projectId,+ entity_type: "observation",+ entity_id: observationId,+ event_id: randomUUID(),+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: `${projectId}/observation/${observationId}-observation.json`,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ },+ {+ id: randomUUID(),+ project_id: projectId,+ entity_type: "score",+ entity_id: scoreId,+ event_id: randomUUID(),+ bucket_name: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ bucket_path: `${projectId}/score/${scoreId}-score.json`,+ created_at: new Date().getTime(),+ updated_at: new Date().getTime(),+ },+ ],+ });++ // When+ await removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces({+ projectId,+ traceIds: [traceId],+ includeEventsTable: false,+ });++ // Then+ const eventLog = getBlobStorageByProjectId(projectId);+ for await (const _ of eventLog) {+ expect(true).toBe(false);+ }++ const files = await eventStorageService.listFiles(projectId);+ expect(files).toHaveLength(0);+ });});diff --git a/worker/src/features/traces/processClickhouseTraceDelete.ts b/worker/src/features/traces/processClickhouseTraceDelete.tsindex b81d766f1b..ede11fc96f 100644--- a/worker/src/features/traces/processClickhouseTraceDelete.ts+++ b/worker/src/features/traces/processClickhouseTraceDelete.ts@@ -179,6 +179,7 @@ export const processClickhouseTraceDelete = async (? removeIngestionEventsFromS3AndDeleteClickhouseRefsForTraces({projectId,traceIds,+ includeEventsTable: v4WritesToEventsTable(env),}): Promise.resolve(),deleteTraces(projectId, traceIds),