🪢 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(blob-export): classify and log abort origin cause (LFE-10388) (#14632)
Niklas Semmler57a7731084ea
diff --git a/worker/src/__tests__/blobExportAbortClassification.unit.test.ts b/worker/src/__tests__/blobExportAbortClassification.unit.test.tsnew file mode 100644index 0000000000..bcf2b11bd4--- /dev/null+++ b/worker/src/__tests__/blobExportAbortClassification.unit.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from "vitest";+import {+ BlobExportAbortTracker,+ classifyBlobExportError,+ errorChainText,+} from "../features/blobstorage/abortClassification";++// Mirrors the ClickHouse repository's enrichWithQueryId wrapping.+function withQueryId(message: string, queryId = "qid-123"): Error {+ const base = new Error(message);+ return new Error(`${base.message} [query_id: ${queryId}]`, { cause: base });+}++// Mirrors handleStorageError's wrapping of the underlying cause.+function uploadWrapped(cause: unknown): Error {+ return new Error("Failed to upload file to S3 (buffered)", { cause });+}++describe("errorChainText", () => {+ it("flattens the cause chain with messages and codes", () => {+ const root: NodeJS.ErrnoException = new Error("socket hang up");+ root.code = "ECONNRESET";+ const wrapped = uploadWrapped(root);+ const text = errorChainText(wrapped);+ expect(text).toContain("Failed to upload file to S3 (buffered)");+ expect(text).toContain("socket hang up");+ expect(text).toContain("ECONNRESET");+ });++ it("is cycle-safe", () => {+ const a = new Error("a");+ const b = new Error("b", { cause: a });+ (a as Error & { cause?: unknown }).cause = b;+ expect(() => errorChainText(a)).not.toThrow();+ });++ it("preserves an appended query_id", () => {+ expect(errorChainText(withQueryId("aborted"))).toContain(+ "[query_id: qid-123]",+ );+ });+});++describe("BlobExportAbortTracker.origin", () => {+ it("returns undefined when nothing recorded", () => {+ expect(new BlobExportAbortTracker().origin()).toBeUndefined();+ });++ it("classifies a concrete ClickHouse exception as ch-error", () => {+ const t = new BlobExportAbortTracker();+ t.record(+ "ch-read",+ withQueryId("Code: 241. DB::Exception: Memory limit exceeded"),+ 1,+ );+ const origin = t.origin();+ expect(origin?.reason).toBe("ch-error");+ expect(origin?.stage).toBe("ch-read");+ expect(origin?.concrete).toBe(true);+ expect(origin?.chain).toContain("query_id");+ });++ it("classifies a concrete S3 fault as upload-error even when ch-read also tore down", () => {+ const t = new BlobExportAbortTracker();+ // ch-read records the teardown first (earlier timestamp)...+ t.record("ch-read", new Error("Premature close"), 1);+ // ...but the concrete S3 fault is the real cause and must win.+ t.record("upload", uploadWrapped(new Error("SlowDown: reduce rate")), 2);+ const origin = t.origin();+ expect(origin?.reason).toBe("upload-error");+ expect(origin?.stage).toBe("upload");+ expect(origin?.concrete).toBe(true);+ });++ it("attributes a bare mutual 'aborted' to the stage that failed first (ch-read)", () => {+ // The prod-us signature: CH stream aborts first, the upload then surfaces+ // the same wrapped 'aborted [query_id]'. Both are generic teardown, so the+ // earliest (ch-read) wins with best-effort attribution.+ const t = new BlobExportAbortTracker();+ const chAborted = withQueryId("aborted");+ t.record("ch-read", chAborted, 1);+ t.record("upload", uploadWrapped(chAborted), 2);+ const origin = t.origin();+ expect(origin?.reason).toBe("ch-error");+ expect(origin?.stage).toBe("ch-read");+ expect(origin?.concrete).toBe(false);+ expect(origin?.chain).toContain("[query_id: qid-123]");+ });++ it("does not misclassify an S3 HTTP 'status code: 503' as ch-error", () => {+ // Regression: a bare `code:\s*\d+` matched "status code: 503" and flipped+ // upload errors to ch-error. The S3 message has no upload-fault keyword, so+ // it must fall through to stage attribution (upload), not CH detection.+ const t = new BlobExportAbortTracker();+ t.record(+ "upload",+ uploadWrapped(+ new Error(+ "InternalError: We encountered an internal error. status code: 503",+ ),+ ),+ 1,+ );+ expect(t.origin()?.reason).toBe("upload-error");+ });++ it("classifies a DB::NetException socket timeout as ch-error", () => {+ const t = new BlobExportAbortTracker();+ t.record(+ "upload",+ uploadWrapped(+ withQueryId(+ "Code: 209. DB::NetException: Timeout exceeded while reading from socket",+ ),+ ),+ 1,+ );+ expect(t.origin()?.reason).toBe("ch-error");+ });++ it("classifies a shutdown-stage record as shutdown", () => {+ const t = new BlobExportAbortTracker();+ t.record("ch-read", new Error("aborted"), 1);+ t.record("shutdown", new Error("aborted"), 2);+ expect(t.origin()?.reason).toBe("shutdown");+ });++ it("prefers a concrete fault over an earlier generic teardown regardless of order", () => {+ const t = new BlobExportAbortTracker();+ t.record("upload", uploadWrapped(new Error("socket hang up")), 5);+ t.record(+ "ch-read",+ withQueryId("Code: 159. DB::Exception: Timeout exceeded"),+ 10,+ );+ expect(t.origin()?.reason).toBe("ch-error");+ });+});++describe("classifyBlobExportError", () => {+ it("classifies an unknown-stage generic error as unknown", () => {+ const origin = classifyBlobExportError(new Error("aborted"));+ expect(origin.reason).toBe("unknown");+ expect(origin.stage).toBe("unknown");+ });++ it("classifies a ClickHouse exception by its chain even without stage", () => {+ const origin = classifyBlobExportError(+ withQueryId("Code: 241. DB::Exception: Memory limit exceeded"),+ );+ expect(origin.reason).toBe("ch-error");+ });+});diff --git a/worker/src/__tests__/blobExportAbortObservability.unit.test.ts b/worker/src/__tests__/blobExportAbortObservability.unit.test.tsnew file mode 100644index 0000000000..c95b261c65--- /dev/null+++ b/worker/src/__tests__/blobExportAbortObservability.unit.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++// Captured recordIncrement calls so we can assert the abortReason tag is+// emitted on the failure metric. Hoisted so the module mock can close over it.+const incrementCalls = vi.hoisted(+ () => [] as { stat: string; tags: Record<string, string | number> }[],+);+const errorLogs = vi.hoisted(() => [] as { msg: string; meta: unknown }[]);++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ blobStorageIntegration: {+ findUnique: vi.fn(),+ update: vi.fn().mockResolvedValue({}),+ updateMany: vi.fn().mockResolvedValue({ count: 0 }),+ },+ project: { findUnique: vi.fn().mockResolvedValue({ name: "p" }) },+ },+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const mod =+ await importOriginal<typeof import("@langfuse/shared/src/server")>();++ // Mirrors enrichWithQueryId: a real CH exception with a query_id appended.+ async function* throwsChException(): AsyncGenerator<Record<string, unknown>> {+ const root = new Error("Code: 241. DB::Exception: Memory limit exceeded");+ throw new Error(`${root.message} [query_id: qid-xyz]`, { cause: root });+ // eslint-disable-next-line no-unreachable+ yield {};+ }+ async function* empty(): AsyncGenerator<Record<string, unknown>> {+ // no rows+ }++ return {+ ...mod,+ recordIncrement: vi.fn(+ (stat: string, _value?: number, tags?: Record<string, string | number>) =>+ incrementCalls.push({ stat, tags: tags ?? {} }),+ ),+ logger: {+ ...mod.logger,+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn((msg: string, meta: unknown) =>+ errorLogs.push({ msg, meta }),+ ),+ },+ StorageServiceFactory: {+ getInstance: () => ({+ uploadFileBuffered: vi.fn(async (params: any) => {+ // Draining the pipeline stream throws the CH error mid-stream — the+ // real teardown path the worker sees in prod.+ for await (const _chunk of params.data) {+ void _chunk;+ }+ return undefined;+ }),+ }),+ },+ getTracesForBlobStorageExport: () => empty(),+ getScoresForBlobStorageExport: () => empty(),+ getObservationsForBlobStorageExport: () => throwsChException(),+ createModelCache: () => ({ getModel: async () => null }),+ blobStorageEndpointConnectionValidationOptions: () => undefined,+ };+});++import { prisma } from "@langfuse/shared/src/db";+import { handleBlobStorageIntegrationProjectJob } from "../features/blobstorage/handleBlobStorageIntegrationProjectJob";+import type { Job } from "bullmq";++function makeJob(): Job<any> {+ return {+ id: "job-1",+ attemptsMade: 0,+ data: { id: "payload-1", payload: { projectId: "project-1" } },+ } as unknown as Job<any>;+}++function baseRow() {+ return {+ projectId: "project-1",+ type: "S3",+ bucketName: "bucket",+ prefix: "",+ accessKeyId: "k",+ secretAccessKey: null,+ region: "auto",+ endpoint: null,+ forcePathStyle: false,+ enabled: true,+ exportFrequency: "daily",+ fileType: "JSONL",+ exportMode: "FROM_CUSTOM_DATE",+ exportStartDate: new Date(Date.now() - 2 * 60 * 60 * 1000),+ exportSource: "TRACES_OBSERVATIONS",+ exportFieldGroups: ["core"],+ compressed: false,+ lastSyncAt: new Date(Date.now() - 2 * 60 * 60 * 1000),+ createdAt: new Date("2026-01-01T00:00:00Z"),+ exportTuning: null,+ };+}++describe("blob export abort observability", () => {+ beforeEach(() => {+ incrementCalls.length = 0;+ errorLogs.length = 0;+ vi.clearAllMocks();+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue(+ baseRow(),+ );+ });++ it("surfaces a mid-stream ClickHouse teardown as abortReason=ch-error", async () => {+ await expect(+ handleBlobStorageIntegrationProjectJob(makeJob()),+ ).rejects.toBeTruthy();++ // Failure metric carries the classified abort reason for the observations+ // table (the one whose CH read threw).+ const failure = incrementCalls.find(+ (c) =>+ c.stat === "langfuse.blobstorage.table_export.count" &&+ c.tags.outcome === "failure" &&+ c.tags.table === "observations",+ );+ expect(failure).toBeDefined();+ expect(failure?.tags.abortReason).toBe("ch-error");++ // Per-table error log names the reason, stage, and preserves the query_id.+ const exportErr = errorLogs.find((l) =>+ l.msg.includes("Error exporting observations"),+ );+ expect(exportErr).toBeDefined();+ expect(exportErr?.msg).toContain("abortReason=ch-error");+ expect(exportErr?.msg).toContain("abortStage=ch-read");+ expect(exportErr?.msg).toContain("[query_id: qid-xyz]");+ });+});diff --git a/worker/src/__tests__/inFlightExports.unit.test.ts b/worker/src/__tests__/inFlightExports.unit.test.tsindex e72eee6942..9f87c2fb83 100644--- a/worker/src/__tests__/inFlightExports.unit.test.ts+++ b/worker/src/__tests__/inFlightExports.unit.test.ts@@ -82,6 +82,7 @@ describe("inFlightExports", () => {1,{outcome: "aborted",+ abortReason: "shutdown",table: "observations_v2",projectId: "p-1",},@@ -91,6 +92,7 @@ describe("inFlightExports", () => {1,{outcome: "aborted",+ abortReason: "shutdown",table: "scores",projectId: "p-1",},diff --git a/worker/src/features/blobstorage/abortClassification.ts b/worker/src/features/blobstorage/abortClassification.tsnew file mode 100644index 0000000000..f075738c21--- /dev/null+++ b/worker/src/features/blobstorage/abortClassification.ts@@ -0,0 +1,179 @@+/**+ * Blob-export abort classification (LFE-10063 / LFE-10388).+ *+ * A table export joins two concurrent stages with a Node `stream.pipeline`: the+ * ClickHouse read and the S3/object-storage upload. When either fails the+ * pipeline tears down and *both* stages surface a generic "aborted" — so the+ * worker logged a bare `aborted` and lost the originating cause. This module+ * records each stage's error and picks the cause (a concrete fault outranks a+ * generic teardown; ties broken by recency), yielding a filterable+ * `abortReason` plus the full cause chain for the log line.+ */++// "ch-read" = the ClickHouse read pipeline (its `stream.pipeline` callback),+// "upload" = the object-storage upload, "shutdown" = graceful SIGTERM.+export type BlobExportAbortStage =+ | "ch-read"+ | "upload"+ | "shutdown"+ | "unknown";++export type BlobExportAbortReason =+ | "ch-error"+ | "upload-error"+ | "stall"+ | "shutdown"+ | "unknown";++export interface BlobExportAbortOrigin {+ reason: BlobExportAbortReason;+ stage: BlobExportAbortStage;+ // False when the cause was only a generic teardown attributed by stage; the+ // log flags this as best-effort.+ concrete: boolean;+ chain: string;+}++interface RecordedStageError {+ stage: BlobExportAbortStage;+ error: unknown;+ at: number;+}++// A teardown signature tells us the pipeline collapsed, not why — never concrete.+const GENERIC_TEARDOWN_PATTERNS = [+ "aborted",+ "premature close",+ "operation was aborted",+ "econnreset",+ "connection reset",+ "socket hang up",+ "epipe",+ "broken pipe",+];++// `db::\w*exception` covers DB::Exception, DB::NetException, etc. A bare+// `code:\s*\d+` is excluded: it also matches S3/Azure "status code: 503" and+// would misclassify upload errors as ch-error.+const CH_EXCEPTION_PATTERN =+ /db::\w*exception|memory_limit_exceeded|timeout_exceeded|too_many_simultaneous_queries|socket_timeout|cannot_schedule_task/;++const UPLOAD_FAULT_PATTERN =+ /slowdown|access denied|accessdenied|nosuchupload|nosuchbucket|entitytoolarge|requesttimeout|invalidpart|signaturedoesnotmatch|notimplemented|preconditionfailed/;++// Rarely reaches this path (a BullMQ stall re-enqueues rather than throwing).+const STALL_PATTERN = /stalled|missing lock|lock.*(lapse|renew)/;++/**+ * Flatten an error's `cause` chain into one string. Cycle-safe. A `query_id`+ * appended by the ClickHouse repository survives here, keeping the pointer into+ * `system.query_log`.+ */+export function errorChainText(error: unknown): string {+ const parts: string[] = [];+ let current: unknown = error;+ const seen = new Set<unknown>();+ while (current != null && !seen.has(current)) {+ seen.add(current);+ if (current instanceof Error) {+ if (current.message) parts.push(current.message);+ const code = (current as NodeJS.ErrnoException).code;+ if (code) parts.push(String(code));+ if (current.name && current.name !== "Error") parts.push(current.name);+ current = current.cause;+ } else {+ parts.push(String(current));+ break;+ }+ }+ return parts.join(" caused by ");+}++function classifyOne(rec: RecordedStageError): {+ reason: BlobExportAbortReason;+ concrete: boolean;+} {+ const text = errorChainText(rec.error).toLowerCase();++ if (rec.stage === "shutdown" || text.includes("sigterm")) {+ return { reason: "shutdown", concrete: true };+ }+ if (STALL_PATTERN.test(text)) {+ return { reason: "stall", concrete: true };+ }+ // CH/upload faults win regardless of stage — the wrapped upload error carries+ // the CH cause in its chain.+ if (CH_EXCEPTION_PATTERN.test(text)) {+ return { reason: "ch-error", concrete: true };+ }+ if (UPLOAD_FAULT_PATTERN.test(text)) {+ return { reason: "upload-error", concrete: true };+ }++ // Only a generic teardown left: attribute by the observing stage, non-concrete.+ if (GENERIC_TEARDOWN_PATTERNS.some((p) => text.includes(p))) {+ if (rec.stage === "ch-read") return { reason: "ch-error", concrete: false };+ if (rec.stage === "upload")+ return { reason: "upload-error", concrete: false };+ return { reason: "unknown", concrete: false };+ }++ // Other real message (not a bare teardown): attribute by stage, concrete.+ if (rec.stage === "ch-read") return { reason: "ch-error", concrete: true };+ if (rec.stage === "upload") return { reason: "upload-error", concrete: true };+ return { reason: "unknown", concrete: false };+}++/** Collects per-stage errors for one table export and resolves the cause. */+export class BlobExportAbortTracker {+ private readonly records: RecordedStageError[] = [];++ // `now` is injectable for deterministic tests.+ record(+ stage: BlobExportAbortStage,+ error: unknown,+ now: number = performance.now(),+ ): void {+ if (error == null) return;+ this.records.push({ stage, error, at: now });+ }++ hasErrors(): boolean {+ return this.records.length > 0;+ }++ /**+ * Concrete faults outrank generic teardowns; ties go to the earliest (the+ * stage that failed first tore down the rest). Undefined if nothing recorded.+ */+ origin(): BlobExportAbortOrigin | undefined {+ if (this.records.length === 0) return undefined;++ const classified = this.records.map((rec) => ({+ rec,+ ...classifyOne(rec),+ }));++ classified.sort((a, b) => {+ if (a.concrete !== b.concrete) return a.concrete ? -1 : 1;+ return a.rec.at - b.rec.at;+ });++ const winner = classified[0];+ return {+ reason: winner.reason,+ stage: winner.rec.stage,+ concrete: winner.concrete,+ chain: errorChainText(winner.rec.error),+ };+ }+}++/** Classify a single error with no per-stage context (tracker recorded nothing). */+export function classifyBlobExportError(+ error: unknown,+ stage: BlobExportAbortStage = "unknown",+): BlobExportAbortOrigin {+ const { reason, concrete } = classifyOne({ stage, error, at: 0 });+ return { reason, stage, concrete, chain: errorChainText(error) };+}diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex a2b5906385..d14e66fa83 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -40,6 +40,12 @@ import {BLOB_TABLE_EXPORT_METRIC,type BlobTableExportOutcome,} from "./inFlightExports";+import {+ BlobExportAbortTracker,+ classifyBlobExportError,+ errorChainText,+} from "./abortClassification";+import { isSigtermReceived } from "../health";import { TimedGzip, ZLIB_DEFAULT_LEVEL, type GzipStats } from "./gzipStream";import { ByteCounter, TimedByteCounter } from "./byteCounters";import { WORKER_HOST_ID } from "../../utils/hostId";@@ -416,6 +422,10 @@ const processBlobStorageExport = async (config: {let uploadSucceeded = false;let heartbeat: ReturnType<typeof setInterval> | undefined;+ // Per-stage errors so the catch can name the originating cause instead of+ // the bare "aborted" the pipeline teardown propagates to every stage.+ const abortTracker = new BlobExportAbortTracker();+try {const blobStorageProps = getFileTypeProperties(config.fileType);@@ -474,6 +484,8 @@ const processBlobStorageExport = async (config: {const pipelineCallback = (err: NodeJS.ErrnoException | null) => {if (err) {+ // The pipeline source is the ClickHouse read.+ abortTracker.record("ch-read", err);logger.error("[BLOB INTEGRATION] Getting data from DB for blob storage integration failed: ",err,@@ -728,15 +740,22 @@ const processBlobStorageExport = async (config: {try {uploadStartMs = performance.now();- await storageService.uploadFileBuffered({- fileName: filePath,- fileType: uploadContentType,- data: fileStream,- partSizeBytes: config.partSizeBytes,- maxConcurrentParts: config.maxConcurrentParts,- maxPartAttempts: config.maxPartAttempts,- stats: uploadStats,- });+ try {+ await storageService.uploadFileBuffered({+ fileName: filePath,+ fileType: uploadContentType,+ data: fileStream,+ partSizeBytes: config.partSizeBytes,+ maxConcurrentParts: config.maxConcurrentParts,+ maxPartAttempts: config.maxPartAttempts,+ stats: uploadStats,+ });+ } catch (uploadError) {+ // Attribute to the upload stage; a CH-origin error surfacing here is+ // still classified as ch-error by its preserved cause chain.+ abortTracker.record("upload", uploadError);+ throw uploadError;+ }// Record at the upload boundary so a throw in the `finally` below// can't miscount a real success as a failure.uploadSucceeded = true;@@ -941,17 +960,31 @@ const processBlobStorageExport = async (config: {}}} catch (error) {+ // On SIGTERM, add a concrete shutdown record. It wins origin() only when+ // no earlier concrete fault (e.g. a real CH exception) was recorded.+ if (isSigtermReceived()) {+ abortTracker.record("shutdown", error);+ }+ // Fall back to the propagated error if no stage recorded one.+ const origin = abortTracker.origin() ?? classifyBlobExportError(error);++ span.setAttribute("blob.abortReason", origin.reason);+ span.setAttribute("blob.abortStage", origin.stage);+// Skip if `success` already fired (a later step threw post-upload).if (!uploadSucceeded) {recordIncrement(BLOB_TABLE_EXPORT_METRIC, 1, {outcome: "failure" satisfies BlobTableExportOutcome,+ abortReason: origin.reason,table: config.table,projectId: config.projectId,});}logger.error(`[BLOB INTEGRATION] Error exporting ${config.table} for project ${config.projectId} ` +- `(jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${WORKER_HOST_ID})`,+ `(jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${WORKER_HOST_ID} ` ++ `abortReason=${origin.reason} abortStage=${origin.stage}` ++ `${origin.concrete ? "" : " attribution=best-effort"}): ${origin.chain}`,error,);throw error;@@ -1342,7 +1375,7 @@ export const handleBlobStorageIntegrationProjectJob = async (notifyBlobStorageExportFailedInBackground(projectId);- const chain = formatErrorChain(error);+ const chain = errorChainText(error);logger.error(`[BLOB INTEGRATION] Error processing blob storage integration for project ${projectId}: ${chain}`,error instanceof Error ? { stack: error.stack } : {},@@ -1460,14 +1493,3 @@ function extractStorageErrorMessage(error: unknown): string {const full = details ? `${message} Details: ${details}` : message;return full.slice(0, 1000);}--function formatErrorChain(error: unknown): string {- if (!(error instanceof Error)) return String(error);- const parts: string[] = [];- let current: unknown = error;- while (current instanceof Error) {- parts.push(current.message);- current = current.cause;- }- return parts.join(" caused by ");-}diff --git a/worker/src/features/blobstorage/inFlightExports.ts b/worker/src/features/blobstorage/inFlightExports.tsindex 8ba4cc02db..e2a42f051c 100644--- a/worker/src/features/blobstorage/inFlightExports.ts+++ b/worker/src/features/blobstorage/inFlightExports.ts@@ -68,6 +68,8 @@ export const logInFlightBlobExportsOnShutdown = (): void => {// May double with `success` if the export finishes within the grace period.recordIncrement(BLOB_TABLE_EXPORT_METRIC, 1, {outcome: "aborted" satisfies BlobTableExportOutcome,+ // Survivors at a graceful shutdown were aborted by the SIGTERM teardown.+ abortReason: "shutdown",table: entry.table,projectId: entry.projectId,});diff --git a/worker/src/features/health/index.ts b/worker/src/features/health/index.tsindex f9e0958793..90a266fc60 100644--- a/worker/src/features/health/index.ts+++ b/worker/src/features/health/index.ts@@ -48,4 +48,4 @@ export const setSigtermReceived = () => {sigtermReceived = true;};-const isSigtermReceived = () => sigtermReceived;+export const isSigtermReceived = () => sigtermReceived;