Files
reverse-engineering-anything/src/gpu/GpuCodeObjectsProvider.ts
T
morluto efbb66c16a fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause (#15581)
* fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause

- inspect_labview_artifact refuses a file with no LabVIEW RSRC data as an
  unrecognized target (code unsupported_target, failure_kind unrecognized),
  as its format siblings do, instead of invalid_request. A PE whose
  resource tree could not be fully read is a malformed PE target.
- inspect_gpu_code_objects, inspect_model_artifact and Apktool reported a
  missing or non-regular selected file through their own copy of the
  selected-file refusal (BinaryTargetError, target_unavailable). They now
  use the shared projectSelectedArtifactFileFailure owner
  (invalid_request, conforming, with its own next step), and the copy is
  removed. The shared owner keeps the verified-symlink recovery the copy
  carried.
- A retained Evidence reference the session does not hold is
  invalid_request / invalid_input instead of evidence_integrity_mismatch.
  Altered or unauthenticated Evidence stays evidence_integrity_mismatch.

BREAKING CHANGE: error codes change for three refusals. A non-LabVIEW
file given to inspect_labview_artifact is unsupported_target (was
invalid_request). A missing or non-regular selected file for
inspect_gpu_code_objects, inspect_model_artifact or Apktool operations is
invalid_request (was target_unavailable). A missing retained Evidence
reference (details.reason "missing") is invalid_request with category
invalid_input (was evidence_integrity_mismatch / integrity_mismatch).
Callers that branch on these codes should match the new values;
details.reason, retry_class and the remediation are unchanged in meaning.

* test(model): expect the shared selected-file refusal for a missing model path

The process-global host read failure test still expected
target_unavailable for path errors on a model file. Those are now the
shared selected-file input refusal.

* fix(resources): name a rejected symlink in the shared selected-file refusal

The GPU and model readers' copy of the selected-file refusal said the
path was a symbolic link; the shared owner reported only ELOOP, so
rejectedSymlinkRecovery failed once they moved to it. Use the rejected
symlink's own message, and keep the errno message for every other
selected-path refusal.

* docs(errors): describe missing references and closure members as the caller's selection

The comment above RESOURCE_SNAPSHOT_NOT_APPLICABLE still said a missing
Evidence reference stays an integrity failure. Missing references,
including retained sources and closure members, are invalid_request; only
altered or unauthenticated Evidence stays an integrity failure.
2026-12-01 17:11:08 -05:00

422 lines
14 KiB
TypeScript

import {
readerIntegrityFailure,
ArtifactResourceScope,
ArtifactReaderFailure,
withArtifactRegularFile,
bindArtifactFileCleanup,
withArtifactCleanupFailure,
artifactFilePrimaryFacts,
artifactFileCancellationError,
artifactFileCompletion,
projectSelectedArtifactFileFailure,
} from "../resources/index.js";
import { GPU_CODE_OBJECTS_PROVIDER_IDENTITY } from "./GpuCodeObjectsProviderIdentity.js";
import { lstat, type FileHandle } from "node:fs/promises";
import type { GpuCodeObjectsPort } from "../ports/gpu/GpuCodeObjectsPort.js";
import {
createGpuCodeObjectsEvidence,
createGpuCodeObjectsPartialEvidence,
} from "../domain/gpu/gpuCodeObjectsEvidence.js";
import type { ExecutionOptions } from "../ports/AnalysisProvider.js";
import type {
GpuCodeObjects,
GpuCodeObjectsInput,
} from "../domain/gpu/gpuCodeObjects.js";
import {
gpuCodeObjectsSchema,
gpuCodeObjectsPartialSchema,
} from "../domain/gpu/gpuCodeObjects.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisArtifactChangedError,
AnalysisAccessDeniedError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import {
parseFailureAnalysisError,
parseLimitConstraint,
} from "../domain/parseFailureAnalysisError.js";
import {
projectZstandardFrameAllowance,
ZstandardFrameAllowanceError,
} from "../domain/compression/zstandardFrameAllowance.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../domain/binaryContainer.js";
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
import { nativeStructureLimit } from "../domain/native/nativeStructureBudget.js";
import {
GPU_AMD_METADATA_DEPTH_LIMIT,
GPU_CONTAINER_NESTING_LIMIT,
gpuBudgetParameterForLimit,
gpuCodeObjectsBudgetLimit,
resolveGpuCodeObjectsBudgets,
type GpuCodeObjectsBudgets,
} from "../domain/gpu/gpuCodeObjectsBudgets.js";
import {
GpuFileSource,
GpuReportCapacityFailure,
gpuCount,
} from "./GpuSource.js";
import { GpuInventory } from "./GpuInventory.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import {
isSelectedRegularFileError,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { hostDescriptorPressure } from "../process/hostDescriptorPressure.js";
const OPERATION = "inspect_gpu_code_objects";
const gpuResourceConstraint = (
primary: BinaryResourceFailure,
budgets: GpuCodeObjectsBudgets,
): AnalysisResourceConstraintError => {
const reportedLimitContext = {
maximum_object_bytes: budgets.maxObjectBytes,
maximum_report_bytes: budgets.maxReportBytes,
...(primary instanceof GpuReportCapacityFailure &&
primary.minimumReportBytes !== undefined
? { minimum_report_bytes: primary.minimumReportBytes }
: {}),
};
const { name, maximum, required } = primary.failure.limit;
const requiredValue =
required !== undefined && required <= BigInt(Number.MAX_SAFE_INTEGER)
? Number(required)
: undefined;
const parameter = gpuBudgetParameterForLimit(name);
if (parameter === "max_structure_bytes")
return parseLimitConstraint(OPERATION, "memory", primary, {
reportedLimitContext,
retryable: false,
limit: nativeStructureLimit(maximum),
});
if (parameter !== undefined)
return parseLimitConstraint(OPERATION, "memory", primary, {
reportedLimitContext,
retryable: false,
limit: gpuCodeObjectsBudgetLimit(parameter, maximum, requiredValue),
});
if (
name === GPU_CONTAINER_NESTING_LIMIT ||
name === GPU_AMD_METADATA_DEPTH_LIMIT
)
return parseLimitConstraint(OPERATION, "memory", primary, {
reportedLimitContext,
...fixedAllowanceOptions(
"The GPU nesting allowance",
"parser",
binaryResourceCeiling(primary),
),
});
return parseLimitConstraint(OPERATION, "memory", primary, {
reportedLimitContext,
...fixedAllowanceOptions(
"The GPU parser syntax allowance",
"parser",
binaryResourceCeiling(primary),
),
});
};
/** One admitted descriptor and bounded report at a time; retained cleanup blocks new work. */
export class GpuCodeObjectsProvider implements GpuCodeObjectsPort {
readonly identity = GPU_CODE_OBJECTS_PROVIDER_IDENTITY;
readonly #resources = new ArtifactResourceScope();
#busy = false;
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause) {
const error = new ProviderCleanupError(
this.identity.id,
this.#resources.cleanupResources,
{},
{ cause, operation: OPERATION },
);
bindArtifactFileCleanup(cause, error);
throw error;
}
}
async inspect(
input: GpuCodeObjectsInput,
options?: ExecutionOptions,
): Promise<Result<GpuCodeObjects, AnalysisError>> {
if (this.#busy)
return err(
new AnalysisResourceConstraintError(
OPERATION,
"capacity",
"One GPU inspection is already active",
{ concurrent_inspections: 1 },
{ retryable: true, measuredExhaustion: true },
),
);
this.#busy = true;
const budgets = resolveGpuCodeObjectsBudgets(input);
let progress: { inventory: GpuInventory; size: number } | undefined;
try {
return ok(
await this.#resources.run(() =>
withArtifactRegularFile(
input.path,
this.#resources,
options?.signal,
({ handle: file }) =>
this.#read(file, input, budgets, options?.signal, (value) => {
progress = value;
}),
),
),
);
} catch (cause) {
const providerId = this.identity.id;
const { cause: primary, origin } = artifactFilePrimaryFacts(cause);
// Malformed and truncated bytes are a malformed target; unsupported
// bytes are an unsupported target, as for every other format parser.
const formatFailure = parseFailureAnalysisError(
OPERATION,
input.path,
primary,
);
const frameAllowance =
primary instanceof ZstandardFrameAllowanceError
? primary
: cause instanceof ZstandardFrameAllowanceError
? cause
: undefined;
const selectedFile = isSelectedRegularFileError(primary)
? projectSelectedArtifactFileFailure(
primary,
OPERATION,
input.path,
"GPU artifact",
)
: undefined;
let error: AnalysisError;
if (frameAllowance !== undefined)
error = projectZstandardFrameAllowance(OPERATION, frameAllowance);
else if (
origin === "owned-or-classified" &&
primary instanceof AnalysisError
)
error = primary;
else if (primary instanceof BinaryResourceFailure)
error = gpuResourceConstraint(primary, budgets);
else if (formatFailure !== undefined) error = formatFailure;
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "cancelled"
)
error = artifactFileCancellationError(OPERATION, primary);
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "integrity"
)
error = readerIntegrityFailure(OPERATION, input.path, primary, {
cause,
});
else if (
primary instanceof Error &&
"code" in primary &&
(primary.code === "EACCES" || primary.code === "EPERM")
)
error = new AnalysisAccessDeniedError(
OPERATION,
input.path,
primary.code,
{ cause: primary },
);
else if (selectedFile !== undefined) error = selectedFile;
else if (
origin === "owned-or-classified" &&
primary instanceof ArtifactReaderFailure &&
primary.reason === "limit"
) {
const requiredBytes =
primary.observedBytes !== undefined &&
primary.observedBytes <= BigInt(Number.MAX_SAFE_INTEGER)
? Number(primary.observedBytes)
: undefined;
error = new AnalysisResourceConstraintError(
OPERATION,
"memory",
primary.message,
{
maximum_object_bytes: budgets.maxObjectBytes,
...(primary.observedBytes === undefined
? {}
: { required: String(primary.observedBytes) }),
},
{
cause: primary,
retryable: false,
limit: gpuCodeObjectsBudgetLimit(
"max_object_bytes",
budgets.maxObjectBytes,
requiredBytes,
),
},
);
}
// Other coded I/O failures remain host failures; descriptor pressure
// is occupied host capacity.
else
error =
hostDescriptorPressure(OPERATION, primary, { path: input.path }) ??
new ProviderAdapterError(providerId, OPERATION, {
cause,
diagnostics: {
path: input.path,
reason: errorMessage(primary),
},
});
if (
cause instanceof ArtifactReaderFailure &&
cause.cleanup !== undefined
) {
error = withArtifactCleanupFailure(cause, error, providerId, OPERATION);
} else {
bindArtifactFileCleanup(cause, error);
}
const completed = artifactFileCompletion(cause);
if (completed !== undefined) {
// The descriptor owner retains observations even when its final close fails.
const report = gpuCodeObjectsSchema.safeParse(completed.value);
if (report.success)
error.retainPartialObservation(
createGpuCodeObjectsEvidence(report.data, this.identity, input),
);
}
if (
error.partialObservation === undefined &&
progress !== undefined &&
progress.inventory.objects.length > 0
) {
const partial = gpuCodeObjectsPartialSchema.parse({
kind: "gpu-code-objects-partial",
artifact: {
path: input.path,
observed_file_size: progress.size,
sha256: null,
file_identity: "unverified",
},
analysis: input.analysis,
objects: progress.inventory.objects,
kernels: progress.inventory.kernels,
ptx_artifacts: progress.inventory.ptx_artifacts,
coverage: { discovery: "partial", payloads: "partial" },
limitations: [
...progress.inventory.limitations,
"Only completed declarations observed before interruption are retained. Root file identity and completeness were not verified; positional IDs are scoped to this interrupted observation.",
],
});
error.retainPartialObservation(
createGpuCodeObjectsPartialEvidence(partial, this.identity, input),
);
}
return err(error);
} finally {
this.#busy = false;
}
}
async #read(
file: FileHandle,
input: GpuCodeObjectsInput,
budgets: GpuCodeObjectsBudgets,
signal: AbortSignal | undefined,
retainProgress: (progress: {
inventory: GpuInventory;
size: number;
}) => void,
): Promise<GpuCodeObjects> {
const initial = await file.stat({ bigint: true });
const size = gpuCount(initial.size);
const source = new GpuFileSource(
file,
size,
signal,
budgets.maxObjectBytes,
);
const sha256 = await source.digest();
if (input.expected_sha256 !== undefined && sha256 !== input.expected_sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
input.path,
"GPU source does not match the inventory's selected SHA-256",
);
const inventory = new GpuInventory(input, signal);
retainProgress({ inventory, size });
const format = await inventory.inspect(source);
const after = await file.stat({ bigint: true });
const named = await lstat(input.path, { bigint: true }).catch(
(cause: unknown) => {
if (
cause instanceof Error &&
"code" in cause &&
["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code))
)
throw new ArtifactReaderFailure(
"integrity",
"Selected GPU path changed during inspection",
{ cause, integrityCheck: "container-identity" },
);
throw cause;
},
);
if ([after, named].some((state) => !sameRegularFileState(initial, state)))
throw new ArtifactReaderFailure(
"integrity",
"GPU source changed during inspection",
{ integrityCheck: "container-identity" },
);
const leaves = inventory.objects.filter(
(row) =>
row.kind !== "cuda-fatbin" &&
row.kind !== "hip-bundle" &&
row.kind !== "native-section" &&
row.kind !== "host",
);
return gpuCodeObjectsSchema.parse({
artifact: {
path: input.path,
file_size: size,
sha256,
bytes_read: source.bytesRead,
},
format,
analysis: input.analysis,
objects: inventory.objects,
kernels: inventory.kernels,
ptx_artifacts: inventory.ptx_artifacts,
coverage: {
discovery_scope: "supported-section-names-and-standalone-formats",
discovery: inventory.discovery,
payloads:
input.analysis === "inventory"
? "not-requested"
: leaves.every((row) => row.inspection === "complete") &&
inventory.discovery === "complete"
? "complete"
: "partial",
examined_sections: inventory.examined_sections,
unknown_section_names: inventory.unknown_section_names,
},
limitations: [
...inventory.limitations,
"Full-file SHA-256 streams every file byte; section and selected payload reads add to artifact.bytes_read. Retained Evidence is historical and never reopens the target.",
],
});
}
}