fix(elf): retain verified artifact reports through descriptor finalization

This commit is contained in:
morluto committed 2026-11-23 01:13:14 -05:00
1 parent ba093e0777
commit fbf79630d2
14 files changed
+271 -76

No files matched your search

+25 -9
View File
@@ -10,7 +10,10 @@ import type {
} from "../ports/AnalysisProvider.js";
import { parseAnalysisInput } from "./AnalysisInput.js";
import type { AnalysisViewRetention } from "./analysisView/AnalysisViewService.js";
import { completeProviderEvidence } from "./ProviderOperationExecution.js";
import {
completeProviderEvidence,
retainCompletedArtifactEvidence,
} from "./ProviderOperationExecution.js";
/** Provider boundary for a single-operation artifact inspection. */
export interface ArtifactInspectionPort<TParameters, TReport> {
@@ -38,6 +41,8 @@ export interface ArtifactInspectionSpec<TInput, TParameters, TReport> {
identity: ProviderIdentity,
parameters: TParameters,
) => Evidence;
/** The provider retains a complete report when finalization fails. */
readonly retainCompletedReport?: true;
readonly selectRetainedView?: (
input: TInput,
) => AnalysisViewRequest | undefined;
@@ -83,16 +88,27 @@ export const executeArtifactInspection = async <TInput, TParameters, TReport>(
}
const parameters = spec.toParameters(input.value);
const inspected = await spec.provider.inspect(parameters, options);
if (!inspected.ok) return inspected;
const checked = spec.outputSchema.safeParse(inspected.value);
const report = inspected.ok
? inspected.value
: spec.retainCompletedReport === true
? inspected.error.partialObservation
: undefined;
if (!inspected.ok && report === undefined) return inspected;
const checked = spec.outputSchema.safeParse(report);
if (!checked.success || !spec.validateReport(checked.data, parameters))
return err(
new AnalysisOutputError(spec.operation, spec.invalidOutputMessage),
);
const completed = completeProviderEvidence(
spec.buildEvidence(checked.data, spec.provider.identity, parameters),
options?.signal,
return inspected.ok
? err(new AnalysisOutputError(spec.operation, spec.invalidOutputMessage))
: inspected;
const evidence = spec.buildEvidence(
checked.data,
spec.provider.identity,
parameters,
);
if (!inspected.ok) {
retainCompletedArtifactEvidence(inspected.error, evidence);
return inspected;
}
const completed = completeProviderEvidence(evidence, options?.signal);
if (!completed.ok || view === undefined) return completed;
return view.service.projectRetainedAnalysis(
completed.value,
@@ -148,6 +148,22 @@ export const completeProviderEvidence = (
return ok(evidence);
};
/** Use the admitted Evidence on every failure retaining the same report. */
export const retainCompletedArtifactEvidence = (
error: AnalysisError,
evidence: Evidence,
): void => {
const source = error.partialObservation;
if (source === undefined) return;
for (
let owner: AnalysisError | undefined = error;
owner !== undefined;
owner = owner.cleanupPrimary
)
if (owner.partialObservation === source)
owner.partialObservation = evidence;
};
/**
* Retain an incomplete observation when projection can serialize it.
* A JSON partial is replaced by one frozen snapshot, so a later mutation
@@ -28,7 +28,10 @@ import {
type ElfDebugLinkRange,
} from "../../domain/native/elfDebugLinkEvidence.js";
import { err, type Result } from "../../domain/result.js";
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
import {
completeProviderEvidence,
retainCompletedArtifactEvidence,
} from "../ProviderOperationExecution.js";
import {
callerAnalysisParameters,
parseAnalysisInput,
@@ -70,14 +73,7 @@ export class ElfDebugLinkService {
this.provider.identity,
parameters,
);
// Cleanup completion can reveal any primary that shares this exact report.
for (
let owner: AnalysisError | undefined = result.error;
owner !== undefined;
owner = owner.cleanupPrimary
)
if (owner.partialObservation === source)
owner.partialObservation = evidence;
retainCompletedArtifactEvidence(result.error, evidence);
}
return result;
}
@@ -16,7 +16,10 @@ import {
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
import { elfArchitecture } from "../../domain/elfFixedHeader.js";
import { err, type Result } from "../../domain/result.js";
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
import {
completeProviderEvidence,
retainCompletedArtifactEvidence,
} from "../ProviderOperationExecution.js";
import {
callerAnalysisParameters,
parseAnalysisInput,
@@ -55,51 +58,56 @@ export class ElfDependenciesService {
);
const parameters = callerAnalysisParameters(rawInput)(input.value);
const result = await this.provider.inspect(input.value, options);
if (!result.ok) return result;
const report = elfDependenciesSchema.safeParse(result.value);
const source = result.ok ? result.value : result.error.partialObservation;
if (!result.ok && source === undefined) return result;
const report = elfDependenciesSchema.safeParse(source);
if (
!report.success ||
report.data.artifact.path !== input.value.path ||
!validReport(report.data, input.value)
)
return err(
new AnalysisOutputError(
OPERATION,
"ELF dependency provider returned malformed output or changed artifact identity.",
),
);
return result.ok
? err(
new AnalysisOutputError(
OPERATION,
"ELF dependency provider returned malformed output or changed artifact identity.",
),
)
: result;
const value = report.data;
const mapped = elfArchitecture(value.machine);
const architecture = BINARY_ARCHITECTURES.find(
(supported) => supported === mapped,
);
return completeProviderEvidence(
createEvidence(
{
path: value.artifact.path,
format: "elf",
sha256: value.artifact.sha256,
...(architecture === undefined ? {} : { architecture }),
},
this.provider.identity,
{
operation: OPERATION,
parameters,
result: value,
confidence: "observed",
limitations: value.limitations,
locations: [
{ kind: "artifact-path", path: value.artifact.path },
...rangesOf(value).map((range) => ({
kind: "file-offset-range" as const,
start: range.offset,
end: range.offset + range.bytes,
})),
],
},
),
options?.signal,
const evidence = createEvidence(
{
path: value.artifact.path,
format: "elf",
sha256: value.artifact.sha256,
...(architecture === undefined ? {} : { architecture }),
},
this.provider.identity,
{
operation: OPERATION,
parameters,
result: value,
confidence: "observed",
limitations: value.limitations,
locations: [
{ kind: "artifact-path", path: value.artifact.path },
...rangesOf(value).map((range) => ({
kind: "file-offset-range" as const,
start: range.offset,
end: range.offset + range.bytes,
})),
],
},
);
if (!result.ok) {
retainCompletedArtifactEvidence(result.error, evidence);
return result;
}
return completeProviderEvidence(evidence, options?.signal);
}
}
@@ -131,3 +131,21 @@ it("retains a completed observation when the caller cancels as the provider comp
normalized_result: report,
});
});
it("keeps a failed report for a different artifact outside admitted Evidence", async () => {
const foreignReport = {
...report,
artifact: { ...report.artifact, path: "/artifacts/other" },
};
const failure = new AnalysisCancelledError("inspect_elf_notes", {
partialObservation: foreignReport,
});
const service = new ElfNotesService({
identity,
inspect: async () => ({ ok: false, error: failure }),
});
const result = await service.inspect({ path });
if (result.ok) throw new Error("Expected the original provider failure");
expect(result.error).toBe(failure);
expect(result.error.partialObservation).toBe(foreignReport);
});
@@ -32,6 +32,7 @@ export class ElfNotesService {
inputSchema: inspectElfNotesInputSchema,
outputSchema: elfNotesSchema,
provider: this.provider,
retainCompletedReport: true,
invalidOutputMessage:
"ELF note provider returned malformed output or changed artifact identity.",
toParameters: (input) => input,
@@ -51,6 +51,7 @@ export class ElfUnwindRangesService {
inputSchema: inspectElfUnwindRangesInputSchema,
outputSchema: elfUnwindRangesSchema,
provider: this.provider,
retainCompletedReport: true,
invalidOutputMessage:
"ELF unwind provider returned malformed output or changed artifact identity.",
toParameters: (input) => input,
+6
View File
@@ -1,4 +1,7 @@
import type { ElfDebugLink } from "./native/elfDebugLink.js";
import type { ElfDependencies } from "./native/elfDependencies.js";
import type { ElfNotes } from "./native/elfNotes.js";
import type { ElfUnwindRanges } from "./native/elfUnwindRanges.js";
import type { InterfaceBuilderAnalysis } from "./apple/interfaceBuilderGraph.js";
import type { PartialTaskMeasurement } from "./desktop/taskDifficulty.js";
import type { AppleIpsPartialObservation } from "./native/appleIps.js";
@@ -690,6 +693,9 @@ import type { WebArtifactAcquisition } from "./webArtifactAcquisition.js";
/** Provider-neutral evidence collected before a typed analysis failure. */
export type AnalysisPartialObservation =
| ElfDebugLink
| ElfDependencies
| ElfNotes
| ElfUnwindRanges
| InterfaceBuilderAnalysis
| PartialTaskMeasurement
| {
+11 -15
View File
@@ -74,14 +74,14 @@ export class ElfDebugLinkProvider implements ElfDebugLinkPort {
let candidatePhase: CandidatePhase | undefined;
let candidate: StableArtifactStream | undefined;
let crc32 = 0;
let parsedImage: ElfDebugLink | undefined;
let completedImage: ElfDebugLink | undefined;
let observedImage:
| { readonly sha256: string; readonly bytes: number }
| undefined;
try {
return await this.#resources.run(async () => {
field = "path";
const image = await withStableArtifactHandle(
const image = await withStableArtifactHandle<ElfDebugLink>(
input.path,
input.max_file_bytes,
{
@@ -91,9 +91,12 @@ export class ElfDebugLinkProvider implements ElfDebugLinkPort {
onIdentity: (identity) => {
observedImage = identity;
},
onVerifiedResult: (value) => {
completedImage = value;
},
},
async (handle) => {
parsedImage = await parseElfDebugLinkFromHandle(
(handle) =>
parseElfDebugLinkFromHandle(
{
size: handle.size,
prefix: handle.prefix,
@@ -106,9 +109,7 @@ export class ElfDebugLinkProvider implements ElfDebugLinkPort {
},
input,
options?.signal,
);
return parsedImage;
},
),
);
if (input.candidate_path === undefined) return ok(image);
field = "candidate_path";
@@ -154,16 +155,11 @@ export class ElfDebugLinkProvider implements ElfDebugLinkPort {
input,
candidate,
);
else if (
parsedImage !== undefined &&
artifactFileCompletion(cause)?.value === parsedImage
) {
// Only the file owner can establish that the decoded image passed
// the final stability check before release was interrupted.
else if (completedImage !== undefined) {
retained =
input.candidate_path === undefined
? parsedImage
: incompleteCandidateObservation(parsedImage);
? completedImage
: incompleteCandidateObservation(completedImage);
}
return err(
elfDebugLinkFailure(cause, input, field, {
+9 -2
View File
@@ -21,6 +21,7 @@ import {
MAX_INSPECT_ELF_DEPENDENCY_IMPORTS,
MAX_INSPECT_ELF_DEPENDENCY_NEEDED,
MAX_INSPECT_ELF_DEPENDENCY_VERSIONS,
type ElfDependencies,
type InspectElfDependenciesInput,
} from "../../domain/native/elfDependencies.js";
import { err, ok } from "../../domain/result.js";
@@ -59,12 +60,13 @@ export class ElfDependenciesProvider {
input: InspectElfDependenciesInput,
options?: { readonly signal?: AbortSignal },
) {
let completed: ElfDependencies | undefined;
let observed:
| { readonly sha256: string; readonly bytes: number }
| undefined;
try {
return await this.#resources.run(async () => {
const result = await withStableArtifactHandle(
const result = await withStableArtifactHandle<ElfDependencies>(
input.path,
input.max_file_bytes,
{
@@ -74,6 +76,9 @@ export class ElfDependenciesProvider {
onIdentity: (identity) => {
observed = identity;
},
onVerifiedResult: (value) => {
completed = value;
},
},
async (handle) => {
assertArtifactReadActive(options?.signal);
@@ -101,7 +106,7 @@ export class ElfDependenciesProvider {
return ok(result);
});
} catch (cause) {
return err(elfDependenciesFailure(cause, input, observed));
return err(elfDependenciesFailure(cause, input, observed, completed));
}
}
}
@@ -116,6 +121,7 @@ const elfDependenciesFailure = (
cause: unknown,
input: InspectElfDependenciesInput,
observed: { readonly sha256: string; readonly bytes: number } | undefined,
completed?: ElfDependencies,
) => {
const facts = artifactFilePrimaryFacts(cause);
const primary = classifyProviderFailure(
@@ -192,6 +198,7 @@ const elfDependenciesFailure = (
),
}),
);
if (completed !== undefined) primary.retainPartialObservation(completed);
return projectStableArtifactFailure(
cause,
primary,
+9 -2
View File
@@ -23,6 +23,7 @@ import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js
import {
MAX_INSPECT_ELF_NOTE_ENTRIES,
MAX_INSPECT_ELF_NOTE_FILE_BYTES,
type ElfNotes,
type InspectElfNotesInput,
} from "../../domain/native/elfNotes.js";
import { err, ok } from "../../domain/result.js";
@@ -54,12 +55,13 @@ export class ElfNotesProvider implements ElfNotesPort {
}
async inspect(input: InspectElfNotesInput, options?: ExecutionOptions) {
let completed: ElfNotes | undefined;
let observed:
| { readonly sha256: string; readonly bytes: number }
| undefined;
try {
return await this.#resources.run(async () => {
const result = await withStableArtifactHandle(
const result = await withStableArtifactHandle<ElfNotes>(
input.path,
input.max_file_bytes,
{
@@ -69,6 +71,9 @@ export class ElfNotesProvider implements ElfNotesPort {
onIdentity: (identity) => {
observed = identity;
},
onVerifiedResult: (value) => {
completed = value;
},
},
(handle) =>
parseElfNotesFromHandle(
@@ -89,7 +94,7 @@ export class ElfNotesProvider implements ElfNotesPort {
return ok(result);
});
} catch (cause) {
return err(elfNotesFailure(cause, input, observed));
return err(elfNotesFailure(cause, input, observed, completed));
}
}
}
@@ -115,6 +120,7 @@ const elfNotesFailure = (
cause: unknown,
input: InspectElfNotesInput,
observed?: { readonly sha256: string; readonly bytes: number },
completed?: ElfNotes,
) => {
const facts = artifactFilePrimaryFacts(cause);
const primary = classifyProviderFailure(
@@ -172,6 +178,7 @@ const elfNotesFailure = (
),
}),
);
if (completed !== undefined) primary.retainPartialObservation(completed);
return projectStableArtifactFailure(
cause,
primary,
+9 -2
View File
@@ -18,6 +18,7 @@ import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js
import {
MAX_INSPECT_ELF_UNWIND_FILE_BYTES,
MAX_INSPECT_ELF_UNWIND_RANGES,
type ElfUnwindRanges,
type InspectElfUnwindRangesInput,
} from "../../domain/native/elfUnwindRanges.js";
import { err, ok } from "../../domain/result.js";
@@ -57,12 +58,13 @@ export class ElfUnwindRangesProvider implements ElfUnwindRangesPort {
options?: ExecutionOptions,
) {
const signal = options?.signal;
let completed: ElfUnwindRanges | undefined;
let snapshot:
| { readonly sha256: string; readonly bytes: number }
| undefined;
try {
return await this.#resources.run(async () => {
const report = await withStableArtifactHandle(
const report = await withStableArtifactHandle<ElfUnwindRanges>(
input.path,
input.max_file_bytes,
{
@@ -72,6 +74,9 @@ export class ElfUnwindRangesProvider implements ElfUnwindRangesPort {
onIdentity: (identity) => {
snapshot = identity;
},
onVerifiedResult: (value) => {
completed = value;
},
},
(handle) =>
parseElfUnwindRangesFromHandle(
@@ -88,7 +93,7 @@ export class ElfUnwindRangesProvider implements ElfUnwindRangesPort {
return ok(report);
});
} catch (cause) {
return err(elfUnwindFailure(cause, input, snapshot));
return err(elfUnwindFailure(cause, input, snapshot, completed));
}
}
}
@@ -107,6 +112,7 @@ const elfUnwindFailure = (
cause: unknown,
input: InspectElfUnwindRangesInput,
snapshot?: { readonly sha256: string; readonly bytes: number },
completed?: ElfUnwindRanges,
) => {
const facts = artifactFilePrimaryFacts(cause);
const primary = classifyProviderFailure(
@@ -162,6 +168,7 @@ const elfUnwindFailure = (
),
}),
);
if (completed !== undefined) primary.retainPartialObservation(completed);
return projectStableArtifactFailure(
cause,
primary,
+5 -2
View File
@@ -222,7 +222,7 @@ export interface StableArtifactHandle {
}
/** Options for {@link withStableArtifactHandle}. */
export interface StableArtifactHandleOptions {
export interface StableArtifactHandleOptions<Value = unknown> {
/** Bytes to retain from the start of the file, given its admitted size. */
readonly retainBytes: (size: number) => number;
/** Maximum streaming hash chunk size in bytes; defaults to 65536. */
@@ -235,6 +235,8 @@ export interface StableArtifactHandleOptions {
readonly sha256: string;
readonly bytes: number;
}) => void;
/** Called after the parsed result passes the final identity check, before closing. */
readonly onVerifiedResult?: (value: Value) => void;
}
/**
@@ -245,7 +247,7 @@ export interface StableArtifactHandleOptions {
export const withStableArtifactHandle = async <Value>(
path: string,
maximumBytes: number,
options: StableArtifactHandleOptions,
options: StableArtifactHandleOptions<Value>,
useFile: (handle: StableArtifactHandle) => Promise<Value>,
): Promise<Value> => {
const chunkBytes = options.chunkBytes ?? DEFAULT_STREAM_CHUNK_BYTES;
@@ -287,6 +289,7 @@ export const withStableArtifactHandle = async <Value>(
throw cause;
});
await verifyState();
options.onVerifiedResult?.(value);
// The descriptor owner records this verified completion before checking
// finalization cancellation, so cleanup errors can retain the value.
return value;
@@ -0,0 +1,113 @@
import { createHash } from "node:crypto";
import { open, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { createElfDependenciesService } from "../../../src/composition/binaryDiagnostics/elfDependencies.js";
import { createElfNotesService } from "../../../src/composition/binaryDiagnostics/elfNotes.js";
import { createElfUnwindRangesService } from "../../../src/composition/binaryDiagnostics/elfUnwindRanges.js";
import {
primaryAnalysisError,
resolvedAnalysisError,
} from "../../../src/domain/analysisErrorBase.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { elfDependencyFixture } from "../../../src/native/elf/ElfDependencies.fixture.js";
import { elfNoteFixture } from "../../../src/native/elf/ElfNotes.fixture.js";
import { elfUnwindFixture } from "../../../src/native/elf/ElfUnwindTables.fixture.js";
import {
expectRetainedDescriptor,
withDescriptorCloseFailure,
} from "../../fixtures/descriptorCloseFailure.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
vi.mock(import("node:fs/promises"), { spy: true });
it.each([
{
operation: "inspect_elf_notes",
createService: createElfNotesService,
fixture: elfNoteFixture,
observed: {
entries: expect.arrayContaining([
expect.objectContaining({
type_name: "gnu_build_id",
gnu: expect.objectContaining({
build_id_hex: "0123456789abcdef0123456789abcdef01234567",
}),
}),
]),
},
},
{
operation: "inspect_elf_dependencies",
createService: createElfDependenciesService,
fixture: elfDependencyFixture,
observed: {
needed: expect.arrayContaining([
expect.objectContaining({ name: "libc.so.6" }),
]),
},
},
{
operation: "inspect_elf_unwind_ranges",
createService: createElfUnwindRangesService,
fixture: elfUnwindFixture,
observed: {
ranges: expect.arrayContaining([
expect.objectContaining({ start: "0x400100", end: "0x400120" }),
]),
},
},
])(
"$operation retains the verified report across descriptor close failure and retry",
async ({ operation, createService, fixture, observed }) => {
const path = join(
await createTestTempDirectory("rea-elf-finalization-"),
"source",
);
const bytes = fixture();
await writeFile(path, bytes);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const service = createService();
const real =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
const cleanup: Parameters<typeof withDescriptorCloseFailure>[1] = {
path,
denied: true,
handles: [],
};
const openFile = vi.mocked(open);
openFile.mockImplementation(withDescriptorCloseFailure(real, cleanup).open);
try {
const parameters = { path, max_file_bytes: bytes.length + 4096 };
const result = await service.inspect(parameters);
if (result.ok) throw new Error("Expected retained descriptor cleanup");
expectRetainedDescriptor(result, cleanup, operation);
const primary = primaryAnalysisError(result.error);
const partial = result.error.partialObservation;
const evidence = parseEvidence(partial);
expect(evidence).toMatchObject({
operation,
parameters,
subject: { identity: { format: "elf", sha256 }, local_path: path },
normalized_result: {
artifact: { path, bytes: bytes.length, sha256 },
...observed,
},
});
if (operation === "inspect_elf_dependencies")
expect(evidence.parameters).toEqual(parameters);
cleanup.denied = false;
await service.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
expect(result.error.cleanupResources).toEqual([]);
expect(resolvedAnalysisError(result.error)).toBe(primary);
expect(primary.partialObservation).toBe(partial);
} finally {
cleanup.denied = false;
openFile.mockReset();
await service.close();
}
},
);