Skip to content

Commit c1b8092

Browse files
committed
perf(command-code): measure fragmented NDJSON incrementally
1 parent 883bf0f commit c1b8092

3 files changed

Lines changed: 68 additions & 7 deletions

File tree

‎src/adapters/command-code.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -437,17 +437,20 @@ async function*ndjson(response: Response, budget: TranslatorBudget): AsyncGenera
437437
try {
438438
for (;;) {
439439
const { value, done } = await reader.read();
440-
const next = buffer + decoder.decode(value, { stream: !done });
441-
const nextBytes = encoder.encode(next).byteLength;
440+
const decoded = decoder.decode(value, { stream: !done });
441+
// TextDecoder emits complete code points, so fragment UTF-8 sizes are additive.
442+
const nextBytes = bufferBytes + encoder.encode(decoded).byteLength;
442443
resizeBuffer(nextBytes);
443-
buffer = next;
444-
let newline = buffer.indexOf("\n");
444+
buffer += decoded;
445+
// The retained suffix has no newline; only new text can complete a record.
446+
const hasNewline = decoded.includes("\n");
447+
let newline = hasNewline ? buffer.indexOf("\n") : -1;
445448
while (newline >= 0) {
446449
const line = buffer.slice(0, newline).trim(); buffer = buffer.slice(newline + 1);
447450
if (line) yield* decodeEventLine(line);
448451
newline = buffer.indexOf("\n");
449452
}
450-
resizeBuffer(encoder.encode(buffer).byteLength);
453+
if (hasNewline) resizeBuffer(encoder.encode(buffer).byteLength);
451454
if (done) break;
452455
}
453456
const final = buffer.trim();

‎structure/transports/byte-accounting.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,10 @@ removed bytes. Recounting an unchanged residual does not reserve it twice. Faile
155155
the previous charge owned until `finally` releases it, without releasing other owners' bytes.
156156
The turn limit and transport-read accounting remain in force. `tests/providers/command-code-buffer-budget.test.ts`
157157
covers exact-limit Unicode records across whole/one-byte reads and newline/EOF termination,
158-
one-byte overflow, another retained owner, consumer return and upstream cancellation.
158+
one-byte overflow, another retained owner, consumer return and upstream cancellation. Byte sizing
159+
measures only new decoded text, including EOF replacement bytes; newline searches run only when
160+
new text contains a newline, and only a drained residual is remeasured. The same tests bound total
161+
measurement and search input by wire size for both newline and EOF termination.
159162

160163
Devin Connect-RPC in `src/adapters/devin/cloud-direct/chat.ts` compacts surviving chunks in place
161164
and truncates the queue, or clears it when no bytes remain. No deleted-chunk

‎tests/providers/command-code-buffer-budget.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { expect, test } from "bun:test";
1+
import { expect, spyOn, test } from "bun:test";
22
import { createCommandCodeAdapter } from "../../src/adapters/command-code";
33
import { createTestTranslatorBudget } from "../helpers/translator-budget";
44
import type { AdapterEvent } from "../../src/types";
@@ -8,6 +8,41 @@ const content = "é한😀".repeat(32);
88
const line = JSON.stringify({ type: "text-delta", text: content });
99
const encoder = new TextEncoder();
1010

11+
for (const ending of ["\n", ""] as const) {
12+
test(`Command Code bounds fragmented NDJSON measurement and scan work with ${JSON.stringify(ending)} termination`, async () => {
13+
const text = "a".repeat(256 * 256);
14+
const bytes = encoder.encode(JSON.stringify({ type: "text-delta", text }) + ending);
15+
const budget = createTestTranslatorBudget({ maxTurnBytes: bytes.length });
16+
const source = input(bytes, 256);
17+
const encode = TextEncoder.prototype.encode;
18+
const indexOf = String.prototype.indexOf;
19+
let measuredChars = 0;
20+
let scannedChars = 0;
21+
const measuring = spyOn(TextEncoder.prototype, "encode").mockImplementation(function (value = "") {
22+
measuredChars += value.length;
23+
return Reflect.apply(encode, this, [value]);
24+
});
25+
const scanning = spyOn(String.prototype, "indexOf").mockImplementation(function (search, position = 0) {
26+
if (search === "\n") scannedChars += Math.max(0, this.length - position);
27+
return Reflect.apply(indexOf, this, [search, position]);
28+
});
29+
const events: AdapterEvent[] = [];
30+
try {
31+
for await (const event of adapter().parseStream(source.response, budget)) events.push(event);
32+
} finally {
33+
measuring.mockRestore();
34+
scanning.mockRestore();
35+
}
36+
expect(events).toEqual([
37+
{ type: "text_delta", text },
38+
{ type: "done", usage: undefined, stopReason: undefined },
39+
]);
40+
expect(budget.snapshot()).toMatchObject({ currentBytes: 0, highWaterBytes: bytes.length, overflows: 0 });
41+
expect(measuredChars).toBeLessThanOrEqual(4 * bytes.length);
42+
expect(scannedChars).toBeLessThanOrEqual(2 * bytes.length);
43+
});
44+
}
45+
1146
function input(bytes: Uint8Array, chunkSize: number, beforeRead?: (offset: number) => void) {
1247
let offset = 0;
1348
let cancelled = false;
@@ -24,6 +59,26 @@ function input(bytes: Uint8Array, chunkSize: number, beforeRead?: (offset: numbe
2459
return { response: new Response(body), cancelled: () => cancelled };
2560
}
2661

62+
for (const maxTurnBytes of [2, 3]) {
63+
test(`Command Code accounts for EOF decoder replacement bytes with a ${maxTurnBytes}-byte budget`, async () => {
64+
const budget = createTestTranslatorBudget({ maxTurnBytes });
65+
const source = input(Uint8Array.of(0xe2), 1); // Incomplete UTF-8 becomes a 3-byte U+FFFD at EOF.
66+
const events: AdapterEvent[] = [];
67+
const consume = async () => {
68+
for await (const event of adapter().parseStream(source.response, budget)) events.push(event);
69+
};
70+
if (maxTurnBytes === 2) {
71+
await expect(consume()).rejects.toMatchObject({ code: "translation_buffer_limit", kind: "live_transient" });
72+
expect(events).toEqual([]);
73+
} else {
74+
await consume();
75+
// Malformed NDJSON retains the existing skip-and-complete behavior.
76+
expect(events).toEqual([{ type: "done", usage: undefined, stopReason: undefined }]);
77+
}
78+
expect(budget.snapshot()).toMatchObject({ currentBytes: 0, overflows: maxTurnBytes === 2 ? 1 : 0 });
79+
});
80+
}
81+
2782
for (const ending of ["\n", ""] as const) {
2883
for (const fragmented of [false, true]) {
2984
test(`Command Code admits an exact-limit ${fragmented ? "fragmented" : "whole"} record with ${JSON.stringify(ending)} termination`, async () => {

0 commit comments

Comments
 (0)