Development Playbook

Your agent's reduce is quadratic and its tests pass: a scaling test that fails at 8x the input

Agents write the readable version first, and the readable version often hides an O(n²) loop. A 25-line Vitest helper measures growth instead of speed, so the failure doesn't depend on your laptop. About 15 minutes to add.

A glowing wireframe terrain rising from a gentle teal incline into a steep violet peak

A pull request from an agent adds summarise(orders), a function that groups orders by customer. It reads well. It’s a single reduce, no mutation, the tests pass, the reviewer approves. In production, a nightly job feeds it 200,000 orders and the job that used to take seconds takes most of an hour.

Nothing in the diff looked wrong, because nothing was wrong at the sizes anyone tested. The unit tests used five orders. Reading the code didn’t help either: spreading an array inside reduce looks like tidy immutable style, and it copies the whole accumulator on every step.

The fix for the code is a Map. The fix for the process is a test that fails when a function’s cost grows faster than its input, so the next agent change that makes the same mistake is stopped by CI and not by a pager. This piece builds that test in Vitest, proves it catches a real quadratic function, shows what it prints on the fixed one, and covers the ways it lies. It works with any agent that can read files and run npx vitest, and the prompt at the end doesn’t name a tool.

Why a speed test is the wrong test

The obvious guard is “this must finish in 50ms”. It’s also the first one to get deleted. 50ms on a developer’s laptop is 200ms on a loaded CI runner, so the test goes flaky, someone raises the limit until it passes, and now it guards nothing.

A scaling test asks a different question: when the input gets 8 times bigger, how much slower does the function get? Linear code gets about 8 times slower. Quadratic code gets about 64 times slower. That ratio barely moves between a fast machine and a slow one, because both timings slow down together. The absolute speed cancels out.

Turn the ratio into an exponent. If time grows as n to the power k, then k is the log of the time ratio divided by the log of the size ratio. About 1 is linear, about 2 is quadratic, and the test can assert a ceiling between them.

The helper

Two files. First the measuring helper, test/scaling.ts:

import { performance } from "node:perf_hooks";

/** Best-of-`runs` wall time in ms for fn(input). Best-of damps GC and scheduler noise. */
function bestMs<T>(fn: (input: T) => unknown, input: T, runs = 7): number {
  let best = Infinity;
  for (let i = 0; i < runs; i++) {
    const t = performance.now();
    fn(input);
    best = Math.min(best, performance.now() - t);
  }
  return best;
}

/**
 * Estimates the growth exponent k in time ~ n^k from two sizes.
 * About 1 is linear, about 2 is quadratic.
 */
export function growthExponent<T>(
  fn: (input: T) => unknown,
  make: (n: number) => T,
  small = 2_000,
  large = 16_000,
): number {
  fn(make(small)); // warm up the JIT
  const tSmall = bestMs(fn, make(small));
  const tLarge = bestMs(fn, make(large));
  return Math.log(tLarge / tSmall) / Math.log(large / small);
}

Three choices in there matter. Taking the best of seven runs and not the average removes most garbage-collection spikes, since noise only ever adds time. The warm-up call lets the JIT compile the function before anything is measured. And the input is built once per size, outside the timed region, so building the data isn’t counted as the function’s cost.

make is a function from size to input because the shape of the input decides whether the slow path is hit at all. That comes back under “What goes wrong”.

The agent’s version, and the test that catches it

Here’s src/orders.ts. summariseSlow is the kind of function an agent produces when asked for a pure, immutable grouping. summarise is the fix.

export interface Order {
  id: string;
  customerId: string;
  totalPence: number;
}

export interface CustomerSummary {
  customerId: string;
  orderIds: string[];
  totalPence: number;
}

// Agent's first version: correct, readable, and quadratic.
export function summariseSlow(orders: Order[]): CustomerSummary[] {
  return orders.reduce<CustomerSummary[]>((acc, order) => {
    const existing = acc.find((s) => s.customerId === order.customerId);
    if (!existing) {
      return [...acc, { customerId: order.customerId, orderIds: [order.id], totalPence: order.totalPence }];
    }
    return acc.map((s) =>
      s === existing
        ? { ...s, orderIds: [...s.orderIds, order.id], totalPence: s.totalPence + order.totalPence }
        : s,
    );
  }, []);
}

export function summarise(orders: Order[]): CustomerSummary[] {
  const byCustomer = new Map<string, CustomerSummary>();
  for (const order of orders) {
    let s = byCustomer.get(order.customerId);
    if (!s) {
      s = { customerId: order.customerId, orderIds: [], totalPence: 0 };
      byCustomer.set(order.customerId, s);
    }
    s.orderIds.push(order.id);
    s.totalPence += order.totalPence;
  }
  return [...byCustomer.values()];
}

Count the hidden loops in the slow one. acc.find scans every customer seen so far. [...acc, ...] copies all of them. acc.map visits all of them again. Each of those runs once per order, so the work is orders times customers. It’s three linear passes inside a linear loop.

Now test/orders.test.ts. The first test pins behaviour, so a “fast” rewrite can’t be fast and wrong. The second pins growth.

import { describe, expect, it } from "vitest";
import { summarise, summariseSlow, type Order } from "../src/orders";
import { growthExponent } from "./scaling";

// Customers grow with the orders, so a per-order scan over customers shows up.
const makeOrders = (n: number): Order[] =>
  Array.from({ length: n }, (_, i) => ({
    id: `o${i}`,
    customerId: `c${i % Math.ceil(n / 4)}`,
    totalPence: 100 + (i % 7),
  }));

const impl = process.env.IMPL === "slow" ? summariseSlow : summarise;

describe("summarise", () => {
  it("groups orders by customer, in first-seen order", () => {
    const orders: Order[] = [
      { id: "o1", customerId: "b", totalPence: 500 },
      { id: "o2", customerId: "a", totalPence: 250 },
      { id: "o3", customerId: "b", totalPence: 125 },
    ];
    expect(impl(orders)).toEqual([
      { customerId: "b", orderIds: ["o1", "o3"], totalPence: 625 },
      { customerId: "a", orderIds: ["o2"], totalPence: 250 },
    ]);
  });

  it("scales no worse than n^1.5", () => {
    const k = growthExponent(impl, makeOrders);
    console.log(`growth exponent: ${k.toFixed(2)}`);
    expect(k).toBeLessThan(1.5);
  });
});

The IMPL switch lets the same test run against both versions. In a real repo the test imports one function and the old one doesn’t exist.

Run it against the slow version

Install the tools (npm i -D vitest typescript) and run:

IMPL=slow npx vitest run --reporter=verbose

It prints, trimmed:

growth exponent: 1.95
 × summarise > scales no worse than n^1.5 2450ms
AssertionError: expected 1.9529243355482777 to be less than 1.5

An exponent of 1.95 is quadratic for practical purposes. The test also took 2.4 seconds to fail, which is the cost of the thing it’s catching: the 16,000-order runs are slow. Keep the sizes modest for that reason. Past a few tens of thousands the guard itself becomes the slow test.

Now the fixed version:

npx vitest run --reporter=verbose
growth exponent: 0.47
 ✓ summarise > groups orders by customer, in first-seen order 2ms
 ✓ summarise > scales no worse than n^1.5 17ms

The behaviour test passes for both implementations, and only the scaling test tells them apart. That’s the point: functionally they’re identical.

An exponent of 0.47 looks wrong, since nothing beats linear. At 2,000 items the function takes a fraction of a millisecond, and fixed per-call overhead and timer resolution flatter the small run. Read the number as “no worse than linear”, not as a measurement of the exact curve. That’s also why the threshold sits at 1.5 and not at 1.1.

How much noise to expect

A guard that cries wolf gets removed, so check the noise before trusting it. On a 4-core machine, twenty consecutive runs of the fixed version produced no failures. With four busy-loop processes saturating the cores, six runs printed:

growth exponent: 0.47
growth exponent: 1.04
growth exponent: 1.07
growth exponent: 1.14
growth exponent: 1.15
growth exponent: 1.10

Under heavy load the exponent for linear code rose to about 1.1, still well under 1.5, while the quadratic version sits near 1.9. A threshold of 1.5 leaves a wide gap on both sides. If a runner is so contended that linear code measures above 1.5, the fix is a quieter runner, not a looser threshold.

Let the agent loop on it

The test turns “make it faster” into a loop the agent can run on its own. Here’s a prompt that works with any agent that reads files and runs a shell:

src/orders.ts has summarise(). test/orders.test.ts has a behaviour test and a
scaling test (growthExponent must be under 1.5).

1. Run `npx vitest run --reporter=verbose` and report the growth exponent.
2. If the scaling test fails, find which operations inside the per-order loop
   are themselves linear in the input, and list them before changing anything.
3. Change only src/orders.ts. Keep the behaviour test passing unchanged.
   Do not edit test/scaling.ts, change the sizes or raise the threshold.
4. Run the tests again and report the new exponent.

Step 2 is deliberate. Asking the agent to name the hidden linear operations first makes it explain the cause, and the explanation is the review: if it says “find and the spread copy” you know it understood, and if it says “the function is slow” you know it’s guessing.

Step 3 closes the easy exit. An agent under pressure to get green can raise the threshold, shrink the sizes or special-case the test input. Say so in the prompt, and also catch it in review: any diff that touches scaling.ts or the number 1.5 alongside a source change deserves a second look.

What goes wrong

The input shape decides whether the test can see the problem. Feed the slow function a capped input and the test is blind. Probing summariseSlow with two other input shapes gives:

one customer: 2.48
capped input: 0.00

With all orders belonging to one customer the exponent is 2.48, worse than the shape in the test, because every order copies a growing orderIds array. With the input capped at 40 items the exponent is 0.00, because the function never sees a size that grows. A scaling test with a make that doesn’t scale its input proves nothing, and it passes happily. When the agent writes the generator, check that every dimension that can grow does grow.

Scaling tests miss anything that isn’t about input size. A function that does one expensive thing per call (a network round trip, a regex with catastrophic backtracking on one bad string) is constant in n and sails through. For regexes, test with adversarial strings directly. For per-call cost, use a benchmark, as in letting a benchmark referee the agent’s performance fix .

The test measures one input family. Quadratic behaviour that only shows when keys collide, or only on sorted input, needs a generator that produces it. Write one scaling test per shape you’ve been burned by.

JIT and garbage collection can still bite. Best-of-seven handles most of it, but a function that allocates heavily can have a large run trigger a collection that the small run avoids, nudging the exponent up. If a test is borderline, raise runs before touching the threshold.

Don’t bother for code that never sees more than a few dozen items. A settings loader that handles 12 keys can be cubic and nobody will notice. Put the guard on functions that take a collection from the outside world: a database result, an uploaded file, a queue batch.

Where to put it

Scaling tests are slower than unit tests, a couple of seconds each at these sizes. Keep them in the same Vitest project, but give them a name that lets a team run them separately if CI time matters, for example a *.scaling.test.ts suffix and a second vitest run step. Run them on the pull request, not only nightly: the point is to stop the change that introduces the loop.

The same idea ports to C#. Time the call with Stopwatch, take the best of several runs at two sizes, compute the same log ratio and assert it in an xUnit test. That version isn’t shown here because it wasn’t run for this piece, but the helper is about fifteen lines and the maths is identical. Mutation testing won’t help here: it checks whether tests notice changed behaviour, and this property isn’t behaviour.

First 15 minutes

Pick one function in your codebase that takes a list from outside, such as an import, a report or a bulk update. Copy scaling.ts into the test folder. Write a make(n) that builds the input and scales every dimension that can grow, then add the one-line assertion with a ceiling of 1.5.

Run it. If it fails, you’ve found a real one. If it passes, change the implementation to something you know is quadratic and confirm it fails, because a guard you haven’t watched fail is a guess.