← reports

#7692 · Repeated pending-buffer byte accounting

Bug Medium priority Low effort host · perf · confirmed-repro

November 17, 2026 · Issue #7692 · trusted base 1320c88e8abdd3f145bc9a5c305eace269fb2f28

Verdict: REPRODUCED · Root-cause confidence: high.

1. TL;DR

A long provider message arriving in many chunks makes the line reader repeatedly measure all bytes accumulated so far. A 24 MiB JSON line delivered in 32 KiB chunks passes more than 9.67 billion characters to byte-length accounting, 384.5 times the payload. Two clean checkouts reproduce the same deterministic work amplification and a failing linear-work assertion. The synchronous feed takes several seconds on this host, although exact timings depend on the environment. No duplicate fix was attempted because open PR #7699 already closes this issue.

2. Claims vs findings

ClaimStatusEvidence
Accumulated text is remeasured after each incomplete chunk.VerifiedTrusted source lines 43–46 and byte-length input instrumentation.
Fixed-size chunk delivery creates quadratic accounting work.Verified32.5×, 128.5×, and 384.5× work amplification for 2, 8, and 24 MiB lines; identical in both checkouts.
The affected reader handles provider process stdout.VerifiedTrusted runtime call at line 435.
The default ceiling is 64 MiB.VerifiedReader constant at line 3; all reproduction inputs stay below it.
The issue's particular machine timings and all-thread user impact.Not measured hereThis investigation uses Node 22 and isolated streams, not a live daemon or provider session. The event-handler work is synchronous; user-visible fleet impact is not quantified.
Rope flattening is the precise engine-level cause.Not independently profiledThe repeated full-prefix byte-length inputs alone establish quadratic accounting work; no V8 profiling claim is required.

3. Environment

4. Minimal reproduction

The test is authored from trusted repository evidence. It uses a real Node PassThrough stream and imports the production TypeScript reader. The first pass measures elapsed time without instrumentation. A separate pass wraps and restores Buffer.byteLength to total ASCII string lengths supplied to byte accounting. It also asserts one complete, exact line and zero overflows. The final assertion deliberately fails on the trusted base.

  1. Save the complete inline reproduction source below as /tmp/bb-7692-line-scaling.mjs.
  2. Prepare a clean copy of the recorded trusted source and install the existing dependencies:
git clone https://github.com/get-bb/bb.git bb-7692-first
cd bb-7692-first
git checkout --detach 1320c88e8abdd3f145bc9a5c305eace269fb2f28
pnpm install --frozen-lockfile --prefer-offline
pnpm exec tsx /tmp/bb-7692-line-scaling.mjs "$PWD"

Expected: byte-accounting input grows linearly, within twice the payload, ending in PASS and exit 0. Actual: the recorded output below ends in FAIL, followed by AssertionError: Byte-length accounting repeatedly scans prior chunks instead of linear total input, exit 1.

Node v22.19.0; chunks=32768 bytes; ASCII JSON lines
2 MiB: 87.27 ms; byteLength input=68157440; scan/payload=32.5x
8 MiB: 832.46 ms; byteLength input=1077936128; scan/payload=128.5x
24 MiB: 4514.56 ms; byteLength input=9676259328; scan/payload=384.5x
Linear-work budget (at most twice the payload): FAIL

The complete source and both output records are inline. Raw evidence remains outside the public repository, following its publication policy.

Complete reproduction source
import assert from "node:assert/strict";
import { performance } from "node:perf_hooks";
import { resolve } from "node:path";
import { PassThrough } from "node:stream";
import { pathToFileURL } from "node:url";

const repository = process.argv[2];
assert.ok(repository, "Pass the trusted repository root");
const { readBoundedLines } = await import(
  pathToFileURL(resolve(repository, "packages/provider-bridge-protocol/src/bridge-kit/bounded-line-reader.ts")).href
);
const chunkBytes = 32 * 1024;
const sizes = [2, 8, 24];
const observations = [];

function exercise(line, instrument) {
  const input = new PassThrough();
  let emitted = 0;
  let observedLine;
  let overflows = 0;
  let measuredCharacters = 0;
  readBoundedLines({
    input,
    onLine(value) {
      emitted += 1;
      observedLine = value;
    },
    onOverflow() {
      overflows += 1;
    },
  });
  const original = Buffer.byteLength;
  if (instrument) {
    Buffer.byteLength = function (value, encoding) {
      if (typeof value === "string") measuredCharacters += value.length;
      return original(value, encoding);
    };
  }
  const started = performance.now();
  try {
    for (let offset = 0; offset < line.length; offset += chunkBytes) {
      input.write(line.subarray(offset, offset + chunkBytes));
    }
    input.write(Buffer.from("\n"));
  } finally {
    Buffer.byteLength = original;
    input.end();
  }
  const milliseconds = performance.now() - started;
  assert.equal(emitted, 1);
  assert.equal(overflows, 0);
  assert.equal(observedLine, line.toString("utf8"));
  return { milliseconds, measuredCharacters };
}

exercise(Buffer.from('{"payload":"warmup"}'), false);
console.log(`Node ${process.version}; chunks=${chunkBytes} bytes; ASCII JSON lines`);
for (const mebibytes of sizes) {
  const bytes = mebibytes * 1024 * 1024;
  const line = Buffer.from('{"payload":"' + "a".repeat(bytes - 14) + '"}');
  assert.equal(line.length, bytes);
  const timing = exercise(line, false);
  const measured = exercise(line, true);
  const scanRatio = measured.measuredCharacters / bytes;
  observations.push({ bytes, measuredCharacters: measured.measuredCharacters });
  console.log(`${mebibytes} MiB: ${timing.milliseconds.toFixed(2)} ms; byteLength input=${measured.measuredCharacters}; scan/payload=${scanRatio.toFixed(1)}x`);
}
const linear = observations.every(({ bytes, measuredCharacters }) => measuredCharacters <= 2 * bytes);
console.log(`Linear-work budget (at most twice the payload): ${linear ? "PASS" : "FAIL"}`);
assert.ok(linear, "Byte-length accounting repeatedly scans prior chunks instead of linear total input");

5. Root cause

Reader, lines 13–49 appends each tail to pending and immediately measures the entire pending string:

pending += tail;
if (Buffer.byteLength(pending) > maxLineBytes) {
  discarding = true;
  discardedBytes = Buffer.byteLength(pending);
  pending = "";
}

For k chunks of c bytes, the arguments total c × k × (k + 1) / 2 characters before the newline. Payload is c × k, so work amplification is (k + 1) / 2. The measurements match this formula exactly. This work happens synchronously in a data listener, so the reader's event loop cannot service other callbacks during that work.

The runtime attaches this reader to child stdout. The default cap allows the tested payload sizes.

6. Proposed fix

Account for each newly decoded tail once and maintain a pending-byte total, resetting it at line boundaries, after entering overflow discard mode, and at close. Preserve the decoder, line output, overflow reporting, and existing limits. Validate multibyte chunks, newline resets, discard recovery, and a deterministic linear-work budget. This is a contained reader change, but no candidate patch was made because a linked open PR already exists.

7. Linked PR review

PR #7699 is open against main and GitHub's closing-issue metadata names #7692. Its metadata and diff were read as untrusted data; its branch and tests were never checked out or run.

Static verdict: its incremental-accounting approach targets the verified root cause. Test limitation: the added correctness case does not establish a linear-work bound; include performance-specific regression evidence before calling that coverage complete. No claim is made that this PR's test suite passes or that the patch has been dynamically validated here. No duplicate pull request is safe or useful while it remains open.

8. Verification — second clean run

The same agent created a second new detached checkout at the full base SHA, performed a separate frozen install, and invoked the identical authored script against that checkout's production module. No files from PR #7699 were used. No ports or data directories were needed.

pnpm exec tsx "$WORK/reports/issues/7692/repro/line-scaling.mjs" "$PWD"

Node v22.19.0; chunks=32768 bytes; ASCII JSON lines
2 MiB: 87.97 ms; byteLength input=68157440; scan/payload=32.5x
8 MiB: 666.17 ms; byteLength input=1077936128; scan/payload=128.5x
24 MiB: 3721.82 ms; byteLength input=9676259328; scan/payload=384.5x
Linear-work budget (at most twice the payload): FAIL

Exit 1, the same intended assertion failure. Accounting totals match the first run exactly. Only elapsed times vary. No report correction was required; this is a repeat by the same agent, not an independent verification.

9. Related issues

A repository-wide issue search for the reader symbol returned only #7692. Existing performance issue #7595 was inspected only for classification precedent, not treated as a related root cause.

10. Appendix — validation and limits

AGENT GENERATED