diff --git a/docs/model-artifacts.md b/docs/model-artifacts.md index ab713bdbac8..d2122f85da1 100644 --- a/docs/model-artifacts.md +++ b/docs/model-artifacts.md @@ -1,9 +1,12 @@ # Model file declarations Use `inspect_model_artifact` (CLI: `inspect-model-artifact`) to inspect a local -GGUF v2/v3 or safetensors file. Detection uses content, including GGUF byte -order, rather than its extension. REA does not load a model, interpret weights, -run inference, import Python, open external-data references or use the network. +GGUF v2/v3 or safetensors file, a PyTorch checkpoint (`.pt`, `.pth`, `.ckpt` or +`.bin`, in the ZIP layout or the legacy `torch.save` layout) or a pickle stream. +Detection uses content, including GGUF byte order, rather than its extension. +REA does not load a model, interpret weights, run inference, unpickle, import +Python, open external-data references or use the network. See +[PyTorch checkpoints and pickle streams](#pytorch-checkpoints-and-pickle-streams). Little-endian GGUF v2/v3 and big-endian v3 are supported. Big-endian v2 is refused as "Big-endian GGUF requires version 3". Other versions are refused @@ -170,7 +173,8 @@ ranges, overlaps, gaps, trailing unindexed data and known dtype/shape byte-lengt contradictions are rejected as an invalid `path` (public code `invalid_request`, category `invalid_input`, issue reason `invalid_format`), like any other malformed or truncated model header. A form outside the reader's coverage, such -as a PyTorch pickle, is `unsupported_target`. +as a ZIP archive without a `/data.pkl` record or a pickle protocol above +5, is `unsupported_target`. A missing, non-regular or otherwise unusable selected path is `target_unavailable`; host I/O or resource failures on a valid selection, such as `EMFILE` or `EIO`, are `execution_failure` with the path and reason in `details.diagnostics`. Empty @@ -267,9 +271,106 @@ tensor layout and limits metadata array nesting to 32 frames. Resource refusals are typed, rather than returned as complete empty inventories. Cancellation joins descriptor finalization; failed cleanup remains owned for retry. -PyTorch pickle and ZIP model deserialization are unsupported; convert using a -trusted external workflow and supply GGUF or safetensors. ONNX, TFLite, Core ML, -model execution and conversion are outside this operation. +The pickle walker has two per-call admission limits that apply across every +stream of one file: `max_pickle_opcodes` (default 4,000,000, at most +16,000,000) and `max_pickle_memo_entries` (default 1,000,000, at most +16,000,000). Each opcode may allocate one modeled value, so the opcode limit +bounds memory as well as work. A refusal is `resource_constraint` with +`details.limit` naming the parameter (`control_kind: "parameter"`) and its +effective value; retry with a larger value. Pickle bytes count against the +100,000,000 byte header allowance: the prefix of a legacy or standalone file, +or the uncompressed `data.pkl` record of a ZIP checkpoint. + +ONNX, TFLite, Core ML, model execution and conversion are outside this +operation. + +## PyTorch checkpoints and pickle streams + +REA walks pickle opcodes (protocols 0–5) statically. It never unpickles, imports +a module, calls a callable or constructs an object; every value is a static +model of what loading would build. Detection is by content: a ZIP local header, +or a pickle `PROTO` opcode for protocol 2–5, when the bytes are not a +safetensors length followed by `{`. A protocol 0 or 1 stream is walked inside a +PyTorch ZIP but is not detected as a standalone file. + +`format` is `pytorch-zip`, `pytorch-legacy` or `pickle`: + +- `pytorch-zip`: the archive's single `/data.pkl` record names the + archive prefix. `pytorch.records` lists `data.pkl`, `version` (or + `.data/version`), `byteorder`, `.data/serialization_id`, `.format_version`, + `.storage_alignment`, unreferenced `data/` records and any other record, + with small text values. `version` and `alignment` come from the `version` and + `.storage_alignment` records. `byte_order` comes from the `byteorder` record; + when it is absent, PyTorch's loader assumes little-endian, but REA reports + `null`. `header_length` and `header_sha256` cover the uncompressed `data.pkl` + record, and header-mode `bytes_read` counts the record bytes REA read, not + ZIP directory reads. Storage bytes are records, so tensor `file_offset` and + `tensor_data_offset` are `null`, `data_offset` is relative to the storage + record and `source_offset` is relative to `data.pkl`. A storage that the + pickle references but the archive lacks is malformed. A ZIP without a + `/data.pkl` record stays `unsupported_target`. +- `pytorch-legacy`: the non-ZIP `torch.save` layout of five pickles (magic + number, protocol version 1001, `sys_info`, data, storage keys), then an + 8-byte element count and the bytes of each storage in key order. + `byte_order` comes from `sys_info.little_endian`, the header is the five + pickles, `tensor_data_offset` is the first storage count, and each storage + and tensor has a file offset. A storage count that disagrees with its + persistent ID, or storage bytes past the end of the file, is refused. +- `pickle`: any other protocol 2–5 stream. Only the first stream is read; + trailing bytes are noted. A standalone pickle has no storage bytes, so + storage sizes and tensor file offsets are unknown. + +`pickle.streams` records each stream's role, record or file offset, length, +protocol, opcode count, persistent IDs and values left on the stack at +`STOP`. `pickle.opcodes` counts each opcode. `pickle.references` lists every +`GLOBAL`, `STACK_GLOBAL`, `INST`, `OBJ`, `REDUCE`, `NEWOBJ`, `NEWOBJ_EX`, `BUILD` +and `EXT1`/`EXT2`/`EXT4` in stream order, with its offset (a file offset, or an +offset inside the stream's archive record) and `module.name`. A call or +`BUILD` names its callable when the stream states it as a global, including +through the memo; otherwise `name` is `null`. `BUILD` names the callable that +produced the object it updates. `pickle.callables` groups references by name, +with counts and the first offset. + +`allow_listed` marks the callables PyTorch's own writer emits to rebuild +tensors and state dicts: `collections.OrderedDict`, `torch.Size`, +`torch._utils._rebuild_tensor_v2`, `torch._utils._rebuild_tensor`, +`torch._utils._rebuild_parameter`, `torch._utils._rebuild_parameter_with_state` +and the `torch.Storage` classes. For every other name, a limitation states +that loading the file with an unrestricted unpickler would import or call it. +This is an observation of what the stream states, not a malware verdict: an +allow-listed name is not proof of safety, and a foreign name is not proof of +intent. + +Tensor rows come from `_rebuild_tensor_v2` and `_rebuild_tensor` calls whose +arguments state a storage persistent ID, offset, shape and stride, including +those wrapped by `_rebuild_parameter`. `type` is the storage dtype (for example +`float32`, `bfloat16`) or, for an unknown storage class, its name with unknown +byte lengths. `byte_length` is the storage span the shape and stride cover, and +an extent past the storage's declared element count is malformed. A tensor is +named by its key path from the pickled root, joined with `.`, when every step +is a string or integer dict key, `OrderedDict` key or list index and no +container on the path is shared; `json_pointer` then gives the exact path. +Other tensors are named `#` with a `null` pointer, and a key path that +collides with another row is treated the same way. A rebuild call whose +arguments cannot be read has no row; `coverage.storage_sizes` and +`coverage.tensor_ranges` are then `partial`. A protocol 0 integer longer than +an exact 64-byte long is reported as unknown rather than converted. `pytorch.storages` lists every +storage persistent ID in the data pickle, whether or not a tensor uses it, with +its key, class, dtype, location, element count, byte length and record or file +offset. Each one must have its storage bytes in the archive or legacy file. + +Malformed opcodes, truncated streams and memo misuse are refused as target +failures (`unsupported_target`) with `details.failure_kind` `malformed` or +`truncated` and `details.offset`: a file offset, or, inside a ZIP, an offset in the record that +`details.field` names. The MCP summary keeps `pickle.streams`, +`pickle.callables`, a reference count, a storage count and the first 16 +`pytorch.records` with `record_count` and `records_omitted`; complete Evidence +keeps every reference, record and storage. If full-file hashing fails or is +cancelled, the partial observation keeps the completed tensors, `pickle` and +`pytorch` facts. A PyTorch ZIP is read under the session ZIP member count, +`artifact.member_count`. Format references: +[pickletools opcodes](https://github.com/python/cpython/blob/v3.13.0/Lib/pickletools.py), +[torch.serialization](https://github.com/pytorch/pytorch/blob/v2.5.0/torch/serialization.py). Format references: [GGUF specification](https://github.com/ggml-org/ggml/blob/da8e2a54b919557b816b1c2beb432ccb766f7ce0/docs/gguf.md), [ggml tensor layouts](https://github.com/ggml-org/ggml/blob/da8e2a54b919557b816b1c2beb432ccb766f7ce0/src/ggml-common.h), diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index ae01917bdab..9a84e7f9624 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -135,7 +135,9 @@ their per-call budgets (`max_file_bytes`, entry, depth and decoded-byte budgets, `compare_wasm_interfaces` (`max_interface_bytes`), `trace_web_source_location` (`source_map_limits.*`), `inspect_v8_code_cache` (`max_file_bytes`, `max_strings`) and -`inspect_erlang_beam` report it too. The per-page symbol-name text allowance of `inspect_elf_unwind_ranges` is a fixed allowance (`details.refusal.kind` `fixed_ceiling`); its `narrowing` asks for a smaller page `limit` or paging with `offset`. `inspect_erlang_beam` accepts `max_table_rows` (export, +`inspect_erlang_beam` and `inspect_model_artifact` (`max_pickle_opcodes`, +`max_pickle_memo_entries`; see [model files](../model-artifacts.md#bounds-and-unsupported-inputs)) +report it too. The per-page symbol-name text allowance of `inspect_elf_unwind_ranges` is a fixed allowance (`details.refusal.kind` `fixed_ceiling`); its `narrowing` asks for a smaller page `limit` or paging with `offset`. `inspect_erlang_beam` accepts `max_table_rows` (export, import and lambda rows combined; default 65,536, at most 1,048,576). `inspect_python_pyc` reports `details.limit` for each of its per-call budgets (`max_file_bytes`, `max_objects`, `max_depth` and `max_string_bytes`). When a pyc limit is the product of two budgets (`max_objects` and `max_depth`), the refusal lists them in `details.related_parameters` instead. @@ -911,8 +913,8 @@ recovery names both routes: the field for one large artifact, then repeated work. When a non-default session value applies, inventory and extraction report the resolved `effective_limits` even if the call selected no `artifact_limits`. Other reader fields are per-call only. Flutter APK -inventory, Playwright trace import, and SAZ decoding have no `artifact_limits` -field. They admit central-directory records at this session count. A refusal +inventory, Playwright trace import, SAZ decoding and PyTorch checkpoint +inspection have no `artifact_limits` field. They admit central-directory records at this session count. A refusal stays that count and reports `artifact.member_count` as the limit, with `parameter` unset. Raise the count with `update_analysis_settings`, or correct `REA_ARTIFACT_MEMBER_COUNT` for a CLI process. Android JNI library inventory diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index 2cc3ebfffe0..2dbf328a8db 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -10,7 +10,7 @@ The table lists what REA returns for each target and which tools or host it requ | Offline ELF layout | Sections, segments, original symbols/relocations and static mitigation candidates | Caller-supplied pwntools on Linux x64; [binary diagnostics](../guides/native/binary-diagnostics.md) | | Go binaries | Embedded compiler version, modules, replacements and build settings | Built-in static ELF/PE/thin or universal Mach-O inspection; no Go installation required | | GPU code objects | CUDA/HIP/AMDGPU targets and ABI, kernel and AMD PAL pipeline declarations, retained PTX text | Built-in static ELF/PE/fatbin/CUBIN/PTX inspection; [GPU code objects](../gpu-code-objects.md) | -| Model artifacts | GGUF / safetensors metadata, tensor declarations and derived totals | Built-in header inspection; optional full-file hash; [model files](../model-artifacts.md) | +| Model artifacts | GGUF / safetensors / PyTorch / pickle declarations, tensors, pickle references and totals | Built-in header inspection and static pickle walk, never unpickled; optional full-file hash; [model files](../model-artifacts.md) | | IL2CPP metadata | Unity global-metadata.dat assembly images, type and method names and index ranges | Built-in static decoding of versions 24, 27, 29, 31 and 39; version 108 gets partial header and bounded string observation only; no Unity required | | Godot PCK | Archive inventory and extraction, original header/directory facts and selected content identities | Built-in static formats 1, 2, 3 and 4; no Godot required | | tar archives | Member inventory and extraction for stored and gzip tar, including `.unitypackage` | Built-in static ustar, pax and GNU headers; [tar archives](../tar-archives.md) | diff --git a/scripts/verify/advertised-schemas/tools/inspect_model_artifact.json b/scripts/verify/advertised-schemas/tools/inspect_model_artifact.json index 856f0af9bcc..9b5fa5b5ab1 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_model_artifact.json +++ b/scripts/verify/advertised-schemas/tools/inspect_model_artifact.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "7ef5e9d63dda272a", + "input compact": "cfb3695e8992df26", "output compact": "4babf3ed292a48aa" }, "patterns": { diff --git a/src/cli/modelCommands.ts b/src/cli/modelCommands.ts index 8681f16ce0d..cf41d31d548 100644 --- a/src/cli/modelCommands.ts +++ b/src/cli/modelCommands.ts @@ -21,7 +21,7 @@ export const registerModelCommands = ( INSPECT_MODEL_ARTIFACT_CONTRACT, { description: - "Inspect GGUF or safetensors headers without loading model weights", + "Inspect GGUF, safetensors, PyTorch checkpoint or pickle declarations without loading weights or unpickling", positionals: ["path"], callerPaths: ["path"], evidenceDelivery: true, diff --git a/src/config/artifactMemberCount.ts b/src/config/artifactMemberCount.ts index ee541f6f8f5..76a0a3512b2 100644 --- a/src/config/artifactMemberCount.ts +++ b/src/config/artifactMemberCount.ts @@ -64,7 +64,8 @@ export const runtimeArtifactMemberCount = ( /** * Member count for a ZIP reader whose caller has no `artifact_limits` field. * `environment` is the launch environment selected for this runtime. - * Flutter APK inventory, Playwright trace import, and SAZ decoding use this. + * Flutter APK inventory, Playwright trace import, SAZ decoding and PyTorch + * checkpoint inspection use this. */ export const operationZipMemberCount = ( environment: Readonly>, diff --git a/src/contracts/model/modelToolContracts.ts b/src/contracts/model/modelToolContracts.ts index 36928dea3a7..6bc512957c0 100644 --- a/src/contracts/model/modelToolContracts.ts +++ b/src/contracts/model/modelToolContracts.ts @@ -16,7 +16,7 @@ export const INSPECT_MODEL_ARTIFACT_CONTRACT = { ...toolContractMetadata("inspect_model_artifact", evidenceEffects), kind: "artifact-provider", description: - 'Inspect GGUF v2/v3 or safetensors metadata and tensor declarations without loading weights or running inference. Default hash header commits only a prefix: full-file SHA-256 and Evidence subject remain unknown; hash full streams every byte for file identity. Tensor shapes/IDs/offsets are observed; textual types and totals are derived, with ambiguous layouts retaining unknown byte lengths. Metadata arrays are eight-element previews; scalar metadata is complete. Default summary retains complete Evidence; detail complete returns all declarations inline. Optional view selects metadata/tensors/types. To page retained tensors, use inspect_analysis_view with source:{kind:"retained-evidence",evidence_id:""} and view:{kind:"model-artifact",collection:"tensors",offset:0,limit:32}. No payload inspection, quality claim, network, model runtime or pickle deserialization; one inspection at a time with explicit resource refusals.', + 'Inspect GGUF v2/v3, safetensors, PyTorch checkpoint (ZIP or legacy torch.save) or protocol 2-5 pickle declarations without loading weights, unpickling or running inference. Default hash header commits only a prefix (for PyTorch ZIP, data.pkl): full-file SHA-256 and Evidence subject remain unknown; hash full streams every byte for file identity. Tensor shapes/IDs/offsets are observed; textual types and totals are derived, with ambiguous layouts retaining unknown byte lengths. Pickles are walked statically: pickle.references lists every GLOBAL/STACK_GLOBAL/INST/OBJ/REDUCE/NEWOBJ/BUILD/EXT with its offset and whether it is on the tensor-rebuild allow-list; nothing is imported or called. max_pickle_opcodes and max_pickle_memo_entries bound the walk. Metadata arrays are eight-element previews; scalar metadata is complete. Default summary retains complete Evidence; detail complete returns all declarations inline. Optional view selects metadata/tensors/types. To page retained tensors, use inspect_analysis_view with source:{kind:"retained-evidence",evidence_id:""} and view:{kind:"model-artifact",collection:"tensors",offset:0,limit:32}. No payload inspection, quality claim, network or model runtime; one inspection at a time with explicit resource refusals.', inputSchema: inspectModelArtifactInputSchema, outputSchema: evidenceResultOf( z.union([ diff --git a/src/domain/analysisView/modelArtifactView.ts b/src/domain/analysisView/modelArtifactView.ts index bc13c4672ec..94a7952f419 100644 --- a/src/domain/analysisView/modelArtifactView.ts +++ b/src/domain/analysisView/modelArtifactView.ts @@ -10,6 +10,8 @@ import { modelMetadataSchema, modelTensorSchema, modelSourceSchema, + pickleSchema, + pytorchSchema, type ModelArtifact, } from "../model/modelArtifact.js"; import type { AnalysisError } from "../analysisErrorBase.js"; @@ -34,12 +36,33 @@ import { pageViewCoverage, } from "./analysisViewCoverage.js"; import { evidenceFileTarget } from "../evidence.js"; +import { boundedList } from "../boundedList.js"; const HEADLINE_TEXT_LIMIT = 512; +/** Compact pickle facts: per-callable groups stay inline; every reference stays in complete Evidence. */ +const pickleSummarySchema = pickleSchema + .omit({ references: true, opcodes: true }) + .extend({ reference_count: z.number().int().nonnegative() }); +/** Archive records are one per storage; the summary previews the first ones and counts the rest. */ +const SUMMARY_RECORD_LIMIT = 16; +const pytorchSummarySchema = pytorchSchema.omit({ storages: true }).extend({ + storage_count: z.number().int().nonnegative(), + record_count: z.number().int().nonnegative(), + records_omitted: z.number().int().nonnegative(), +}); + export const modelArtifactSummarySchema = modelArtifactObjectSchema - .omit({ metadata: true, tensors: true, totals: true }) + .omit({ + metadata: true, + tensors: true, + totals: true, + pickle: true, + pytorch: true, + }) .extend({ + pickle: pickleSummarySchema.optional(), + pytorch: pytorchSummarySchema.optional(), totals: modelArtifactObjectSchema.shape.totals.omit({ by_type: true }), counts: z.strictObject({ metadata: z.number().int().nonnegative(), @@ -63,6 +86,8 @@ const summarizeModel = ( tensors, metadata, totals: { by_type, ...totals }, + pickle, + pytorch, ...identity } = report; const headlineKeys = new Set([ @@ -82,6 +107,29 @@ const summarizeModel = ( headlineKeys.add(`${architecture}.context_length`); return { ...identity, + ...(pickle === undefined + ? {} + : { + pickle: { + streams: pickle.streams, + callables: pickle.callables, + reference_count: pickle.references.length, + }, + }), + ...(pytorch === undefined + ? {} + : { + pytorch: { + layout: pytorch.layout, + archive_prefix: pytorch.archive_prefix, + ...(({ items, omitted }) => ({ + records: [...items], + records_omitted: omitted, + }))(boundedList(pytorch.records, SUMMARY_RECORD_LIMIT)), + record_count: pytorch.records.length, + storage_count: pytorch.storages.length, + }, + }), totals, counts: { tensors: tensors.length, diff --git a/src/domain/model/modelArtifact.ts b/src/domain/model/modelArtifact.ts index d65e2be3a27..7ac49bcc14f 100644 --- a/src/domain/model/modelArtifact.ts +++ b/src/domain/model/modelArtifact.ts @@ -46,8 +46,10 @@ export const modelTensorSchema = z.strictObject({ type: z.string(), type_id: count.nullable(), shape: z.array(decimal), - data_offset: count, - file_offset: count, + /** Null only for PyTorch tensors whose element size is unknown. */ + data_offset: count.nullable(), + /** Null where storage bytes have no plain file position, such as ZIP records. */ + file_offset: count.nullable(), byte_length: count.nullable(), parameter_count: decimal, byte_length_state: z.enum(["derived", "declared", "unknown"]), @@ -55,13 +57,104 @@ export const modelTensorSchema = z.strictObject({ ...location, }); +export const modelFormatSchema = z.enum([ + "gguf", + "safetensors", + "pytorch-zip", + "pytorch-legacy", + "pickle", +]); + +const pickleStreamSchema = z.strictObject({ + index: count, + role: z.enum(["data", "magic", "protocol", "sys-info", "storage-keys"]), + /** Archive record holding the stream; null when it is read from the file itself. */ + member: z.string().nullable(), + /** File offset of the stream's first byte; null inside an archive record. */ + file_offset: count.nullable(), + length: count, + protocol: count.nullable(), + opcode_count: count, + persistent_ids: count, + /** Values left on the stack after STOP, which an unpickler ignores. */ + trailing_values: count, +}); + +/** Every import or call the stream states; nothing was imported or called. */ +export const pickleReferenceSchema = z.strictObject({ + index: count, + stream: count, + /** File offset, or the offset inside the stream's archive record. */ + offset: count, + opcode: z.string(), + /** `module.name`; null when the stream does not state it. */ + name: z.string().nullable(), + allow_listed: z.boolean(), +}); + +export const pickleSchema = z.strictObject({ + streams: z.array(pickleStreamSchema), + opcodes: z.array(z.strictObject({ opcode: z.string(), code: count, count })), + references: z.array(pickleReferenceSchema), + callables: z.array( + z.strictObject({ + name: z.string().nullable(), + allow_listed: z.boolean(), + references: count, + first_stream: count, + first_offset: count, + }), + ), +}); + +export const pytorchStorageSchema = z.strictObject({ + index: count, + key: z.string(), + storage_type: z.string().nullable(), + dtype: z.string().nullable(), + location: z.string().nullable(), + element_count: decimal.nullable(), + byte_length: count.nullable(), + /** ZIP record that holds the storage bytes. */ + record: z.string().nullable(), + record_bytes: count.nullable(), + /** File offset of legacy storage bytes after their element-count field. */ + file_offset: count.nullable(), + validation: z.enum(["consistent", "unknown"]), +}); + +export const pytorchSchema = z.strictObject({ + layout: z.enum(["zip", "legacy"]), + archive_prefix: z.string().nullable(), + records: z.array( + z.strictObject({ + name: z.string(), + role: z.enum([ + "data-pickle", + "version", + "byteorder", + "serialization-id", + "format-version", + "storage-alignment", + "storage", + "other", + ]), + bytes: count.nullable(), + value: z.string().nullable(), + }), + ), + storages: z.array(pytorchStorageSchema), +}); + export const modelArtifactObjectSchema = z.strictObject({ artifact: modelSourceSchema, - format: z.enum(["gguf", "safetensors"]), + format: modelFormatSchema, version: count.nullable(), - byte_order: z.enum(["little", "big"]), + /** Null when the file does not declare its storage byte order. */ + byte_order: z.enum(["little", "big"]).nullable(), alignment: count.nullable(), - tensor_data_offset: count, + /** Null where tensor bytes have no single file position. */ + tensor_data_offset: count.nullable(), metadata: z.array(modelMetadataSchema), tensors: z.array(modelTensorSchema), totals: z.strictObject({ @@ -84,11 +177,15 @@ export const modelArtifactObjectSchema = z.strictObject({ tensor_ranges: knownCoverageStatusSchema, storage_sizes: knownCoverageStatusSchema, }), + pickle: pickleSchema.optional(), + pytorch: pytorchSchema.optional(), limitations: z.array(z.string()), }); /** Facts proven before an interrupted model read reached final file identity checks. */ export const modelArtifactPartialTensorSchema = modelTensorSchema.extend({ + // Partial tensors are GGUF directory rows, which always declare a data offset. + data_offset: modelTensorSchema.shape.data_offset.unwrap(), file_offset: modelTensorSchema.shape.file_offset.nullable(), storage_validation: z.enum([ ...modelTensorSchema.shape.storage_validation.options, @@ -105,7 +202,7 @@ export const modelArtifactPartialSchema = z.strictObject({ sha256: z.null(), file_identity: z.literal("unverified"), }), - format: z.enum(["gguf", "safetensors"]), + format: modelFormatSchema, version: count.nullable(), byte_order: z.enum(["little", "big"]).nullable(), alignment: count.nullable(), @@ -114,6 +211,8 @@ export const modelArtifactPartialSchema = z.strictObject({ metadata: z.array(modelMetadataSchema), tensor_declarations: z.array(modelArtifactPartialTensorSchema), tensors: z.array(modelTensorSchema), + pickle: pickleSchema.optional(), + pytorch: pytorchSchema.optional(), coverage: z.strictObject({ header: knownCoverageStatusSchema, metadata: z.enum(["not-started", ...knownCoverageStatusSchema.options]), @@ -165,12 +264,21 @@ export const modelArtifactSchema = modelArtifactObjectSchema.superRefine( export type ModelArtifact = z.infer; export type ModelTensor = z.infer; +/** GGUF and safetensors rows always state both offsets. */ +export type LocatedModelTensor = ModelTensor & { + data_offset: number; + file_offset: number; +}; export type ModelMetadata = z.infer; export type ModelArtifactPartial = z.infer; +export type PickleFacts = z.infer; +export type PytorchFacts = z.infer; export type ModelArtifactPartialTensor = z.infer< typeof modelArtifactPartialTensorSchema >; export interface ModelArtifactInput { readonly path: string; readonly hash: "header" | "full"; + readonly max_pickle_opcodes?: number | undefined; + readonly max_pickle_memo_entries?: number | undefined; } diff --git a/src/domain/model/modelArtifactEvidence.ts b/src/domain/model/modelArtifactEvidence.ts index c6adffc5828..69deb6dd463 100644 --- a/src/domain/model/modelArtifactEvidence.ts +++ b/src/domain/model/modelArtifactEvidence.ts @@ -10,6 +10,18 @@ import type { ModelArtifactPartial, } from "./modelArtifact.js"; +/** Caller-selected pickle budgets are recorded only when the caller set them. */ +const modelEvidenceParameters = (parameters: ModelArtifactInput) => ({ + path: parameters.path, + hash: parameters.hash, + ...(parameters.max_pickle_opcodes === undefined + ? {} + : { max_pickle_opcodes: parameters.max_pickle_opcodes }), + ...(parameters.max_pickle_memo_entries === undefined + ? {} + : { max_pickle_memo_entries: parameters.max_pickle_memo_entries }), +}); + /** One Evidence interpretation for success and observations retained by file finalization failures. */ export const createModelArtifactEvidence = ( report: ModelArtifact | ModelArtifactPartial, @@ -30,12 +42,14 @@ export const createModelArtifactEvidence = ( provider, { operation: "inspect_model_artifact", - parameters: { path: parameters.path, hash: parameters.hash }, + parameters: modelEvidenceParameters(parameters), result: report, confidence: "observed", + // An interrupted read retains rows that own their offsets, and a ZIP + // checkpoint's header is its data.pkl record, not a file prefix. locations: [ { kind: "artifact-path", path: source.path }, - ...(interrupted + ...(interrupted || report.format === "pytorch-zip" ? [] : [ { diff --git a/src/domain/model/modelArtifactQuery.ts b/src/domain/model/modelArtifactQuery.ts index 49495a85660..5eaa824f02c 100644 --- a/src/domain/model/modelArtifactQuery.ts +++ b/src/domain/model/modelArtifactQuery.ts @@ -5,6 +5,35 @@ import { modelMetadataSchema, modelTensorSchema, } from "./modelArtifact.js"; +import { + parameterBudgetLimitFor, + type ParameterBudget, +} from "../parameterBudget.js"; + +/** Per-call admission limits of the static pickle walker. */ +export const MODEL_PICKLE_BUDGETS = { + /** Opcodes across every pickle stream of one file; each may allocate one value. */ + max_pickle_opcodes: { + minimum: 1, + maximum: 16_000_000, + default_value: 4_000_000, + unit: "count", + }, + /** Distinct memo keys across every pickle stream of one file. */ + max_pickle_memo_entries: { + minimum: 1, + maximum: 16_000_000, + default_value: 1_000_000, + unit: "count", + }, +} as const satisfies Record; +export type ModelPickleBudget = keyof typeof MODEL_PICKLE_BUDGETS; +export const modelPickleBudgetLimit = + parameterBudgetLimitFor(MODEL_PICKLE_BUDGETS); + +/** Omission stays visible in Evidence; the reader applies the default. */ +const optionalBudget = (budget: ParameterBudget) => + z.number().int().min(budget.minimum).max(budget.maximum).optional(); export const modelTypeRowSchema = modelArtifactObjectSchema.shape.totals.shape.by_type.element.extend({ @@ -64,6 +93,16 @@ export const inspectModelArtifactInputSchema = z .describe( "header reads declarations only; full streams all bytes for SHA-256", ), + max_pickle_opcodes: optionalBudget( + MODEL_PICKLE_BUDGETS.max_pickle_opcodes, + ).describe( + "Maximum pickle opcodes walked in a PyTorch checkpoint or pickle (default 4000000); exceeding it fails without partial success", + ), + max_pickle_memo_entries: optionalBudget( + MODEL_PICKLE_BUDGETS.max_pickle_memo_entries, + ).describe( + "Maximum distinct pickle memo entries (default 1000000); exceeding it fails without partial success", + ), detail: z.enum(["summary", "complete"]).default("summary"), view: modelArtifactSelectionSchema .optional() diff --git a/src/model/GgufHeader.ts b/src/model/GgufHeader.ts index a44b66766bc..1b8e2d05f58 100644 --- a/src/model/GgufHeader.ts +++ b/src/model/GgufHeader.ts @@ -5,7 +5,7 @@ import { setImmediate } from "node:timers/promises"; import type { JsonValue } from "../domain/jsonValue.js"; import type { ModelMetadata, - ModelTensor, + LocatedModelTensor, ModelArtifactPartialTensor, } from "../domain/model/modelArtifact.js"; import { ModelHeaderReader } from "./ModelHeaderReader.js"; @@ -292,7 +292,7 @@ export class GgufHeader { alignment: number; tensor_data_offset: number; metadata: ModelMetadata[]; - tensors: ModelTensor[]; + tensors: LocatedModelTensor[]; limitations: string[]; }> { const versionBytes = await this.reader.take(4); @@ -487,7 +487,7 @@ export class GgufHeader { rejectModel(`GGUF tensor ${tensor.name} range is outside the file`); tensor.file_offset = Number(offset); } - const completeTensors: ModelTensor[] = tensors.map((tensor) => ({ + const completeTensors: LocatedModelTensor[] = tensors.map((tensor) => ({ ...tensor, file_offset: tensor.file_offset!, storage_validation: diff --git a/src/model/ModelArtifactProvider.ts b/src/model/ModelArtifactProvider.ts index 257d9556c86..d36f8ffd70d 100644 --- a/src/model/ModelArtifactProvider.ts +++ b/src/model/ModelArtifactProvider.ts @@ -1,4 +1,5 @@ import { + artifactReaderTargetFailure, readerIntegrityFailure, ArtifactResourceScope, ArtifactReaderFailure, @@ -32,15 +33,32 @@ import { import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { err, ok, type Result } from "../domain/result.js"; import { ModelHeaderReader } from "./ModelHeaderReader.js"; +import { + readPickleFile, + readPytorchZip, + type PickleArtifact, +} from "./PytorchArtifactReader.js"; +import { readFileHandleRange } from "../filesystem/readFileHandleRange.js"; +import { + MODEL_PICKLE_BUDGETS, + modelPickleBudgetLimit, +} from "../domain/model/modelArtifactQuery.js"; +import { + isParseLimit, + parseLimitConstraint, + parseFailureAnalysisError, +} from "../domain/parseFailureAnalysisError.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; import { GgufHeader } from "./GgufHeader.js"; import { readSafetensorsHeader } from "./SafetensorsHeader.js"; import { + classifyModelPrefix, + MODEL_FORMAT, modelCapacityFailure, modelCapacityConstraint, MODEL_REPORT_BYTES, } from "./ModelFormat.js"; import { jsonValueByteLength } from "../domain/jsonValueByteLength.js"; -import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { isSelectedRegularFileError, @@ -50,6 +68,19 @@ import { errorMessage } from "../kernel/errorMessage.js"; import { hostDescriptorPressure } from "../process/hostDescriptorPressure.js"; const OPERATION = "inspect_model_artifact"; + +/** A per-call pickle budget stopped the walk; its recovery is the named parameter. */ +const pickleBudgetConstraint = (cause: unknown) => { + if (!isParseLimit(cause, MODEL_FORMAT)) return undefined; + const { name, maximum } = cause.failure.limit; + if (name !== "max_pickle_opcodes" && name !== "max_pickle_memo_entries") + return undefined; + return parseLimitConstraint(OPERATION, "capacity", cause, { + legacyMaximumKey: name, + retryable: false, + limit: modelPickleBudgetLimit(name, maximum), + }); +}; /** One admitted descriptor and bounded report at a time; retained cleanup blocks new work. */ export class ModelArtifactProvider implements ModelArtifactPort { readonly identity = MODEL_ARTIFACT_PROVIDER_IDENTITY; @@ -94,8 +125,8 @@ export class ModelArtifactProvider implements ModelArtifactPort { input.path, this.#resources, options?.signal, - ({ handle: file }) => - this.#read(file, input, options?.signal, (progress) => { + (source) => + this.#read(source, input, options?.signal, (progress) => { partialProgress = progress; }), ), @@ -104,12 +135,19 @@ export class ModelArtifactProvider implements ModelArtifactPort { } catch (cause) { const providerId = this.identity.id; const { cause: primary, origin } = artifactFilePrimaryFacts(cause); - const capacityError = modelCapacityConstraint(OPERATION, primary); + const capacityError = + modelCapacityConstraint(OPERATION, primary) ?? + pickleBudgetConstraint(primary); const formatError = parseFailureAnalysisError( OPERATION, input.path, primary, ); + // The shared ZIP reader owns malformed-archive facts for PyTorch ZIP checkpoints. + const zipTargetError = + origin === "owned-or-classified" + ? artifactReaderTargetFailure(OPERATION, input.path, primary) + : undefined; const selectedFile = isSelectedRegularFileError(primary) ? projectSelectedArtifactFileFailure( primary, @@ -123,6 +161,7 @@ export class ModelArtifactProvider implements ModelArtifactPort { error = primary; else if (capacityError !== undefined) error = capacityError; else if (formatError !== undefined) error = formatError; + else if (zipTargetError !== undefined) error = zipTargetError; else if ( origin === "owned-or-classified" && primary instanceof ArtifactReaderFailure && @@ -212,25 +251,247 @@ export class ModelArtifactProvider implements ModelArtifactPort { } async #read( - file: FileHandle, + source: StableRegularFileDescriptor, input: ModelArtifactInput, signal: AbortSignal | undefined, retainProgress: (progress: ModelArtifactPartial) => void, ): Promise { + const file = source.handle; const initial = await file.stat({ bigint: true }); if (initial.size > BigInt(Number.MAX_SAFE_INTEGER)) throw modelCapacityFailure( "exact-offset", "Model file exceeds exact host offset precision", ); - const reader = new ModelHeaderReader(file, Number(initial.size), signal); + const size = Number(initial.size); + // Fill the whole peek: one positional read may return fewer bytes. + const peek = await readFileHandleRange(file, 0, Math.min(9, size)); + const container = classifyModelPrefix(peek, size); + const { header_length, tensors_complete, ...parsedWithHashes } = + container === "pickle" || container === "zip" + ? await this.#readPickle( + source, + container, + input, + size, + signal, + retainProgress, + ) + : { + ...(await this.#readHeader( + file, + container, + input, + size, + signal, + retainProgress, + )), + // Header formats declare every tensor in their directory. + tensors_complete: true, + }; + const { header_sha256, sha256, bytes_read, ...parsed } = parsedWithHashes; + const hashes = { header_sha256, sha256, bytes_read }; + const after = await file.stat({ bigint: true }); + const named = await lstat(input.path, { bigint: true }).catch( + (cause: unknown) => { + if ( + cause instanceof Error && + "code" in cause && + ["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code)) + ) + throw new ArtifactReaderFailure( + "integrity", + "Selected model path changed during inspection", + { cause, integrityCheck: "container-identity" }, + ); + throw cause; + }, + ); + if ([after, named].some((stat) => !sameRegularFileState(initial, stat))) + throw new ArtifactReaderFailure( + "integrity", + "Model file changed during inspection", + { integrityCheck: "container-identity" }, + ); + const groups = new Map< + string, + { + type: string; + tensors: number; + parameter_count: bigint; + bytes: bigint | null; + } + >(); + let parameters = 0n; + let bytes: bigint | null = 0n; + for (const row of parsed.tensors) { + const count = BigInt(row.parameter_count); + parameters += count; + bytes = + bytes === null || row.byte_length === null + ? null + : bytes + BigInt(row.byte_length); + const group = groups.get(row.type) ?? { + type: row.type, + tensors: 0, + parameter_count: 0n, + bytes: 0n, + }; + group.tensors++; + group.parameter_count += count; + group.bytes = + group.bytes === null || row.byte_length === null + ? null + : group.bytes + BigInt(row.byte_length); + groups.set(row.type, group); + } + const maxSafe = BigInt(Number.MAX_SAFE_INTEGER); + // Byte totals become JSON numbers, so they must stay exact; parameter + // counts stay decimal strings and may exceed the safe range exactly. + if (bytes !== null && bytes > maxSafe) + throw modelCapacityFailure( + "exact-offset", + "Model tensor totals exceed exact host offset precision", + ); + for (const group of groups.values()) + if (group.bytes !== null && group.bytes > maxSafe) + throw modelCapacityFailure( + "exact-offset", + "Model tensor totals exceed exact host offset precision", + ); + const report = { + artifact: { + path: input.path, + file_size: Number(initial.size), + header_length, + ...hashes, + read_scope: + input.hash === "full" ? ("full-file" as const) : ("header" as const), + }, + ...parsed, + totals: { + confidence: "derived" as const, + parameter_count: parameters.toString(), + tensor_bytes: bytes === null ? null : Number(bytes), + by_type: [...groups.values()].map((group) => ({ + ...group, + bytes: group.bytes === null ? null : Number(group.bytes), + parameter_count: group.parameter_count.toString(), + })), + }, + coverage: { + header: "complete" as const, + tensor_data: "not-interpreted" as const, + array_values: parsed.metadata.every((row) => row.preview_complete) + ? ("complete" as const) + : ("partial" as const), + // A tensor rebuild call that could not be read leaves its tensor out of both. + storage_sizes: + tensors_complete && + parsed.tensors.every((row) => row.storage_validation === "consistent") + ? ("complete" as const) + : ("partial" as const), + tensor_ranges: + tensors_complete && + parsed.tensors.every((row) => row.byte_length !== null) + ? ("complete" as const) + : ("partial" as const), + }, + limitations: [ + "Facts are file declarations; model behavior, weight values and compatibility with an inference runtime were not verified.", + parsed.format === "pytorch-zip" + ? "Header SHA-256 commits only to the uncompressed data.pkl record; file size is a separate observation. Different weights may share these declarations." + : "Header SHA-256 commits only to the recorded prefix; file size is a separate observation. Different weights may share these declarations.", + ...(input.hash === "header" + ? ["Full-file SHA-256 is unknown because tensor data was not read."] + : [ + "Full-file SHA-256 required streaming the entire file, including tensor data, without interpreting it.", + ]), + ...(parsed.metadata.some((row) => !row.preview_complete) + ? [ + "Metadata arrays retain at most eight elements per array; remaining values are omitted, with exact declared counts and source byte ranges.", + ] + : []), + ...parsed.limitations, + ], + }; + if (jsonValueByteLength(report, MODEL_REPORT_BYTES) > MODEL_REPORT_BYTES) + throw modelCapacityFailure("report-bytes", "Model report exceeds 32 MiB"); + return modelArtifactSchema.parse(report); + } + + async #readPickle( + source: StableRegularFileDescriptor, + container: "pickle" | "zip", + input: ModelArtifactInput, + size: number, + signal: AbortSignal | undefined, + retainProgress: (progress: ModelArtifactPartial) => void, + ) { + // Completed facts stay retainable if full-file hashing then fails or is cancelled. + const retain = (facts: PickleArtifact) => { + retainProgress({ + kind: "model-artifact-partial", + artifact: { + path: input.path, + observed_file_size: size, + header_sha256: null, + sha256: null, + file_identity: "unverified", + }, + format: facts.format, + version: facts.version, + byte_order: facts.byte_order, + alignment: facts.alignment, + declared_metadata_count: null, + declared_tensor_count: null, + metadata: [], + tensor_declarations: [], + tensors: facts.tensors, + coverage: { + header: "complete", + metadata: "complete", + tensors: facts.tensors_complete ? "complete" : "partial", + }, + pickle: facts.pickle, + ...(facts.pytorch === undefined ? {} : { pytorch: facts.pytorch }), + limitations: [ + "Full-file hashing did not complete; the full-file SHA-256 and final file identity are unknown.", + "No model behavior or tensor payload values were interpreted.", + ...facts.limitations, + ], + }); + }; + const budgets = { + max_pickle_opcodes: + input.max_pickle_opcodes ?? + MODEL_PICKLE_BUDGETS.max_pickle_opcodes.default_value, + max_pickle_memo_entries: + input.max_pickle_memo_entries ?? + MODEL_PICKLE_BUDGETS.max_pickle_memo_entries.default_value, + }; + const full = input.hash === "full"; + return container === "pickle" + ? readPickleFile(source.handle, size, full, budgets, signal, retain) + : readPytorchZip(input.path, source, size, full, budgets, signal, retain); + } + + async #readHeader( + file: FileHandle, + container: "gguf" | "safetensors", + input: ModelArtifactInput, + size: number, + signal: AbortSignal | undefined, + retainProgress: (progress: ModelArtifactPartial) => void, + ) { + const reader = new ModelHeaderReader(file, size, signal); const first = await reader.take(4); - const format = first.equals(Buffer.from("GGUF")) ? "gguf" : "safetensors"; + const format = container; const partial: ModelArtifactPartial = { kind: "model-artifact-partial", artifact: { path: input.path, - observed_file_size: Number(initial.size), + observed_file_size: size, header_sha256: null, sha256: null, file_identity: "unverified", @@ -295,114 +556,11 @@ export class ModelArtifactProvider implements ModelArtifactPort { tensors: "complete", }; const header_length = reader.position; - const hashes = await reader.finish(input.hash === "full"); - const after = await file.stat({ bigint: true }); - const named = await lstat(input.path, { bigint: true }).catch( - (cause: unknown) => { - if ( - cause instanceof Error && - "code" in cause && - ["ENOENT", "ENOTDIR", "ELOOP"].includes(String(cause.code)) - ) - throw new ArtifactReaderFailure( - "integrity", - "Selected model path changed during inspection", - { cause, integrityCheck: "container-identity" }, - ); - throw cause; - }, - ); - if ([after, named].some((stat) => !sameRegularFileState(initial, stat))) - throw new ArtifactReaderFailure( - "integrity", - "Model file changed during inspection", - { integrityCheck: "container-identity" }, - ); - const groups = new Map< - string, - { - type: string; - tensors: number; - parameter_count: bigint; - bytes: number | null; - } - >(); - let parameters = 0n; - let bytes: number | null = 0; - for (const row of parsed.tensors) { - const count = BigInt(row.parameter_count); - parameters += count; - bytes = - bytes === null || row.byte_length === null - ? null - : bytes + row.byte_length; - const group = groups.get(row.type) ?? { - type: row.type, - tensors: 0, - parameter_count: 0n, - bytes: 0, - }; - group.tensors++; - group.parameter_count += count; - group.bytes = - group.bytes === null || row.byte_length === null - ? null - : group.bytes + row.byte_length; - groups.set(row.type, group); - } - const report = { - artifact: { - path: input.path, - file_size: Number(initial.size), - header_length, - ...hashes, - read_scope: - input.hash === "full" ? ("full-file" as const) : ("header" as const), - }, - format, + return { ...parsed, - totals: { - confidence: "derived" as const, - parameter_count: parameters.toString(), - tensor_bytes: bytes, - by_type: [...groups.values()].map((group) => ({ - ...group, - parameter_count: group.parameter_count.toString(), - })), - }, - coverage: { - header: "complete" as const, - tensor_data: "not-interpreted" as const, - array_values: parsed.metadata.every((row) => row.preview_complete) - ? ("complete" as const) - : ("partial" as const), - storage_sizes: parsed.tensors.every( - (row) => row.storage_validation === "consistent", - ) - ? ("complete" as const) - : ("partial" as const), - tensor_ranges: parsed.tensors.every((row) => row.byte_length !== null) - ? ("complete" as const) - : ("partial" as const), - }, - limitations: [ - "Facts are file declarations; model behavior, weight values and compatibility with an inference runtime were not verified.", - "Header SHA-256 commits only to the recorded prefix; file size is a separate observation. Different weights may share these declarations.", - ...(input.hash === "header" - ? ["Full-file SHA-256 is unknown because tensor data was not read."] - : [ - "Full-file SHA-256 required streaming the entire file, including tensor data, without interpreting it.", - ]), - ...(parsed.metadata.some((row) => !row.preview_complete) - ? [ - "Metadata arrays retain at most eight elements per array; remaining values are omitted, with exact declared counts and source byte ranges.", - ] - : []), - ...parsed.limitations, - ], + format, + header_length, + ...(await reader.finish(input.hash === "full")), }; - if (jsonValueByteLength(report, MODEL_REPORT_BYTES) > MODEL_REPORT_BYTES) - throw modelCapacityFailure("report-bytes", "Model report exceeds 32 MiB"); - return modelArtifactSchema.parse(report); } } diff --git a/src/model/ModelFormat.ts b/src/model/ModelFormat.ts index 7eae5ff4832..36a6d656aa6 100644 --- a/src/model/ModelFormat.ts +++ b/src/model/ModelFormat.ts @@ -1,3 +1,4 @@ +import { BinaryReader } from "../domain/binaryContainer.js"; import { Budget } from "../domain/budget.js"; import { decodeLimit, @@ -10,7 +11,7 @@ import { parseLimitConstraint, } from "../domain/parseFailureAnalysisError.js"; -/** The ParseFailure format of GGUF and Safetensors model headers. */ +/** The ParseFailure format of GGUF, Safetensors, PyTorch and pickle model headers. */ export const MODEL_FORMAT = "model"; /** A fixed model allowance refused the input; the limit name is its {@link ModelCapacityLimit}. */ @@ -23,16 +24,54 @@ export const modelCapacityFailure = ( maximum: modelCapacityLimits[limit].maximum, }); -export function rejectModel(message: string): never { - throw malformedInput(MODEL_FORMAT, message); +export function rejectModel( + message: string, + site?: { readonly offset?: number; readonly field?: string }, +): never { + throw malformedInput(MODEL_FORMAT, message, site); } -export function rejectPickle(): never { +/** How the first bytes frame the file; each reader owns the rest of its format. */ +export type ModelContainer = "gguf" | "safetensors" | "pickle" | "zip"; + +const GGUF_MAGIC = Buffer.from("GGUF"); +const ZIP_LOCAL_HEADER = Buffer.from([0x50, 0x4b, 3, 4]); + +/** + * Classify a model file from up to its first nine bytes. A safetensors length + * prefix can begin like a pickle PROTO opcode (640 is 80 02 ...) or a ZIP + * local header; a brace after an admissible length is safetensors, even if + * the header is later truncated. + */ +export const classifyModelPrefix = ( + prefix: Buffer, + size: number, +): ModelContainer => { + const head = prefix.subarray(0, 4); + if (head.equals(GGUF_MAGIC)) return "gguf"; + const protocol = prefix[1] ?? 0; + const pickle = prefix[0] === 0x80 && protocol >= 2 && protocol <= 5; + const zip = head.equals(ZIP_LOCAL_HEADER); + if (!pickle && !zip) return "safetensors"; + if (size >= 9 && prefix.length >= 9) { + const length = new BinaryReader(prefix, true, MODEL_FORMAT).word(0, 64); + if ( + length !== 0n && + prefix[8] === 0x7b && + length <= BigInt(MODEL_HEADER_BYTES) + ) + return "safetensors"; + } + return pickle ? "pickle" : "zip"; +}; + +/** A ZIP archive without PyTorch's record layout is another package format. */ +export const rejectForeignZip = (detail: string): never => { throw unsupportedInput( MODEL_FORMAT, - "PyTorch pickle/ZIP model deserialization is unsupported; supply GGUF or safetensors instead", + `${detail}; inspect_model_artifact reads GGUF, safetensors, PyTorch checkpoints and pickle streams`, ); -} +}; // Shared header ceiling for GGUF and Safetensors. Safetensors counts declared // JSON bytes after the eight-byte length prefix; GGUF counts the complete diff --git a/src/model/PickleInspection.ts b/src/model/PickleInspection.ts new file mode 100644 index 00000000000..6018e5a1746 --- /dev/null +++ b/src/model/PickleInspection.ts @@ -0,0 +1,652 @@ +import { boundedList } from "../domain/boundedList.js"; +import { escapeJsonPointerToken } from "../domain/jsonPointer.js"; +import type { + ModelTensor, + PickleFacts, + PytorchFacts, +} from "../domain/model/modelArtifact.js"; +import { + modelCapacityFailure, + rejectModel, + type ModelReportBudget, +} from "./ModelFormat.js"; +import { + calleeName, + pickleOpcodeName, + type PickleCall, + type PickleNode, + type PickleWalker, +} from "./PickleWalker.js"; + +type StreamRole = PickleFacts["streams"][number]["role"]; +type PytorchStorage = PytorchFacts["storages"][number]; + +export interface WalkedStream { + readonly walker: PickleWalker; + readonly role: StreamRole; + readonly length: number; +} + +interface StorageType { + readonly dtype: string; + readonly itemsize: number; +} + +const STORAGE_TYPES: Readonly> = { + DoubleStorage: { dtype: "float64", itemsize: 8 }, + FloatStorage: { dtype: "float32", itemsize: 4 }, + HalfStorage: { dtype: "float16", itemsize: 2 }, + BFloat16Storage: { dtype: "bfloat16", itemsize: 2 }, + LongStorage: { dtype: "int64", itemsize: 8 }, + IntStorage: { dtype: "int32", itemsize: 4 }, + ShortStorage: { dtype: "int16", itemsize: 2 }, + CharStorage: { dtype: "int8", itemsize: 1 }, + ByteStorage: { dtype: "uint8", itemsize: 1 }, + BoolStorage: { dtype: "bool", itemsize: 1 }, + ComplexDoubleStorage: { dtype: "complex128", itemsize: 16 }, + ComplexFloatStorage: { dtype: "complex64", itemsize: 8 }, + UInt16Storage: { dtype: "uint16", itemsize: 2 }, + UInt32Storage: { dtype: "uint32", itemsize: 4 }, + UInt64Storage: { dtype: "uint64", itemsize: 8 }, + Float8_e5m2Storage: { dtype: "float8_e5m2", itemsize: 1 }, + Float8_e4m3fnStorage: { dtype: "float8_e4m3fn", itemsize: 1 }, + Float8_e5m2fnuzStorage: { dtype: "float8_e5m2fnuz", itemsize: 1 }, + Float8_e4m3fnuzStorage: { dtype: "float8_e4m3fnuz", itemsize: 1 }, + QInt8Storage: { dtype: "qint8", itemsize: 1 }, + QUInt8Storage: { dtype: "quint8", itemsize: 1 }, + QInt32Storage: { dtype: "qint32", itemsize: 4 }, + UntypedStorage: { dtype: "uint8", itemsize: 1 }, +}; + +const storageType = (name: string | null): StorageType | undefined => { + if (name === null) return undefined; + const match = /^torch\.(?:cuda\.)?([A-Za-z0-9_]+)$/u.exec(name); + const key = match?.[1]; + return key !== undefined && Object.hasOwn(STORAGE_TYPES, key) + ? STORAGE_TYPES[key] + : undefined; +}; + +const TENSOR_REBUILDERS = new Set([ + "torch._utils._rebuild_tensor_v2", + "torch._utils._rebuild_tensor", +]); +const PARAMETER_REBUILDERS = new Set([ + "torch._utils._rebuild_parameter", + "torch._utils._rebuild_parameter_with_state", +]); +const ORDERED_DICT = "collections.OrderedDict"; + +/** + * Callables PyTorch's own writer emits to rebuild tensors and state dicts. + * Membership is a familiarity fact for reporting, not a safety verdict. + */ +export const isAllowListedCallable = (name: string | null): boolean => + name !== null && + (name === ORDERED_DICT || + name === "torch.Size" || + TENSOR_REBUILDERS.has(name) || + PARAMETER_REBUILDERS.has(name) || + storageType(name) !== undefined); + +const NAMED_LIMIT = 8; + +/** Aggregate walked streams into reported pickle facts. */ +export const pickleFacts = ( + streams: readonly WalkedStream[], + budget: ModelReportBudget, +): { facts: PickleFacts; limitations: string[] } => { + const opcodes = new Map(); + const references: PickleFacts["references"] = []; + const callables = new Map(); + streams.forEach(({ walker }, stream) => { + for (const [code, count] of walker.opcodes) + opcodes.set(code, (opcodes.get(code) ?? 0) + count); + for (const reference of walker.references) { + budget.charge(96 + 2 * (reference.name?.length ?? 0)); + const allow_listed = isAllowListedCallable(reference.name); + references.push({ + index: references.length, + stream, + offset: reference.offset, + opcode: reference.opcode, + name: reference.name, + allow_listed, + }); + const group = callables.get(reference.name); + if (group === undefined) { + budget.charge(96 + 2 * (reference.name?.length ?? 0)); + callables.set(reference.name, { + name: reference.name, + allow_listed, + references: 1, + first_stream: stream, + first_offset: reference.offset, + }); + } else group.references++; + } + }); + const foreign = [...callables.values()].filter( + (group) => group.name !== null && !group.allow_listed, + ); + const limitations = [ + "Pickle values were modeled statically: no module was imported, no callable was run and no object was constructed. The allow-list marks callables PyTorch writes to rebuild tensors and state dicts; it is not a safety verdict.", + ]; + if (foreign.length > 0) { + const shown = boundedList(foreign, NAMED_LIMIT); + const named = shown.items + .map( + (group) => + `${group.name ?? "an unnamed callable"} (stream ${String(group.first_stream)}, offset ${String(group.first_offset)})`, + ) + .join(", "); + limitations.push( + `Loading this file with an unrestricted unpickler would import or call ${String(foreign.length)} callable(s) outside the tensor-rebuild allow-list: ${named}${shown.omitted > 0 ? `, and ${String(shown.omitted)} more listed in pickle.callables` : ""}. REA recorded these references without importing or calling them.`, + ); + } + for (const [index, { walker }] of streams.entries()) + if (walker.trailingValues > 0) + limitations.push( + `Pickle stream ${String(index)} left ${String(walker.trailingValues)} value(s) on the stack at STOP; an unpickler ignores them.`, + ); + return { + facts: { + streams: streams.map(({ walker, role, length }, index) => ({ + index, + role, + member: walker.site.member, + file_offset: walker.site.fileOffset, + length, + protocol: walker.protocol, + opcode_count: walker.opcodeCount, + persistent_ids: walker.persistentIds, + trailing_values: walker.trailingValues, + })), + opcodes: [...opcodes] + .sort(([left], [right]) => left - right) + .map(([code, count]) => ({ + opcode: pickleOpcodeName(code), + code, + count, + })), + references, + callables: [...callables.values()], + }, + limitations, + }; +}; + +const exactInt = (node: PickleNode | undefined): bigint | undefined => + node?.kind === "int" && node.value !== null ? node.value : undefined; + +const text = (node: PickleNode | undefined): string | undefined => + node?.kind === "str" ? node.value : undefined; + +const tupleItems = (node: PickleNode | undefined): PickleNode[] | undefined => + node?.kind === "tuple" ? node.items : undefined; + +// Checked shape/stride tuples are shared: a memoized tuple reached by many +// rebuild calls is converted once, not copied per call. +const countsCache = new WeakMap(); + +const counts = (node: PickleNode | undefined): bigint[] | undefined => { + if (node === undefined) return undefined; + const cached = countsCache.get(node); + if (cached !== undefined || countsCache.has(node)) return cached; + const items = tupleItems(node); + const values = items?.map(exactInt); + const result = + values !== undefined && + values.every((value) => value !== undefined && value >= 0n) + ? (values as bigint[]) + : undefined; + countsCache.set(node, result); + return result; +}; + +/** A persistent ID PyTorch writes for a storage: ('storage', type, key, location, numel, ...). */ +export interface StorageReference { + readonly key: string; + readonly storageType: string | null; + readonly location: string | null; + readonly elementCount: bigint | null; +} + +export const storageReference = ( + node: PickleNode, +): StorageReference | undefined => { + if (node.kind !== "persistent") return undefined; + const items = tupleItems(node.pid); + if (items === undefined || text(items[0]) !== "storage") return undefined; + const key = text(items[2]); + if (key === undefined) return undefined; + const type = items[1]; + const elements = exactInt(items[4]); + return { + key, + storageType: type === undefined ? null : calleeName(type), + location: text(items[3]) ?? null, + elementCount: elements !== undefined && elements >= 0n ? elements : null, + }; +}; + +interface TensorCall { + readonly call: PickleCall; + readonly storage: StorageReference; + readonly storageOffset: bigint; + readonly shape: bigint[]; + readonly stride: bigint[]; +} + +type TensorReading = TensorCall | "uninterpretable" | undefined; + +/** Read the rebuild call a node states; parameter wrappers unwrap iteratively. */ +const readTensor = ( + node: PickleNode, + memo: Map, +): TensorReading => { + if (node.kind !== "call") return undefined; + // Collect a wrapper chain first, so a deep chain neither recurses nor repeats work. + const wrappers: PickleCall[] = []; + let current: PickleNode = node; + let reading: TensorReading; + for (;;) { + if (memo.has(current)) { + reading = memo.get(current); + break; + } + if (current.kind !== "call") { + reading = wrappers.length === 0 ? undefined : "uninterpretable"; + break; + } + const name = calleeName(current.callable); + const args = tupleItems(current.args); + if (name !== null && PARAMETER_REBUILDERS.has(name)) { + const data = args?.[0]; + wrappers.push(current); + if (data === undefined) { + reading = "uninterpretable"; + break; + } + current = data; + continue; + } + if (name === null || !TENSOR_REBUILDERS.has(name)) { + reading = wrappers.length === 0 ? undefined : "uninterpretable"; + memo.set(current, undefined); + break; + } + reading = rebuildCall(current, args); + memo.set(current, reading); + break; + } + // A non-tensor reached through a wrapper is not a tensor of that wrapper. + if (reading === undefined && wrappers.length > 0) reading = "uninterpretable"; + for (let index = wrappers.length - 1; index >= 0; index--) { + const wrapper = wrappers[index]!; + reading = + reading === undefined || reading === "uninterpretable" + ? "uninterpretable" + : { ...reading, call: wrapper }; + memo.set(wrapper, reading); + } + return reading; +}; + +const rebuildCall = ( + call: PickleCall, + args: PickleNode[] | undefined, +): TensorReading => { + const storage = + args?.[0] === undefined ? undefined : storageReference(args[0]); + const storageOffset = exactInt(args?.[1]); + const shape = counts(args?.[2]); + const stride = counts(args?.[3]); + if ( + storage === undefined || + storageOffset === undefined || + storageOffset < 0n || + shape === undefined || + stride === undefined || + shape.length !== stride.length + ) + return "uninterpretable"; + return { call, storage, storageOffset, shape, stride }; +}; + +type Edge = { readonly parent: PickleNode; readonly label: string | null }; + +const keyLabel = (key: PickleNode): string | null => + key.kind === "str" + ? key.value + : key.kind === "int" && key.value !== null + ? key.value.toString() + : null; + +/** Children that may hold tensors, labelled when the container states an exact key or index. */ +const children = (node: PickleNode): [PickleNode, string | null][] => { + switch (node.kind) { + case "dict": + return node.entries.map(([key, value]) => [value, keyLabel(key)]); + case "list": + case "tuple": + return node.items.map((item, index) => [item, String(index)]); + case "set": + return node.items.map((item) => [item, null]); + case "call": { + // state_dict() pickles as OrderedDict() + SETITEMS, then BUILD of its _metadata attribute. + const keyed = + calleeName(node.callable) === ORDERED_DICT && + (tupleItems(node.args)?.length ?? 1) === 0 && + node.items.length === 0; + return [ + ...(keyed ? [] : [[node.args, null] as [PickleNode, null]]), + ...node.items.map((item): [PickleNode, null] => [item, null]), + ...node.entries.map(([key, value]): [PickleNode, string | null] => [ + value, + keyed ? keyLabel(key) : null, + ]), + ...node.states.map((state): [PickleNode, null] => [state, null]), + ]; + } + default: + return []; + } +}; + +export interface PlacedTensor { + readonly tensor: TensorCall; + /** Exact container keys from the root, or undefined when not unambiguous. */ + readonly path: string[] | undefined; +} + +interface PathState { + readonly named: boolean; + /** Characters of the dotted name, -1 for the root's empty path. */ + readonly length: number; +} + +/** + * Find tensors reachable from the root and name those with one unshared key + * path. Every node is expanded and resolved once, and names are charged to + * the report budget before they are built, so work stays linear in the stream. + */ +export const placeTensors = ( + root: PickleNode, + budget: ModelReportBudget, +): { tensors: PlacedTensor[]; uninterpretable: number } => { + const indegree = new Map(); + const parents = new Map(); + const readings = new Map(); + const found: TensorCall[] = []; + let uninterpretable = 0; + const expanded = new Set([root]); + const pending: PickleNode[] = [root]; + while (pending.length > 0) { + const node = pending.pop()!; + const reading = readTensor(node, readings); + if (reading === "uninterpretable") { + uninterpretable++; + continue; + } + if (reading !== undefined) { + found.push(reading); + continue; + } + for (const [child, label] of children(node)) { + indegree.set(child, (indegree.get(child) ?? 0) + 1); + if (!parents.has(child)) parents.set(child, { parent: node, label }); + if (!expanded.has(child)) { + expanded.add(child); + pending.push(child); + } + } + } + const states = new Map([ + [root, { named: (indegree.get(root) ?? 0) === 0, length: -1 }], + ]); + const resolve = (start: PickleNode): PathState => { + const chain: PickleNode[] = []; + let current = start; + let state: PathState | undefined; + for (;;) { + state = states.get(current); + if (state !== undefined) break; + const edge = parents.get(current); + if ( + edge === undefined || + edge.label === null || + (indegree.get(current) ?? 0) !== 1 + ) { + state = { named: false, length: 0 }; + states.set(current, state); + break; + } + chain.push(current); + current = edge.parent; + } + for (let index = chain.length - 1; index >= 0; index--) { + const node = chain[index]!; + const label = parents.get(node)!.label!; + state = state.named + ? { named: true, length: state.length + 1 + label.length } + : { named: false, length: 0 }; + states.set(node, state); + } + return state; + }; + found.sort((left, right) => left.call.offset - right.call.offset); + const tensors = found.map((tensor): PlacedTensor => { + if (tensor.call === root) return { tensor, path: undefined }; + const state = resolve(tensor.call); + if (!state.named) return { tensor, path: undefined }; + // The name and its JSON pointer are retained; charge both before building them. + budget.charge(4 * state.length); + const path: string[] = []; + for (let current: PickleNode = tensor.call; current !== root;) { + const edge: Edge = parents.get(current)!; + path.push(edge.label!); + current = edge.parent; + } + path.reverse(); + return { tensor, path }; + }); + return { tensors, uninterpretable }; +}; + +/** Storage facts that a container layout supplies for one key. */ +export interface StorageRecord { + readonly record: string | null; + readonly recordBytes: number | null; + readonly fileOffset: number | null; + /** Element count the storage bytes declare, when the layout states one. */ + readonly declaredElements: bigint | null; +} + +const safe = (value: bigint, what: string): number => { + if (value > BigInt(Number.MAX_SAFE_INTEGER)) + throw modelCapacityFailure( + "exact-offset", + `PyTorch ${what} exceeds exact host offset precision`, + ); + return Number(value); +}; + +/** Storage rows for every storage persistent ID, in first-reference order. */ +export const storageRows = ( + references: readonly StorageReference[], + record: (key: string) => StorageRecord | undefined, + budget: ModelReportBudget, +): Map => { + const rows = new Map(); + for (const reference of references) { + const { key, storageType: type, location, elementCount } = reference; + if (rows.has(key)) continue; + budget.charge(256 + 2 * (key.length + (type?.length ?? 0))); + const known = storageType(type); + const source = record(key); + const byteLength = + known === undefined || elementCount === null + ? null + : safe(elementCount * BigInt(known.itemsize), "storage length"); + const recordBytes = source?.recordBytes ?? null; + const consistent = + byteLength !== null && + ((recordBytes !== null && recordBytes === byteLength) || + (source?.declaredElements != null && + source.declaredElements === elementCount)); + rows.set(key, { + index: rows.size, + key, + storage_type: type, + dtype: known?.dtype ?? null, + location, + element_count: elementCount?.toString() ?? null, + byte_length: byteLength, + record: source?.record ?? null, + record_bytes: recordBytes, + file_offset: source?.fileOffset ?? null, + validation: consistent ? "consistent" : "unknown", + }); + } + return rows; +}; + +/** Tensor rows with derived extents; extents past their declared storage are malformed. */ +/** + * Product of shape dimensions, stopping as soon as it exceeds `cap` so an + * adversarial shape cannot force an unbounded BigInt. Returns null on excess. + */ +const boundedProduct = ( + values: readonly bigint[], + cap: bigint, +): bigint | null => { + let product = 1n; + for (const value of values) { + if (value === 0n) return 0n; + if (product > cap / value) return null; + product *= value; + } + return product; +}; + +export const tensorRows = ( + tensors: readonly PlacedTensor[], + storages: ReadonlyMap, + budget: ModelReportBudget, +): { rows: ModelTensor[]; unnamed: number } => { + const rows: ModelTensor[] = tensors.map(({ tensor, path }, index) => { + const storage = storages.get(tensor.storage.key)!; + const known = storageType(storage.storage_type); + const elements = + storage.element_count === null ? null : BigInt(storage.element_count); + // The logical element count is bounded on its own: a view may address + // fewer elements than it declares (stride 0, or a zero dimension), so + // only the addressed span is compared with the storage below. + const numel = boundedProduct(tensor.shape, BigInt(Number.MAX_SAFE_INTEGER)); + if (numel === null) + throw modelCapacityFailure( + "exact-offset", + "PyTorch tensor element count exceeds exact host offset precision", + ); + let span = 0n; + if (numel !== 0n) { + // span = 1 + sum((size - 1) * stride); accumulate with the same cap. + span = 1n; + const spanCap = elements ?? BigInt(Number.MAX_SAFE_INTEGER); + for (let axis = 0; axis < tensor.shape.length; axis++) { + const term = (tensor.shape[axis]! - 1n) * tensor.stride[axis]!; + if (term > spanCap - span) { + if (elements !== null) + rejectModel( + `PyTorch tensor ${path?.join(".") ?? `#${String(index)}`} extends past its ${String(elements)}-element storage ${storage.key}`, + { offset: tensor.call.offset }, + ); + throw modelCapacityFailure( + "exact-offset", + "PyTorch tensor span exceeds exact host offset precision", + ); + } + span += term; + } + } + if ( + elements !== null && + numel !== 0n && + tensor.storageOffset + span > elements + ) + rejectModel( + `PyTorch tensor ${path?.join(".") ?? `#${String(index)}`} extends past its ${String(elements)}-element storage ${storage.key}`, + { offset: tensor.call.offset }, + ); + if ( + elements === null && + numel !== 0n && + known !== undefined && + storage.record_bytes !== null && + tensor.storageOffset + span > + BigInt(storage.record_bytes) / BigInt(known.itemsize) + ) + rejectModel( + `PyTorch tensor ${path?.join(".") ?? `#${String(index)}`} extends past its ${String(storage.record_bytes)}-byte storage record ${storage.key}`, + { offset: tensor.call.offset }, + ); + const itemsize = known === undefined ? null : BigInt(known.itemsize); + const dataOffset = + itemsize === null + ? null + : safe(tensor.storageOffset * itemsize, "tensor offset"); + const name = path?.join(".") ?? `#${String(index)}`; + budget.charge(256 + 2 * name.length + 24 * tensor.shape.length); + return { + index, + name, + type: storage.dtype ?? storage.storage_type ?? "unknown", + type_id: null, + shape: tensor.shape.map(String), + data_offset: dataOffset, + file_offset: + storage.file_offset === null || dataOffset === null + ? null + : storage.file_offset + dataOffset, + byte_length: + itemsize === null ? null : safe(span * itemsize, "tensor length"), + parameter_count: numel.toString(), + byte_length_state: itemsize === null ? "unknown" : "derived", + storage_validation: + storage.validation === "consistent" ? "consistent" : "unknown", + source_offset: tensor.call.offset, + source_length: 1, + json_pointer: + path === undefined + ? null + : `/${path.map(escapeJsonPointerToken).join("/")}`, + }; + }); + // Names identify rows; a key path that collides with another row is not + // unambiguous. One pass: names used once are kept, colliding rows take + // their `#index` fallback unless that name is already kept or assigned. + let unnamed = rows.filter((row) => row.json_pointer === null).length; + const countsByName = new Map(); + for (const row of rows) + countsByName.set(row.name, (countsByName.get(row.name) ?? 0) + 1); + const used = new Set( + rows + .filter((row) => (countsByName.get(row.name) ?? 0) === 1) + .map((row) => row.name), + ); + for (const row of rows) { + if (row.json_pointer === null || (countsByName.get(row.name) ?? 0) === 1) + continue; + let candidate = `#${String(row.index)}`; + while (used.has(candidate)) candidate = `#${candidate}`; + used.add(candidate); + row.name = candidate; + row.json_pointer = null; + unnamed++; + } + return { rows, unnamed }; +}; + +export const STORAGE_ITEMSIZE = (type: string | null): number | null => + storageType(type)?.itemsize ?? null; diff --git a/src/model/PickleWalker.ts b/src/model/PickleWalker.ts new file mode 100644 index 00000000000..356170d3015 --- /dev/null +++ b/src/model/PickleWalker.ts @@ -0,0 +1,1118 @@ +import { + decodeLimit, + malformedInput, + truncatedInput, + unsupportedInput, + type ParseFailureError, +} from "../domain/parseFailure.js"; +import { Budget } from "../domain/budget.js"; +import { BinaryReader } from "../domain/binaryContainer.js"; +import { decodeStrictUtf8, isStrictUtf8 } from "../domain/strictUtf8.js"; +import { byteToHex } from "../kernel/byteToHex.js"; +import { MODEL_FORMAT } from "./ModelFormat.js"; + +/** + * A static model of the values a pickle stream would build. Nothing here is + * imported, called or constructed: a `call` records that loading the stream + * would call its callable with these arguments. + */ +export type PickleNode = + | { readonly kind: "none" | "float" | "buffer" } + | { readonly kind: "bool"; readonly value: boolean } + /** `null` when the encoded integer is too long to retain exactly. */ + | { readonly kind: "int"; readonly value: bigint | null } + | { + readonly kind: "str"; + /** Display text; Python surrogate code points may pair into one astral character here. */ + readonly value: string; + /** Set when `value` holds Python surrogate code points: their exact sequence, for key equality. */ + readonly identity?: string; + } + | { readonly kind: "bytes"; readonly length: number } + | { readonly kind: "tuple"; readonly items: PickleNode[] } + | { readonly kind: "list" | "set"; readonly items: PickleNode[] } + | { readonly kind: "dict"; readonly entries: [PickleNode, PickleNode][] } + | { readonly kind: "global"; readonly name: string } + | { readonly kind: "extension"; readonly code: number } + | { readonly kind: "persistent"; readonly pid: PickleNode } + | PickleCall; + +/** A REDUCE/NEWOBJ/OBJ/INST result; APPEND, SETITEM and BUILD record what loading would do to it. */ +export interface PickleCall { + readonly kind: "call"; + readonly callable: PickleNode; + readonly args: PickleNode; + readonly offset: number; + readonly items: PickleNode[]; + readonly entries: [PickleNode, PickleNode][]; + readonly states: PickleNode[]; +} + +export interface PickleReference { + readonly offset: number; + readonly opcode: string; + readonly name: string | null; +} + +export interface PickleBudgets { + readonly max_pickle_opcodes: number; + readonly max_pickle_memo_entries: number; +} + +/** Where a stream lives: a file offset, or an offset inside a named archive record. */ +export interface PickleStreamSite { + readonly fileOffset: number | null; + readonly member: string | null; +} + +/** Shared opcode and memo allowances across every stream of one inspection. */ +export class PickleWork { + readonly opcodes: Budget; + readonly memo: Budget; + constructor(readonly budgets: PickleBudgets) { + this.opcodes = new Budget(budgets.max_pickle_opcodes); + this.memo = new Budget(budgets.max_pickle_memo_entries); + } +} + +const OPCODES: Readonly> = { + 0x28: "MARK", + 0x2e: "STOP", + 0x30: "POP", + 0x31: "POP_MARK", + 0x32: "DUP", + 0x46: "FLOAT", + 0x49: "INT", + 0x4a: "BININT", + 0x4b: "BININT1", + 0x4c: "LONG", + 0x4d: "BININT2", + 0x4e: "NONE", + 0x50: "PERSID", + 0x51: "BINPERSID", + 0x52: "REDUCE", + 0x53: "STRING", + 0x54: "BINSTRING", + 0x55: "SHORT_BINSTRING", + 0x56: "UNICODE", + 0x58: "BINUNICODE", + 0x61: "APPEND", + 0x62: "BUILD", + 0x63: "GLOBAL", + 0x64: "DICT", + 0x7d: "EMPTY_DICT", + 0x65: "APPENDS", + 0x67: "GET", + 0x68: "BINGET", + 0x69: "INST", + 0x6a: "LONG_BINGET", + 0x6c: "LIST", + 0x5d: "EMPTY_LIST", + 0x6f: "OBJ", + 0x70: "PUT", + 0x71: "BINPUT", + 0x72: "LONG_BINPUT", + 0x73: "SETITEM", + 0x74: "TUPLE", + 0x29: "EMPTY_TUPLE", + 0x75: "SETITEMS", + 0x47: "BINFLOAT", + 0x80: "PROTO", + 0x81: "NEWOBJ", + 0x82: "EXT1", + 0x83: "EXT2", + 0x84: "EXT4", + 0x85: "TUPLE1", + 0x86: "TUPLE2", + 0x87: "TUPLE3", + 0x88: "NEWTRUE", + 0x89: "NEWFALSE", + 0x8a: "LONG1", + 0x8b: "LONG4", + 0x42: "BINBYTES", + 0x43: "SHORT_BINBYTES", + 0x8c: "SHORT_BINUNICODE", + 0x8d: "BINUNICODE8", + 0x8e: "BINBYTES8", + 0x8f: "EMPTY_SET", + 0x90: "ADDITEMS", + 0x91: "FROZENSET", + 0x92: "NEWOBJ_EX", + 0x93: "STACK_GLOBAL", + 0x94: "MEMOIZE", + 0x95: "FRAME", + 0x96: "BYTEARRAY8", + 0x97: "NEXT_BUFFER", + 0x98: "READONLY_BUFFER", +}; + +/** Integers longer than this are retained as unknown values rather than decoded. */ +const EXACT_LONG_BYTES = 64; +/** Decimal digits of the largest exact binary long, 2^(8 * EXACT_LONG_BYTES). */ +const EXACT_DECIMAL_DIGITS = + Math.ceil(EXACT_LONG_BYTES * 8 * Math.log10(2)) + 1; +const NONE: PickleNode = { kind: "none" }; +const FLOAT: PickleNode = { kind: "float" }; + +/** + * A protocol 0 FLOAT operand, checked in one pass: an optional sign, digits + * with at most one dot (or a leading dot with digits), an optional exponent, + * or the inf/nan spellings CPython emits. No backtracking, so a long digit + * run is rejected in linear time. + */ +const isDecimalFloat = (text: string): boolean => { + const lower = text.toLowerCase(); + const unsigned = + lower.startsWith("+") || lower.startsWith("-") ? lower.slice(1) : lower; + if (unsigned === "inf" || unsigned === "infinity" || unsigned === "nan") + return true; + let index = 0; + let digits = 0; + let dot = false; + while (index < unsigned.length) { + const char = unsigned[index]!; + if (char >= "0" && char <= "9") { + digits++; + index++; + } else if (char === "." && !dot) { + dot = true; + index++; + } else break; + } + if (digits === 0) return false; + if (index === unsigned.length) return true; + if (unsigned[index] !== "e" && unsigned[index] !== "E") return false; + index++; + if (unsigned[index] === "+" || unsigned[index] === "-") index++; + let exponentDigits = 0; + while (index < unsigned.length) { + const char = unsigned[index]!; + if (char < "0" || char > "9") return false; + exponentDigits++; + index++; + } + return exponentDigits > 0; +}; + +/** Signals that the opcode at the current position needs bytes not yet supplied. */ +const NEED_MORE = Symbol("need-more-pickle-bytes"); + +/** + * Walks one pickle stream (protocols 0–5) opcode by opcode without importing + * or calling anything. Feed it the stream's bytes from its start; it resumes + * at the last complete opcode when more bytes arrive. + */ +export class PickleWalker { + position = 0; + protocol: number | null = null; + result: PickleNode | undefined; + persistentIds = 0; + trailingValues = 0; + /** Persistent-ID values in stream order; their meaning belongs to the reader. */ + readonly persistent: PickleNode[] = []; + readonly opcodes = new Map(); + readonly references: PickleReference[] = []; + #opcodeCount = 0; + #stack: PickleNode[] = []; + readonly #marks: number[] = []; + readonly #memo = new Map(); + /** Entry positions by key identity, for keys whose equality the stream states exactly. */ + readonly #entryKeys = new WeakMap>(); + #buffer: Buffer = Buffer.alloc(0); + #reader = new BinaryReader(this.#buffer, true, MODEL_FORMAT); + #end = 0; + #final = false; + #opcodeStart = 0; + + constructor( + readonly site: PickleStreamSite, + readonly work: PickleWork, + ) {} + + get opcodeCount(): number { + return this.#opcodeCount; + } + + get done(): boolean { + return this.result !== undefined; + } + + /** + * Walk as far as `bytes` allow. `final` states that no later bytes exist, + * so an incomplete opcode is a truncated stream. + * Returns true once STOP completed the stream. + */ + feed(bytes: Buffer, final: boolean): boolean { + this.#buffer = bytes; + this.#reader = new BinaryReader(bytes, true, MODEL_FORMAT); + this.#end = bytes.length; + this.#final = final; + while (this.result === undefined) { + this.#opcodeStart = this.position; + try { + this.#step(); + } catch (cause) { + if (cause !== NEED_MORE) throw cause; + this.position = this.#opcodeStart; + if (!final) return false; + throw this.#truncated(); + } + } + return true; + } + + #at(offset: number): number { + return (this.site.fileOffset ?? 0) + offset; + } + + #where(offset = this.#opcodeStart) { + return { + offset: this.#at(offset), + ...(this.site.member === null ? {} : { field: this.site.member }), + }; + } + + #describe(offset = this.#opcodeStart): string { + return this.site.member === null + ? `at file offset ${String(this.#at(offset))}` + : `at offset ${String(offset)} of ${this.site.member}`; + } + + #truncated(): ParseFailureError<"truncated"> { + const name = OPCODES[this.#buffer[this.#opcodeStart] ?? -1]; + return truncatedInput( + MODEL_FORMAT, + this.#opcodeStart >= this.#end + ? `Pickle stream ends before STOP ${this.#describe()}` + : `Pickle ${name ?? "opcode"} ${this.#describe()} is truncated`, + this.#where(), + ); + } + + malformed( + detail: string, + offset = this.#opcodeStart, + ): ParseFailureError<"malformed"> { + return malformedInput( + MODEL_FORMAT, + `${detail} ${this.#describe(offset)}`, + this.#where(offset), + ); + } + + #need(length: number): number { + if (this.position + length > this.#end) throw NEED_MORE; + const start = this.position; + this.position += length; + return start; + } + + #bytes(length: number): Buffer { + const start = this.#need(length); + return this.#buffer.subarray(start, start + length); + } + + #u8(): number { + return this.#buffer[this.#need(1)]!; + } + + #u16(): number { + return this.#reader.u16(this.#need(2)); + } + + #u32(): number { + return this.#reader.u32(this.#need(4)); + } + + #length64(): number { + const value = this.#reader.word(this.#need(8), 64); + if (value > BigInt(Number.MAX_SAFE_INTEGER)) + throw this.malformed("Pickle length exceeds exact host precision"); + return Number(value); + } + + /** A protocol 0 argument line, without its newline. */ + #line(): Buffer { + const newline = this.#buffer.indexOf(0x0a, this.position); + if (newline < 0 || newline >= this.#end) throw NEED_MORE; + const line = this.#buffer.subarray(this.position, newline); + this.position = newline + 1; + return line; + } + + #utf8(bytes: Buffer, what: string): string { + try { + return decodeStrictUtf8(bytes, "preserve"); + } catch { + throw this.malformed(`Pickle ${what} is not valid UTF-8`); + } + } + + /** BINUNICODE strings: UTF-8 with Python's surrogatepass, so lone surrogates are valid. */ + #unicode(bytes: Buffer, what: string): PickleNode { + if (isStrictUtf8(bytes)) + return { kind: "str", value: decodeStrictUtf8(bytes, "preserve") }; + const decoded = decodeSurrogatePass(bytes); + if (decoded === undefined) + throw this.malformed(`Pickle ${what} is not valid UTF-8`); + return { kind: "str", ...decoded }; + } + + /** Protocol 0 UNICODE: raw-unicode-escape, where only an odd backslash run before u or U escapes. */ + #rawUnicode(line: Buffer): PickleNode { + const text = line.toString("latin1"); + let surrogates = false; + const value = this.#rawUnicodeText( + text, + (slice) => slice, + (point) => { + if (point >= 0xd800 && point <= 0xdfff) surrogates = true; + return String.fromCodePoint(point); + }, + "", + ); + // Surrogate code points stay distinct in the identity, so equal-looking keys are not merged. + return surrogates + ? { + kind: "str", + value, + identity: this.#rawUnicodeText( + text, + identityText, + identityPoint, + "p", + ), + } + : { kind: "str", value }; + } + + /** + * One pass over raw-unicode-escape text: each backslash run is measured once, + * only an odd run before u or U escapes, and output joins in bounded chunks. + */ + #rawUnicodeText( + text: string, + literal: (slice: string) => string, + decoded: (point: number) => string, + prefix: string, + ): string { + const out = new ChunkedText(); + out.push(prefix); + let index = 0; + for (let slash = text.indexOf("\\"); slash >= 0;) { + let end = slash; + while (text.charCodeAt(end) === 0x5c) end++; + const marker = text[end]; + if ((end - slash) % 2 === 0 || (marker !== "u" && marker !== "U")) { + slash = text.indexOf("\\", end); + continue; + } + const digits = marker === "u" ? 4 : 8; + const hex = text.slice(end + 1, end + 1 + digits); + if (hex.length !== digits || !/^[0-9a-fA-F]*$/u.test(hex)) + throw this.malformed( + `Pickle UNICODE has a truncated \\${marker} escape`, + ); + const point = parseInt(hex, 16); + if (point > 0x10ffff) + throw this.malformed( + `Pickle UNICODE escape \\U${hex} is beyond U+10FFFF`, + ); + // The escaping backslash is dropped; the even run before it stays literal. + out.push(literal(text.slice(index, end - 1))); + out.push(decoded(point)); + index = end + 1 + digits; + slash = text.indexOf("\\", index); + } + out.push(literal(text.slice(index))); + return out.join(); + } + + /** + * A protocol 0 decimal argument. Digits past the exact binary-long bound are + * validated but not converted, so one opcode cannot force an unbounded BigInt. + */ + #decimal(line: Buffer, what: string): bigint | null { + const text = line.toString("latin1").trim(); + if (!/^[+-]?[0-9]+$/u.test(text)) + throw this.malformed(`Pickle ${what} argument is not a decimal integer`); + const digits = text.length - (/^[+-]/u.test(text) ? 1 : 0); + return digits > EXACT_DECIMAL_DIGITS ? null : BigInt(text); + } + + /** A protocol 0 GET or PUT memo key, which must be exact. */ + #decimalKey(what: string): bigint { + const key = this.#decimal(this.#line(), what); + if (key === null) + throw this.malformed(`Pickle ${what} memo key exceeds exact precision`); + return key; + } + + #push(node: PickleNode): void { + this.#stack.push(node); + } + + #pop(): PickleNode { + if (this.#stack.length <= (this.#marks.at(-1) ?? 0)) + throw this.malformed("Pickle opcode pops from an empty stack"); + return this.#stack.pop()!; + } + + #top(): PickleNode { + if (this.#stack.length <= (this.#marks.at(-1) ?? 0)) + throw this.malformed("Pickle opcode reads an empty stack"); + return this.#stack.at(-1)!; + } + + #popMark(): PickleNode[] { + const mark = this.#marks.pop(); + if (mark === undefined) + throw this.malformed("Pickle opcode requires a MARK that is not open"); + return this.#stack.splice(mark); + } + + #memoPut(key: number, node: PickleNode): void { + if (!this.#memo.has(key)) { + this.work.memo.charge(1, () => + decodeLimit( + MODEL_FORMAT, + `Pickle memo entries exceed max_pickle_memo_entries (${String(this.work.budgets.max_pickle_memo_entries)}) ${this.#describe()}`, + { + name: "max_pickle_memo_entries", + maximum: this.work.budgets.max_pickle_memo_entries, + }, + this.#where(), + ), + ); + } + this.#memo.set(key, node); + } + + #memoGet(key: bigint | number): PickleNode { + const node = + typeof key === "number" || (key >= 0n && key <= 0xffffffffn) + ? this.#memo.get(Number(key)) + : undefined; + if (node === undefined) + throw this.malformed( + `Pickle memo misuse: GET of undefined memo key ${String(key)}`, + ); + return node; + } + + #putKey(key: bigint): number { + if (key < 0n || key > 0xffffffffn) + throw this.malformed( + `Pickle memo misuse: PUT key ${String(key)} is out of range`, + ); + return Number(key); + } + + #reference(opcode: string, name: string | null): void { + this.references.push({ offset: this.#at(this.#opcodeStart), opcode, name }); + } + + #global(opcode: string, module: string, name: string): PickleNode { + const qualified = `${module}.${name}`; + this.#reference(opcode, qualified); + return { kind: "global", name: qualified }; + } + + #call(opcode: string, callable: PickleNode, args: PickleNode): PickleCall { + this.#reference(opcode, calleeName(callable)); + return { + kind: "call", + callable, + args, + offset: this.#at(this.#opcodeStart), + items: [], + entries: [], + states: [], + }; + } + + #items(target: PickleNode, items: PickleNode[], opcode: string): void { + // A loop, not a spread: one APPENDS may carry more values than a call accepts. + if (target.kind === "list" || target.kind === "call") + for (const item of items) target.items.push(item); + else + throw this.malformed(`Pickle ${opcode} target is not a list or object`); + } + + #entries(target: PickleNode, items: PickleNode[], opcode: string): void { + if (items.length % 2 !== 0) + throw this.malformed(`Pickle ${opcode} has an unpaired key`); + if (target.kind !== "dict" && target.kind !== "call") + throw this.malformed(`Pickle ${opcode} target is not a dict or object`); + // SETITEM replaces an equal key, so the model keeps only the value loading would leave. + let keys = this.#entryKeys.get(target); + if (keys === undefined) { + keys = new Map(); + this.#entryKeys.set(target, keys); + } + for (let index = 0; index < items.length; index += 2) { + const entry: [PickleNode, PickleNode] = [ + items[index]!, + items[index + 1]!, + ]; + const identity = entryIdentity(entry[0]); + const existing = identity === undefined ? undefined : keys.get(identity); + // Python keeps the first equal key and replaces only its value. + if (existing !== undefined) + target.entries[existing] = [target.entries[existing]![0], entry[1]]; + else { + if (identity !== undefined) keys.set(identity, target.entries.length); + target.entries.push(entry); + } + } + } + + #long(bytes: Buffer): PickleNode { + if (bytes.length === 0) return { kind: "int", value: 0n }; + if (bytes.length > EXACT_LONG_BYTES) return { kind: "int", value: null }; + let value = 0n; + for (let index = bytes.length - 1; index >= 0; index--) + value = (value << 8n) | BigInt(bytes[index]!); + if ((bytes.at(-1)! & 0x80) !== 0) value -= 1n << BigInt(bytes.length * 8); + return { kind: "int", value }; + } + + #step(): void { + const code = this.#u8(); + const name = OPCODES[code]; + if (name === undefined) + throw this.malformed(`Unknown pickle opcode 0x${byteToHex(code)}`); + // Operands are read before any state changes, so a resumed opcode replays cleanly. + switch (code) { + case 0x80: { + const protocol = this.#u8(); + if (protocol > 5) + throw unsupportedInput( + MODEL_FORMAT, + `Pickle protocol ${String(protocol)} ${this.#describe()} is newer than protocol 5`, + this.#where(), + ); + this.#count(code); + this.protocol ??= protocol; + return; + } + case 0x95: { + // An unpickler reads a whole frame before its opcodes; a short frame is truncated here. + const length = this.#length64(); + if (this.position + length > this.#end) throw NEED_MORE; + this.#count(code); + return; + } + case 0x2e: + this.#count(code); + this.#stop(); + return; + default: + break; + } + const apply = this.#operation(code, name); + this.#count(code); + apply(); + } + + #count(code: number): void { + this.work.opcodes.charge(1, () => + decodeLimit( + MODEL_FORMAT, + `Pickle opcodes exceed max_pickle_opcodes (${String(this.work.budgets.max_pickle_opcodes)}) ${this.#describe()}`, + { + name: "max_pickle_opcodes", + maximum: this.work.budgets.max_pickle_opcodes, + }, + this.#where(), + ), + ); + this.#opcodeCount++; + this.opcodes.set(code, (this.opcodes.get(code) ?? 0) + 1); + } + + #stop(): void { + const value = this.#pop(); + if (this.#marks.length > 0) + throw this.malformed("Pickle STOP leaves a MARK open"); + this.trailingValues = this.#stack.length; + this.#stack = []; + this.result = value; + } + + /** Read the operands of one opcode and return its effect on the stack and memo. */ + #operation(code: number, name: string): () => void { + const push = (node: PickleNode) => () => this.#push(node); + switch (code) { + case 0x28: + return () => this.#marks.push(this.#stack.length); + case 0x30: + return () => { + if (this.#stack.length > (this.#marks.at(-1) ?? 0)) this.#pop(); + else this.#popMark(); + }; + case 0x31: + return () => void this.#popMark(); + case 0x32: + return () => this.#push(this.#top()); + case 0x46: { + const text = this.#line().toString("latin1").trim(); + if (!isDecimalFloat(text)) + throw this.malformed("Pickle FLOAT argument is not a decimal float"); + return push(FLOAT); + } + case 0x47: + this.#bytes(8); + return push(FLOAT); + case 0x49: { + const line = this.#line(); + const text = line.toString("latin1"); + if (text === "00") return push({ kind: "bool", value: false }); + if (text === "01") return push({ kind: "bool", value: true }); + return push({ kind: "int", value: this.#decimal(line, "INT") }); + } + case 0x4c: { + const line = this.#line(); + const text = line.toString("latin1").replace(/L$/u, ""); + return push({ + kind: "int", + value: this.#decimal(Buffer.from(text, "latin1"), "LONG"), + }); + } + case 0x4a: + return push({ + kind: "int", + value: BigInt(this.#reader.i32(this.#need(4))), + }); + case 0x4b: + return push({ kind: "int", value: BigInt(this.#u8()) }); + case 0x4d: + return push({ kind: "int", value: BigInt(this.#u16()) }); + case 0x8a: + return push(this.#long(this.#bytes(this.#u8()))); + case 0x8b: { + const length = this.#reader.i32(this.#need(4)); + if (length < 0) throw this.malformed("Pickle LONG4 length is negative"); + return push(this.#long(this.#bytes(length))); + } + case 0x4e: + return push(NONE); + case 0x88: + return push({ kind: "bool", value: true }); + case 0x89: + return push({ kind: "bool", value: false }); + case 0x53: + return push({ + kind: "str", + value: this.#quoted(this.#line()), + }); + case 0x54: { + const length = this.#reader.i32(this.#need(4)); + if (length < 0) + throw this.malformed("Pickle BINSTRING length is negative"); + return push({ + kind: "str", + value: this.#bytes(length).toString("latin1"), + }); + } + case 0x55: + return push({ + kind: "str", + value: this.#bytes(this.#u8()).toString("latin1"), + }); + case 0x56: + return push(this.#rawUnicode(this.#line())); + case 0x58: + return push(this.#unicode(this.#bytes(this.#u32()), "BINUNICODE")); + case 0x8c: + return push(this.#unicode(this.#bytes(this.#u8()), "SHORT_BINUNICODE")); + case 0x8d: + return push( + this.#unicode(this.#bytes(this.#length64()), "BINUNICODE8"), + ); + case 0x42: + return push({ kind: "bytes", length: this.#bytes(this.#u32()).length }); + case 0x43: + return push({ kind: "bytes", length: this.#bytes(this.#u8()).length }); + case 0x8e: + case 0x96: + return push({ + kind: "bytes", + length: this.#bytes(this.#length64()).length, + }); + case 0x97: + return push({ kind: "buffer" }); + case 0x98: + return () => void this.#top(); + case 0x29: + return push({ kind: "tuple", items: [] }); + case 0x5d: + return push({ kind: "list", items: [] }); + case 0x7d: + return push({ kind: "dict", entries: [] }); + case 0x8f: + return push({ kind: "set", items: [] }); + case 0x74: + return () => this.#push({ kind: "tuple", items: this.#popMark() }); + case 0x6c: + return () => this.#push({ kind: "list", items: this.#popMark() }); + case 0x91: + return () => this.#push({ kind: "set", items: this.#popMark() }); + case 0x85: + case 0x86: + case 0x87: + return () => { + const items: PickleNode[] = []; + for (let count = code - 0x84; count > 0; count--) + items.unshift(this.#pop()); + this.#push({ kind: "tuple", items }); + }; + case 0x64: + return () => { + const dict: PickleNode = { kind: "dict", entries: [] }; + this.#entries(dict, this.#popMark(), name); + this.#push(dict); + }; + case 0x61: + return () => { + const value = this.#pop(); + this.#items(this.#top(), [value], name); + }; + case 0x65: + return () => { + const items = this.#popMark(); + this.#items(this.#top(), items, name); + }; + case 0x90: + return () => { + const items = this.#popMark(); + const target = this.#top(); + if (target.kind !== "set" && target.kind !== "call") + throw this.malformed("Pickle ADDITEMS target is not a set"); + for (const item of items) target.items.push(item); + }; + case 0x73: + return () => { + const value = this.#pop(); + const key = this.#pop(); + this.#entries(this.#top(), [key, value], name); + }; + case 0x75: + return () => { + const items = this.#popMark(); + this.#entries(this.#top(), items, name); + }; + case 0x67: { + const key = this.#decimalKey("GET"); + return () => this.#push(this.#memoGet(key)); + } + case 0x68: { + const key = this.#u8(); + return () => this.#push(this.#memoGet(key)); + } + case 0x6a: { + const key = this.#u32(); + return () => this.#push(this.#memoGet(key)); + } + case 0x70: { + const key = this.#putKey(this.#decimalKey("PUT")); + return () => this.#memoPut(key, this.#top()); + } + case 0x71: { + const key = this.#u8(); + return () => this.#memoPut(key, this.#top()); + } + case 0x72: { + const key = this.#u32(); + return () => this.#memoPut(key, this.#top()); + } + case 0x94: + return () => this.#memoPut(this.#memo.size, this.#top()); + case 0x63: { + const module = this.#utf8(this.#line(), "GLOBAL module"); + const qualified = this.#utf8(this.#line(), "GLOBAL name"); + return () => this.#push(this.#global(name, module, qualified)); + } + case 0x93: + return () => { + const qualified = this.#pop(); + const module = this.#pop(); + if (module.kind !== "str" || qualified.kind !== "str") + throw this.malformed( + "Pickle STACK_GLOBAL module and name are not strings", + ); + this.#push(this.#global(name, module.value, qualified.value)); + }; + case 0x82: + case 0x83: + case 0x84: { + const extension = + code === 0x82 + ? this.#u8() + : code === 0x83 + ? this.#u16() + : this.#u32(); + return () => { + this.#reference(name, null); + this.#push({ kind: "extension", code: extension }); + }; + } + case 0x50: { + const pid = this.#line().toString("latin1"); + return () => { + this.persistentIds++; + const node: PickleNode = { + kind: "persistent", + pid: { kind: "str", value: pid }, + }; + this.persistent.push(node); + this.#push(node); + }; + } + case 0x51: + return () => { + const node: PickleNode = { kind: "persistent", pid: this.#pop() }; + this.persistentIds++; + this.persistent.push(node); + this.#push(node); + }; + case 0x52: + return () => { + const args = this.#pop(); + const callable = this.#pop(); + this.#push(this.#call(name, callable, args)); + }; + case 0x81: + return () => { + const args = this.#pop(); + const cls = this.#pop(); + this.#push(this.#call(name, cls, args)); + }; + case 0x92: + return () => { + const kwargs = this.#pop(); + const args = this.#pop(); + const cls = this.#pop(); + this.#push( + this.#call(name, cls, { kind: "tuple", items: [args, kwargs] }), + ); + }; + case 0x6f: + return () => { + const items = this.#popMark(); + const cls = items.shift(); + if (cls === undefined) + throw this.malformed("Pickle OBJ has no class after its MARK"); + this.#push(this.#call(name, cls, { kind: "tuple", items })); + }; + case 0x69: { + const module = this.#utf8(this.#line(), "INST module"); + const qualified = this.#utf8(this.#line(), "INST name"); + return () => { + const items = this.#popMark(); + const cls = this.#global(name, module, qualified); + // INST both imports and calls; the import is the reference above. + this.#push({ + kind: "call", + callable: cls, + args: { kind: "tuple", items }, + offset: this.#at(this.#opcodeStart), + items: [], + entries: [], + states: [], + }); + }; + } + case 0x62: + return () => { + const state = this.#pop(); + const target = this.#top(); + this.#reference( + name, + target.kind === "call" ? calleeName(target.callable) : null, + ); + if (target.kind === "call") target.states.push(state); + }; + default: + throw this.malformed(`Pickle opcode ${name} is not handled`); + } + } + + /** Protocol 0 STRING: a quoted Python 2 repr. */ + #quoted(line: Buffer): string { + const text = line.toString("latin1"); + const quote = text[0]; + if ( + text.length < 2 || + (quote !== "'" && quote !== '"') || + text.at(-1) !== quote + ) + throw this.malformed("Pickle STRING argument is not quoted"); + // Python's string-escape rules; an unknown escape keeps its backslash. + return text + .slice(1, -1) + .replace( + /\\(x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S]|$)/gu, + (_match, escape: string) => { + if (escape === "" || escape === "x") + throw this.malformed( + escape === "" + ? "Pickle STRING argument ends with a lone backslash" + : "Pickle STRING argument has a truncated \\x escape", + ); + if (escape.length === 3 && escape[0] === "x") + return String.fromCharCode(parseInt(escape.slice(1), 16)); + if (/^[0-7]/u.test(escape)) + return String.fromCharCode(parseInt(escape, 8) & 0xff); + return PYTHON_STRING_ESCAPES[escape] ?? `\\${escape}`; + }, + ); + } +} + +const PYTHON_STRING_ESCAPES: Readonly> = { + "\n": "", + "\\": "\\", + "'": "'", + '"': '"', + a: "\x07", + b: "\b", + f: "\f", + n: "\n", + r: "\r", + t: "\t", + v: "\v", +}; + +const entryIdentities = new WeakMap(); + +/** + * Python treats equal str, int and bool keys as one dict key; other keys stay + * distinct. A key node's identity is built once, so a memoized key reused in + * many writes is hashed once rather than rebuilt per write. + */ +const entryIdentity = (key: PickleNode): string | undefined => { + switch (key.kind) { + case "str": { + let identity = entryIdentities.get(key); + if (identity === undefined) { + identity = key.identity ?? `s${key.value}`; + entryIdentities.set(key, identity); + } + return identity; + } + case "int": + return key.value === null ? undefined : `i${key.value.toString()}`; + case "bool": + return key.value ? "i1" : "i0"; + case "none": + return "n"; + default: + return undefined; + } +}; + +/** Joins text slices in bounded batches, so a long string never holds one array slot per slice. */ +class ChunkedText { + readonly #chunks: string[] = []; + readonly #batch: string[] = []; + + push(text: string): void { + if (text.length === 0) return; + this.#batch.push(text); + if (this.#batch.length >= 4096) this.#flush(); + } + + join(): string { + this.#flush(); + return this.#chunks.join(""); + } + + #flush(): void { + if (this.#batch.length === 0) return; + this.#chunks.push(this.#batch.join("")); + this.#batch.length = 0; + } +} + +/** + * Identity text for a str holding Python surrogate code points: backslashes are + * doubled and each surrogate is `\uXXXX`, so the code point sequence is exact. + */ +const identityText = (text: string): string => text.replaceAll("\\", "\\\\"); + +const identityPoint = (point: number): string => + point >= 0xd800 && point <= 0xdfff + ? `\\u${point.toString(16).padStart(4, "0")}` + : identityText(String.fromCodePoint(point)); + +/** + * UTF-8 that also admits encoded surrogates (U+D800–U+DFFF), as Python's + * surrogatepass handler does. Undefined for any other invalid sequence. + */ +const decodeSurrogatePass = ( + bytes: Uint8Array, +): { value: string; identity: string } | undefined => { + const value = new ChunkedText(); + const identity = new ChunkedText(); + identity.push("p"); + const units: number[] = []; + const flush = () => { + const text = String.fromCharCode(...units); + value.push(text); + units.length = 0; + }; + let literal = 0; + for (let index = 0; index < bytes.length;) { + const lead = bytes[index]!; + const width = + lead < 0x80 + ? 1 + : lead >= 0xc2 && lead < 0xe0 + ? 2 + : lead >= 0xe0 && lead < 0xf0 + ? 3 + : lead >= 0xf0 && lead < 0xf5 + ? 4 + : 0; + if (width === 0 || index + width > bytes.length) return undefined; + let point = width === 1 ? lead : lead & (0xff >> (width + 1)); + for (let offset = 1; offset < width; offset++) { + const next = bytes[index + offset]!; + if ((next & 0xc0) !== 0x80) return undefined; + point = (point << 6) | (next & 0x3f); + } + const minimum = [0, 0, 0x80, 0x800, 0x10000][width]!; + if (point < minimum || point > 0x10ffff) return undefined; + if (point >= 0xd800 && point <= 0xdfff) { + // The identity copies the strict text before this surrogate, then marks the surrogate. + flush(); + identity.push( + identityText( + decodeStrictUtf8(bytes.subarray(literal, index), "preserve"), + ), + ); + identity.push(identityPoint(point)); + literal = index + width; + } + if (point >= 0x10000) { + point -= 0x10000; + units.push(0xd800 + (point >> 10), 0xdc00 + (point & 0x3ff)); + } else units.push(point); + if (units.length >= 8192) flush(); + index += width; + } + flush(); + identity.push( + identityText(decodeStrictUtf8(bytes.subarray(literal), "preserve")), + ); + return { value: value.join(), identity: identity.join() }; +}; + +/** The qualified name of a callable when the stream states it. */ +export const calleeName = (node: PickleNode): string | null => + node.kind === "global" ? node.name : null; + +/** Stable opcode name for a byte that the walker counted. */ +export const pickleOpcodeName = (code: number): string => + OPCODES[code] ?? `0x${code.toString(16)}`; diff --git a/src/model/PytorchArtifactReader.ts b/src/model/PytorchArtifactReader.ts new file mode 100644 index 00000000000..b6a4ac0ede6 --- /dev/null +++ b/src/model/PytorchArtifactReader.ts @@ -0,0 +1,730 @@ +import { createHash, type Hash } from "node:crypto"; +import type { FileHandle } from "node:fs/promises"; +import { setImmediate } from "node:timers/promises"; +import type { Readable } from "node:stream"; +import type { + ModelTensor, + PickleFacts, + PytorchFacts, +} from "../domain/model/modelArtifact.js"; +import { + malformedInput, + truncatedInput, + unsupportedInput, +} from "../domain/parseFailure.js"; +import { BinaryReader } from "../domain/binaryContainer.js"; +import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; +import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js"; +import { + ArtifactReaderFailure, + assertArtifactReadActive, + throwZipPackageFailure, + ZipArtifactReader, + type ArtifactEntry, +} from "../resources/index.js"; +import { + MODEL_FORMAT, + MODEL_HEADER_BYTES, + MODEL_REPORT_BYTES, + modelCapacityFailure, + ModelReportBudget, + rejectForeignZip, + rejectModel, +} from "./ModelFormat.js"; +import { + operationZipMemberCount, + zipMemberCountConstraint, +} from "../config/artifactMemberCount.js"; +import { + pickleFacts, + placeTensors, + storageReference, + storageRows, + STORAGE_ITEMSIZE, + tensorRows, + type StorageRecord, + type StorageReference, + type WalkedStream, +} from "./PickleInspection.js"; +import { + PickleWalker, + PickleWork, + type PickleBudgets, + type PickleNode, +} from "./PickleWalker.js"; + +/** Facts and read accounting for a PyTorch checkpoint or standalone pickle. */ +export interface PickleArtifact { + readonly format: "pytorch-zip" | "pytorch-legacy" | "pickle"; + readonly version: number | null; + readonly byte_order: "little" | "big" | null; + readonly alignment: number | null; + readonly tensor_data_offset: number | null; + readonly metadata: []; + readonly tensors: ModelTensor[]; + /** False when a tensor rebuild call could not be read, so rows omit tensors. */ + readonly tensors_complete: boolean; + readonly limitations: string[]; + readonly pickle: PickleFacts; + readonly pytorch?: PytorchFacts; + readonly header_length: number; + readonly header_sha256: string; + readonly sha256: string | null; + readonly bytes_read: number; +} + +/** torch.save's legacy (non-ZIP) format begins with this pickled integer. */ +const LEGACY_MAGIC = 0x1950a86a20f9469cfc6cn; +const LEGACY_PROTOCOL = 1001n; +const FEED_SLICE = 4 * 1024 * 1024; +const RECORD_TEXT_BYTES = 4096; +const MODEL_OPERATION = "inspect_model_artifact"; + +/** Feed one complete or growing stream in bounded slices so cancellation is observed. */ +const feedSlices = async ( + walker: PickleWalker, + bytes: Buffer, + final: boolean, + signal: AbortSignal | undefined, +): Promise => { + // The slice grows monotonically so one operand larger than a slice still completes. + let end = walker.position; + for (;;) { + assertArtifactReadActive(signal); + end = Math.min(bytes.length, Math.max(end, walker.position) + FEED_SLICE); + const last = end === bytes.length; + if (walker.feed(bytes.subarray(0, end), final && last)) return true; + if (last) return false; + await setImmediate(); + } +}; + +/** A contiguous, hashed-on-demand file prefix bounded by the model header allowance. */ +class FilePrefix { + buffer = Buffer.alloc(0); + /** Bytes read outside the contiguous prefix, such as legacy storage counts. */ + extraBytes = 0; + + constructor( + readonly file: FileHandle, + readonly size: number, + readonly signal: AbortSignal | undefined, + ) {} + + get loaded(): number { + return this.buffer.length; + } + + get complete(): boolean { + return this.loaded >= this.size; + } + + async grow(): Promise { + const ceiling = Math.min(this.size, MODEL_HEADER_BYTES); + if (this.loaded >= ceiling) + throw modelCapacityFailure( + "header-bytes", + "Pickle streams exceed 100,000,000 bytes before their last STOP. This release has no runtime override.", + ); + const target = Math.min( + ceiling, + Math.max(this.loaded + 65536, this.loaded * 2), + ); + const next = Buffer.allocUnsafe(target); + this.buffer.copy(next); + await readExactly(this.file, next, this.loaded, target, this.signal); + this.buffer = next; + } + + async readAt(position: number, length: number): Promise { + if (position + length <= this.loaded) + return this.buffer.subarray(position, position + length); + const bytes = Buffer.allocUnsafe(length); + await readExactly(this.file, bytes, 0, length, this.signal, position); + this.extraBytes += length; + return bytes; + } +} + +const readExactly = async ( + file: FileHandle, + target: Buffer, + from: number, + to: number, + signal: AbortSignal | undefined, + position = from, +): Promise => { + let offset = from; + while (offset < to) { + assertArtifactReadActive(signal); + const { bytesRead } = await file.read( + target, + offset, + to - offset, + position + offset - from, + ); + if (bytesRead === 0) + throw new ArtifactReaderFailure( + "integrity", + "Model ended before its admitted file extent", + { integrityCheck: "read-coverage" }, + ); + offset += bytesRead; + } +}; + +/** Stream the file from `from` into `hash`; bytes before it were hashed by the caller. */ +const hashRemainder = async ( + file: FileHandle, + size: number, + from: number, + hash: Hash, + signal: AbortSignal | undefined, +): Promise => { + const buffer = Buffer.allocUnsafe(1024 * 1024); + for (let position = from; position < size;) { + const length = Math.min(buffer.length, size - position); + await readExactly(file, buffer, 0, length, signal, position); + hash.update(buffer.subarray(0, length)); + position += length; + } +}; + +const intValue = (node: PickleNode | undefined): bigint | undefined => + node?.kind === "int" && node.value !== null ? node.value : undefined; + +/** Storage references in first-appearance order; later conflicting declarations keep the first. */ +const storageReferences = ( + walker: PickleWalker, +): Map => { + const byKey = new Map(); + for (const node of walker.persistent) { + const reference = storageReference(node); + if (reference !== undefined && !byKey.has(reference.key)) + byKey.set(reference.key, reference); + } + return byKey; +}; + +/** Shared tensor and storage interpretation of a walked data stream. */ +const interpret = ( + data: PickleWalker, + record: (key: string) => StorageRecord | undefined, + budget: ModelReportBudget, +) => { + // Every storage persistent ID is inventoried and checked, whether or not a tensor uses it. + const storages = storageRows( + [...storageReferences(data).values()], + record, + budget, + ); + const { tensors: placed, uninterpretable } = placeTensors( + data.result!, + budget, + ); + const { rows, unnamed } = tensorRows(placed, storages, budget); + const limitations: string[] = []; + if (unnamed > 0) + limitations.push( + `${String(unnamed)} tensor(s) are not reached through one unshared chain of string or integer container keys from the pickled root; their names are # and json_pointer is null.`, + ); + if (uninterpretable > 0) + limitations.push( + `${String(uninterpretable)} tensor rebuild call(s) have arguments that do not state a storage, offset, shape and stride; they remain in pickle.references without tensor rows.`, + ); + return { + rows, + storages: [...storages.values()], + limitations, + complete: uninterpretable === 0, + }; +}; + +/** Facts a reader has completed, offered before full-file hashing can fail or be cancelled. */ +export type RetainPickleFacts = (facts: PickleArtifact) => void; + +/** Standalone pickle or legacy torch.save file, read as a sequential prefix. */ +export const readPickleFile = async ( + file: FileHandle, + size: number, + full: boolean, + budgets: PickleBudgets, + signal: AbortSignal | undefined, + retain: RetainPickleFacts, +): Promise => { + const budget = new ModelReportBudget(); + const prefix = new FilePrefix(file, size, signal); + const work = new PickleWork(budgets); + const streams: WalkedStream[] = []; + const walk = async (start: number, role: WalkedStream["role"]) => { + const walker = new PickleWalker({ fileOffset: start, member: null }, work); + for (;;) { + if ( + prefix.loaded > start && + (await feedSlices( + walker, + prefix.buffer.subarray(start), + prefix.complete, + signal, + )) + ) + break; + if (prefix.complete) + // An empty remainder: the stream has no opcode at all. + walker.feed(Buffer.alloc(0), true); + await prefix.grow(); + } + streams.push({ walker, role, length: walker.position }); + return walker; + }; + const first = await walk(0, "data"); + const legacy = intValue(first.result) === LEGACY_MAGIC; + const limitations: string[] = []; + let headerEnd = first.position; + let version: number | null = null; + let byteOrder: "little" | "big" | null = null; + let tensorDataOffset: number | null = null; + let data = first; + const records = new Map(); + if (legacy) { + streams[0] = { ...streams[0]!, role: "magic" }; + const protocol = await walk(headerEnd, "protocol"); + const declared = intValue(protocol.result); + if (declared !== LEGACY_PROTOCOL) + throw malformedInput( + MODEL_FORMAT, + `Legacy torch.save protocol version ${declared?.toString() ?? "is not an integer"}; expected 1001`, + { offset: headerEnd }, + ); + version = Number(LEGACY_PROTOCOL); + const sysInfo = await walk( + protocol.site.fileOffset! + protocol.position, + "sys-info", + ); + byteOrder = legacyByteOrder(sysInfo.result!); + data = await walk(sysInfo.site.fileOffset! + sysInfo.position, "data"); + const keysStart = data.site.fileOffset! + data.position; + const keys = await walk(keysStart, "storage-keys"); + headerEnd = keys.site.fileOffset! + keys.position; + tensorDataOffset = headerEnd; + const keyList = keys.result!; + if ( + keyList.kind !== "list" || + !keyList.items.every((item) => item.kind === "str") + ) + throw malformedInput( + MODEL_FORMAT, + "Legacy torch.save storage key list is not a list of strings", + { offset: keysStart }, + ); + const references = storageReferences(data); + const declaredKeys = new Set( + keyList.items.map((item) => (item.kind === "str" ? item.value : "")), + ); + for (const key of references.keys()) + if (!declaredKeys.has(key)) + throw malformedInput( + MODEL_FORMAT, + `Legacy torch.save storage ${key} is referenced by the data pickle but has no entry in the storage key list`, + { offset: keysStart }, + ); + let position = headerEnd; + for (const [index, item] of keyList.items.entries()) { + const key = item.kind === "str" ? item.value : ""; + const reference = references.get(key); + if (reference === undefined) + throw malformedInput( + MODEL_FORMAT, + `Legacy torch.save storage key ${key} has no persistent storage declaration`, + { offset: keysStart }, + ); + const itemsize = STORAGE_ITEMSIZE(reference.storageType); + if (itemsize === null) { + limitations.push( + `Legacy storage ${key} has unknown element size; file offsets of it and ${String(keyList.items.length - index - 1)} later storage(s) are unknown.`, + ); + break; + } + if (position + 8 > size) + throw truncatedInput( + MODEL_FORMAT, + `Legacy storage ${key} element count at file offset ${String(position)} is truncated`, + { offset: position }, + ); + const countBytes = await prefix.readAt(position, 8); + const elements = new BinaryReader( + countBytes, + byteOrder !== "big", + MODEL_FORMAT, + ).word(0, 64); + if ( + reference.elementCount !== null && + elements !== reference.elementCount + ) + throw malformedInput( + MODEL_FORMAT, + `Legacy storage ${key} declares ${elements.toString()} elements at file offset ${String(position)}; its persistent ID declares ${reference.elementCount.toString()}`, + { offset: position }, + ); + const bytes = elements * BigInt(itemsize); + const end = BigInt(position) + 8n + bytes; + if (end > BigInt(size)) + throw truncatedInput( + MODEL_FORMAT, + `Legacy storage ${key} at file offset ${String(position)} extends past the end of the file`, + { offset: position }, + ); + records.set(key, { + record: null, + recordBytes: Number(bytes), + fileOffset: position + 8, + declaredElements: elements, + }); + position = Number(end); + if (index === keyList.items.length - 1 && position < size) + limitations.push( + `${String(size - position)} byte(s) follow the last legacy storage and were not interpreted.`, + ); + } + if (byteOrder === null) + limitations.push( + "The legacy sys_info record does not state little_endian; storage byte order is unknown.", + ); + } else { + if (headerEnd < size) + limitations.push( + `${String(size - headerEnd)} byte(s) follow the pickle's STOP; an unpickler reads only the first stream and REA did not interpret them.`, + ); + limitations.push( + "A standalone pickle carries no storage bytes; storage sizes and tensor file offsets are unknown.", + ); + } + const interpreted = interpret(data, (key) => records.get(key), budget); + const facts = pickleFacts(streams, budget); + const artifact: PickleArtifact = { + format: legacy ? "pytorch-legacy" : "pickle", + version, + byte_order: byteOrder, + alignment: null, + tensor_data_offset: tensorDataOffset, + metadata: [], + tensors: interpreted.rows, + tensors_complete: interpreted.complete, + limitations: [ + ...facts.limitations, + ...limitations, + ...interpreted.limitations, + ], + pickle: facts.facts, + ...(legacy + ? { + pytorch: { + layout: "legacy" as const, + archive_prefix: null, + records: [], + storages: interpreted.storages, + }, + } + : {}), + header_length: headerEnd, + header_sha256: sha256Hex(prefix.buffer.subarray(0, headerEnd)), + sha256: null, + bytes_read: prefix.loaded + prefix.extraBytes, + }; + if (!full) return artifact; + retain(artifact); + const hash = createHash("sha256").update(prefix.buffer); + await hashRemainder(file, size, prefix.loaded, hash, signal); + return { ...artifact, sha256: hash.digest("hex"), bytes_read: size }; +}; + +const legacyByteOrder = (node: PickleNode): "little" | "big" | null => { + if (node.kind !== "dict") return null; + for (const [key, value] of node.entries) + if (key.kind === "str" && key.value === "little_endian") + return value.kind === "bool" ? (value.value ? "little" : "big") : null; + return null; +}; + +type RecordRole = PytorchFacts["records"][number]["role"]; + +const recordRole = (relative: string): RecordRole => { + switch (relative) { + case "data.pkl": + return "data-pickle"; + case "version": + case ".data/version": + return "version"; + case "byteorder": + return "byteorder"; + case ".data/serialization_id": + return "serialization-id"; + case ".format_version": + return "format-version"; + case ".storage_alignment": + return "storage-alignment"; + default: + return /^data\/[^/]+$/u.test(relative) ? "storage" : "other"; + } +}; + +const readMember = async ( + reader: ZipArtifactReader, + entry: ArtifactEntry, + maximum: number, + signal: AbortSignal | undefined, +): Promise => { + if (entry.encrypted) + rejectModel(`PyTorch archive record ${entry.path} is encrypted`); + const stream: Readable = await reader.open(entry, signal); + const chunks: Buffer[] = []; + let length = 0; + for await (const chunk of stream as AsyncIterable) { + length += chunk.length; + if (length > maximum) { + stream.destroy(); + throw modelCapacityFailure( + "header-bytes", + `PyTorch archive record ${entry.path} exceeds ${String(maximum)} bytes. This release has no runtime override.`, + ); + } + chunks.push(chunk); + } + return Buffer.concat(chunks, length); +}; + +/** PyTorch's ZIP checkpoint layout: `/data.pkl` plus `/data/` records. */ +export const readPytorchZip = async ( + path: string, + source: StableRegularFileDescriptor, + size: number, + full: boolean, + budgets: PickleBudgets, + signal: AbortSignal | undefined, + retain: RetainPickleFacts, +): Promise => { + const memberCount = operationZipMemberCount(process.env); + // No directory read may exceed what a report could retain. + const reader = new ZipArtifactReader( + path, + "zip", + MODEL_REPORT_BYTES, + source, + undefined, + memberCount.value, + ); + try { + return await readPytorchArchive( + reader, + source, + size, + full, + budgets, + signal, + retain, + ); + } catch (cause) { + const count = + cause instanceof ArtifactReaderFailure + ? zipMemberCountConstraint(MODEL_OPERATION, cause, memberCount) + : undefined; + if (count !== undefined) throw count; + // An encrypted or otherwise unsupported archive feature is outside this reader's coverage. + if ( + cause instanceof ArtifactReaderFailure && + cause.reason === "unavailable" + ) + throw unsupportedInput( + MODEL_FORMAT, + `PyTorch checkpoint ZIP uses an unsupported layout: ${cause.message}`, + { cause }, + ); + return throwZipPackageFailure(cause, MODEL_FORMAT, "PyTorch checkpoint"); + } finally { + await reader.close(); + } +}; + +const readPytorchArchive = async ( + reader: ZipArtifactReader, + source: StableRegularFileDescriptor, + size: number, + full: boolean, + budgets: PickleBudgets, + signal: AbortSignal | undefined, + retain: RetainPickleFacts, +): Promise => { + const budget = new ModelReportBudget(); + const files: ArtifactEntry[] = []; + // Each listed name may become a record row; charge it as it is enumerated. + for await (const entry of reader.entries(signal)) + if (entry.kind === "file") { + budget.charge(128 + 2 * entry.path.length); + files.push(entry); + } + const prefixes = files.flatMap((entry) => { + const match = /^([^/]+)\/data\.pkl$/u.exec(entry.path); + return match?.[1] === undefined ? [] : [match[1]]; + }); + if (prefixes.length === 0) + rejectForeignZip( + "ZIP archive has no /data.pkl record, so it is not a PyTorch checkpoint", + ); + if (prefixes.length > 1) + rejectForeignZip( + `ZIP archive has ${String(prefixes.length)} /data.pkl records, so its PyTorch archive name is ambiguous`, + ); + const prefix = prefixes[0]!; + const limitations: string[] = []; + const records: PytorchFacts["records"] = []; + const storageEntries = new Map(); + const values = new Map(); + let dataEntry: ArtifactEntry | undefined; + let bytesRead = 0; + for (const entry of files) { + const relative = entry.path.startsWith(`${prefix}/`) + ? entry.path.slice(prefix.length + 1) + : undefined; + const role = relative === undefined ? "other" : recordRole(relative); + if (role === "storage") { + storageEntries.set(relative!.slice("data/".length), entry); + continue; + } + if (role === "data-pickle") dataEntry = entry; + let value: string | null = null; + if (role !== "data-pickle" && role !== "other") { + if ((entry.declaredSize ?? Infinity) <= RECORD_TEXT_BYTES) { + const bytes = await readMember( + reader, + entry, + RECORD_TEXT_BYTES, + signal, + ); + bytesRead += entry.compressedSize ?? bytes.length; + try { + value = decodeStrictUtf8(bytes, "preserve").trim(); + } catch { + rejectModel(`PyTorch archive record ${entry.path} is not UTF-8 text`); + } + } else + limitations.push( + `PyTorch archive record ${entry.path} exceeds ${String(RECORD_TEXT_BYTES)} bytes; its value was not read.`, + ); + values.set(role, value); + } + // The row and its name were charged at enumeration. + budget.charge(2 * (value?.length ?? 0)); + records.push({ + name: entry.path, + role, + bytes: entry.declaredSize, + value, + }); + } + const pickleBytes = await readMember( + reader, + dataEntry!, + MODEL_HEADER_BYTES, + signal, + ); + bytesRead += dataEntry!.compressedSize ?? pickleBytes.length; + const work = new PickleWork(budgets); + const data = new PickleWalker( + { fileOffset: null, member: dataEntry!.path }, + work, + ); + await feedSlices(data, pickleBytes, true, signal); + const byteorder = values.get("byteorder"); + if ( + byteorder !== undefined && + byteorder !== null && + byteorder !== "little" && + byteorder !== "big" + ) + rejectModel( + `PyTorch byteorder record states ${JSON.stringify(byteorder)}; expected little or big`, + ); + if (byteorder === undefined) + limitations.push( + "The archive has no byteorder record. PyTorch's loader then assumes little-endian storage; REA reports the byte order as unknown.", + ); + const decimal = (role: RecordRole): number | null => { + const value = values.get(role); + return value != null && /^[0-9]{1,15}$/u.test(value) ? Number(value) : null; + }; + const referenced = new Set(); + const interpreted = interpret( + data, + (key) => { + referenced.add(key); + const entry = storageEntries.get(key); + if (entry === undefined) + rejectModel( + `PyTorch storage ${key} has no ${prefix}/data/${key} record in the archive`, + { field: `${prefix}/data/${key}` }, + ); + return { + record: entry.path, + recordBytes: entry.declaredSize, + fileOffset: null, + declaredElements: null, + }; + }, + budget, + ); + for (const [key, entry] of storageEntries) + if (!referenced.has(key)) + records.push({ + name: entry.path, + role: "storage", + bytes: entry.declaredSize, + value: null, + }); + if (records.some((record) => record.role === "other")) + limitations.push( + "Archive records with role other were listed but not interpreted.", + ); + limitations.push( + "Storage bytes are ZIP records, so tensor file_offset is null; data_offset is relative to the storage record and source_offset is relative to data.pkl.", + ); + const facts = pickleFacts( + [{ walker: data, role: "data", length: data.position }], + budget, + ); + if (data.position < pickleBytes.length) + limitations.push( + `${String(pickleBytes.length - data.position)} byte(s) follow STOP in ${dataEntry!.path} and were not interpreted.`, + ); + const artifact: PickleArtifact = { + format: "pytorch-zip", + version: decimal("version"), + byte_order: (byteorder ?? null) as "little" | "big" | null, + alignment: decimal("storage-alignment"), + tensor_data_offset: null, + metadata: [], + tensors: interpreted.rows, + tensors_complete: interpreted.complete, + limitations: [ + ...facts.limitations, + ...limitations, + ...interpreted.limitations, + ], + pickle: facts.facts, + pytorch: { + layout: "zip", + archive_prefix: prefix, + records, + storages: interpreted.storages, + }, + header_length: pickleBytes.length, + header_sha256: sha256Hex(pickleBytes), + sha256: null, + bytes_read: bytesRead, + }; + if (!full) return artifact; + retain(artifact); + const hash = createHash("sha256"); + await hashRemainder(source.handle, size, 0, hash, signal); + return { ...artifact, sha256: hash.digest("hex"), bytes_read: size }; +}; diff --git a/src/model/SafetensorsHeader.ts b/src/model/SafetensorsHeader.ts index a4f135f4202..efa4c31725a 100644 --- a/src/model/SafetensorsHeader.ts +++ b/src/model/SafetensorsHeader.ts @@ -7,7 +7,7 @@ import { setImmediate } from "node:timers/promises"; import { assertArtifactReadActive } from "../resources/index.js"; import type { ModelMetadata, - ModelTensor, + LocatedModelTensor, } from "../domain/model/modelArtifact.js"; import { ModelHeaderReader } from "./ModelHeaderReader.js"; import { unrecognizedInput } from "../domain/parseFailure.js"; @@ -18,7 +18,6 @@ import { modelCapacityFailure, ModelReportBudget, rejectModel, - rejectPickle, } from "./ModelFormat.js"; import { safetensorsBits } from "./ModelTensorTypes.js"; @@ -264,16 +263,10 @@ export const readSafetensorsHeader = async ( alignment: null; tensor_data_offset: number; metadata: ModelMetadata[]; - tensors: ModelTensor[]; + tensors: LocatedModelTensor[]; limitations: string[]; }> => { const budget = new ModelReportBudget(); - // Lengths such as 640 (80 02 ...) also begin like a pickle PROTO opcode. - const protocol = first[1] ?? 0; - const pickle = first[0] === 0x80 && protocol >= 2 && protocol <= 5; - // ZIP's four-byte signature is also a valid little-endian header length. - const zip = first.equals(Buffer.from([0x50, 0x4b, 3, 4])); - if ((pickle || zip) && reader.size < 9) rejectPickle(); const second = await reader.take(4); reader.excludeSafetensorsLengthPrefix(); // first and second are exact four-byte takes of the little-endian u64 prefix. @@ -281,12 +274,6 @@ export const readSafetensorsHeader = async ( new BinaryReader(first, true, "safetensors").word(0, 32) + (new BinaryReader(second, true, "safetensors").word(0, 32) << 32n); const brace = length === 0n ? undefined : (await reader.take(1))[0]; - // A brace after an admissible length is safetensors, even if truncated. - if ( - (pickle || zip) && - (brace !== 0x7b || length > BigInt(MODEL_HEADER_BYTES)) - ) - rejectPickle(); // Neither GGUF magic nor a safetensors JSON header: another format's bytes, not a damaged model. if (brace !== 0x7b) throw unrecognizedInput( @@ -333,7 +320,7 @@ export const readSafetensorsHeader = async ( }); } } - const tensors: ModelTensor[] = []; + const tensors: LocatedModelTensor[] = []; const unknownTypes = new Set(); const tensor_data_offset = 8 + size; const names = Object.keys(root) diff --git a/tests/acceptance/modelArtifactCli.test.ts b/tests/acceptance/modelArtifactCli.test.ts index 3fe3b0bc3ed..0579cd9976e 100644 --- a/tests/acceptance/modelArtifactCli.test.ts +++ b/tests/acceptance/modelArtifactCli.test.ts @@ -24,6 +24,11 @@ import { safetensorsFixture, } from "../fixtures/model/model.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { + SAMPLE_TENSORS, + stateDictPickle, + storedZip, +} from "../fixtures/model/pytorch.js"; import { cliTest, createSharedMcpSession } from "../support/cli/cliFixture.js"; /** A malformed model header is a target refusal on both adapters. */ @@ -1287,3 +1292,33 @@ cliTest( expect(JSON.stringify(result.json)).not.toContain("ENOENT"); }, ); + +it("previews PyTorch archive records in the MCP summary and counts the rest", async () => { + const root = await createTestTempDirectory("rea-model-pytorch-records-"); + const path = join(root, "checkpoint.pt"); + await writeFile( + path, + storedZip([ + ["archive/data.pkl", stateDictPickle(SAMPLE_TENSORS)], + ["archive/data/0", Buffer.alloc(24)], + ["archive/data/1", Buffer.alloc(8)], + ...Array.from( + { length: 30 }, + (_, index) => + [`archive/extra/${String(index)}`, Buffer.alloc(1)] as const, + ), + ]), + ); + const call = await modelMcp.session.call(); + const response = await call("inspect_model_artifact", { path }); + expect(response.isError, JSON.stringify(response)).not.toBe(true); + const { summary } = modelArtifactSummaryViewResultSchema.parse( + parseEvidence(response.structuredContent).normalized_result, + ); + expect(summary.pytorch).toMatchObject({ + record_count: 31, + records_omitted: 15, + storage_count: 2, + }); + expect(summary.pytorch?.records).toHaveLength(16); +}); diff --git a/tests/boundary/model/modelArtifact.test.ts b/tests/boundary/model/modelArtifact.test.ts index 0893696482f..92a97cd9961 100644 --- a/tests/boundary/model/modelArtifact.test.ts +++ b/tests/boundary/model/modelArtifact.test.ts @@ -254,7 +254,7 @@ it.each([8, 24, 40])( expect(report.alignment).toBe(alignment); expect(report.tensor_data_offset).toBe(fixture.dataOffset); expect( - report.tensors.every((row) => row.file_offset % alignment === 0), + report.tensors.every((row) => (row.file_offset ?? 1) % alignment === 0), ).toBe(true); expect(report.tensors[1]?.file_offset).toBe( fixture.dataOffset + Math.ceil(16 / alignment) * alignment, @@ -1417,12 +1417,6 @@ it.each([640, 896, 1152, 1408, 66_176])( it.each([ // Protocol 2 pickle of {"a": 1}: PROTO 2, EMPTY_DICT, BINPUT 0, ... - ["a ZIP local header", Buffer.from("504b0304140000000000", "hex")], - ["a short ZIP signature", Buffer.from("504b0304", "hex")], - [ - "a ZIP signature followed by a brace and an inadmissible length", - Buffer.from("504b0304140000007b", "hex"), - ], ["a real pickle", Buffer.from("80027d710058010000006171014b01732e", "hex")], // Protocol 2 pickle of {}: six bytes, shorter than a safetensors prefix. ["an empty dict", Buffer.from("80027d71002e", "hex")], @@ -1431,16 +1425,31 @@ it.each([ "a protocol 4 frame", Buffer.from("8004950a000000000000007d948c0161944b01732e", "hex"), ], - // The magic number torch.save writes first in its legacy format. - [ - "the legacy torch.save magic", - Buffer.from("80028a0a6cfc9c46f9206aa850192e", "hex"), - ], // Protocol 2 pickle of "x{": its brace lands at offset 8. [ "a brace after an inadmissible length", Buffer.from("80025802000000787b71002e", "hex"), ], +] as const)( + "reads pickle protocol bytes followed by %s as a pickle stream", + async (_case, bytes) => { + const report = await readFixtureHeader(bytes); + expect(report).toMatchObject({ format: "pickle", tensors: [] }); + }, +); + +it.each([ + ["a ZIP local header", Buffer.from("504b0304140000000000", "hex")], + ["a short ZIP signature", Buffer.from("504b0304", "hex")], + [ + "a ZIP signature followed by a brace and an inadmissible length", + Buffer.from("504b0304140000007b", "hex"), + ], + // The magic number torch.save writes first, without the pickles that follow it. + [ + "the legacy torch.save magic alone", + Buffer.from("80028a0a6cfc9c46f9206aa850192e", "hex"), + ], [ "an in-file length without a JSON brace", Buffer.concat([ @@ -1449,14 +1458,14 @@ it.each([ ]), ], ] as const)( - "refuses pickle protocol bytes followed by %s", + "refuses %s as a damaged pickle or ZIP rather than safetensors", async (_case, bytes) => { const { provider, path } = await providerAt(bytes); const result = await provider.inspect({ path, hash: "header" }); - if (result.ok) throw new Error("Pickle admitted"); - expect(result.error).toMatchObject({ - _tag: "AnalysisTargetFailureError", - failure: { detail: expect.stringContaining("PyTorch pickle") }, + if (result.ok) throw new Error("Damaged input admitted"); + expect(result.error).toMatchObject({ _tag: "AnalysisTargetFailureError" }); + expect(projectAnalysisError(result.error).details).not.toMatchObject({ + format: "safetensors", }); }, ); diff --git a/tests/boundary/model/modelPickle.test.ts b/tests/boundary/model/modelPickle.test.ts new file mode 100644 index 00000000000..9291e130e19 --- /dev/null +++ b/tests/boundary/model/modelPickle.test.ts @@ -0,0 +1,934 @@ +import { createHash } from "node:crypto"; +import { writeFile, open } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, it, onTestFinished, vi } from "vitest"; +import { createModelArtifactService } from "../../../src/composition/model.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; +import { modelArtifactSchema } from "../../../src/domain/model/modelArtifact.js"; +import { ModelArtifactProvider } from "../../../src/model/ModelArtifactProvider.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { ggufFixture } from "../../fixtures/model/model.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { + legacyCheckpointFixture, + op, + pickle, + pytorchZipFixture, + SAMPLE_TENSORS, + stateDictPickle, + storedZip, + tensorRebuild, +} from "../../fixtures/model/pytorch.js"; + +const inspect = async ( + bytes: Buffer, + options: { + readonly hash?: "header" | "full"; + readonly max_pickle_opcodes?: number; + readonly max_pickle_memo_entries?: number; + } = {}, +) => { + const root = await createTestTempDirectory("rea-model-pickle-"); + const path = join(root, "content.without-format-extension"); + await writeFile(path, bytes); + const provider = new ModelArtifactProvider(); + onTestFinished(() => provider.close()); + return { + path, + result: await provider.inspect({ path, hash: "header", ...options }), + }; +}; + +const inspected = async ( + bytes: Buffer, + options?: Parameters[1], +) => { + const { result } = await inspect(bytes, options); + if (!result.ok) throw result.error; + return modelArtifactSchema.parse(result.value); +}; + +const refusal = async ( + bytes: Buffer, + options?: Parameters[1], +) => { + const { result } = await inspect(bytes, options); + if (result.ok) throw new Error("Malformed pickle was admitted"); + return projectAnalysisError(result.error); +}; + +const SAMPLE_ROWS = [ + { + name: "encoder.weight", + type: "float32", + shape: ["2", "3"], + data_offset: 0, + byte_length: 24, + parameter_count: "6", + storage_validation: "consistent", + json_pointer: "/encoder.weight", + }, + { + name: "encoder.bias", + type: "float16", + shape: ["3"], + data_offset: 2, + byte_length: 6, + parameter_count: "3", + storage_validation: "consistent", + json_pointer: "/encoder.bias", + }, +]; + +it("reads a PyTorch ZIP checkpoint's records, storages and state-dict tensors without unpickling", async () => { + const bytes = pytorchZipFixture(); + const report = await inspected(bytes); + expect(report).toMatchObject({ + format: "pytorch-zip", + version: 3, + byte_order: "little", + tensor_data_offset: null, + artifact: { + header_length: stateDictPickle(SAMPLE_TENSORS).length, + header_sha256: createHash("sha256") + .update(stateDictPickle(SAMPLE_TENSORS)) + .digest("hex"), + sha256: null, + }, + totals: { parameter_count: "9", tensor_bytes: 30 }, + coverage: { storage_sizes: "complete", tensor_ranges: "complete" }, + pytorch: { + layout: "zip", + archive_prefix: "archive", + storages: [ + { + key: "0", + storage_type: "torch.FloatStorage", + dtype: "float32", + element_count: "6", + byte_length: 24, + record: "archive/data/0", + record_bytes: 24, + validation: "consistent", + }, + { + key: "1", + dtype: "float16", + byte_length: 8, + record: "archive/data/1", + validation: "consistent", + }, + ], + }, + }); + expect(report.tensors).toMatchObject(SAMPLE_ROWS); + expect(report.tensors.every((row) => row.file_offset === null)).toBe(true); + expect( + report.pytorch?.records.map(({ name, role, value }) => [name, role, value]), + ).toEqual([ + ["archive/data.pkl", "data-pickle", null], + ["archive/byteorder", "byteorder", "little"], + ["archive/version", "version", "3"], + ["archive/.data/serialization_id", "serialization-id", "1234567890"], + ]); + expect(report.pickle?.streams).toEqual([ + expect.objectContaining({ + role: "data", + member: "archive/data.pkl", + file_offset: null, + protocol: 2, + persistent_ids: 2, + trailing_values: 0, + }), + ]); + expect(report.pickle?.callables).toEqual([ + expect.objectContaining({ + name: "collections.OrderedDict", + allow_listed: true, + first_offset: 2, + }), + expect.objectContaining({ + name: "torch._utils._rebuild_tensor_v2", + allow_listed: true, + }), + expect.objectContaining({ name: "torch.FloatStorage", allow_listed: true }), + expect.objectContaining({ name: "torch.HalfStorage", allow_listed: true }), + ]); + expect( + report.pickle?.references.filter(({ opcode }) => opcode === "REDUCE"), + ).toHaveLength(6); + expect( + report.pickle?.references.filter(({ opcode }) => opcode === "BUILD"), + ).toEqual([ + expect.objectContaining({ + name: "collections.OrderedDict", + allow_listed: true, + }), + ]); + expect(report.limitations).toContain( + "Storage bytes are ZIP records, so tensor file_offset is null; data_offset is relative to the storage record and source_offset is relative to data.pkl.", + ); + + const full = await inspected(bytes, { hash: "full" }); + expect(full.artifact).toMatchObject({ + sha256: createHash("sha256").update(bytes).digest("hex"), + bytes_read: bytes.length, + read_scope: "full-file", + }); +}); + +it("reads a legacy torch.save checkpoint and locates each storage in the file", async () => { + const { bytes, dataStart } = legacyCheckpointFixture(); + const report = await inspected(bytes); + expect(report).toMatchObject({ + format: "pytorch-legacy", + version: 1001, + byte_order: "little", + tensor_data_offset: dataStart, + artifact: { header_length: dataStart }, + pytorch: { + layout: "legacy", + storages: [ + { key: "0", file_offset: dataStart + 8, validation: "consistent" }, + { + key: "1", + file_offset: dataStart + 8 + 24 + 8, + validation: "consistent", + }, + ], + }, + }); + expect(report.pickle?.streams.map(({ role }) => role)).toEqual([ + "magic", + "protocol", + "sys-info", + "data", + "storage-keys", + ]); + expect(report.tensors).toMatchObject(SAMPLE_ROWS); + expect(report.tensors.map(({ file_offset }) => file_offset)).toEqual([ + dataStart + 8, + dataStart + 8 + 24 + 8 + 2, + ]); +}); + +it("reports a non-allow-listed GLOBAL with its offset as an observation of what loading would call", async () => { + // A protocol 2 pickle of posix.system("id"): the classic __reduce__ shape. + const bytes = pickle( + op.proto(2), + op.global("posix", "system"), + op.unicode("id"), + op.tuple1, + op.reduce, + op.stop, + ); + const report = await inspected(bytes); + expect(report).toMatchObject({ + format: "pickle", + byte_order: null, + tensors: [], + pickle: { + references: [ + { + offset: 2, + opcode: "GLOBAL", + name: "posix.system", + allow_listed: false, + }, + { + offset: 24, + opcode: "REDUCE", + name: "posix.system", + allow_listed: false, + }, + ], + callables: [ + { + name: "posix.system", + allow_listed: false, + references: 2, + first_stream: 0, + first_offset: 2, + }, + ], + }, + }); + expect(report.limitations).toContainEqual( + expect.stringContaining( + "would import or call 1 callable(s) outside the tensor-rebuild allow-list: posix.system (stream 0, offset 2)", + ), + ); + expect(report.pytorch).toBeUndefined(); +}); + +it("resolves STACK_GLOBAL names from memoized strings in protocol 4 streams", async () => { + const report = await inspected( + pickle( + op.proto(4), + op.shortUnicode("builtins"), + op.memoize, + op.shortUnicode("eval"), + op.memoize, + op.stackGlobal, + op.memoize, + op.stop, + ), + ); + expect(report.pickle?.references).toEqual([ + expect.objectContaining({ + opcode: "STACK_GLOBAL", + name: "builtins.eval", + allow_listed: false, + offset: 20, + }), + ]); + expect(report.pickle?.streams[0]).toMatchObject({ protocol: 4 }); +}); + +it.each([ + [ + "a truncated stream", + stateDictPickle(SAMPLE_TENSORS).subarray(0, 40), + { failure_kind: "truncated", offset: 34 }, + ], + [ + "a stream without STOP", + pickle(op.proto(2), op.none), + { failure_kind: "truncated", offset: 3 }, + ], + [ + "an unknown opcode", + pickle(op.proto(2), Buffer.of(0xff), op.stop), + { failure_kind: "malformed", offset: 2 }, + ], + [ + "a GET of an undefined memo key", + pickle(op.proto(2), op.binget(5), op.stop), + { failure_kind: "malformed", offset: 2 }, + ], + [ + "an empty-stack REDUCE", + pickle(op.proto(2), op.reduce, op.stop), + { failure_kind: "malformed", offset: 2 }, + ], +] as const)("reports %s with its offset", async (_name, bytes, expected) => { + const error = await refusal(bytes); + expect(error).toMatchObject({ + code: "unsupported_target", + details: expected, + }); +}); + +it("names the archive record of a malformed opcode inside data.pkl", async () => { + const error = await refusal( + pytorchZipFixture({ + dataPickle: pickle(op.proto(2), op.binget(9), op.stop), + }), + ); + expect(error).toMatchObject({ + details: { + failure_kind: "malformed", + offset: 2, + field: "archive/data.pkl", + }, + }); +}); + +it("refuses a referenced storage record the archive lacks", async () => { + const error = await refusal(pytorchZipFixture({ omit: ["archive/data/1"] })); + expect(error).toMatchObject({ + details: { failure_kind: "malformed" }, + }); +}); + +it("keeps a ZIP without /data.pkl an unsupported target", async () => { + const error = await refusal( + storedZip([["model/weights.bin", Buffer.alloc(4)]]), + ); + expect(error).toMatchObject({ code: "unsupported_target" }); +}); + +it.each([ + ["max_pickle_opcodes", { max_pickle_opcodes: 3 }], + ["max_pickle_memo_entries", { max_pickle_memo_entries: 1 }], +] as const)( + "stops at %s and names that per-call parameter", + async (parameter, options) => { + const error = await refusal(stateDictPickle(SAMPLE_TENSORS), options); + expect(error).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter, + effective_value: Object.values(options)[0], + }, + }, + }); + }, +); + +it("names tensors unknown when a shared container hides their key path", async () => { + // The same list sits under two keys, so its tensor has no single path. + const tensor = stateDictPickle([SAMPLE_TENSORS[0]!]); + const body = tensor.subarray(2, tensor.length - 1); // drop PROTO and STOP + const report = await inspected( + pickle( + op.proto(2), + op.emptyDict, + op.mark, + op.unicode("left"), + op.emptyList, + Buffer.of(0x71, 9), // BINPUT 9 + op.mark, + body, + op.appends, + op.unicode("right"), + op.binget(9), + op.setitems, + op.stop, + ), + ); + expect(report.tensors).toMatchObject([ + { name: "#0", json_pointer: null, parameter_count: "6" }, + ]); + expect(report.limitations).toContainEqual( + expect.stringContaining( + "1 tensor(s) are not reached through one unshared chain", + ), + ); +}); + +it("keeps every reference in complete Evidence and records only caller-set pickle budgets", async () => { + const root = await createTestTempDirectory("rea-model-pickle-summary-"); + const path = join(root, "checkpoint.pt"); + await writeFile(path, pytorchZipFixture()); + const service = createModelArtifactService(); + onTestFinished(() => service.close()); + const complete = await service.inspect({ path, detail: "complete" }); + if (!complete.ok) throw complete.error; + expect(complete.value.parameters).toEqual({ path, hash: "header" }); + const result = complete.value.normalized_result as { + pickle: { references: unknown[] }; + }; + expect(result.pickle.references).toHaveLength(11); + const budgeted = await service.inspect({ + path, + detail: "complete", + max_pickle_opcodes: 1000, + }); + if (!budgeted.ok) throw budgeted.error; + expect(budgeted.value.parameters).toEqual({ + path, + hash: "header", + max_pickle_opcodes: 1000, + }); +}); + +it("walks a 200,000-value APPENDS without spreading it onto the call stack", async () => { + const count = 200_000; + const report = await inspected( + pickle( + op.proto(2), + op.emptyList, + op.mark, + Buffer.alloc(count, op.none[0]!), + op.appends, + op.stop, + ), + ); + expect(report.pickle?.streams[0]).toMatchObject({ opcode_count: count + 5 }); +}); + +it("unwraps a deep _rebuild_parameter chain without recursion", async () => { + const depth = 20_000; + const wrapper = op.global("torch._utils", "_rebuild_parameter"); + const report = await inspected( + pickle( + op.proto(2), + wrapper, + op.binput(3), + op.mark, + ...Array.from({ length: depth - 1 }, () => pickle(op.binget(3), op.mark)), + tensorRebuild(SAMPLE_TENSORS[0]!), + ...Array.from({ length: depth }, () => + pickle(op.newFalse, op.emptyDict, op.tuple, op.reduce), + ), + op.stop, + ), + ); + expect(report.tensors).toMatchObject([ + { name: "#0", type: "float32", parameter_count: "6" }, + ]); +}); + +it("names a tensor at the end of a deep key path in linear work", async () => { + const depth = 20_000; + const report = await inspected( + pickle( + op.proto(2), + ...Array.from({ length: depth }, () => + pickle(op.emptyDict, op.shortUnicode("a")), + ), + tensorRebuild(SAMPLE_TENSORS[0]!), + Buffer.alloc(depth, op.setitem[0]!), + op.stop, + ), + ); + const name = Array.from({ length: depth }, () => "a").join("."); + expect(report.tensors).toMatchObject([ + { name, json_pointer: `/${name.replaceAll(".", "/")}` }, + ]); +}); + +it("keeps the last value of a repeated dict key, as unpickling would", async () => { + const [first, second] = SAMPLE_TENSORS; + const report = await inspected( + pickle( + op.proto(2), + op.emptyDict, + op.mark, + op.unicode("w"), + tensorRebuild(first!), + op.unicode("w"), + tensorRebuild(second!), + op.setitems, + op.stop, + ), + ); + expect(report.tensors).toMatchObject([ + { name: "w", json_pointer: "/w", type: "float16", parameter_count: "3" }, + ]); +}); + +const directStorage = pickle( + op.proto(2), + op.mark, + op.unicode("storage"), + op.global("torch", "FloatStorage"), + op.unicode("7"), + op.unicode("cpu"), + op.int(2), + op.tuple, + op.binpersid, + op.stop, +); + +it("inventories a storage the pickle saves without a tensor", async () => { + const report = await inspected( + storedZip([ + ["archive/data.pkl", directStorage], + ["archive/data/7", Buffer.alloc(8)], + ["archive/version", Buffer.from("3\n")], + ]), + ); + expect(report.tensors).toEqual([]); + expect(report.pytorch?.storages).toMatchObject([ + { + key: "7", + dtype: "float32", + element_count: "2", + byte_length: 8, + record: "archive/data/7", + record_bytes: 8, + validation: "consistent", + }, + ]); +}); + +it("refuses a tensor-less storage the archive lacks", async () => { + const error = await refusal( + storedZip([ + ["archive/data.pkl", directStorage], + ["archive/version", Buffer.from("3\n")], + ]), + ); + expect(error).toMatchObject({ details: { failure_kind: "malformed" } }); +}); + +it.each([ + [ + "a FRAME longer than the stream", + pickle(op.proto(4), Buffer.of(0x95, 100, 0, 0, 0, 0, 0, 0, 0), op.stop), + "truncated", + ], + [ + "a \\U escape past U+10FFFF", + pickle(op.proto(2), Buffer.from("V\\U00110000\n"), op.stop), + "malformed", + ], + [ + "a short \\u escape", + pickle(op.proto(2), Buffer.from("V\\u12\n"), op.stop), + "malformed", + ], + [ + "BINUNICODE that is not UTF-8", + pickle(op.proto(2), Buffer.of(0x8c, 2, 0xc3, 0x28), op.stop), + "malformed", + ], +] as const)("refuses %s", async (_name, bytes, failure_kind) => { + const error = await refusal(bytes); + expect(error).toMatchObject({ + code: "unsupported_target", + details: { failure_kind }, + }); +}); + +it.each([ + [ + "a lone surrogate in BINUNICODE, which pickle writes with surrogatepass", + pickle(op.proto(2), Buffer.of(0x8c, 3, 0xed, 0xa0, 0x80), op.stop), + ], + [ + "an escaped backslash before u in raw-unicode-escape text", + pickle(op.proto(2), Buffer.from("V\\\\u12\n"), op.stop), + ], +] as const)("admits %s", async (_name, bytes) => { + const report = await inspected(bytes); + expect(report.format).toBe("pickle"); +}); + +it("keeps a LONG with more digits than an exact long as an unknown integer", async () => { + const report = await inspected( + pickle(op.proto(2), Buffer.from(`L${"9".repeat(100_000)}L\n`), op.stop), + ); + expect(report.format).toBe("pickle"); +}); + +it("refuses a protocol 0 memo key that exceeds exact precision", async () => { + const error = await refusal( + pickle(op.proto(2), op.none, Buffer.from(`p${"1".repeat(200)}\n`), op.stop), + ); + expect(error).toMatchObject({ + code: "unsupported_target", + details: { failure_kind: "malformed", offset: 3 }, + }); +}); + +it("decodes STRING keys with Python's escapes, keeping unknown escapes", async () => { + const report = await inspected( + pickle( + op.proto(2), + op.emptyDict, + op.mark, + Buffer.from("S'left\\fright\\q'\n"), + tensorRebuild(SAMPLE_TENSORS[0]!), + op.setitems, + op.stop, + ), + ); + expect(report.tensors).toMatchObject([{ name: "left\fright\\q" }]); +}); + +it("marks tensor coverage partial when a rebuild call cannot be read", async () => { + const report = await inspected( + pickle( + op.proto(2), + op.global("torch._utils", "_rebuild_tensor_v2"), + op.mark, + op.none, + op.tuple, + op.reduce, + op.stop, + ), + ); + expect(report.tensors).toEqual([]); + expect(report.coverage).toMatchObject({ + storage_sizes: "partial", + tensor_ranges: "partial", + }); +}); + +it("classifies a model whose first positional read returns fewer bytes", async () => { + const root = await createTestTempDirectory("rea-model-short-peek-"); + const path = join(root, "model.bin"); + await writeFile(path, ggufFixture().bytes); + const sample = await open(path, "r"); + const prototype = Object.getPrototypeOf(sample) as { + read: ( + buffer: Buffer, + offset: number, + length: number, + position: number, + ) => Promise<{ bytesRead: number }>; + }; + await sample.close(); + const originalRead = prototype.read; + const spy = vi.spyOn(prototype, "read").mockImplementation(function ( + this: unknown, + buffer: Buffer, + offset: number, + length: number, + position: number, + ) { + // The first read of the file returns three bytes, as a positional read may. + return originalRead.call( + this, + buffer, + offset, + position === 0 ? Math.min(length, 3) : length, + position, + ); + }); + onTestFinished(() => spy.mockRestore()); + const provider = new ModelArtifactProvider(); + onTestFinished(() => provider.close()); + const result = await provider.inspect({ path, hash: "header" }); + expect(result).toMatchObject({ ok: true, value: { format: "gguf" } }); +}); + +it("retains completed pickle facts when full-file hashing is cancelled", async () => { + const root = await createTestTempDirectory("rea-model-pickle-partial-"); + const path = join(root, "checkpoint.pt"); + const tail = 32 * 1024 * 1024; + await writeFile( + path, + Buffer.concat([stateDictPickle(SAMPLE_TENSORS), Buffer.alloc(tail)]), + ); + const controller = new AbortController(); + const reason = { marker: "cancel-during-full-hash" }; + const sample = await open(path, "r"); + const prototype = Object.getPrototypeOf(sample) as { + read: (...args: unknown[]) => Promise<{ bytesRead: number }>; + }; + await sample.close(); + const originalRead = prototype.read; + const spy = vi.spyOn(prototype, "read").mockImplementation(async function ( + this: unknown, + ...args: unknown[] + ) { + const result = await originalRead.apply(this, args); + if ((args[3] as number) > tail / 2) controller.abort(reason); + return result; + }); + onTestFinished(() => spy.mockRestore()); + const provider = new ModelArtifactProvider(); + onTestFinished(() => provider.close()); + const result = await provider.inspect( + { path, hash: "full" }, + { signal: controller.signal }, + ); + if (result.ok) throw new Error("Expected hashing cancellation"); + expect(result.error.cause).toBe(reason); + const evidence = parseEvidence(result.error.partialObservation); + expect(evidence.normalized_result).toMatchObject({ + kind: "model-artifact-partial", + format: "pickle", + artifact: { sha256: null, file_identity: "unverified" }, + coverage: { header: "complete", tensors: "complete" }, + tensors: [{ name: "encoder.weight" }, { name: "encoder.bias" }], + pickle: { streams: [{ role: "data" }] }, + }); +}); + +it("applies the session ZIP member count to PyTorch archives", async () => { + vi.stubEnv("REA_ARTIFACT_MEMBER_COUNT", "2"); + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + const error = await refusal(pytorchZipFixture()); + expect(error).toMatchObject({ + code: "resource_constraint", + details: { + limit: { setting: "artifact.member_count", effective_value: 2 }, + }, + }); +}); + +const keyed = (...pairs: (readonly [Buffer, Buffer])[]) => + pickle( + op.proto(2), + op.emptyDict, + op.mark, + ...pairs.flat(), + op.setitems, + op.stop, + ); + +it("keeps an astral character and its surrogate pair as distinct dict keys", async () => { + const report = await inspected( + keyed( + [ + Buffer.of(0x8c, 4, 0xf0, 0x9f, 0x98, 0x80), + tensorRebuild(SAMPLE_TENSORS[0]!), + ], + [ + Buffer.of(0x8c, 6, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80), + tensorRebuild(SAMPLE_TENSORS[1]!), + ], + ), + ); + // Both tensors survive; their equal display names are not unambiguous. + expect(report.tensors).toMatchObject([ + { name: "#0", parameter_count: "6" }, + { name: "#1", parameter_count: "3" }, + ]); +}); + +it("treats raw-unicode-escape and surrogatepass surrogates as one key", async () => { + const report = await inspected( + keyed( + [Buffer.from("V\\ud83d\\ude00\n"), tensorRebuild(SAMPLE_TENSORS[0]!)], + [ + Buffer.of(0x8c, 6, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80), + tensorRebuild(SAMPLE_TENSORS[1]!), + ], + ), + ); + expect(report.tensors).toMatchObject([{ parameter_count: "3" }]); +}); + +it("keeps the first equal key when a later key replaces its value", async () => { + const report = await inspected( + keyed( + [op.int(1), tensorRebuild(SAMPLE_TENSORS[0]!)], + [op.newTrue, tensorRebuild(SAMPLE_TENSORS[1]!)], + ), + ); + expect(report.tensors).toMatchObject([ + { name: "1", json_pointer: "/1", type: "float16" }, + ]); +}); + +it("decodes UNICODE text full of literal backslashes in bounded slices", async () => { + const report = await inspected( + pickle(op.proto(2), Buffer.from(`V${"\\x".repeat(4_000_000)}\n`), op.stop), + ); + expect(report.format).toBe("pickle"); +}); + +it("writes a memoized 1 MiB key many times without rebuilding its identity", async () => { + const writes = 100_000; + const report = await inspected( + pickle( + op.proto(2), + op.emptyDict, + op.unicode("k".repeat(1024 * 1024)), + op.binput(1), + op.none, + op.setitem, + ...Array.from({ length: writes }, () => + pickle(op.binget(1), op.none, op.setitem), + ), + op.stop, + ), + ); + expect(report.pickle?.streams[0]).toMatchObject({ + opcode_count: 7 + 3 * writes, + }); +}, 20_000); + +it("refuses a tensor whose shape product exceeds its storage without building an unbounded count", async () => { + const huge = (1n << 511n) - 1n; + const shape = pickle( + op.mark, + ...Array.from({ length: 64 }, () => op.binget(1)), + op.tuple, + ); + const stride = pickle( + op.mark, + ...Array.from({ length: 64 }, () => op.int(0)), + op.tuple, + ); + const bytes = pickle( + op.proto(2), + op.long1(huge), + op.binput(1), + op.global("torch._utils", "_rebuild_tensor_v2"), + op.mark, + op.mark, + op.unicode("storage"), + op.global("torch", "FloatStorage"), + op.unicode("0"), + op.unicode("cpu"), + op.int(1), + op.tuple, + op.binpersid, + op.int(0), + shape, + stride, + op.newFalse, + op.global("collections", "OrderedDict"), + op.emptyTuple, + op.reduce, + op.tuple, + op.reduce, + op.stop, + ); + const error = await refusal(bytes); + expect(error).toMatchObject({ + code: "resource_constraint", + details: { + reason: + "PyTorch tensor element count exceeds exact host offset precision", + }, + }); +}); + +it("reads an expanded tensor view and an empty tensor", async () => { + const expanded = await inspected( + stateDictPickle([ + { + name: "expanded", + storage: "0", + elements: 1, + shape: [8], + stride: [0], + }, + ]), + ); + expect(expanded.tensors).toMatchObject([ + { name: "expanded", parameter_count: "8", byte_length: 4 }, + ]); + const empty = await inspected( + stateDictPickle([ + { + name: "empty", + storage: "0", + elements: 0, + shape: [2, 0], + stride: [0, 1], + }, + ]), + ); + expect(empty.tensors).toMatchObject([ + { name: "empty", parameter_count: "0", byte_length: 0 }, + ]); +}); + +it("refuses a malformed FLOAT operand", async () => { + const error = await refusal( + pickle(op.proto(2), Buffer.from("Fnot-a-number\n"), op.stop), + ); + expect(error).toMatchObject({ details: { failure_kind: "malformed" } }); +}); + +it("does not report BUILD or EXT references as foreign callables", async () => { + const built = await inspected( + pickle(op.proto(2), op.emptyDict, op.none, op.build, op.stop), + ); + expect( + built.limitations.some((text) => text.includes("would import or call")), + ).toBe(false); + const extended = await inspected( + pickle(op.proto(2), Buffer.of(0x82, 5), op.stop), + ); + expect( + extended.limitations.some((text) => text.includes("would import or call")), + ).toBe(false); +}); + +it("refuses a referenced storage record the archive lacks, naming the record", async () => { + const error = await refusal(pytorchZipFixture({ omit: ["archive/data/1"] })); + expect(error).toMatchObject({ + details: { failure_kind: "malformed", field: "archive/data/1" }, + }); +}); + +it("scans a long backslash run in UNICODE text once", async () => { + const report = await inspected( + pickle(op.proto(2), Buffer.from(`V${"\\".repeat(200_000)}x\n`), op.stop), + ); + expect(report.format).toBe("pickle"); +}); diff --git a/tests/fixtures/model/pytorch.ts b/tests/fixtures/model/pytorch.ts new file mode 100644 index 00000000000..6213793180f --- /dev/null +++ b/tests/fixtures/model/pytorch.ts @@ -0,0 +1,283 @@ +import { crc32 } from "node:zlib"; + +/** + * Raw pickle opcodes, written from the CPython pickle opcode table + * (Lib/pickletools.py) so fixtures need neither Python nor torch. + */ +export const op = { + proto: (version: number) => Buffer.of(0x80, version), + stop: Buffer.from("."), + mark: Buffer.from("("), + tuple: Buffer.from("t"), + tuple1: Buffer.of(0x85), + tuple2: Buffer.of(0x86), + emptyTuple: Buffer.from(")"), + emptyDict: Buffer.from("}"), + emptyList: Buffer.from("]"), + setitems: Buffer.from("u"), + setitem: Buffer.from("s"), + appends: Buffer.from("e"), + reduce: Buffer.from("R"), + build: Buffer.from("b"), + binpersid: Buffer.from("Q"), + newFalse: Buffer.of(0x89), + newTrue: Buffer.of(0x88), + none: Buffer.from("N"), + global: (module: string, name: string) => + Buffer.from(`c${module}\n${name}\n`), + stackGlobal: Buffer.of(0x93), + memoize: Buffer.of(0x94), + unicode: (text: string) => { + const bytes = Buffer.from(text); + const length = Buffer.alloc(4); + length.writeUInt32LE(bytes.length); + return Buffer.concat([Buffer.from("X"), length, bytes]); + }, + shortUnicode: (text: string) => { + const bytes = Buffer.from(text); + return Buffer.concat([Buffer.of(0x8c, bytes.length), bytes]); + }, + int: (value: number) => { + if (value >= 0 && value < 256) return Buffer.of(0x4b, value); + const bytes = Buffer.alloc(5); + bytes[0] = 0x4a; + bytes.writeInt32LE(value, 1); + return bytes; + }, + long1: (value: bigint) => { + const bytes: number[] = []; + let rest = value; + while (rest > 0n || bytes.length === 0 || (bytes.at(-1)! & 0x80) !== 0) { + bytes.push(Number(rest & 0xffn)); + rest >>= 8n; + } + return Buffer.of(0x8a, bytes.length, ...bytes); + }, + binput: (key: number) => Buffer.of(0x71, key), + binget: (key: number) => Buffer.of(0x68, key), +} as const; + +export const pickle = (...parts: Buffer[]): Buffer => Buffer.concat(parts); + +interface TensorSpec { + readonly name: string; + readonly storage: string; + readonly storageType?: string; + readonly elements: number; + readonly offset?: number; + readonly shape: readonly number[]; + readonly stride: readonly number[]; +} + +const ints = (values: readonly number[]) => + pickle(op.mark, ...values.map(op.int), op.tuple); + +/** + * `_rebuild_tensor_v2(persistent storage, offset, size, stride, False, OrderedDict())`. + * The callable and OrderedDict default to GLOBALs; a caller may pass memo reads. + */ +export const tensorRebuild = ( + tensor: TensorSpec, + options: { + readonly legacy?: boolean; + readonly rebuild?: Buffer; + readonly orderedDict?: Buffer; + } = {}, +): Buffer => + pickle( + options.rebuild ?? op.global("torch._utils", "_rebuild_tensor_v2"), + op.mark, + op.mark, + op.unicode("storage"), + op.global("torch", tensor.storageType ?? "FloatStorage"), + op.unicode(tensor.storage), + op.unicode("cpu"), + op.int(tensor.elements), + ...(options.legacy === true ? [op.none] : []), + op.tuple, + op.binpersid, + op.int(tensor.offset ?? 0), + ints(tensor.shape), + ints(tensor.stride), + op.newFalse, + options.orderedDict ?? op.global("collections", "OrderedDict"), + op.emptyTuple, + op.reduce, + op.tuple, + op.reduce, + ); + +/** The OrderedDict state dict torch.save pickles, with each value a {@link tensorRebuild}. */ +export const stateDictPickle = ( + tensors: readonly TensorSpec[], + options: { readonly legacy?: boolean } = {}, +): Buffer => + pickle( + op.proto(2), + op.global("collections", "OrderedDict"), + op.binput(0), + op.emptyTuple, + op.reduce, + op.binput(1), + op.mark, + ...tensors.flatMap((tensor, index) => [ + op.unicode(tensor.name), + tensorRebuild(tensor, { + ...options, + rebuild: + index === 0 + ? pickle( + op.global("torch._utils", "_rebuild_tensor_v2"), + op.binput(2), + ) + : op.binget(2), + orderedDict: op.binget(0), + }), + ]), + op.setitems, + // state_dict() carries a _metadata attribute that BUILD sets on the OrderedDict. + op.emptyDict, + op.unicode("_metadata"), + op.binget(0), + op.emptyTuple, + op.reduce, + op.setitem, + op.build, + op.stop, + ); + +export const SAMPLE_TENSORS: readonly TensorSpec[] = [ + { + name: "encoder.weight", + storage: "0", + elements: 6, + shape: [2, 3], + stride: [3, 1], + }, + { + name: "encoder.bias", + storage: "1", + storageType: "HalfStorage", + elements: 4, + offset: 1, + shape: [3], + stride: [1], + }, +]; + +/** A stored (uncompressed) ZIP, as PyTorch's writer produces, from PKWARE APPNOTE records. */ +export const storedZip = ( + members: readonly (readonly [string, Buffer])[], +): Buffer => { + const locals: Buffer[] = []; + const centrals: Buffer[] = []; + let offset = 0; + for (const [name, content] of members) { + const nameBytes = Buffer.from(name); + const checksum = crc32(content); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(0x5021, 12); + local.writeUInt32LE(checksum, 14); + local.writeUInt32LE(content.length, 18); + local.writeUInt32LE(content.length, 22); + local.writeUInt16LE(nameBytes.length, 26); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(0x5021, 14); + central.writeUInt32LE(checksum, 16); + central.writeUInt32LE(content.length, 20); + central.writeUInt32LE(content.length, 24); + central.writeUInt16LE(nameBytes.length, 28); + central.writeUInt32LE(offset, 42); + locals.push(local, nameBytes, content); + centrals.push(central, nameBytes); + offset += local.length + nameBytes.length + content.length; + } + const directory = Buffer.concat(centrals); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(members.length, 8); + end.writeUInt16LE(members.length, 10); + end.writeUInt32LE(directory.length, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, directory, end]); +}; + +/** A torch.save ZIP checkpoint of {@link SAMPLE_TENSORS}. */ +export const pytorchZipFixture = ( + options: { + readonly dataPickle?: Buffer; + readonly omit?: readonly string[]; + readonly byteorder?: string; + } = {}, +): Buffer => + storedZip( + ( + [ + [ + "archive/data.pkl", + options.dataPickle ?? stateDictPickle(SAMPLE_TENSORS), + ], + ["archive/byteorder", Buffer.from(options.byteorder ?? "little")], + ["archive/data/0", Buffer.alloc(24)], + ["archive/data/1", Buffer.alloc(8)], + ["archive/version", Buffer.from("3\n")], + ["archive/.data/serialization_id", Buffer.from("1234567890")], + ] as const + ).filter(([name]) => !(options.omit ?? []).includes(name)), + ); + +const LEGACY_MAGIC = 0x1950a86a20f9469cfc6cn; + +/** torch.save's legacy format: five pickles, then `[u64 element count][bytes]` per storage key. */ +export const legacyCheckpointFixture = (): { + readonly bytes: Buffer; + readonly dataStart: number; +} => { + const header = pickle( + pickle(op.proto(2), op.long1(LEGACY_MAGIC), op.stop), + pickle(op.proto(2), Buffer.of(0x4d, 0xe9, 0x03), op.stop), + pickle( + op.proto(2), + op.emptyDict, + op.mark, + op.unicode("protocol_version"), + Buffer.of(0x4d, 0xe9, 0x03), + op.unicode("little_endian"), + op.newTrue, + op.setitems, + op.stop, + ), + stateDictPickle(SAMPLE_TENSORS, { legacy: true }), + pickle( + op.proto(2), + op.emptyList, + op.mark, + op.unicode("0"), + op.unicode("1"), + op.appends, + op.stop, + ), + ); + const count = (elements: number) => { + const bytes = Buffer.alloc(8); + bytes.writeBigUInt64LE(BigInt(elements)); + return bytes; + }; + return { + bytes: Buffer.concat([ + header, + count(6), + Buffer.alloc(24), + count(4), + Buffer.alloc(8), + ]), + dataStart: header.length, + }; +};