🪢 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(worker): drop obsolete blob export job when integration deleted mid-run (LFE-14894) (#15938)
Niklas Semmlerc67ea78ef6cd
diff --git a/worker/src/__tests__/blobExportAbortObservability.unit.test.ts b/worker/src/__tests__/blobExportAbortObservability.unit.test.tsindex c95b261c65..5dc74ff3fe 100644--- a/worker/src/__tests__/blobExportAbortObservability.unit.test.ts+++ b/worker/src/__tests__/blobExportAbortObservability.unit.test.ts@@ -12,7 +12,9 @@ vi.mock("@langfuse/shared/src/db", () => ({blobStorageIntegration: {findUnique: vi.fn(),update: vi.fn().mockResolvedValue({}),- updateMany: vi.fn().mockResolvedValue({ count: 0 }),+ // count 1 = row still exists; 0 would signal deleted-mid-run and make+ // the handler drop the job as obsolete (LFE-14894).+ updateMany: vi.fn().mockResolvedValue({ count: 1 }),},project: { findUnique: vi.fn().mockResolvedValue({ name: "p" }) },},diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex a42aaa1881..898f12c659 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -61,6 +61,7 @@ import {handleBlobStorageIntegrationProjectJob,BLOB_STORAGE_LAG_BUFFER_MS,} from "../features/blobstorage/handleBlobStorageIntegrationProjectJob";+import { BLOB_INTEGRATION_DISABLED_METRIC } from "../features/blobstorage/isCustomerFaultError";import {BlobStorageIntegrationType,BlobStorageIntegrationFileType,@@ -407,6 +408,105 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ // LFE-14894: an integration deleted mid-run makes the job obsolete — it must+ // complete quietly instead of failing on the now-missing row (P2025) and+ // paging on a config that no longer exists.+ describe("integration deleted mid-run", () => {+ // endpoint must be non-null so the handler runs the preflight we stub —+ // that stub is the seam to delete the row after the initial load.+ const createIntegration = async (+ projectId: string,+ overrides: { exportFrequency?: string; lastSyncAt?: Date } = {},+ ) => {+ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: projectId,+ accessKeyId,+ secretAccessKey: encrypt(secretAccessKey),+ region: region ? region : "auto",+ endpoint: "https://customer-bucket.s3.example.com",+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: overrides.exportFrequency ?? "daily",+ exportSource: "TRACES_OBSERVATIONS",+ lastSyncAt:+ overrides.lastSyncAt ??+ new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),+ },+ });+ };++ it("drops the obsolete job instead of failing when the row is gone before the error is persisted", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ await createIntegration(projectId);+ mockRecordIncrement.mockClear();+ // Customer fault on the final attempt — normally disable + notify — but+ // the row vanishes before the catch block can persist anything.+ mockValidateBlobStorageEndpoint.mockImplementationOnce(async () => {+ await prisma.blobStorageIntegration.delete({ where: { projectId } });+ const err = new Error("Access Denied");+ err.name = "AccessDenied";+ Object.assign(err, {+ Code: "AccessDenied",+ $metadata: { httpStatusCode: 403 },+ });+ throw err;+ });++ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ attemptsMade: 4,+ opts: { attempts: 5 },+ } as Job),+ ).resolves.toBeUndefined();++ // Give fire-and-forget notification paths time to (not) run.+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(mockRecordIncrement).not.toHaveBeenCalledWith(+ BLOB_INTEGRATION_DISABLED_METRIC,+ expect.anything(),+ expect.anything(),+ );+ });++ it("drops the obsolete job instead of failing when the row is gone after a successful export", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ // Recent lastSyncAt keeps the window non-empty while staying caught up.+ await createIntegration(projectId, {+ exportFrequency: "hourly",+ lastSyncAt: new Date(+ Date.now() - BLOB_STORAGE_LAG_BUFFER_MS - 30 * 60 * 1000,+ ),+ });+ mockValidateBlobStorageEndpoint.mockImplementationOnce(async () => {+ await prisma.blobStorageIntegration.delete({ where: { projectId } });+ });+ const getInstanceSpy = vi+ .spyOn(StorageServiceFactory, "getInstance")+ .mockReturnValue({+ uploadFile: vi.fn().mockResolvedValue(undefined),+ uploadFileBuffered: vi.fn().mockResolvedValue(undefined),+ deleteFiles: vi.fn().mockResolvedValue(undefined),+ listFiles: vi.fn().mockResolvedValue([]),+ } as unknown as StorageService);++ try {+ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job),+ ).resolves.toBeUndefined();+ } finally {+ getInstanceSpy.mockRestore();+ }+ });+ });+it("should not process when blob storage integration is disabled", async () => {const { projectId } = await createOrgProjectAndApiKey();s3Prefix = projectId;diff --git a/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts b/worker/src/__tests__/blobStorageTuningWiring.unit.test.tsindex 5b76bacb08..75f4326882 100644--- a/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts+++ b/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts@@ -10,7 +10,9 @@ vi.mock("@langfuse/shared/src/db", () => ({blobStorageIntegration: {findUnique: vi.fn(),update: vi.fn().mockResolvedValue({}),- updateMany: vi.fn().mockResolvedValue({ count: 0 }),+ // count 1 = row still exists; 0 would signal deleted-mid-run and make+ // the handler drop the job as obsolete (LFE-14894).+ updateMany: vi.fn().mockResolvedValue({ count: 1 }),},project: { findUnique: vi.fn().mockResolvedValue({ name: "p" }) },},diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 15fa90ab26..2cca794ec9 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -1,7 +1,7 @@import { pipeline, Transform, type Readable } from "stream";import { monitorEventLoopDelay } from "perf_hooks";import { Job } from "bullmq";-import { prisma } from "@langfuse/shared/src/db";+import { prisma, Prisma } from "@langfuse/shared/src/db";import {QueueName,TQueueJobTypes,@@ -1158,6 +1158,13 @@ const removeBlobExportDeprecationNotice = async (params: {}};+// LFE-14894: the integration can be deleted while a run is in flight; a row+// write racing that delete throws P2025, which must mark the job obsolete+// rather than fail it.+const isRecordNotFoundError = (error: unknown): boolean =>+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2025";+export const handleBlobStorageIntegrationProjectJob = async (job: Job<TQueueJobTypes[QueueName.BlobStorageIntegrationProcessingQueue]>,) => {@@ -1197,17 +1204,23 @@ export const handleBlobStorageIntegrationProjectJob = async (logger.info(`[BLOB INTEGRATION] Blob storage integration is disabled for project ${projectId}`,);- await prisma.blobStorageIntegration.update({+ await prisma.blobStorageIntegration.updateMany({where: { projectId },data: { runStartedAt: null },});return;}- await prisma.blobStorageIntegration.update({+ const { count: claimed } = await prisma.blobStorageIntegration.updateMany({where: { projectId },data: { runStartedAt: new Date() },});+ if (claimed === 0) {+ logger.info(+ `[BLOB INTEGRATION] Blob storage integration for project ${projectId} was deleted before the run started; dropping obsolete job`,+ );+ return;+ }// Sync between lastSyncAt and now - 30 minutes// Cap the export to one frequency period to enable chunked historic exports@@ -1248,7 +1261,7 @@ export const handleBlobStorageIntegrationProjectJob = async (logger.info(`[BLOB INTEGRATION] Skipping export for project ${projectId}: time window is empty (min: ${minTimestamp.toISOString()}, max: ${maxTimestamp.toISOString()})`,);- await prisma.blobStorageIntegration.update({+ await prisma.blobStorageIntegration.updateMany({where: { projectId },data: {runStartedAt: null,@@ -1477,19 +1490,29 @@ export const handleBlobStorageIntegrationProjectJob = async ();}- // Update integration after successful processing- await prisma.blobStorageIntegration.update({- where: {- projectId,- },- data: {- lastSyncAt: maxTimestamp,- nextSyncAt,- lastError: null,- lastErrorAt: null,- runStartedAt: null,+ // Update integration after successful processing. count === 0 means the+ // integration was deleted mid-run — skip the catch-up re-enqueue below,+ // the job is obsolete.+ const { count: persisted } = await prisma.blobStorageIntegration.updateMany(+ {+ where: {+ projectId,+ },+ data: {+ lastSyncAt: maxTimestamp,+ nextSyncAt,+ lastError: null,+ lastErrorAt: null,+ runStartedAt: null,+ },},- });+ );+ if (persisted === 0) {+ logger.info(+ `[BLOB INTEGRATION] Blob storage integration for project ${projectId} was deleted mid-run; dropping obsolete job after successful export`,+ );+ return;+ }// If still catching up, immediately queue the next chunk jobif (!caughtUp) {@@ -1569,6 +1592,15 @@ export const handleBlobStorageIntegrationProjectJob = async (}}} catch (persistError) {+ if (isRecordNotFoundError(persistError)) {+ // Integration deleted mid-run: nothing to persist, nobody to notify —+ // the notification would reference a config that no longer exists.+ // Complete the obsolete job instead of failing it.+ logger.info(+ `[BLOB INTEGRATION] Blob storage integration for project ${projectId} was deleted mid-run; dropping obsolete job after error: ${errorMessage}`,+ );+ return;+ }logger.error(`[BLOB INTEGRATION] Failed to persist blob storage error for project ${projectId}`,persistError,