Development How-to

Your agent's CSV import works on the sample file and dies on the real one: put it on a heap budget

Agent-written Node code loves readFile and split. A Vitest test that runs the import in a 48 MB heap fails it in about 150 ms, and the streaming rewrite passes.

A wide flat ribbon cable narrowing to a thin strip as it passes through a slot in a small metal bracket

An agent is asked to total order values per customer from a CSV export. It writes twelve tidy lines, a test with a five-row fixture passes, and the pull request looks fine. In production the export is 4 GB and the process dies with JavaScript heap out of memory at 2am.

Nothing in the diff is wrong in the way a reviewer looks for. The logic is correct. The shape is wrong: the whole file goes into memory before the first row is processed, and no test ever pushes the code past a toy size.

The fix is a test that gives the function a small, fixed heap and a file much larger than that heap. A version that reads everything fails in about 150 ms. A version that streams passes, and the test keeps catching the regression every time someone, human or agent, edits the module later. The technique works with any coding agent that can read files and run a shell, because the budget lives in the repo and the agent only has to make the test go green. The example is TypeScript on Node 22 with Vitest.

What the agent writes first

This is the typical first draft. It’s correct, readable and short:

import { readFile } from "node:fs/promises";

export async function totalsByCustomer(path: string): Promise<Map<string, number>> {
  const text = await readFile(path, "utf8");
  const rows = text.split("\n").filter((line) => line.length > 0);
  const totals = new Map<string, number>();
  for (const row of rows.slice(1)) {
    const [customer, cents] = row.split(",");
    totals.set(customer, (totals.get(customer) ?? 0) + Number(cents));
  }
  return totals;
}

Three copies of the data exist at once: the decoded string, the array of line strings, and the filtered array. Peak memory is a multiple of the file size, and it’s off in a place a unit test never looks.

There’s also a quieter variant that looks like streaming and isn’t. It reads with readline, then pushes every line into an array and processes the array afterwards. The tests below catch that one too.

Step 1: a fixture that is big and cheap

The fixture generator writes rows to disk as a stream, so building the test file doesn’t need the memory the test is about to limit. It respects backpressure by waiting for drain when the write buffer is full.

// test/make-fixture.ts
import { createWriteStream } from "node:fs";
import { once } from "node:events";

export async function makeFixture(path: string, rows: number, customers = 1000) {
  const out = createWriteStream(path);
  out.write("customer,cents\n");
  for (let i = 0; i < rows; i++) {
    if (!out.write(`c${i % customers},${(i % 97) + 1}\n`)) await once(out, "drain");
  }
  out.end();
  await once(out, "finish");
}

Twelve million rows come to 93,566,607 bytes. That builds in a few seconds and is about twice the heap the test is about to allow.

Step 2: run the import in a child process with a small heap

A running test can’t shrink its own heap. So the test starts a fresh Node process with --max-old-space-size set low and compares what comes back. Node’s CLI docs describe the flag as the maximum size of V8’s old memory section, and say V8 spends more time on garbage collection as usage approaches it. In practice, when the live data doesn’t fit, the process aborts.

The child is a few lines that load the module under test, run it and print a summary:

// test/child.ts
// Run as: node --max-old-space-size=48 test/child.ts <module> <file>
const [, , modulePath, file] = process.argv;
const { totalsByCustomer } = await import(modulePath);
const totals: Map<string, number> = await totalsByCustomer(file);
let sum = 0;
for (const v of totals.values()) sum += v;
console.log(JSON.stringify({ customers: totals.size, sum }));

Node 22.18 and later strips TypeScript types by default, so node test/child.ts runs without a build step. The docs list the catches: only erasable syntax (no enums), and import paths need the .ts extension. Set "type": "module" in package.json or Node prints a reparsing warning on every run.

The test itself builds the fixture once, runs the import in a 48 MB heap, and checks the answer as well as the survival:

// test/memory.test.ts
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { makeFixture } from "./make-fixture.ts";

const run = promisify(execFile);
const ROWS = 12_000_000; // about 94 MB of CSV
const HEAP_MB = 48; // about half the file size, so only a streaming import fits

let dir: string;
let file: string;
beforeAll(async () => {
  dir = await mkdtemp(join(tmpdir(), "import-"));
  file = join(dir, "orders.csv");
  await makeFixture(file, ROWS);
}, 60_000);
afterAll(() => rm(dir, { recursive: true, force: true }));

async function importInChild(module: string) {
  return run(process.execPath, [
    `--max-old-space-size=${HEAP_MB}`,
    resolve("test/child.ts"),
    resolve(module),
    file,
  ]);
}

describe(`totalsByCustomer within a ${HEAP_MB} MB heap`, () => {
  it("streams a large file and gets the right totals", async () => {
    const { stdout } = await importInChild("src/totals.ts");
    let expectedSum = 0;
    for (let i = 0; i < ROWS; i++) expectedSum += (i % 97) + 1;
    expect(JSON.parse(stdout)).toEqual({ customers: 1000, sum: expectedSum });
  }, 60_000);
});

Checking sum matters. A test that only asserts the process survived would pass an implementation that quietly skips rows.

Step 3: watch it fail on the agent’s first draft

Save the first draft as src/totals.ts and run npx vitest run. Output, trimmed:

 FAIL  test/memory.test.ts > totalsByCustomer within a 48 MB heap > streams a large file and gets the right totals
Error: Command failed: node --max-old-space-size=48 .../test/child.ts .../src/totals.ts .../orders.csv
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

 Test Files  1 failed (1)
      Tests  1 failed (1)
   Duration  2.68s

The test itself failed in 143 ms. The failure is ugly (a V8 abort, not a neat assertion), but the message names the cause, and the stack in the output points at string decoding, which is where readFile with "utf8" allocates the string.

Run the same test against the fake-streaming variant and it fails too, in about 660 ms, with the same heap error. The agent has read the file in chunks and then held every chunk.

Step 4: hand the agent the failing test

The prompt can be short, because the test carries the requirement. Paste something like this, adjusting the paths:

The test in test/memory.test.ts fails: src/totals.ts runs out of heap on a 94 MB
CSV with a 48 MB limit. Rewrite totalsByCustomer so it passes without raising
HEAP_MB and without changing the function's signature or its result. It must
process the file as a stream and keep only the per-customer totals in memory.
Don't edit the test. Run `npx vitest run` and show me the output.

Two clauses carry the weight. “Without raising HEAP_MB” closes the cheapest escape, which agents do take when a test is the only obstacle. “Don’t edit the test” keeps the budget honest. Check the diff for both anyway.

A typical fix looks like this:

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

export async function totalsByCustomer(path: string): Promise<Map<string, number>> {
  const lines = createInterface({
    input: createReadStream(path, { encoding: "utf8" }),
    crlfDelay: Infinity,
  });
  const totals = new Map<string, number>();
  let first = true;
  for await (const line of lines) {
    if (first) { first = false; continue; }
    if (line.length === 0) continue;
    const [customer, cents] = line.split(",");
    totals.set(customer, (totals.get(customer) ?? 0) + Number(cents));
  }
  return totals;
}

crlfDelay: Infinity makes \r\n count as one line break, which the readline docs recommend for files. The docs also warn that createInterface starts consuming the stream immediately, so any await between creating the interface and the for await can drop lines. Here there’s nothing in between. If an agent adds a setup await there, the totals test fails on sum, which is another reason to assert on the result.

Run it again:

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Duration  7.37s

Most of those seven seconds is building the fixture.

The budget has a second half: distinct keys

Streaming bounds memory by the size of the answer, not the size of the input. This function keeps one map entry per customer. With 1,000 customers that’s nothing. With a few million it’s not.

To see where that bites, generate 6,000,000 rows across 3,000,000 distinct customers and run the streaming version directly at three heap sizes:

heap 48:  FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
heap 128: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
heap 256: {"customers":3000000,"sum":293998960}

So the budget in the test has to match what production looks like. A realistic customer count belongs in the fixture, and the heap limit should sit at a number the real deployment can spare, not at 48 because 48 made the demo fail nicely. If the answer itself is too big for memory, the design has to change (aggregate in the database, or sort and merge on disk), and no amount of prompt tuning fixes that.

Make it yours

Writing the output has the mirror-image problem. An export that builds a giant array and calls JSON.stringify once will pass the input-side test and fail on output. Pipe rows through stream/promises pipeline into the destination so a slow consumer applies backpressure, and add a second budget test that reads the output file and checks its size against the heap.

For a service, test the endpoint, not the function. Start the server in the child process with the same flag and upload the large fixture, so a handler that buffers the request body fails the same way.

What goes wrong

The heap limit is not the process’s total memory. Node holds file buffers, streams and native allocations outside the V8 old space, so a function can pass at 48 MB and still use far more resident memory. If the deployment has a container limit, set the budget from that, and read resident memory in the child (process.memoryUsage().rss) as a second check.

Small limits make the test machine-sensitive in the other direction too. A budget set exactly at the edge flakes when V8 changes. Pick a limit with room: a third of the input size is a sensible start, then tighten it once the test is green and stable.

Don’t bother when the input is bounded by design, for example a config file or a request body capped at 1 MB. A budget test there is noise. It earns its keep on anything that reads a file, a query result or a response whose size somebody else controls.

First 15 minutes

Pick one function in your codebase that reads an uploaded or exported file. Write makeFixture for its format, set a heap about a third of the fixture size, and run the function in a child process with --max-old-space-size. If it passes, the budget is a guard rail for later edits. If it fails, the agent now has a failing test to fix.