πͺ’ 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
feat(worker): per-project blob export tuning via exportTuning column (LFE-10394) (#14387)
Niklas Semmler890b5f4493c1
diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.tsindex 8d359708fd..7f16b6b811 100644--- a/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.ts+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.ts@@ -1,111 +1,355 @@import { describe, it, expect } from "vitest";-import { resolveBlobExportTuning } from "./blob-export-tuning";++import {+ resolveBlobExportTuning,+ BlobExportTuningSchema,+ BLOB_EXPORT_TUNING_BOUNDS,+ DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES,+ type BlobExportTuningDefaults,+ type ResolvedBlobExportTuning,+} from "./blob-export-tuning";++const DEFAULTS: BlobExportTuningDefaults = {+ partSizeBytes: DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES, // 100 MiB+};++// Fully-resolved object with the defaults applied; override per assertion.+// Concurrency/attempts default to undefined (operator did not set them) so the+// backend keeps its native default.+function resolved(+ overrides: Partial<ResolvedBlobExportTuning> = {},+): ResolvedBlobExportTuning {+ return {+ rawPassthrough: false,+ gzipLevel: undefined,+ partSizeBytes: DEFAULTS.partSizeBytes,+ maxConcurrentParts: undefined,+ maxPartAttempts: undefined,+ skipEnrichment: false,+ ...overrides,+ };+}describe("resolveBlobExportTuning", () => {- it("defaults to rawPassthrough=false for null/undefined", () => {- expect(resolveBlobExportTuning(null)).toEqual({- resolved: { rawPassthrough: false, gzipLevel: undefined },- warnings: [],+ describe("null / absent / malformed β defaults, byte-for-byte unchanged", () => {+ it("returns defaults with no warnings for null", () => {+ expect(resolveBlobExportTuning(null, DEFAULTS)).toEqual({+ resolved: resolved(),+ warnings: [],+ });});- expect(resolveBlobExportTuning(undefined)).toEqual({- resolved: { rawPassthrough: false, gzipLevel: undefined },- warnings: [],++ it("returns defaults with no warnings for undefined", () => {+ expect(resolveBlobExportTuning(undefined, DEFAULTS)).toEqual({+ resolved: resolved(),+ warnings: [],+ });});- });- it("honors rawPassthrough=true", () => {- expect(resolveBlobExportTuning({ rawPassthrough: true })).toEqual({- resolved: { rawPassthrough: true, gzipLevel: undefined },- warnings: [],+ it("returns defaults with no warnings for an empty object", () => {+ expect(resolveBlobExportTuning({}, DEFAULTS)).toEqual({+ resolved: resolved(),+ warnings: [],+ });});- });- it("honors rawPassthrough=false explicitly", () => {- expect(resolveBlobExportTuning({ rawPassthrough: false })).toEqual({- resolved: { rawPassthrough: false, gzipLevel: undefined },- warnings: [],+ it("warns and uses defaults when the value is not an object", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ "garbage",+ DEFAULTS,+ );+ expect(res).toEqual(resolved());+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toContain("expected an object");});- });- it("defaults rawPassthrough when the key is absent from a valid object", () => {- expect(resolveBlobExportTuning({})).toEqual({- resolved: { rawPassthrough: false, gzipLevel: undefined },- warnings: [],+ it("warns and uses defaults for an array (objects only)", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ [1, 2],+ DEFAULTS,+ );+ expect(res).toEqual(resolved());+ expect(warnings[0]).toContain("expected an object");});});- it("ignores unknown keys (forward-compat with LFE-10394 knobs)", () => {- const result = resolveBlobExportTuning({- rawPassthrough: true,- partSizeBytes: 200,- maxConcurrentParts: 8,- skipEnrichment: true,+ describe("rawPassthrough (LFE-10402)", () => {+ it("honors rawPassthrough=true", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { rawPassthrough: true },+ DEFAULTS,+ );+ expect(res).toEqual(resolved({ rawPassthrough: true }));+ expect(warnings).toEqual([]);+ });++ it("honors rawPassthrough=false explicitly", () => {+ const { resolved: res } = resolveBlobExportTuning(+ { rawPassthrough: false },+ DEFAULTS,+ );+ expect(res.rawPassthrough).toBe(false);+ });++ it("falls back to false and warns on a wrong-typed rawPassthrough", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { rawPassthrough: "yes" },+ DEFAULTS,+ );+ expect(res.rawPassthrough).toBe(false);+ expect(warnings.some((w) => w.includes("expected a boolean"))).toBe(true);});- expect(result.resolved).toEqual({- rawPassthrough: true,- gzipLevel: undefined,++ it("composes rawPassthrough with upload knobs", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ {+ rawPassthrough: true,+ partSizeBytes: 200 * 1024 * 1024,+ maxConcurrentParts: 8,+ skipEnrichment: true,+ },+ DEFAULTS,+ );+ expect(res).toEqual(+ resolved({+ rawPassthrough: true,+ partSizeBytes: 200 * 1024 * 1024,+ maxConcurrentParts: 8,+ skipEnrichment: true,+ }),+ );+ expect(warnings).toEqual([]);});- expect(result.warnings).toEqual([]);});- it("falls back to defaults and warns on a wrong-typed rawPassthrough", () => {- const result = resolveBlobExportTuning({ rawPassthrough: "yes" });- expect(result.resolved).toEqual({- rawPassthrough: false,- gzipLevel: undefined,+ describe("gzipLevel (LFE-10402)", () => {+ it("honors a valid gzipLevel independently of rawPassthrough", () => {+ expect(+ resolveBlobExportTuning(+ { rawPassthrough: true, gzipLevel: 1 },+ DEFAULTS,+ ).resolved,+ ).toEqual(resolved({ rawPassthrough: true, gzipLevel: 1 }));+ // level 0 (store) and 9 (max) are both valid+ expect(+ resolveBlobExportTuning({ gzipLevel: 0 }, DEFAULTS).resolved.gzipLevel,+ ).toBe(0);+ expect(+ resolveBlobExportTuning({ gzipLevel: 9 }, DEFAULTS).resolved.gzipLevel,+ ).toBe(9);+ });++ it("drops an out-of-range gzipLevel to the zlib default without disabling rawPassthrough", () => {+ const tooHigh = resolveBlobExportTuning(+ { rawPassthrough: true, gzipLevel: 12 },+ DEFAULTS,+ );+ expect(tooHigh.resolved.rawPassthrough).toBe(true);+ expect(tooHigh.resolved.gzipLevel).toBeUndefined();+ expect(+ tooHigh.warnings.some((w) => w.includes("out of range [0, 9]")),+ ).toBe(true);++ expect(+ resolveBlobExportTuning({ gzipLevel: -1 }, DEFAULTS).resolved.gzipLevel,+ ).toBeUndefined();+ });++ it("reports gzipLevel failure modes with accurate, distinct messages", () => {+ // non-integer in range β "not an integer", NOT "out of range"+ const frac = resolveBlobExportTuning({ gzipLevel: 5.5 }, DEFAULTS);+ expect(frac.resolved.gzipLevel).toBeUndefined();+ expect(frac.warnings.some((w) => w.includes("is not an integer"))).toBe(+ true,+ );+ expect(frac.warnings.some((w) => w.includes("out of range"))).toBe(false);++ // wrong type β "expected a finite number", NOT "out of range"+ const str = resolveBlobExportTuning({ gzipLevel: "high" }, DEFAULTS);+ expect(str.resolved.gzipLevel).toBeUndefined();+ expect(+ str.warnings.some((w) => w.includes("expected a finite number")),+ ).toBe(true);+ expect(str.warnings.some((w) => w.includes("out of range"))).toBe(false);});- expect(result.warnings.length).toBe(1);});- it("falls back to defaults and warns on a non-object column", () => {- const result = resolveBlobExportTuning("garbage");- expect(result.resolved).toEqual({- rawPassthrough: false,- gzipLevel: undefined,+ describe("valid in-range upload knobs are honoured silently", () => {+ it("passes through values within bounds", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ {+ partSizeBytes: 200 * 1024 * 1024,+ maxConcurrentParts: 16,+ maxPartAttempts: 5,+ skipEnrichment: true,+ },+ DEFAULTS,+ );+ expect(res).toEqual(+ resolved({+ partSizeBytes: 200 * 1024 * 1024,+ maxConcurrentParts: 16,+ maxPartAttempts: 5,+ skipEnrichment: true,+ }),+ );+ expect(warnings).toEqual([]);});- expect(result.warnings.length).toBe(1);});- it("honors a valid gzipLevel and keeps rawPassthrough independent", () => {- expect(- resolveBlobExportTuning({ rawPassthrough: true, gzipLevel: 1 }),- ).toEqual({- resolved: { rawPassthrough: true, gzipLevel: 1 },- warnings: [],+ describe("out-of-range numbers are clamped (not defaulted) and warned", () => {+ it("clamps maxConcurrentParts above the ceiling to 32", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { maxConcurrentParts: 50 },+ DEFAULTS,+ );+ expect(res.maxConcurrentParts).toBe(+ BLOB_EXPORT_TUNING_BOUNDS.maxConcurrentParts.max,+ );+ expect(warnings.some((w) => w.includes("clamped to 32"))).toBe(true);});- // level 0 (store) is valid- expect(resolveBlobExportTuning({ gzipLevel: 0 })).toEqual({- resolved: { rawPassthrough: false, gzipLevel: 0 },- warnings: [],++ it("clamps maxConcurrentParts below the floor to 1", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { maxConcurrentParts: 0 },+ DEFAULTS,+ );+ expect(res.maxConcurrentParts).toBe(1);+ expect(warnings.some((w) => w.includes("clamped to 1"))).toBe(true);});- expect(resolveBlobExportTuning({ gzipLevel: 9 })).toEqual({- resolved: { rawPassthrough: false, gzipLevel: 9 },- warnings: [],++ it("clamps maxPartAttempts above 10 to 10", () => {+ const { resolved: res } = resolveBlobExportTuning(+ { maxPartAttempts: 99 },+ DEFAULTS,+ );+ expect(res.maxPartAttempts).toBe(10);+ });++ it("clamps partSizeBytes below 5 MiB to the floor", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { partSizeBytes: 1024 },+ DEFAULTS,+ );+ expect(res.partSizeBytes).toBe(+ BLOB_EXPORT_TUNING_BOUNDS.partSizeBytes.min,+ );+ expect(warnings.some((w) => w.includes("clamped"))).toBe(true);+ });++ it("clamps partSizeBytes above 5 GiB to the ceiling", () => {+ const { resolved: res } = resolveBlobExportTuning(+ { partSizeBytes: 9 * 1024 * 1024 * 1024 },+ DEFAULTS,+ );+ expect(res.partSizeBytes).toBe(+ BLOB_EXPORT_TUNING_BOUNDS.partSizeBytes.max,+ );});});- it("clamps an out-of-range gzipLevel to default without disabling rawPassthrough", () => {- const tooHigh = resolveBlobExportTuning({- rawPassthrough: true,- gzipLevel: 12,+ describe("in-range non-integers are rounded, not reported as out of range", () => {+ it("rounds an in-range float and warns about rounding only", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { maxConcurrentParts: 3.5 },+ DEFAULTS,+ );+ expect(res.maxConcurrentParts).toBe(4);+ expect(warnings.some((w) => w.includes("rounded to 4"))).toBe(true);+ // Must NOT claim the in-range value was out of range.+ expect(warnings.some((w) => w.includes("out of range"))).toBe(false);});- expect(tooHigh.resolved).toEqual({- rawPassthrough: true,- gzipLevel: undefined,++ it("reports both rounding and clamping for an out-of-range float", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { maxConcurrentParts: 41.6 },+ DEFAULTS,+ );+ expect(res.maxConcurrentParts).toBe(32);+ expect(warnings.some((w) => w.includes("rounded to 42"))).toBe(true);+ expect(warnings.some((w) => w.includes("clamped to 32"))).toBe(true);});- expect(tooHigh.warnings.length).toBe(1);+ });- const negative = resolveBlobExportTuning({ gzipLevel: -1 });- expect(negative.resolved.gzipLevel).toBeUndefined();- expect(negative.warnings.length).toBe(1);+ describe("wrong-typed / non-finite values fall back to defaults and warn", () => {+ it("falls back to undefined (backend default) when a concurrency knob is a string", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { maxConcurrentParts: "x" },+ DEFAULTS,+ );+ expect(res.maxConcurrentParts).toBeUndefined();+ expect(warnings.some((w) => w.includes("expected a finite number"))).toBe(+ true,+ );+ });++ it("falls back to the partSize default when partSizeBytes is NaN", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { partSizeBytes: NaN },+ DEFAULTS,+ );+ expect(res.partSizeBytes).toBe(DEFAULTS.partSizeBytes);+ expect(warnings.some((w) => w.includes("expected a finite number"))).toBe(+ true,+ );+ });++ it("falls back to false when skipEnrichment is not a boolean", () => {+ const { resolved: res, warnings } = resolveBlobExportTuning(+ { skipEnrichment: "yes" },+ DEFAULTS,+ );+ expect(res.skipEnrichment).toBe(false);+ expect(warnings.some((w) => w.includes("expected a boolean"))).toBe(true);+ });+ });- const fractional = resolveBlobExportTuning({ gzipLevel: 3.5 });- expect(fractional.resolved.gzipLevel).toBeUndefined();- expect(fractional.warnings.length).toBe(1);+ it("never throws across a range of hostile inputs", () => {+ const inputs: unknown[] = [+ 0,+ "",+ true,+ [],+ 12345,+ { partSizeBytes: -1, maxConcurrentParts: Infinity },+ { skipEnrichment: 1, maxPartAttempts: {} },+ { rawPassthrough: [], gzipLevel: "x" },+ Symbol("x") as unknown,+ ];+ for (const input of inputs) {+ expect(() => resolveBlobExportTuning(input, DEFAULTS)).not.toThrow();+ }+ });+});++describe("BlobExportTuningSchema (write schema)", () => {+ it("accepts an in-range partial object", () => {+ expect(+ BlobExportTuningSchema.safeParse({ maxConcurrentParts: 10 }).success,+ ).toBe(true);+ });++ it("accepts rawPassthrough and gzipLevel", () => {+ expect(+ BlobExportTuningSchema.safeParse({ rawPassthrough: true, gzipLevel: 6 })+ .success,+ ).toBe(true);+ });++ it("rejects out-of-range values (writes reject; reads clamp)", () => {+ expect(+ BlobExportTuningSchema.safeParse({ maxConcurrentParts: 50 }).success,+ ).toBe(false);+ expect(BlobExportTuningSchema.safeParse({ gzipLevel: 12 }).success).toBe(+ false,+ );});- it("never throws", () => {- expect(() => resolveBlobExportTuning(12345)).not.toThrow();- expect(() => resolveBlobExportTuning([])).not.toThrow();+ it("strips unknown keys (forward-compat, not strict)", () => {+ const parsed = BlobExportTuningSchema.safeParse({ bogus: 1 });+ expect(parsed.success).toBe(true);+ if (parsed.success) {+ expect(parsed.data).not.toHaveProperty("bogus");+ }});});diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.tsindex 76021ff99e..1c3c59f17a 100644--- a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts@@ -2,14 +2,20 @@// (`BlobStorageIntegration.exportTuning`) and set via the DB directly for now// (no UI/tRPC write path yet). Validated and resolved at job time.//-// This module is client-safe (no logger / server imports) so a future settings-// UI can reuse the schema for write-validation. The worker logs the warnings-// returned by the resolver.+// This is a client-safe file (no logger / server imports) so a future settings+// UI can reuse the schema for write-validation. The read-side resolver does NOT+// log β it returns a `warnings` array so the (server-side) caller can log+// without pulling a server logger into this module.//-// Shared with LFE-10394 (upload tuning knobs: partSizeBytes / maxConcurrentParts-// / maxPartAttempts / skipEnrichment). Extend this schema rather than forking-// it. Unknown keys are stripped (zod default) so a key written by a newer-// writer is harmless to an older worker.+// Several overlapping feature sets share this module β extend, don't fork:+// - LFE-10402: `rawPassthrough` (stream ClickHouse JSONEachRow bytes straight+// to gzip β upload) and `gzipLevel` (zlib deflate level for compressed+// exports).+// - LFE-10394: upload tuning (`partSizeBytes` / `maxConcurrentParts` /+// `maxPartAttempts`) + `skipEnrichment`.+// Unknown keys are stripped (zod default) so a key written by a newer writer is+// harmless to an older worker.+import { z } from "zod";// Minimum ClickHouse version for safe raw passthrough. The passthrough relies on@@ -22,6 +28,28 @@ import { z } from "zod";// Langfuse Cloud runs a newer ClickHouse, so this only affects self-hosters.export const RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION = "25.11";+// Bounds applied by the resolver (clamp) and the write schema (reject).+//+// NOTE on the original ranges β keep visible for orientation and future revert:+// - maxConcurrentParts: env `LANGFUSE_S3_UPLOAD_MAX_CONCURRENT_PARTS` is 1β10+// (default 3). Deliberately WIDENED to 1β32 here for per-project+// experimentation. Restore `max: 10` to return to env parity.+// - maxPartAttempts: env `LANGFUSE_S3_UPLOAD_MAX_PART_ATTEMPTS` is 1β10+// (default 3). UNCHANGED.+// - partSizeBytes: previously hardcoded to 100 MiB. S3 multipart limits are a+// 5 MiB minimum and 5 GiB maximum per part; we allow that full range. Azure+// caps a stage-block at 4000 MiB (< 5 GiB), so the Azure upload path clamps+// partSize to its own limit rather than constraining this shared S3 range.+export const BLOB_EXPORT_TUNING_BOUNDS = {+ partSizeBytes: { min: 5 * 1024 * 1024, max: 5 * 1024 * 1024 * 1024 },+ maxConcurrentParts: { min: 1, max: 32 },+ maxPartAttempts: { min: 1, max: 10 },+} as const;++// Default part size when the column does not specify one. Matches the value+// that was previously hardcoded in handleBlobStorageIntegrationProjectJob.ts.+export const DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES = 100 * 1024 * 1024; // 100 MiB+export const BlobExportTuningSchema = z.object({// LFE-10402 raw-passthrough export path: stream ClickHouse JSONEachRow row text// straight to gzip β upload, skipping the per-row JS parse/enrich/serialize@@ -33,71 +61,237 @@ export const BlobExportTuningSchema = z.object({// detection. Do not enable on older self-hosted ClickHouse.rawPassthrough: z.boolean().optional(),// LFE-10402 gzip tuning: zlib deflate level for compressed exports. Lower- // levels trade output size for markedly less worker CPU (the gzip step is the- // dominant remaining cost on large passthrough exports). Only honored when the- // integration has compression enabled. zlib accepts 0 (store, no compression)- // through 9 (max); absent / out-of-range falls back to the zlib default (6).- gzipLevel: z.number().optional(),+ // levels trade output size for markedly less worker CPU. Only honored when the+ // integration has compression enabled. zlib accepts 0 (store) through 9 (max);+ // absent / out-of-range falls back to the zlib default (6).+ gzipLevel: z.number().int().min(0).max(9).optional(),+ // LFE-10394 upload tuning. Out-of-range values are REJECTED here (write path)+ // but CLAMPED by the read-side resolver.+ partSizeBytes: z+ .number()+ .int()+ .min(BLOB_EXPORT_TUNING_BOUNDS.partSizeBytes.min)+ .max(BLOB_EXPORT_TUNING_BOUNDS.partSizeBytes.max)+ .optional(),+ maxConcurrentParts: z+ .number()+ .int()+ .min(BLOB_EXPORT_TUNING_BOUNDS.maxConcurrentParts.min)+ .max(BLOB_EXPORT_TUNING_BOUNDS.maxConcurrentParts.max)+ .optional(),+ maxPartAttempts: z+ .number()+ .int()+ .min(BLOB_EXPORT_TUNING_BOUNDS.maxPartAttempts.min)+ .max(BLOB_EXPORT_TUNING_BOUNDS.maxPartAttempts.max)+ .optional(),+ skipEnrichment: z.boolean().optional(),});export type BlobExportTuning = z.infer<typeof BlobExportTuningSchema>;+// Default the resolver falls back to for partSizeBytes when the column is absent+// or invalid. Concurrency/attempts intentionally have NO default here β see+// ResolvedBlobExportTuning for why they resolve to `undefined`.+export interface BlobExportTuningDefaults {+ partSizeBytes: number;+}+export type ResolvedBlobExportTuning = {rawPassthrough: boolean;// undefined => use the zlib default (6); a concrete 0-9 otherwise.gzipLevel: number | undefined;+ partSizeBytes: number;+ // undefined => not set by the operator; each backend keeps its native default+ // (S3 buffered β env var, Azure β 5, OCI β 5). A concrete default here would+ // override those per-backend defaults.+ maxConcurrentParts: number | undefined;+ maxPartAttempts: number | undefined;+ skipEnrichment: boolean;};-/**- * Resolve the persisted `exportTuning` JSON into concrete export settings.- * Pure and total: never throws. A null / non-object / malformed column resolves- * to the safe defaults (today's behaviour) and records a warning the caller can- * log. Unknown keys are ignored.- */-export function resolveBlobExportTuning(raw: unknown): {+export interface ResolveBlobExportTuningResult {resolved: ResolvedBlobExportTuning;warnings: string[];-} {- const defaults: ResolvedBlobExportTuning = {+}++type Bound = { min: number; max: number };++function resolveNumber(+ field: string,+ value: unknown,+ bound: Bound,+ fallback: number,+ warnings: string[],+): number {+ if (value === undefined) return fallback; // absent β default, silent+ if (typeof value !== "number" || !Number.isFinite(value)) {+ warnings.push(+ `${field}: expected a finite number, got ${JSON.stringify(value)}; using default ${fallback}`,+ );+ return fallback;+ }+ // Rounding and clamping warn separately so the message reflects what happened.+ const rounded = Math.round(value);+ const clamped = Math.min(bound.max, Math.max(bound.min, rounded));+ if (rounded !== value) {+ warnings.push(+ `${field}: ${value} is not an integer; rounded to ${rounded}`,+ );+ }+ if (clamped !== rounded) {+ warnings.push(+ `${field}: ${rounded} out of range [${bound.min}, ${bound.max}]; clamped to ${clamped}`,+ );+ }+ return clamped;+}++// resolveNumber variant returning undefined when absent or wrong-typed, so the+// caller can distinguish "unset" (use backend default) from a set value.+function resolveOptionalNumber(+ field: string,+ value: unknown,+ bound: Bound,+ warnings: string[],+): number | undefined {+ if (value === undefined) return undefined; // absent β backend default, silent+ if (typeof value !== "number" || !Number.isFinite(value)) {+ warnings.push(+ `${field}: expected a finite number, got ${JSON.stringify(value)}; using backend default`,+ );+ return undefined;+ }+ const rounded = Math.round(value);+ const clamped = Math.min(bound.max, Math.max(bound.min, rounded));+ if (rounded !== value) {+ warnings.push(+ `${field}: ${value} is not an integer; rounded to ${rounded}`,+ );+ }+ if (clamped !== rounded) {+ warnings.push(+ `${field}: ${rounded} out of range [${bound.min}, ${bound.max}]; clamped to ${clamped}`,+ );+ }+ return clamped;+}++function resolveBoolean(+ field: string,+ value: unknown,+ warnings: string[],+): boolean {+ if (value === undefined) return false; // absent β false, silent+ if (typeof value !== "boolean") {+ warnings.push(+ `${field}: expected a boolean, got ${JSON.stringify(value)}; using default false`,+ );+ return false;+ }+ return value;+}++// gzipLevel uses clamp-to-DEFAULT (not clamp-to-bound): an out-of-range level is+// dropped so the zlib default (6) applies, rather than silently snapping to 0/9.+function resolveGzipLevel(+ value: unknown,+ warnings: string[],+): number | undefined {+ if (value === undefined) return undefined;+ // Wrong type / non-integer / out-of-range warn distinctly; all fall back to+ // the zlib default.+ if (typeof value !== "number" || !Number.isFinite(value)) {+ warnings.push(+ `gzipLevel: expected a finite number, got ${JSON.stringify(value)}; using zlib default`,+ );+ return undefined;+ }+ if (!Number.isInteger(value)) {+ warnings.push(`gzipLevel: ${value} is not an integer; using zlib default`);+ return undefined;+ }+ if (value < 0 || value > 9) {+ warnings.push(+ `gzipLevel: ${value} out of range [0, 9]; using zlib default`,+ );+ return undefined;+ }+ return value;+}++/**+ * Read-side resolver for the `exportTuning` JSON column. Never throws.+ *+ * Semantics:+ * - null / undefined / non-object β all defaults (non-object is warned).+ * - upload knob numeric out of range β CLAMPED to the bound (warned).+ * - gzipLevel out of range β dropped β zlib default (warned).+ * - field of the wrong type / NaN β default (warned).+ * - absent field β default (silent).+ *+ * The caller is expected to log each returned warning.+ */+export function resolveBlobExportTuning(+ raw: unknown,+ defaults: BlobExportTuningDefaults,+): ResolveBlobExportTuningResult {+ const warnings: string[] = [];++ const fallback: ResolvedBlobExportTuning = {rawPassthrough: false,gzipLevel: undefined,+ partSizeBytes: defaults.partSizeBytes,+ maxConcurrentParts: undefined,+ maxPartAttempts: undefined,+ skipEnrichment: false,};if (raw === null || raw === undefined) {- return { resolved: defaults, warnings: [] };+ return { resolved: fallback, warnings };}- const parsed = BlobExportTuningSchema.safeParse(raw);- if (!parsed.success) {- return {- resolved: defaults,- warnings: [- `Malformed exportTuning column, falling back to defaults: ${parsed.error.message}`,- ],- };+ if (typeof raw !== "object" || Array.isArray(raw)) {+ warnings.push(+ `exportTuning: expected an object, got ${JSON.stringify(raw)}; using defaults`,+ );+ return { resolved: fallback, warnings };}- const warnings: string[] = [];-- // Clamp-to-default rather than fail: a bad gzipLevel must not also disable a- // valid rawPassthrough. An out-of-range / non-integer level is dropped (zlib- // default applies) with a warning the caller logs.- let gzipLevel: number | undefined;- const rawLevel = parsed.data.gzipLevel;- if (rawLevel !== undefined) {- if (Number.isInteger(rawLevel) && rawLevel >= 0 && rawLevel <= 9) {- gzipLevel = rawLevel;- } else {- warnings.push(- `Ignoring out-of-range gzipLevel ${rawLevel} (expected integer 0-9), using zlib default`,- );- }- }+ const obj = raw as Record<string, unknown>;return {resolved: {- rawPassthrough: parsed.data.rawPassthrough ?? false,- gzipLevel,+ rawPassthrough: resolveBoolean(+ "rawPassthrough",+ obj.rawPassthrough,+ warnings,+ ),+ gzipLevel: resolveGzipLevel(obj.gzipLevel, warnings),+ partSizeBytes: resolveNumber(+ "partSizeBytes",+ obj.partSizeBytes,+ BLOB_EXPORT_TUNING_BOUNDS.partSizeBytes,+ defaults.partSizeBytes,+ warnings,+ ),+ maxConcurrentParts: resolveOptionalNumber(+ "maxConcurrentParts",+ obj.maxConcurrentParts,+ BLOB_EXPORT_TUNING_BOUNDS.maxConcurrentParts,+ warnings,+ ),+ maxPartAttempts: resolveOptionalNumber(+ "maxPartAttempts",+ obj.maxPartAttempts,+ BLOB_EXPORT_TUNING_BOUNDS.maxPartAttempts,+ warnings,+ ),+ skipEnrichment: resolveBoolean(+ "skipEnrichment",+ obj.skipEnrichment,+ warnings,+ ),},warnings,};diff --git a/packages/shared/src/server/services/BufferedStreamUploader.ts b/packages/shared/src/server/services/BufferedStreamUploader.tsindex b3b304669c..394ad6521c 100644--- a/packages/shared/src/server/services/BufferedStreamUploader.ts+++ b/packages/shared/src/server/services/BufferedStreamUploader.ts@@ -34,12 +34,29 @@ export interface ChunkedUploadStrategy {uploadSingleObject(data: Buffer): Promise<void>;}+// Upload counters surfaced for telemetry. `partRetries` is the total number of+// retry attempts across all parts (not distinct parts retried); `partFailures`+// is the number of parts that exhausted their attempts; `partsUploaded` is the+// number of completed parts.+export interface UploadPartStats {+ partsUploaded: number;+ partRetries: number;+ partFailures: number;+}++export function emptyUploadPartStats(): UploadPartStats {+ return { partsUploaded: 0, partRetries: 0, partFailures: 0 };+}+export interface BufferedStreamUploaderParams {strategy: ChunkedUploadStrategy;partSizeBytes: number;maxPartAttempts: number;maxConcurrentParts: number;key: string; // for logging+ // Optional mutable sink the caller owns. Incremented live so counts are+ // readable even when upload() throws. A fresh one is used when omitted.+ stats?: UploadPartStats;}// Collects errors from concurrent part uploads. Append-only by design so@@ -74,12 +91,14 @@ export class BufferedStreamUploader {private isCompleted = false;private inFlightUploads: Map<symbol, Promise<void>> = new Map();private readonly errors = new ErrorSink();+ private readonly stats: UploadPartStats;constructor(params: BufferedStreamUploaderParams) {this.params = params;+ this.stats = params.stats ?? emptyUploadPartStats();}- async upload(stream: Readable): Promise<void> {+ async upload(stream: Readable): Promise<UploadPartStats> {try {await this.params.strategy.initialize();@@ -131,7 +150,7 @@ export class BufferedStreamUploader {);await this.params.strategy.uploadSingleObject(Buffer.alloc(0));this.isCompleted = true;- return;+ return this.stats;}const sortedParts = [...this.completedParts].sort(@@ -145,6 +164,8 @@ export class BufferedStreamUploader {await this.params.strategy.abort("upload failed or incomplete");}}++ return this.stats;}private async flushBuffer(): Promise<void> {@@ -171,11 +192,13 @@ export class BufferedStreamUploader {const promise = this.uploadPartWithRetry(data, partNumber).then((result) => {this.completedParts.push(result);+ this.stats.partsUploaded++;logger.debug(`Uploaded part ${partNumber} (${(data.byteLength / 1024 / 1024).toFixed(1)} MiB) for key ${this.params.key}`,);}).catch((err) => {+ this.stats.partFailures++;this.errors.capture(err);}).finally(() => {@@ -198,6 +221,12 @@ export class BufferedStreamUploader {if (!isTransientError(error)) {return false;}+ // backoff also invokes this on the final failing attempt; skip counting+ // it so partRetries reflects actual retries, not total failures.+ if (attemptNumber >= this.params.maxPartAttempts) {+ return true;+ }+ this.stats.partRetries++;logger.warn(`Part ${partNumber} upload failed (attempt ${attemptNumber}/${this.params.maxPartAttempts}): ${error.message}. Retrying...`,);diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.tsindex efaed17dda..ab3857eaf8 100644--- a/packages/shared/src/server/services/StorageService.ts+++ b/packages/shared/src/server/services/StorageService.ts@@ -23,7 +23,10 @@ import { logger } from "../logger";import { env } from "../../env";import { backOff } from "exponential-backoff";import { ServiceUnavailableError } from "../../errors";-import { BufferedStreamUploader } from "./BufferedStreamUploader";+import {+ BufferedStreamUploader,+ type UploadPartStats,+} from "./BufferedStreamUploader";import { S3ChunkedUploadStrategy } from "./S3ChunkedUploadStrategy";import {buildS3RequestDiagnostics,@@ -71,6 +74,13 @@ type UploadFileBuffered = {fileType: string;data: Readable;partSizeBytes: number;+ // Optional per-call overrides. Default to env vars when absent (S3 only; Azure+ // maps maxConcurrentParts to its upload concurrency and ignores maxPartAttempts).+ maxConcurrentParts?: number;+ maxPartAttempts?: number;+ // Optional mutable sink populated with upload counters; readable by the caller+ // even when the upload throws. Only the S3 buffered path populates it.+ stats?: UploadPartStats;};type UploadWithSignedUrl = UploadFile & {@@ -222,7 +232,11 @@ function createSecureAzureBlobRequestPolicyFactory(export interface StorageService {uploadFile(params: UploadFile): Promise<void>;- uploadFileBuffered(params: UploadFileBuffered): Promise<void>;+ // Returns upload counters when the implementation produces them (S3 buffered+ // path); undefined otherwise. Backward-compatible β existing callers ignore it.+ uploadFileBuffered(+ params: UploadFileBuffered,+ ): Promise<UploadPartStats | undefined>;uploadWithSignedUrl(params: UploadWithSignedUrl,@@ -387,7 +401,7 @@ class AzureBlobStorageService implements StorageService {}public async uploadFile(params: UploadFile): Promise<void> {- const { fileName, fileType, data, partSize } = params;+ const { fileName, fileType, data, partSize, queueSize } = params;try {await this.createContainerIfNotExists();@@ -400,7 +414,7 @@ class AzureBlobStorageService implements StorageService {} else if (data instanceof Readable) {// bufferSize controls the block size (default 8MB supports ~800GB files)const bufferSize = partSize ?? 8 * 1024 * 1024; // Default 8MB per block- const maxConcurrency = 5; // Default value+ const maxConcurrency = queueSize ?? 5; // Default valueawait blockBlobClient.uploadStream(data, bufferSize, maxConcurrency, {blobHTTPHeaders: { blobContentType: fileType },@@ -419,13 +433,36 @@ class AzureBlobStorageService implements StorageService {}}- public async uploadFileBuffered(params: UploadFileBuffered): Promise<void> {+ public async uploadFileBuffered(+ params: UploadFileBuffered,+ ): Promise<UploadPartStats | undefined> {+ // Azure has no per-part retry knob β its SDK pipeline owns retries β so+ // maxPartAttempts has no effect here. Warn so an operator isn't surprised.+ if (params.maxPartAttempts !== undefined) {+ logger.warn(+ `Azure blob upload for ${params.fileName}: maxPartAttempts is set but has no effect on the Azure path (SDK manages retries)`,+ );+ }+ // partSizeBytes -> block size, maxConcurrentParts -> upload concurrency.+ // Azure rejects a stageBlock larger than BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES+ // (4000 MiB). The shared tuning bound allows up to 5 GiB (S3's per-part max),+ // so clamp here to keep the Azure path within its own limit and warn.+ const AZURE_MAX_BLOCK_BYTES = 4000 * 1024 * 1024;+ let partSize = params.partSizeBytes;+ if (partSize > AZURE_MAX_BLOCK_BYTES) {+ logger.warn(+ `Azure blob upload for ${params.fileName}: partSizeBytes ${partSize} exceeds Azure's per-block max ${AZURE_MAX_BLOCK_BYTES}; clamping to the max`,+ );+ partSize = AZURE_MAX_BLOCK_BYTES;+ }await this.uploadFile({fileName: params.fileName,fileType: params.fileType,data: params.data,- partSize: params.partSizeBytes,+ partSize,+ queueSize: params.maxConcurrentParts,});+ return undefined; // Azure does not produce part-level stats.}public async uploadWithSignedUrl(@@ -751,9 +788,16 @@ class S3StorageService implements StorageService {fileType,data,partSizeBytes,- }: UploadFileBuffered): Promise<void> {+ maxConcurrentParts,+ maxPartAttempts,+ stats,+ }: UploadFileBuffered): Promise<UploadPartStats | undefined> {if (env.LANGFUSE_S3_UPLOAD_ENABLE_BUFFERED !== "true") {- return this.uploadFile({ fileName, fileType, data });+ // Tuning applies only on the buffered path. Forward no overrides so the+ // fallback keeps lib-storage's defaults β forwarding the resolved 100 MiB+ // partSize would ~20x per-upload memory (buffered is off by default).+ await this.uploadFile({ fileName, fileType, data });+ return undefined;}const strategy = new S3ChunkedUploadStrategy({@@ -770,13 +814,16 @@ class S3StorageService implements StorageService {const uploader = new BufferedStreamUploader({strategy,partSizeBytes,- maxPartAttempts: env.LANGFUSE_S3_UPLOAD_MAX_PART_ATTEMPTS,- maxConcurrentParts: env.LANGFUSE_S3_UPLOAD_MAX_CONCURRENT_PARTS,+ maxPartAttempts:+ maxPartAttempts ?? env.LANGFUSE_S3_UPLOAD_MAX_PART_ATTEMPTS,+ maxConcurrentParts:+ maxConcurrentParts ?? env.LANGFUSE_S3_UPLOAD_MAX_CONCURRENT_PARTS,key: fileName,+ stats,});try {- await uploader.upload(data);+ return await uploader.upload(data);} catch (err) {logger.error(`Failed to upload file (buffered) to ${fileName}`, err);handleStorageError(err, "upload file to S3 (buffered)");@@ -1030,12 +1077,15 @@ class GoogleCloudStorageService implements StorageService {}}- public async uploadFileBuffered(params: UploadFileBuffered): Promise<void> {+ public async uploadFileBuffered(+ params: UploadFileBuffered,+ ): Promise<UploadPartStats | undefined> {await this.uploadFile({fileName: params.fileName,fileType: params.fileType,data: params.data,});+ return undefined; // GCS does not produce part-level stats.}public async uploadWithSignedUrl({@@ -1459,13 +1509,18 @@ class OCIObjectStorageService implements StorageService {fileType,data,partSizeBytes,- }: UploadFileBuffered): Promise<void> {+ maxConcurrentParts,+ // maxPartAttempts omitted: OCI's UploadManager owns retries, no per-part knob.+ }: UploadFileBuffered): Promise<UploadPartStats | undefined> {+ // queueSize maps to UploadManager.maxConcurrentUploads (undefined => OCI's 5).await this.uploadFile({fileName,fileType,data,partSize: partSizeBytes,+ queueSize: maxConcurrentParts,});+ return undefined; // OCI does not produce part-level stats.}public async uploadWithSignedUrl({diff --git a/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts b/worker/src/__tests__/blobStorageTuningWiring.unit.test.tsnew file mode 100644index 0000000000..2055a0ede3--- /dev/null+++ b/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts@@ -0,0 +1,132 @@+import { describe, expect, it, vi, beforeEach } from "vitest";++// Records of every uploadFileBuffered call so we can assert the resolved tuning+// was threaded through. Hoisted so the module mock can close over it.+const uploadCalls = vi.hoisted(() => [] as any[]);++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")>();+ async function* empty(): AsyncGenerator<Record<string, unknown>> {+ // no rows+ }+ return {+ ...mod,+ StorageServiceFactory: {+ getInstance: () => ({+ uploadFileBuffered: vi.fn(async (params: any) => {+ uploadCalls.push(params);+ // Drain the pipeline stream so it does not hang.+ for await (const _chunk of params.data) {+ void _chunk;+ }+ return undefined;+ }),+ }),+ },+ getTracesForBlobStorageExport: () => empty(),+ getObservationsForBlobStorageExport: () => empty(),+ getScoresForBlobStorageExport: () => empty(),+ getEventsForBlobStorageExport: () => empty(),+ 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(exportTuning: unknown) {+ return {+ projectId: "project-1",+ type: "S3",+ bucketName: "bucket",+ prefix: "",+ accessKeyId: "k",+ secretAccessKey: null,+ region: "auto",+ endpoint: null,+ forcePathStyle: false,+ enabled: true,+ exportFrequency: "daily",+ fileType: "CSV",+ exportMode: "FROM_CUSTOM_DATE",+ exportStartDate: new Date(Date.now() - 2 * 60 * 60 * 1000),+ exportSource: "TRACES_OBSERVATIONS", // legacy, non-enriched β no gate+ exportFieldGroups: ["core"],+ compressed: false,+ // 2h ago so minTimestamp = lastSyncAt and we skip the ClickHouse min query.+ lastSyncAt: new Date(Date.now() - 2 * 60 * 60 * 1000),+ createdAt: new Date("2026-01-01T00:00:00Z"),+ exportTuning,+ };+}++describe("handleBlobStorageIntegrationProjectJob tuning wiring", () => {+ beforeEach(() => {+ uploadCalls.length = 0;+ vi.clearAllMocks();+ });++ it("clamps out-of-range tuning and threads it into uploadFileBuffered", async () => {+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue(+ baseRow({+ partSizeBytes: 1024, // below 5 MiB floor β clamped up+ maxConcurrentParts: 50, // above 32 ceiling β clamped to 32+ maxPartAttempts: 7, // in range+ skipEnrichment: true,+ }),+ );++ await handleBlobStorageIntegrationProjectJob(makeJob());++ expect(uploadCalls.length).toBeGreaterThan(0);+ for (const call of uploadCalls) {+ expect(call.partSizeBytes).toBe(5 * 1024 * 1024); // floor+ expect(call.maxConcurrentParts).toBe(32); // ceiling+ expect(call.maxPartAttempts).toBe(7);+ expect(call.stats).toEqual({+ partsUploaded: 0,+ partRetries: 0,+ partFailures: 0,+ });+ }+ });++ it("uses defaults when exportTuning is null", async () => {+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue(+ baseRow(null),+ );++ await handleBlobStorageIntegrationProjectJob(makeJob());++ expect(uploadCalls.length).toBeGreaterThan(0);+ for (const call of uploadCalls) {+ expect(call.partSizeBytes).toBe(100 * 1024 * 1024); // 100 MiB default+ // Concurrency/attempts are undefined when unset so each StorageService+ // backend keeps its native default (Azure 5, buffered S3 env, etc.).+ expect(call.maxConcurrentParts).toBeUndefined();+ expect(call.maxPartAttempts).toBeUndefined();+ }+ });+});diff --git a/worker/src/__tests__/bufferedStreamUploader.test.ts b/worker/src/__tests__/bufferedStreamUploader.test.tsindex 24cf430c81..32e52417a8 100644--- a/worker/src/__tests__/bufferedStreamUploader.test.ts+++ b/worker/src/__tests__/bufferedStreamUploader.test.ts@@ -341,6 +341,81 @@ describe("BufferedStreamUploader", () => {expect(parts.map((p) => p.partNumber)).toEqual([1, 2, 3]);});+ it("should report counters that the caller's stats sink can read", async () => {+ const mock = createMockStrategy();+ const stats = { partsUploaded: 0, partRetries: 0, partFailures: 0 };+ const uploader = new BufferedStreamUploader({+ ...defaultParams(mock.strategy),+ partSizeBytes: 5,+ maxConcurrentParts: 2,+ stats,+ });++ const returned = await uploader.upload(+ streamFrom(["aaaaa", "bbbbb", "ccccc"]),+ );++ // 3 parts uploaded, no retries, no failures.+ expect(stats).toEqual({+ partsUploaded: 3,+ partRetries: 0,+ partFailures: 0,+ });+ // The return value mirrors the caller's sink.+ expect(returned).toEqual(stats);+ });++ it("should count retries on transient failures", async () => {+ let attempts = 0;+ const mock = createMockStrategy({+ uploadPartImpl: async (data, partNumber) => {+ attempts++;+ if (attempts <= 2) {+ throw new Error("socket hang up");+ }+ return { partIdentifier: `etag-${partNumber}`, partNumber };+ },+ });+ const stats = { partsUploaded: 0, partRetries: 0, partFailures: 0 };+ const uploader = new BufferedStreamUploader({+ ...defaultParams(mock.strategy),+ maxPartAttempts: 5,+ stats,+ });++ await uploader.upload(streamFrom(["hello"]));++ expect(stats.partsUploaded).toBe(1);+ expect(stats.partRetries).toBe(2); // two transient retries before success+ expect(stats.partFailures).toBe(0);+ });++ it("should count a part failure and keep stats readable after throw", async () => {+ const mock = createMockStrategy({+ uploadPartImpl: async () => {+ throw new Error("socket hang up");+ },+ });+ const stats = { partsUploaded: 0, partRetries: 0, partFailures: 0 };+ const uploader = new BufferedStreamUploader({+ ...defaultParams(mock.strategy),+ maxPartAttempts: 2,+ stats,+ });++ await expect(uploader.upload(streamFrom(["hello"]))).rejects.toThrow(+ "socket hang up",+ );++ // The caller's sink survives the throw with accurate counts. With+ // maxPartAttempts=2 the part fails attempt 1 (one real retry follows) then+ // fails attempt 2 (no retry) β so exactly 1 retry, not 2 (the final+ // failing attempt must not be counted as a retry).+ expect(stats.partsUploaded).toBe(0);+ expect(stats.partFailures).toBe(1);+ expect(stats.partRetries).toBe(1);+ });+it("should stop scheduling new parts when a concurrent part fails", async () => {let partsStarted = 0;diff --git a/worker/src/__tests__/enrichObservationStream.unit.test.ts b/worker/src/__tests__/enrichObservationStream.unit.test.tsindex f90a58e69a..ed51a29b07 100644--- a/worker/src/__tests__/enrichObservationStream.unit.test.ts+++ b/worker/src/__tests__/enrichObservationStream.unit.test.ts@@ -158,3 +158,81 @@ describe("enrichObservationStream field group filtering", () => {expect(results[0]).toHaveProperty("total_price");});});++describe("enrichObservationStream skipEnrichment", () => {+ it("is byte-for-byte unchanged when skipEnrichment is false (default)", async () => {+ const rows = [+ { id: "obs-1", model_id: "gpt-4", latency: 2000, metadata: {} },+ ];+ const baseline = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", true, [+ "core" as ObservationFieldGroupFull,+ "model" as ObservationFieldGroupFull,+ "metrics" as ObservationFieldGroupFull,+ ]),+ );+ const explicitFalse = await collect(+ enrichObservationStream(+ rowStream(rows),+ "project-1",+ "model_id",+ true,+ [+ "core" as ObservationFieldGroupFull,+ "model" as ObservationFieldGroupFull,+ "metrics" as ObservationFieldGroupFull,+ ],+ false,+ ),+ );+ expect(explicitFalse).toEqual(baseline);+ // Pricing fields present (as null from the mock).+ expect(explicitFalse[0]).toHaveProperty("input_price");+ expect(explicitFalse[0]).toHaveProperty("output_price");+ expect(explicitFalse[0]).toHaveProperty("total_price");+ });++ it("drops only the three price fields when skipEnrichment is true", async () => {+ const rows = [+ { id: "obs-1", model_id: "gpt-4", latency: 2000, metadata: {} },+ ];+ const results = await collect(+ enrichObservationStream(+ rowStream(rows),+ "project-1",+ "model_id",+ true,+ [+ "core" as ObservationFieldGroupFull,+ "model" as ObservationFieldGroupFull,+ "metrics" as ObservationFieldGroupFull,+ ],+ true,+ ),+ );++ // Price fields dropped...+ expect(results[0]).not.toHaveProperty("input_price");+ expect(results[0]).not.toHaveProperty("output_price");+ expect(results[0]).not.toHaveProperty("total_price");+ // ...but model_id is preserved (it is a source column, not enrichment)...+ expect(results[0]).toHaveProperty("model_id");+ // ...and latency conversion (msβs) still happens.+ expect(results[0].latency).toBe(2);+ });++ it("still cleans up the metadata map when skipEnrichment is true", async () => {+ const rows = [{ id: "obs-1", metadata: {} }];+ const results = await collect(+ enrichObservationStream(+ rowStream(rows),+ "project-1",+ "model_id",+ false,+ ["core" as ObservationFieldGroupFull],+ true,+ ),+ );+ expect(results[0]).not.toHaveProperty("metadata");+ });+});diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex d634eb42da..c1088a2656 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -47,8 +47,11 @@ import {isEnrichedBlobExportAvailable,isEnrichedBlobExportSource,resolveBlobExportTuning,+ DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES,} from "@langfuse/shared";import { decrypt } from "@langfuse/shared/encryption";+// Shared env for the buffered-upload flag (gates part-level upload stats).+import { env as sharedEnv } from "@langfuse/shared/src/env";import { randomUUID } from "crypto";import { SpanKind } from "@opentelemetry/api";import { env, v4AllowPreviewOptIn } from "../../env";@@ -61,10 +64,13 @@ export async function* enrichObservationStream(modelIdField: string,convertLatencyToSeconds: boolean,fieldGroups?: ObservationFieldGroupFull[],+ skipEnrichment: boolean = false,): AsyncGenerator<Record<string, unknown>> {const { getModel } = createModelCache(projectId);- const includeModelId = !fieldGroups || fieldGroups.includes("model");+ // skipEnrichment drops only the model-price lookup; latency + metadata cleanup still run.+ const includeModelId =+ !skipEnrichment && (!fieldGroups || fieldGroups.includes("model"));for await (const row of stream) {const enriched: Record<string, unknown> = { ...row };@@ -275,6 +281,11 @@ const processBlobStorageExport = async (config: {convertV4LatencyToSeconds: boolean;exportFieldGroups?: ObservationFieldGroupFull[];rawPassthrough: boolean;+ // undefined concurrency/attempts => backend keeps its native default.+ partSizeBytes: number;+ maxConcurrentParts: number | undefined;+ maxPartAttempts: number | undefined;+ skipEnrichment: boolean;bullmqJobId: string | undefined;bullmqAttemptsMade: number;}) => {@@ -324,6 +335,24 @@ const processBlobStorageExport = async (config: {span.setAttribute("job.attemptsMade", config.bullmqAttemptsMade);span.setAttribute("host.name", WORKER_HOST_ID);+ // Resolved per-project tuning. Concurrency/attempts omitted when unset+ // (no single value β the backend default applies).+ span.setAttribute("blob.config.partSizeBytes", config.partSizeBytes);+ if (config.maxConcurrentParts !== undefined) {+ span.setAttribute(+ "blob.config.maxConcurrentParts",+ config.maxConcurrentParts,+ );+ }+ if (config.maxPartAttempts !== undefined) {+ span.setAttribute(+ "blob.config.maxPartAttempts",+ config.maxPartAttempts,+ );+ }+ span.setAttribute("blob.config.skipEnrichment", config.skipEnrichment);+ span.setAttribute("blob.config.rawPassthrough", config.rawPassthrough);+// Event-loop delay during the stream: if it spikes, lock renewal can't// fire and the job re-enqueues as stalled (LFE-10063). Torn down below.const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });@@ -504,6 +533,7 @@ const processBlobStorageExport = async (config: {"model_id",false, // v3 query already returns latency in secondsexportFieldGroups,+ config.skipEnrichment,);break;case "scores":@@ -529,6 +559,7 @@ const processBlobStorageExport = async (config: {"model_id",config.convertV4LatencyToSeconds,exportFieldGroups,+ config.skipEnrichment,);break;default:@@ -560,6 +591,17 @@ const processBlobStorageExport = async (config: {// For CSV exports, use larger part size to handle big files// 100 MB parts support files up to ~1 TB (100 MB Γ 10,000 AWS limit)// This prevents hitting AWS's 10,000 part limit on large exports+ // Mutable sink the uploader fills live (readable even if upload throws).+ // Only the S3 buffered path populates it; producesUploadStats gates the+ // telemetry so other paths don't report zero-part uploads.+ const uploadStats = {+ partsUploaded: 0,+ partRetries: 0,+ partFailures: 0,+ };+ const producesUploadStats =+ config.type !== BlobStorageIntegrationType.AZURE_BLOB_STORAGE &&+ sharedEnv.LANGFUSE_S3_UPLOAD_ENABLE_BUFFERED === "true";let uploadStartMs: number | undefined;let uploadDurationMsFinal: number | undefined;try {@@ -569,7 +611,10 @@ const processBlobStorageExport = async (config: {fileName: filePath,fileType: uploadContentType,data: fileStream,- partSizeBytes: 100 * 1024 * 1024, // 100 MB part size+ partSizeBytes: config.partSizeBytes,+ maxConcurrentParts: config.maxConcurrentParts,+ maxPartAttempts: config.maxPartAttempts,+ stats: uploadStats,});// Record at the upload boundary so a throw in the `finally` below// can't miscount a real success as a failure.@@ -626,7 +671,14 @@ const processBlobStorageExport = async (config: {`path=${passthroughEligible ? "passthrough" : "standard"} ` +`rows=${sourceStats.rows} chReadMs=${chReadMs} enrichMs=${enrichMs} ` +`gzipCpuMs=${gzipCpuMs} uploadWaitMs=${uploadWaitMs} ` +- `serializedBytes=${serializedCounter.bytes} uploadDurationMs=${uploadDurationMs}` ++ `serializedBytes=${serializedCounter.bytes} uploadDurationMs=${uploadDurationMs} ` ++ // "configured*" = resolved tuning, not necessarily what the backend+ // applied; uploadParts/Retries/Failures below are the actual effects.+ `configuredPartSizeBytes=${config.partSizeBytes} configuredMaxConcurrentParts=${config.maxConcurrentParts ?? "default"} ` ++ `configuredMaxPartAttempts=${config.maxPartAttempts ?? "default"} skipEnrichment=${config.skipEnrichment}` ++ (producesUploadStats+ ? ` uploadParts=${uploadStats.partsUploaded} uploadRetries=${uploadStats.partRetries} uploadFailures=${uploadStats.partFailures}`+ : "") +(gzipStats && compressedCounter? ` gzipLevel=${gzipStats.level} compressedBytes=${compressedCounter.bytes}`: ""),@@ -689,6 +741,11 @@ const processBlobStorageExport = async (config: {);}}+ if (producesUploadStats) {+ span.setAttribute("blob.upload.parts", uploadStats.partsUploaded);+ span.setAttribute("blob.upload.retries", uploadStats.partRetries);+ span.setAttribute("blob.upload.failures", uploadStats.partFailures);+ }if (compressedCounter) {span.setAttribute("blob.compressedBytes", compressedCounter.bytes);}@@ -901,7 +958,9 @@ export const handleBlobStorageIntegrationProjectJob = async (// Per-project export tuning (set via DB directly; no UI/tRPC write path).// Malformed/absent column resolves to defaults β never throws.const { resolved: exportTuning, warnings: exportTuningWarnings } =- resolveBlobExportTuning(blobStorageIntegration.exportTuning);+ resolveBlobExportTuning(blobStorageIntegration.exportTuning, {+ partSizeBytes: DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES,+ });for (const warning of exportTuningWarnings) {logger.warn(`[BLOB INTEGRATION] exportTuning for project ${projectId}: ${warning}`,@@ -929,6 +988,10 @@ export const handleBlobStorageIntegrationProjectJob = async (exportFieldGroups:blobStorageIntegration.exportFieldGroups as ObservationFieldGroupFull[],rawPassthrough: exportTuning.rawPassthrough,+ partSizeBytes: exportTuning.partSizeBytes,+ maxConcurrentParts: exportTuning.maxConcurrentParts,+ maxPartAttempts: exportTuning.maxPartAttempts,+ skipEnrichment: exportTuning.skipEnrichment,bullmqJobId: job.id,bullmqAttemptsMade: job.attemptsMade,};