Skip to content

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

fix(shared): coalesce buffered S3 upload parts in a single pass (#16973)

Niklas Semmler94428222e4cf
diff --git a/packages/shared/src/server/services/BufferedStreamUploader.ts b/packages/shared/src/server/services/BufferedStreamUploader.ts
index 394ad6521c..aa4cbd743b 100644
--- a/packages/shared/src/server/services/BufferedStreamUploader.ts
+++ b/packages/shared/src/server/services/BufferedStreamUploader.ts
@@ -94,7 +94,12 @@ export class BufferedStreamUploader {
private readonly stats: UploadPartStats;
constructor(params: BufferedStreamUploaderParams) {
- this.params = params;
+ // Buffer.concat rejects a non-integer length. Callers can pass
+ // MiB * 1024 * 1024 from a fractional env value (e.g. 5.1).
+ this.params = {
+ ...params,
+ partSizeBytes: Math.floor(params.partSizeBytes),
+ };
this.stats = params.stats ?? emptyUploadPartStats();
}
@@ -118,15 +123,20 @@ export class BufferedStreamUploader {
this.currentBuffer.push(buf);
this.currentBufferSize += buf.byteLength;
- if (this.currentBufferSize >= this.params.partSizeBytes) {
- await this.flushBuffer();
- if (this.errors.hasError()) break;
+ // Slice exact partSizeBytes parts and carry the remainder. Some
+ // S3-compatible endpoints reject complete-multipart when non-trailing
+ // parts differ in length.
+ while (
+ this.currentBufferSize >= this.params.partSizeBytes &&
+ !this.errors.hasError()
+ ) {
+ await this.flushExactPart();
}
}
- // Flush remaining data
+ // Final part is the only one allowed to be smaller than partSizeBytes.
if (this.currentBufferSize > 0 && !this.errors.hasError()) {
- await this.flushBuffer();
+ await this.flushRemainder();
}
// Wait for all in-flight uploads to complete
@@ -168,10 +178,60 @@ export class BufferedStreamUploader {
return this.stats;
}
- private async flushBuffer(): Promise<void> {
- const partData = Buffer.concat(this.currentBuffer);
- this.currentBuffer = [];
- this.currentBufferSize = 0;
+ private async flushExactPart(): Promise<void> {
+ await this.enqueuePart(this.takeBytes(this.params.partSizeBytes));
+ }
+
+ private async flushRemainder(): Promise<void> {
+ await this.enqueuePart(this.takeBytes(this.currentBufferSize));
+ }
+
+ // Splits off the first `byteLength` bytes of currentBuffer as the part to
+ // upload and keeps the leftover as the new buffer. Coalesces in a single
+ // Buffer.concat pass so cost stays linear in the byte count regardless of
+ // how many row chunks accumulated; a part can hold hundreds of thousands of
+ // per-row chunks and this runs on the worker's shared event loop.
+ // Caller must pass byteLength <= currentBufferSize.
+ private takeBytes(byteLength: number): Buffer {
+ // Single backing buffer: this is the loop that slices one oversized stream
+ // chunk into k = chunkSize / partSizeBytes parts. Re-concatenating and
+ // re-copying the shrinking leftover on each of those k calls would be
+ // O(chunkSize^2 / partSizeBytes) — the same synchronous event-loop stall
+ // this class avoids for many small chunks. Instead slice by view: copy
+ // only the emitted part (so the large source frees once this synchronous
+ // loop ends, rather than being pinned for the upload's retry lifetime) and
+ // carry the leftover as a zero-copy view. Cost stays O(chunkSize).
+ if (this.currentBuffer.length === 1) {
+ const buf = this.currentBuffer[0];
+ this.currentBufferSize -= byteLength;
+ if (byteLength === buf.byteLength) {
+ this.currentBuffer = [];
+ return buf;
+ }
+ this.currentBuffer = [buf.subarray(byteLength)];
+ return Buffer.from(buf.subarray(0, byteLength));
+ }
+
+ const combined = Buffer.concat(this.currentBuffer);
+ const remainderLength = combined.byteLength - byteLength;
+ // Non-final parts are normally returned as a view into `combined`: no copy
+ // on the hot path, where `combined` is one part plus at most a trailing
+ // row. But a single oversized stream chunk makes `combined` several parts
+ // large, and a view would pin that whole buffer for the part upload's
+ // lifetime (including retry backoff). When at least one more part is left
+ // over, copy the slice so `combined` is freed as soon as this returns.
+ const partData =
+ remainderLength >= byteLength
+ ? Buffer.from(combined.subarray(0, byteLength))
+ : combined.subarray(0, byteLength);
+ // Copy the leftover into its own allocation for the same reason.
+ this.currentBuffer =
+ remainderLength > 0 ? [Buffer.from(combined.subarray(byteLength))] : [];
+ this.currentBufferSize -= byteLength;
+ return partData;
+ }
+
+ private async enqueuePart(partData: Buffer): Promise<void> {
this.partNumber++;
// Wait for a slot if all concurrent slots are full
diff --git a/worker/src/__tests__/bufferedStreamUploader.test.ts b/worker/src/__tests__/bufferedStreamUploader.test.ts
index 32e52417a8..2a1b44b7af 100644
--- a/worker/src/__tests__/bufferedStreamUploader.test.ts
+++ b/worker/src/__tests__/bufferedStreamUploader.test.ts
@@ -127,6 +127,167 @@ describe("BufferedStreamUploader", () => {
});
});
+ describe("equal-sized non-final parts", () => {
+ it("emits exact partSizeBytes non-final parts, splitting a chunk across a boundary", async () => {
+ const mock = createMockStrategy();
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes: 10,
+ });
+
+ // 4-byte chunks that do not align to the 10-byte boundary: "cccc" must
+ // be split so part 1 is exactly 10 bytes.
+ await uploader.upload(streamFrom(["aaaa", "bbbb", "cccc", "dddd"]));
+
+ expect(mock.uploadedParts).toHaveLength(2);
+ expect(mock.uploadedParts[0].data).toEqual(Buffer.from("aaaabbbbcc"));
+ expect(mock.uploadedParts[1].data).toEqual(Buffer.from("ccdddd"));
+ });
+
+ it("splits a single oversized chunk into exact parts plus a remainder", async () => {
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => {});
+ try {
+ const mock = createMockStrategy();
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes: 10,
+ });
+
+ await uploader.upload(streamFrom(["x".repeat(25)]));
+
+ expect(mock.uploadedParts.map((p) => p.data.byteLength)).toEqual([
+ 10, 10, 5,
+ ]);
+ expect(Buffer.concat(mock.uploadedParts.map((p) => p.data))).toEqual(
+ Buffer.from("x".repeat(25)),
+ );
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
+ it("returns an oversized chunk's non-final parts as their own allocation, not a view pinning the whole chunk", async () => {
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => {});
+ try {
+ const mock = createMockStrategy();
+ // Above Node's Buffer pool threshold so a copied slice gets a
+ // dedicated ArrayBuffer sized to the slice, while a subarray view
+ // would keep the full coalesced backing buffer.
+ const partSizeBytes = 8192;
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes,
+ });
+
+ // One chunk spanning >2 parts: part 1 leaves >= a full part over.
+ await uploader.upload(
+ streamFrom(["x".repeat(partSizeBytes * 2 + 100)]),
+ );
+
+ const parts = [...mock.uploadedParts].sort(
+ (a, b) => a.partNumber - b.partNumber,
+ );
+ expect(parts.map((p) => p.data.byteLength)).toEqual([
+ partSizeBytes,
+ partSizeBytes,
+ 100,
+ ]);
+ // Part 1 is copied, so its backing buffer is exactly the slice size
+ // rather than the full ~16 KiB coalesced chunk.
+ expect(parts[0].data.buffer.byteLength).toBe(partSizeBytes);
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
+ it("splits a single chunk spanning many parts without a quadratic slowdown", async () => {
+ const warnSpy = vi.spyOn(logger, "warn").mockImplementation(() => {});
+ try {
+ const mock = createMockStrategy();
+ const partSizeBytes = 1024;
+ const numParts = 2000; // one ~2 MiB chunk sliced into 2000 parts
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes,
+ maxConcurrentParts: 5,
+ });
+
+ // Re-concatenating/re-copying the shrinking leftover on each of the
+ // 2000 slices would be O(chunkSize^2) and blow the test timeout;
+ // view-based slicing keeps it O(chunkSize).
+ await uploader.upload(
+ streamFrom(["x".repeat(partSizeBytes * numParts)]),
+ );
+
+ const parts = [...mock.uploadedParts].sort(
+ (a, b) => a.partNumber - b.partNumber,
+ );
+ expect(parts).toHaveLength(numParts);
+ expect(parts.every((p) => p.data.byteLength === partSizeBytes)).toBe(
+ true,
+ );
+ expect(parts.reduce((sum, p) => sum + p.data.byteLength, 0)).toBe(
+ partSizeBytes * numParts,
+ );
+ } finally {
+ warnSpy.mockRestore();
+ }
+ });
+
+ it("floors a fractional partSizeBytes so Buffer.concat does not throw", async () => {
+ const mock = createMockStrategy();
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes: 10.7,
+ });
+
+ await uploader.upload(streamFrom(["a".repeat(20)]));
+
+ expect(mock.uploadedParts.map((p) => p.data.byteLength)).toEqual([
+ 10, 10,
+ ]);
+ });
+
+ it("coalesces very many small chunks into equal parts without a quadratic slowdown", async () => {
+ const mock = createMockStrategy();
+ const partSizeBytes = 1024 * 1024; // 1 MiB
+ const chunkBytes = 20;
+ const numChunks = 100_000; // ~52k chunks land in a single part
+ const uploader = new BufferedStreamUploader({
+ ...defaultParams(mock.strategy),
+ partSizeBytes,
+ maxConcurrentParts: 3,
+ });
+
+ // A generator stream avoids materializing all chunks in an array. This
+ // many chunks in a single part finishes near-instantly only if part
+ // assembly is linear in the byte count; a quadratic-per-chunk assembly
+ // would blow the test timeout.
+ const stream = Readable.from(
+ (function* () {
+ for (let i = 0; i < numChunks; i++) yield "x".repeat(chunkBytes);
+ })(),
+ );
+
+ await uploader.upload(stream);
+
+ const totalBytes = numChunks * chunkBytes;
+ const parts = [...mock.uploadedParts].sort(
+ (a, b) => a.partNumber - b.partNumber,
+ );
+ // Every part except the last must be exactly partSizeBytes.
+ for (const part of parts.slice(0, -1)) {
+ expect(part.data.byteLength).toBe(partSizeBytes);
+ }
+ expect(parts[parts.length - 1].data.byteLength).toBeLessThanOrEqual(
+ partSizeBytes,
+ );
+ expect(parts.reduce((sum, p) => sum + p.data.byteLength, 0)).toBe(
+ totalBytes,
+ );
+ });
+ });
+
describe("empty stream", () => {
it("should handle empty stream with single object upload instead of multipart", async () => {
const mock = createMockStrategy();