mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 19:03:31 +08:00
* feat(gpu)!: add per-call object, work, report, metadata, structure, and parser budgets to inspect_gpu_code_objects Replace the pending GPU object and parser ceilings in GpuCodeObjectsProvider with domain-owned optional per-call parameters (max_object_bytes, max_work_bytes, max_report_bytes, max_metadata_bytes, max_structure_bytes, max_parser_entries, max_parser_visits, and max_token_bytes) reporting details.limit and adjustable_budget, remove superseded hardcoded constants, and register only the recursive container and AMDGPU MessagePack nesting caps as a fixed representation allowance. BREAKING CHANGE: inspect_gpu_code_objects adds optional per-call budget parameters and reports details.limit with details.refusal.kind "adjustable_budget" instead of "fixed_ceiling" on top-level object, work, report, metadata, structure, and parser budget refusals. * fix(gpu): clamp padding scans, classify multi-frame CCOB budget cuts, and keep max_work_bytes at 512 MiB * fix(gpu): align --max-work-bytes help text, release partial decode before refill, and admit floats under small token budgets * test(gpu): keep multi-frame CCOB v1 decoded size within cut budgets * fix(gpu): report decoder inputExhausted to refill and bound trailing Zstandard frames * fix(gpu): peek next Zstd frame, charge AMD structure reads to work budget, and keep 128-token PTX limit * fix(gpu): fix CCOB refill work double-charge, meter section reads, decouple non-GPU recognition, and align frame/recovery bounds * refactor(gpu): drop redundant lookahead on non-refill path and pin refill/readBounded regressions * fix(gpu): keep standalone PTX peak heap at 1x, use explicit scan reads, forward CUDA cancel signal, and report max_report_bytes required_value * fix(gpu): report lower-bound report bytes in reported_limits and enforce max_token_bytes on recognized PTX headers
415 lines
14 KiB
TypeScript
415 lines
14 KiB
TypeScript
import {
|
|
readerIntegrityFailure,
|
|
ArtifactResourceScope,
|
|
ArtifactReaderFailure,
|
|
withArtifactRegularFile,
|
|
bindArtifactFileCleanup,
|
|
artifactFilePrimaryFacts,
|
|
artifactFileCancellationError,
|
|
artifactFileCompletion,
|
|
selectedFileTargetError,
|
|
} 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 { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.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";
|
|
|
|
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 { 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;
|
|
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 (isSelectedRegularFileError(primary))
|
|
error = selectedFileTargetError(input.path, primary, cause);
|
|
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 (for example, EMFILE).
|
|
else
|
|
error = new ProviderAdapterError(this.identity.id, OPERATION, {
|
|
cause,
|
|
diagnostics: {
|
|
path: input.path,
|
|
reason: errorMessage(primary),
|
|
},
|
|
});
|
|
if (
|
|
cause instanceof ArtifactReaderFailure &&
|
|
cause.cleanup !== undefined
|
|
) {
|
|
const cleanup = new ProviderCleanupError(
|
|
this.identity.id,
|
|
cause.cleanup.resources,
|
|
{ reason: cause.cleanup.reason },
|
|
{ cause, operation: OPERATION },
|
|
);
|
|
error = analysisErrorWithCleanupFailure(error, cleanup, OPERATION);
|
|
}
|
|
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),
|
|
);
|
|
}
|
|
bindArtifactFileCleanup(cause, error);
|
|
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.",
|
|
],
|
|
});
|
|
}
|
|
}
|