Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(worker): instrument gzip cost + tunable level for blob export (LFE-10402) (#14426)

Niklas Semmlerd5f7674f9e90
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.ts
index ce627d7498..8d359708fd 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
@@ -4,32 +4,32 @@ import { resolveBlobExportTuning } from "./blob-export-tuning";
describe("resolveBlobExportTuning", () => {
it("defaults to rawPassthrough=false for null/undefined", () => {
expect(resolveBlobExportTuning(null)).toEqual({
- resolved: { rawPassthrough: false },
+ resolved: { rawPassthrough: false, gzipLevel: undefined },
warnings: [],
});
expect(resolveBlobExportTuning(undefined)).toEqual({
- resolved: { rawPassthrough: false },
+ resolved: { rawPassthrough: false, gzipLevel: undefined },
warnings: [],
});
});
it("honors rawPassthrough=true", () => {
expect(resolveBlobExportTuning({ rawPassthrough: true })).toEqual({
- resolved: { rawPassthrough: true },
+ resolved: { rawPassthrough: true, gzipLevel: undefined },
warnings: [],
});
});
it("honors rawPassthrough=false explicitly", () => {
expect(resolveBlobExportTuning({ rawPassthrough: false })).toEqual({
- resolved: { rawPassthrough: false },
+ resolved: { rawPassthrough: false, gzipLevel: undefined },
warnings: [],
});
});
it("defaults rawPassthrough when the key is absent from a valid object", () => {
expect(resolveBlobExportTuning({})).toEqual({
- resolved: { rawPassthrough: false },
+ resolved: { rawPassthrough: false, gzipLevel: undefined },
warnings: [],
});
});
@@ -41,22 +41,69 @@ describe("resolveBlobExportTuning", () => {
maxConcurrentParts: 8,
skipEnrichment: true,
});
- expect(result.resolved).toEqual({ rawPassthrough: true });
+ expect(result.resolved).toEqual({
+ rawPassthrough: true,
+ gzipLevel: undefined,
+ });
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 });
+ expect(result.resolved).toEqual({
+ rawPassthrough: false,
+ gzipLevel: undefined,
+ });
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 });
+ expect(result.resolved).toEqual({
+ rawPassthrough: false,
+ gzipLevel: undefined,
+ });
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: [],
+ });
+ // level 0 (store) is valid
+ expect(resolveBlobExportTuning({ gzipLevel: 0 })).toEqual({
+ resolved: { rawPassthrough: false, gzipLevel: 0 },
+ warnings: [],
+ });
+ expect(resolveBlobExportTuning({ gzipLevel: 9 })).toEqual({
+ resolved: { rawPassthrough: false, gzipLevel: 9 },
+ warnings: [],
+ });
+ });
+
+ it("clamps an out-of-range gzipLevel to default without disabling rawPassthrough", () => {
+ const tooHigh = resolveBlobExportTuning({
+ rawPassthrough: true,
+ gzipLevel: 12,
+ });
+ expect(tooHigh.resolved).toEqual({
+ rawPassthrough: true,
+ gzipLevel: undefined,
+ });
+ expect(tooHigh.warnings.length).toBe(1);
+
+ const negative = resolveBlobExportTuning({ gzipLevel: -1 });
+ expect(negative.resolved.gzipLevel).toBeUndefined();
+ expect(negative.warnings.length).toBe(1);
+
+ const fractional = resolveBlobExportTuning({ gzipLevel: 3.5 });
+ expect(fractional.resolved.gzipLevel).toBeUndefined();
+ expect(fractional.warnings.length).toBe(1);
+ });
+
it("never throws", () => {
expect(() => resolveBlobExportTuning(12345)).not.toThrow();
expect(() => resolveBlobExportTuning([])).not.toThrow();
diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts
index e6b2e9d9f1..76021ff99e 100644
--- a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts
+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts
@@ -32,12 +32,20 @@ export const BlobExportTuningSchema = z.object({
// >= RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION (see above) for mid-stream failure
// 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(),
});
export type BlobExportTuning = z.infer<typeof BlobExportTuningSchema>;
export type ResolvedBlobExportTuning = {
rawPassthrough: boolean;
+ // undefined => use the zlib default (6); a concrete 0-9 otherwise.
+ gzipLevel: number | undefined;
};
/**
@@ -50,7 +58,10 @@ export function resolveBlobExportTuning(raw: unknown): {
resolved: ResolvedBlobExportTuning;
warnings: string[];
} {
- const defaults: ResolvedBlobExportTuning = { rawPassthrough: false };
+ const defaults: ResolvedBlobExportTuning = {
+ rawPassthrough: false,
+ gzipLevel: undefined,
+ };
if (raw === null || raw === undefined) {
return { resolved: defaults, warnings: [] };
@@ -66,8 +77,28 @@ export function resolveBlobExportTuning(raw: unknown): {
};
}
+ 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`,
+ );
+ }
+ }
+
return {
- resolved: { rawPassthrough: parsed.data.rawPassthrough ?? false },
- warnings: [],
+ resolved: {
+ rawPassthrough: parsed.data.rawPassthrough ?? false,
+ gzipLevel,
+ },
+ warnings,
};
}
diff --git a/worker/src/features/blobstorage/gzipStream.test.ts b/worker/src/features/blobstorage/gzipStream.test.ts
new file mode 100644
index 0000000000..c4975d1b36
--- /dev/null
+++ b/worker/src/features/blobstorage/gzipStream.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect } from "vitest";
+import { pipeline, Readable, Writable } from "stream";
+import { promisify } from "util";
+import { gunzipSync } from "zlib";
+import { TimedGzip, type GzipStats } from "./gzipStream";
+
+const pipelineAsync = promisify(pipeline);
+
+const collect = (chunks: Buffer[]): Writable =>
+ new Writable({
+ write(chunk: Buffer, _enc, cb) {
+ chunks.push(Buffer.from(chunk));
+ cb();
+ },
+ });
+
+// Drives `source` through TimedGzip, collects the compressed output, and
+// returns the concatenated gzip buffer alongside the populated stats.
+async function runGzip(
+ source: Readable,
+ level: number | undefined,
+): Promise<{ output: Buffer; stats: GzipStats }> {
+ const stats: GzipStats = { level: level ?? 6, activeMs: 0 };
+ const chunks: Buffer[] = [];
+ await pipelineAsync(source, new TimedGzip(level, stats), collect(chunks));
+ return { output: Buffer.concat(chunks), stats };
+}
+
+describe("TimedGzip", () => {
+ it("produces a valid gzip stream that round-trips back to the input", async () => {
+ const input = Buffer.from(
+ Array.from({ length: 5000 }, (_, i) => `{"row":${i},"v":"x".}\n`).join(
+ "",
+ ),
+ );
+ const { output, stats } = await runGzip(Readable.from([input]), 6);
+
+ expect(gunzipSync(output).equals(input)).toBe(true);
+ // Real compression work was attributed to the gzip step: zlib offloads each
+ // write to the libuv threadpool, so the write->callback delta is always > 0.
+ expect(stats.activeMs).toBeGreaterThan(0);
+ // It actually compressed (input is highly repetitive).
+ expect(output.length).toBeLessThan(input.length);
+ });
+
+ it("round-trips multi-chunk input and accumulates active time across chunks", async () => {
+ const chunks = Array.from({ length: 50 }, (_, i) =>
+ Buffer.from(`chunk-${i}-`.repeat(2000)),
+ );
+ const expected = Buffer.concat(chunks);
+ const { output, stats } = await runGzip(Readable.from(chunks), 1);
+
+ expect(gunzipSync(output).equals(expected)).toBe(true);
+ expect(stats.activeMs).toBeGreaterThan(0);
+ });
+
+ it("level 0 stores without shrinking but still wraps in valid gzip", async () => {
+ // Near-random data: level 0 must not expand it the way a real codec would
+ // try to, and must still gunzip cleanly.
+ const input = Buffer.from("abcdefghij".repeat(1000));
+ const { output } = await runGzip(Readable.from([input]), 0);
+ expect(gunzipSync(output).equals(input)).toBe(true);
+ });
+
+ it("higher level yields a smaller (or equal) output than level 1", async () => {
+ const input = Buffer.from(
+ Array.from(
+ { length: 8000 },
+ (_, i) => `{"id":${i},"name":"item-${i % 50}"}`,
+ ).join("\n"),
+ );
+ const fast = await runGzip(Readable.from([input]), 1);
+ const best = await runGzip(Readable.from([input]), 9);
+ expect(best.output.length).toBeLessThanOrEqual(fast.output.length);
+ // Both still decompress to the original.
+ expect(gunzipSync(fast.output).equals(input)).toBe(true);
+ expect(gunzipSync(best.output).equals(input)).toBe(true);
+ });
+
+ it("propagates upstream errors so the pipeline aborts", async () => {
+ const boom = new Error("upstream failed");
+ const source = new Readable({
+ read() {
+ this.destroy(boom);
+ },
+ });
+ const stats: GzipStats = { level: 6, activeMs: 0 };
+ await expect(
+ pipelineAsync(source, new TimedGzip(6, stats), collect([])),
+ ).rejects.toThrow("upstream failed");
+ });
+
+ it("uses the zlib default when level is undefined", async () => {
+ const input = Buffer.from("default-level-".repeat(3000));
+ const { output } = await runGzip(Readable.from([input]), undefined);
+ expect(gunzipSync(output).equals(input)).toBe(true);
+ });
+});
diff --git a/worker/src/features/blobstorage/gzipStream.ts b/worker/src/features/blobstorage/gzipStream.ts
new file mode 100644
index 0000000000..e7da9941fe
--- /dev/null
+++ b/worker/src/features/blobstorage/gzipStream.ts
@@ -0,0 +1,81 @@
+import { Transform } from "stream";
+import { createGzip, type Gzip } from "zlib";
+
+export type GzipStats = {
+ // zlib level actually used (the resolved tuning level, or the zlib default
+ // when none was configured). Recorded so a measurement can be tied to a level.
+ level: number;
+ // Active compression time, summed per input chunk as the latency from handing
+ // the chunk to zlib until zlib reports it consumed (zlib offloads to the libuv
+ // threadpool). This isolates compression work from the idle gaps spent waiting
+ // on the next ClickHouse row; under sustained downstream backpressure it also
+ // absorbs upload-wait, which is itself a useful "gzip is not the bottleneck"
+ // signal. Use together with input/output bytes to derive throughput + ratio.
+ activeMs: number;
+};
+
+// zlib resolves Z_DEFAULT_COMPRESSION (-1) to compression level 6. Surfaced
+// explicitly so the gauge reports the real level even when none is configured.
+export const ZLIB_DEFAULT_LEVEL = 6;
+
+/**
+ * Streaming gzip wrapper that attributes compression cost to the gzip step
+ * alone (LFE-10402). It owns a zlib gzip instance, times each chunk's
+ * write→consumed latency into `stats.activeMs`, and forwards the compressed
+ * output while honouring backpressure (pauses the inner stream when the
+ * readable side fills, resumes on the next `_read`). Errors from the inner gzip
+ * surface through the wrapper so `pipeline` aborts the upload as before.
+ */
+export class TimedGzip extends Transform {
+ private readonly gzip: Gzip;
+
+ constructor(
+ level: number | undefined,
+ private readonly stats: GzipStats,
+ ) {
+ super();
+ this.gzip = level === undefined ? createGzip() : createGzip({ level });
+ this.gzip.on("data", (chunk: Buffer) => {
+ if (!this.push(chunk)) this.gzip.pause();
+ });
+ this.gzip.on("error", (err: Error) => this.destroy(err));
+ }
+
+ _read() {
+ this.gzip.resume();
+ }
+
+ _transform(
+ chunk: Buffer,
+ _encoding: string,
+ callback: (error?: Error | null) => void,
+ ) {
+ const startedAt = performance.now();
+ this.gzip.write(chunk, (err) => {
+ this.stats.activeMs += performance.now() - startedAt;
+ callback(err);
+ });
+ }
+
+ _flush(callback: (error?: Error | null) => void) {
+ const startedAt = performance.now();
+ // Complete the flush only once the inner gzip has emitted every byte (its
+ // readable `end`), so the final block + gzip trailer are pushed downstream
+ // before this Transform ends its own readable side. Resolving on `end`
+ // alone — rather than the `end()` write-callback — avoids truncating the
+ // last chunk when output trails the writable `finish`.
+ this.gzip.once("end", () => {
+ this.stats.activeMs += performance.now() - startedAt;
+ callback();
+ });
+ this.gzip.end();
+ // Ensure the readable side is flowing so the trailing `data`/`end` fire even
+ // if downstream had paused us right before flush.
+ this.gzip.resume();
+ }
+
+ _destroy(error: Error | null, callback: (error: Error | null) => void) {
+ this.gzip.destroy(error ?? undefined);
+ callback(error);
+ }
+}
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 389c12a0c7..37487a59f0 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -1,5 +1,4 @@
import { pipeline, Transform, type Readable } from "stream";
-import { createGzip } from "zlib";
import { monitorEventLoopDelay } from "perf_hooks";
import { Job } from "bullmq";
import { prisma } from "@langfuse/shared/src/db";
@@ -19,6 +18,7 @@ import {
getCurrentSpan,
instrumentAsync,
recordGauge,
+ recordHistogram,
recordIncrement,
BlobStorageIntegrationProcessingQueue,
queryClickhouse,
@@ -36,6 +36,7 @@ import {
BLOB_TABLE_EXPORT_METRIC,
type BlobTableExportOutcome,
} from "./inFlightExports";
+import { TimedGzip, ZLIB_DEFAULT_LEVEL, type GzipStats } from "./gzipStream";
import { WORKER_HOST_ID } from "../../utils/hostId";
import {
BlobStorageIntegrationType,
@@ -268,6 +269,9 @@ const processBlobStorageExport = async (config: {
table: "traces" | "observations" | "scores" | "observations_v2"; // observations_v2 is the events table
fileType: BlobStorageIntegrationFileType;
compressed: boolean;
+ // zlib level for the gzip step; undefined => zlib default (6). Only relevant
+ // when `compressed` is true.
+ gzipLevel: number | undefined;
convertV4LatencyToSeconds: boolean;
exportFieldGroups?: ObservationFieldGroupFull[];
rawPassthrough: boolean;
@@ -394,6 +398,10 @@ const processBlobStorageExport = async (config: {
const serializedCounter = new ByteCounter();
const compressedCounter = config.compressed ? new ByteCounter() : null;
+ // Paired with compressedCounter: both exist iff compression is on.
+ const gzipStats: GzipStats | null = compressedCounter
+ ? { level: config.gzipLevel ?? ZLIB_DEFAULT_LEVEL, activeMs: 0 }
+ : null;
// Both paths tally rows in JS via countedStream (the passthrough yields
// raw row text rather than parsed objects, but still iterates).
@@ -427,21 +435,22 @@ const processBlobStorageExport = async (config: {
const dataStream = countedStream(rawRows, sourceStats);
const jsonlNewline = createRawJsonlNewlineTransform();
- fileStream = compressedCounter
- ? pipeline(
- dataStream,
- jsonlNewline,
- serializedCounter,
- createGzip(),
- compressedCounter,
- pipelineCallback,
- )
- : pipeline(
- dataStream,
- jsonlNewline,
- serializedCounter,
- pipelineCallback,
- );
+ fileStream =
+ compressedCounter && gzipStats
+ ? pipeline(
+ dataStream,
+ jsonlNewline,
+ serializedCounter,
+ new TimedGzip(config.gzipLevel, gzipStats),
+ compressedCounter,
+ pipelineCallback,
+ )
+ : pipeline(
+ dataStream,
+ jsonlNewline,
+ serializedCounter,
+ pipelineCallback,
+ );
} else {
let rawStream: AsyncGenerator<Record<string, unknown>>;
@@ -495,21 +504,22 @@ const processBlobStorageExport = async (config: {
const dataStream = countedStream(rawStream, sourceStats);
const formatTransform = streamTransformations[config.fileType]();
- fileStream = compressedCounter
- ? pipeline(
- dataStream,
- formatTransform,
- serializedCounter,
- createGzip(),
- compressedCounter,
- pipelineCallback,
- )
- : pipeline(
- dataStream,
- formatTransform,
- serializedCounter,
- pipelineCallback,
- );
+ fileStream =
+ compressedCounter && gzipStats
+ ? pipeline(
+ dataStream,
+ formatTransform,
+ serializedCounter,
+ new TimedGzip(config.gzipLevel, gzipStats),
+ compressedCounter,
+ pipelineCallback,
+ )
+ : pipeline(
+ dataStream,
+ formatTransform,
+ serializedCounter,
+ pipelineCallback,
+ );
}
// Upload the file to cloud storage
@@ -540,7 +550,11 @@ const processBlobStorageExport = async (config: {
`jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${WORKER_HOST_ID} ` +
`path=${passthroughEligible ? "passthrough" : "standard"} ` +
`rows=${sourceStats.rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` +
- `serializedBytes=${serializedCounter.bytes} uploadDurationMs=${Math.round(performance.now() - uploadStartMs)}`,
+ `serializedBytes=${serializedCounter.bytes} uploadDurationMs=${Math.round(performance.now() - uploadStartMs)}` +
+ (gzipStats && compressedCounter
+ ? ` gzipLevel=${gzipStats.level} gzipActiveMs=${Math.round(gzipStats.activeMs)} ` +
+ `compressedBytes=${compressedCounter.bytes}`
+ : ""),
);
} finally {
span.setAttribute("blob.rows", sourceStats.rows);
@@ -558,6 +572,50 @@ const processBlobStorageExport = async (config: {
if (compressedCounter) {
span.setAttribute("blob.compressedBytes", compressedCounter.bytes);
}
+ if (gzipStats && compressedCounter) {
+ // Gauge the cost of the gzip step so a level change (or moving
+ // compression off the worker) can be evaluated against real data.
+ const activeMs = Math.round(gzipStats.activeMs);
+ // Input/output ratio (>1 = shrank); guard div-by-zero on empty exports.
+ const ratio =
+ compressedCounter.bytes > 0
+ ? serializedCounter.bytes / compressedCounter.bytes
+ : 0;
+ // Compression throughput over uncompressed input bytes.
+ const throughputMbPerSec =
+ gzipStats.activeMs > 0
+ ? serializedCounter.bytes / (gzipStats.activeMs * 1000)
+ : 0;
+
+ span.setAttribute("blob.gzip.level", gzipStats.level);
+ span.setAttribute("blob.gzip.activeMs", activeMs);
+ span.setAttribute("blob.gzip.ratio", Number(ratio.toFixed(3)));
+ span.setAttribute(
+ "blob.gzip.throughputMbPerSec",
+ Number(throughputMbPerSec.toFixed(2)),
+ );
+
+ const metricTags = {
+ table: config.table,
+ path: passthroughEligible ? "passthrough" : "standard",
+ gzipLevel: gzipStats.level,
+ };
+ recordHistogram(
+ "langfuse.blob_export.gzip.active_ms",
+ activeMs,
+ metricTags,
+ );
+ recordHistogram(
+ "langfuse.blob_export.gzip.ratio",
+ ratio,
+ metricTags,
+ );
+ recordHistogram(
+ "langfuse.blob_export.gzip.throughput_mb_per_sec",
+ throughputMbPerSec,
+ metricTags,
+ );
+ }
}
} catch (error) {
// Skip if `success` already fired (a later step threw post-upload).
@@ -745,6 +803,7 @@ export const handleBlobStorageIntegrationProjectJob = async (
type: blobStorageIntegration.type,
fileType: blobStorageIntegration.fileType,
compressed: blobStorageIntegration.compressed,
+ gzipLevel: exportTuning.gzipLevel,
convertV4LatencyToSeconds,
exportFieldGroups:
blobStorageIntegration.exportFieldGroups as ObservationFieldGroupFull[],