🪢 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
fix: reduce postgres parameters for media delete to avoid PG exceptions (#10246)
Steffen Schmitz3ef84f455b8f
diff --git a/web/src/features/datasets/components/PreviewCsvImport.tsx b/web/src/features/datasets/components/PreviewCsvImport.tsxindex dbdca775e1..5c6688c5f9 100644--- a/web/src/features/datasets/components/PreviewCsvImport.tsx+++ b/web/src/features/datasets/components/PreviewCsvImport.tsx@@ -23,6 +23,7 @@ import { MAX_FILE_SIZE_BYTES } from "@/src/features/datasets/components/UploadDaimport { Progress } from "@/src/components/ui/progress";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";+import { chunk } from "lodash";const MIN_CHUNK_SIZE = 1;const CHUNK_START_SIZE = 50;@@ -68,12 +69,6 @@ type ImportProgress = {status: "not-started" | "processing" | "complete";};-function chunkArray<T>(array: T[], size: number): T[][] {- return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>- array.slice(i * size, i * size + size),- );-}-function sleep(ms: number) {return new Promise((resolve) => setTimeout(resolve, ms));}@@ -280,7 +275,7 @@ export function PreviewCsvImport({});const optimalChunkSize = getOptimalChunkSize(items, CHUNK_START_SIZE);- const chunks = chunkArray(items, optimalChunkSize);+ const chunks = chunk(items, optimalChunkSize);for (const [index, chunk] of chunks.entries()) {await mutCreateManyDatasetItems.mutateAsync({diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex 719a8ea45e..f79e7d121b 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -10,6 +10,7 @@ import { env } from "../../env";import { ClickhouseWriter } from "../../services/ClickhouseWriter";import { IngestionService } from "../../services/IngestionService";import { prisma } from "@langfuse/shared/src/db";+import { chunk } from "lodash";const EXPERIMENT_BACKFILL_TIMESTAMP_KEY ="langfuse:event-propagation:experiment-backfill:last-run";@@ -686,17 +687,6 @@ export async function updateBackfillTimestamp(timestamp: Date): Promise<void> {}}-/**- * Chunk an array into smaller arrays of specified size.- */-function chunk<T>(array: T[], size: number): T[][] {- const chunks: T[][] = [];- for (let i = 0; i < array.length; i += size) {- chunks.push(array.slice(i, i + size));- }- return chunks;-}-/*** Main entry point for experiment backfill.* Handles initialization, throttle checking, execution, and timestamp updates.diff --git a/worker/src/features/traces/processClickhouseTraceDelete.ts b/worker/src/features/traces/processClickhouseTraceDelete.tsindex a58bceb08d..8a84d9f2a5 100644--- a/worker/src/features/traces/processClickhouseTraceDelete.ts+++ b/worker/src/features/traces/processClickhouseTraceDelete.ts@@ -10,6 +10,7 @@ import {} from "@langfuse/shared/src/server";import { env } from "../../env";import { prisma } from "@langfuse/shared/src/db";+import { chunk } from "lodash";let s3MediaStorageClient: StorageService;@@ -36,7 +37,9 @@ const deleteMediaItemsForTraces = async (if (!env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET) {return;}- // First, find all records associated with the traces to be deleted++ // Phase 1: Find and delete references, collect affected mediaIds+ const allMediaIds = new Set<string>();const [traceMediaItems, observationMediaItems] = await Promise.all([prisma.traceMedia.findMany({select: {@@ -64,55 +67,11 @@ const deleteMediaItemsForTraces = async (}),]);- // Find media items that will have no remaining references after deletion- const mediaDeleteCandidates = await prisma.media.findMany({- select: {- id: true,- bucketPath: true,- },- where: {- projectId,- id: {- in: [...traceMediaItems, ...observationMediaItems].map(- (ref) => ref.mediaId,- ),- },- TraceMedia: {- every: {- id: {- in: traceMediaItems.map((ref) => ref.id),- },- },- },- ObservationMedia: {- every: {- id: {- in: observationMediaItems.map((ref) => ref.id),- },- },- },- },- });-- // Remove the media items that will have no remaining references- if (mediaDeleteCandidates.length > 0) {- // Delete from Cloud Storage- await getS3MediaStorageClient(- env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET ?? "", // Fallback is never used.- ).deleteFiles(mediaDeleteCandidates.map((f) => f.bucketPath));+ // Collect all affected mediaIds+ traceMediaItems.forEach((item) => allMediaIds.add(item.mediaId));+ observationMediaItems.forEach((item) => allMediaIds.add(item.mediaId));- // Delete from postgres- await prisma.media.deleteMany({- where: {- id: {- in: mediaDeleteCandidates.map((f) => f.id),- },- projectId,- },- });- }-- // Remove all traceMedia and observationMedia items that we found earlier+ // Delete the junction table records in chunksawait Promise.all([prisma.traceMedia.deleteMany({where: {@@ -131,6 +90,52 @@ const deleteMediaItemsForTraces = async (},}),]);++ // Phase 2: Delete orphaned media items using NOT EXISTS subquery+ if (allMediaIds.size === 0) {+ return;+ }++ const mediaIdChunks = chunk(Array.from(allMediaIds), 1000);++ for (const mediaIdChunk of mediaIdChunks) {+ // First, fetch media items that are orphaned (no references) to get their bucket paths+ const orphanedMedia = await prisma.media.findMany({+ select: {+ id: true,+ bucketPath: true,+ },+ where: {+ projectId,+ id: {+ in: mediaIdChunk,+ },+ TraceMedia: {+ none: {},+ },+ ObservationMedia: {+ none: {},+ },+ },+ });++ if (orphanedMedia.length > 0) {+ // Delete from S3+ await getS3MediaStorageClient(+ env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET ?? "", // Fallback is never used.+ ).deleteFiles(orphanedMedia.map((f) => f.bucketPath));++ // Delete from postgres+ await prisma.media.deleteMany({+ where: {+ projectId,+ id: {+ in: orphanedMedia.map((f) => f.id),+ },+ },+ });+ }+ }};export const processClickhouseTraceDelete = async (