From 2e59f08992271b10bedfe92b1d39fdfa521d2d21 Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:14:15 -0500 Subject: [PATCH] feat(gpu)!: add per-call object, work, report, metadata, structure, and parser budgets to inspect_gpu_code_objects (#14882) * 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 --- docs/gpu-code-objects.md | 43 +- docs/reference/limits-and-recovery.md | 18 +- docs/reference/rea-limit-inventory.md | 12 + .../tools/inspect_gpu_code_objects.json | 2 +- scripts/verify/fixed-ceiling-registry.json | 14 +- src/cli/gpuCommands.ts | 32 + .../compression/zstandardExactFrame.test.ts | 72 +- src/domain/compression/zstandardExactFrame.ts | 98 +- src/domain/compression/zstandardFrameWire.ts | 62 +- src/domain/gpu/gpuCodeObjects.ts | 16 +- src/domain/gpu/gpuCodeObjectsBudgets.ts | 218 ++++ src/domain/gpu/gpuCodeObjectsEvidence.ts | 24 + src/gpu/AmdGpuMetadata.test.ts | 14 + src/gpu/AmdGpuMetadata.ts | 80 +- src/gpu/ClangOffloadBundle.ts | 69 +- src/gpu/CudaFatbinary.ts | 2 +- src/gpu/CudaInfo.ts | 52 +- src/gpu/GpuCodeObjectsProvider.ts | 113 +- src/gpu/GpuElfKernels.ts | 44 +- src/gpu/GpuInventory.ts | 533 +++++++- src/gpu/GpuPayloadCodec.test.ts | 44 +- src/gpu/GpuPayloadCodec.ts | 102 +- src/gpu/GpuSource.ts | 145 ++- src/gpu/PtxKernels.test.ts | 38 +- src/gpu/PtxKernels.ts | 257 +++- tests/acceptance/gpuCodeObjectsCli.test.ts | 119 ++ tests/boundary/gpu/codeObjects.test.ts | 1156 ++++++++++++++++- 27 files changed, 3108 insertions(+), 271 deletions(-) create mode 100644 src/domain/gpu/gpuCodeObjectsBudgets.ts diff --git a/docs/gpu-code-objects.md b/docs/gpu-code-objects.md index 54f8896ca5..ad89b8901b 100644 --- a/docs/gpu-code-objects.md +++ b/docs/gpu-code-objects.md @@ -189,8 +189,9 @@ Kernel representations have different meanings: that is not an array, are `malformed`. Note failures preserve earlier parsed declarations, including earlier pipelines, and the original failure reason. -Standalone PTX recognition scans up to 16 MiB, allowing leading comments and -whitespace, after which `.version` must be the first module token. Inventory and +Standalone PTX recognition scans up to `max_report_bytes` (default and maximum +16 MiB), allowing leading comments and whitespace, after which `.version` must +be the first module token. Inventory and kernel inspection use strict UTF-8 and reuse a complete, valid scan. Invalid encoding can leave a recognizable PTX object with an unknown target. A file longer than the scan budget, including one that ends mid-character at the @@ -250,23 +251,31 @@ workflow. Inventory then reads bounded native directories and bundle headers; CCOB requires decompression to find its inner directory. Kernel analysis reads selected payloads. `bytes_read` includes hashing and later descriptor reads. -| Resource | Limit | -| ---------------------------------------------------------------- | ------- | -| Active inspections | 1 | -| Each input or output buffer | 128 MiB | -| Payload input, decoded output and AMD note reads, per inspection | 512 MiB | -| Retained facts, including selected PTX | 16 MiB | -| Native tables; decoded section names (each) | 16 MiB | -| AMDGPU ELF note source bytes | 8 MiB | -| Standalone PTX recognition scan | 16 MiB | -| CUDA ELF record and symbol visits | 262,144 | -| CUDA ELF cumulative metadata section reads | 128 MiB | -| CUDA ELF temporary index facts (serialized-size accounting) | 16 MiB | -| Response page | 1 MiB | +| Resource | Default | Per-call parameter (range) | +| --------------------------------------------------------------------------------------------- | ------- | ----------------------------------- | +| Active inspections | 1 | Fixed (`measuredExhaustion`) | +| Each input or output buffer | 128 MiB | `max_object_bytes` (1..128 MiB) | +| Payload input, decoded output, native-section and AMDGPU note/structure reads, per inspection | 512 MiB | `max_work_bytes` (1..512 MiB) | +| Retained facts, including selected PTX and Clang directories | 16 MiB | `max_report_bytes` (1..16 MiB) | +| Native tables; decoded section names (each) | 16 MiB | `max_structure_bytes` (64..512 MiB) | +| AMDGPU ELF note source bytes | 8 MiB | `max_metadata_bytes` (1..8 MiB) | +| Standalone PTX recognition scan | 16 MiB | `max_report_bytes` (1..16 MiB) | +| Clang entries, PTX kernels/parameters, AMDGPU container entries | 65,536 | `max_parser_entries` (1..65,536) | +| Tokens per PTX parameter declaration | 128 | Fixed syntax limit | +| CUDA ELF record/symbol visits; AMDGPU aggregate values | 262,144 | `max_parser_visits` (1..262,144) | +| Clang bundle ID, PTX token, AMDGPU string/binary scalar | 65,536 | `max_token_bytes` (1..65,536) | +| CUDA ELF cumulative metadata section reads | 128 MiB | `max_object_bytes` (1..128 MiB) | +| CUDA ELF temporary index facts (serialized-size accounting) | 16 MiB | `max_report_bytes` (1..16 MiB) | +| Container / AMDGPU MessagePack nesting depth | 8 / 32 | Fixed (`representation` allowance) | +| Response page | 1 MiB | Fixed MCP response page budget | Payload work is reserved before reading or allocating, and a capacity refusal -does not reread an aliased payload. AMD note discovery also bounds depth and -container and string allocations, and shares one 262,144-value allowance across +does not reread an aliased payload. Top-level container/report/directory/ID +refusals fail with `code: "resource_constraint"` and `details.limit`, while +per-object payload/metadata/visit/nesting limits retain sibling observations and +record `inspection: "capacity"` with the budget name in `limitations`. AMD note +discovery also bounds depth and container and string allocations, and shares the +per-call `max_parser_visits` allowance (default and maximum 262,144) across all of a code object's notes, which also bounds the PAL pipeline facts expanded from them; standalone AMD targets are read from those notes before target selection, and kernel analysis reuses the parsed diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index fc3b575732..c635967727 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -90,6 +90,20 @@ Frida process discovery applies `limit` and `offset` after enumerating the selected device. It reports `total_processes` and `truncated`. Moving to another page runs a fresh discovery on that device. +`inspect_gpu_code_objects` accepts per-call budgets `max_object_bytes` (default +and maximum 128 MiB), `max_work_bytes` (default and maximum 512 MiB, covering +payload input, decoded output, native-section reads, and AMDGPU note/structure +reads), `max_report_bytes` (default and maximum 16 MiB), `max_metadata_bytes` +(default and maximum 8 MiB), `max_structure_bytes` (default 16 MiB, up to +512 MiB), `max_parser_entries` (default and maximum 65,536), +`max_parser_visits` (default and maximum 262,144), and `max_token_bytes` +(default and maximum 65,536). Top-level refusals report `details.limit` +(`control_kind: "parameter"`), per-object payload/metadata/visit limits retain +sibling observations with `inspection: "capacity"` naming the budget, and +recursive container/AMDGPU MessagePack nesting caps and the 128-token PTX +single-parameter syntax limit remain fixed ceilings; see +[GPU code objects](../gpu-code-objects.md#work-and-limits). + Graph tools accept per-call traversal bounds (`max_depth` and `max_nodes` on `get_call_graph` and `trace_call_path`). @@ -119,8 +133,8 @@ import and lambda rows combined; default 65,536, at most 1,048,576). ### Native table structure budget `inspect_elf_unwind_ranges`, `inspect_kernel_module`, `inspect_elf_debug_link`, -`inspect_dwarf_units`, `inspect_binary_hardening`, `inspect_native_initializers` -and `inspect_native_exports` accept `max_structure_bytes` (CLI +`inspect_dwarf_units`, `inspect_binary_hardening`, `inspect_native_initializers`, +`inspect_gpu_code_objects` and `inspect_native_exports` accept `max_structure_bytes` (CLI `--max-structure-bytes`, 64 bytes to 512 MiB, default 16 MiB). It bounds one header, section, load-command or ELF dynamic-directory table read, and, separately, the section names decoded from the section-name table, before the diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index f403615c48..4e4c106877 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -253,3 +253,15 @@ including IL2CPP's remaining allowances), [#14236](https://github.com/morluto/rea/issues/14236) (archive and container readers) and [#14237](https://github.com/morluto/rea/issues/14237) (producer output and capture). + +Additional `inspect_gpu_code_objects` per-call parameters (heap-bound allowances keep their existing ceilings): + +| Operation | Parameter | Default | Floor | Maximum | Owner | +| -------------------------- | -------------------- | --------: | ----: | --------: | ----------------------------------------- | +| `inspect_gpu_code_objects` | `max_object_bytes` | 134217728 | 1 | 134217728 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_work_bytes` | 536870912 | 1 | 536870912 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_report_bytes` | 16777216 | 1 | 16777216 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_metadata_bytes` | 8388608 | 1 | 8388608 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_parser_entries` | 65536 | 1 | 65536 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_parser_visits` | 262144 | 1 | 262144 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | +| `inspect_gpu_code_objects` | `max_token_bytes` | 65536 | 1 | 65536 | `src/domain/gpu/gpuCodeObjectsBudgets.ts` | diff --git a/scripts/verify/advertised-schemas/tools/inspect_gpu_code_objects.json b/scripts/verify/advertised-schemas/tools/inspect_gpu_code_objects.json index 2fbbcfa396..0e9c123aba 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_gpu_code_objects.json +++ b/scripts/verify/advertised-schemas/tools/inspect_gpu_code_objects.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "c1268fcea30658bc", + "input compact": "48e65025c05627f4", "output compact": "fc6c5d5a78a47254" }, "patterns": { diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json index de810419cf..b374a3d635 100644 --- a/scripts/verify/fixed-ceiling-registry.json +++ b/scripts/verify/fixed-ceiling-registry.json @@ -206,15 +206,13 @@ } }, "src/gpu/GpuCodeObjectsProvider.ts": { - "\"The GPU object allowance\"": { - "class": "pending", - "issue": 14235, - "reason": "The 128 MiB GPU object read allowance is a resource policy without a control." + "\"The GPU nesting allowance\"": { + "class": "representation", + "reason": "Bounds recursive GPU container nesting (8 levels in GpuInventory.ts) and AMDGPU MessagePack value nesting (32 levels in AmdGpuMetadata.ts) to prevent unbounded call-stack recursion." }, - "\"The GPU parser allowance\"": { - "class": "pending", - "issue": 14235, - "reason": "AMDGPU metadata, HIP bundle, CUDA and PTX decode allowances (8 MiB to 512 MiB, visit and token counts) are resource policies without a control." + "\"The GPU parser syntax allowance\"": { + "class": "representation", + "reason": "Fallback fixed parser syntax ceiling (such as 128 tokens per PTX parameter declaration) so unmapped parser BinaryResourceFailure values stay inside the Result error contract." } }, "src/ida/IdaMcpConnection.ts": { diff --git a/src/cli/gpuCommands.ts b/src/cli/gpuCommands.ts index 9e3ec4ca31..3a9e69de90 100644 --- a/src/cli/gpuCommands.ts +++ b/src/cli/gpuCommands.ts @@ -51,6 +51,38 @@ export const registerGpuCommands = (cli: CliInstance, logger: Logger): void => { targets: { description: "JSON array of exact target declarations to decode", }, + max_object_bytes: { + description: + "Maximum bytes per GPU object read or decoded buffer (default and maximum 134217728)", + }, + max_work_bytes: { + description: + "Maximum aggregate payload input, decoded output, native-section, and AMDGPU note/structure bytes per inspection (default and maximum 536870912)", + }, + max_report_bytes: { + description: + "Maximum bytes for retained GPU report facts, PTX text, Clang directories, and CUDA temporary indexes (default and maximum 16777216)", + }, + max_metadata_bytes: { + description: + "Maximum AMDGPU ELF note and MessagePack metadata bytes (default and maximum 8388608)", + }, + max_structure_bytes: { + description: + "Maximum bytes of one native ELF/PE section table or decoded section names (default 16777216, up to 536870912)", + }, + max_parser_entries: { + description: + "Maximum entries per Clang bundle directory, PTX kernel/parameter list, or AMDGPU container (default and maximum 65536)", + }, + max_parser_visits: { + description: + "Maximum aggregate CUDA record/symbol visits or AMDGPU MessagePack values per code object (default and maximum 262144)", + }, + max_token_bytes: { + description: + "Maximum bytes per Clang bundle ID, PTX token, or AMDGPU MessagePack scalar (default and maximum 65536)", + }, view: { description: "JSON GPU object/kernel/PTX page selection; requires --detail summary and --evidence_output", diff --git a/src/domain/compression/zstandardExactFrame.test.ts b/src/domain/compression/zstandardExactFrame.test.ts index 9595291add..af947e8aeb 100644 --- a/src/domain/compression/zstandardExactFrame.test.ts +++ b/src/domain/compression/zstandardExactFrame.test.ts @@ -164,7 +164,7 @@ describe("exact Zstandard frames", () => { ).toMatchObject({ ok: false, reason: "truncated_frame_header" }); }); - it("stops a prefix at the first non-frame byte", async () => { + it("stops a prefix at the first non-frame byte and reports inputExhausted", async () => { const frame = rawFrame(0x61); const suffix = Buffer.from("CCOB"); const input = Buffer.concat([frame, suffix]); @@ -174,11 +174,81 @@ describe("exact Zstandard frames", () => { bytes: Buffer.from("a"), consumedBytes: frame.length, frames: 1, + inputExhausted: false, }; expect(decodeZstandardFrames(input, options)).toMatchObject(expected); await expect( decodeZstandardFramesCooperative(input, options, async () => {}), ).resolves.toMatchObject(expected); + + // Frame-boundary EOF and 1-3 byte magic prefixes report inputExhausted: true; + // definite 1-3 byte non-magic suffixes report inputExhausted: false. + for (const tail of [ + Buffer.alloc(0), + Buffer.of(0x28), + Buffer.of(0x28, 0xb5), + Buffer.of(0x28, 0xb5, 0x2f), + Buffer.of(0x50), + Buffer.of(0x5f, 0x2a), + Buffer.of(0x50, 0x2a, 0x4d), + ]) { + const sample = Buffer.concat([frame, tail]); + const expectedExhausted = { + ok: true, + consumedBytes: frame.length, + inputExhausted: true, + }; + expect(decodeZstandardFrames(sample, options)).toMatchObject( + expectedExhausted, + ); + await expect( + decodeZstandardFramesCooperative(sample, options, async () => {}), + ).resolves.toMatchObject(expectedExhausted); + } + for (const nonMagic of [ + Buffer.of(0x00), + Buffer.of(0x43, 0x43), + Buffer.of(0x28, 0xb5, 0x00), + Buffer.of(0x50, 0x2a, 0x00), + ]) { + const sample = Buffer.concat([frame, nonMagic]); + const expectedComplete = { + ok: true, + consumedBytes: frame.length, + inputExhausted: false, + }; + expect(decodeZstandardFrames(sample, options)).toMatchObject( + expectedComplete, + ); + await expect( + decodeZstandardFramesCooperative(sample, options, async () => {}), + ).resolves.toMatchObject(expectedComplete); + } + // At the maxFrames cap in prefix mode, distinguish a partial magic prefix from non-magic trailing bytes. + const oneFrameOptions = { + mode: "prefix", + allowance: allowance(1, "runtime"), + } as const; + expect( + decodeZstandardFrames( + Buffer.concat([frame, Buffer.of(0x28, 0xb5)]), + oneFrameOptions, + ), + ).toMatchObject({ + ok: true, + consumedBytes: frame.length, + inputExhausted: true, + }); + expect( + decodeZstandardFrames( + Buffer.concat([frame, Buffer.of(0x43, 0x43)]), + oneFrameOptions, + ), + ).toMatchObject({ + ok: true, + consumedBytes: frame.length, + inputExhausted: false, + }); }); it("refuses 65536 productive frames on the work allowance", () => { diff --git a/src/domain/compression/zstandardExactFrame.ts b/src/domain/compression/zstandardExactFrame.ts index 43070ed97c..12c31de2c2 100644 --- a/src/domain/compression/zstandardExactFrame.ts +++ b/src/domain/compression/zstandardExactFrame.ts @@ -18,9 +18,11 @@ import { } from "./zstandardFrameAllowance.js"; import { ZSTANDARD_MAGIC_BYTES, - zstandardFrameKind, + ZSTANDARD_TRUNCATION_REASONS, + zstandardFrameMagicStatus, zstandardFrameReads, type ZstandardFrameKind, + type ZstandardTruncationReason, } from "./zstandardFrameWire.js"; /** Zstandard's default maximum decoder window, 2^27 bytes (128 MiB). */ @@ -31,9 +33,7 @@ export const ZSTANDARD_WINDOW_LOG_MAX = 27; * evidence that the bytes are malformed. */ export const ZSTANDARD_FRAME_REASONS = [ - "truncated_frame_header", - "truncated_block", - "truncated_checksum", + ...ZSTANDARD_TRUNCATION_REASONS, "trailing_bytes", "work_limit", "malformed", @@ -43,6 +43,15 @@ export const ZSTANDARD_FRAME_REASONS = [ export type ZstandardFrameReason = (typeof ZSTANDARD_FRAME_REASONS)[number]; +const ZSTANDARD_TRUNCATION_REASON_SET: ReadonlySet = + new Set(ZSTANDARD_TRUNCATION_REASONS); + +/** True when framing ended before the end of the Zstandard frame rather than on corrupt bytes. */ +export const isZstandardTruncationReason = ( + reason: ZstandardFrameReason, +): reason is ZstandardTruncationReason => + ZSTANDARD_TRUNCATION_REASON_SET.has(reason); + export type ZstandardFrameMode = "exact" | "prefix"; export interface ZstandardDecodeOptions { @@ -84,6 +93,18 @@ export interface ZstandardFrameSuccess { readonly bytes: Buffer; readonly consumedBytes: number; readonly frames: number; + /** + * True when the walk stopped because the supplied input ended at a frame + * boundary or inside a 1-3 byte prefix of a possible next Zstandard/skippable + * frame magic, rather than on definite non-frame trailing bytes. + */ + readonly inputExhausted: boolean; + /** + * Present when `inputExhausted` is true and the walk already admitted + * `allowance.maxFrames` frames, so any following Zstandard/skippable frame + * would exceed `zstd.max_frames`. + */ + readonly frameAllowanceReached?: ZstandardFrameAllowance; } export type ZstandardFrameResult = @@ -100,6 +121,8 @@ interface WalkSuccess { readonly ok: true; readonly frames: readonly FrameSpan[]; readonly consumed: number; + readonly inputExhausted: boolean; + readonly frameAllowanceReached?: ZstandardFrameAllowance; } // Bound structural work between cooperative pauses, including across frames. @@ -168,30 +191,49 @@ function* walkFrames( const frames: FrameSpan[] = []; const progress = { reads: 0 }; let offset = 0; + let inputExhausted = false; while (offset < bytes.length) { - const kind = zstandardFrameKind(bytes, offset); + const status = zstandardFrameMagicStatus(bytes, offset); if (frames.length === allowance.maxFrames) { - if (kind !== undefined) return workLimit(allowance, offset); + if (status === "zstd" || status === "skippable") + return workLimit(allowance, offset); if (mode === "exact") return failure("trailing_bytes", offset); + inputExhausted = status === "incomplete"; break; } - if (offset + ZSTANDARD_MAGIC_BYTES > bytes.length) { + if (status === "incomplete") { if (frames.length === 0) return failure("truncated_frame_header", offset); if (mode === "exact") return failure("trailing_bytes", offset); + inputExhausted = true; break; } - if (kind === undefined) { - if (frames.length === 0) return failure("malformed", offset, "magic"); + if (status === "none") { + if (frames.length === 0) { + if (offset + ZSTANDARD_MAGIC_BYTES > bytes.length) + return failure("truncated_frame_header", offset); + return failure("malformed", offset, "magic"); + } if (mode === "exact") return failure("trailing_bytes", offset); break; } - const next = yield* frameAt(bytes, offset, kind, progress); + const next = yield* frameAt(bytes, offset, status, progress); if ("ok" in next) return next; frames.push(next); offset += next.length; } if (frames.length === 0) return failure("truncated_frame_header", 0); - return { ok: true, frames, consumed: offset }; + if (offset === bytes.length) inputExhausted = true; + const frameAllowanceReached = + inputExhausted && frames.length === allowance.maxFrames + ? allowance + : undefined; + return { + ok: true, + frames, + consumed: offset, + inputExhausted, + ...(frameAllowanceReached === undefined ? {} : { frameAllowanceReached }), + }; } const decoderFailure = ( @@ -346,6 +388,8 @@ const finishFrames = ( chunks: readonly Buffer[], consumed: number, frames: number, + inputExhausted: boolean, + frameAllowanceReached?: ZstandardFrameAllowance, ): ZstandardFrameSuccess => { const only = chunks.length === 1 ? chunks[0] : undefined; return { @@ -358,6 +402,8 @@ const finishFrames = ( : Buffer.concat(chunks), consumedBytes: consumed, frames, + inputExhausted, + ...(frameAllowanceReached === undefined ? {} : { frameAllowanceReached }), }; }; @@ -365,6 +411,8 @@ const decodeFrames = ( bytes: Uint8Array, frames: readonly FrameSpan[], consumed: number, + inputExhausted: boolean, + frameAllowanceReached: ZstandardFrameAllowance | undefined, options: DecompressOptions, ): ZstandardFrameSuccess | ZstandardFrameFailure => { if (options.rejectTrailing) { @@ -377,6 +425,8 @@ const decodeFrames = ( [ownedZstandardBytes(bounded.bytes)], consumed, frames.length, + inputExhausted, + frameAllowanceReached, ), }; } @@ -389,7 +439,13 @@ const decodeFrames = ( total += step.bytes.length; chunks.push(step.bytes); } - return finishFrames(chunks, consumed, frames.length); + return finishFrames( + chunks, + consumed, + frames.length, + inputExhausted, + frameAllowanceReached, + ); }; /** @@ -401,6 +457,8 @@ const decodeFrames = ( interface PreparedDecode { readonly frames: readonly FrameSpan[]; readonly consumed: number; + readonly inputExhausted: boolean; + readonly frameAllowanceReached?: ZstandardFrameAllowance; readonly options: DecompressOptions; } @@ -425,6 +483,10 @@ function* prepareDecode( return { frames: walked.frames, consumed: walked.consumed, + inputExhausted: walked.inputExhausted, + ...(walked.frameAllowanceReached === undefined + ? {} + : { frameAllowanceReached: walked.frameAllowanceReached }), options: { maxOutputLength: options.maxOutputLength ?? bufferConstants.MAX_LENGTH, windowLogMax: options.windowLogMax ?? ZSTANDARD_WINDOW_LOG_MAX, @@ -455,6 +517,8 @@ export const decodeZstandardFrames = ( bytes, prepared.frames, prepared.consumed, + prepared.inputExhausted, + prepared.frameAllowanceReached, prepared.options, ); }; @@ -499,6 +563,8 @@ export const decodeZstandardFramesCooperative = async ( [bounded.bytes], prepared.consumed, prepared.frames.length, + prepared.inputExhausted, + prepared.frameAllowanceReached, ); } const chunks: Buffer[] = []; @@ -512,5 +578,11 @@ export const decodeZstandardFramesCooperative = async ( chunks.push(step.bytes); } await pause(); - return finishFrames(chunks, prepared.consumed, prepared.frames.length); + return finishFrames( + chunks, + prepared.consumed, + prepared.frames.length, + prepared.inputExhausted, + prepared.frameAllowanceReached, + ); }; diff --git a/src/domain/compression/zstandardFrameWire.ts b/src/domain/compression/zstandardFrameWire.ts index bc13387131..68ab29ba18 100644 --- a/src/domain/compression/zstandardFrameWire.ts +++ b/src/domain/compression/zstandardFrameWire.ts @@ -1,19 +1,25 @@ const ZSTD_MAGIC = 0xfd2fb528; +const ZSTD_MAGIC_BYTES = [0x28, 0xb5, 0x2f, 0xfd] as const; const SKIPPABLE_MAGIC_MIN = 0x184d2a50; const SKIPPABLE_MAGIC_MAX = 0x184d2a5f; +const SKIPPABLE_MAGIC_REST = [0x2a, 0x4d, 0x18] as const; export const ZSTANDARD_MAGIC_BYTES = 4; export type ZstandardFrameKind = "zstd" | "skippable"; -type Truncation = - | "truncated_frame_header" - | "truncated_block" - | "truncated_checksum"; +export const ZSTANDARD_TRUNCATION_REASONS = [ + "truncated_frame_header", + "truncated_block", + "truncated_checksum", +] as const; + +export type ZstandardTruncationReason = + (typeof ZSTANDARD_TRUNCATION_REASONS)[number]; export interface ZstandardFrameRead { readonly length: number; readonly inspect: boolean; - readonly eof: Truncation; + readonly eof: ZstandardTruncationReason; readonly failureOffset: number; } @@ -27,16 +33,50 @@ const u24 = (bytes: Uint8Array, offset: number): number => const u32 = (bytes: Uint8Array, offset: number): number => (u24(bytes, offset) | ((bytes[offset + 3] ?? 0) << 24)) >>> 0; +export type ZstandardFrameMagicStatus = + | ZstandardFrameKind + | "incomplete" + | "none"; + +/** + * Inspect the next 4-byte Zstandard or skippable frame magic at `offset`, + * distinguishing a complete frame magic, an incomplete 0-3 byte magic prefix + * that could continue with more input, and a definite non-frame byte sequence. + */ +export const zstandardFrameMagicStatus = ( + bytes: Uint8Array, + offset: number, +): ZstandardFrameMagicStatus => { + const remaining = bytes.length - offset; + if (remaining <= 0) return "incomplete"; + if (remaining >= ZSTANDARD_MAGIC_BYTES) { + const magic = u32(bytes, offset); + if (magic === ZSTD_MAGIC) return "zstd"; + if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) + return "skippable"; + return "none"; + } + let matchesZstd = true; + for (let index = 0; index < remaining; index += 1) + if (bytes[offset + index] !== ZSTD_MAGIC_BYTES[index]) { + matchesZstd = false; + break; + } + if (matchesZstd) return "incomplete"; + const first = bytes[offset]!; + if (first < 0x50 || first > 0x5f) return "none"; + for (let index = 1; index < remaining; index += 1) + if (bytes[offset + index] !== SKIPPABLE_MAGIC_REST[index - 1]) + return "none"; + return "incomplete"; +}; + export const zstandardFrameKind = ( bytes: Uint8Array, offset: number, ): ZstandardFrameKind | undefined => { - if (bytes.length - offset < ZSTANDARD_MAGIC_BYTES) return undefined; - const magic = u32(bytes, offset); - if (magic === ZSTD_MAGIC) return "zstd"; - if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) - return "skippable"; - return undefined; + const status = zstandardFrameMagicStatus(bytes, offset); + return status === "zstd" || status === "skippable" ? status : undefined; }; /** diff --git a/src/domain/gpu/gpuCodeObjects.ts b/src/domain/gpu/gpuCodeObjects.ts index 166f2acc47..685fb91816 100644 --- a/src/domain/gpu/gpuCodeObjects.ts +++ b/src/domain/gpu/gpuCodeObjects.ts @@ -6,6 +6,7 @@ import { localPathStringSchema, } from "../localPath.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; +import { gpuCodeObjectsBudgetFields } from "./gpuCodeObjectsBudgets.js"; const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); /** * GPU inventories report known coverage: discovery, note and payload @@ -512,6 +513,7 @@ export const inspectGpuCodeObjectsInputSchema = z .describe( "Decode only exact target declarations, preserving all inventory rows", ), + ...gpuCodeObjectsBudgetFields, detail: z.enum(["summary", "complete"]).default("summary"), view: gpuCodeObjectsSelectionSchema.optional(), }) @@ -535,5 +537,17 @@ export type GpuKernel = z.infer; export type GpuLocation = z.infer; export type GpuCodeObjectsInput = Pick< z.infer, - "path" | "analysis" | "object_ids" | "targets" | "expected_sha256" + | "path" + | "analysis" + | "object_ids" + | "targets" + | "expected_sha256" + | "max_object_bytes" + | "max_work_bytes" + | "max_report_bytes" + | "max_metadata_bytes" + | "max_structure_bytes" + | "max_parser_entries" + | "max_parser_visits" + | "max_token_bytes" >; diff --git a/src/domain/gpu/gpuCodeObjectsBudgets.ts b/src/domain/gpu/gpuCodeObjectsBudgets.ts new file mode 100644 index 0000000000..b5756892f2 --- /dev/null +++ b/src/domain/gpu/gpuCodeObjectsBudgets.ts @@ -0,0 +1,218 @@ +import { z } from "zod"; +import type { AnalysisParameterLimit } from "../analysisSettings.js"; +import { NATIVE_STRUCTURE_LIMIT } from "../binaryContainer.js"; +import { maxStructureBytesSchema } from "../native/nativeStructureBudget.js"; + +export const DEFAULT_GPU_OBJECT_BYTES = 128 * 1024 * 1024; +const DEFAULT_GPU_WORK_BYTES = 512 * 1024 * 1024; +export const DEFAULT_GPU_REPORT_BYTES = 16 * 1024 * 1024; +export const DEFAULT_GPU_METADATA_BYTES = 8 * 1024 * 1024; +export const DEFAULT_GPU_PARSER_ENTRIES = 65_536; +export const DEFAULT_GPU_PARSER_VISITS = 262_144; +export const DEFAULT_GPU_TOKEN_BYTES = 65_536; + +export const GPU_CONTAINER_NESTING_LIMIT = "gpu-container-nesting-depth"; +export const GPU_AMD_METADATA_DEPTH_LIMIT = "amdgpu-metadata-depth"; +export const GPU_OBJECT_BYTES_LIMIT = "gpu-object-bytes"; +export const GPU_WORK_BYTES_LIMIT = "gpu-work-bytes"; +export const GPU_METADATA_BYTES_LIMIT = "gpu-metadata-bytes"; +export const GPU_PARSER_ENTRIES_LIMIT = "gpu-parser-entries"; +export const GPU_PARSER_VISITS_LIMIT = "gpu-parser-visits"; +export const GPU_TOKEN_BYTES_LIMIT = "gpu-token-bytes"; +export const GPU_RETAINED_REPORT_BYTES_LIMIT = "gpu-retained-report-bytes"; +const GPU_HIP_BUNDLE_ENTRIES_LIMIT = "hip-bundle-entries"; +const GPU_HIP_BUNDLE_ID_BYTES_LIMIT = "hip-bundle-id-bytes"; +const GPU_HIP_BUNDLE_DIRECTORY_BYTES_LIMIT = "hip-bundle-directory-bytes"; +const GPU_AMD_METADATA_VALUES_LIMIT = "amdgpu-metadata-values"; + +const GPU_CODE_OBJECTS_BUDGETS = { + max_object_bytes: { + minimum: 1, + maximum: DEFAULT_GPU_OBJECT_BYTES, + default_value: DEFAULT_GPU_OBJECT_BYTES, + unit: "bytes", + }, + max_work_bytes: { + minimum: 1, + maximum: DEFAULT_GPU_WORK_BYTES, + default_value: DEFAULT_GPU_WORK_BYTES, + unit: "bytes", + }, + max_report_bytes: { + minimum: 1, + maximum: DEFAULT_GPU_REPORT_BYTES, + default_value: DEFAULT_GPU_REPORT_BYTES, + unit: "bytes", + }, + max_metadata_bytes: { + minimum: 1, + maximum: DEFAULT_GPU_METADATA_BYTES, + default_value: DEFAULT_GPU_METADATA_BYTES, + unit: "bytes", + }, + max_parser_entries: { + minimum: 1, + maximum: DEFAULT_GPU_PARSER_ENTRIES, + default_value: DEFAULT_GPU_PARSER_ENTRIES, + unit: "count", + }, + max_parser_visits: { + minimum: 1, + maximum: DEFAULT_GPU_PARSER_VISITS, + default_value: DEFAULT_GPU_PARSER_VISITS, + unit: "count", + }, + max_token_bytes: { + minimum: 1, + maximum: DEFAULT_GPU_TOKEN_BYTES, + default_value: DEFAULT_GPU_TOKEN_BYTES, + unit: "bytes", + }, +} as const; + +type GpuCodeObjectsBudgetParameter = keyof typeof GPU_CODE_OBJECTS_BUDGETS; + +/** Optional per-call budget fields for `inspect_gpu_code_objects`. */ +export const gpuCodeObjectsBudgetFields = { + max_object_bytes: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_object_bytes.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_object_bytes.maximum) + .optional() + .describe( + `Maximum bytes for one GPU object buffer read or decoded payload, legacy CCOB v1 recovery scan, or cumulative CUDA ELF metadata reads (default ${String(DEFAULT_GPU_OBJECT_BYTES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_object_bytes.maximum)})`, + ), + max_work_bytes: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_work_bytes.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_work_bytes.maximum) + .optional() + .describe( + `Maximum aggregate payload input, decoded output, native-section, and AMDGPU note/structure read bytes per inspection (default ${String(DEFAULT_GPU_WORK_BYTES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_work_bytes.maximum)})`, + ), + max_report_bytes: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_report_bytes.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_report_bytes.maximum) + .optional() + .describe( + `Maximum bytes for retained GPU report facts, standalone or embedded PTX text, Clang offload bundle directories, and CUDA temporary indexes (default ${String(DEFAULT_GPU_REPORT_BYTES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_report_bytes.maximum)})`, + ), + max_metadata_bytes: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_metadata_bytes.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_metadata_bytes.maximum) + .optional() + .describe( + `Maximum AMDGPU ELF note discovery and MessagePack metadata bytes (default ${String(DEFAULT_GPU_METADATA_BYTES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_metadata_bytes.maximum)})`, + ), + max_structure_bytes: maxStructureBytesSchema, + max_parser_entries: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_parser_entries.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_parser_entries.maximum) + .optional() + .describe( + `Maximum entries per Clang offload bundle directory, PTX kernel/parameter list, or AMDGPU MessagePack container (default ${String(DEFAULT_GPU_PARSER_ENTRIES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_parser_entries.maximum)})`, + ), + max_parser_visits: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_parser_visits.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_parser_visits.maximum) + .optional() + .describe( + `Maximum aggregate CUDA ELF metadata record/symbol visits or AMDGPU MessagePack values per code object (default ${String(DEFAULT_GPU_PARSER_VISITS)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_parser_visits.maximum)})`, + ), + max_token_bytes: z + .number() + .int() + .min(GPU_CODE_OBJECTS_BUDGETS.max_token_bytes.minimum) + .max(GPU_CODE_OBJECTS_BUDGETS.max_token_bytes.maximum) + .optional() + .describe( + `Maximum bytes for one Clang offload bundle ID, PTX token, or AMDGPU MessagePack string/binary scalar (default ${String(DEFAULT_GPU_TOKEN_BYTES)}, up to ${String(GPU_CODE_OBJECTS_BUDGETS.max_token_bytes.maximum)})`, + ), +} as const; + +/** Effective per-inspection GPU budgets after applying defaults to omitted fields. */ +export interface GpuCodeObjectsBudgets { + readonly maxObjectBytes: number; + readonly maxWorkBytes: number; + readonly maxReportBytes: number; + readonly maxMetadataBytes: number; + readonly maxStructureBytes: number | undefined; + readonly maxParserEntries: number; + readonly maxParserVisits: number; + readonly maxTokenBytes: number; +} + +export const resolveGpuCodeObjectsBudgets = (input: { + readonly max_object_bytes?: number | undefined; + readonly max_work_bytes?: number | undefined; + readonly max_report_bytes?: number | undefined; + readonly max_metadata_bytes?: number | undefined; + readonly max_structure_bytes?: number | undefined; + readonly max_parser_entries?: number | undefined; + readonly max_parser_visits?: number | undefined; + readonly max_token_bytes?: number | undefined; +}): GpuCodeObjectsBudgets => ({ + maxObjectBytes: input.max_object_bytes ?? DEFAULT_GPU_OBJECT_BYTES, + maxWorkBytes: input.max_work_bytes ?? DEFAULT_GPU_WORK_BYTES, + maxReportBytes: input.max_report_bytes ?? DEFAULT_GPU_REPORT_BYTES, + maxMetadataBytes: input.max_metadata_bytes ?? DEFAULT_GPU_METADATA_BYTES, + maxStructureBytes: input.max_structure_bytes, + maxParserEntries: input.max_parser_entries ?? DEFAULT_GPU_PARSER_ENTRIES, + maxParserVisits: input.max_parser_visits ?? DEFAULT_GPU_PARSER_VISITS, + maxTokenBytes: input.max_token_bytes ?? DEFAULT_GPU_TOKEN_BYTES, +}); + +export const formatGpuByteBudget = (bytes: number): string => + bytes % (1024 * 1024) === 0 + ? `${String(bytes / (1024 * 1024))} MiB` + : `${String(bytes)}-byte`; + +export const gpuBudgetParameterForLimit = ( + name: string, +): GpuCodeObjectsBudgetParameter | "max_structure_bytes" | undefined => { + if (name === NATIVE_STRUCTURE_LIMIT) return "max_structure_bytes"; + if (name === GPU_WORK_BYTES_LIMIT) return "max_work_bytes"; + if (name === GPU_OBJECT_BYTES_LIMIT) return "max_object_bytes"; + if (name === GPU_METADATA_BYTES_LIMIT) return "max_metadata_bytes"; + if ( + name === GPU_HIP_BUNDLE_ENTRIES_LIMIT || + name === GPU_PARSER_ENTRIES_LIMIT + ) + return "max_parser_entries"; + if ( + name === GPU_AMD_METADATA_VALUES_LIMIT || + name === GPU_PARSER_VISITS_LIMIT + ) + return "max_parser_visits"; + if (name === GPU_HIP_BUNDLE_ID_BYTES_LIMIT || name === GPU_TOKEN_BYTES_LIMIT) + return "max_token_bytes"; + if ( + name === GPU_RETAINED_REPORT_BYTES_LIMIT || + name === GPU_HIP_BUNDLE_DIRECTORY_BYTES_LIMIT + ) + return "max_report_bytes"; + return undefined; +}; + +export const gpuCodeObjectsBudgetLimit = ( + parameter: GpuCodeObjectsBudgetParameter, + effectiveValue: number, + requiredValue?: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter, + effective_value: effectiveValue, + ...GPU_CODE_OBJECTS_BUDGETS[parameter], + applies_at: "next_call", + ...(requiredValue === undefined ? {} : { required_value: requiredValue }), +}); diff --git a/src/domain/gpu/gpuCodeObjectsEvidence.ts b/src/domain/gpu/gpuCodeObjectsEvidence.ts index 0b0b4ceb79..e84256d043 100644 --- a/src/domain/gpu/gpuCodeObjectsEvidence.ts +++ b/src/domain/gpu/gpuCodeObjectsEvidence.ts @@ -20,6 +20,30 @@ const gpuParameters = (parameters: GpuCodeObjectsInput) => ({ ...(parameters.expected_sha256 === undefined ? {} : { expected_sha256: parameters.expected_sha256 }), + ...(parameters.max_object_bytes === undefined + ? {} + : { max_object_bytes: parameters.max_object_bytes }), + ...(parameters.max_work_bytes === undefined + ? {} + : { max_work_bytes: parameters.max_work_bytes }), + ...(parameters.max_report_bytes === undefined + ? {} + : { max_report_bytes: parameters.max_report_bytes }), + ...(parameters.max_metadata_bytes === undefined + ? {} + : { max_metadata_bytes: parameters.max_metadata_bytes }), + ...(parameters.max_structure_bytes === undefined + ? {} + : { max_structure_bytes: parameters.max_structure_bytes }), + ...(parameters.max_parser_entries === undefined + ? {} + : { max_parser_entries: parameters.max_parser_entries }), + ...(parameters.max_parser_visits === undefined + ? {} + : { max_parser_visits: parameters.max_parser_visits }), + ...(parameters.max_token_bytes === undefined + ? {} + : { max_token_bytes: parameters.max_token_bytes }), }); /** One Evidence interpretation for success and observations retained by file finalization failures. */ diff --git a/src/gpu/AmdGpuMetadata.test.ts b/src/gpu/AmdGpuMetadata.test.ts index 4f2ec3e2e2..cc8705d666 100644 --- a/src/gpu/AmdGpuMetadata.test.ts +++ b/src/gpu/AmdGpuMetadata.test.ts @@ -193,3 +193,17 @@ it("accepts non-negative signed MessagePack integer keys and rejects negative or ), ).toThrow(expect.objectContaining({ kind: "unsupported" })); }); + +it("admits float32 and float64 scalars under a small maxTokenBytes budget", () => { + const float64Map = Buffer.from([ + 0x81, 0xa1, 0x61, 0xcb, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]); + expect( + readAmdMetadata(float64Map, "string", undefined, { + maxMetadataBytes: 1024, + maxParserVisits: 100, + maxParserEntries: 100, + maxTokenBytes: 4, + }), + ).toEqual({ a: 1.5 }); +}); diff --git a/src/gpu/AmdGpuMetadata.ts b/src/gpu/AmdGpuMetadata.ts index c1364847ef..fa99dff454 100644 --- a/src/gpu/AmdGpuMetadata.ts +++ b/src/gpu/AmdGpuMetadata.ts @@ -5,20 +5,26 @@ import { BinaryResourceFailure, BinaryFormatFailure, } from "../domain/binaryContainer.js"; +import { + DEFAULT_GPU_METADATA_BYTES, + DEFAULT_GPU_PARSER_ENTRIES, + DEFAULT_GPU_PARSER_VISITS, + DEFAULT_GPU_TOKEN_BYTES, + GPU_METADATA_BYTES_LIMIT, + GPU_PARSER_ENTRIES_LIMIT, + GPU_TOKEN_BYTES_LIMIT, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; import { rejectGpu } from "./GpuSource.js"; import { isRecord } from "../kernel/isRecord.js"; -export const AMD_METADATA_BYTES = 8 * 1024 * 1024; const AMD_METADATA_DEPTH = 32; -const AMD_METADATA_VALUES = 262144; -const AMD_METADATA_CONTAINER_ENTRIES = 65536; -const AMD_METADATA_VALUE_BYTES = 65536; -const metadataValueLimit = () => +const metadataValueLimit = (maxValues: number) => new BinaryResourceFailure( "structure", - AMD_METADATA_VALUES, - `AMDGPU metadata exceeds its ${String(AMD_METADATA_VALUES)}-value aggregate allowance`, + maxValues, + `AMDGPU metadata exceeds its ${String(maxValues)}-value aggregate allowance`, "amdgpu-metadata-values", "entries", ); @@ -42,6 +48,11 @@ const preflight = ( bytes: Buffer, keyKinds: AmdMetadataKeys, budget: AmdMetadataValueBudget, + limits: { + readonly maxValues: number; + readonly maxContainerEntries: number; + readonly maxValueBytes: number; + }, ): Set => { const strings = new Set(); const reader = new BinaryReader(bytes, false, "amdgpu-metadata"); @@ -64,7 +75,7 @@ const preflight = ( `AMDGPU metadata exceeds its ${String(AMD_METADATA_DEPTH)}-level nesting allowance`, "amdgpu-metadata-depth", ); - if (++values > AMD_METADATA_VALUES) throw metadataValueLimit(); + if (++values > limits.maxValues) throw metadataValueLimit(limits.maxValues); const code = bytes[take(1)]!; const string = (code & 0xe0) === 0xa0 || code === 0xd9 || code === 0xda || code === 0xdb; @@ -108,6 +119,7 @@ const preflight = ( payload = width!; } const start = take(payload); + if (code === 0xca || code === 0xcb) return undefined; if (code >= 0xcc && code <= 0xcf) return code === 0xcf ? BigInt.asUintN(64, reader.i64(start)) @@ -135,19 +147,24 @@ const preflight = ( // its type. Impossible extents are malformed independently of limits. if (count > bytes.length - at) rejectGpu("Truncated AMDGPU MessagePack metadata container"); - if ((map ? count / 2 : count) > AMD_METADATA_CONTAINER_ENTRIES) + if ((map ? count / 2 : count) > limits.maxContainerEntries) throw new BinaryResourceFailure( "structure", - AMD_METADATA_CONTAINER_ENTRIES, - `AMDGPU metadata container exceeds its ${String(AMD_METADATA_CONTAINER_ENTRIES)}-entry allocation budget`, + limits.maxContainerEntries, + `AMDGPU metadata container exceeds its ${String(limits.maxContainerEntries)}-entry allocation budget`, + GPU_PARSER_ENTRIES_LIMIT, + "entries", ); - if (payload > AMD_METADATA_VALUE_BYTES) + if (payload > limits.maxValueBytes) throw new BinaryResourceFailure( "structure", - AMD_METADATA_VALUE_BYTES, - `AMDGPU metadata value exceeds its ${String(AMD_METADATA_VALUE_BYTES)}-byte allocation budget`, + limits.maxValueBytes, + `AMDGPU metadata value exceeds its ${String(limits.maxValueBytes)}-byte allocation budget`, + GPU_TOKEN_BYTES_LIMIT, + "bytes", ); - if (count > AMD_METADATA_VALUES - values) throw metadataValueLimit(); + if (count > limits.maxValues - values) + throw metadataValueLimit(limits.maxValues); if (string) { strings.add(`${bytes.byteOffset + start}:${payload}`); try { @@ -189,14 +206,31 @@ export const readAmdMetadata = ( bytes: Buffer, keys: AmdMetadataKeys = "string", budget = new AmdMetadataValueBudget(), + budgets?: Pick< + GpuCodeObjectsBudgets, + | "maxMetadataBytes" + | "maxParserVisits" + | "maxParserEntries" + | "maxTokenBytes" + >, ): unknown => { - if (bytes.length > AMD_METADATA_BYTES) + const maxMetadataBytes = + budgets?.maxMetadataBytes ?? DEFAULT_GPU_METADATA_BYTES; + const limits = { + maxValues: budgets?.maxParserVisits ?? DEFAULT_GPU_PARSER_VISITS, + maxContainerEntries: + budgets?.maxParserEntries ?? DEFAULT_GPU_PARSER_ENTRIES, + maxValueBytes: budgets?.maxTokenBytes ?? DEFAULT_GPU_TOKEN_BYTES, + }; + if (bytes.length > maxMetadataBytes) throw new BinaryResourceFailure( "structure", - AMD_METADATA_BYTES, - "AMDGPU metadata exceeds 8 MiB", + maxMetadataBytes, + `AMDGPU metadata exceeds ${String(maxMetadataBytes)} bytes`, + GPU_METADATA_BYTES_LIMIT, + "bytes", ); - const strings = preflight(bytes, keys, budget); + const strings = preflight(bytes, keys, budget, limits); const stringValue = (value: unknown): string => { if ( !(value instanceof Uint8Array) || @@ -245,10 +279,10 @@ export const readAmdMetadata = ( return rejectGpu("AMDGPU metadata map key is not a string"); }, useBigInt64: true, - maxStrLength: AMD_METADATA_VALUE_BYTES, - maxBinLength: AMD_METADATA_VALUE_BYTES, - maxArrayLength: AMD_METADATA_CONTAINER_ENTRIES, - maxMapLength: AMD_METADATA_CONTAINER_ENTRIES, + maxStrLength: limits.maxValueBytes, + maxBinLength: limits.maxValueBytes, + maxArrayLength: limits.maxContainerEntries, + maxMapLength: limits.maxContainerEntries, maxExtLength: 0, }), ); diff --git a/src/gpu/ClangOffloadBundle.ts b/src/gpu/ClangOffloadBundle.ts index 1923e1487c..6dd6cfaa38 100644 --- a/src/gpu/ClangOffloadBundle.ts +++ b/src/gpu/ClangOffloadBundle.ts @@ -8,9 +8,16 @@ import { } from "../domain/binaryContainer.js"; import { assertArtifactReadActive } from "../resources/index.js"; import { + DEFAULT_GPU_OBJECT_BYTES, + DEFAULT_GPU_PARSER_ENTRIES, + DEFAULT_GPU_REPORT_BYTES, + DEFAULT_GPU_TOKEN_BYTES, + GPU_OBJECT_BYTES_LIMIT, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; +import { + CONTAINER_SCAN_CHUNK_BYTES, gpuCount, - GPU_OBJECT_BYTES, - GPU_REPORT_BYTES, rejectGpu, type GpuSource, } from "./GpuSource.js"; @@ -24,16 +31,21 @@ export const CLANG_BUNDLE_MAGIC = Buffer.from("__CLANG_OFFLOAD_BUNDLE__"); export const CCOB_MAGIC = Buffer.from("CCOB"); const CLANG_BUNDLE_HEADER_BYTES = 32; const CLANG_BUNDLE_ENTRY_BYTES = 24; -const CLANG_BUNDLE_MAX_ENTRIES = 65_536; -const CLANG_BUNDLE_MAX_ID_BYTES = 65_536; export const readClangBundleDirectory = async ( source: GpuSource, base: number, signal?: AbortSignal, + budgets?: Pick< + GpuCodeObjectsBudgets, + "maxParserEntries" | "maxTokenBytes" | "maxReportBytes" + >, ): Promise<{ declarations: { object: GpuObject; amdTarget: AmdGpuTargetIdentity | null }[]; end: number; }> => { + const maxEntries = budgets?.maxParserEntries ?? DEFAULT_GPU_PARSER_ENTRIES; + const maxIdBytes = budgets?.maxTokenBytes ?? DEFAULT_GPU_TOKEN_BYTES; + const maxDirectoryBytes = budgets?.maxReportBytes ?? DEFAULT_GPU_REPORT_BYTES; const header = await source.read(base, CLANG_BUNDLE_HEADER_BYTES); if (!header.subarray(0, CLANG_BUNDLE_MAGIC.length).equals(CLANG_BUNDLE_MAGIC)) rejectGpu("Invalid Clang offload bundle magic"); @@ -51,17 +63,17 @@ export const readClangBundleDirectory = async ( ) rejectGpu("Clang offload bundle directory is truncated"); const count = gpuCount(declaredCount); - if (count > CLANG_BUNDLE_MAX_ENTRIES) + if (count > maxEntries) throw new BinaryResourceFailure( "structure", - CLANG_BUNDLE_MAX_ENTRIES, + maxEntries, "HIP bundle entry count exceeds the inventory budget", "hip-bundle-entries", "entries", ); // One wrapper/identity per admitted entry. Processor text is // no longer than its admitted name; cumulative name bytes remain - // within the 16 MiB directory bound before identities are allocated. + // within the retained report directory budget before identities are allocated. const declarations: { object: GpuObject; amdTarget: AmdGpuTargetIdentity | null; @@ -100,18 +112,18 @@ export const readClangBundleDirectory = async ( if (minimumDirectoryEnd > firstPayload) rejectGpu("HIP entry overlaps its bundle directory"); const nameSize = Number(rawNameSize); - if (nameSize > CLANG_BUNDLE_MAX_ID_BYTES) + if (nameSize > maxIdBytes) throw new BinaryResourceFailure( "structure", - CLANG_BUNDLE_MAX_ID_BYTES, - `HIP bundle ID exceeds ${String(CLANG_BUNDLE_MAX_ID_BYTES)} bytes`, + maxIdBytes, + `HIP bundle ID exceeds ${String(maxIdBytes)} bytes`, "hip-bundle-id-bytes", "bytes", ); - if (nameOffset - base + nameSize > GPU_REPORT_BYTES) + if (nameOffset - base + nameSize > maxDirectoryBytes) throw new BinaryResourceFailure( "structure", - GPU_REPORT_BYTES, + maxDirectoryBytes, "HIP bundle directory exceeds its retained byte budget", "hip-bundle-directory-bytes", "bytes", @@ -185,25 +197,42 @@ export const readCcobHeader = (bytes: Buffer, remaining: number) => { export const findLegacyCcobRecoveryTotal = async ( source: GpuSource, base: number, + maxObjectBytes: number = DEFAULT_GPU_OBJECT_BYTES, ): Promise => { - const searchEnd = Math.min(source.size, base + GPU_OBJECT_BYTES); + const maxStart = Math.min(source.size, base + maxObjectBytes); + // Read up to 4 bytes past `maxStart` so a valid following CCOB magic starting + // at `base + maxObjectBytes` (when the corrupt v1 extent equals maxObjectBytes) + // is still observed without admitting markers starting beyond `maxStart`. + const searchEnd = Math.min(source.size, maxStart + CCOB_MAGIC.length); + const maxChunk = Math.max( + 1, + Math.min(CONTAINER_SCAN_CHUNK_BYTES, maxObjectBytes), + ); let position = base + 20; const seam = Buffer.allocUnsafe(6); let tailLen = 0; while (position < searchEnd) { const bytes = await source.read( position, - Math.min(64 * 1024, searchEnd - position), + Math.min(maxChunk, searchEnd - position), ); if (bytes.length === 0) break; if (tailLen > 0) { const headLen = Math.min(3, bytes.length); bytes.copy(seam, tailLen, 0, headLen); const seamIndex = seam.subarray(0, tailLen + headLen).indexOf("CCOB"); - if (seamIndex >= 0) return position - tailLen + seamIndex - base; + if (seamIndex >= 0) { + const matchOffset = position - tailLen + seamIndex; + if (matchOffset <= maxStart) return matchOffset - base; + break; + } } const index = bytes.indexOf("CCOB"); - if (index >= 0) return position + index - base; + if (index >= 0) { + const matchOffset = position + index; + if (matchOffset <= maxStart) return matchOffset - base; + break; + } if (bytes.length >= 3) { bytes.copy(seam, 0, bytes.length - 3, bytes.length); tailLen = 3; @@ -221,11 +250,13 @@ export const findLegacyCcobRecoveryTotal = async ( } position += bytes.length; } - if (searchEnd < source.size) + if (maxStart < source.size) throw new BinaryResourceFailure( "structure", - GPU_OBJECT_BYTES, - "Legacy CCOB v1 extent exceeds the 128 MiB decoding budget", + maxObjectBytes, + `Legacy CCOB v1 extent exceeds the ${String(maxObjectBytes)}-byte decoding budget`, + GPU_OBJECT_BYTES_LIMIT, + "bytes", ); return source.size - base; }; diff --git a/src/gpu/CudaFatbinary.ts b/src/gpu/CudaFatbinary.ts index 2d574ef4cc..6d387b06f9 100644 --- a/src/gpu/CudaFatbinary.ts +++ b/src/gpu/CudaFatbinary.ts @@ -94,6 +94,6 @@ export async function* readCudaFatbinary( yield { row, declaredDecodedSize }; position += width + padded; } - base = await nextGpuContainerOffset(source, end); + base = await nextGpuContainerOffset(source, end, signal); } } diff --git a/src/gpu/CudaInfo.ts b/src/gpu/CudaInfo.ts index 304a79953c..c54eccd464 100644 --- a/src/gpu/CudaInfo.ts +++ b/src/gpu/CudaInfo.ts @@ -2,24 +2,50 @@ import { BinaryReader, BinaryResourceFailure, } from "../domain/binaryContainer.js"; -import { GPU_OBJECT_BYTES, GPU_REPORT_BYTES, rejectGpu } from "./GpuSource.js"; +import { + DEFAULT_GPU_OBJECT_BYTES, + DEFAULT_GPU_PARSER_VISITS, + DEFAULT_GPU_REPORT_BYTES, + GPU_OBJECT_BYTES_LIMIT, + GPU_PARSER_VISITS_LIMIT, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; +import { rejectGpu } from "./GpuSource.js"; import { Budget } from "../domain/budget.js"; import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; import type { JsonValue } from "../domain/jsonValue.js"; /** Shared by every metadata record, symbol and temporary index in one CUDA ELF. */ export class CudaMetadataBudget { - readonly #visits = new Budget(262144); - readonly #readBytes = new Budget(GPU_OBJECT_BYTES); - readonly #indexBytes = new Budget(GPU_REPORT_BYTES); + readonly #maxVisits: number; + readonly #maxReadBytes: number; + readonly #maxIndexBytes: number; + readonly #visits: Budget; + readonly #readBytes: Budget; + readonly #indexBytes: Budget; + constructor( + budgets?: Pick< + GpuCodeObjectsBudgets, + "maxParserVisits" | "maxObjectBytes" | "maxReportBytes" + >, + ) { + this.#maxVisits = budgets?.maxParserVisits ?? DEFAULT_GPU_PARSER_VISITS; + this.#maxReadBytes = budgets?.maxObjectBytes ?? DEFAULT_GPU_OBJECT_BYTES; + this.#maxIndexBytes = budgets?.maxReportBytes ?? DEFAULT_GPU_REPORT_BYTES; + this.#visits = new Budget(this.#maxVisits); + this.#readBytes = new Budget(this.#maxReadBytes); + this.#indexBytes = new Budget(this.#maxIndexBytes); + } visit(): void { this.#visits.charge( 1, () => new BinaryResourceFailure( "structure", - 262144, - "CUDA metadata exceeds 262144 aggregate record/symbol visits", + this.#maxVisits, + `CUDA metadata exceeds ${String(this.#maxVisits)} aggregate record/symbol visits`, + GPU_PARSER_VISITS_LIMIT, + "entries", ), ); } @@ -29,19 +55,23 @@ export class CudaMetadataBudget { () => new BinaryResourceFailure( "structure", - GPU_OBJECT_BYTES, - "CUDA metadata exceeds 128 MiB aggregate section reads", + this.#maxReadBytes, + `CUDA metadata exceeds ${String(this.#maxReadBytes)}-byte aggregate section reads`, + GPU_OBJECT_BYTES_LIMIT, + "bytes", ), ); } retain(value: JsonValue): void { this.#indexBytes.charge( - jsonValueByteLength(value, GPU_REPORT_BYTES) + 2, + jsonValueByteLength(value, this.#maxIndexBytes) + 2, () => new BinaryResourceFailure( "structure", - GPU_REPORT_BYTES, - "CUDA metadata exceeds the 16 MiB temporary index budget", + this.#maxIndexBytes, + `CUDA metadata exceeds the ${String(this.#maxIndexBytes)}-byte temporary index budget`, + "gpu-retained-report-bytes", + "bytes", ), ); } diff --git a/src/gpu/GpuCodeObjectsProvider.ts b/src/gpu/GpuCodeObjectsProvider.ts index d738adc939..d658d3a9e6 100644 --- a/src/gpu/GpuCodeObjectsProvider.ts +++ b/src/gpu/GpuCodeObjectsProvider.ts @@ -46,15 +46,20 @@ import { BinaryResourceFailure, binaryResourceCeiling, } from "../domain/binaryContainer.js"; +import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; +import { nativeStructureLimit } from "../domain/native/nativeStructureBudget.js"; import { - fixedAllowanceOptions, - fixedProducerInputAllowance, -} from "../domain/fixedAllowanceRemediation.js"; + GPU_AMD_METADATA_DEPTH_LIMIT, + GPU_CONTAINER_NESTING_LIMIT, + gpuBudgetParameterForLimit, + gpuCodeObjectsBudgetLimit, + resolveGpuCodeObjectsBudgets, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; import { GpuFileSource, + GpuReportCapacityFailure, gpuCount, - GPU_OBJECT_BYTES, - GPU_REPORT_BYTES, } from "./GpuSource.js"; import { GpuInventory } from "./GpuInventory.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; @@ -66,6 +71,58 @@ 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; @@ -102,6 +159,7 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { ), ); this.#busy = true; + const budgets = resolveGpuCodeObjectsBudgets(input); let progress: { inventory: GpuInventory; size: number } | undefined; try { return ok( @@ -111,7 +169,7 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { this.#resources, options?.signal, ({ handle: file }) => - this.#read(file, input, options?.signal, (value) => { + this.#read(file, input, budgets, options?.signal, (value) => { progress = value; }), ), @@ -141,17 +199,7 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { ) error = primary; else if (primary instanceof BinaryResourceFailure) - error = parseLimitConstraint(OPERATION, "memory", primary, { - reportedLimitContext: { - maximum_object_bytes: GPU_OBJECT_BYTES, - maximum_report_bytes: GPU_REPORT_BYTES, - }, - ...fixedAllowanceOptions( - "The GPU parser allowance", - "parser", - binaryResourceCeiling(primary), - ), - }); + error = gpuResourceConstraint(primary, budgets); else if (formatFailure !== undefined) error = formatFailure; else if ( origin === "owned-or-classified" && @@ -184,20 +232,33 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { 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: GPU_OBJECT_BYTES }, + { + maximum_object_bytes: budgets.maxObjectBytes, + ...(primary.observedBytes === undefined + ? {} + : { required: String(primary.observedBytes) }), + }, { cause: primary, - ...fixedProducerInputAllowance( - GPU_OBJECT_BYTES, - "The GPU object allowance", + 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, { @@ -265,6 +326,7 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { async #read( file: FileHandle, input: GpuCodeObjectsInput, + budgets: GpuCodeObjectsBudgets, signal: AbortSignal | undefined, retainProgress: (progress: { inventory: GpuInventory; @@ -273,7 +335,12 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { ): Promise { const initial = await file.stat({ bigint: true }); const size = gpuCount(initial.size); - const source = new GpuFileSource(file, size, signal); + 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( diff --git a/src/gpu/GpuElfKernels.ts b/src/gpu/GpuElfKernels.ts index 5dbd227022..5ca087ac50 100644 --- a/src/gpu/GpuElfKernels.ts +++ b/src/gpu/GpuElfKernels.ts @@ -46,7 +46,12 @@ import { type GpuSource, } from "./GpuSource.js"; import { - AMD_METADATA_BYTES, + DEFAULT_GPU_METADATA_BYTES, + GPU_METADATA_BYTES_LIMIT, + formatGpuByteBudget, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; +import { AmdMetadataValueBudget, amdCount, amdRecord, @@ -124,6 +129,7 @@ export const readGpuElfKernels = async ( pause: ZstandardFramePause, preparedAmd?: AmdElfMetadata, onTarget?: (target: GpuPayloadTarget) => void, + budgets?: GpuCodeObjectsBudgets, ): Promise<{ limitations: string[]; coverage: "complete" | "partial"; @@ -132,14 +138,20 @@ export const readGpuElfKernels = async ( return amdKernels(source, preparedAmd, onKernel, onTarget); const directory = await readGpuNativeDirectory( source, - readElfSectionDirectory(source.size), + readElfSectionDirectory( + source.size, + budgets?.maxStructureBytes === undefined + ? undefined + : { structureBytes: budgets.maxStructureBytes }, + ), pause, + budgets?.maxStructureBytes, ); if (directory.machine !== (kind === "cubin" ? 190 : 224)) rejectGpu("GPU entry kind disagrees with ELF machine"); if (kind === "cubin") { onTarget?.(readCudaTarget(source, directory)); - const coverage = await cudaKernels(source, directory, onKernel); + const coverage = await cudaKernels(source, directory, onKernel, budgets); return { coverage, limitations: [ @@ -156,7 +168,7 @@ export const readGpuElfKernels = async ( ], }; } - const metadata = await readAmdElfMetadata(source, directory); + const metadata = await readAmdElfMetadata(source, directory, budgets); const parsed = amdKernels( source, metadata.ok ? metadata.value : metadata.error.partial, @@ -169,11 +181,12 @@ export const readGpuElfKernels = async ( const indexCudaMetadata = async ( source: GpuSource, directory: NativeSectionDirectory, + budgets?: GpuCodeObjectsBudgets, ) => { const infosByText = new Map(), sharedByText = new Map(); const registerFacts = new Map>(); - const budget = new CudaMetadataBudget(), + const budget = new CudaMetadataBudget(budgets), seenMetadata = new Set(); for (const row of directory.sections) { const map = @@ -302,8 +315,9 @@ const cudaKernels = async ( source: GpuSource, directory: NativeSectionDirectory, onKernel: (kernel: GpuKernel) => void, + budgets?: GpuCodeObjectsBudgets, ): Promise<"complete" | "partial"> => { - const index = await indexCudaMetadata(source, directory); + const index = await indexCudaMetadata(source, directory, budgets); const extendedTables = new ElfSymbolSectionIndexTables(directory.sections); let complete = index.allNamesKnown; let symbolTables = 0; @@ -457,12 +471,21 @@ const legacyAmdNoteLimitation = (abi: AmdGpuAbi, type: number) => export const readAmdElfMetadata = async ( source: GpuSource, directory: NativeSectionDirectory, + budgets?: Pick< + GpuCodeObjectsBudgets, + | "maxMetadataBytes" + | "maxParserVisits" + | "maxParserEntries" + | "maxTokenBytes" + >, ): Promise< Result< AmdElfMetadata, { kind: "incomplete-amd-metadata"; cause: unknown; partial: AmdElfMetadata } > > => { + const maxMetadataBytes = + budgets?.maxMetadataBytes ?? DEFAULT_GPU_METADATA_BYTES; const limitations: string[] = []; const notes: AmdElfMetadata["notes"] = []; let retainedBytes = 0; @@ -550,11 +573,13 @@ export const readAmdElfMetadata = async ( for (const section of directory.sections) { if (elfNoteSectionStorage(section) === "not-note") continue; const sectionSize = gpuCount(section.size); - if (sectionSize > AMD_METADATA_BYTES - retainedBytes) + if (sectionSize > maxMetadataBytes - retainedBytes) throw new BinaryResourceFailure( "structure", - AMD_METADATA_BYTES, - "AMDGPU ELF note discovery exceeds the 8 MiB retained metadata budget", + maxMetadataBytes, + `AMDGPU ELF note discovery exceeds the ${formatGpuByteBudget(maxMetadataBytes)} retained metadata budget`, + GPU_METADATA_BYTES_LIMIT, + "bytes", ); retainedBytes += sectionSize; const bytes = await sectionBytes(source, section); @@ -591,6 +616,7 @@ export const readAmdElfMetadata = async ( // PAL register maps are keyed by unsigned register offsets. pal === null ? "string" : "string-or-unsigned", valueBudget, + budgets, ), ); if (metadata === null) rejectGpu("AMDGPU metadata is not a map"); diff --git a/src/gpu/GpuInventory.ts b/src/gpu/GpuInventory.ts index c8828883f0..cc3f0175dc 100644 --- a/src/gpu/GpuInventory.ts +++ b/src/gpu/GpuInventory.ts @@ -21,11 +21,20 @@ import { } from "./GpuObject.js"; import { readCudaTarget } from "./CudaTarget.js"; import { readCudaFatbinary } from "./CudaFatbinary.js"; -import { decodeGpuPayload, decodeGpuPayloadStream } from "./GpuPayloadCodec.js"; +import { + decodeGpuPayload, + decodeGpuPayloadStream, + isTruncatedGpuPayloadFailure, +} from "./GpuPayloadCodec.js"; import { projectZstandardFrameAllowance, ZstandardFrameAllowanceError, + type ZstandardFrameAllowance, } from "../domain/compression/zstandardFrameAllowance.js"; +import { + ZSTANDARD_MAGIC_BYTES, + zstandardFrameKind, +} from "../domain/compression/zstandardFrameWire.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { createHash } from "node:crypto"; import { scheduler } from "node:timers/promises"; @@ -35,6 +44,7 @@ import { BinaryResourceFailure, hasElfMagic, isBinaryStringReadLimit, + NATIVE_STRUCTURE_LIMIT, } from "../domain/binaryContainer.js"; import { hasDosMzMagic } from "../domain/dosMz.js"; import { @@ -49,10 +59,9 @@ import { import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { + CONTAINER_SCAN_CHUNK_BYTES, GpuBufferSource, checkGpuRange, - GPU_OBJECT_BYTES, - GPU_REPORT_BYTES, GpuReportCapacityFailure, gpuCount, nextGpuContainerOffset, @@ -60,6 +69,16 @@ import { rejectGpu, type GpuSource, } from "./GpuSource.js"; +import { + DEFAULT_GPU_REPORT_BYTES, + GPU_CONTAINER_NESTING_LIMIT, + GPU_OBJECT_BYTES_LIMIT, + GPU_WORK_BYTES_LIMIT, + formatGpuByteBudget, + gpuBudgetParameterForLimit, + resolveGpuCodeObjectsBudgets, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; import { sha256Hex } from "../kernel/sha256Hex.js"; import { readGpuElfKernels, @@ -68,6 +87,7 @@ import { } from "./GpuElfKernels.js"; import { createPtxTargetTracker, + createPtxVersionScanner, ptxTargetIdentity, readPtxKernels, readPtxTarget, @@ -90,6 +110,17 @@ const readPtxText = ( } }; +interface MeteredGpuSource extends GpuSource { + /** Read for format recognition: charges aggregate work without enforcing max_object_bytes. */ + readWorkOnly?( + offset: number, + size: number, + maximumBytes: number, + ): Promise; + /** Read bytes whose object and work budgets were already reserved by the caller. */ + readPrecharged?(offset: number, size: number): Promise; +} + /** File declarations only. Every child range stays in its named parent coordinate space. */ export class GpuInventory { readonly objects: GpuObject[] = []; @@ -108,23 +139,44 @@ export class GpuInventory { GpuObject, string | AmdGpuTargetIdentity | null >(); + readonly #meteredSources = new WeakSet(); readonly #selectedObjects: ReadonlySet | undefined; readonly #selectedTargets: ReadonlySet | undefined; + readonly #budgets: GpuCodeObjectsBudgets; constructor( readonly input: GpuCodeObjectsInput, readonly signal?: AbortSignal, ) { + this.#budgets = resolveGpuCodeObjectsBudgets(input); this.#selectedObjects = input.object_ids === undefined ? undefined : new Set(input.object_ids); this.#selectedTargets = input.targets === undefined ? undefined : new Set(input.targets); - this.#retain({ path: input.path, limitations: this.limitations }); - this.#factBytes += 1024; + const headerBytes = + jsonValueByteLength( + { path: input.path, limitations: this.limitations }, + DEFAULT_GPU_REPORT_BYTES, + ) + 2; + const baselineRequired = headerBytes + 1024; + if (baselineRequired > this.#budgets.maxReportBytes) + throw new GpuReportCapacityFailure( + this.#budgets.maxReportBytes, + baselineRequired, + ); + this.#factBytes = baselineRequired; } #retain(value: JsonValue): void { - const bytes = jsonValueByteLength(value, GPU_REPORT_BYTES); - if (bytes + 2 > GPU_REPORT_BYTES - this.#factBytes) - throw new GpuReportCapacityFailure(); + const bytes = jsonValueByteLength(value, this.#budgets.maxReportBytes); + if (bytes + 2 > this.#budgets.maxReportBytes - this.#factBytes) { + const required = + bytes <= this.#budgets.maxReportBytes + ? this.#factBytes + bytes + 2 + : undefined; + throw new GpuReportCapacityFailure( + this.#budgets.maxReportBytes, + required, + ); + } this.#factBytes += bytes + 2; } #add(row: GpuObject, amdTarget?: AmdGpuTargetIdentity | null): void { @@ -148,20 +200,80 @@ export class GpuInventory { this.#retain(messages); row.limitations.push(...messages); } - /** Reserve input/output work atomically, before any payload allocation or read. */ - #budgetWork(...sizes: (number | bigint)[]): void { + /** Reserve aggregate work bytes without enforcing max_object_bytes (used for structure reads bounded by max_structure_bytes). */ + #reserveWork(...sizes: (number | bigint)[]): void { let workBytes = this.#workBytes; + const { maxWorkBytes } = this.#budgets; for (const size of sizes) { - if (size > Math.min(GPU_OBJECT_BYTES, 512 * 1024 * 1024 - workBytes)) + if (size > maxWorkBytes - workBytes) { + const workLabel = + maxWorkBytes % (1024 * 1024) === 0 + ? `${String(maxWorkBytes / (1024 * 1024))} MiB` + : `${String(maxWorkBytes)} bytes`; throw new BinaryResourceFailure( "structure", - GPU_OBJECT_BYTES, - "GPU reads/decoding exceed 128 MiB per buffer or 512 MiB per inspection", + maxWorkBytes, + `GPU reads/decoding exceed ${workLabel} per inspection`, + GPU_WORK_BYTES_LIMIT, + "bytes", ); + } workBytes += Number(size); } this.#workBytes = workBytes; } + /** Verify that every single-buffer read/decode size fits within max_object_bytes. */ + #checkObjectBytes(...sizes: (number | bigint)[]): void { + const { maxObjectBytes } = this.#budgets; + for (const size of sizes) { + if (size > maxObjectBytes) + throw new BinaryResourceFailure( + "structure", + maxObjectBytes, + `GPU read/decoding buffer exceeds the ${String(maxObjectBytes)}-byte object budget`, + GPU_OBJECT_BYTES_LIMIT, + "bytes", + ); + } + } + /** Reserve input/output work atomically, before any payload allocation or read. */ + #budgetWork(...sizes: (number | bigint)[]): void { + this.#checkObjectBytes(...sizes); + this.#reserveWork(...sizes); + } + /** Read a format-recognition chunk without enforcing max_object_bytes or borrowing NATIVE_STRUCTURE_LIMIT. */ + #readRecognitionChunk( + source: MeteredGpuSource, + offset: number, + size: number, + maximumBytes: number, + ): Promise { + if (source.readWorkOnly !== undefined) + return source.readWorkOnly(offset, size, maximumBytes); + if (source.readBounded !== undefined) + return source.readBounded(offset, size, maximumBytes); + return source.read(offset, size); + } + /** + * Atomically verify and reserve work for a read of `readBytes` plus `extra` + * (such as decoded output), avoiding double-charging `readBytes` when + * `source` itself meters every underlying read. + */ + #reserveReadWork( + source: GpuSource, + readBytes: number, + ...extra: (number | bigint)[] + ): void { + if (!this.#meteredSources.has(source)) { + this.#budgetWork(readBytes, ...extra); + return; + } + const previous = this.#workBytes; + this.#budgetWork(readBytes, ...extra); + // `source.read` will charge `readBytes` when it executes; retain only `extra`. + this.#workBytes = previous; + if (extra.length > 0) this.#reserveWork(...extra); + } #selected(row: GpuObject): boolean { return ( (this.#selectedObjects === undefined || @@ -171,7 +283,7 @@ export class GpuInventory { ); } async inspect( - source: GpuSource, + source: MeteredGpuSource, depth = 0, ): Promise { assertArtifactReadActive(this.signal); @@ -180,8 +292,15 @@ export class GpuInventory { "structure", 8, "GPU container nesting exceeds eight levels", + GPU_CONTAINER_NESTING_LIMIT, ); - const prefix = await source.read(0, Math.min(32, source.size)); + const prefixLength = Math.min(32, source.size); + const prefix = await this.#readRecognitionChunk( + source, + 0, + prefixLength, + 32, + ); if (prefix.subarray(0, 4).equals(Buffer.from([0x50, 0xed, 0x55, 0xba]))) { await this.#cuda(source); return "cuda-fatbin"; @@ -201,9 +320,18 @@ export class GpuInventory { const directory = await readGpuNativeDirectory( source, elf - ? readElfSectionDirectory(source.size) - : readPeSectionDirectory(source.size), + ? readElfSectionDirectory( + source.size, + this.#budgets.maxStructureBytes === undefined + ? undefined + : { structureBytes: this.#budgets.maxStructureBytes }, + ) + : readPeSectionDirectory( + source.size, + this.#budgets.maxStructureBytes, + ), () => yieldArtifactRead(this.signal), + this.#budgets.maxStructureBytes, ); if (elf && (directory.machine === 190 || directory.machine === 224)) { const row = gpuObject(source, { @@ -219,6 +347,7 @@ export class GpuInventory { await this.#amdPayload(source, row, directory); else await this.#payload(source, row); } else { + const parentMetered = this.#meteredSources.has(source); for (const section of directory.sections) { this.examined_sections++; if (section.name === null) { @@ -236,14 +365,6 @@ export class GpuInventory { } const offset = gpuCount(section.offset), size = gpuCount(section.size); - const borrowed: GpuSource = { - size, - containerId: source.containerId, - read: (start, length) => { - checkGpuRange(size, start, length); - return source.read(offset + start, length); - }, - }; // A section is a coordinate space with an explicit physical backing, including PE short names. const row = gpuObject(source, { offset: offset, @@ -262,7 +383,54 @@ export class GpuInventory { row.location.section_index = section.index; row.location.section_name = section.name; this.#add(row); - const sectionSource: GpuSource = { ...borrowed, containerId: row.id }; + const sectionSource: MeteredGpuSource = { + size, + containerId: row.id, + maxObjectBytes: this.#budgets.maxObjectBytes, + read: (start, length) => { + checkGpuRange(size, start, length, this.#budgets.maxObjectBytes); + if (!parentMetered) this.#budgetWork(length); + return source.read(offset + start, length); + }, + readBounded: (start, length, maximumBytes, limitName) => { + checkGpuRange(size, start, length, maximumBytes, limitName); + if (!parentMetered) { + if (limitName === NATIVE_STRUCTURE_LIMIT) + this.#reserveWork(length); + else this.#budgetWork(length); + } + return source.readBounded !== undefined + ? source.readBounded( + offset + start, + length, + maximumBytes, + limitName, + ) + : source.read(offset + start, length); + }, + readWorkOnly: (start, length, maximumBytes) => { + checkGpuRange(size, start, length, maximumBytes); + if (!parentMetered) this.#reserveWork(length); + if (source.readWorkOnly !== undefined) + return source.readWorkOnly( + offset + start, + length, + maximumBytes, + ); + return source.readBounded !== undefined + ? source.readBounded(offset + start, length, maximumBytes) + : source.read(offset + start, length); + }, + readPrecharged: (start, length) => { + checkGpuRange(size, start, length, size); + if (source.readPrecharged !== undefined) + return source.readPrecharged(offset + start, length); + return source.readBounded !== undefined + ? source.readBounded(offset + start, length, size) + : source.read(offset + start, length); + }, + }; + this.#meteredSources.add(sectionSource); try { await this.inspect(sectionSource, depth + 1); row.inspection = "complete"; @@ -275,12 +443,77 @@ export class GpuInventory { return directory.format; } // PTX is positively identified by its directives, never by extension or arbitrary embedded text. - const probe = await source.read(0, Math.min(source.size, GPU_REPORT_BYTES)); + // Recognize the leading `.version .` header incrementally without retaining + // chunks so non-GPU inputs fail with unsupported_target and peak heap stays at 1x probeSize. + const probeSize = Math.min(source.size, this.#budgets.maxReportBytes); + const scanner = createPtxVersionScanner(); + let firstPiece: Buffer | undefined; + let scanned = 0; + let verdict: "yes" | "no" | "incomplete" = "incomplete"; + let chunkLimit = 4096; + while (scanned < probeSize && verdict === "incomplete") { + if (scanned > 0) await yieldArtifactRead(this.signal); + const want = Math.min(chunkLimit, probeSize - scanned); + const piece = await this.#readRecognitionChunk( + source, + scanned, + want, + CONTAINER_SCAN_CHUNK_BYTES, + ); + firstPiece = scanned === 0 ? piece : undefined; + scanned += piece.length; + verdict = scanner.feed(piece); + chunkLimit = CONTAINER_SCAN_CHUNK_BYTES; + } + if (verdict === "incomplete" && scanned === source.size) + verdict = scanner.finish(); + if (verdict === "no") { + firstPiece = undefined; + throw new BinaryFormatFailure( + "unsupported", + "No supported CUDA/HIP container or PTX declarations were identified", + ); + } + if (verdict === "incomplete") { + firstPiece = undefined; + throw new BinaryResourceFailure( + "structure", + this.#budgets.maxReportBytes, + `Standalone text recognition exceeds the ${String(this.#budgets.maxReportBytes)}-byte PTX budget before a target was established`, + "gpu-retained-report-bytes", + "bytes", + ); + } + let probe: Buffer; + const metered = this.#meteredSources.has(source); + if (firstPiece !== undefined && scanned === probeSize) { + // Single <= 4 KiB read already holds the complete probe buffer. + this.#checkObjectBytes(probeSize); + if (!metered) this.#reserveWork(probeSize); + probe = firstPiece; + firstPiece = undefined; + } else { + // Release the recognition chunk before reading into one probe-sized buffer + // so peak heap remains 1x max_report_bytes rather than 2x. + firstPiece = undefined; + this.#checkObjectBytes(probeSize); + const remainingWork = metered + ? Math.max(0, probeSize - scanned) + : probeSize; + if (remainingWork > 0) this.#reserveWork(remainingWork); + probe = + metered && source.readPrecharged !== undefined + ? await source.readPrecharged(0, probeSize) + : await source.read(0, probeSize); + } const complete = probe.length === source.size; const text = readPtxText(probe, complete ? "complete" : "prefix"); // Replacement decoding may identify a malformed candidate. Only strict // text can establish its target or become retained PTX text evidence. - const targetFacts = readPtxTarget(text ?? probe.toString("utf8")); + const targetFacts = readPtxTarget( + text ?? probe.toString("utf8"), + this.#budgets.maxTokenBytes, + ); if (targetFacts.recognized) { const row = gpuObject(source, { offset: 0, @@ -290,7 +523,7 @@ export class GpuInventory { if (text === null) row.limitations.push(PTX_INVALID_UTF8); if (!complete) row.limitations.push( - "PTX target scan reached the 16 MiB text budget before all module directives were examined.", + `PTX target scan reached the ${formatGpuByteBudget(this.#budgets.maxReportBytes)} text budget before all module directives were examined.`, ); if (complete && text !== null) { row.target = targetFacts.target; @@ -303,7 +536,13 @@ export class GpuInventory { } this.#add(row); await this.#payload( - complete ? new GpuBufferSource(probe, source.containerId) : source, + complete + ? new GpuBufferSource( + probe, + source.containerId, + this.#budgets.maxObjectBytes, + ) + : source, row, complete ? { standalonePtx: text === null ? null : { text, targetFacts } } @@ -314,8 +553,10 @@ export class GpuInventory { if (!complete) throw new BinaryResourceFailure( "structure", - GPU_REPORT_BYTES, - "Standalone text recognition exceeds the 16 MiB PTX budget before a target was established", + this.#budgets.maxReportBytes, + `Standalone text recognition exceeds the ${String(this.#budgets.maxReportBytes)}-byte PTX budget before a target was established`, + "gpu-retained-report-bytes", + "bytes", ); throw new BinaryFormatFailure( "unsupported", @@ -335,7 +576,11 @@ export class GpuInventory { : cause.kind === "unsupported" ? "unsupported" : "malformed"; - this.#objectLimitations(row, [cause.message]); + const message = + cause instanceof BinaryResourceFailure + ? gpuCapacityLimitationMessage(cause) + : cause.message; + this.#objectLimitations(row, [message]); } async #payload( source: GpuSource, @@ -367,12 +612,14 @@ export class GpuInventory { let coverage: "complete" | "partial" = "complete"; if ( row.kind === "ptx" && - (decodedSize === null || decodedSize > GPU_REPORT_BYTES) + (decodedSize === null || decodedSize > this.#budgets.maxReportBytes) ) throw new BinaryResourceFailure( "structure", - GPU_REPORT_BYTES, - "PTX text exceeds the 16 MiB retained report budget", + this.#budgets.maxReportBytes, + `PTX text exceeds the ${String(this.#budgets.maxReportBytes)}-byte retained report budget`, + "gpu-retained-report-bytes", + "bytes", ); const compression = row.compression; const compressed = @@ -381,10 +628,13 @@ export class GpuInventory { compression === "lz4"; if (compressed && decodedSize === null) rejectGpu("Compressed GPU object has no decoded length"); - this.#budgetWork( - row.location.size, - ...(compressed ? [decodedSize!] : []), - ); + // Standalone PTX probes already reserved and read their complete buffer. + if (standalonePtx === undefined) + this.#reserveReadWork( + source, + row.location.size, + ...(compressed ? [decodedSize!] : []), + ); let bytes = await source.read(row.location.offset, row.location.size); if (compressed) { try { @@ -393,6 +643,7 @@ export class GpuInventory { compression, Number(decodedSize), this.signal, + this.#budgets.maxObjectBytes, ); } catch (cause) { if (cause instanceof ZstandardFrameAllowanceError) @@ -414,7 +665,11 @@ export class GpuInventory { } const decodedSha256 = sha256Hex(bytes); this.#decoded(row, decodedSha256, bytes.length); - const decoded = new GpuBufferSource(bytes, row.id); + const decoded = new GpuBufferSource( + bytes, + row.id, + this.#budgets.maxObjectBytes, + ); if (row.kind === "ptx") { // Standalone discovery already retained this encoding failure. if (standalonePtx === null) return; @@ -464,6 +719,7 @@ export class GpuInventory { text, row.id, tracker, + this.#budgets, )) { this.#retain(kernel); this.kernels.push(kernel); @@ -471,7 +727,10 @@ export class GpuInventory { } } catch (cause) { if (!(cause instanceof GpuReportCapacityFailure)) - finishTarget(standalonePtx?.targetFacts ?? readPtxTarget(text)); + finishTarget( + standalonePtx?.targetFacts ?? + readPtxTarget(text, this.#budgets.maxTokenBytes), + ); throw cause; } finishTarget(standalonePtx?.targetFacts ?? tracker!.facts()); @@ -554,15 +813,38 @@ export class GpuInventory { row: GpuObject, directory?: NativeSectionDirectory, ): Promise { + const parentMetered = this.#meteredSources.has(source); const child: GpuSource = { size: row.location.size, containerId: row.id, + maxObjectBytes: this.#budgets.maxObjectBytes, read: (offset, size) => { - checkGpuRange(row.location.size, offset, size); - this.#budgetWork(size); + checkGpuRange( + row.location.size, + offset, + size, + this.#budgets.maxObjectBytes, + ); + if (!parentMetered) this.#budgetWork(size); return source.read(row.location.offset + offset, size); }, + readBounded: (offset, size, maximumBytes, limitName) => { + checkGpuRange(row.location.size, offset, size, maximumBytes, limitName); + if (!parentMetered) { + if (limitName === NATIVE_STRUCTURE_LIMIT) this.#reserveWork(size); + else this.#budgetWork(size); + } + return source.readBounded !== undefined + ? source.readBounded( + row.location.offset + offset, + size, + maximumBytes, + limitName, + ) + : source.read(row.location.offset + offset, size); + }, }; + this.#meteredSources.add(child); try { // An AMD target declaration does not establish an ELF representation. @@ -582,10 +864,16 @@ export class GpuInventory { directory ?? (await readGpuNativeDirectory( child, - readElfSectionDirectory(child.size), + readElfSectionDirectory( + child.size, + this.#budgets.maxStructureBytes === undefined + ? undefined + : { structureBytes: this.#budgets.maxStructureBytes }, + ), () => yieldArtifactRead(this.signal), + this.#budgets.maxStructureBytes, )); - const inspected = await readAmdElfMetadata(child, native); + const inspected = await readAmdElfMetadata(child, native, this.#budgets); const prepared = inspected.ok ? inspected.value : inspected.error.partial; if (prepared.limitations.length > 0) this.discovery = "partial"; this.#target(row, { @@ -632,6 +920,7 @@ export class GpuInventory { (target) => { conflict = this.#target(row, target); }, + this.#budgets, ); this.#objectLimitations(row, parsed.limitations); return conflict !== undefined ? "partial" : parsed.coverage; @@ -660,6 +949,7 @@ export class GpuInventory { source, base, this.signal, + this.#budgets, ); for (const { object: row, amdTarget } of directory.declarations) { this.#add(row, amdTarget); @@ -668,7 +958,7 @@ export class GpuInventory { await this.#amdPayload(source, row); else await this.#payload(source, row); } - base = await nextGpuContainerOffset(source, directory.end); + base = await nextGpuContainerOffset(source, directory.end, this.signal); continue; } if (!prefix.subarray(0, CCOB_MAGIC.length).equals(CCOB_MAGIC)) @@ -698,7 +988,7 @@ export class GpuInventory { // the codec's completed extent, never an embedded CCOB marker. const inputSize = version === 1 - ? Math.min(total - width, GPU_OBJECT_BYTES) + ? Math.min(total - width, this.#budgets.maxObjectBytes) : total - width; let data: Buffer; if (version === 1) { @@ -707,8 +997,12 @@ export class GpuInventory { legacyWindow !== undefined && start >= legacyWindow.offset && start < legacyWindow.offset + legacyWindow.bytes.length; - const readWindow = async (): Promise => { - this.#budgetWork(inputSize, declaredDecodedSize); + const readWindow = async ( + chargeDecoded: boolean, + ): Promise => { + if (chargeDecoded) + this.#reserveReadWork(source, inputSize, declaredDecodedSize); + else this.#reserveReadWork(source, inputSize); legacyWindow = undefined; const bytes = await source.read(start, inputSize); legacyWindow = { offset: start, bytes }; @@ -717,33 +1011,120 @@ export class GpuInventory { if (cached) this.#budgetWork(declaredDecodedSize); let encoded: Buffer | undefined = cached ? legacyWindow!.bytes.subarray(start - legacyWindow!.offset) - : await readWindow(); + : await readWindow(true); const decoded = Number(declaredDecodedSize); const available = encoded.length; const compression = row.compression; - const completed = await decodeGpuPayloadStream( + const ccobWindowLimit = (): BinaryResourceFailure => + new BinaryResourceFailure( + "structure", + this.#budgets.maxObjectBytes, + `Legacy CCOB v1 compressed payload exceeds the ${String(this.#budgets.maxObjectBytes)}-byte object budget`, + GPU_OBJECT_BYTES_LIMIT, + "bytes", + ); + const decodeRefilledWindow = async (): Promise<{ + buffer: Buffer; + consumedBytes: number; + inputExhausted: boolean; + frameAllowanceReached?: ZstandardFrameAllowance; + }> => { + // Retire the previous window before allocating its replacement. + // `declaredDecodedSize` was already reserved when the cached path began. + encoded = undefined; + const refilled = await readWindow(false); + encoded = refilled; + return decodeGpuPayloadStream( + refilled, + compression, + decoded, + this.signal, + ).catch((refillCause: unknown) => { + if ( + isTruncatedGpuPayloadFailure(refillCause) && + total - width > this.#budgets.maxObjectBytes + ) + throw ccobWindowLimit(); + throw refillCause; + }); + }; + let refilled = false; + let completed: + | { + buffer: Buffer; + consumedBytes: number; + inputExhausted: boolean; + frameAllowanceReached?: ZstandardFrameAllowance; + } + | undefined = await decodeGpuPayloadStream( encoded, compression, decoded, this.signal, ).catch(async (cause: unknown) => { // A cached window may end inside this sibling. Refill once - // before treating that incomplete view as a malformed stream. + // before treating that incomplete view as a truncated stream. if ( - !(cause instanceof BinaryFormatFailure) || - !cached || - available >= inputSize + isTruncatedGpuPayloadFailure(cause) && + cached && + available < inputSize + ) { + refilled = true; + return decodeRefilledWindow(); + } + if ( + isTruncatedGpuPayloadFailure(cause) && + total - width > this.#budgets.maxObjectBytes ) - throw cause; - // Retire the previous window before allocating its replacement. - encoded = undefined; - return decodeGpuPayloadStream( - await readWindow(), - compression, - decoded, - this.signal, - ); + throw ccobWindowLimit(); + throw cause; }); + // When the decoder stopped because the supplied window ran out at a + // frame boundary or partial next-frame magic (including before a + // trailing skippable or empty Zstandard frame), peek 4 bytes past the + // consumed extent to confirm another Zstandard/skippable frame actually + // follows before reporting zstd.max_frames, refilling, or reporting capacity. + const hasFollowingZstandardFrame = async ( + consumedBytes: number, + ): Promise => { + if (total - width - consumedBytes < ZSTANDARD_MAGIC_BYTES) + return false; + const peek = await source.read( + start + consumedBytes, + ZSTANDARD_MAGIC_BYTES, + ); + return zstandardFrameKind(peek, 0) !== undefined; + }; + if ( + completed.inputExhausted && + (await hasFollowingZstandardFrame(completed.consumedBytes)) + ) { + if (completed.frameAllowanceReached !== undefined) + throw new ZstandardFrameAllowanceError( + completed.frameAllowanceReached, + completed.consumedBytes, + ); + if (!refilled && cached && available < inputSize) { + // Release the partial decode output before allocating a refilled window. + completed = undefined; + refilled = true; + completed = await decodeRefilledWindow(); + if ( + completed.inputExhausted && + (await hasFollowingZstandardFrame(completed.consumedBytes)) + ) { + if (completed.frameAllowanceReached !== undefined) + throw new ZstandardFrameAllowanceError( + completed.frameAllowanceReached, + completed.consumedBytes, + ); + if (total - width > this.#budgets.maxObjectBytes) + throw ccobWindowLimit(); + } + } else if (total - width > this.#budgets.maxObjectBytes) { + throw ccobWindowLimit(); + } + } total = width + completed.consumedBytes; extentKnown = true; this.#encodedExtent(row, completed.consumedBytes); @@ -755,12 +1136,13 @@ export class GpuInventory { "GPU decompressed length disagrees with its declaration", ); } else { - this.#budgetWork(inputSize, declaredDecodedSize); + this.#reserveReadWork(source, inputSize, declaredDecodedSize); data = await decodeGpuPayload( await source.read(base + width, inputSize), row.compression, Number(declaredDecodedSize), this.signal, + this.#budgets.maxObjectBytes, ); } if ( @@ -772,7 +1154,10 @@ export class GpuInventory { ) rejectGpu("CCOB truncated MD5 does not match decoded bytes"); this.#decoded(row, sha256Hex(data), data.length); - await this.inspect(new GpuBufferSource(data, row.id), depth + 1); + await this.inspect( + new GpuBufferSource(data, row.id, this.#budgets.maxObjectBytes), + depth + 1, + ); row.inspection = "complete"; } catch (cause) { this.#retainFailure(row, cause); @@ -781,7 +1166,11 @@ export class GpuInventory { if (!extentKnown) { if (row.inspection !== "capacity") try { - total = await findLegacyCcobRecoveryTotal(source, base); + total = await findLegacyCcobRecoveryTotal( + source, + base, + this.#budgets.maxObjectBytes, + ); } catch (cause) { if (!(cause instanceof BinaryResourceFailure)) throw cause; this.#retainFailure(row, cause); @@ -802,12 +1191,18 @@ export class GpuInventory { ]); this.#add(row); } - base = await nextGpuContainerOffset(source, base + total); + base = await nextGpuContainerOffset(source, base + total, this.signal); } } } const LLVM_BITCODE_LIMITATION = "LLVM bitcode kernel metadata is outside current coverage; bitcode validity and inner target were not inspected."; +const gpuCapacityLimitationMessage = (cause: BinaryResourceFailure): string => { + const parameter = gpuBudgetParameterForLimit(cause.failure.limit.name); + return parameter === undefined + ? cause.message + : `${cause.message} (parameter: ${parameter})`; +}; /** LLVM raw and wrapper signatures identify representation, not bitcode validity. */ const isLlvmBitcode = (bytes: Buffer): boolean => { if (bytes.length < 4) return false; diff --git a/src/gpu/GpuPayloadCodec.test.ts b/src/gpu/GpuPayloadCodec.test.ts index e399e07599..d235b42f77 100644 --- a/src/gpu/GpuPayloadCodec.test.ts +++ b/src/gpu/GpuPayloadCodec.test.ts @@ -5,7 +5,11 @@ import { MAXIMUM_ZSTD_MAX_FRAMES, MINIMUM_ZSTD_MAX_FRAMES, } from "../domain/analysisResourceLimits.js"; -import { decodeGpuPayload, decodeGpuPayloadStream } from "./GpuPayloadCodec.js"; +import { + decodeGpuPayload, + decodeGpuPayloadStream, + isTruncatedGpuPayloadFailure, +} from "./GpuPayloadCodec.js"; it.each(["zlib", "zstd"] as const)( "requires all declared %s input bytes to belong to the codec stream", async (codec) => { @@ -85,6 +89,14 @@ it.each(["zlib", "zstd"] as const)( expect(await decodeGpuPayloadStream(input, codec, source.length)).toEqual({ buffer: source, consumedBytes: compressed.length, + inputExhausted: false, + }); + expect( + await decodeGpuPayloadStream(compressed, codec, source.length), + ).toEqual({ + buffer: source, + consumedBytes: compressed.length, + inputExhausted: codec === "zstd", }); await expect( decodeGpuPayloadStream(compressed.subarray(0, -1), codec, source.length), @@ -94,3 +106,33 @@ it.each(["zlib", "zstd"] as const)( ).rejects.toMatchObject({ kind: "malformed" }); }, ); + +it.each(["zlib", "zstd"] as const)( + "distinguishes truncated %s streams from corrupt bytes and output overflow", + async (codec) => { + const source = Buffer.from("ordinary CCOB marker payload"); + const compressed = + codec === "zstd" ? zstdCompressSync(source) : deflateSync(source); + + const truncatedError = await decodeGpuPayloadStream( + compressed.subarray(0, -1), + codec, + source.length, + ).catch((cause: unknown) => cause); + expect(isTruncatedGpuPayloadFailure(truncatedError)).toBe(true); + + const corruptError = await decodeGpuPayloadStream( + Buffer.alloc(16, 0xff), + codec, + source.length, + ).catch((cause: unknown) => cause); + expect(isTruncatedGpuPayloadFailure(corruptError)).toBe(false); + + const overflowError = await decodeGpuPayloadStream( + compressed, + codec, + 1, + ).catch((cause: unknown) => cause); + expect(isTruncatedGpuPayloadFailure(overflowError)).toBe(false); + }, +); diff --git a/src/gpu/GpuPayloadCodec.ts b/src/gpu/GpuPayloadCodec.ts index 4e2f74951c..6ef190e684 100644 --- a/src/gpu/GpuPayloadCodec.ts +++ b/src/gpu/GpuPayloadCodec.ts @@ -6,19 +6,54 @@ import { assertArtifactReadActive } from "../resources/index.js"; import { decodeLz4Block } from "../compression/Lz4Block.js"; import { decodeZstandardFramesCooperative, + isZstandardTruncationReason, ZSTANDARD_WINDOW_LOG_MAX, } from "../domain/compression/zstandardExactFrame.js"; -import { ZstandardFrameAllowanceError } from "../domain/compression/zstandardFrameAllowance.js"; -import { BinaryFormatFailure } from "../domain/binaryContainer.js"; -import { GPU_OBJECT_BYTES, rejectGpu } from "./GpuSource.js"; +import { + ZstandardFrameAllowanceError, + type ZstandardFrameAllowance, +} from "../domain/compression/zstandardFrameAllowance.js"; +import { + BinaryFormatFailure, + BinaryResourceFailure, +} from "../domain/binaryContainer.js"; +import { + DEFAULT_GPU_OBJECT_BYTES, + GPU_OBJECT_BYTES_LIMIT, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; +import { rejectGpu } from "./GpuSource.js"; const unzip = promisify(inflate); -/** Completed codec bytes and their encoded extent share one completion owner. */ + +/** Codec-owned marker for a stream that ran out of input bytes rather than corrupting or overflowing. */ +class GpuTruncatedPayloadFailure extends BinaryFormatFailure { + constructor( + message: string, + context?: { + readonly format?: string; + readonly field?: string; + readonly offset?: number; + }, + ) { + super("malformed", message, context); + } +} + +/** True when a GPU codec failure indicates truncated compressed input rather than corrupt bytes or output overflow. */ +export const isTruncatedGpuPayloadFailure = ( + error: unknown, +): error is BinaryFormatFailure => error instanceof GpuTruncatedPayloadFailure; +/** Completed codec bytes, their encoded extent, and whether input ended where another frame could still continue. */ export const decodeGpuPayloadStream = async ( bytes: Buffer, compression: "zlib" | "zstd", maximumDecodedSize: number, signal?: AbortSignal, -): Promise<{ buffer: Buffer; consumedBytes: number }> => { +): Promise<{ + buffer: Buffer; + consumedBytes: number; + inputExhausted: boolean; + frameAllowanceReached?: ZstandardFrameAllowance; +}> => { assertArtifactReadActive(signal); const maxOutputLength = Math.max(1, maximumDecodedSize); if (compression === "zstd") { @@ -49,6 +84,15 @@ export const decodeGpuPayloadStream = async ( }, decoded.offset, ); + if (isZstandardTruncationReason(decoded.reason)) + throw new GpuTruncatedPayloadFailure( + "GPU payload decompression failed or exceeded its declared length", + { + format: "zstd", + field: decoded.reason, + offset: decoded.offset, + }, + ); throw new BinaryFormatFailure( "malformed", "GPU payload decompression failed or exceeded its declared length", @@ -59,13 +103,29 @@ export const decodeGpuPayloadStream = async ( }, ); } - return { buffer: decoded.bytes, consumedBytes: decoded.consumedBytes }; + return { + buffer: decoded.bytes, + consumedBytes: decoded.consumedBytes, + inputExhausted: decoded.inputExhausted, + ...(decoded.frameAllowanceReached === undefined + ? {} + : { frameAllowanceReached: decoded.frameAllowanceReached }), + }; } let result: unknown; try { result = await unzip(bytes, { maxOutputLength, info: true }); - } catch { + } catch (cause: unknown) { assertArtifactReadActive(signal); + const code = + cause instanceof Error && "code" in cause + ? String(cause.code) + : undefined; + if (code === "Z_BUF_ERROR") + throw new GpuTruncatedPayloadFailure( + "GPU payload decompression failed or exceeded its declared length", + { format: "zlib", field: code }, + ); return rejectGpu( "GPU payload decompression failed or exceeded its declared length", ); @@ -78,17 +138,39 @@ export const decodeGpuPayloadStream = async ( consumed > bytes.length ) rejectGpu("GPU decoder returned an invalid complete codec extent"); - return { buffer: decoded, consumedBytes: consumed }; + return { buffer: decoded, consumedBytes: consumed, inputExhausted: false }; }; export const decodeGpuPayload = async ( bytes: Buffer, compression: "zlib" | "zstd" | "lz4", expected: number, signal?: AbortSignal, + maxObjectBytes: number = DEFAULT_GPU_OBJECT_BYTES, ): Promise => { assertArtifactReadActive(signal); - if (compression === "lz4") - return decodeLz4Block(bytes, expected, GPU_OBJECT_BYTES, signal); + if (expected > maxObjectBytes) + throw new BinaryResourceFailure( + "structure", + maxObjectBytes, + `GPU payload decoded length exceeds the ${String(maxObjectBytes)}-byte object budget`, + GPU_OBJECT_BYTES_LIMIT, + "bytes", + ); + if (compression === "lz4") { + try { + return await decodeLz4Block(bytes, expected, maxObjectBytes, signal); + } catch (cause) { + if (cause instanceof BinaryResourceFailure) + throw new BinaryResourceFailure( + "structure", + maxObjectBytes, + cause.message, + GPU_OBJECT_BYTES_LIMIT, + "bytes", + ); + throw cause; + } + } const decoded = await decodeGpuPayloadStream( bytes, compression, diff --git a/src/gpu/GpuSource.ts b/src/gpu/GpuSource.ts index 56d4de0c65..fac04f9595 100644 --- a/src/gpu/GpuSource.ts +++ b/src/gpu/GpuSource.ts @@ -3,29 +3,47 @@ import type { FileHandle } from "node:fs/promises"; import { assertArtifactReadActive, ArtifactReaderFailure, + yieldArtifactRead, } from "../resources/index.js"; import { BinaryFormatFailure, BinaryResourceFailure, + NATIVE_STRUCTURE_LIMIT, } from "../domain/binaryContainer.js"; import { decodeElfSectionNameRequestCooperative } from "../domain/native/elfSectionNameTable.js"; import type { ZstandardFramePause } from "../domain/compression/zstandardExactFrame.js"; +import { NATIVE_STRUCTURE_BYTES } from "../domain/native/nativeStructureBudget.js"; import type { NativeReadRequest, NativeSectionDirectory, } from "../domain/native/nativeSectionDirectory.js"; -export const GPU_OBJECT_BYTES = 128 * 1024 * 1024; -export const GPU_REPORT_BYTES = 16 * 1024 * 1024; +import { + DEFAULT_GPU_OBJECT_BYTES, + DEFAULT_GPU_REPORT_BYTES, + GPU_OBJECT_BYTES_LIMIT, + GPU_RETAINED_REPORT_BYTES_LIMIT, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; /** A retained-facts refusal aborts discovery; it is never downgraded to one opaque payload. */ export class GpuReportCapacityFailure extends BinaryResourceFailure { - constructor() { + /** + * Lower bound measured up to the stopped step. Kept out of `limit.required` + * because later facts may require more bytes to admit the complete request. + */ + readonly minimumReportBytes?: number; + + constructor( + maxReportBytes: number = DEFAULT_GPU_REPORT_BYTES, + minimumReportBytes?: number, + ) { super( "structure", - GPU_REPORT_BYTES, - "GPU facts exceed the 16 MiB retained report budget", - "gpu-retained-report-bytes", + maxReportBytes, + `GPU facts exceed the ${String(maxReportBytes)}-byte retained report budget`, + GPU_RETAINED_REPORT_BYTES_LIMIT, "bytes", ); + if (minimumReportBytes !== undefined) + this.minimumReportBytes = minimumReportBytes; } } export const rejectGpu = (message: string): never => { @@ -39,12 +57,21 @@ export const gpuCount = (value: bigint): number => { export interface GpuSource { readonly size: number; readonly containerId: string | null; + readonly maxObjectBytes?: number; read(offset: number, size: number): Promise; + readBounded?( + offset: number, + size: number, + maximumBytes: number, + limitName?: string, + ): Promise; } export const checkGpuRange = ( length: number, offset: number, size: number, + maxBytes: number = DEFAULT_GPU_OBJECT_BYTES, + limitName: string = GPU_OBJECT_BYTES_LIMIT, ): void => { if ( !Number.isSafeInteger(offset) || @@ -55,11 +82,15 @@ export const checkGpuRange = ( size > length - offset ) rejectGpu("GPU byte range is outside its containing object"); - if (size > GPU_OBJECT_BYTES) + if (size > maxBytes) throw new BinaryResourceFailure( "structure", - GPU_OBJECT_BYTES, - "GPU object exceeds the 128 MiB decoding budget", + maxBytes, + limitName === NATIVE_STRUCTURE_LIMIT + ? `Native container structure read exceeds the ${String(maxBytes)}-byte structure budget` + : `GPU object exceeds the ${String(maxBytes)}-byte decoding budget`, + limitName, + "bytes", ); }; export class GpuFileSource implements GpuSource { @@ -69,9 +100,23 @@ export class GpuFileSource implements GpuSource { readonly file: FileHandle, readonly size: number, readonly signal?: AbortSignal, + readonly maxObjectBytes: number = DEFAULT_GPU_OBJECT_BYTES, ) {} - async read(offset: number, size: number): Promise { - checkGpuRange(this.size, offset, size); + read(offset: number, size: number): Promise { + return this.readBounded( + offset, + size, + this.maxObjectBytes, + GPU_OBJECT_BYTES_LIMIT, + ); + } + async readBounded( + offset: number, + size: number, + maximumBytes: number, + limitName: string = GPU_OBJECT_BYTES_LIMIT, + ): Promise { + checkGpuRange(this.size, offset, size, maximumBytes, limitName); const bytes = Buffer.alloc(size); let position = 0; while (position < size) { @@ -94,14 +139,22 @@ export class GpuFileSource implements GpuSource { return bytes; } async digest(): Promise { + // Full-file SHA-256 streams in fixed 1 MiB chunks independent of per-object maxObjectBytes. const hash = createHash("sha256"); + const chunk = Buffer.allocUnsafe(Math.min(1024 * 1024, this.size)); for (let position = 0; position < this.size;) { - const bytes = await this.read( - position, - Math.min(1024 * 1024, this.size - position), - ); - hash.update(bytes); - position += bytes.length; + assertArtifactReadActive(this.signal); + const want = Math.min(chunk.length, this.size - position); + const result = await this.file.read(chunk, 0, want, position); + if (result.bytesRead === 0) + throw new ArtifactReaderFailure( + "integrity", + "GPU source was truncated during inspection", + { integrityCheck: "read-coverage" }, + ); + hash.update(chunk.subarray(0, result.bytesRead)); + position += result.bytesRead; + this.bytesRead += result.bytesRead; } return hash.digest("hex"); } @@ -111,11 +164,25 @@ export class GpuBufferSource implements GpuSource { constructor( readonly bytes: Buffer, readonly containerId: string | null, + readonly maxObjectBytes: number = DEFAULT_GPU_OBJECT_BYTES, ) { this.size = bytes.length; } - async read(offset: number, size: number): Promise { - checkGpuRange(this.size, offset, size); + read(offset: number, size: number): Promise { + return this.readBounded( + offset, + size, + this.maxObjectBytes, + GPU_OBJECT_BYTES_LIMIT, + ); + } + async readBounded( + offset: number, + size: number, + maximumBytes: number, + limitName: string = GPU_OBJECT_BYTES_LIMIT, + ): Promise { + checkGpuRange(this.size, offset, size, maximumBytes, limitName); return this.bytes.subarray(offset, offset + size); } } @@ -123,6 +190,7 @@ export const readGpuNativeDirectory = async ( source: GpuSource, steps: Generator, pause: ZstandardFramePause, + maxStructureBytes: number = NATIVE_STRUCTURE_BYTES.default_value, ): Promise => { let next = steps.next(); while (!next.done) { @@ -137,24 +205,49 @@ export const readGpuNativeDirectory = async ( next = steps.next(Buffer.alloc(0)); continue; } - next = steps.next(await source.read(step.offset, step.size)); + const chunk = + source.readBounded !== undefined + ? await source.readBounded( + step.offset, + step.size, + maxStructureBytes, + NATIVE_STRUCTURE_LIMIT, + ) + : await source.read(step.offset, step.size); + next = steps.next(chunk); } return next.value; }; +export const CONTAINER_SCAN_CHUNK_BYTES = 65_536; export const nextGpuContainerOffset = async ( source: GpuSource, start: number, + signal?: AbortSignal, ): Promise => { - let width = 64; + const maxChunk = Math.max( + 1, + Math.min( + CONTAINER_SCAN_CHUNK_BYTES, + source.maxObjectBytes ?? DEFAULT_GPU_OBJECT_BYTES, + ), + ); + let width = Math.min(64, maxChunk); + let scannedSinceYield = 0; for (let position = start; position < source.size;) { - const bytes = await source.read( - position, - Math.min(width, source.size - position), - ); + const chunk = Math.min(width, maxChunk, source.size - position); + const bytes = + source.readBounded !== undefined + ? await source.readBounded(position, chunk, maxChunk) + : await source.read(position, chunk); const index = bytes.findIndex((byte) => byte !== 0); if (index >= 0) return position + index; position += bytes.length; - width = 65536; + scannedSinceYield += bytes.length; + if (scannedSinceYield >= 1024 * 1024) { + scannedSinceYield = 0; + await yieldArtifactRead(signal); + } + width = maxChunk; } return source.size; }; diff --git a/src/gpu/PtxKernels.test.ts b/src/gpu/PtxKernels.test.ts index 6e5372a5da..2721ddf990 100644 --- a/src/gpu/PtxKernels.test.ts +++ b/src/gpu/PtxKernels.test.ts @@ -1,5 +1,9 @@ import { expect, it } from "vitest"; -import { readPtxKernels, readPtxTarget } from "./PtxKernels.js"; +import { + createPtxVersionScanner, + readPtxKernels, + readPtxTarget, +} from "./PtxKernels.js"; it("recognizes directives outside comments and strings and preserves UTF-8 byte coordinates", () => { expect(readPtxTarget('".version 8.8\n.target sm_80\n"').recognized).toBe( false, @@ -278,3 +282,35 @@ it("does not label unrelated malformed quoted text as a recognized PTX artifact" expect(readPtxTarget('unrelated "unterminated').recognized).toBe(false); expect(readPtxTarget("/* unrelated unterminated").recognized).toBe(false); }); + +it("does not preempt non-PTX recognition with max_token_bytes but enforces it after .version", () => { + expect( + readPtxTarget( + "this_is_plain_non_gpu_text_with_a_long_identifier_token_123", + 16, + ).recognized, + ).toBe(false); + expect(() => + readPtxTarget( + ".version 8.8\n.target sm_80\n.visible .entry very_long_kernel_name_exceeding_sixteen() { ret; }\n", + 16, + ), + ).toThrow("PTX token exceeds the string budget"); + + // Long leading-zero version numbers (> 32 bytes) must agree between the + // incremental scanner and readPtxTarget, and header tokens remain bounded by max_token_bytes. + const longZeroVersion = `.version ${"0".repeat(40)}8.${"0".repeat(40)}0\n.target sm_80\n`; + const scanner = createPtxVersionScanner(); + expect(scanner.feed(Buffer.from(longZeroVersion))).toBe("yes"); + expect(readPtxTarget(longZeroVersion)).toMatchObject({ + recognized: true, + target: "sm_80", + }); + expect(() => readPtxTarget(".version 8.8\n.target sm_80\n", 7)).toThrow( + "PTX token exceeds the string budget", + ); + const overDefaultZeroVersion = `.version ${"0".repeat(70_000)}8.0\n.target sm_80\n`; + expect(() => readPtxTarget(overDefaultZeroVersion)).toThrow( + "PTX token exceeds the string budget", + ); +}); diff --git a/src/gpu/PtxKernels.ts b/src/gpu/PtxKernels.ts index ff90e27525..1134fcd0c5 100644 --- a/src/gpu/PtxKernels.ts +++ b/src/gpu/PtxKernels.ts @@ -3,7 +3,15 @@ import { BinaryResourceFailure, } from "../domain/binaryContainer.js"; import type { GpuKernel } from "../domain/gpu/gpuCodeObjects.js"; -import { GPU_REPORT_BYTES, rejectGpu } from "./GpuSource.js"; +import { + DEFAULT_GPU_PARSER_ENTRIES, + DEFAULT_GPU_REPORT_BYTES, + DEFAULT_GPU_TOKEN_BYTES, + GPU_PARSER_ENTRIES_LIMIT, + GPU_TOKEN_BYTES_LIMIT, + type GpuCodeObjectsBudgets, +} from "../domain/gpu/gpuCodeObjectsBudgets.js"; +import { rejectGpu } from "./GpuSource.js"; interface Token { readonly value: string; readonly start: number; @@ -25,7 +33,12 @@ const isWhitespaceAt = (text: string, at: number, code: number): boolean => : /\s/u.test(text[at]!); /** Byte coordinates are accumulated once, including non-ASCII comments and quoted strings. */ -function* tokens(text: string): Generator { +function* tokens( + text: string, + maxTokenBytes: number | (() => number) = DEFAULT_GPU_TOKEN_BYTES, +): Generator { + const limit = + typeof maxTokenBytes === "function" ? maxTokenBytes : () => maxTokenBytes; const len = text.length; let at = 0, byte = 0; @@ -103,11 +116,14 @@ function* tokens(text: string): Generator { byte += 1; } } else advance(); - if (at - position > 65536) + const currentLimit = limit(); + if (byte - start > currentLimit) throw new BinaryResourceFailure( "structure", - 65536, + currentLimit, "PTX token exceeds the string budget", + GPU_TOKEN_BYTES_LIMIT, + "bytes", ); yield { value: text.slice(position, at), start, end: byte }; } @@ -298,14 +314,24 @@ export function* readPtxKernels( text: string, objectId: string, targetTracker?: PtxTargetTracker, + budgets?: Pick< + GpuCodeObjectsBudgets, + "maxReportBytes" | "maxParserEntries" | "maxTokenBytes" + >, ): Generator<{ kernel: GpuKernel; coverage: "complete" | "partial" }> { - if (Buffer.byteLength(text) > GPU_REPORT_BYTES) + const maxReportBytes = budgets?.maxReportBytes ?? DEFAULT_GPU_REPORT_BYTES; + const maxParserEntries = + budgets?.maxParserEntries ?? DEFAULT_GPU_PARSER_ENTRIES; + const maxTokenBytes = budgets?.maxTokenBytes ?? DEFAULT_GPU_TOKEN_BYTES; + if (Buffer.byteLength(text) > maxReportBytes) throw new BinaryResourceFailure( "structure", - GPU_REPORT_BYTES, - "PTX text exceeds the 16 MiB retained report budget", + maxReportBytes, + `PTX text exceeds the ${String(maxReportBytes)}-byte retained report budget`, + "gpu-retained-report-bytes", + "bytes", ); - const iterator = tokens(text); + const iterator = tokens(text, maxTokenBytes); const next = (): Token => { const value = iterator.next(); if (value.done) return rejectGpu("Truncated PTX entry declaration"); @@ -355,11 +381,13 @@ export function* readPtxKernels( const flush = (): void => { if (part.length === 0) return; if (part[0] !== ".param") rejectGpu("Unknown PTX parameter declaration"); - if (parameters.length >= 65536) + if (parameters.length >= maxParserEntries) throw new BinaryResourceFailure( "structure", - 65536, + maxParserEntries, "PTX parameter declarations exceed the facts budget", + GPU_PARSER_ENTRIES_LIMIT, + "entries", ); const value = declaration(part); let offset: number | null = null; @@ -404,8 +432,8 @@ export function* readPtxKernels( if (part.length > 128) throw new BinaryResourceFailure( "structure", - 65536, - "PTX parameter declarations exceed the facts budget", + 128, + "PTX parameter declaration exceeds the fixed 128-token syntax limit", ); } flush(); @@ -463,8 +491,8 @@ export function* readPtxKernels( if (bodyParameter.length >= 128) throw new BinaryResourceFailure( "structure", - 65536, - "PTX parameter declarations exceed the facts budget", + 128, + "PTX parameter declaration exceeds the fixed 128-token syntax limit", ); bodyParameter.push(t.value); } @@ -571,11 +599,13 @@ export function* readPtxKernels( "Unsupported PTX register declarations or overflowing totals leave the affected virtual register count unknown.", ); } - if (++kernelCount > 65536) + if (++kernelCount > maxParserEntries) throw new BinaryResourceFailure( "structure", - 65536, + maxParserEntries, "PTX kernel count exceeds the facts budget", + GPU_PARSER_ENTRIES_LIMIT, + "entries", ); yield { kernel, coverage }; } @@ -658,9 +688,188 @@ export const createPtxTargetTracker = (): PtxTargetTracker => { export const ptxTargetIdentity = (target: string): string => target.replace(/^compute_(\d+[a-z]?)$/u, "sm_$1"); +/** + * Incremental standalone PTX candidate recognizer. Skips leading whitespace + * (including UTF-8 BOM and Unicode whitespace) and `//` or `/* ... *\/` comments + * across chunks to verify the first module token is `.version .` + * without applying caller object or token budgets to non-PTX inputs. + */ +export const createPtxVersionScanner = (): { + feed(chunk: Uint8Array): "yes" | "no" | "incomplete"; + finish(): "yes" | "no"; +} => { + type State = + | "leading" + | "slash" + | "line-comment" + | "block-comment" + | "block-star" + | "version-word" + | "after-version" + | "after-slash" + | "after-line-comment" + | "after-block-comment" + | "after-block-star" + | "version-major" + | "version-minor"; + const VERSION_DIRECTIVE = ".version"; + let state: State = "leading"; + let wordIndex = 0; + let majorValue = 0; + let hasMajorDigit = false; + let minorValue = 0; + let hasMinorDigit = false; + let utf8Pending: number[] = []; + let utf8Expected = 0; + + const isAsciiWhitespace = (byte: number): boolean => + byte === 0x20 || (byte >= 0x09 && byte <= 0x0d); + + const isUnicodeWhitespace = (bytes: readonly number[]): boolean => { + const text = Buffer.from(bytes).toString("utf8"); + return text.length > 0 && /^\s+$/u.test(text); + }; + + const stepByte = (byte: number): "yes" | "no" | "incomplete" => { + if (utf8Expected > 0) { + if ((byte & 0xc0) === 0x80) { + utf8Pending.push(byte); + if (utf8Pending.length < utf8Expected) return "incomplete"; + const ws = isUnicodeWhitespace(utf8Pending); + utf8Pending = []; + utf8Expected = 0; + return ws ? "incomplete" : "no"; + } + // Invalid UTF-8 continuation sequence cannot be whitespace. + utf8Pending = []; + utf8Expected = 0; + return "no"; + } + while (true) { + if (state === "leading" || state === "after-version") { + if (isAsciiWhitespace(byte)) return "incomplete"; + if (byte >= 0x80) { + if (byte >= 0xc2 && byte <= 0xdf) utf8Expected = 2; + else if (byte >= 0xe0 && byte <= 0xef) utf8Expected = 3; + else if (byte >= 0xf0 && byte <= 0xf4) utf8Expected = 4; + else return "no"; + utf8Pending = [byte]; + return "incomplete"; + } + if (byte === 0x2f) { + state = state === "leading" ? "slash" : "after-slash"; + return "incomplete"; + } + if (state === "leading") { + if (byte !== 0x2e) return "no"; + state = "version-word"; + wordIndex = 1; + return "incomplete"; + } + if (byte < 0x30 || byte > 0x39) return "no"; + state = "version-major"; + majorValue = byte - 0x30; + hasMajorDigit = true; + return "incomplete"; + } + if (state === "slash" || state === "after-slash") { + if (byte === 0x2f) { + state = state === "slash" ? "line-comment" : "after-line-comment"; + return "incomplete"; + } + if (byte === 0x2a) { + state = state === "slash" ? "block-comment" : "after-block-comment"; + return "incomplete"; + } + return "no"; + } + if (state === "line-comment" || state === "after-line-comment") { + if (byte === 0x0a) + state = state === "line-comment" ? "leading" : "after-version"; + return "incomplete"; + } + if (state === "block-comment" || state === "after-block-comment") { + if (byte === 0x2a) + state = state === "block-comment" ? "block-star" : "after-block-star"; + return "incomplete"; + } + if (state === "block-star" || state === "after-block-star") { + if (byte === 0x2f) { + state = state === "block-star" ? "leading" : "after-version"; + return "incomplete"; + } + if (byte !== 0x2a) + state = + state === "block-star" ? "block-comment" : "after-block-comment"; + return "incomplete"; + } + if (state === "version-word") { + if (isPtxWordChar(byte) && byte !== 0x2e) { + if ( + wordIndex >= VERSION_DIRECTIVE.length || + byte !== VERSION_DIRECTIVE.charCodeAt(wordIndex) + ) + return "no"; + wordIndex++; + return "incomplete"; + } + if (wordIndex !== VERSION_DIRECTIVE.length) return "no"; + state = "after-version"; + continue; + } + if (state === "version-major") { + if (byte >= 0x30 && byte <= 0x39) { + majorValue = majorValue * 10 + (byte - 0x30); + if (!Number.isSafeInteger(majorValue)) return "no"; + return "incomplete"; + } + if (byte === 0x2e && hasMajorDigit) { + state = "version-minor"; + minorValue = 0; + hasMinorDigit = false; + return "incomplete"; + } + return "no"; + } + // state === "version-minor" + if (byte >= 0x30 && byte <= 0x39) { + minorValue = minorValue * 10 + (byte - 0x30); + if (!Number.isSafeInteger(minorValue)) return "no"; + hasMinorDigit = true; + return "incomplete"; + } + if (isPtxWordChar(byte)) return "no"; + return hasMinorDigit ? "yes" : "no"; + } + }; + + return { + feed(chunk) { + for (let i = 0; i < chunk.length; i++) { + const verdict = stepByte(chunk[i]!); + if (verdict !== "incomplete") return verdict; + } + return "incomplete"; + }, + finish() { + return state === "version-minor" && hasMinorDigit && utf8Expected === 0 + ? "yes" + : "no"; + }, + }; +}; + /** Resolve all module-scope targets through the highest numbered architecture. */ -export const readPtxTarget = (text: string): PtxTargetFacts => { - const stream = tokens(text); +export const readPtxTarget = ( + text: string, + maxTokenBytes: number = DEFAULT_GPU_TOKEN_BYTES, +): PtxTargetFacts => { + // Format recognition (.version .) must not be preempted by a + // caller-lowered max_token_bytes on non-PTX text; enforce it after recognition. + let enforceTokenBudget = false; + const stream = tokens(text, () => + enforceTokenBudget ? maxTokenBytes : Number.POSITIVE_INFINITY, + ); const tracker = createPtxTargetTracker(); let depth = 0; try { @@ -673,6 +882,18 @@ export const readPtxTarget = (text: string): PtxTargetFacts => { ptxVersion(declaredVersion.value.value) === null ) return { recognized: false, target: null, limitation: null }; + if ( + first.value.end - first.value.start > maxTokenBytes || + declaredVersion.value.end - declaredVersion.value.start > maxTokenBytes + ) + throw new BinaryResourceFailure( + "structure", + maxTokenBytes, + "PTX token exceeds the string budget", + GPU_TOKEN_BYTES_LIMIT, + "bytes", + ); + enforceTokenBudget = true; for (const token of stream) { if (token.value === "{") { depth++; diff --git a/tests/acceptance/gpuCodeObjectsCli.test.ts b/tests/acceptance/gpuCodeObjectsCli.test.ts index 82b613a2df..5fa00bf0bc 100644 --- a/tests/acceptance/gpuCodeObjectsCli.test.ts +++ b/tests/acceptance/gpuCodeObjectsCli.test.ts @@ -1427,3 +1427,122 @@ cliTest( expect(regConflictReport.kernels[0]?.sources.shared).not.toBeNull(); }, ); + +cliTest( + "projects per-call GPU budget refusals with adapter flags and preserves omission through CLI and MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-gpu-budgets-cli-mcp-"); + const ptxPath = join(root, "sample.ptx"); + const ptxSource = [ + ".version 8.0", + ".target sm_90", + ".address_size 64", + ".visible .entry add_one(.param .u64 a) {", + " .reg .b32 %r<4>;", + " ret;", + "}", + ].join("\n"); + await writeFile(ptxPath, ptxSource, "utf8"); + + const refusedCli = await cli.run({ + arguments: [ + "inspect-gpu-code-objects", + ptxPath, + "--analysis", + "kernels", + "--max-report-bytes", + "64", + "--json", + ], + }); + expect(refusedCli.exitCode).toBe(1); + expect(refusedCli.json).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { + limit: { + control_kind: "parameter", + parameter: "max_report_bytes", + cli_flag: "--max-report-bytes", + effective_value: 64, + unit: "bytes", + minimum: 1, + maximum: 16 * 1024 * 1024, + default_value: 16 * 1024 * 1024, + applies_at: "next_call", + }, + refusal: { + kind: "adjustable_budget", + operation: "inspect_gpu_code_objects", + control: "max_report_bytes", + }, + }, + remediation: { + action: expect.stringContaining("--max-report-bytes"), + }, + }); + + const recoveredCli = await cli.run({ + arguments: [ + "inspect-gpu-code-objects", + ptxPath, + "--analysis", + "kernels", + "--max-report-bytes", + "1048576", + "--json", + ], + }); + expect(recoveredCli.exitCode, recoveredCli.stderr).toBe(0); + const cliEvidence = parseEvidence( + toolContract("inspect_gpu_code_objects").outputSchema.parse( + recoveredCli.json, + ), + ); + expect(cliEvidence.parameters).toEqual({ + path: ptxPath, + analysis: "kernels", + max_report_bytes: 1048576, + }); + + const { call } = await connectLocalToolsMcp(); + const refusedMcp = await call("inspect_gpu_code_objects", { + path: ptxPath, + analysis: "kernels", + detail: "complete", + max_report_bytes: 64, + }); + expect(refusedMcp.isError).toBe(true); + const mcpError = parseMcpToolError(refusedMcp).error; + expect(mcpError).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + parameter: "max_report_bytes", + effective_value: 64, + }, + refusal: { + kind: "adjustable_budget", + control: "max_report_bytes", + }, + }, + }); + expect( + (mcpError.details as { limit?: Record } | undefined) + ?.limit, + ).not.toHaveProperty("cli_flag"); + + const omittedMcp = await call("inspect_gpu_code_objects", { + path: ptxPath, + analysis: "kernels", + detail: "complete", + }); + expect(omittedMcp.isError, JSON.stringify(omittedMcp.content)).not.toBe( + true, + ); + expect(parseEvidence(omittedMcp.structuredContent).parameters).toEqual({ + path: ptxPath, + analysis: "kernels", + }); + }, +); diff --git a/tests/boundary/gpu/codeObjects.test.ts b/tests/boundary/gpu/codeObjects.test.ts index b41e772ed6..f3e88b0c10 100644 --- a/tests/boundary/gpu/codeObjects.test.ts +++ b/tests/boundary/gpu/codeObjects.test.ts @@ -15,9 +15,12 @@ import { parseEvidence } from "../../../src/domain/evidence.js"; import { gpuCodeObjectsPartialSchema, gpuCodeObjectsSchema, + inspectGpuCodeObjectsInputSchema, + type GpuCodeObjectsInput, } from "../../../src/domain/gpu/gpuCodeObjects.js"; import { GpuCodeObjectsProvider } from "../../../src/gpu/GpuCodeObjectsProvider.js"; import { GpuInventory } from "../../../src/gpu/GpuInventory.js"; +import { nextGpuContainerOffset } from "../../../src/gpu/GpuSource.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cudaFixture, @@ -37,12 +40,7 @@ import { } from "../../fixtures/gpu/codeObjects.js"; const inspect = async ( bytes: Buffer, - options: { - analysis?: "inventory" | "kernels"; - targets?: string[]; - object_ids?: string[]; - expected_sha256?: string; - } = {}, + options: Partial> = {}, ) => { const root = await createTestTempDirectory("rea-gpu-"), path = join(root, "no-format-extension"); @@ -2081,6 +2079,1152 @@ it("reports aggregate Clang directory capacity when every ID fits", async () => boundary: "hip-bundle-directory-bytes", maximum: 16_777_216, }, + limit: { + control_kind: "parameter", + parameter: "max_report_bytes", + effective_value: 16_777_216, + }, + refusal: { + kind: "adjustable_budget", + control: "max_report_bytes", + }, }, }); }); + +it("enforces per-call GPU budgets and recovers when raised", async () => { + const limitedReport = await inspect(Buffer.from(ptxFixture), { + analysis: "kernels", + max_report_bytes: 64, + }); + if (limitedReport.ok) throw new Error("Expected max_report_bytes refusal"); + expect(projectAnalysisError(limitedReport.error)).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { + limit: { + control_kind: "parameter", + parameter: "max_report_bytes", + effective_value: 64, + unit: "bytes", + maximum: 16 * 1024 * 1024, + default_value: 16 * 1024 * 1024, + }, + refusal: { + kind: "adjustable_budget", + operation: "inspect_gpu_code_objects", + control: "max_report_bytes", + }, + }, + }); + + // Exercise max_report_bytes past constructor overhead (after initial facts are retained). + const paddedPtx = Buffer.from(ptxFixture + "\n//" + "a".repeat(4096)); + const limitedReportRetention = await inspect(paddedPtx, { + analysis: "kernels", + max_report_bytes: 2048, + }); + if (limitedReportRetention.ok) + throw new Error("Expected post-constructor max_report_bytes refusal"); + expect(projectAnalysisError(limitedReportRetention.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_report_bytes", + effective_value: 2048, + }, + refusal: { + kind: "adjustable_budget", + control: "max_report_bytes", + }, + }, + }); + + const raisedReport = await inspect(paddedPtx, { + analysis: "kernels", + max_report_bytes: 1024 * 1024, + }); + expect(raisedReport.ok).toBe(true); + + const limitedToken = await inspect(hipFixture(), { + analysis: "inventory", + max_token_bytes: 4, + }); + if (limitedToken.ok) throw new Error("Expected max_token_bytes refusal"); + expect(projectAnalysisError(limitedToken.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_token_bytes", + effective_value: 4, + maximum: 65_536, + unit: "bytes", + }, + refusal: { + kind: "adjustable_budget", + control: "max_token_bytes", + }, + }, + }); + + const limitedEntries = await inspect(hipFixture(), { + analysis: "inventory", + max_parser_entries: 1, + }); + if (limitedEntries.ok) throw new Error("Expected max_parser_entries refusal"); + expect(projectAnalysisError(limitedEntries.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_parser_entries", + effective_value: 1, + maximum: 65_536, + unit: "count", + }, + refusal: { + kind: "adjustable_budget", + control: "max_parser_entries", + }, + }, + }); + + const recoveredHip = await inspect(hipFixture(), { + analysis: "inventory", + max_parser_entries: 16, + max_token_bytes: 128, + }); + expect(recoveredHip.ok).toBe(true); + + // max_object_bytes: standalone PTX refusal & recovery. + const limitedObject = await inspect(Buffer.from(ptxFixture), { + analysis: "kernels", + max_object_bytes: 64, + }); + if (limitedObject.ok) throw new Error("Expected max_object_bytes refusal"); + expect(projectAnalysisError(limitedObject.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_object_bytes", + effective_value: 64, + maximum: 128 * 1024 * 1024, + unit: "bytes", + }, + refusal: { + kind: "adjustable_budget", + control: "max_object_bytes", + }, + }, + }); + const recoveredObject = await inspect(Buffer.from(ptxFixture), { + analysis: "kernels", + max_object_bytes: 4096, + }); + expect(recoveredObject.ok).toBe(true); + + // max_work_bytes: per-object capacity limitation names max_work_bytes and recovers when raised. + const limitedWork = await inspect(cudaFixture("none"), { + analysis: "kernels", + max_work_bytes: 32, + }); + if (!limitedWork.ok) throw limitedWork.error; + expect(limitedWork.value.coverage.payloads).toBe("partial"); + expect( + limitedWork.value.objects.some( + (row) => + row.inspection === "capacity" && + row.limitations.some((note) => + note.includes("(parameter: max_work_bytes)"), + ), + ), + ).toBe(true); + const recoveredWork = await inspect(cudaFixture("none"), { + analysis: "kernels", + max_work_bytes: 1024 * 1024, + }); + if (!recoveredWork.ok) throw recoveredWork.error; + expect(recoveredWork.value.coverage.payloads).toBe("complete"); + + // max_structure_bytes: ELF section directory refusal & recovery. + const amdBytes = amdFixture(); + const limitedStructure = await inspect(amdBytes, { + analysis: "inventory", + max_structure_bytes: 64, + }); + if (limitedStructure.ok) + throw new Error("Expected max_structure_bytes refusal"); + expect(projectAnalysisError(limitedStructure.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_structure_bytes", + effective_value: 64, + maximum: 512 * 1024 * 1024, + unit: "bytes", + }, + refusal: { + kind: "adjustable_budget", + control: "max_structure_bytes", + }, + }, + }); + const recoveredStructure = await inspect(amdBytes, { + analysis: "inventory", + max_structure_bytes: 65_536, + }); + expect(recoveredStructure.ok).toBe(true); + + // max_metadata_bytes & max_parser_visits on AMDGPU metadata note. + const limitedMetadata = await inspect(amdBytes, { + analysis: "kernels", + max_metadata_bytes: 16, + }); + if (!limitedMetadata.ok) throw limitedMetadata.error; + expect(limitedMetadata.value.objects[0]).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining("(parameter: max_metadata_bytes)"), + ]), + }); + + const limitedVisits = await inspect(amdBytes, { + analysis: "kernels", + max_parser_visits: 2, + }); + if (!limitedVisits.ok) throw limitedVisits.error; + expect(limitedVisits.value.objects[0]).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining("(parameter: max_parser_visits)"), + ]), + }); + + const recoveredAmd = await inspect(amdBytes, { + analysis: "kernels", + max_metadata_bytes: 65_536, + max_parser_visits: 4096, + }); + if (!recoveredAmd.ok) throw recoveredAmd.error; + expect(recoveredAmd.value.objects[0]?.inspection).toBe("complete"); + expect(recoveredAmd.value.kernels.length).toBeGreaterThan(0); +}); + +it("respects max_object_bytes during container scanning and full-file digesting", async () => { + // Trailing NUL bytes past a HIP bundle must be scanned in chunks <= max_object_bytes + // on both readBounded and read fallback paths. + const paddedSourceBytes = Buffer.concat([ + Buffer.alloc(2048), + Buffer.from("CCOB"), + ]); + const boundedCalls: Array<{ size: number; limit: number }> = []; + const nextOffset = await nextGpuContainerOffset( + { + size: paddedSourceBytes.length, + containerId: null, + maxObjectBytes: 512, + async read(offset, size) { + return paddedSourceBytes.subarray(offset, offset + size); + }, + async readBounded(offset, size, limit) { + boundedCalls.push({ size, limit }); + return paddedSourceBytes.subarray(offset, offset + size); + }, + }, + 0, + ); + expect(nextOffset).toBe(2048); + expect(boundedCalls.length).toBeGreaterThan(1); + for (const call of boundedCalls) { + expect(call.size).toBeLessThanOrEqual(512); + expect(call.limit).toBeLessThanOrEqual(512); + } + + const smallBundle = hipFixture(Buffer.from("x"), "host-x86_64"); + const paddedBundle = Buffer.concat([smallBundle, Buffer.alloc(2048)]); + const scanned = await inspect(paddedBundle, { + analysis: "inventory", + max_object_bytes: 512, + }); + if (!scanned.ok) throw scanned.error; + expect(scanned.value.format).toBe("hip-bundle"); + expect(scanned.value.coverage.discovery).toBe("complete"); + + // Full-file SHA-256 digest streams independently of max_object_bytes instead of issuing 1-byte reads. + const largePtx = Buffer.concat([ + Buffer.from(ptxFixture), + Buffer.from("\n//" + "z".repeat(32 * 1024)), + ]); + const refused = await inspect(largePtx, { + analysis: "kernels", + max_object_bytes: 1, + }); + if (refused.ok) throw new Error("Expected max_object_bytes refusal"); + expect(projectAnalysisError(refused.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + parameter: "max_object_bytes", + effective_value: 1, + }, + refusal: { + kind: "adjustable_budget", + control: "max_object_bytes", + }, + }, + }); +}); + +it("keeps PTX single-parameter 128-token ceiling fixed independently of max_parser_entries", async () => { + const manyDimensions = "[1]".repeat(45); + const widePtx = Buffer.from( + `.version 8.8\n.target sm_80\n.address_size 64\n.visible .entry wide_param(.param .u32 p${manyDimensions}) {\nret;\n}\n`, + ); + const defaultRefused = await inspect(widePtx, { + analysis: "kernels", + }); + if (!defaultRefused.ok) throw defaultRefused.error; + expect(defaultRefused.value.objects[0]).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + "PTX parameter declaration exceeds the fixed 128-token syntax limit", + ]), + }); + expect( + defaultRefused.value.objects[0]?.limitations.some((l) => + l.includes("(parameter: max_parser_entries)"), + ), + ).toBe(false); + + // PTX 1.3 body .param declarations keep the same fixed 128-token limit under defaults. + const wideBodyParamPtx = Buffer.from( + `.version 1.3\n.target sm_10\n.entry wide_body() {\n.param .u32 p${manyDimensions};\nret;\n}\n`, + ); + const bodyRefused = await inspect(wideBodyParamPtx, { + analysis: "kernels", + }); + if (!bodyRefused.ok) throw bodyRefused.error; + expect(bodyRefused.value.objects[0]).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + "PTX parameter declaration exceeds the fixed 128-token syntax limit", + ]), + }); + expect( + bodyRefused.value.objects[0]?.limitations.some((l) => + l.includes("(parameter: max_parser_entries)"), + ), + ).toBe(false); + + // Lowering max_parser_entries below 128 does not reject a single normal parameter declaration. + const singleParamPtx = Buffer.from( + ".version 8.8\n.target sm_80\n.address_size 64\n.visible .entry add_one(.param .align 8 .u32 x[4]) {\nret;\n}\n", + ); + const singleParam = await inspect(singleParamPtx, { + analysis: "kernels", + max_parser_entries: 4, + }); + if (!singleParam.ok) throw singleParam.error; + expect(singleParam.value.objects[0]?.inspection).toBe("complete"); + expect(singleParam.value.kernels.map((k) => k.name)).toEqual(["add_one"]); +}); + +it("keeps corrupt CCOB v1 recovery distinct from max_object_bytes window truncation", async () => { + // Corrupt CCOB v1 bytes inside a container larger than max_object_bytes must stay + // malformed and still recover a later valid CCOB v2 sibling. + const smallBundle = hipFixture(Buffer.from("x"), "host-x86_64"); + const corruptV1 = Buffer.from(ccobFixture(1, "zlib", smallBundle)); + corruptV1.fill(0xff, 20); + const siblingV2 = ccobFixture(2, "zlib", smallBundle); + const combined = Buffer.concat([corruptV1, siblingV2, Buffer.alloc(600)]); + const recovered = await inspect(combined, { + analysis: "inventory", + max_object_bytes: 512, + }); + if (!recovered.ok) throw recovered.error; + const bundles = recovered.value.objects.filter( + (o) => o.kind === "hip-bundle", + ); + expect(bundles.map((b) => b.inspection)).toEqual(["malformed", "complete"]); + expect(recovered.value.objects.length).toBe(4); + + // A valid CCOB v1 stream whose compressed extent exceeds max_object_bytes + // while its declared decoded size fits triggers Z_BUF_ERROR -> capacity (max_object_bytes) + // and recovers once raised. + const storedCompressed = deflateSync(smallBundle, { level: 0 }); + const header = Buffer.from( + ccobFixture(1, "zlib", smallBundle).subarray(0, 20), + ); + const validV1 = Buffer.concat([header, storedCompressed]); + expect(storedCompressed.length).toBeGreaterThan(smallBundle.length); + const truncatedByBudget = await inspect(validV1, { + analysis: "inventory", + max_object_bytes: smallBundle.length, + }); + if (!truncatedByBudget.ok) throw truncatedByBudget.error; + expect(truncatedByBudget.value.objects[0]).toMatchObject({ + kind: "hip-bundle", + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining( + `Legacy CCOB v1 compressed payload exceeds the ${String(smallBundle.length)}-byte object budget (parameter: max_object_bytes)`, + ), + ]), + }); + const raisedV1 = await inspect(validV1, { + analysis: "inventory", + max_object_bytes: validV1.length + 64, + }); + if (!raisedV1.ok) throw raisedV1.error; + expect(raisedV1.value.objects[0]?.inspection).toBe("complete"); + + // Multi-frame Zstandard CCOB v1 whose declared decoded size fits every cut + // budget (so #budgetWork admits it and execution reaches inputExhausted): + // cutting at the exact frame boundary or inside the next frame's 4-byte magic + // must report ccobWindowLimit() capacity instead of publishing a short extent + // as malformed corruption, and must refill a cached legacy window cleanly. + const splitAt = Math.floor(smallBundle.length / 2); + const prefixChunkFrames: Buffer[] = []; + for (let offset = 0; offset < splitAt; offset += 4) { + prefixChunkFrames.push( + zstdCompressSync( + smallBundle.subarray(offset, Math.min(splitAt, offset + 4)), + ), + ); + } + const prefixFrames = Buffer.concat(prefixChunkFrames); + const finalFrame = zstdCompressSync(smallBundle.subarray(splitAt)); + const multiFrames = Buffer.concat([prefixFrames, finalFrame]); + expect(prefixFrames.length).toBeGreaterThanOrEqual(smallBundle.length); + const zstdHeader = Buffer.from( + ccobFixture(1, "zstd", smallBundle).subarray(0, 20), + ); + const multiFrameV1 = Buffer.concat([zstdHeader, multiFrames]); + for (const extra of [0, 1, 2, 3]) { + const budget = prefixFrames.length + extra; + expect(smallBundle.length).toBeLessThanOrEqual(budget); + expect(budget).toBeLessThan(multiFrames.length); + const cut = await inspect(multiFrameV1, { + analysis: "inventory", + max_object_bytes: budget, + }); + if (!cut.ok) throw cut.error; + expect(cut.value.objects).toHaveLength(1); + expect(cut.value.objects[0]).toMatchObject({ + kind: "hip-bundle", + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining( + `Legacy CCOB v1 compressed payload exceeds the ${String(budget)}-byte object budget (parameter: max_object_bytes)`, + ), + ]), + }); + } + const fullMultiFrame = await inspect(multiFrameV1, { + analysis: "inventory", + max_object_bytes: multiFrames.length + 64, + }); + if (!fullMultiFrame.ok) throw fullMultiFrame.error; + expect(fullMultiFrame.value.objects[0]?.inspection).toBe("complete"); + + // When a sibling's cached legacy window ends right between prefixFrames and + // finalFrame while max_object_bytes admits the full sibling, refill succeeds. + const prefixBundle = hipFixture( + Buffer.from("p".repeat(smallBundle.length)), + "host-x86_64", + ); + const prefixStored = deflateSync(prefixBundle, { level: 0 }); + const prefixHeader = Buffer.from( + ccobFixture(1, "zlib", prefixBundle).subarray(0, 20), + ); + const prefixV1 = Buffer.concat([prefixHeader, prefixStored]); + const cachedWindowCut = prefixStored.length + 20 + prefixFrames.length; + expect(cachedWindowCut).toBeGreaterThanOrEqual(smallBundle.length); + expect(cachedWindowCut).toBeGreaterThanOrEqual(multiFrames.length); + const twoSiblings = Buffer.concat([prefixV1, multiFrameV1]); + const refilledSiblings = await inspect(twoSiblings, { + analysis: "inventory", + max_object_bytes: cachedWindowCut, + }); + if (!refilledSiblings.ok) throw refilledSiblings.error; + expect( + refilledSiblings.value.objects + .filter((o) => o.kind === "hip-bundle") + .map((o) => o.inspection), + ).toEqual(["complete", "complete"]); + + // Trailing zero-output Zstandard frames (skippable frame and empty Zstd frame) + // after a complete data frame: cutting a budget or cached window at the frame + // boundary (+0), inside the tail magic (+1..+3), in the tail header, or in the + // tail body must refill when max_object_bytes admits the full stream or report + // ccobWindowLimit() capacity instead of publishing a short extent. + const skippablePayload = Buffer.from("skip-tail-payload"); + const skippableTail = Buffer.alloc(8 + skippablePayload.length); + skippableTail.writeUInt32LE(0x184d2a50, 0); + skippableTail.writeUInt32LE(skippablePayload.length, 4); + skippablePayload.copy(skippableTail, 8); + const emptyZstdTail = zstdCompressSync(Buffer.alloc(0)); + expect(emptyZstdTail.length).toBeGreaterThanOrEqual(8); + + const zeroOutputCases = [ + { + name: "skippable", + tail: skippableTail, + cuts: [0, 1, 2, 3, 6, 10], + }, + { + name: "empty-zstd", + tail: emptyZstdTail, + cuts: [0, 1, 2, 3, 5, emptyZstdTail.length - 1], + }, + ] as const; + + for (const { tail, cuts } of zeroOutputCases) { + const withTailEncoded = Buffer.concat([multiFrames, tail]); + const withTailV1 = Buffer.concat([zstdHeader, withTailEncoded]); + const siblingWithTail = Buffer.concat([prefixV1, withTailV1]); + for (const extra of cuts) { + // Budget cuts off the trailing zero-output frame: decoded === smallBundle.length + // already matches the declaration, yet capacity must be reported without a short extent. + const cutBudget = multiFrames.length + extra; + expect(smallBundle.length).toBeLessThanOrEqual(cutBudget); + expect(cutBudget).toBeLessThan(withTailEncoded.length); + const cutTail = await inspect(withTailV1, { + analysis: "inventory", + max_object_bytes: cutBudget, + }); + if (!cutTail.ok) throw cutTail.error; + expect(cutTail.value.objects).toHaveLength(1); + expect(cutTail.value.objects[0]).toMatchObject({ + kind: "hip-bundle", + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining( + `Legacy CCOB v1 compressed payload exceeds the ${String(cutBudget)}-byte object budget (parameter: max_object_bytes)`, + ), + ]), + }); + + // Cached window from sibling 1 ends inside sibling 2's trailing zero-output frame + // while max_object_bytes admits sibling 2 completely: refill must succeed cleanly. + const refillBudget = + prefixStored.length + 20 + multiFrames.length + extra; + expect(refillBudget).toBeGreaterThanOrEqual(withTailEncoded.length); + const refilledTail = await inspect(siblingWithTail, { + analysis: "inventory", + max_object_bytes: refillBudget, + }); + if (!refilledTail.ok) throw refilledTail.error; + const tailBundles = refilledTail.value.objects.filter( + (o) => o.kind === "hip-bundle", + ); + expect(tailBundles.map((b) => b.inspection)).toEqual([ + "complete", + "complete", + ]); + expect(tailBundles[1]?.encoded_size).toBe(withTailEncoded.length); + } + } + + // Exact-fit single-frame Zstd CCOB v1 followed by non-frame containers (CCOB v2, + // NUL padding, or __CLANG_OFFLOAD_BUNDLE__ whose leading '_' = 0x5f overlaps + // skippable magic's first byte) must not be falsely refused or trigger redundant + // work-budget-charging refills. + const exactFrame = zstdCompressSync(smallBundle); + const exactZstdV1 = Buffer.concat([zstdHeader, exactFrame]); + const trailingClangBundle = hipFixture(Buffer.from("next"), "host-x86_64"); + const exactWithNul = await inspect( + Buffer.concat([exactZstdV1, Buffer.alloc(4)]), + { + analysis: "inventory", + max_object_bytes: Math.max(smallBundle.length, exactFrame.length), + }, + ); + if (!exactWithNul.ok) throw exactWithNul.error; + expect(exactWithNul.value.coverage.discovery).toBe("complete"); + expect(exactWithNul.value.objects[0]?.inspection).toBe("complete"); + + const exactWithClang = await inspect( + Buffer.concat([exactZstdV1, trailingClangBundle]), + { + analysis: "inventory", + max_object_bytes: Math.max(smallBundle.length, exactFrame.length + 1), + }, + ); + if (!exactWithClang.ok) throw exactWithClang.error; + expect(exactWithClang.value.coverage.discovery).toBe("complete"); + expect( + exactWithClang.value.objects.every((o) => o.inspection === "complete"), + ).toBe(true); + + // Cached sibling window ending right at a complete Zstd sibling or 1 byte into + // the following __CLANG_OFFLOAD_BUNDLE__ ('_') must not refill and double-charge + // max_work_bytes under a tight work budget. + const tightThree = Buffer.concat([ + prefixV1, + exactZstdV1, + trailingClangBundle, + ]); + for (const extra of [0, 1]) { + const windowBudget = prefixStored.length + 20 + exactFrame.length + extra; + const tightWorkBudget = + windowBudget + prefixBundle.length + smallBundle.length; + const tightResult = await inspect(tightThree, { + analysis: "inventory", + max_object_bytes: windowBudget, + max_work_bytes: tightWorkBudget, + }); + if (!tightResult.ok) throw tightResult.error; + expect(tightResult.value.coverage.discovery).toBe("complete"); + expect( + tightResult.value.objects.every((o) => o.inspection === "complete"), + ).toBe(true); + } + + // Aliased targetless AMDGPU entries in a Clang offload bundle must charge + // their native section-table structure reads against max_work_bytes. + const amdElf = elfFixture( + 224, + Array.from({ length: 32 }, (_, index) => ({ + name: `.s${String(index)}`, + type: 1, + bytes: Buffer.alloc(0), + })), + ); + const aliasedCount = 40; + const aliasedId = Buffer.from("hipv4-amdgcn-amd-amdhsa--"); + const aliasedEntrySize = 8 + 8 + 8 + aliasedId.length; + const aliasedHeaderLen = 24 + 8 + aliasedCount * aliasedEntrySize; + const aliasedBundle = Buffer.alloc(aliasedHeaderLen + amdElf.length); + Buffer.from("__CLANG_OFFLOAD_BUNDLE__").copy(aliasedBundle, 0); + aliasedBundle.writeBigUInt64LE(BigInt(aliasedCount), 24); + for (let i = 0; i < aliasedCount; i += 1) { + const at = 32 + i * aliasedEntrySize; + aliasedBundle.writeBigUInt64LE(BigInt(aliasedHeaderLen), at); + aliasedBundle.writeBigUInt64LE(BigInt(amdElf.length), at + 8); + aliasedBundle.writeBigUInt64LE(BigInt(aliasedId.length), at + 16); + aliasedId.copy(aliasedBundle, at + 24); + } + amdElf.copy(aliasedBundle, aliasedHeaderLen); + + const amdWorkRefused = await inspect(aliasedBundle, { + analysis: "inventory", + max_work_bytes: 16_384, + }); + if (!amdWorkRefused.ok) throw amdWorkRefused.error; + expect( + amdWorkRefused.value.objects.some( + (o) => + o.inspection === "capacity" && + o.limitations.some((l) => l.includes("(parameter: max_work_bytes)")), + ), + ).toBe(true); + const amdWorkRaised = await inspect(aliasedBundle, { + analysis: "inventory", + max_work_bytes: 512 * 1024, + }); + if (!amdWorkRaised.ok) throw amdWorkRaised.error; + expect( + amdWorkRaised.value.objects.some((o) => o.inspection === "capacity"), + ).toBe(false); + + // max_work_bytes stays capped at main's 512 MiB heap ceiling. + const overWorkMax = inspectGpuCodeObjectsInputSchema.safeParse({ + path: "/tmp/sample.ptx", + analysis: "inventory", + max_work_bytes: 512 * 1024 * 1024 + 1, + }); + expect(overWorkMax.success).toBe(false); + const atWorkMax = inspectGpuCodeObjectsInputSchema.safeParse({ + path: "/tmp/sample.ptx", + analysis: "inventory", + max_work_bytes: 512 * 1024 * 1024, + }); + expect(atWorkMax.success).toBe(true); +}); + +it("does not double-charge work on CCOB v1 refill, bounds aliased sections, keeps non-GPU inputs unsupported, and aligns zstd.max_frames and recovery bounds", async () => { + // 1. Cached CCOB v1 refill charges declaredDecodedSize once, not twice. + const b1 = hipFixture(Buffer.alloc(200, 0x31), "host-x86_64"); + const c1 = deflateSync(b1, { level: 0 }); + const h1 = Buffer.from(ccobFixture(1, "zlib", b1).subarray(0, 20)); + const v1First = Buffer.concat([h1, c1]); + + const b2 = hipFixture(Buffer.alloc(120, 0x41), "host-x86_64"); + const f2a = zstdCompressSync(b2.subarray(0, 60)); + const f2b = zstdCompressSync(b2.subarray(60)); + const c2 = Buffer.concat([f2a, f2b]); + const h2 = Buffer.from(ccobFixture(1, "zstd", b2).subarray(0, 20)); + const v1Second = Buffer.concat([h2, c2]); + const refillPair = Buffer.concat([v1First, v1Second]); + const refillObjBudget = c1.length + 20 + f2a.length; + expect(refillObjBudget).toBeGreaterThanOrEqual(b2.length); + expect(refillObjBudget).toBeGreaterThanOrEqual(c2.length); + const exactWorkOnce = refillObjBudget + b1.length + b2.length + c2.length; + const refillOnce = await inspect(refillPair, { + analysis: "inventory", + max_object_bytes: refillObjBudget, + max_work_bytes: exactWorkOnce, + }); + if (!refillOnce.ok) throw refillOnce.error; + expect( + refillOnce.value.objects + .filter((o) => o.kind === "hip-bundle") + .map((o) => o.inspection), + ).toEqual(["complete", "complete"]); + + // 2. Second hasFollowingZstandardFrame check after refill prevents false capacity + // when cached window ends on sibling 2's exact frame boundary (triggering the + // inputExhausted refill path), refill completes sibling 2 at max_object_bytes, + // and 16 NUL bytes follow. + const small1 = hipFixture(Buffer.from("x"), "host-x86_64"); + const stored1 = deflateSync(small1, { level: 0 }); + const stored1V1 = Buffer.concat([ + Buffer.from(ccobFixture(1, "zlib", small1).subarray(0, 20)), + stored1, + ]); + const small2 = hipFixture(Buffer.from("x"), "host-x86_64"); + const manySmallFrames: Buffer[] = []; + for (let off = 0; off < small2.length; off += 2) { + manySmallFrames.push( + zstdCompressSync(small2.subarray(off, Math.min(small2.length, off + 2))), + ); + } + const manyEncoded = Buffer.concat(manySmallFrames); + const manyV1 = Buffer.concat([ + Buffer.from(ccobFixture(1, "zstd", small2).subarray(0, 20)), + manyEncoded, + ]); + // Align sibling 2 so window 1 (length === manyEncoded.length, starting at offset 20) + // ends on the exact boundary of sibling 2's first frame (available === firstFrameLen). + const firstFrameLen = manySmallFrames[0]!.length; + const alignPad = manyEncoded.length - stored1V1.length - firstFrameLen; + expect(alignPad).toBeGreaterThan(0); + const refillThenNul = Buffer.concat([ + stored1V1, + Buffer.alloc(alignPad), + manyV1, + Buffer.alloc(16), + ]); + const afterRefillNul = await inspect(refillThenNul, { + analysis: "inventory", + max_object_bytes: manyEncoded.length, + }); + if (!afterRefillNul.ok) throw afterRefillNul.error; + const refillNulBundles = afterRefillNul.value.objects.filter( + (o) => o.kind === "hip-bundle", + ); + expect(refillNulBundles.map((o) => o.inspection)).toEqual([ + "complete", + "complete", + ]); + expect(refillNulBundles[1]?.encoded_size).toBe(manyEncoded.length); + + // 3. 40 aliased .hip_fatbin sections pointing to a 3,860-byte PTX payload (all + // bytes read via sectionSource recognition) must yield exactly 4 complete and + // 36 capacity sections under max_work_bytes: 16_384. + const ptxHeader = ".version 8.8\n.target sm_80\n// "; + const ptxFooter = "\n.visible .entry k() { ret; }\n"; + const aliasedPtx = Buffer.from( + `${ptxHeader}${"x".repeat(3860 - ptxHeader.length - ptxFooter.length)}${ptxFooter}`, + ); + expect(aliasedPtx.length).toBe(3860); + const secCount = 40; + const totalSections = 2 + secCount; + const shstrtab = Buffer.from("\0.shstrtab\0.hip_fatbin\0"); + const payloadOff = 64; + const strOff = Math.ceil((payloadOff + aliasedPtx.length) / 8) * 8; + const shoff = Math.ceil((strOff + shstrtab.length) / 8) * 8; + const aliasedSectionElf = Buffer.alloc(shoff + totalSections * 64); + Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]).copy(aliasedSectionElf, 0); + aliasedSectionElf.writeUInt16LE(2, 16); + aliasedSectionElf.writeUInt16LE(62, 18); + aliasedSectionElf.writeUInt32LE(1, 20); + aliasedSectionElf.writeBigUInt64LE(BigInt(shoff), 40); + aliasedSectionElf.writeUInt16LE(64, 52); + aliasedSectionElf.writeUInt16LE(64, 58); + aliasedSectionElf.writeUInt16LE(totalSections, 60); + aliasedSectionElf.writeUInt16LE(1, 62); + aliasedPtx.copy(aliasedSectionElf, payloadOff); + shstrtab.copy(aliasedSectionElf, strOff); + const s1 = shoff + 64; + aliasedSectionElf.writeUInt32LE(1, s1); + aliasedSectionElf.writeUInt32LE(3, s1 + 4); + aliasedSectionElf.writeBigUInt64LE(BigInt(strOff), s1 + 24); + aliasedSectionElf.writeBigUInt64LE(BigInt(shstrtab.length), s1 + 32); + for (let i = 0; i < secCount; i += 1) { + const sh = shoff + (2 + i) * 64; + aliasedSectionElf.writeUInt32LE(11, sh); + aliasedSectionElf.writeUInt32LE(1, sh + 4); + aliasedSectionElf.writeBigUInt64LE(BigInt(payloadOff), sh + 24); + aliasedSectionElf.writeBigUInt64LE(BigInt(aliasedPtx.length), sh + 32); + } + const aliasedSectionRefused = await inspect(aliasedSectionElf, { + analysis: "inventory", + max_work_bytes: 16_384, + }); + if (!aliasedSectionRefused.ok) throw aliasedSectionRefused.error; + const nativeSections = aliasedSectionRefused.value.objects.filter( + (o) => o.kind === "native-section", + ); + expect( + nativeSections.filter((o) => o.inspection === "complete"), + ).toHaveLength(4); + const capacitySections = nativeSections.filter( + (o) => + o.inspection === "capacity" && + o.limitations.some((l) => l.includes("(parameter: max_work_bytes)")), + ); + expect(capacitySections).toHaveLength(36); + + // 3b. Single .hip_fatbin section with 6,060-byte PTX: + // (a) max_work_bytes: 6100 succeeds (no double-charge across recognition + probe read); + // (b) max_object_bytes: 4096 reports capacity (parameter: max_object_bytes). + const sectionPtx6060 = Buffer.from( + `${ptxHeader}${"y".repeat(6060 - ptxHeader.length - ptxFooter.length)}${ptxFooter}`, + ); + expect(sectionPtx6060.length).toBe(6060); + const singleSectionPtxElf = elfFixture(62, [ + { name: ".hip_fatbin", type: 1, bytes: sectionPtx6060 }, + ]); + const singleSectionWorkOk = await inspect(singleSectionPtxElf, { + analysis: "inventory", + max_work_bytes: 6100, + }); + if (!singleSectionWorkOk.ok) throw singleSectionWorkOk.error; + expect( + singleSectionWorkOk.value.objects.every( + (o) => o.inspection === "complete" || o.inspection === "inventory", + ), + ).toBe(true); + expect( + singleSectionWorkOk.value.objects.find((o) => o.kind === "native-section") + ?.inspection, + ).toBe("complete"); + + const singleSectionObjRefused = await inspect(singleSectionPtxElf, { + analysis: "inventory", + max_object_bytes: 4096, + }); + if (!singleSectionObjRefused.ok) throw singleSectionObjRefused.error; + expect( + singleSectionObjRefused.value.objects.find( + (o) => o.kind === "native-section", + ), + ).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining("(parameter: max_object_bytes)"), + ]), + }); + + // 3c. Metered #reserveReadWork, nested sectionSource !parentMetered, and + // #amdPayload child !parentMetered must each charge work once, not twice. + const ccobInnerPayload = hipFixture(Buffer.alloc(2000, 0x41), "host-x86_64"); + const ccobStoredV2 = ccobFixture(2, "zlib", ccobInnerPayload); + const ccobInSectionElf = elfFixture(62, [ + { name: ".hip_fatbin", type: 1, bytes: ccobStoredV2 }, + ]); + const ccobExactWork = 32 + 32 + ccobStoredV2.length + ccobInnerPayload.length; + const ccobSectionOk = await inspect(ccobInSectionElf, { + analysis: "inventory", + max_work_bytes: ccobExactWork, + }); + if (!ccobSectionOk.ok) throw ccobSectionOk.error; + expect( + ccobSectionOk.value.objects.find((o) => o.kind === "hip-bundle") + ?.inspection, + ).toBe("complete"); + + const nestedPtx = Buffer.from( + `${ptxHeader}${"n".repeat(2000 - ptxHeader.length - ptxFooter.length)}${ptxFooter}`, + ); + const innerElf = elfFixture(62, [ + { name: ".hip_fatbin", type: 1, bytes: nestedPtx }, + ]); + const outerElf = elfFixture(62, [ + { name: ".hip_fatbin", type: 1, bytes: innerElf }, + ]); + const nestedExactWork = innerElf.length + 256; + const nestedSectionOk = await inspect(outerElf, { + analysis: "inventory", + max_work_bytes: nestedExactWork, + }); + if (!nestedSectionOk.ok) throw nestedSectionOk.error; + expect( + nestedSectionOk.value.objects + .filter((o) => o.kind === "native-section") + .every((o) => o.inspection === "complete"), + ).toBe(true); + + const nestedAmdElf = elfFixture( + 224, + Array.from({ length: 48 }, (_, index) => ({ + name: `.s${String(index)}`, + type: 1, + bytes: Buffer.alloc(0), + })), + ); + const nestedAmdBundle = hipFixture(nestedAmdElf, "hipv4-amdgcn-amd-amdhsa--"); + const nestedAmdSectionElf = elfFixture(62, [ + { name: ".hip_fatbin", type: 1, bytes: nestedAmdBundle }, + ]); + const nestedAmdWork = nestedAmdElf.length + 512; + const nestedAmdOk = await inspect(nestedAmdSectionElf, { + analysis: "inventory", + max_work_bytes: nestedAmdWork, + }); + if (!nestedAmdOk.ok) throw nestedAmdOk.error; + expect( + nestedAmdOk.value.objects.some((o) => o.inspection === "capacity"), + ).toBe(false); + + // 4. Non-GPU plain text must fail with unsupported_target rather than being + // preempted by lowered max_object_bytes or max_token_bytes. + const plainLong = Buffer.from("hello world ".repeat(100)); // 1200 bytes + for (const budget of [512, 1]) { + const nonGpuObj = await inspect(plainLong, { + analysis: "inventory", + max_object_bytes: budget, + }); + expect(nonGpuObj.ok).toBe(false); + if (nonGpuObj.ok) return; + expect(projectAnalysisError(nonGpuObj.error)).toMatchObject({ + code: "unsupported_target", + }); + } + const plainWord = Buffer.from( + "this_is_plain_non_gpu_text_with_a_long_identifier_token_123", + ); + const nonGpuToken = await inspect(plainWord, { + analysis: "inventory", + max_token_bytes: 16, + }); + expect(nonGpuToken.ok).toBe(false); + if (nonGpuToken.ok) return; + expect(projectAnalysisError(nonGpuToken.error)).toMatchObject({ + code: "unsupported_target", + }); + + // Once PTX is recognized, max_token_bytes still applies to the .version header + // tokens in inventory mode (matching kernels mode) and prevents over-limit + // zero-padded version literals from bypassing the default token ceiling. + const ptxHeaderTooSmall = await inspect( + Buffer.from(".version 8.8\n.target sm_80\n"), + { + analysis: "inventory", + max_token_bytes: 7, + }, + ); + expect(ptxHeaderTooSmall.ok).toBe(false); + if (ptxHeaderTooSmall.ok) return; + expect(projectAnalysisError(ptxHeaderTooSmall.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { parameter: "max_token_bytes", effective_value: 7 }, + refusal: { kind: "adjustable_budget", control: "max_token_bytes" }, + }, + }); + const overDefaultVersionPtx = Buffer.from( + `.version ${"0".repeat(70_000)}8.0\n.target sm_80\n`, + ); + const ptxVersionOverDefault = await inspect(overDefaultVersionPtx, { + analysis: "inventory", + }); + expect(ptxVersionOverDefault.ok).toBe(false); + if (ptxVersionOverDefault.ok) return; + expect(projectAnalysisError(ptxVersionOverDefault.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { parameter: "max_token_bytes", effective_value: 65_536 }, + refusal: { kind: "adjustable_budget", control: "max_token_bytes" }, + }, + }); + + // 5. zstd.max_frames takes precedence over max_object_bytes at +0..+3 when + // lookahead confirms a following frame past the frame allowance. + const frameTarget = hipFixture(Buffer.from("x"), "host-x86_64"); + const bigSkipPayload = Buffer.alloc(frameTarget.length + 16); + const bigSkip = Buffer.alloc(8 + bigSkipPayload.length); + bigSkip.writeUInt32LE(0x184d2a50, 0); + bigSkip.writeUInt32LE(bigSkipPayload.length, 4); + const dataFrame = zstdCompressSync(frameTarget); + const skipThenDataV1 = Buffer.concat([ + Buffer.from(ccobFixture(1, "zstd", frameTarget).subarray(0, 20)), + bigSkip, + dataFrame, + ]); + for (const extra of [0, 1, 2, 3, 4]) { + const res = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "zstd.max_frames": 1 } }, + () => + inspect(skipThenDataV1, { + analysis: "inventory", + max_object_bytes: bigSkip.length + extra, + }), + ); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(res.error).toMatchObject({ + _tag: "AnalysisResourceConstraintError", + limit: { setting: "zstd.max_frames", effective_value: 1 }, + }); + } + + // 6. Corrupt CCOB v1 whose total extent equals max_object_bytes still recovers + // the immediately following valid CCOB v2 marker at offset === max_object_bytes. + const corruptExact = Buffer.concat([ + Buffer.from(ccobFixture(1, "zlib", small1).subarray(0, 20)), + Buffer.alloc(180, 0xff), + ]); + expect(corruptExact.length).toBe(200); + const nextValidV2 = ccobFixture(2, "zlib", small1); + const exactRecovery = await inspect( + Buffer.concat([corruptExact, nextValidV2]), + { + analysis: "inventory", + max_object_bytes: corruptExact.length, + }, + ); + if (!exactRecovery.ok) throw exactRecovery.error; + expect( + exactRecovery.value.objects + .filter((o) => o.kind === "hip-bundle") + .map((o) => o.inspection), + ).toEqual(["malformed", "complete"]); + + const overRecovery = await inspect( + Buffer.concat([corruptExact, Buffer.of(0xff), nextValidV2]), + { + analysis: "inventory", + max_object_bytes: corruptExact.length, + }, + ); + if (!overRecovery.ok) throw overRecovery.error; + expect( + overRecovery.value.objects + .filter((o) => o.kind === "hip-bundle") + .map((o) => o.inspection), + ).toEqual(["capacity"]); + + // 7. CudaFatbinary forwards AbortSignal to nextGpuContainerOffset during + // multi-megabyte NUL padding scans. + const cudaBase = cudaFixture("none"); + const paddedCuda = Buffer.concat([cudaBase, Buffer.alloc(2 * 1024 * 1024)]); + const abortController = new AbortController(); + let readsAfterStart = 0; + const origSource = new GpuInventory( + { path: "/padded-cuda", analysis: "inventory" }, + abortController.signal, + ); + await expect( + origSource.inspect({ + size: paddedCuda.length, + containerId: null, + read: async (offset, size) => paddedCuda.subarray(offset, offset + size), + readBounded: async (offset, size) => { + if (offset >= cudaBase.length && ++readsAfterStart === 17) + abortController.abort( + new Error("cancelled during cuda padding scan"), + ); + return paddedCuda.subarray(offset, offset + size); + }, + }), + ).rejects.toThrow(); +}); + +it("applies max_structure_bytes independently of max_object_bytes and covers PE, CUBIN, and report baseline", async () => { + // ELF section table (8 sections = 512 bytes) succeeds when max_structure_bytes admits it + // even if max_object_bytes is smaller (256 bytes). + const emptyElf = elfFixture( + 62, + Array.from({ length: 6 }, (_, i) => ({ + name: `.s${String(i)}`, + type: 1, + bytes: Buffer.alloc(8), + })), + ); + const elfOk = await inspect(emptyElf, { + analysis: "inventory", + max_object_bytes: 256, + max_structure_bytes: 65_536, + }); + if (!elfOk.ok) throw elfOk.error; + expect(elfOk.value.format).toBe("elf"); + expect(elfOk.value.coverage.discovery).toBe("complete"); + + // Baseline report reservation is enforced even when no GPU sections are present. + // Because this is a lower bound before later facts are retained, details.limit + // omits required_value and details.reported_limits records minimum_report_bytes. + const baselineRefused = await inspect(emptyElf, { + analysis: "inventory", + max_report_bytes: 500, + }); + if (baselineRefused.ok) + throw new Error("Expected baseline max_report_bytes refusal"); + const baselineProjected = projectAnalysisError(baselineRefused.error); + expect(baselineProjected).toMatchObject({ + code: "resource_constraint", + details: { + limit: { parameter: "max_report_bytes", effective_value: 500 }, + refusal: { kind: "adjustable_budget", control: "max_report_bytes" }, + }, + }); + const baselineDetails = baselineProjected.details as { + limit?: { required_value?: number }; + reported_limits?: { minimum_report_bytes?: number }; + }; + expect(baselineDetails.limit?.required_value).toBeUndefined(); + const minimumBaseline = baselineDetails.reported_limits?.minimum_report_bytes; + expect(minimumBaseline).toBeTypeOf("number"); + expect(minimumBaseline!).toBeGreaterThan(500); + const baselineRecovered = await inspect(emptyElf, { + analysis: "inventory", + max_report_bytes: minimumBaseline!, + }); + expect(baselineRecovered.ok).toBe(true); + + // PE section directory enforces max_structure_bytes and recovers when raised. + const peBytes = peGpuFixture(); + const peRefused = await inspect(peBytes, { + analysis: "inventory", + max_structure_bytes: 64, + }); + if (peRefused.ok) throw new Error("Expected PE max_structure_bytes refusal"); + expect(projectAnalysisError(peRefused.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { parameter: "max_structure_bytes", effective_value: 64 }, + refusal: { kind: "adjustable_budget", control: "max_structure_bytes" }, + }, + }); + const peRecovered = await inspect(peBytes, { + analysis: "inventory", + max_structure_bytes: 65_536, + }); + expect(peRecovered.ok).toBe(true); + + // CUBIN CudaMetadataBudget respects max_parser_visits and recovers when raised. + const cubinBytes = cubinFixture(); + const cubinLimited = await inspect(cubinBytes, { + analysis: "kernels", + max_parser_visits: 1, + }); + if (!cubinLimited.ok) throw cubinLimited.error; + expect(cubinLimited.value.objects[0]).toMatchObject({ + inspection: "capacity", + limitations: expect.arrayContaining([ + expect.stringContaining("(parameter: max_parser_visits)"), + ]), + }); + const cubinRecovered = await inspect(cubinBytes, { + analysis: "kernels", + max_parser_visits: 4096, + }); + if (!cubinRecovered.ok) throw cubinRecovered.error; + expect(cubinRecovered.value.objects[0]?.inspection).toBe("complete"); +});