From 963535fb15ec0fa01fced2a8272c7b0acf4da748 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:39:05 -0500 Subject: [PATCH] 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 --- src/filesystem/StableFileHash.ts | 10 +- src/kuna/KunaCommand.ts | 4 +- src/kuna/KunaProjectExport.ts | 37 +++--- src/kuna/KunaProjectFiles.ts | 117 +++++++++++++----- .../boundary/filesystem/inesArtifact.test.ts | 9 +- .../providers/kuna/kunaProjectFiles.test.ts | 34 +++++ 6 files changed, 149 insertions(+), 62 deletions(-) diff --git a/src/filesystem/StableFileHash.ts b/src/filesystem/StableFileHash.ts index 88ef1d86b8..ac1485410a 100644 --- a/src/filesystem/StableFileHash.ts +++ b/src/filesystem/StableFileHash.ts @@ -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 => { 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); diff --git a/src/kuna/KunaCommand.ts b/src/kuna/KunaCommand.ts index 3b8c01db33..c3cf1ad160 100644 --- a/src/kuna/KunaCommand.ts +++ b/src/kuna/KunaCommand.ts @@ -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 => { const { installation } = request; try { - const changed = await verifyExecutable( + const changed = await verifyKunaExecutableDigest( installation, request.signal, request.operation, diff --git a/src/kuna/KunaProjectExport.ts b/src/kuna/KunaProjectExport.ts index 9a2938a428..b41a2fe65d 100644 --- a/src/kuna/KunaProjectExport.ts +++ b/src/kuna/KunaProjectExport.ts @@ -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> => { - 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 > = {}; + 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, diff --git a/src/kuna/KunaProjectFiles.ts b/src/kuna/KunaProjectFiles.ts index cc1f712cbb..9f28ae0634 100644 --- a/src/kuna/KunaProjectFiles.ts +++ b/src/kuna/KunaProjectFiles.ts @@ -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, +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, + 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 => { + 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, summary: KunaExportSummary, ): Promise> => { - 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 => { 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( diff --git a/tests/boundary/filesystem/inesArtifact.test.ts b/tests/boundary/filesystem/inesArtifact.test.ts index 6e015f5596..e30c3d0233 100644 --- a/tests/boundary/filesystem/inesArtifact.test.ts +++ b/tests/boundary/filesystem/inesArtifact.test.ts @@ -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); } diff --git a/tests/boundary/providers/kuna/kunaProjectFiles.test.ts b/tests/boundary/providers/kuna/kunaProjectFiles.test.ts index 711d4c3ef2..0bf427c99e 100644 --- a/tests/boundary/providers/kuna/kunaProjectFiles.test.ts +++ b/tests/boundary/providers/kuna/kunaProjectFiles.test.ts @@ -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",