🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(worker): measure Parquet upload-wait via byte-counter backpressure (LFE-10463) (#14561)
Niklas Semmler65cefb72a618
diff --git a/worker/src/features/blobstorage/byteCounters.test.ts b/worker/src/features/blobstorage/byteCounters.test.tsnew file mode 100644index 0000000000..19acfbbf7e--- /dev/null+++ b/worker/src/features/blobstorage/byteCounters.test.ts@@ -0,0 +1,104 @@+import { describe, it, expect } from "vitest";+import { pipeline, Readable, Writable } from "stream";+import { promisify } from "util";+import {+ ByteCounter,+ TimedByteCounter,+ type TimedByteCounterStats,+} from "./byteCounters";++const pipelineAsync = promisify(pipeline);++const collect = (chunks: Buffer[], perChunkDelayMs = 0): Writable =>+ new Writable({+ // highWaterMark 1 keeps the readable buffer shallow so a slow sink reliably+ // backpressures the counter (push() returns false), exercising the timer.+ highWaterMark: 1,+ write(chunk: Buffer, _enc, cb) {+ chunks.push(Buffer.from(chunk));+ if (perChunkDelayMs > 0) setTimeout(cb, perChunkDelayMs);+ else cb();+ },+ });++// Emits `count` chunks `gapMs` apart, simulating ClickHouse delivering row+// groups with a wait between each.+function spacedSource(+ count: number,+ gapMs: number,+ bytesPerChunk = 64 * 1024,+): Readable {+ async function* gen() {+ for (let i = 0; i < count; i++) {+ if (gapMs > 0) await new Promise((r) => setTimeout(r, gapMs));+ yield Buffer.alloc(bytesPerChunk, i % 256);+ }+ }+ return Readable.from(gen());+}++describe("ByteCounter", () => {+ it("forwards bytes unchanged and tallies the total", async () => {+ const input = [Buffer.from("hello "), Buffer.from("world")];+ const out: Buffer[] = [];+ const counter = new ByteCounter();+ await pipelineAsync(Readable.from(input), counter, collect(out));+ expect(Buffer.concat(out).toString()).toBe("hello world");+ expect(counter.bytes).toBe(11);+ });+});++describe("TimedByteCounter", () => {+ it("forwards every byte unchanged", async () => {+ const chunks = Array.from({ length: 20 }, (_, i) =>+ Buffer.from(`row-${i};`),+ );+ const expected = Buffer.concat(chunks);+ const stats: TimedByteCounterStats = { sourceWaitMs: 0, backpressureMs: 0 };+ const out: Buffer[] = [];+ const counter = new TimedByteCounter(stats);+ await pipelineAsync(Readable.from(chunks), counter, collect(out));+ expect(Buffer.concat(out).equals(expected)).toBe(true);+ expect(counter.bytes).toBe(expected.length);+ });++ it("attributes wait to ClickHouse when the source is the bottleneck", async () => {+ // Slow source (30ms between chunks), instant sink: the gap is pure CH read.+ const stats: TimedByteCounterStats = { sourceWaitMs: 0, backpressureMs: 0 };+ const counter = new TimedByteCounter(stats);+ await pipelineAsync(spacedSource(6, 30), counter, collect([]));++ const chReadMs = stats.sourceWaitMs - stats.backpressureMs;+ // ~6 * 30ms of source wait, almost none of it backpressure.+ expect(stats.sourceWaitMs).toBeGreaterThan(100);+ expect(stats.backpressureMs).toBeLessThan(stats.sourceWaitMs / 2);+ expect(chReadMs).toBeGreaterThan(50);+ });++ it("attributes wait to upload backpressure when the sink is the bottleneck", async () => {+ // Instant source, slow sink (40ms/chunk): the wait is S3 backpressure, and+ // chReadMs (sourceWaitMs - backpressureMs) must not absorb it.+ const stats: TimedByteCounterStats = { sourceWaitMs: 0, backpressureMs: 0 };+ const counter = new TimedByteCounter(stats);+ await pipelineAsync(spacedSource(6, 0), counter, collect([], 40));++ const chReadMs = Math.max(0, stats.sourceWaitMs - stats.backpressureMs);+ expect(stats.backpressureMs).toBeGreaterThan(100);+ // The dominant wait is upload, not ClickHouse — the bug this guards against+ // (uploadWaitMs collapsing to ~0) would instead show all time as chRead.+ expect(stats.backpressureMs).toBeGreaterThan(chReadMs);+ });++ 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: TimedByteCounterStats = { sourceWaitMs: 0, backpressureMs: 0 };+ await expect(+ pipelineAsync(source, new TimedByteCounter(stats), collect([])),+ ).rejects.toThrow("upstream failed");+ });+});diff --git a/worker/src/features/blobstorage/byteCounters.ts b/worker/src/features/blobstorage/byteCounters.tsnew file mode 100644index 0000000000..bca90639b5--- /dev/null+++ b/worker/src/features/blobstorage/byteCounters.ts@@ -0,0 +1,62 @@+import { Transform } from "stream";++export type TimedByteCounterStats = {+ sourceWaitMs: number;+ backpressureMs: number;+};++export class ByteCounter extends Transform {+ bytes = 0;+ _transform(+ chunk: Buffer,+ _encoding: string,+ callback: (error: Error | null, data?: Buffer) => void,+ ) {+ this.bytes += chunk.length;+ callback(null, chunk);+ }+}++// Boundary byte counter for the Parquet path. sourceWaitMs is the total+// inter-chunk gap; backpressureMs isolates the S3-upload share of it via the+// push()/_read() gap (as TimedGzip does). chReadMs = sourceWaitMs -+// backpressureMs; uploadWaitMs = backpressureMs.+export class TimedByteCounter extends ByteCounter {+ private readonly stats: TimedByteCounterStats;+ // From construction so the first gap captures Parquet's time-to-first-byte.+ private lastChunkDoneAt: number = performance.now();+ private bpStart: number | null = null;+ constructor(stats: TimedByteCounterStats) {+ super();+ this.stats = stats;+ }+ private creditBackpressure() {+ if (this.bpStart !== null) {+ this.stats.backpressureMs += performance.now() - this.bpStart;+ this.bpStart = null;+ }+ }+ // _read = downstream drained; closes the open backpressure interval.+ _read(size: number) {+ this.creditBackpressure();+ super._read(size);+ }+ _transform(+ chunk: Buffer,+ _encoding: string,+ callback: (error: Error | null, data?: Buffer) => void,+ ) {+ this.stats.sourceWaitMs += performance.now() - this.lastChunkDoneAt;+ this.bytes += chunk.length;+ // Explicit push so a false return opens a backpressure interval.+ if (!this.push(chunk) && this.bpStart === null) {+ this.bpStart = performance.now();+ }+ this.lastChunkDoneAt = performance.now();+ callback(null);+ }+ _flush(callback: (error?: Error | null) => void) {+ this.creditBackpressure();+ callback();+ }+}diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex e67ee13dab..67cf3f9fb7 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -41,6 +41,7 @@ import {type BlobTableExportOutcome,} from "./inFlightExports";import { TimedGzip, ZLIB_DEFAULT_LEVEL, type GzipStats } from "./gzipStream";+import { ByteCounter, TimedByteCounter } from "./byteCounters";import { WORKER_HOST_ID } from "../../utils/hostId";import {BlobStorageIntegrationType,@@ -269,44 +270,6 @@ const getFileTypeProperties = (fileType: BlobStorageIntegrationFileType) => {}};-class ByteCounter extends Transform {- bytes = 0;- _transform(- chunk: Buffer,- _encoding: string,- callback: (error: Error | null, data?: Buffer) => void,- ) {- this.bytes += chunk.length;- callback(null, chunk);- }-}--// ByteCounter that also tallies inter-chunk gaps into `stats.sourceWaitMs`, so-// the Parquet path (piped binary stream, no per-row generator) reuses the-// standard chReadMs/uploadWaitMs derivation. Coarse: source wait conflates CH-// delivery with S3 backpressure (same as countedStream).-class TimedByteCounter extends ByteCounter {- private readonly stats: { sourceWaitMs: number };- // Clock starts at construction (like countedStream, before its loop) so the- // first gap captures time-to-first-byte — the dominant CH wait, since Parquet- // composes a row group before any bytes. Guarding it would drop TTFB from chReadMs.- private lastChunkDoneAt: number = performance.now();- constructor(stats: { sourceWaitMs: number }) {- super();- this.stats = stats;- }- _transform(- chunk: Buffer,- _encoding: string,- callback: (error: Error | null, data?: Buffer) => void,- ) {- this.stats.sourceWaitMs += performance.now() - this.lastChunkDoneAt;- this.bytes += chunk.length;- this.lastChunkDoneAt = performance.now();- callback(null, chunk);- }-}-async function* countedStream<T>(source: AsyncGenerator<T>,stats: { rows: number; sourceWaitMs: number },@@ -518,10 +481,9 @@ const processBlobStorageExport = async (config: {}};- // Tracks ClickHouse read wait. Declared before the counters so the- // parquet TimedByteCounter can write into it (the parquet path has no- // per-row generator, so countedStream does not run).- const sourceStats = { rows: 0, sourceWaitMs: 0 };+ // Source read wait; backpressureMs is set only by the parquet+ // TimedByteCounter and stays 0 on every other path.+ const sourceStats = { rows: 0, sourceWaitMs: 0, backpressureMs: 0 };// When enrichment is active, chStats isolates ClickHouse read wait from// enrichment CPU. enrichMs = sourceStats.sourceWaitMs - chStats.sourceWaitMs.let chStats: { rows: number; sourceWaitMs: number } | null = null;@@ -805,8 +767,15 @@ const processBlobStorageExport = async (config: {});const uploadDurationMs = uploadDurationMsFinal;+ // Parquet's source counter sits at the upload boundary, so strip its+ // backpressure to recover pure CH read (no-op elsewhere: gzip isolates+ // CH read in chStats, and backpressureMs is 0 on every other path).const chReadMs = Math.round(- chStats ? chStats.sourceWaitMs : sourceStats.sourceWaitMs,+ Math.max(+ 0,+ (chStats ? chStats.sourceWaitMs : sourceStats.sourceWaitMs) -+ (chStats ? 0 : sourceStats.backpressureMs),+ ),);const enrichMs = chStats? Math.max(@@ -820,9 +789,12 @@ const processBlobStorageExport = async (config: {Math.round(gzipStats.activeMs - gzipStats.backpressureMs),): 0;+ // Measured backpressure (gzip / parquet boundary), else duration residual.const uploadWaitMs = gzipStats? Math.round(gzipStats.backpressureMs)- : Math.max(0, uploadDurationMs - chReadMs - enrichMs);+ : parquetEligible+ ? Math.round(sourceStats.backpressureMs)+ : Math.max(0, uploadDurationMs - chReadMs - enrichMs);logger.info(`[BLOB INTEGRATION] Successfully exported ${config.table} for project ${config.projectId}: ` +@@ -844,8 +816,13 @@ const processBlobStorageExport = async (config: {);} finally {span.setAttribute("blob.rows", sourceStats.rows);+ // Same chReadMs / uploadWaitMs derivation as the success path above.const finalChReadMs = Math.round(- chStats ? chStats.sourceWaitMs : sourceStats.sourceWaitMs,+ Math.max(+ 0,+ (chStats ? chStats.sourceWaitMs : sourceStats.sourceWaitMs) -+ (chStats ? 0 : sourceStats.backpressureMs),+ ),);const finalEnrichMs = chStats? Math.max(@@ -870,7 +847,9 @@ const processBlobStorageExport = async (config: {: 0;const finalUploadWaitMs = gzipStats? Math.round(gzipStats.backpressureMs)- : Math.max(0, totalUploadMs - finalChReadMs - finalEnrichMs);+ : parquetEligible+ ? Math.round(sourceStats.backpressureMs)+ : Math.max(0, totalUploadMs - finalChReadMs - finalEnrichMs);span.setAttribute("blob.gzipCpuMs", finalGzipCpuMs);span.setAttribute("blob.uploadWaitMs", finalUploadWaitMs);const finalExportFormat = parquetEligible