From fbf79630d23a02ef26bb560dbdbc17ed3055b992 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:22:10 -0500 Subject: [PATCH] fix(elf): retain verified artifact reports through descriptor finalization --- .../ArtifactInspectionExecution.ts | 34 ++++-- src/application/ProviderOperationExecution.ts | 16 +++ .../binaryDiagnostics/ElfDebugLinkService.ts | 14 +-- .../ElfDependenciesService.ts | 78 ++++++------ .../binaryDiagnostics/ElfNotesService.test.ts | 18 +++ .../binaryDiagnostics/ElfNotesService.ts | 1 + .../ElfUnwindRangesService.ts | 1 + src/domain/analysisErrorBase.ts | 6 + src/native/elf/ElfDebugLinkProvider.ts | 26 ++-- src/native/elf/ElfDependenciesProvider.ts | 11 +- src/native/elf/ElfNotesProvider.ts | 11 +- src/native/elf/ElfUnwindRangesProvider.ts | 11 +- src/resources/readStableArtifact.ts | 7 +- .../elfStableReportFinalization.test.ts | 113 ++++++++++++++++++ 14 files changed, 271 insertions(+), 76 deletions(-) create mode 100644 tests/boundary/filesystem/elfStableReportFinalization.test.ts diff --git a/src/application/ArtifactInspectionExecution.ts b/src/application/ArtifactInspectionExecution.ts index 2ef45651600..8f598ad0bc6 100644 --- a/src/application/ArtifactInspectionExecution.ts +++ b/src/application/ArtifactInspectionExecution.ts @@ -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 { @@ -38,6 +41,8 @@ export interface ArtifactInspectionSpec { 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 ( } 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, diff --git a/src/application/ProviderOperationExecution.ts b/src/application/ProviderOperationExecution.ts index 94d09e89c47..5e86aa701ac 100644 --- a/src/application/ProviderOperationExecution.ts +++ b/src/application/ProviderOperationExecution.ts @@ -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 diff --git a/src/application/binaryDiagnostics/ElfDebugLinkService.ts b/src/application/binaryDiagnostics/ElfDebugLinkService.ts index 34517c573f9..3c03f34aa1f 100644 --- a/src/application/binaryDiagnostics/ElfDebugLinkService.ts +++ b/src/application/binaryDiagnostics/ElfDebugLinkService.ts @@ -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; } diff --git a/src/application/binaryDiagnostics/ElfDependenciesService.ts b/src/application/binaryDiagnostics/ElfDependenciesService.ts index 75bebcda25c..7046ab82409 100644 --- a/src/application/binaryDiagnostics/ElfDependenciesService.ts +++ b/src/application/binaryDiagnostics/ElfDependenciesService.ts @@ -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); } } diff --git a/src/application/binaryDiagnostics/ElfNotesService.test.ts b/src/application/binaryDiagnostics/ElfNotesService.test.ts index cd22f20e40a..d8a39a0ee10 100644 --- a/src/application/binaryDiagnostics/ElfNotesService.test.ts +++ b/src/application/binaryDiagnostics/ElfNotesService.test.ts @@ -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); +}); diff --git a/src/application/binaryDiagnostics/ElfNotesService.ts b/src/application/binaryDiagnostics/ElfNotesService.ts index 41a7472042d..df648e4a04b 100644 --- a/src/application/binaryDiagnostics/ElfNotesService.ts +++ b/src/application/binaryDiagnostics/ElfNotesService.ts @@ -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, diff --git a/src/application/binaryDiagnostics/ElfUnwindRangesService.ts b/src/application/binaryDiagnostics/ElfUnwindRangesService.ts index 284e524f9cd..67079d6690b 100644 --- a/src/application/binaryDiagnostics/ElfUnwindRangesService.ts +++ b/src/application/binaryDiagnostics/ElfUnwindRangesService.ts @@ -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, diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 481fb780ce1..8bfecf63c38 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -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 | { diff --git a/src/native/elf/ElfDebugLinkProvider.ts b/src/native/elf/ElfDebugLinkProvider.ts index 7f57479c447..efaf48d107f 100644 --- a/src/native/elf/ElfDebugLinkProvider.ts +++ b/src/native/elf/ElfDebugLinkProvider.ts @@ -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( 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, { diff --git a/src/native/elf/ElfDependenciesProvider.ts b/src/native/elf/ElfDependenciesProvider.ts index 5fb00818c30..3072b8193b9 100644 --- a/src/native/elf/ElfDependenciesProvider.ts +++ b/src/native/elf/ElfDependenciesProvider.ts @@ -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( 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, diff --git a/src/native/elf/ElfNotesProvider.ts b/src/native/elf/ElfNotesProvider.ts index 45e1ddde6b8..1d78b7c6bed 100644 --- a/src/native/elf/ElfNotesProvider.ts +++ b/src/native/elf/ElfNotesProvider.ts @@ -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( 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, diff --git a/src/native/elf/ElfUnwindRangesProvider.ts b/src/native/elf/ElfUnwindRangesProvider.ts index 75320ececc1..e1002d6221d 100644 --- a/src/native/elf/ElfUnwindRangesProvider.ts +++ b/src/native/elf/ElfUnwindRangesProvider.ts @@ -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( 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, diff --git a/src/resources/readStableArtifact.ts b/src/resources/readStableArtifact.ts index 3bdc9770cb8..3aff3ffa723 100644 --- a/src/resources/readStableArtifact.ts +++ b/src/resources/readStableArtifact.ts @@ -222,7 +222,7 @@ export interface StableArtifactHandle { } /** Options for {@link withStableArtifactHandle}. */ -export interface StableArtifactHandleOptions { +export interface StableArtifactHandleOptions { /** 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 ( path: string, maximumBytes: number, - options: StableArtifactHandleOptions, + options: StableArtifactHandleOptions, useFile: (handle: StableArtifactHandle) => Promise, ): Promise => { const chunkBytes = options.chunkBytes ?? DEFAULT_STREAM_CHUNK_BYTES; @@ -287,6 +289,7 @@ export const withStableArtifactHandle = async ( 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; diff --git a/tests/boundary/filesystem/elfStableReportFinalization.test.ts b/tests/boundary/filesystem/elfStableReportFinalization.test.ts new file mode 100644 index 00000000000..c58528d8f2f --- /dev/null +++ b/tests/boundary/filesystem/elfStableReportFinalization.test.ts @@ -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( + "node:fs/promises", + ); + const cleanup: Parameters[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(); + } + }, +);