perf(process): fix expectedSize EOF probing in readBoundedFileBytes and eliminate 2x buffer copies (#13494)

* perf(process): fix expectedSize EOF probing in readBoundedFileBytes and eliminate 2x buffer copies (#13492)

* fix(setup): bound skill snapshots to the admitted file size
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 18:23:12 +00:00
1 parent 03a9b549e1
commit 9a85100b59
10 files changed
+118 -25

No files matched your search

+1
View File
@@ -909,6 +909,7 @@ export class LinuxHopperPublisher {
);
const bytes = await readBoundedFileBytes(handle, stats.size, {
signal,
expectedSize: stats.size,
});
if (bytes === undefined)
throw new HopperReleaseError(
+4 -7
View File
@@ -61,13 +61,10 @@ const readSkillFileSnapshot = async (
withRegularFile(
path,
async (handle, stats) => {
const bytes = await readBoundedFileBytes(
handle,
Math.min(stats.size, maxBytes),
{
expectedSize: stats.size,
},
);
if (stats.size > maxBytes) throw new RegularFileChangedError(path);
const bytes = await readBoundedFileBytes(handle, stats.size, {
expectedSize: stats.size,
});
if (bytes === undefined || bytes.length !== stats.size)
throw new RegularFileChangedError(path);
return { bytes, mode: stats.mode & 0o7777, state: stats };
+1
View File
@@ -1018,6 +1018,7 @@ export class CutterBridgeClient {
const bytes = await readBoundedFileBytes(
file,
MAX_DESCRIPTOR_BYTES,
{ expectedSize: info.size },
);
assertArtifactReadActive(signal);
return bytes;
+4 -1
View File
@@ -106,7 +106,10 @@ export const readManagedSnapshot = async (
const signal = options.signal;
if (metadata.size > maxBytes)
throw managedSnapshotCapacityError(operation, maxBytes);
const bytes = await readBoundedFileBytes(handle, maxBytes, { signal });
const bytes = await readBoundedFileBytes(handle, maxBytes, {
signal,
expectedSize: metadata.size,
});
if (bytes === undefined)
throw managedSnapshotCapacityError(operation, maxBytes);
signal?.throwIfAborted();
+14 -8
View File
@@ -12,7 +12,6 @@ import {
} from "../domain/dosMz.js";
import { err } from "../domain/result.js";
import type { NativeLoadImageObservation } from "../domain/native/nativeLoadImage.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
import {
attestGhidraDosLoadImage,
@@ -34,13 +33,20 @@ export const attestGhidraDosSnapshot = async (
signal?: AbortSignal,
) => {
const headerBytes = Math.min(fileBytes, 64);
const header = await readBoundedFileBytes(handle, headerBytes, {
signal,
expectedSize: headerBytes,
cancellationFailure: cancelled,
});
if (header === undefined || header.length !== headerBytes)
throw new RegularFileChangedError(path);
const header = Buffer.allocUnsafe(headerBytes);
let headerRead = 0;
while (headerRead < headerBytes) {
if (signal?.aborted) throw cancelled(signal.reason);
const { bytesRead } = await handle.read(
header,
headerRead,
headerBytes - headerRead,
headerRead,
);
if (signal?.aborted) throw cancelled(signal.reason);
if (bytesRead === 0) throw new RegularFileChangedError(path);
headerRead += bytesRead;
}
const declarations = readDosMzDeclarations(header);
if (!declarations.ok) return declarations;
const extent = dosMzDeclaredImageByteLength(declarations.value);
+1
View File
@@ -210,6 +210,7 @@ export const readIdaConfiguration = (
MAXIMUM_REGISTRATION_BYTES,
{
signal: options.signal,
expectedSize: metadata.size,
cancellationFailure: (reason) =>
new RegularFileOperationCancelled(reason),
},
+1
View File
@@ -432,6 +432,7 @@ export const inspectAppleDispatchMetadata = async (
if (signal?.aborted) throw cancelled();
const read = await readBoundedFileBytes(handle, maximumBytes, {
signal,
expectedSize: before.size,
cancellationFailure: () => cancelled(),
});
if (read === undefined) throw inputBudgetExceeded(admission, null);
+15 -9
View File
@@ -42,10 +42,14 @@ export const readBoundedFileBytes = async (
)
throw new RangeError("Expected file size must fit the byte limit");
assertActive();
if (expectedSize === undefined) {
const chunks: Buffer[] = [];
const buffer = Buffer.allocUnsafe(Math.min(64 * 1_024, maxBytes + 1));
let total = 0;
const readChunks = async (
chunks: Buffer[],
initialTotal: number,
): Promise<Buffer | undefined> => {
const buffer = Buffer.allocUnsafe(
Math.min(64 * 1_024, maxBytes - initialTotal + 1),
);
let total = initialTotal;
for (;;) {
assertActive();
const { bytesRead } = await read(
@@ -59,17 +63,19 @@ export const readBoundedFileBytes = async (
if (total > maxBytes) return undefined;
chunks.push(Buffer.from(buffer.subarray(0, bytesRead)));
}
}
const buffer = Buffer.allocUnsafe(expectedSize);
if (expectedSize === 0) return buffer;
};
if (expectedSize === undefined) return readChunks([], 0);
// Allocate one extra probe byte so an unchanged file is read in a single
// buffer without Buffer.concat while still proving EOF (or detecting growth).
const buffer = Buffer.allocUnsafe(expectedSize + 1);
let total = 0;
for (;;) {
assertActive();
const { bytesRead } = await read(buffer, total, expectedSize - total);
const { bytesRead } = await read(buffer, total, buffer.length - total);
assertActive();
if (bytesRead === 0) return buffer.subarray(0, total);
total += bytesRead;
if (total > maxBytes) return undefined;
if (total === expectedSize) return buffer;
if (total === buffer.length) return readChunks([buffer], total);
}
};
+1
View File
@@ -359,6 +359,7 @@ const readRegularFileContent = <Value>(
options.admit?.(stats);
const bytes = await readBoundedFileBytes(handle, stats.size, {
...(options.signal === undefined ? {} : { signal: options.signal }),
expectedSize: stats.size,
cancellationFailure: (reason) =>
new RegularFileOperationCancelled(reason),
operationFailure: (cause) => new RegularFileReadFailure(cause),
@@ -120,3 +120,79 @@ describe("bounded file byte reads", () => {
}
});
});
describe("bounded file byte reads with expectedSize", () => {
it.each([0, 65_536])(
"accepts a file matching expectedSize %i at the byte limit",
async (limit) => {
const root = await createTestTempDirectory("rea-bounded-expected-");
const path = join(root, "input");
const content = Buffer.alloc(limit, 0x62);
await writeFile(path, content);
const handle = await open(path, "r");
try {
const actual = await readBoundedFileBytes(handle, limit, {
expectedSize: limit,
});
if (actual === undefined)
throw new Error("Expected complete file bytes");
expect(actual.equals(content)).toBe(true);
} finally {
await handle.close();
}
},
);
it.each([0, 10])(
"detects growth past maxBytes when expectedSize equals maxBytes (%i)",
async (expectedSize) => {
const root = await createTestTempDirectory("rea-growing-expected-");
const path = join(root, "input");
await writeFile(path, "0".repeat(expectedSize));
const handle = await open(path, "r");
try {
await appendFile(path, "abcdef");
expect(
await readBoundedFileBytes(handle, expectedSize, { expectedSize }),
).toBeUndefined();
const next = Buffer.alloc(1);
expect((await handle.read(next, 0, 1, null)).bytesRead).toBe(1);
expect(next.toString()).toBe("b");
} finally {
await handle.close();
}
},
);
it("reads through EOF when a file grows beyond expectedSize but stays within maxBytes", async () => {
const root = await createTestTempDirectory("rea-growing-within-max-");
const path = join(root, "input");
await writeFile(path, "hello");
const handle = await open(path, "r");
try {
await appendFile(path, " world!");
const actual = await readBoundedFileBytes(handle, 32, {
expectedSize: 5,
});
if (actual === undefined) throw new Error("Expected complete file bytes");
expect(actual.toString("utf8")).toBe("hello world!");
} finally {
await handle.close();
}
});
it("returns undefined when a file grows beyond expectedSize and exceeds maxBytes", async () => {
const root = await createTestTempDirectory("rea-growing-past-max-");
const path = join(root, "input");
await writeFile(path, "hello");
const handle = await open(path, "r");
try {
await appendFile(path, "0123456789");
expect(
await readBoundedFileBytes(handle, 10, { expectedSize: 5 }),
).toBeUndefined();
} finally {
await handle.close();
}
});
});