#6540 · Quadratic file-edit history reconstruction blocks the event loop
GitHub issue · October 29, 2026 · trusted main 3bacfac9ed69d42392076e5b3da2815bec822cd8
Verdict: REPRODUCED · Root-cause confidence: high for the synchronous projection hotspot. Live browser/API latency and the reporter's exact measurements were not tested.
1. TL;DR
A server rebuilding a long edit-heavy conversation runs the shared projection synchronously, so timers and other requests cannot progress until it returns. A newly written synthetic history of 6,000 file edits and 18,001 events blocked a zero-delay timer for approximately 989 ms. A second clean trusted checkout repeated the block at approximately 983 ms. Every file-change start/completion needlessly searched and copied the growing message array, even when the call was new or the existing rows were already updated in place. A bounded two-file fix skips those two unnecessary rebuilds; the same test then took approximately 135 ms and the existing thread-view suite passed.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Long edit histories can synchronously stall the server. | Verified mechanism | The real shared projection delayed a timer by 989 ms and 983 ms on trusted main. No live HTTP server or browser was used. |
| File-edit replacement copies the whole history. | Verified | The original replacement helper unconditionally uses findIndex and filter for each lifecycle update with file changes. |
| Every output update scans all file edits. | Qualified | The flush helper scans all historical edits, but its callers flush at turn completion, interruption, or finalization, not on every individual stdout delta. The reproduced quadratic cost comes from file-change lifecycle replacement. |
| The scheduler's pause equals build duration. | Verified source, not quantified | The pause is min(1,000 ms, build duration); an approximately 50% duty cycle applies only while builds stay below that cap and pushes remain pending. |
| A byte-budget query prepares a statement every rebuild. | Verified source, causal share unverified | The query helper prepares on each invocation; this report does not benchmark its database cost. |
| Reported macOS timings, percentages, and multi-second speedup. | Unverified | No reporter logs or branch code were executed. These are different Linux/Node 22 fixtures and cannot validate those exact numbers. |
3. Environment
- Public repository get-bb/bb, official origin/main at
3bacfac9ed69d42392076e5b3da2815bec822cd8. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1.
- Two separate temporary source checkouts; no production runtime data, provider processes, ports, or application data directory.
- Frozen installs completed. Initial full build needed the documented SDK build:types preparation; afterward all 72 build tasks succeeded in both checkouts.
4. Minimal reproduction
- Clone the official public target and select the recorded commit; install and build dependencies.
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach 3bacfac9ed69d42392076e5b3da2815bec822cd8 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk pnpm exec turbo run build
Save the test below as packages/thread-view/test/timeline-file-edit-responsiveness.test.ts, then run:
pnpm exec turbo run test --filter=@bb/thread-view -- test/timeline-file-edit-responsiveness.test.ts --silent=false
Expected: all 6,000 projected edits retain completed status and output, with synchronous projection below a deliberately loose 500 ms guard. Actual on unchanged production code: data assertions pass but the latency assertion fails.
First trusted checkout:
{"events":18001,"edits":6000,"projectionMs":988.7867210000001,"timerDelayMs":988.9052310000001}
AssertionError: expected 988.7867210000001 to be less than 500
Second clean checkout:
{"events":18001,"edits":6000,"projectionMs":983.201864,"timerDelayMs":983.325254}
AssertionError: expected 983.201864 to be less than 500
This tests the real projection, not a simulated implementation. The timer is scheduled immediately before synchronous projection and measured before message assertions. The fixture has one active turn; it is a stress case, not a claim that 1,000 total messages always block for the same duration. Elapsed-time assertions vary by machine; the budget is not a frame-latency guarantee.
Complete regression test
import { turnScope } from "@bb/domain";
import { expect, it } from "vitest";
import {
buildEventProjection,
type ThreadEventWithMeta,
} from "../src/build-event-projection.js";
import { getProjectionEntryMessages } from "../src/event-projection-flatten.js";
function editHistory(count: number): ThreadEventWithMeta[] {
const history: ThreadEventWithMeta[] = [];
function append(event: ThreadEventWithMeta["event"]): void {
const sequence = history.length + 1;
history.push({
event,
meta: { id: `event-${sequence}`, seq: sequence, createdAt: sequence },
});
}
const common = {
threadId: "responsiveness-thread",
providerThreadId: "responsiveness-provider",
scope: turnScope("responsiveness-turn"),
};
append({ ...common, type: "turn/started" });
for (let index = 0; index < count; index++) {
const item = {
type: "fileChange" as const,
id: `edit-${index}`,
changes: [{ path: `src/file-${index}.ts`, kind: "update" as const }],
approvalStatus: null,
};
append({
...common,
type: "item/started",
item: { ...item, status: "pending" },
});
append({
...common,
type: "item/fileChange/outputDelta",
itemId: item.id,
delta: `saved-${index}`,
});
append({
...common,
type: "item/completed",
item: { ...item, status: "completed" },
});
}
return history;
}
it("projects a long streamed edit history without a half-second synchronous stall", async () => {
const options = {
threadName: "Responsiveness fixture",
threadStatus: "active" as const,
turnMessageDetail: "full" as const,
};
buildEventProjection(editHistory(100), options);
const history = editHistory(6000);
const startedAt = performance.now();
const pendingTimer = new Promise<number>((resolve) => {
setTimeout(() => resolve(performance.now() - startedAt), 0);
});
const projection = buildEventProjection(history, options);
const projectionMs = performance.now() - startedAt;
const timerDelayMs = await pendingTimer;
const edits = projection.entries
.flatMap(getProjectionEntryMessages)
.filter((message) => message.kind === "file-edit");
console.log(
JSON.stringify({
events: history.length,
edits: edits.length,
projectionMs,
timerDelayMs,
}),
);
expect(edits).toHaveLength(6000);
expect(edits[0]?.stdout).toBe("saved-0");
expect(edits[5999]?.stdout).toBe("saved-5999");
expect(edits.every((message) => message.status === "completed")).toBe(true);
expect(projectionMs).toBeLessThan(500);
}, 30_000);
The complete test and exact output are inline to follow the reports repository's no-published-test-artifacts policy. Raw evidence and an artifact copy are retained locally, not committed to this public site.
5. Root cause
The file-change upsert mutates reusable row objects, then calls replacement even when their identities and order did not change. For new calls it similarly filters the entire existing history before appending. With N independent edits the growing-array scans cost O(N²), allocating a new history array on each start/completion. The helper runs on the same JavaScript event loop as request handling.
function replaceFileEditMessagesForCall(
state: OperationProjectionState,
callId: string,
nextRows: readonly EventProjectionFileEditMessage[],
): void {
const insertionIndex = state.messages.findIndex(
(message) => message.kind === "file-edit" && message.callId === callId,
);
const messagesWithoutCallRows = state.messages.filter(
(message) => message.kind !== "file-edit" || message.callId !== callId,
);
if (insertionIndex === -1) {
messagesWithoutCallRows.push(...nextRows);
} else {
messagesWithoutCallRows.splice(insertionIndex, 0, ...nextRows);
}
state.messages = messagesWithoutCallRows;
}
- Lifecycle upsert updates rows and invokes replacement.
- The server invokes the shared projection synchronously in its timeline build.
- Historical flush traversal and its callers: distinct remaining costs, not removed by the narrow fix.
- Push scheduler pause and byte-budget statement preparation: source-confirmed contributors requiring separate measurement.
6. Proposed fix and measured validation
Use the existing call-to-rows map: append directly for a new call, and return when the same row objects remain in the same order. Their fields have already been updated. Preserve the original replacement fallback for structural changes, removals, and reordering; introduce no cached positions, additional state, or wire changes.
After the 11-line production change:
{"events":18001,"edits":6000,"projectionMs":135.12772099999995,"timerDelayMs":135.24380099999996}
Test Files 1 passed (1)
Tests 1 passed (1)
Full package verification:
Test Files 32 passed (32)
Tests 506 passed (506)
Tasks 4 successful, 4 total (tests, typecheck, upstream dependencies)
The before/after result supports this hotspot fix, not a promise that all scheduler, database, or browser latency is eliminated. Existing tests cover reused call IDs across turns, row identity, moves, multi-file updates, grouping, and interruption. The focused guard was added before the production change and failed for the intended latency reason. Final change size: 93 added text lines, zero deletions, two files; 11 production lines and an 82-line regression. No dependency, migration, generated file, persisted data, protocol, or public API change. Formatting and git diff --check passed. This package has no lint task; Turbo correctly reported zero lint tasks.
7. Linked PR review
#6544 — closed, unmerged
Metadata and diff were read only as untrusted evidence after the local reproduction and fix were written. The diff changes scheduler pacing, caches a prepared database statement, tracks pending stdout scopes and file-row positions, and adds tests across eight files (1,230 changed lines). It targets additional costs but exceeds this run's simple-fix limits. No branch checkout or tests from it were run, and no correctness approval is implied. The narrower local fix was designed from trusted main and does not depend on that diff. No linked open PR existed when the duplicate check ran.
8. Related issues
#1972 is closed and concerns conversation-outline history reconstruction. Its symptom is similar, but this reproduction executes file-edit projection rather than the outline.
9. Verification
The same agent created a second clean detached checkout at the exact trusted base, performed a separate frozen install and full build, copied only the newly authored regression test, and reran the command above. Production source in that checkout remained unchanged. The repeated 983 ms projection and delayed timer support the final root-cause conclusion. This is a second run by the same agent, not independent verification. Both baseline runs failed only the intended 500 ms budget after validating completed outputs. No report correction was needed after the second run.
10. Appendix and limits
Relevant verification commands:
pnpm exec turbo run test --filter=@bb/thread-view -- test/timeline-file-edit-responsiveness.test.ts --silent=false pnpm exec turbo run test typecheck --filter=@bb/thread-view pnpm exec oxfmt packages/thread-view/src/operation-projection.ts packages/thread-view/test/timeline-file-edit-responsiveness.test.ts pnpm exec turbo run lint --filter=@bb/thread-view git diff --check git diff --numstat origin/main
Issue data was treated as untrusted. No supplied command, external branch, patch, script, or test was executed. All running production code came from official origin/main or the local 11-line change. No live app, browser click, HTTP latency, macOS behavior, reporter log statistics, or provider-specific behavior was validated. The larger fixture demonstrates a provider-independent blocking mechanism and a regression boundary; future measurement should include real timeline-window selection and concurrent HTTP requests.
> AGENT GENERATED