fix(io): consolidate managed snapshots and retain cleanup ownership

Reuse managed snapshot admission and hashing in sequential path comparisons, retaining caller paths and completed inspection Evidence on later failure. Preserve exact failed-close owners alongside typed read and cancellation failures, and retry them through caller-owned resource scopes. Require canonical Hopper lease identities, remove signed offset coercion, and repair stale setup cleanup expectations that failed CI.
This commit is contained in:
morluto
2026-10-12 14:46:37 +08:00
parent e9970855ba
commit 98d8470d36
16 changed files with 899 additions and 225 deletions
@@ -1,9 +1,11 @@
import { readFile, writeFile } from "node:fs/promises";
import { truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
import {
compareManagedMembersEvidenceValidated,
@@ -19,6 +21,11 @@ import { compareManagedMembersInputSchema } from "../../../../src/domain/managed
import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";
import { managedPeFixtureTarget } from "../../../../src/dotnet/ManagedPe.fixture.js";
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
import {
MAX_MANAGED_SNAPSHOT_BYTES,
readManagedSnapshot,
} from "../../../../src/dotnet/ManagedSnapshot.js";
import * as boundedFileBytes from "../../../../src/process/BoundedFileBytes.js";
it.each([
["accessibility", 6, 0x0011],
@@ -184,6 +191,14 @@ describe("managed member comparison path workflow", () => {
confidence: "inferred",
authority: "analyst-inference",
});
expect(result.value.parameters).toMatchObject({
left_path: leftPath,
right_path: rightPath,
});
expect(result.value.locations).toEqual([
{ kind: "artifact-path", path: leftPath },
{ kind: "artifact-path", path: rightPath },
]);
expect(
managedMemberComparisonResultSchema.parse(result.value.normalized_result)
.matching.exact_il_signature,
@@ -205,7 +220,179 @@ describe("managed member comparison path workflow", () => {
details: { path: expect.stringContaining("missing.dll") },
});
});
});
describe("managed comparison post-admission read failures", () => {
it.each([
["left", "disappearance", "ENOENT"],
["left", "permission denial", "EACCES"],
["right", "disappearance", "ENOENT"],
["right", "permission denial", "EACCES"],
])(
"classifies a %s-side %s during the post-resolution read",
async (side, _name, code) => {
const directory = await createTestTempDirectory(
"rea-managed-read-failure-",
);
const leftPath = join(directory, "left.dll");
const rightPath = join(directory, "right.dll");
await writeFile(leftPath, buildManagedPeFixture());
await writeFile(rightPath, buildManagedPeFixture());
const result = await compareManagedMemberPaths(
{ leftPath, rightPath },
{
resolveTarget: parseBinaryTarget,
readSnapshot: async (path, operation, options) => {
if (path === (side === "left" ? leftPath : rightPath)) {
const failure = Object.assign(new Error(`read failed: ${code}`), {
code,
});
throw failure;
}
return readManagedSnapshot(path, operation, options);
},
},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error._tag).toBe("BinaryTargetError");
expect(projectAnalysisError(result.error)).toMatchObject({
details: { path: side === "left" ? leftPath : rightPath },
});
if (side === "right")
expect(result.error.partialObservation).toMatchObject({
operation: "inspect_managed_members",
subject: {
local_path: leftPath,
digest: { sha256: expect.stringMatching(/^[0-9a-f]{64}$/u) },
},
});
else expect(result.error.partialObservation).toBeUndefined();
if (code === "EACCES")
expect(projectAnalysisError(result.error)).toMatchObject({
code: "access_denied",
});
},
);
});
describe("managed comparison snapshot admission and cleanup", () => {
it("rejects a sparse oversized snapshot through the default reader before reading it", async () => {
const directory = await createTestTempDirectory(
"rea-managed-oversized-snapshot-",
);
const leftPath = join(directory, "oversized.dll");
const rightPath = join(directory, "right.dll");
const fixture = buildManagedPeFixture();
await writeFile(leftPath, Buffer.alloc(0));
await truncate(leftPath, MAX_MANAGED_SNAPSHOT_BYTES + 1);
await writeFile(rightPath, fixture);
const template = managedPeFixtureTarget(fixture);
const read = vi.spyOn(boundedFileBytes, "readBoundedFileBytes");
try {
const result = await compareManagedMemberPaths(
{ leftPath, rightPath },
{
resolveTarget: async (path) => ({
ok: true,
value: { ...template, path },
}),
},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
operation: "compare_managed_members",
reportedLimits: {
max_snapshot_bytes: MAX_MANAGED_SNAPSHOT_BYTES,
},
});
expect(read).not.toHaveBeenCalled();
} finally {
read.mockRestore();
}
});
it("retries a transient snapshot close failure through the same resource owner", async () => {
const directory = await createTestTempDirectory(
"rea-managed-compare-close-",
);
const leftPath = join(directory, "left.dll");
const rightPath = join(directory, "right.dll");
await writeFile(leftPath, buildManagedPeFixture());
await writeFile(rightPath, buildManagedPeFixture());
const resources = new ArtifactResourceScope();
const originalClose = OwnedFileHandle.prototype.close;
const owners: OwnedFileHandle[] = [];
let attempts = 0;
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementation(async function (this: OwnedFileHandle) {
owners.push(this);
attempts += 1;
if (attempts === 1) throw new Error("injected transient close failure");
await originalClose.call(this);
});
try {
const result = await compareManagedMemberPaths(
{ leftPath, rightPath },
{},
resources,
);
expect(result.ok).toBe(true);
expect(owners[0]).toBe(owners[1]);
expect(attempts).toBe(3);
} finally {
close.mockRestore();
await resources.close();
}
});
it("projects persistent snapshot cleanup failure and retains its exact owner", async () => {
const directory = await createTestTempDirectory(
"rea-managed-compare-cleanup-",
);
const leftPath = join(directory, "left.dll");
const rightPath = join(directory, "right.dll");
await writeFile(leftPath, buildManagedPeFixture());
await writeFile(rightPath, buildManagedPeFixture());
const resources = new ArtifactResourceScope();
const cleanupCause = new Error("injected persistent close failure");
const owners: OwnedFileHandle[] = [];
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementation(async function (this: OwnedFileHandle) {
owners.push(this);
throw cleanupCause;
});
let result: Awaited<ReturnType<typeof compareManagedMemberPaths>>;
try {
result = await compareManagedMemberPaths(
{ leftPath, rightPath },
{},
resources,
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
details: { cleanup: "incomplete", resources: [leftPath] },
});
expect(owners[0]).toBe(owners[1]);
expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0);
} finally {
close.mockRestore();
await resources.close();
}
});
});
describe("managed comparison target identity", () => {
it("rejects a file that changes after target identity is resolved", async () => {
const directory = await createTestTempDirectory(
"rea-managed-compare-race-",
@@ -227,7 +414,6 @@ describe("managed member comparison path workflow", () => {
await writeFile(path, replacement);
return target;
},
readBytes: (path) => readFile(path),
},
);