ai icon indicating copy to clipboard operation
ai copied to clipboard

bug(provider-utils): readResponseWithSizeLimit retains every chunk view — peak memory is chunk count × chunk buffer size, not body size

Open luizfneves404 opened this issue 1 month ago • 7 comments

Summary

readResponseWithSizeLimit reads a fetch response body incrementally, but keeps every reader.read() value in a chunks: Uint8Array[] array and only concatenates once the body ends (packages/provider-utils/src/read-response-with-size-limit.ts, chunks.push(value) in the loop). response-handler.ts's readResponseBodyAsText calls it, so this is on the path of every AI SDK JSON response (generateText, Output.object, embed, embedMany, createJsonResponseHandler, …).

The size limit itself is good: it turns an unbounded arrayBuffer() OOM into a catchable DownloadError. The issue is only the retention of every intermediate view.

Why it costs more than the body size

Two separate effects:

  1. Runtime-independent, minor. Even on a runtime that returns exact-size chunks, the loop holds the whole body as chunk views and then allocates a second, full-size result buffer while chunks is still referenced, so peak is about 2 × bodySize. When content-length is known this could be a single preallocated buffer instead.
  2. Runtime-dependent, far worse on Deno. In Deno, each reader.read() on a chunked fetch body returns a Uint8Array that is a view over its own fresh ~64 KiB backing buffer, regardless of value.byteLength. Because the loop holds every view until the body ends, each one keeps its 64 KiB backing buffer alive, so peak memory becomes chunk count × 64 KiB, independent of the body's actual size. (The multiplier is specific to bodies delivered in many small HTTP chunks: when the peer sends a content-length, Deno coalesces reads to ~64 KiB and there is no waste.)

Measured on standalone Deno 2.9.6 (--v8-flags=--expose-gc, synthetic body, local chunked server with no content-length):

Body Reader Peak
14 MB, ~1 KB chunks bare reader loop, views retained (what the SDK does) 14,379 reads → 14,379 distinct backing buffers = 899 MB backing, RSS +675 MB
14 MB, ~1 KB chunks AI SDK doEmbed (gateway) RSS +771 MB
15.2 MB, ~1 KB chunks bare reader loop, views retained 15,624 reads → 15,624 distinct backing buffers = 976 MB backing, RSS +731 MB
15.2 MB, content-length sent bare reader / AI SDK RSS +123 MB (no multiplier)

So a response of a few MB that arrives in many small chunks can pin hundreds of MB.

Impact

A Supabase Edge Function isolate (256 MB limit) calling embedMany with 500 headlines receives a ~14 MB JSON body (500 × 1536 floats) streamed in small chunks. Measured against the real gateway: 500 values → 232–382 MB RSS (baseline ≈ 110 MB), against the 256 MB limit. The worker was killed four times in a row with Memory limit exceeded. Replaying the same input in a local edge isolate dies with memory limit reached for the worker before it parses the body; with the batch capped at 100 values the same run stays at ~36 MB.

Expected

The reader should not retain the views reader.read() returns. When content-length is known, preallocate once and result.set(value, offset) per chunk; otherwise copy each chunk into an accumulator as it arrives. Either way the reader's backing buffers become collectable right away, so peak memory tracks the body size rather than the chunk count. For comparison, the current function costs +760 MB RSS for a 15.9 MB body at ~1 KB chunks.

Versions

Present since at least @ai-sdk/provider-utils 5.0.36, and still present in the latest published 5.0.60 and on main. The reporting app is on [email protected] / @ai-sdk/[email protected], both of which resolve to @ai-sdk/[email protected].

Reproduction (no API key needed)

Server that streams a saved body in configurable chunks, no content-length:

Deno.serve({ port, onListen: () => {} }, () => {
  let off = 0;
  const stream = new ReadableStream<Uint8Array>({
    pull(c) {
      if (off >= body.length) return c.close();
      c.enqueue(body.subarray(off, off + CH));
      off += CH;
    },
  });
  return new Response(stream, { headers: { "content-type": "application/json" } });
});

Client that reproduces the retention (CH = 1000, ~15 MB body):

const res = await fetch(url, { method: "POST", body: "{}" });
const reader = res.body!.getReader();
const chunks: Uint8Array[] = [];
const bufs = new Set<ArrayBufferLike>();
let n = 0, backing = 0;
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  n++; bufs.add(value.buffer); chunks.push(value);
}
for (const b of bufs) backing += b.byteLength;
console.log({ chunks: n, distinctBackingBuffers: bufs.size, backing });
// => { chunks: 15_624, distinctBackingBuffers: 15_624, backing: 1_023_934_464 }

The same body through the real function:

import { readResponseWithSizeLimit } from "@ai-sdk/provider-utils";
const out = await readResponseWithSizeLimit({ response: res, url });
// RSS +760 MB for a 15.9 MB body at ~1 KB chunks;
// +46 MB when the server sends the same body with a content-length.

(Note: the 14 MB and 15.2 MB rows are two different bodies from the same script, not disagreeing measurements of one run.)

luizfneves404 avatar Oct 15 '26 13:10 luizfneves404

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete failure in existing response-reading behavior: excessive buffer retention causes severe memory amplification and can terminate constrained runtimes during normal SDK operations.

Evidence

  • readResponseWithSizeLimit retains every reader.read() chunk view until the response completes, then allocates another full-size result buffer.
  • On Deno chunked responses, small views retain separate ~64 KiB backing buffers, causing memory usage to scale with chunk count rather than response size.
  • The report provides reproducible measurements, code, affected versions, and observed worker termination from exceeding memory limits.
  • The behavior is reported as present in current published versions and on main.

ai-sdk-factory[bot] avatar Oct 15 '26 13:10 ai-sdk-factory[bot]

I'd like to work on this — please assign it to me.

akhil9tiet avatar Oct 15 '26 14:10 akhil9tiet

Usage context, since the original report leads with the mechanism:

How we called the SDK. A Supabase Edge Function (Deno, 256 MB memory limit) embeds a batch of up to 500 short strings with openai/text-embedding-3-small through the AI Gateway, in one embedMany call to save round trips:

import { embedMany } from "ai"; // [email protected], @ai-sdk/[email protected] -> @ai-sdk/[email protected]

const { embeddings } = await embedMany({
  model, // gateway "openai/text-embedding-3-small"
  values, // up to 500 short strings
  maxRetries: 2,
  abortSignal: AbortSignal.timeout(60_000),
});

What happened. The worker was killed with Memory limit exceeded on four consecutive attempts at the same batch. Nothing reached our code to catch, because the isolate was killed outright rather than throwing (the existing DownloadError limit never comes into play, since the body is only ~14 MB). The response is about 14 MB of JSON (500 × 1536 floats), and the gateway streamed it in small chunks. Measured against the real gateway, RSS during the call was 232–382 MB from a ~110 MB baseline.

Workaround. We split the input into sequential embedMany calls of at most 100 values, which keeps the same run at about 36 MB. It works, but every Deno or edge caller of embedMany (and of any large JSON response) has to discover this limit on their own. A reader that copies chunks as they arrive would remove the need for it.

Happy to test a canary build against the same workload.

luizfneves404 avatar Oct 15 '26 14:10 luizfneves404

@luizfneves404 that is amazing summary. Do you wish to work on this? I can unclaim since it seems you have so much context

akhil9tiet avatar Oct 15 '26 17:10 akhil9tiet

Noting that this is now assigned to n1ckoates — withdrawing my claim so there's no duplicate work.

akhil9tiet avatar Oct 17 '26 00:10 akhil9tiet

Identify bug discovery

Discovery source: discovery:usage (high confidence).

The bug was discovered through a concrete failure while using the AI SDK in a real Supabase Edge Function, before the reporter investigated the response-reading implementation.

  • A Supabase Edge Function used embedMany for 500 headlines through the AI Gateway.
  • The production worker was killed on four consecutive attempts with Memory limit exceeded.
  • Measurements against the real gateway showed RSS reaching 232–382 MB from an approximately 110 MB baseline.
  • The reporting app’s exact package versions are provided: [email protected] and @ai-sdk/[email protected].
  • The reporter deployed a practical workaround by splitting batches into sequential calls of at most 100 values.

ai-sdk-factory[bot] avatar Oct 19 '26 19:10 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
@ai-sdk/tool-bash 1.0.0 github npm

github-actions[bot] avatar Oct 21 '26 13:10 github-actions[bot]