ai icon indicating copy to clipboard operation
ai copied to clipboard

convertBase64ToUint8Array peaks at ~25-30x the decoded size and blocks the event loop (~0.9 s for a 20 MB image on Node 24)

Open mttzzz opened this issue 1 month ago • 6 comments

Description

convertBase64ToUint8Array in @ai-sdk/provider-utils (packages/provider-utils/src/uint8-utils.ts, unchanged on main as of 2026-11-01) has a transient peak of about 25–30× the decoded size. It also blocks the event loop for a long time: ~0.9 s for a 20 MB image on Node 24.

export function convertBase64ToUint8Array(base64String: string) {
  const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');
  const latin1string = atob(base64Url);
  return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);
}

Uint8Array.from(string, mapFn) uses the iterator protocol. It allocates a one-character string per byte, calls the map callback per byte, and collects the values into an intermediate list before it allocates the typed array. Callers hit this path when they read .uint8Array of a generated file, e.g. image results of generateImage and file parts from generateText (DefaultGeneratedFile).

The encode direction (convertUint8ArrayToBase64) already uses Buffer when it is available. The decode direction does not.

Measurements. One fresh process per measurement. "Peak" is process.resourceUsage().maxRSS after the call minus the value before it. Each cell is the median of 3 runs, random bytes, correctness checked byte-for-byte.

decoded size current (Node 24.21) preallocated loop (Node) Buffer.from (Node) current (Bun 1.4.3) Buffer.from (Bun) Uint8Array.fromBase64 (Bun)
2 MB 109 MiB / 120 ms 12 MiB / 4 ms 4 MiB / 1 ms 66 MiB / 30 ms 2 MiB / 1 ms 4 MiB / 1 ms
8 MB 366 MiB / 394 ms 28 MiB / 12 ms 15 MiB / 2 ms 247 MiB / 91 ms 8 MiB / 2 ms 16 MiB / 5 ms
20 MB 559 MiB / 910 ms 63 MiB / 30 ms 38 MiB / 5 ms 510 MiB / 202 ms 19 MiB / 5 ms 39 MiB / 10 ms

Impact we saw. Our image-generation worker runs 8 concurrent jobs through the gateway provider. With ~20 MB images it peaked at ~1.9 GiB in a container. A single Gemini response with 4 images peaked at 0.9–1.3 GiB on its own. Replacing only this conversion with Buffer.from(base64, 'base64') on our side cut the 8-job peak from 1858 to 1208 MiB.

Suggested fix. Any of these keeps the API unchanged:

export function convertBase64ToUint8Array(base64String: string) {
  const base64 = base64String.replace(/-/g, '+').replace(/_/g, '/');
  const latin1 = atob(base64); // keeps today's strictness (InvalidCharacterError on bad input)
  const bytes = new Uint8Array(latin1.length);
  for (let i = 0; i < latin1.length; i++) bytes[i] = latin1.charCodeAt(i);
  return bytes;
}
  1. Preallocated loop (above). The smallest change: same validation behaviour, ~9× less peak and ~30× faster on Node.
  2. Buffer.from when available, mirroring convertUint8ArrayToBase64. Cheapest, but Buffer is lenient: it ignores invalid characters instead of throwing. The strictness would have to be kept separately if it matters (cf. #23943).
  3. Uint8Array.fromBase64 where available (Bun, recent browsers; not yet in Node 24).

Related, lower priority. For base64-heavy JSON responses the body exists several times at peak before this step:

  • readResponseWithSizeLimit keeps chunks[] plus the concatenated Uint8Array;
  • TextDecoder.decode produces the text;
  • secureJsonParse runs JSON.parse plus two regex tests over the full text.

With a 26 MB body (one 20 MB image) that is roughly 4 copies alive at once. The decode fix above is the cheap big win. Streaming large binary fields would be the follow-up.

I'm happy to open a PR with option 1 (or 2) and a test.

Reproduction

node repro.mjs (each measurement runs in a fresh child; on Linux ru_maxrss is inherited across fork/exec, so the child is spawned from a small parent to get a clean baseline):

import { randomBytes } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const impl = {
  current: s => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), b => b.codePointAt(0)),
  loop: s => { const l = atob(s.replace(/-/g, '+').replace(/_/g, '/')); const o = new Uint8Array(l.length); for (let i = 0; i < l.length; i++) o[i] = l.charCodeAt(i); return o; },
  buffer: s => { const b = Buffer.from(s, 'base64'); return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); },
};

const [method, mb] = process.argv.slice(2);
if (!method) {
  for (const size of [2, 8, 20])
    for (const m of Object.keys(impl))
      process.stdout.write(spawnSync(process.execPath, ['--expose-gc', fileURLToPath(import.meta.url), m, String(size)], { encoding: 'utf8' }).stdout);
} else {
  const bytes = randomBytes(Number(mb) * 1e6);
  const b64 = bytes.toString('base64');
  globalThis.gc();
  const before = process.resourceUsage().maxRSS; // KiB
  const t0 = performance.now();
  const out = impl[method](b64);
  const ms = performance.now() - t0;
  const peak = Math.round((process.resourceUsage().maxRSS - before) / 1024);
  console.log(`${method} ${mb} MB: +${peak} MiB peak RSS, ${Math.round(ms)} ms, ok=${Buffer.compare(Buffer.from(out), bytes) === 0}`);
}

Output on Node 24.21.0 (linux/x64, single run):

current 2 MB: +118 MiB peak RSS, 114 ms, ok=true
loop 2 MB: +10 MiB peak RSS, 4 ms, ok=true
buffer 2 MB: +2 MiB peak RSS, 0 ms, ok=true
current 8 MB: +306 MiB peak RSS, 375 ms, ok=true
loop 8 MB: +21 MiB peak RSS, 12 ms, ok=true
buffer 8 MB: +8 MiB peak RSS, 2 ms, ok=true
current 20 MB: +559 MiB peak RSS, 904 ms, ok=true
loop 20 MB: +44 MiB peak RSS, 28 ms, ok=true
buffer 20 MB: +19 MiB peak RSS, 5 ms, ok=true

AI SDK Version

  • ai: 7.0.143
  • @ai-sdk/provider-utils: 5.0.62 (same code on main)
  • @ai-sdk/gateway: 4.0.116
  • Runtimes: Node 24.21.0, Bun 1.4.3 (linux/x64)

Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

mttzzz avatar Nov 01 '26 06:11 mttzzz

Identify issue type

Identified as Bug
Confidence: High

Rationale

The issue reports a concrete performance defect in existing SDK behavior, supported by reproduction code and measured operational impact, rather than requesting a new capability.

Evidence

  • The existing base64 decoder reportedly consumes roughly 25–30 times the decoded size in transient memory and blocks the event loop for about 0.9 seconds for a 20 MB image.
  • A runnable reproduction demonstrates excessive memory and latency compared with equivalent decoding implementations.
  • The reporter observed substantial memory pressure in concurrent image-generation jobs and proposes an API-preserving fix.

ai-sdk-factory[bot] avatar Nov 01 '26 06:11 ai-sdk-factory[bot]

Identify bug discovery

Discovery source: discovery:usage (high confidence).

The author reports concrete operational impact in their image-generation worker, including container memory peaks and an application-side mitigation. This establishes actual application use rather than an audit-only discovery; the source analysis and benchmarks explain the observed problem.

  • “Our image-generation worker runs 8 concurrent jobs through the gateway provider.”
  • With approximately 20 MB images, the worker peaked at approximately 1.9 GiB in a container.
  • A single Gemini response containing four images peaked at 0.9–1.3 GiB.
  • Replacing the conversion on their side reduced the eight-job peak from 1858 to 1208 MiB.

ai-sdk-factory[bot] avatar Nov 01 '26 06:11 ai-sdk-factory[bot]

@mttzzz @ai-sdk-factory Could you assign it to me?

himanchalkaushale avatar Nov 01 '26 06:11 himanchalkaushale

Thanks for the interest! I'm not a maintainer, so I can't assign it. I already offered a PR in the description and I'm putting it together now (the preallocated loop, which keeps atob's strict validation, plus tests). I'll link it here shortly.

mttzzz avatar Nov 01 '26 07:11 mttzzz

PR: #24325

mttzzz avatar Nov 01 '26 07:11 mttzzz

Follow-up PR for the remaining copies of the response body (streaming extraction of large base64 fields, opt-in, gateway image model as the first user): #24326

mttzzz avatar Nov 01 '26 09:11 mttzzz