perf(kuna): share stat-verified executable cache and fuse .c export hashing with source scanning (#13508)

* perf(kuna): share stat-verified executable cache and fuse .c export hashing with source scanning (#13506)

* fix(filesystem): preserve 64 KiB read chunk size in StableFileHash

* test(kuna): exercise reused source buffers and stabilize hash fault fixture

* test(artifacts): type the positional hash fault fixture
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 18:39:05 +00:00
1 parent 3a0d9d6874
commit 963535fb15
6 files changed
+149 -62

No files matched your search

+9 -1
View File
@@ -20,6 +20,8 @@ import { errorMessage } from "../kernel/errorMessage.js";
export interface StableFileHashOptions {
readonly signal?: AbortSignal;
readonly retainFailedClose: (owner: OwnedFileHandle) => void;
/** Optional synchronous observer invoked with each read slice (reused buffer; copy if retained). */
readonly onChunk?: (chunk: Buffer) => void;
}
export interface StableFileObservation {
@@ -91,6 +93,9 @@ async function readStableFile(
symlinks: "follow",
prefixBytes: includePrefix ? STABLE_FILE_PREFIX_BYTES : 0,
...(options.signal === undefined ? {} : { signal: options.signal }),
...(options.onChunk === undefined
? {}
: { onChunk: options.onChunk }),
},
);
return includePrefix
@@ -123,6 +128,7 @@ export const hashStableRegularFileDescriptor = async (
readonly symlinks: "follow" | "reject";
readonly signal?: AbortSignal;
readonly prefixBytes?: number;
readonly onChunk?: (chunk: Buffer) => void;
},
): Promise<StableFileFingerprint & { readonly prefix: Buffer }> => {
if (!Number.isSafeInteger(initial.size) || initial.size < 0)
@@ -149,7 +155,9 @@ export const hashStableRegularFileDescriptor = async (
const prefixBytes = Math.min(read.bytesRead, prefix.length - position);
chunk.copy(prefix, position, 0, prefixBytes);
}
hash.update(chunk.subarray(0, read.bytesRead));
const slice = chunk.subarray(0, read.bytesRead);
hash.update(slice);
options.onChunk?.(slice);
position += read.bytesRead;
}
assertRegularFileActive(options.signal);
+2 -2
View File
@@ -202,7 +202,7 @@ const verifiedExecutables = new Map<
* Confirm the executable still has the digest its analysis profile committed,
* so no answer names one Kuna build while another produced it.
*/
const verifyExecutable = async (
export const verifyKunaExecutableDigest = async (
installation: KunaInstallation,
signal: AbortSignal,
operation: string,
@@ -242,7 +242,7 @@ export const runKunaCommand = async (
): Promise<KunaCommandOutcome> => {
const { installation } = request;
try {
const changed = await verifyExecutable(
const changed = await verifyKunaExecutableDigest(
installation,
request.signal,
request.operation,
+18 -19
View File
@@ -26,13 +26,11 @@ import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { ProviderFailureDialect } from "../providers/classifyProviderFailure.js";
import { err, ok, type Result } from "../domain/result.js";
import {
hashStableFile,
observeStableFile,
StableFileHashFailure,
} from "../filesystem/StableFileHash.js";
import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";
import { assertArtifactCommandPath } from "../process/ArtifactCommandPath.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
import {
copyAndHash,
@@ -40,12 +38,14 @@ import {
KUNA_INVENTORY_OUTPUT_BYTES,
kunaFileCleanupError,
runKunaCommand,
verifyKunaExecutableDigest,
type KunaProcessLauncher,
} from "./KunaCommand.js";
import type { KunaDeadline } from "./KunaConfiguration.js";
import type { KunaInstallation } from "./KunaInstallation.js";
import { KUNA_DIAGNOSTIC_BYTES } from "./KunaLimits.js";
import {
createKunaProjectSourceScanner,
parseKunaExportSummary,
parseKunaInventory,
scanKunaProjectSource,
@@ -240,22 +240,19 @@ const verifyKunaExecutable = async (
signal: AbortSignal,
retainFailedFileClose: KunaExportRequest["retainFailedFileClose"],
): Promise<Result<null, ProviderAdapterError>> => {
const invocationPath = installation.configuration.command;
await assertArtifactCommandPath(
{ invocationPath, resolvedPath: installation.executable },
KUNA_EXPORT_OPERATION,
);
const executable = await hashStableFile(invocationPath, {
const changed = await verifyKunaExecutableDigest(
installation,
signal,
retainFailedClose: (owner) => retainFailedFileClose(owner, invocationPath),
});
if (executable.sha256 === installation.sha256) return ok(null);
KUNA_EXPORT_OPERATION,
retainFailedFileClose,
);
if (changed === undefined) return ok(null);
return err(
new ProviderAdapterError(KUNA_PROVIDER_ID, KUNA_EXPORT_OPERATION, {
userMessage: `${installation.executable} changed after readiness inspection; reopen the target so REA probes the current Kuna executable.`,
diagnostics: {
expected_sha256: installation.sha256,
observed_sha256: executable.sha256,
observed_sha256: changed,
},
}),
);
@@ -367,6 +364,7 @@ export const exportKunaProject = async (
const fileStates: Partial<
Record<keyof KunaProjectFileStates, RegularFileState>
> = {};
const sourceScanner = createKunaProjectSourceScanner(summary);
for (const [role, name] of Object.entries(names) as [
keyof KunaExportFiles,
string,
@@ -381,6 +379,13 @@ export const exportKunaProject = async (
const observed = await observeStableFile(path, {
signal,
retainFailedClose: (owner) => request.retainFailedFileClose(owner, path),
...(role === "c"
? {
onChunk: (chunk) => {
sourceScanner.push(chunk);
},
}
: {}),
});
files[role] = {
path: name,
@@ -394,14 +399,8 @@ export const exportKunaProject = async (
if (complete.inventory.sha256 !== sha256Hex(listed.snapshot.stdout.text))
return unusable("the retained inventory changed before export sealing");
await assertKunaProjectState(request.output, complete, states, signal);
const functions = await readKunaExportSource(
request.output,
complete.c,
summary,
signal,
);
const functions = sourceScanner.finish();
if (!functions.ok) return unusable(functions.error);
await assertKunaProjectState(request.output, complete, states, signal);
const identity = await verifyKunaExecutable(
installation,
signal,
+84 -33
View File
@@ -71,16 +71,10 @@ export const decodeKunaProjectText = (
* `headBytes` bytes `keep` accepts. Every other line is skipped without being
* buffered, so a large export is never held in memory.
*/
const scanLines = async (
chunks: AsyncIterable<Buffer>,
const createLineScanner = (
headBytes: number,
keep: (head: Buffer) => boolean,
): Promise<
Result<
{ readonly lines: readonly KeptLine[]; readonly bytes: number },
string
>
> => {
) => {
const lines: KeptLine[] = [];
let offset = 0;
let lineStart = 0;
@@ -89,6 +83,7 @@ const scanLines = async (
let lineBytes = 0;
let decided = false;
let skipped = false;
let error: string | undefined;
const recordLine = (bytes: Buffer): string | undefined => {
const decoded = decodeKunaProjectText(bytes, lineStart);
if (!decoded.ok)
@@ -96,7 +91,8 @@ const scanLines = async (
lines.push({ offset: lineStart, text: decoded.value });
return undefined;
};
for await (const chunk of chunks) {
const push = (chunk: Buffer): boolean => {
if (error !== undefined) return false;
let position = 0;
while (position < chunk.length) {
const newline = chunk.indexOf(0x0a, position);
@@ -105,10 +101,15 @@ const scanLines = async (
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`);
if (segment.length > MAX_KEPT_LINE_BYTES) {
error = `the line at byte ${String(lineStart)} is too long`;
return false;
}
const failure = recordLine(segment);
if (failure !== undefined) return err(failure);
if (failure !== undefined) {
error = failure;
return false;
}
}
position = newline + 1;
lineStart = offset + position;
@@ -121,16 +122,18 @@ const scanLines = async (
break;
}
}
if (segment.length > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
line.push(segment);
if (segment.length > MAX_KEPT_LINE_BYTES) {
error = `the line at byte ${String(lineStart)} is too long`;
return false;
}
line.push(Buffer.from(segment));
lineBytes = segment.length;
break;
}
if (!skipped) {
const segment = chunk.subarray(position, end);
if (segment.length > 0) {
line.push(segment);
line.push(Buffer.from(segment));
lineBytes += segment.length;
}
let assembled: Buffer | undefined;
@@ -143,13 +146,18 @@ const scanLines = async (
}
}
if (!skipped) {
if (lineBytes > MAX_KEPT_LINE_BYTES)
return err(`the line at byte ${String(lineStart)} is too long`);
if (lineBytes > MAX_KEPT_LINE_BYTES) {
error = `the line at byte ${String(lineStart)} is too long`;
return false;
}
if (newline !== -1) {
const failure = recordLine(
assembled ?? (line.length === 1 ? line[0]! : Buffer.concat(line)),
);
if (failure !== undefined) return err(failure);
if (failure !== undefined) {
error = failure;
return false;
}
}
}
}
@@ -162,19 +170,57 @@ const scanLines = async (
skipped = false;
}
offset += chunk.length;
}
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);
return true;
};
const finish = (): Result<
{ readonly lines: readonly KeptLine[]; readonly bytes: number },
string
> => {
if (error !== undefined) return err(error);
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);
}
}
}
return ok({ lines, bytes: offset });
return ok({ lines, bytes: offset });
};
return { push, finish };
};
const scanLines = async (
chunks: AsyncIterable<Buffer>,
headBytes: number,
keep: (head: Buffer) => boolean,
): Promise<
Result<
{ readonly lines: readonly KeptLine[]; readonly bytes: number },
string
>
> => {
const scanner = createLineScanner(headBytes, keep);
for await (const chunk of chunks) if (!scanner.push(chunk)) break;
return scanner.finish();
};
const HEADER_PREFIX_BYTES = Buffer.from(HEADER_PREFIX);
/** Push-based scanner for `.c` function blocks so hashing and scanning share one read pass. */
export const createKunaProjectSourceScanner = (summary: KunaExportSummary) => {
const scanner = createLineScanner(HEADER_PREFIX_BYTES.length, (head) =>
head.equals(HEADER_PREFIX_BYTES),
);
return {
push: scanner.push,
finish: (): Result<readonly KunaProjectFunction[], string> => {
const scanned = scanner.finish();
if (!scanned.ok) return scanned;
return parseScannedKunaFunctions(scanned.value, summary);
},
};
};
/**
* Split a finished export's `.c` into its function blocks.
*
@@ -186,17 +232,22 @@ export const scanKunaProjectSource = async (
chunks: AsyncIterable<Buffer>,
summary: KunaExportSummary,
): Promise<Result<readonly KunaProjectFunction[], string>> => {
const scanned = await scanLines(chunks, HEADER_PREFIX_BYTES.length, (head) =>
head.equals(HEADER_PREFIX_BYTES),
);
if (!scanned.ok) return scanned;
const scanner = createKunaProjectSourceScanner(summary);
for await (const chunk of chunks) if (!scanner.push(chunk)) break;
return scanner.finish();
};
const parseScannedKunaFunctions = (
scanned: { readonly lines: readonly KeptLine[]; readonly bytes: number },
summary: KunaExportSummary,
): Result<readonly KunaProjectFunction[], string> => {
const headers: {
readonly name: string;
readonly address: string;
readonly error: string | null;
readonly offset: number;
}[] = [];
for (const { offset, text } of scanned.value.lines) {
for (const { offset, text } of scanned.lines) {
const match = HEADER.exec(text);
if (match?.[1] === undefined || match[2] === undefined)
return err(`unrecognized function header at byte ${String(offset)}`);
@@ -207,7 +258,7 @@ export const scanKunaProjectSource = async (
offset,
});
}
const total = scanned.value.bytes;
const total = scanned.bytes;
const expected = summary.decompiled + summary.failed;
if (headers.length !== expected)
return err(
@@ -642,13 +642,8 @@ it("reports source loss during target hashing as a changed input", async () => {
) {
const result = await originalRead.call(this, ...args);
const readArguments: readonly unknown[] = args;
const [buffer, , , position] = readArguments;
if (
Buffer.isBuffer(buffer) &&
buffer.byteLength === 64 * 1024 &&
position === bytes.length &&
result.bytesRead === 0
) {
const [, , , position] = readArguments;
if (position === 0 && result.bytesRead === bytes.length) {
faultInjected = true;
await unlink(path);
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
createKunaProjectSourceScanner,
parseKunaExportSummary,
parseKunaInventory,
scanKunaAssembly,
@@ -79,6 +80,39 @@ it("splits Kuna's .c into function blocks at any chunk size", async () => {
);
});
it("retains split UTF-8 headers and byte spans when the input buffer is reused", () => {
const preamble = "// generated\n";
const first = "// Function: café @ 0x10\nvoid a() {}\n";
const second = "// Function: 雪 @ 0x20\nvoid b() {}\n";
const source = Buffer.from(preamble + first + second);
const scanner = createKunaProjectSourceScanner({ decompiled: 2, failed: 0 });
const scratch = Buffer.alloc(1);
for (const byte of source) {
scratch[0] = byte;
scanner.push(scratch);
scratch.fill(0xff);
}
expect(scanner.finish()).toEqual({
ok: true,
value: [
{
name: "café",
address: "0x10",
cOffset: Buffer.byteLength(preamble),
cLength: Buffer.byteLength(first),
error: null,
},
{
name: "雪",
address: "0x20",
cOffset: Buffer.byteLength(preamble + first),
cLength: Buffer.byteLength(second),
error: null,
},
],
});
});
it.each([
[
"a header count that disagrees with Kuna's summary",