Skip to main content

MSC Serial (mscs)

Binary serialization for Python with explicit class registration, optional HMAC-SHA256 authentication, and NumPy/PyTorch support.

Version 2.7.0 · Python 3.9+ · MIT license

MSCS supports primitive values, containers, shared references, many cyclic graphs, registered classes and dataclasses. It uses its own wire format; it cannot read pickle files or implement every pickle protocol feature.

Install

python -m pip install mscs
python -m pip install "mscs[numpy]"  # NumPy >=1.20
python -m pip install "mscs[torch]"  # NumPy >=1.20 and PyTorch >=2.8

The base package has no mandatory runtime dependencies. Optional dependency versions must also support your Python version and platform.

Quick start

import mscs

data = {"name": "example", "values": [1, 2, 3]}
blob = mscs.dumps(data)
assert mscs.loads(blob) == data

with open("example.msc", "wb") as file:
    mscs.dump(data, file)
with open("example.msc", "rb") as file:
    restored = mscs.load(file)

Register only classes whose reconstruction code you trust:

from dataclasses import dataclass
import mscs

@mscs.register
@dataclass
class Point:
    x: float
    y: float

point = mscs.loads(mscs.dumps(Point(1.0, 2.0)))
assert isinstance(point, Point)

Classes are identified by module and qualified name. Keep those names stable across producer and consumer; use register_alias(old_name, cls) for migrations. Enums also require registration to restore their class identity.

Authentication and limits

import secrets
import mscs

key = secrets.token_bytes(32)  # Example: securely share/persist your real key.
signed = mscs.dumps({"value": 42}, hmac_key=key)
value = mscs.loads(
    signed,
    hmac_key=key,
    max_size=8 * 1024 * 1024,
    max_depth=64,
    max_hash_work=100_000,
)

Providing hmac_key on load requires a valid signature and rejects unsigned v2 and legacy v1 input. Authentication is checked before object reconstruction. For compressed files, bounded decompression precedes authentication of the inner message. HMAC does not encrypt data. with_crc=True detects accidental corruption; CRC is not authentication and cannot be combined with hmac_key.

Load option Default Meaning
strict True Reject unregistered classes; False returns fallback data for them.
max_size 512 MiB Maximum encoded message size, including framing.
max_depth 256 Maximum nesting depth; also available on encoding.
max_hash_work 1,000,000 Cumulative expanded builtin hash work for keys, set items and Enum values; also bounds reference scans in graphs with tuple cycles.

Use per-call options; rebinding exported MAX_* constants does not change the decoder defaults. Python object overhead can make memory usage substantially larger than max_size. Hash work limits do not bound collision costs, equality comparisons or registered class methods. For hostile workloads, also impose process memory and execution-time limits appropriate to your application.

The registry is a trust boundary, not a sandbox. Reconstruction may execute registered __new__, __setstate__, attribute descriptors, hash/equality methods and Enum _missing_ hooks. strict=False does not disable registered class hooks. MSCS does not import arbitrary classes named by a payload, but registering a class explicitly authorizes its reconstruction behavior.

Arrays, tensors and object state

import numpy as np
import mscs

array = np.arange(12, dtype=np.float32).reshape(3, 4)
assert np.array_equal(mscs.loads(mscs.dumps(array)), array)

Numeric and boolean NumPy dtypes are supported; object, structured, void and string dtypes are rejected. Arrays are reconstructed into copied buffers. Dense PyTorch tensors are serialized through CPU storage, including bfloat16 and resolved conjugate/negative views. Restored tensors are on CPU; device placement, storage views and autograd graphs are not preserved. The requires_grad flag is retained where the dtype supports it.

Dataclass fields, inherited/private slots and unset slots are handled explicitly. Shared references and supported cycles preserve identity. Cycles that require passing unresolved tuple state into an opaque __setstate__ fail with MSCDecodeError; use a mutable container to break that reconstruction dependency.

API

Function Purpose
dumps(obj, **options) / loads(blob, **options) Encode/decode bytes.
dump(obj, file, **options) / load(file, **options) Stream to/from an open binary file (dump() streams incrementally with bounded memory).
dump_compressed(obj, file, level=6, **options) / load_compressed(file, **options) Use a bounded zlib container around an MSCS message.
Registry(copy_default=False) Create an isolated, thread-safe class registry.
register(cls) / register_alias(name, cls) Allow a class or its former wire name in the default registry.
register_module(module) Register classes from a trusted module; review what it exposes.
unregister(target) / clear_registry() / list_registered() Remove an entry, clear, or inspect a copy of the default registry.
copy(obj, **options) Round-trip a trusted object with non-strict fallback behavior.
inspect(blob) Read framing metadata from bytes, bytearray, or memoryview (including has_crc and has_hmac); does not authenticate or validate the entire message.
benchmark(obj, rounds=100) Run the included local serialization benchmark.

Encoding options are with_crc, hmac_key, max_depth and registry. Decoding options are strict, hmac_key, max_size, max_depth, max_hash_work and registry. copy() accepts max_depth and registry. Catch MSCError for library errors, or its subclasses MSCEncodeError, MSCDecodeError and MSCSecurityError for more specific handling.

Upgrading to 2.7

  • Isolated registries are available via mscs.Registry() and the registry= keyword option on dumps, loads, dump, load, dump_compressed, load_compressed and copy, alongside unregister, clear_registry and list_registered.
  • Registered subclasses of NamedTuple, OrderedDict, defaultdict, and builtin containers/scalars (list, dict, set, frozenset, deque, int, float, complex, str, bytes, bytearray) now preserve their exact registered class identity; unregistered subclasses continue to serialize as their base wire types. Subclasses of value types (Decimal, datetime, date, time, timedelta, UUID, Path, arrays, tensors) and builtin subclasses that are dataclasses or define __getstate__ / __setstate__ also keep their base wire type, as in 2.6: items and values are preserved, the subtype and its extra attributes are not.
  • Upgrade readers before writers: 2.6 readers reject a registered NamedTuple written by 2.7 and load other registered builtin subclasses as empty containers or zero/empty scalars without raising an error. Messages written by 2.6 load with the same result, except some graphs that cycle through a tuple, where hooks may run later or decoding may raise MSCDecodeError instead of running them on incomplete data; see the changelog.
  • datetime and time values with fold=1 or ZoneInfo timezones encode additive metadata (|fold=1, |tz=<key>) that requires 2.7+ readers; values with fold=0 and without ZoneInfo remain wire-identical to 2.6.
  • Forged v2 headers setting reserved flag bits or both CRC and HMAC (0x03), _OBJ states with non-str keys, and _PATH values with embedded NUL bytes now fail closed with MSCDecodeError.
  • dump() now writes incrementally in bounded chunks with on-the-fly CRC32 / HMAC-SHA256 calculation, and validates options and file.write upfront before emitting any bytes.

Upgrading to 2.6

  • Readers continue to accept supported v1/v2 messages, subject to authentication and resource limits. Wire v2 remains the writer's version.
  • New field-and-slot dataclass states and bfloat16 metadata require 2.6 readers. Upgrade consumers before writing those forms. Field-only frozen slotted dataclasses keep their existing list state representation.
  • Primitive-backed Enums now retain their registered type. Older messages that stored them as scalars cannot recover the original Enum class.
  • Invalid Enum values produce bounded builtin diagnostics. Stored members and registered _missing_ hooks are used for resolution; custom Enum metaclass __call__ is not a deserialization hook.
  • The new hash work budget may reject large legitimate hashed graphs; choose an explicit budget after measuring your workload. PyTorch extras now require 2.8+.

See the changelog for the complete release history.

Development

python -m pip install -e ".[test]"
python -m pytest -q
python tests/security_audit.py

Install .[all,test] to exercise the optional array and tensor tests. The CI configuration targets Python 3.9–3.14 on Linux and Windows, with separate base and optional dependency jobs. The suite includes mutation, authentication, resource-limit and object graph regressions. Passing tests does not establish absence of other defects.

Security policy · License

Metadata

Release files for mscs 2.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mscs 2.7.0
File Size Uploaded Provenance Actions
mscs-2.7.0.tar.gz 152.4 kB Without provenance Details for mscs-2.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mscs 2.7.0
File Interpreter ABI Platform Actions
mscs-2.7.0-py3-none-any.whl Python 3 none any Details for mscs-2.7.0-py3-none-any.whl

Total release size: 192.9 kB

Release files / mscs-2.7.0.tar.gz

Download URL mscs-2.7.0.tar.gz
Size 152.4 kB
Tags Source
SHA-256 checksum
How to use checksums
21d05d7432578282ec6867b3e5281173d33ef2784d526dc558d04aeb7559232e
BLAKE2b-256 checksum
How to use checksums
8c28e0e46735d127923fa0f561e3bd3d0e03336d64af816bb6e4bdbea4f64124
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / mscs-2.7.0-py3-none-any.whl

Download URL mscs-2.7.0-py3-none-any.whl
Size 40.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3755e415ce7d51ff87d86ebf8037afe41b04fde9ce9d388b2a435c9ad50cc54c
BLAKE2b-256 checksum
How to use checksums
378aec93208eb9c36fccf1574677341b4a06cd23f1605f5fe56cd1175e4da4d1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for mscs 2.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page