🪢 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(blob-storage): fail loud on S3 multipart part-count limit (#17304)
Niklas Semmler9698074b624d
diff --git a/packages/shared/src/server/services/S3ChunkedUploadStrategy.ts b/packages/shared/src/server/services/S3ChunkedUploadStrategy.tsindex ebb25fde7f..5ab70b2898 100644--- a/packages/shared/src/server/services/S3ChunkedUploadStrategy.ts+++ b/packages/shared/src/server/services/S3ChunkedUploadStrategy.ts@@ -13,6 +13,12 @@ import type {} from "./BufferedStreamUploader";import { type S3SseConfig, buildS3SseParams } from "./StorageService";+// S3 caps a multipart upload at 10,000 parts. lib-storage enforces this+// client-side ("Exceeded 10000 parts"); the raw UploadPart calls below do not,+// so guard it here with the same wording. Without it, S3 rejects part 10,001+// with a differently-worded error the export's terminal-failure detector misses.+export const S3_MAX_MULTIPART_PARTS = 10_000;+export interface S3ChunkedUploadStrategyParams {client: S3Client;bucket: string;@@ -47,6 +53,12 @@ export class S3ChunkedUploadStrategy implements ChunkedUploadStrategy {}async uploadPart(data: Buffer, partNumber: number): Promise<CompletedPart> {+ if (partNumber > S3_MAX_MULTIPART_PARTS) {+ throw new Error(+ `Exceeded ${S3_MAX_MULTIPART_PARTS} parts in multipart upload to ${this.params.key}`,+ );+ }+const response = await this.params.client.send(new UploadPartCommand({Bucket: this.params.bucket,diff --git a/worker/src/__tests__/blobExportPartLimitError.unit.test.ts b/worker/src/__tests__/blobExportPartLimitError.unit.test.tsnew file mode 100644index 0000000000..56039f8bb8--- /dev/null+++ b/worker/src/__tests__/blobExportPartLimitError.unit.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { isMultipartPartLimitError } from "../features/blobstorage/partLimitError";++// Mirrors handleStorageError's wrapping of the underlying SDK cause.+function uploadWrapped(cause: unknown): Error {+ return new Error("Failed to upload file to S3", { cause });+}++// The exact @aws-sdk/lib-storage message.+const AWS_PART_LIMIT_MESSAGE =+ "Exceeded 10000 parts in multipart upload to Bucket: my-bucket Key: p/traces/2026-01-01.json.";++describe("isMultipartPartLimitError", () => {+ it("matches the raw AWS SDK part-limit message", () => {+ expect(isMultipartPartLimitError(new Error(AWS_PART_LIMIT_MESSAGE))).toBe(+ true,+ );+ });++ it("matches the message through StorageService's cause wrapping", () => {+ expect(+ isMultipartPartLimitError(+ uploadWrapped(new Error(AWS_PART_LIMIT_MESSAGE)),+ ),+ ).toBe(true);+ });++ it("tolerates wording drift (case, no multipart-upload tail)", () => {+ expect(isMultipartPartLimitError(new Error("EXCEEDED 10000 PARTS"))).toBe(+ true,+ );+ expect(isMultipartPartLimitError(new Error("Exceeded 10,000 parts"))).toBe(+ true,+ );+ });++ it("does not match unrelated upload errors", () => {+ expect(isMultipartPartLimitError(new Error("Access Denied"))).toBe(false);+ expect(+ isMultipartPartLimitError(uploadWrapped(new Error("connection reset"))),+ ).toBe(false);+ expect(isMultipartPartLimitError(undefined)).toBe(false);+ expect(isMultipartPartLimitError("some string")).toBe(false);+ });+});diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 275693fb93..58cc5eb53e 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -23,6 +23,10 @@ const mockRecordDistribution = vi.hoisted(() => vi.fn());// Stubbable endpoint preflight — the customer-fault tests reject it to drive an// in-try failure without infra. Defaults to the real impl for other tests.const mockValidateBlobStorageEndpoint = vi.hoisted(() => vi.fn());+// Spy on the failure notification dispatch so the part-limit test can assert it+// fired (a cooldown-bypassed notification leaves no lastFailureNotificationSentAt+// stamp to observe). Defaults to a no-op so real notification infra isn't needed.+const mockDispatchProjectNotification = vi.hoisted(() => vi.fn());vi.mock("@langfuse/shared/src/server", async (importOriginal) => {const actual =await importOriginal<typeof import("@langfuse/shared/src/server")>();@@ -31,12 +35,16 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {actual.validateBlobStorageEndpoint,);}+ if (mockDispatchProjectNotification.getMockImplementation() === undefined) {+ mockDispatchProjectNotification.mockResolvedValue(undefined);+ }return {...actual,recordIncrement: mockRecordIncrement,recordHistogram: mockRecordHistogram,recordDistribution: mockRecordDistribution,validateBlobStorageEndpoint: mockValidateBlobStorageEndpoint,+ dispatchProjectNotification: mockDispatchProjectNotification,};});@@ -60,11 +68,12 @@ import {} from "@langfuse/shared/src/server";import { EXPORT_FRESHNESS_LAG_METRIC } from "../services/exportFreshnessLagMetric";import { prisma } from "@langfuse/shared/src/db";-import { Job } from "bullmq";+import { Job, UnrecoverableError } from "bullmq";import {handleBlobStorageIntegrationProjectJob,BLOB_STORAGE_LAG_BUFFER_MS,BLOB_STORAGE_REMAINDER_COALESCE_MS,+ BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE,} from "../features/blobstorage/handleBlobStorageIntegrationProjectJob";import { BLOB_INTEGRATION_DISABLED_METRIC } from "../features/blobstorage/isCustomerFaultError";import {@@ -546,6 +555,146 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ // A multipart part-count-limit exhaustion is terminal: retrying re-queries a+ // retention-shrinking window until a truncated object commits as success. The+ // run must fail loud (UnrecoverableError, no retry, notification) and stop —+ // without auto-disabling or advancing the export watermark.+ describe("multipart part-limit failure", () => {+ const lastSyncAt = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);++ const createIntegration = async (projectId: string) => {+ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: projectId,+ accessKeyId: minioAccessKeyId,+ secretAccessKey: encrypt(minioAccessKeySecret),+ region: region ? region : "auto",+ // endpoint null -> skip the persisted-endpoint preflight; the storage+ // service is mocked anyway.+ endpoint: null,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: "daily",+ // Non-enriched source: runs outside the V4-preview guard on every leg.+ exportSource: "TRACES_OBSERVATIONS",+ lastSyncAt,+ },+ });+ };++ // The exact @aws-sdk/lib-storage message, wrapped the way+ // StorageService.handleStorageError wraps the SDK cause.+ const partLimitError = () =>+ new Error("Failed to upload file to S3", {+ cause: new Error(+ "Exceeded 10000 parts in multipart upload to Bucket: b Key: k.",+ ),+ });++ const settleBackgroundTasks = () =>+ new Promise((resolve) => setTimeout(resolve, 200));++ it("fails terminally without retry, persists lastError, notifies, keeps enabled, and does not advance the watermark", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ // No s3Prefix: the storage service is mocked, so nothing is uploaded and+ // the MinIO cleanup in afterEach must not run.+ await createIntegration(projectId);+ mockDispatchProjectNotification.mockClear();++ const getInstanceSpy = vi+ .spyOn(StorageServiceFactory, "getInstance")+ .mockReturnValue({+ uploadFileBuffered: vi.fn().mockRejectedValue(partLimitError()),+ } as unknown as StorageService);++ try {+ // Attempt 0 of 5: a transient error would retry, so rejecting with+ // UnrecoverableError here is the proof that no retry will happen.+ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ attemptsMade: 0,+ opts: { attempts: 5 },+ } as Job),+ ).rejects.toBeInstanceOf(UnrecoverableError);+ await settleBackgroundTasks();+ } finally {+ getInstanceSpy.mockRestore();+ }++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(row.lastError).toBe(BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE);+ expect(row.lastErrorAt).not.toBeNull();+ // Not a customer-config fault: the integration stays on.+ expect(row.enabled).toBe(true);+ // Watermark untouched so the failed window is not skipped on the next run.+ expect(row.lastSyncAt?.getTime()).toBe(lastSyncAt.getTime());++ // Notification fired, as a failure (not the disabled variant).+ expect(mockDispatchProjectNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ projectId,+ event: expect.objectContaining({+ eventType: "blob-export-failed",+ disabled: false,+ }),+ }),+ );+ });++ // A user toggle (or concurrent disable) landing mid-run leaves the row+ // disabled by the time the terminal catch records the failure. Still fail+ // loud (UnrecoverableError, lastError recorded) but suppress the+ // informational alert, mirroring the generic terminal path's stillEnabled+ // gate: "will retry at the next scheduled export" is false once it is off.+ it("suppresses the failure notification when the integration was disabled mid-run", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ await createIntegration(projectId);+ mockDispatchProjectNotification.mockClear();++ const getInstanceSpy = vi+ .spyOn(StorageServiceFactory, "getInstance")+ .mockReturnValue({+ uploadFileBuffered: vi.fn().mockImplementation(async () => {+ await prisma.blobStorageIntegration.updateMany({+ where: { projectId },+ data: { enabled: false },+ });+ throw partLimitError();+ }),+ } as unknown as StorageService);++ try {+ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ attemptsMade: 0,+ opts: { attempts: 5 },+ } as Job),+ ).rejects.toBeInstanceOf(UnrecoverableError);+ await settleBackgroundTasks();+ } finally {+ getInstanceSpy.mockRestore();+ }++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ // Still terminal: the failure is recorded and the run does not retry.+ expect(row.lastError).toBe(BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE);+ expect(row.enabled).toBe(false);+ // No alert: the integration is off, so the informational variant would be+ // misleading.+ expect(mockDispatchProjectNotification).not.toHaveBeenCalled();+ });+ });+// 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.diff --git a/worker/src/__tests__/bufferedStreamUploader.test.ts b/worker/src/__tests__/bufferedStreamUploader.test.tsindex 2a1b44b7af..f215b8a108 100644--- a/worker/src/__tests__/bufferedStreamUploader.test.ts+++ b/worker/src/__tests__/bufferedStreamUploader.test.ts@@ -7,8 +7,12 @@ import {type ChunkedUploadStrategy,type CompletedPart,} from "@langfuse/shared/src/server";-import { S3ChunkedUploadStrategy } from "@langfuse/shared/src/server";+import {+ S3ChunkedUploadStrategy,+ S3_MAX_MULTIPART_PARTS,+} from "@langfuse/shared/src/server";import { logger } from "@langfuse/shared/src/server";+import { isMultipartPartLimitError } from "../features/blobstorage/partLimitError";/*** Creates a mock ChunkedUploadStrategy that records method calls.@@ -674,6 +678,50 @@ describe("S3ChunkedUploadStrategy", () => {return { client: { send } as any, sentCommands };}+ describe("part-count limit guard", () => {+ it("throws a detectable part-limit error before sending an over-limit part", async () => {+ const mock = createMockS3Client();+ const strategy = new S3ChunkedUploadStrategy({+ client: mock.client,+ bucket: "test-bucket",+ key: "big-export.parquet",+ contentType: "application/octet-stream",+ });+ await strategy.initialize();++ let thrown: unknown;+ try {+ await strategy.uploadPart(Buffer.from("x"), S3_MAX_MULTIPART_PARTS + 1);+ } catch (e) {+ thrown = e;+ }++ expect(thrown).toBeInstanceOf(Error);+ // The blob export's terminal-failure detector must recognise this wording;+ // otherwise the buffered path silently retries into truncated success.+ expect(isMultipartPartLimitError(thrown)).toBe(true);+ // Guard is pre-flight: no UploadPart for the over-limit part reached S3.+ expect(+ mock.sentCommands.some((c) => c.name === "UploadPartCommand"),+ ).toBe(false);+ });++ it("allows the last valid part number", async () => {+ const mock = createMockS3Client();+ const strategy = new S3ChunkedUploadStrategy({+ client: mock.client,+ bucket: "test-bucket",+ key: "big-export.parquet",+ contentType: "application/octet-stream",+ });+ await strategy.initialize();++ await expect(+ strategy.uploadPart(Buffer.from("x"), S3_MAX_MULTIPART_PARTS),+ ).resolves.toBeDefined();+ });+ });+describe("S3 command mapping", () => {it("should map initialize to CreateMultipartUploadCommand with SSE params", async () => {const mock = createMockS3Client();diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 27e4ca28d6..523947ca08 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -1,6 +1,6 @@import { pipeline, Transform, type Readable } from "stream";import { monitorEventLoopDelay } from "perf_hooks";-import { Job } from "bullmq";+import { Job, UnrecoverableError } from "bullmq";import { prisma } from "@langfuse/shared/src/db";import {QueueName,@@ -51,6 +51,7 @@ import {classifyCustomerFault,type CustomerFaultReason,} from "./isCustomerFaultError";+import { isMultipartPartLimitError } from "./partLimitError";import { isRecordNotFoundError } from "../integrations/prismaErrors";import { isFinalBullmqAttempt } from "../integrations/bullmqAttempts";import { ByteCounter, TimedByteCounter } from "./byteCounters";@@ -150,6 +151,14 @@ export const BLOB_STORAGE_LAG_BUFFER_MS = 20 * 60 * 1000; // 20-minute lag buffe// is deferred.export const BLOB_STORAGE_REMAINDER_COALESCE_MS = 1000;+// Persisted as lastError when a window exceeds S3's 10,000-part multipart cap.+// Retrying re-queries a retention-shrinking window until a truncated object+// commits as success, so the run stops loud instead of degrading silently.+export const BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE =+ "Blob storage export stopped: the export window exceeded the storage provider's " ++ "10,000-part multipart upload limit. Increase the upload part size or reduce the " ++ "export frequency so each window fits within the limit.";+export async function* enrichObservationStream(stream: AsyncGenerator<Record<string, unknown>>,projectId: string,@@ -1561,6 +1570,69 @@ export const handleBlobStorageIntegrationProjectJob = async (`[BLOB INTEGRATION] Successfully processed blob storage integration for project ${projectId}`,);} catch (error) {+ // A part-count-limit exhaustion is terminal, not transient: the window is+ // too large for the configured part size and no retry can shrink it safely.+ // Fail loud and stop before BullMQ burns its remaining attempts re-querying+ // ClickHouse against a retention-shrinking window. Runs BEFORE the generic+ // customer-fault/transient handling below.+ if (isMultipartPartLimitError(error)) {+ // Missing-row-safe: a delete mid-run makes the job obsolete. lastSyncAt /+ // nextSyncAt are left untouched so the window is not advanced past a+ // failed export. enabled is left untouched: a too-large window is not a+ // customer-config fault, so this never auto-disables. update (not+ // updateMany) so the notification can read the post-write enabled state.+ let integration;+ try {+ integration = await prisma.blobStorageIntegration.update({+ where: { projectId },+ data: {+ lastError: BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE,+ lastErrorAt: new Date(),+ runStartedAt: null,+ },+ });+ } catch (persistError) {+ if (isRecordNotFoundError(persistError)) {+ logger.info(+ `[BLOB INTEGRATION] Blob storage integration for project ${projectId} was deleted before the part-limit failure could be recorded; dropping obsolete job`,+ );+ return;+ }+ throw persistError;+ }++ if (!watermarkAdvanced) {+ recordExportFreshnessLag({+ integration: "blob_storage",+ window: windowClassFromBlobFrequency(+ blobStorageIntegration.exportFrequency,+ ),+ status: "failure",+ runStartTime,+ maxExportedTimestamp: blobStorageIntegration.lastSyncAt,+ });+ }++ // Cooldown-gated, not bypassed: the integration stays enabled and the+ // watermark does not advance, so every scheduled run re-attempts the same+ // too-large window and re-enters here. The cooldown caps this to one alert+ // per cooldown window instead of one per run. (The disable notification+ // bypasses the cooldown because it is a one-shot terminal event.)+ //+ // Gated on the post-write enabled state, mirroring the generic terminal+ // path's stillEnabled check: a user who disabled the integration mid-run+ // must not get an "export failed" alert for a run they already turned off.+ if (integration.enabled) {+ await notifyBlobStorageExportFailed(projectId, { disabled: false });+ }++ logger.error(+ `[BLOB INTEGRATION] Blob storage export for project ${projectId} exceeded the multipart part-count limit; failing terminally without retry: ${errorChainText(error)}`,+ );+ // UnrecoverableError so BullMQ fails the job now instead of retrying.+ throw new UnrecoverableError(BLOB_EXPORT_PART_LIMIT_ERROR_MESSAGE);+ }+const errorMessage = extractStorageErrorMessage(error);const isFinalAttempt = isFinalBullmqAttempt(job, error);@@ -1594,7 +1666,7 @@ export const handleBlobStorageIntegrationProjectJob = async (case "disabled-by-us":// Awaited: the integration is now off, so the scheduler never revisits// it and nothing would carry an interrupted dispatch.- await notifyBlobStorageExportFailed(projectId, true);+ await notifyBlobStorageExportFailed(projectId, { disabled: true });return; // resolving is the point; a throw would light the monitorcase "lost-disable-race":return; // the winner sent the terminal email@@ -1603,7 +1675,7 @@ export const handleBlobStorageIntegrationProjectJob = async (// scheduled export" is no longer true. Not awaited: this path rethrows,// so the job is about to fail and be retried regardless.if (isFinalAttempt && outcome.stillEnabled) {- notifyBlobStorageExportFailed(projectId, false);+ notifyBlobStorageExportFailed(projectId, { disabled: false });}break;case "persist-failed":@@ -1711,16 +1783,19 @@ async function recordTerminalExportError({// even on the awaited path; the persisted lastError is the durable signal.async function notifyBlobStorageExportFailed(projectId: string,- disabled = false,+ {+ disabled = false,+ bypassCooldown = disabled,+ }: { disabled?: boolean; bypassCooldown?: boolean } = {},): Promise<void> {try {// Called once per exhausted run. The cooldown gates across scheduled// runs (the scheduler re-enqueues every frequency period, and each- // failing run would otherwise email again). The disable notification- // bypasses it: it is a one-time, terminal event — the integration- // won't run again until the customer re-enables it — and a cooldown- // claim could silently drop the one email that says it was turned off.- if (!disabled) {+ // failing run would otherwise email again). The disable notice bypasses+ // it: that is a one-shot terminal event and a cooldown claim could+ // silently drop the single email saying the integration was turned off.+ // Recurring failures stay gated so they alert once per window, not per run.+ if (!bypassCooldown) {const cooldownMs =env.LANGFUSE_BLOB_STORAGE_FAILURE_NOTIFICATION_COOLDOWN_HOURS *60 *diff --git a/worker/src/features/blobstorage/partLimitError.ts b/worker/src/features/blobstorage/partLimitError.tsnew file mode 100644index 0000000000..d3ec68c48a--- /dev/null+++ b/worker/src/features/blobstorage/partLimitError.ts@@ -0,0 +1,17 @@+import { errorChainText } from "./abortClassification";++/**+ * Detect an S3 multipart-upload part-count-limit exhaustion.+ *+ * `@aws-sdk/lib-storage` throws `Exceeded 10000 parts in multipart upload ...`+ * when a stream needs more than S3's 10,000-part cap. The SDK exposes no stable+ * error code for it, so we match the message across the wrapped cause chain+ * (StorageService.handleStorageError wraps SDK errors via `new Error(_, { cause })`).+ * The pattern tolerates wording drift (case, the part count, an absent+ * "multipart upload" tail) so it survives an SDK message change.+ */+const PART_LIMIT_PATTERN = /exceeded\s+[\d,_]+\s+parts/i;++export function isMultipartPartLimitError(error: unknown): boolean {+ return PART_LIMIT_PATTERN.test(errorChainText(error));+}