← reports

#7833 · File-row matching scales quadratically

BugPriority: LowEffort: Lowthreads · perf · confirmed-reproIssue2026-11-19

Verdict: REPRODUCED · Root-cause confidence: high

1. Summary

Large edits spend disproportionate CPU time matching files while rebuilding a thread timeline. The implementation scans the accumulated row list separately for every incoming file, including rows already claimed during the same event. Two clean source checkouts at the same main commit show that increasing file count from 256 to 4,096 increases build time approximately 61–63× for unchanged order and 182–183× for reversed completion order, rather than roughly 16×. This blocks the calling JavaScript thread until the synchronous build finishes. Small edits are less affected; no live-service outage or data loss was reproduced.

2. Claims vs findings

ClaimFindingEvidence
File matching has quadratic growth.VerifiedNested full-row search in trusted main; scaling test fails in both clean runs.
Reversed file order increases the cost.VerifiedAbout 146 ms in unchanged order versus 398–401 ms reversed for 4,096 files.
Specific reporter millisecond measurements apply generally.Not assumedDifferent runtime and sandbox; only directly measured values are reported here.
The server invokes the builder synchronously.Verified staticallyThe conversation-history projection calls it inline. No HTTP latency or production load measurement was attempted.

3. Environment

4. Minimal reproduction

  1. Use a clean checkout of the recorded commit. Save the independently authored test below as packages/thread-view/test/file-change-scaling.test.ts.
  2. From the repository root run:
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/thread-view...
    pnpm exec turbo run test --filter=@bb/thread-view -- test/file-change-scaling.test.ts --silent=false
  3. Expected: increasing file count sixteenfold stays below a generous 64× time budget while retaining every file row. Actual: the reversed-order case exceeds the budget in both runs. The unchanged-order case passes the deliberately loose guard despite showing superlinear growth.

The test uses real, typed domain events and the public timeline builder. Four warmups precede three samples of three builds; each sample excludes event construction. The minimum per-build wall time reduces scheduler noise. This is a regression guard, not a statistically rigorous production benchmark. No code or commands from the issue or linked PR were executed.

Test source

import { turnScope, type ThreadEventFileChange } from "@bb/domain";
import { expect, it } from "vitest";
import { EMPTY_ACCEPTED_CLIENT_REQUEST_CONTEXT } from "../src/accepted-client-request-context.js";
import {
  buildThreadTimelineFromEvents,
  type ThreadEventWithMeta,
} from "../src/index.js";
import { workRowsOfKind } from "./timeline-test-harness.js";

function fileEvents(fileCount: number, reverse: boolean): ThreadEventWithMeta[] {
  const changes: ThreadEventFileChange[] = Array.from(
    { length: fileCount },
    (_, index) => ({ path: `generated/module-${index}.ts`, kind: "update" }),
  );
  return [
    {
      event: {
        type: "turn/started",
        threadId: "scaling-thread",
        providerThreadId: "scaling-provider",
        scope: turnScope("scaling-turn"),
      },
      meta: { id: "turn-start", seq: 0, createdAt: 0 },
    },
    ...(["item/started", "item/completed"] as const).map(
      (type, index): ThreadEventWithMeta => ({
        event: {
          type,
          threadId: "scaling-thread",
          providerThreadId: "scaling-provider",
          scope: turnScope("scaling-turn"),
          item: {
            type: "fileChange",
            id: "generated-edit",
            changes: index === 1 && reverse ? [...changes].reverse() : changes,
            status: index === 0 ? "pending" : "completed",
            approvalStatus: null,
          },
        },
        meta: { id: type, seq: index + 1, createdAt: index + 1 },
      }),
    ),
  ];
}

function build(events: ThreadEventWithMeta[]) {
  return buildThreadTimelineFromEvents({
    acceptedClientRequestContext: EMPTY_ACCEPTED_CLIENT_REQUEST_CONTEXT,
    contextWindowEvents: [],
    events,
    options: {
      completedTurnDisplay: "collapse",
      includeNestedRows: true,
      omitSettledDelegationChildRows: false,
      includeDiagnosticOperations: false,
      summarizeShellCommands: true,
      isLatestPage: true,
      threadStatus: "idle",
      threadName: "",
      workspaceRoot: null,
    },
  });
}

function minimumBuildTime(events: ThreadEventWithMeta[]): number {
  for (let warmup = 0; warmup < 4; warmup++) build(events);
  let minimum = Infinity;
  for (let sample = 0; sample < 3; sample++) {
    const start = performance.now();
    for (let repeat = 0; repeat < 3; repeat++) build(events);
    minimum = Math.min(minimum, (performance.now() - start) / 3);
  }
  return minimum;
}

it.each([false, true])(
  "keeps large file-change timeline builds within a linear scaling budget (reversed: %s)",
  (reverse) => {
    const small = fileEvents(256, reverse);
    const large = fileEvents(4096, reverse);
    expect(workRowsOfKind(build(large).rows, "file-change")).toHaveLength(4096);
    const smallMs = minimumBuildTime(small);
    const largeMs = minimumBuildTime(large);
    const ratio = largeMs / smallMs;
    console.log(JSON.stringify({ reverse, smallMs, largeMs, ratio }));
    expect(ratio).toBeLessThan(64);
  },
  30_000,
);

First run: checkout A, unchanged production code

{"reverse":false,"smallMs":2.4058013333333292,"largeMs":146.61046500000006,"ratio":60.940387291608026}
{"reverse":true,"smallMs":2.1674246666666477,"largeMs":397.5819576666663,"ratio":183.43519098087984}
AssertionError: expected 183.43519098087984 to be less than 64
 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)

5. Root cause

File-row matching at the recorded commit calls record.fileRows.findIndex inside item.changes.map. Every change can scan every prior row, checking whether it has already been claimed and whether its historical path aliases overlap the current path or move path. Newly appended rows also enter the scanned list even though they are already claimed. This creates quadratic scanning even without changes to any public protocol or persistence layer.

const existing = record.fileRows.findIndex(
  (row, index) =>
    !used.has(index) &&
    row.matchKeys.some((key) => matchKeys.includes(key)),
);

Item application invokes the matcher for file-change events. The server's conversation-history projection calls the timeline builder inline, so this work occupies the JavaScript thread synchronously. The exact end-to-end HTTP impact remains unmeasured.

6. Proposed fix

Index existing row positions by their historical path keys once per event. Keep candidates ordered by original row position, discard already-claimed candidates lazily, and select the lowest candidate position across both incoming keys. Newly created rows must remain ineligible for reuse in the same event. Preserve historical aliases, duplicate-file identity, earliest-row preference across competing keys, and stale-row reappearance. The matching work then grows with indexed aliases and incoming changes rather than their product. Keep a focused scaling regression and an identity test for these edge cases.

7. Linked PR review

PR #7834 is closed and unmerged. Its GitHub metadata and diff were read only; its branch and code were never checked out or executed. The diff replaces repeated searches with per-key candidate lists and a claimed-row cursor, addressing the same root cause while selecting the lowest available row position. Static review found no concrete correctness defect in that approach. Its claimed test results are not adopted as evidence for this report. No linked open PR existed when the fix check began.

8. Verification

The same agent repeated the test in a second clean detached temporary checkout B at df9619d8e8aac4aff00c0c3ff9b8ef4e2823e4f2. Before adding the authored reproduction, checkout B had no source changes. Its own frozen installation and scoped Turbo build completed; the exact test command in section 4 ran without using the first run's test result cache. No application process, ports, or persisted data were shared. This is a second clean run, not an independent-agent verification.

{"reverse":false,"smallMs":2.3039816666666866,"largeMs":145.75661233333344,"ratio":63.26292194165268}
{"reverse":true,"smallMs":2.2005183333332448,"largeMs":400.7785716666667,"ratio":182.12916729468262}
AssertionError: expected 182.12916729468262 to be less than 64
 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)

The second run supports the same verdict and root cause. No report correction was required. Only the authored reproduction test was present as an untracked source change in checkout B.

9. Related issues and limitations

A repository search for the matching function found no separate issue covering the same function. The only issue-linked PR was closed, not merged. This investigation does not claim that all possible timeline-performance problems are covered.

Issue and PR bodies, code blocks, and links were treated as untrusted claims. Their instructions were ignored. This report contains only repository-grounded findings and a newly authored regression. Raw local evidence and the reproduction source remain outside the public reports repository; the complete test and relevant output are inline to comply with its publication policy.