From 9d64f92f16afab7c4ac7e6cc217c7f4b196ace7e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:28:29 -0500 Subject: [PATCH] perf(entropy): count selected bytes once and honor admission cancellation (#13660) * fix(entropy): stop after cancelled file admission and strengthen census proof * perf(entropy): count selected bytes once with a reusable histogram * test(entropy): align lifecycle coverage with current tests --- .../ByteEntropyService.test.ts | 222 ++++++++---------- .../binaryDiagnostics/ByteEntropyService.ts | 10 +- src/domain/native/byteEntropy.test.ts | 17 +- src/domain/native/byteEntropy.ts | 19 +- tests/support/providerLifecycleCoverage.ts | 4 +- 5 files changed, 122 insertions(+), 150 deletions(-) diff --git a/src/application/binaryDiagnostics/ByteEntropyService.test.ts b/src/application/binaryDiagnostics/ByteEntropyService.test.ts index fe91bd5a2a..b65acb8436 100644 --- a/src/application/binaryDiagnostics/ByteEntropyService.test.ts +++ b/src/application/binaryDiagnostics/ByteEntropyService.test.ts @@ -8,46 +8,21 @@ import { byteEntropySchema } from "../../domain/native/byteEntropy.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { ByteEntropyService } from "./ByteEntropyService.js"; -it("keeps whole-file identity and entropy while selecting unaligned blocks and a partial tail", async () => { - const root = await createTestTempDirectory("rea-entropy-"); - const path = join(root, "bytes"); - const bytes = Buffer.from(Array.from({ length: 1024 }, (_, i) => i % 256)); - await writeFile(path, bytes); - const result = await new ByteEntropyService().inspect({ - path, - offset: 3, - length: 513, - block_size: 256, - }); - if (!result.ok) throw result.error; - const report = byteEntropySchema.parse(result.value.normalized_result); - expect(report.blocks).toEqual([ - { offset: 3, length: 256, entropy: 8 }, - { offset: 259, length: 256, entropy: 8 }, - { offset: 515, length: 1, entropy: 0 }, - ]); - expect(report.file_entropy).toBe(8); - expect(report.artifact).toEqual({ - path, - bytes: 1024, - sha256: createHash("sha256").update(bytes).digest("hex"), - }); - expect(fileIdentity(result.value.subject).sha256).toBe( - report.artifact.sha256, - ); - expect(result.value.confidence).toBe("observed"); -}); - it.each([256, 4096, 65536])( "keeps %i-byte blocks relative to an unaligned window across short physical reads", async (blockSize) => { const root = await createTestTempDirectory("rea-entropy-short-reads-"); const path = join(root, "bytes"); - const bytes = Buffer.from( - Array.from({ length: 3 * 65536 + 256 }, (_, i) => i % 256), - ); + const bytes = Buffer.alloc(3 * 65536 + 256); + const selectedOffset = 3; + const fullBlockBytes = 2 * 65536; + // The selected blocks are uniform over all 256 values. The zero-filled + // prefix and suffix make file-wide entropy distinct from window entropy. + const values = Buffer.from(Array.from({ length: 256 }, (_, byte) => byte)); + bytes.fill(values, selectedOffset, selectedOffset + fullBlockBytes); await writeFile(path, bytes); let reads = 0; + let shortReads = 0; const service = new ByteEntropyService({ stat, open: async (...args) => { @@ -61,7 +36,15 @@ it.each([256, 4096, 65536])( position: number, ) => { reads += 1; - return read(buffer, offset, Math.min(length, 3571), position); + const result = await read( + buffer, + offset, + Math.min(length, 3571), + position, + ); + if (result.bytesRead > 0 && result.bytesRead < length) + shortReads += 1; + return result; }, }); return file; @@ -70,31 +53,44 @@ it.each([256, 4096, 65536])( try { const result = await service.inspect({ path, - offset: 3, - length: 2 * 65536 + 1, + offset: selectedOffset, + length: fullBlockBytes + 1, block_size: blockSize, }); if (!result.ok) throw result.error; const report = byteEntropySchema.parse(result.value.normalized_result); - const fullBlocks = (2 * 65536) / blockSize; + const fullBlocks = fullBlockBytes / blockSize; expect(report.blocks).toEqual([ ...Array.from({ length: fullBlocks }, (_, i) => ({ - offset: 3 + i * blockSize, + offset: selectedOffset + i * blockSize, length: blockSize, entropy: 8, })), - { offset: 3 + 2 * 65536, length: 1, entropy: 0 }, + { offset: selectedOffset + fullBlockBytes, length: 1, entropy: 0 }, ]); expect(report.runs).toEqual([ - { offset: 3, length: 2 * 65536, classification: "high" }, - { offset: 3 + 2 * 65536, length: 1, classification: "low" }, + { + offset: selectedOffset, + length: fullBlockBytes, + classification: "high", + }, + { + offset: selectedOffset + fullBlockBytes, + length: 1, + classification: "low", + }, ]); - expect(report.file_entropy).toBe(8); - expect(report.artifact.sha256).toBe( - createHash("sha256").update(bytes).digest("hex"), + expect(report.file_entropy).toBe(6.2236); + expect(report.limitations).not.toContainEqual( + expect.stringContaining("reports a size of 0"), ); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + expect(report.artifact).toEqual({ path, bytes: bytes.length, sha256 }); + expect(fileIdentity(result.value.subject).sha256).toBe(sha256); + expect(result.value.confidence).toBe("observed"); // Even with 3,571-byte short reads, finer report resolution does not // require hundreds of asynchronous reads of this 193 KiB file. + expect(shortReads).toBeGreaterThan(0); expect(reads).toBeLessThan(100); } finally { await service.close(); @@ -147,15 +143,6 @@ it.skipIf(process.platform !== "linux" && process.platform !== "darwin")( const service = new ByteEntropyService(); try { for (const [path, code] of cases) { - let observedCode: unknown; - try { - await stat(path); - } catch (cause: unknown) { - observedCode = - cause instanceof Error && "code" in cause ? cause.code : undefined; - } - expect(observedCode).toBe(code); - const result = await service.inspect({ path }); if (result.ok) throw new Error(`Expected ${code} path failure`); expect(result.error).toMatchObject({ @@ -225,88 +212,69 @@ it.skipIf(process.platform !== "linux")( }, ); -it("adds no zero-size limitation to a file with content", async () => { - const root = await createTestTempDirectory("rea-entropy-nonempty-"); - const path = join(root, "one"); - await writeFile(path, "x"); - const result = await new ByteEntropyService().inspect({ path }); - if (!result.ok) throw result.error; - expect( - byteEntropySchema - .parse(result.value.normalized_result) - .limitations.join(" "), - ).not.toContain("reports a size of 0"); -}); - -it("honors cancellation before and during streaming", async () => { - const root = await createTestTempDirectory("rea-entropy-cancel-"); - const path = join(root, "bytes"); - await writeFile(path, Buffer.alloc(1024 * 1024)); - const service = new ByteEntropyService(); - const reason = { request: "opaque cancellation" }; - const before = await service.inspect( - { path }, - { signal: AbortSignal.abort(reason) }, - ); - if (before.ok) throw new Error("Expected cancellation before admission"); - expect(before.error.cause).toBe(reason); - expect(before.error.partialObservation).toBeUndefined(); - const controller = new AbortController(); - let reads = 0; - const streaming = new ByteEntropyService({ - stat, - open: async (...args) => { +it.each([ + ["before admission", 0, 0, 0, 0], + ["during stat", 1, 0, 0, 0], + ["during open", 1, 1, 0, 1], + ["during streaming", 1, 1, 1, 1], +] as const)( + "honors cancellation %s and closes any admitted descriptor", + async (stage, stats, opens, reads, closes) => { + const root = await createTestTempDirectory("rea-entropy-cancel-"); + const path = join(root, "bytes"); + await writeFile(path, Buffer.alloc(2 * 65_536)); + const controller = new AbortController(); + const reason = { request: "opaque cancellation" }; + const inspectStat = vi.fn(async (...args: Parameters) => { + const result = await stat(...args); + if (stage === "during stat") controller.abort(reason); + return result; + }); + let readCount = 0; + let closeCount = 0; + const inspectOpen = vi.fn(async (...args: Parameters) => { const file = await open(...args); const read = file.read.bind(file); + const close = file.close.bind(file); vi.spyOn(file, "read").mockImplementation(async (...readArgs) => { const result = await read(...readArgs); - reads += 1; - controller.abort(reason); + readCount += 1; + if (stage === "during streaming") controller.abort(reason); return result; }); + vi.spyOn(file, "close").mockImplementation(async () => { + closeCount += 1; + await close(); + }); + if (stage === "during open") controller.abort(reason); return file; - }, - }); - const pending = streaming.inspect( - { path, block_size: 256 }, - { signal: controller.signal }, - ); - const during = await pending; - if (during.ok) throw new Error("Expected cancellation during read"); - expect(during.error).toMatchObject({ _tag: "AnalysisCancelledError" }); - expect(during.error.cause).toBe(reason); - expect(during.error.partialObservation).toBeUndefined(); - expect(reads).toBe(1); -}); + }); + const service = new ByteEntropyService({ + stat: inspectStat as typeof stat, + open: inspectOpen, + }); -it("maps cancellation during open to the cancelled algebra with its original cause", async () => { - const root = await createTestTempDirectory("rea-entropy-open-cancel-"); - const path = join(root, "bytes"); - await writeFile(path, Buffer.alloc(512)); - const controller = new AbortController(); - const reason = new Error("cancelled while opening"); - const service = new ByteEntropyService({ - stat, - open: async (...args) => { - const file = await open(...args); - controller.abort(reason); - return file; - }, - }); - - const result = await service.inspect( - { path, block_size: 256 }, - { signal: controller.signal }, - ); - - if (result.ok) throw new Error("Expected cancellation during open"); - expect(result.error).toMatchObject({ _tag: "AnalysisCancelledError" }); - expect(result.error.cause).toBe(reason); - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "cancelled", - }); - await service.close(); -}); + try { + if (stage === "before admission") controller.abort(reason); + const result = await service.inspect( + { path }, + { signal: controller.signal }, + ); + if (result.ok) throw new Error("Expected cancellation"); + expect(result.error.cause).toBe(reason); + expect(result.error.partialObservation).toBeUndefined(); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "cancelled", + }); + expect(inspectStat).toHaveBeenCalledTimes(stats); + expect(inspectOpen).toHaveBeenCalledTimes(opens); + expect(readCount).toBe(reads); + expect(closeCount).toBe(closes); + } finally { + await service.close(); + } + }, +); it.each([false, true])( "retains completed Evidence when final close is cancelled (close fails: %s)", diff --git a/src/application/binaryDiagnostics/ByteEntropyService.ts b/src/application/binaryDiagnostics/ByteEntropyService.ts index e843822f1a..c36ff12366 100644 --- a/src/application/binaryDiagnostics/ByteEntropyService.ts +++ b/src/application/binaryDiagnostics/ByteEntropyService.ts @@ -22,7 +22,7 @@ import { } from "../../domain/evidence.js"; import { byteEntropySchema, - computeBlockEntropy, + createBlockEntropyCalculator, entropyFromCounts, countByteValues, wholeFileByteCounts, @@ -190,6 +190,7 @@ export class ByteEntropyService { }; try { const before = await this.files.stat(input.path, { bigint: true }); + assertArtifactReadActive(options?.signal); if (!before.isFile()) throw invalid("path", "Expected a regular file."); admitted = true; // Only an admitted selected file may consult filesystem spelling. Do not @@ -261,6 +262,7 @@ export class ByteEntropyService { // size divides this buffer, so only the window's final block is short. const buffer = Buffer.alloc(65_536); const counts = wholeFileByteCounts(); + const computeBlockEntropy = createBlockEntropyCalculator(counts); const hash = createHash("sha256"); let position = 0; while (position < size) { @@ -283,8 +285,7 @@ export class ByteEntropyService { } const bytes = buffer.subarray(0, filled); hash.update(bytes); - countByteValues(bytes, counts); - if (selected) + if (selected) { for ( let offset = 0; offset < filled; @@ -297,6 +298,9 @@ export class ByteEntropyService { entropy: computeBlockEntropy(block), }); } + } else { + countByteValues(bytes, counts); + } position += filled; } if ( diff --git a/src/domain/native/byteEntropy.test.ts b/src/domain/native/byteEntropy.test.ts index 2f2cee99de..459c053f56 100644 --- a/src/domain/native/byteEntropy.test.ts +++ b/src/domain/native/byteEntropy.test.ts @@ -1,6 +1,6 @@ import { expect, it } from "vitest"; import { - computeBlockEntropy, + createBlockEntropyCalculator, countByteValues, entropyFromCounts, inspectByteEntropyInputSchema, @@ -9,6 +9,9 @@ import { } from "./byteEntropy.js"; it("computes known Shannon answers including partial and empty blocks", () => { + const computeBlockEntropy = createBlockEntropyCalculator( + wholeFileByteCounts(), + ); expect(computeBlockEntropy(new Uint8Array(4096))).toBe(0); expect( computeBlockEntropy(Uint8Array.from({ length: 256 }, (_, i) => i)), @@ -67,15 +70,3 @@ it("counts a repeated byte past 2^32 without wrapping", () => { expect(counts[0]).toBe(2 ** 32 + 2 ** 15); expect(entropyFromCounts(counts, counts[0]!)).toBe(0); }); - -it("accumulates the same census across chunks as one concatenated run", () => { - // The service counts chunk by chunk; a per-chunk counter would be wrong. Both chunks go into - // one counter here, which is what the service does. - const counts = wholeFileByteCounts(); - countByteValues(new Uint8Array([0, 1, 0]), counts); - countByteValues(new Uint8Array([1, 0]), counts); - expect(Array.from(counts.slice(0, 2))).toEqual([3, 2]); - expect(entropyFromCounts(counts, 5)).toBe( - computeBlockEntropy(new Uint8Array([0, 1, 0, 1, 0])), - ); -}); diff --git a/src/domain/native/byteEntropy.ts b/src/domain/native/byteEntropy.ts index b32d638687..24e3e6494b 100644 --- a/src/domain/native/byteEntropy.ts +++ b/src/domain/native/byteEntropy.ts @@ -52,16 +52,21 @@ export const byteEntropySchema = z.strictObject({ }); export type ByteEntropy = z.infer; -/** Shannon entropy in bits per byte, rounded once at the reporting boundary. */ +/** + * Shannon entropy in bits per byte, rounded once at the reporting boundary. + * When counting a selected block, also add its bins to the whole-file census. + */ export const entropyFromCounts = ( counts: ArrayLike, length: number, + fileCounts?: Float64Array, ): number => { if (length === 0) return 0; let entropy = 0; for (let i = 0; i < counts.length; i++) { const count = counts[i] ?? 0; if (count > 0) { + if (fileCounts !== undefined) fileCounts[i] = fileCounts[i]! + count; const probability = count / length; entropy -= probability * Math.log2(probability); } @@ -100,10 +105,14 @@ export const countByteValues = ( } }; -export const computeBlockEntropy = (bytes: Uint8Array): number => { - const counts = new Float64Array(256); - countByteValues(bytes, counts); - return entropyFromCounts(counts, bytes.length); +/** Reuse one block histogram and accumulate its counts into the file census. */ +export const createBlockEntropyCalculator = (fileCounts: Float64Array) => { + const counts = wholeFileByteCounts(); + return (bytes: Uint8Array): number => { + counts.fill(0); + countByteValues(bytes, counts); + return entropyFromCounts(counts, bytes.length, fileCounts); + }; }; /** Merge only adjacent classified blocks, using the reported rounded entropy. */ diff --git a/tests/support/providerLifecycleCoverage.ts b/tests/support/providerLifecycleCoverage.ts index 796af86bec..4fdb9032b0 100644 --- a/tests/support/providerLifecycleCoverage.ts +++ b/tests/support/providerLifecycleCoverage.ts @@ -294,13 +294,13 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< covered( test( "src/application/binaryDiagnostics/ByteEntropyService.test.ts", - "keeps whole-file identity and entropy while selecting unaligned blocks and a partial tail", + "keeps %i-byte blocks relative to an unaligned window across short physical reads", ), ), covered( test( "src/application/binaryDiagnostics/ByteEntropyService.test.ts", - "honors cancellation before and during streaming", + "honors cancellation %s and closes any admitted descriptor", ), ), ),