perf(kuna): avoid per-line Buffer.concat allocations in KunaProjectFiles.scanLines (#13270)

* perf(kuna): avoid per-line Buffer.concat allocations in KunaProjectFiles.scanLines

* test(kuna): cover single-chunk UTF-8 and length refusals in scanLines
This commit is contained in:
morluto authored and GitHub committed 2026-11-21 22:31:44 -05:00
1 parent 7269165323
commit f7355b1b61
2 files changed
+161 -18

No files matched your search

+55 -17
View File
@@ -83,10 +83,11 @@ const scanLines = async (
const lines: KeptLine[] = [];
let offset = 0;
let lineStart = 0;
// The current line's bytes while it is undecided or kept; undefined once skipped.
let line: Buffer[] | undefined = [];
// Cross-chunk fragments of the active line while it is undecided or kept.
const line: Buffer[] = [];
let lineBytes = 0;
let decided = false;
let skipped = false;
const recordLine = (bytes: Buffer): string | undefined => {
const decoded = decodeKunaProjectText(bytes, lineStart);
if (!decoded.ok)
@@ -99,35 +100,72 @@ const scanLines = async (
while (position < chunk.length) {
const newline = chunk.indexOf(0x0a, position);
const end = newline === -1 ? chunk.length : newline;
if (line !== undefined) {
if (!skipped && line.length === 0) {
const segment = chunk.subarray(position, end);
if (newline !== -1) {
if (keep(segment.subarray(0, headBytes))) {
if (segment.length > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
const failure = recordLine(segment);
if (failure !== undefined) return err(failure);
}
position = newline + 1;
lineStart = offset + position;
continue;
}
if (segment.length >= headBytes) {
decided = true;
if (!keep(segment.subarray(0, headBytes))) {
skipped = true;
break;
}
}
if (segment.length > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
line.push(segment);
lineBytes += segment.length;
lineBytes = segment.length;
break;
}
if (!skipped) {
const segment = chunk.subarray(position, end);
if (segment.length > 0) {
line.push(segment);
lineBytes += segment.length;
}
let assembled: Buffer | undefined;
if (!decided && (lineBytes >= headBytes || newline !== -1)) {
decided = true;
if (!keep(Buffer.concat(line).subarray(0, headBytes)))
line = undefined;
assembled = line.length === 1 ? line[0]! : Buffer.concat(line);
if (!keep(assembled.subarray(0, headBytes))) {
skipped = true;
line.length = 0;
}
}
if (!skipped) {
if (lineBytes > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
if (newline !== -1) {
const failure = recordLine(
assembled ?? (line.length === 1 ? line[0]! : Buffer.concat(line)),
);
if (failure !== undefined) return err(failure);
}
}
if (line !== undefined && lineBytes > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
}
if (newline === -1) break;
if (line !== undefined) {
const failure = recordLine(Buffer.concat(line));
if (failure !== undefined) return err(failure);
}
position = newline + 1;
lineStart = offset + position;
line = [];
line.length = 0;
lineBytes = 0;
decided = false;
skipped = false;
}
offset += chunk.length;
}
if (line !== undefined && lineBytes > 0) {
const head = Buffer.concat(line);
if (decided || keep(head.subarray(0, headBytes))) {
const failure = recordLine(head);
if (!skipped && lineBytes > 0) {
const tail = line.length === 1 ? line[0]! : Buffer.concat(line);
if (decided || keep(tail.subarray(0, headBytes))) {
const failure = recordLine(tail);
if (failure !== undefined) return err(failure);
}
}
@@ -1,4 +1,4 @@
import { expect, it } from "vitest";
import { describe, expect, it } from "vitest";
import {
parseKunaExportSummary,
@@ -246,3 +246,108 @@ it.each([
]);
},
);
describe("Kuna streaming line-scanner chunk boundary parity", () => {
it("handles empty lines, overlong skipped lines, cross-chunk kept lines, and unterminated EOF lines across chunk sizes", async () => {
const padding = "x".repeat(70_000);
const body = ` ${padding}`;
const header = "entry: ; 0x1000";
// An overlong indented body line must be skipped without triggering MAX_KEPT_LINE_BYTES.
const asm = [
"",
header,
body,
"",
"; --- data ---",
"",
"g_val: ; 0x2000 = dat_2000",
].join("\n");
const expectedLen = Buffer.byteLength(`${header}\n${body}\n\n`);
for (const chunkSize of [1, 3, 17, 4096, 131_072]) {
const scanned = await scanKunaAssembly(chunked(asm, chunkSize));
if (!scanned.ok) throw new Error(scanned.error);
expect([...scanned.value.code.values()]).toEqual([
{
name: "entry",
address: "0x1000",
offset: 1,
length: expectedLen,
},
]);
expect([...scanned.value.data]).toEqual([["0x2000", "g_val"]]);
}
// Cross-chunk overlong kept header still refuses with exact starting byte offset.
const overlongHeader = `${header}\n// kept_${padding}\n`;
expect(await scanKunaAssembly(chunked(overlongHeader, 16))).toEqual({
ok: false,
error: `the line at byte ${String(Buffer.byteLength(`${header}\n`))} is too long`,
});
});
});
describe("Kuna streaming line-scanner single-chunk fast-path refusals", () => {
const padding = "x".repeat(70_000);
it.each([
{
format: ".c",
scan: (chunks: AsyncIterable<Buffer>) =>
scanKunaProjectSource(chunks, { decompiled: 2, failed: 0 }),
skippedPrefix: Buffer.from('#include "sample.h"\n'),
validLine: Buffer.from("// Function: ok @ 0x1000\n"),
malformedLine: Buffer.concat([
Buffer.from("// Function: "),
Buffer.from([0xff]),
Buffer.from(" @ 0x1010\n"),
]),
overlongLine: Buffer.from(`// Function: ${padding} @ 0x1010\n`),
},
{
format: ".asm",
scan: (chunks: AsyncIterable<Buffer>) => scanKunaAssembly(chunks),
skippedPrefix: Buffer.from(" 00001000: c3 RET\n"),
validLine: Buffer.from("entry: ; 0x1000\n"),
malformedLine: Buffer.concat([
Buffer.from("bad_"),
Buffer.from([0xff]),
Buffer.from(": ; 0x1010\n"),
]),
overlongLine: Buffer.from(`fn_${padding}: ; 0x1010\n`),
},
])(
"refuses single-chunk malformed UTF-8 and overlong kept $format lines with exact byte offsets",
async ({ scan, skippedPrefix, validLine, malformedLine, overlongLine }) => {
const cases = [
{
failingLine: malformedLine,
errorAt: (byteOffset: number) =>
`the structural line at byte ${String(byteOffset)} is not valid UTF-8`,
},
{
failingLine: overlongLine,
errorAt: (byteOffset: number) =>
`the line at byte ${String(byteOffset)} is too long`,
},
] as const;
for (const { failingLine, errorAt } of cases) {
const singleChunk = Buffer.concat([validLine, failingLine]);
const singleExpected = { ok: false, error: errorAt(validLine.length) };
expect(await scan(chunked(singleChunk, singleChunk.length))).toEqual(
singleExpected,
);
expect(await scan(chunked(singleChunk, 7))).toEqual(singleExpected);
expect(
await scan(
(async function* () {
yield skippedPrefix;
yield singleChunk;
})(),
),
).toEqual({
ok: false,
error: errorAt(skippedPrefix.length + validLine.length),
});
}
},
);
});