Skip to main content

A compact, high-performance persistent record store with zero-copy batch gathering and transparent per-record compression, designed for single-machine AI training and serving pipelines

Project description

Loaderx

A compact, high-performance persistent record store with zero-copy batch gathering and transparent per-record compression, designed for single-machine AI training and serving pipelines

pip install loaderx

Wheels are published for Linux (glibc ≥ 2.17 and musl, x86-64 and arm64), macOS (≥ 11.0, Intel and Apple Silicon) and Windows (x64 and arm64). The bindings use cffi in ABI mode, so nothing links against the CPython ABI and one wheel per platform serves every supported Python.

Design Philosophy

loaderx is built around several core principles:

  1. A pragmatic approach that prioritizes minimal memory overhead and minimal dependencies.
  2. A strong focus on single-machine training workflows.
  3. We implement based on NumPy semantics, persisted through the Zrecord storage runtime.
  4. An immortal (endless) step-based data loader, rather than the traditional epoch-based design—better aligned with modern ML training practices.
  5. Dense and ragged are separate contracts, and the loader serves both. zrecord still speaks one language underneath — records are packed byte ranges located by offsets, and every read/write is a batch operation where the batch size 1 is the degenerate case. But the Python layer does not force equal length to be a special case of variable length: :class:DenseDataset reads fixed-shape records with the shape inferred straight from the schema and no per-record metadata, while :class:RaggedDataset reads variable-length records into a list. Two kinds, one store engine — a dense stream stacks into one array per batch, a ragged one comes back as a list, and neither is padded.

Quick Start

from loaderx.converter import from_numpy
from loaderx.dataset import DenseDataset
from loaderx.dataloader import DataLoader

from_numpy('train_data', np.load('data.npy', mmap_mode='r'))
from_numpy('train_label', np.load('label.npy', mmap_mode='r'))

loader = DataLoader({'data': DenseDataset('train_data'), 'label': DenseDataset('train_label')},
                    transform=lambda batch: batch)

for i, batch in enumerate(loader):
    if i >= 256:
        break

print(batch['data'].shape)
print(batch['label'].shape)

A batch is a dict {name: values}: each value is the stacked (batch_size, *item_shape) array for that stream. Every stream is gathered at the same indices, so record i lines up across them. The transform callback is the collate step — reshape, cast, stack — where values is the plain dense batch ready for the model.

Converting a NumPy tensor

import numpy as np
from loaderx.converter import from_numpy
from loaderx.dataset import DenseDataset

from_numpy('train_data', np.load('data.npy', mmap_mode='r'))
from_numpy('train_label', np.load('label.npy', mmap_mode='r'))

# many small, similar records compress far better against a trained dictionary:
from_numpy('train_data', images, codec='zstd_dict')

One record per slice along axis 0; a 1-D array (the usual shape of a label set) becomes a dataset of scalars. The conversion streams in bounded chunks, so an mmapped array is never fully materialized. Open the result with :class:DenseDataset:

ds = DenseDataset('train_data')

The store carries a single schema.msgpack recording the kind ("dense" or "ragged"), the per-sample dtype, and the shape contract — one item_shape for a dense store, one shape per record for a ragged store. That is the only loaderx-level metadata. Everything beneath it is plain Zrecord, reachable through loaderx.zrecord.Zrecord when you want raw byte records (ragged samples, pre-encoded images) instead of tensors.

Records

One store engine, two kinds of view. from_numpy writes a dense store where every record is exactly one row of the recorded item_shape; reads are fixed-stride gathers and the batch shape follows from the schema, so no per-record metadata is touched:

import numpy as np
from loaderx.converter import from_numpy
from loaderx.dataset import DenseDataset

from_numpy('data', np.arange(64, dtype=np.float32).reshape(8, 2, 4))
ds = DenseDataset('data')
ds[[0, 5, 2]]                       # (3, 2, 4) — shape straight from the schema

from_iterator writes a ragged store of variable-length records. It is a separate contract: :class:RaggedDataset hands back a list of arrays, so a loader never has to carry row_splits around. dtype is unified and explicit; each record keeps its own shape, recorded per record as it is written and restored exactly on read — so records may differ in shape arbitrarily, and nothing is ever inferred from the source (an iterator can't tell you what its later records look like). Densifying a list into a dense batch is the model's call — a plain numpy loop, wherever you need it:

from loaderx.converter import from_iterator
from loaderx.dataset import RaggedDataset

seqs = [np.arange(L, dtype=np.int32) for L in (3, 1, 4, 1, 5)]
from_iterator('tokens', seqs, np.int32)   # dtype explicit; each record keeps its shape
rs = RaggedDataset('tokens')

records = rs[[0, 2, 4]]                # list of ndarray — one per record, exact shapes
lengths = np.array([len(r) for r in records])
padded = np.zeros((len(records), lengths.max()), dtype=records[0].dtype)
for i, r in enumerate(records):
    padded[i, :len(r)] = r             # (B, max_len) — your policy, your loop

A DataLoader works with dense streams, so collation is just the transform — a batch dict in, a batch dict out:

def collate(batch):
    return {'input_ids': batch['tokens'], 'label': batch['label']}

loader = DataLoader({'tokens': dense_tokens, 'label': labelset}, batch_size=32,
                    transform=collate)

Writable datasets

The dataset classes are the general user-space scheme over zrecord: they are read-write, and append is explicit — one container of records, one batch, one native call. Nothing is buffered, inferred, or compressed for you.

from loaderx.dataset import DenseDataset, RaggedDataset

ds = DenseDataset('mnist/x', dtype=np.uint8, item_shape=(28, 28))  # schema written now
ds.append(images[i:i + 1024])        # (B, 28, 28) → one batch, returns first index
ds.append(single_image[None])        # one sample is batch_size 1 — add the axis yourself
ds[:4]                               # read path is unchanged

tok = RaggedDataset('tokens', dtype=np.int32)     # each record keeps its own shape
tok.append([seq_a, seq_b, seq_c])    # list in, list out — `tok[[0, 2]]` returns a list

The schema is declared at construction and written to schema.msgpack immediately; append validates every record against it and errors loudly. The dictionary is the one thing kept out of append: train_dict is explicit and separate, and a zstd_dict store refuses to append until it is called.

The store's maintenance pass-throughs are on the same object, normalized like reads (scalar, slice, array, bool mask):

ds.delete(np.arange(0, len(ds), 2))   # swap-last: index space stays dense, survivors reindex
ds.stats()                            # {'records', 'live_bytes', 'chunk_bytes', 'reclaimable'}
ds.compact()                          # reclaim the deleted bytes, in place — offline only

Deletion and compaction move records, so a multi-stream index you keep yourself must tolerate it — the guarantee is only that the live records are exactly 0..len(ds).

Codec notes

"zstd" compresses each record independently with plain zstd (level 3). Use it for general-purpose compression — it is fast and the default.

"zstd_dict" trains a shared dictionary on a sample of the data before writing any record, then compresses every record against it at level 19. The dictionary captures structure shared across records that per-record compression cannot see — a large win for many small, similar records (image tiles, token sequences).

The dictionary's cost is a cache footprint: every record's decompression references the shared dictionary window, so a larger dictionary means more cache misses on gather — the path a loader pays forever. dict_size therefore offers named tiers (loaderx.dataset.DICT_TIERS) trading ratio against gather throughput:

tier size tradeoff
"small" 32 KiB fastest gather and write; ratio barely above zstd
"balanced" 128 KiB default — most of the ratio at ~2x the gather speed of "max"
"max" 1 MiB best ratio; slowest gather and write

Pass an explicit byte count instead (up to 1 MiB) to pick anything in between. On this box's 12 KiB sample, "balanced" gathers ~3660 MiB/s at 1.17x against "max"'s ~2400 MiB/s at 1.34x — for a loader the throughput is the hot path, for archival the ratio is.

"zstd_dict" records can only be read from a store that has the dictionary (dict.zr). The dictionary is loaded on open and shared, lock-free, across all reader threads.

A dictionary must train on the settled, complete data — so the streaming path (from_iterator) refuses "zstd_dict". Two routes train it correctly, both on the full dataset: from_numpy samples a strided slice of the whole array before writing, and recode rewrites an existing store's codec once the data is final:

from loaderx.converter import from_iterator, recode

# data still arriving — stream it as plain zstd
from_iterator('tokens', token_generator, np.int32)

# preprocessing complete, content final — settle it into a dictionary
recode('tokens', 'tokens_dict', codec='zstd_dict')

recode is a general store-to-store codec rewrite (raw/zstd/ zstd_dict in any direction): records are copied in ascending order, so a multi-stream dataset recoded together stays index-aligned, and memory is bounded by the dictionary sample and chunk_bytes.

Important: Do not use "zstd_dict" while data is still changing (through deletes or compaction below the Python layer). The dictionary captures a snapshot of the data; training it before the data settles wastes compression. Train the dictionary once preprocessing is complete and the content is final.

Multi-stream datasets (MSDataset)

A zrecord store is one stream; a training sample is usually several streams (skeleton + label + id, tokens + label, ...). A multi-stream dataset is just a directory whose immediate children are stores. MSDataset wraps them and guarantees the one thing that matters: index alignment — record i lines up across every stream, append writes every stream at the same indices, delete removes the same indices from every stream, so alignment survives. No new storage format, no manifest, no bundle-level batch API.

from loaderx.converter import from_numpy, from_iterator
from loaderx.dataset import MSDataset
from loaderx.dataloader import DataLoader

root = "xsub/train"
from_numpy(root + "/joint", joint)     # the streams are ordinary zrecord stores
from_numpy(root + "/label", label)
from_iterator(root + "/token", iter(seqs), np.int32)

ds = MSDataset(root)                   # wrap + verify they hold the same count
ds["joint"][[0, 5, 2]]                 # the stream's own index forms apply
ds.append({"joint": b, "label": l})    # same batch size, all streams, once
ds.delete([0, 5])                      # same indices, all streams, still aligned

loader = DataLoader(ds.streams, batch_size=256)   # hand the streams to a loader
batch = next(loader)                      # {name: values}, index-aligned

Equal-length and variable-length are both just stores — DenseDataset (one fixed-shape record per sample) and RaggedDataset (variable row count per record). The loader does not interpret either: it fetches by index and packs a dict, so a dense stream's batch value is the stacked (B, *item_shape) array and a ragged stream's is a list of per-record arrays. No padding is imposed — densify to a fixed shape however the model needs (a plain numpy loop), or reshape/stack in the transform collate.

Integrating with JAX/Flax

For practical integration examples, please refer to the Data2Latent repository

Benchmarks

scripts/bench.py measures zrecord and loaderx against the alternatives in the index sampler, the record store, and the full data loader — each through the binding a client actually uses, so cffi, the GIL and the NumPy allocation are all inside the timings. One run is enough: this is a qualitative horizontal comparison, and the defaults are sized so python3 scripts/bench.py all — which prints this machine block first — finishes in under half a minute. Warm page cache.

Machine — one box, inside a container on a personal laptop (AMD Strix Point APU, 12 cores / 24 threads):

machine value
CPU AMD Ryzen AI 9 HX PRO 370 w/ Radeon 890M, 1 socket, 12 cores / 24 threads
frequency 605–5158 MHz
caches L1d 576 KiB, L1i 384 KiB, L2 12 MiB, L3 24 MiB
NUMA 1 node
memory 31 GiB (not limited by cgroup)
OS Debian GNU/Linux forky/sid, kernel 7.1.3+deb13-amd64
python 3.14.6, numpy 2.5.1

The container sees all 24 threads and has no CPU quota. The benchmark runs on the ordinary page cache.

1. Sampler — index generation on its own, IID (with replacement), 1M index space, against NumPy's modern API. The µs-scale figures fluctuate with box load; the stable signal is the ~2x margin, widest at the smallest batches.

sampler batch per batch vs default_rng
numpy default_rng 256 5.7 µs 1.00x
zsampler 256 1.7 µs 3.32x
numpy default_rng 1024 4.4 µs 1.00x
zsampler 1024 2.3 µs 1.89x
numpy default_rng 8192 18.6 µs 1.00x
zsampler 8192 9.5 µs 1.97x

2. Store — Zrecord against the alternatives: random batch gather, 10000 records, batch 256, structured (mildly compressible) data. A single 12 KiB sample is the horizontal comparison; other record sizes are a --shape away. Two backends stay out of the default because they would dominate the runtime without moving the comparison — they remain reachable through --only: arrayrecord (no usable wheel here, and one record per Python call) and hdf5-gzip (the same driver as hdf5 plus a codec axis, ~180 MiB/s gather vs hdf5's ~430).

Small records — 12 KiB per record, 3 MiB per batch:

store write gather on disk ratio
zrecord-zstd 524 MiB/s 10668 MiB/s 108 MiB 1.08x
zrecord-zstdict 16 MiB/s 3743 MiB/s 100 MiB 1.17x
zrecord-raw 729 MiB/s 21412 MiB/s 117 MiB 1.00x
npy-mmap 2616 MiB/s 12063 MiB/s 117 MiB 1.00x
hdf5 1109 MiB/s 436 MiB/s 118 MiB 0.99x
blosc2 31 MiB/s 434 MiB/s 108 MiB 1.09x
tensorstore 460 MiB/s 87 MiB/s 107 MiB 1.09x

3. Loader — the full input pipeline end to end (sample, fetch, collate, hand over a batch), same workload, 4 workers. (grain stays out of the default: it needs JAX, its build writes ArrayRecord one sample at a time — tens of seconds for this workload — and it lands ~50 batches/s, an order of magnitude below the rest. --only grain reaches it when installed.)

loader batches/s
loaderx 4115.5
loaderx-raw 4833.8
torch 770.7

Free-threaded Python. loaderx targets free-threaded builds (no GIL), and the key sections are also measured on 3.14t — the question is whether anything gains when nothing is GIL-limited. These are opt-in runs (a second interpreter and --transform augment); they are not part of the default all:

  • Sampler — zsampler draws ~1.9–2x faster than free-threaded numpy, the same margin as on the GIL build: a batch is one Zig call either way.

  • Store — the free-threaded numbers track the GIL table within ~10%. zrecord-raw gathers ~19.4–21.4 GiB/s on both (still ~1.7x npy-mmap), zrecord-zstd ~9.4–10.7 GiB/s. Notably, the alternatives do not gain from the build: blosc2's free-threaded wheel re-enables the GIL to load its extension, so it runs exactly as on the GIL build. Random gather, 12 KiB records:

    store CPython 3.14 (GIL) free-threaded 3.14t
    zrecord-raw 21412 MiB/s 19374 MiB/s
    zrecord-zstd 10668 MiB/s 9399 MiB/s
    npy-mmap 12063 MiB/s 10399 MiB/s
    hdf5 436 MiB/s 307 MiB/s
    blosc2 434 MiB/s 419 MiB/s
    tensorstore 87 MiB/s 86 MiB/s
  • Loader, identity — unchanged, ~4100–6000 batches/s on both interpreters.

  • Loader, CPU-heavy transform — the one place the free-threaded build matters. A transform runs on the prefetch threads, so the GIL serializes it on standard CPython — the case where worker processes win, and the reason for the free-threaded build. --transform augment (a Python-bound per-sample loop), 4 workers, loaderx vs torch (which has no free-threaded wheel, so its row is the GIL build's worker processes):

    loader CPython 3.14 (GIL) free-threaded 3.14t
    loaderx 128.9 687.9 batches/s
    loaderx-raw 127.9 727.2 batches/s
    torch 408.7 n/a

    Under the GIL, loaderx's prefetch threads serialize the transform and fall to ~1/3 of torch's worker processes; free-threaded, they parallelize and loaderx reaches ~1.7x torch while keeping the zero-copy, IPC-free path.

Conclusion — why the numbers look like this.

Every hot path is one native call. Zsampler draws a whole batch of indices, zrecord gathers a whole batch and decompresses it, in a single cffi call into Zig with the GIL released and the batch copied straight into its destination buffer. The contenders do the same work one record at a time from Python. That one fact runs through all three tables: the sampler's margin is widest at the smallest batches (a batch costs one call either way, so the per-index work is what divides them), and the store gather column is where one-record-per-call costs the most. The speedup is not bought with distribution shortcuts: the IID draw is unbiased like NumPy's (Lemire with rejection, so uniformity costs nothing over a real index space).

The layout matches what a training loader does. zrecord is built for random record access — the meta table is mmap'd, any record is found in O(1), a dense store gathers at a fixed stride. Array stores are built for contiguous scans, so a scattered batch — exactly what a loader reads — fights their layout. That is why uncompressed .npy, which does no per-record work at all, still loses to zrecord-raw on gather.

Compression is in the kernel, and there is one codec. zrecord-zstd is not "storage plus a codec": the layout, the multi-core decompress and the GIL-free copy are one path, so turning compression on costs part of a margin, not an order of magnitude — ~10.7 GiB/s here, one to two orders of magnitude ahead of the other compressed stores (87–434 MiB/s) at the same ~1.1x ratio. The modest ratio is the data, not the format: these samples are barely compressible, and on a smooth image set plain zstd reaches 7.6x and the dictionary (at the "max" tier) 16.5x.

The loader gap is architecture, not storage. loaderx uses threads and never ends an epoch, so a step pays no IPC and never waits on an epoch boundary; torch restarts per epoch with worker processes. That is most of the ~5–6x end to end. Storage also differs per loader — each reads from what it was built for — so the loader table is a different comparison than the store table, not a rerun of it. The one crack in the thread model is a CPU-heavy transform, which the GIL serializes — that is exactly what free-threaded Python removes, so loaderx is developed and benchmarked against free-threaded builds first.

What these numbers do not claim. Everything runs with a warm page cache: this measures the access path, not cold storage or disk. on disk is allocated blocks, so zrecord's sparse preallocation is not charged to it while TensorStore's sharding is; both are layout, not compression. Writing is a one-time cost zrecord does not chase. This is a single qualitative pass — the µs-scale sampler timings and the loader batches/s fluctuate with box load (on these 12 cores the compressed loader trails the raw one by ~25–30%), so treat the absolute numbers as ballpark and the cross-backend margins as the signal.

Real-data verification: NTU RGB-D skeletons

The tables above are synthetic workloads. As a ground-truth check, loaderx was run end to end on NTU RGB-D skeleton data — 114,480 raw .skeleton files, 120 action classes, 25 joints — processed into the ST-GCN N C T V M layout (per-sample (3, 300, 25, 2) float32) for the xsub/xview protocols. The .npy outputs of the standard preprocessing pipeline were treated as ground truth; every number below comes from a machine identical to the Benchmarks box.

Correctness — the read path is bit-exact against the ground truth:

  • Full scan of all 228,356 records (joint float32 + label int64, all four splits) through DenseDataset: byte-for-byte identical to the reference npy.
  • A DataLoader over joint + label + an index stream, run under all three sampler modes (sequential, iid, cyclic): every received batch is bit-exact to the ground truth at its own declared indices, and the streams stay index-aligned.
  • Sampler semantics hold on real index spaces: sequential walks in order, cyclic draws a full cycle without replacement, iid is deterministic per seed.

Storage — zstd on this data:

store on disk ratio
npy (raw float32) 6.4 GB 1.00x
zrecord raw 6.86 GB 1.00x
zrecord zstd 0.79 GB 8.66x
zrecord zstd_dict 0.75 GB 9.13x

Sizes above are for one split (xview/val, 38,132 records); across all four splits the zstd joint stores total 4.97 GB against 41 GB of raw npy (~8x).

Throughput (180 KB per record, warm page cache, 12 physical cores):

path throughput
random-batch gather, zstd store 4.1–4.5 GiB/s
same, npy-mmap fancy indexing 0.6–1.3 GiB/s
DataLoader, 4 prefetch threads 5.7–6.6 GiB/s (123–144 batches/s)

zstd decompression reads ~8x fewer bytes than raw storage, so the compressed store gathers faster than the raw one (zstd 4587 MiB/s vs raw 1792 MiB/s on the same split).

The npy intermediate is optional. from_numpy is chunked append under the hood, so the whole npy staging step can be skipped: parse the skeleton files in parallel and feed DenseDataset.append the fixed-shape chunks directly. This writes the store in one pass (no npy, no second read), and the resulting store is byte-for-byte the same size as the from_numpy equivalent — verified record by record against the npy ground truth.

Current Limitations

  • Single-host only; multi-host training is not supported.
  • A single sample must be at most 1 MiB, and a store holds at most 2^24 (16777216) records.
  • Metadata is mapped and used in place, so a store carries the host's byte order and is not portable to a machine of the opposite endianness. Every published platform is little-endian, so this only matters if you build for one yourself.

Build

zig build                       # host shared objects, into loaderx/lib/
zig build test                  # Zrecord suite, in both Debug and ReleaseFast
python3 tests/test_loaderx.py   # Python layer, against whichever build is importable
python3 scripts/bench.py        # throughput, against other stores

The Zig side is tested for behaviour only; throughput is measured from Python, through the binding a client actually uses. scripts/bench.py runs in three layers (sampler, store, loader, or all) and skips contenders that are not installed. See Benchmarks.

Publishing

Zig cross-compiles every target from one machine, so releases need no CI matrix:

zig build dist                    # every platform, into zig-out/dist/<wheel tag>/
python3 scripts/build_wheels.py   # one wheel per platform, plus the sdist

The dist directories are named after their Python wheel platform tag, so the tag mapping lives in exactly one place (dist_targets in build.zig). glibc and macOS minimums are pinned in the target triple, which is what makes manylinux_2_17 and macosx_11_0 honest rather than aspirational. Each wheel is checked after packing: it must carry this platform's libraries and no others.

The sdist ships sources only. Installing from it runs zig build through setup.py, so it needs the Zig compiler; wheel users never hit that path.


Zsampler

Index Generator: a high-performance sampler implemented in Zig. Every mode is a pure function of (seed, step), so a run resumes exactly by seeking to a step — there is no epoch to track, in keeping with the endless step-based loader.

  1. Sequential — traverse the index space in order through a fixed-size sliding window, treating the space as a circular queue so the tail never truncates.
  2. IID — draw each index uniformly at random with replacement. Unbiased (Lemire with rejection), matching NumPy. Simplest, but coverage is uneven over any short run.
  3. Cyclic — without replacement, round-robin. Each cycle traverses a fresh permutation of the whole index space, so within a cycle every record appears exactly once and no batch repeats an index — coverage is even by construction, which keeps how often each sample is seen uniform. The permutation is a stateless bijection (a small Feistel network over the index space, brought into range by cycle-walking), so a million-record shuffle materializes nothing the size of the dataset and reshuffling each cycle is free. Every batch is exactly batch_size: an endless step-based loader has no final partial batch to special-case, so when batch_size does not divide the length the cycle's remainder is dropped — a different remainder each cycle, since the permutation changes, so every record is still reached over time.

Zrecord

A record-based data runtime, focused on delivering extreme throughput and low latency.

  1. Zrecord is an unordered physical store made of N records. Records are independent and carry no ordering, so every index and slice operation is equivalent to a gather.
  2. Zrecord hands the client a dense index space: the live records are always exactly 0..N. Deletion preserves that by swapping the tail into the hole, which means an index is stable only until something is deleted. A multi-stream dataset is purely a client-side notion; the client keeps its own stream index table pointing at records.
  3. Zrecord returns byte arrays. Type interpretation is the client's job.
  4. The IO model (append | read | delete) is batch-oriented and shape-agnostic. A record is a packed byte range located by an offset; there is no notion of fixed vs variable length, and a single-record operation is just the batch_size == 1 case. Equal length and single records are special cases, not parallel code paths.
  5. Zrecord owns its memory internally — allocation and release are explicit.
  6. Each record is compressed and decompressed independently:
| tag   |  name     | algorithm                              |
|-------|-----------|----------------------------------------|
|   0   |  raw      | none                                   |
|   1   |  zstd     | zstd (plain, level 3)                  |
|   2   |  zstdict  | zstd with a trained dictionary (level 19) |
  1. Compression is transparent to the client:
    • Compression runs concurrently across all cores. A record that fails to shrink is stored raw automatically, so reading never costs more than the data itself.
    • Decompression writes straight into the caller's destination memory (gather), with no intermediate buffer and no extra copy.
    • zstd is the one transparent codec — faster than Deflate at both ends and a better ratio, so there is no reason to carry a second. It is vendored C, built for every platform by Zig, so the one-wheel-per-platform story is unchanged.
    • zstd_dict additionally trains one dictionary on a sample of the data (stored as dict.zr) and compresses every record against it. Because each record is still independent, random access is unchanged — but the dictionary carries the structure shared across records, which per-record compression cannot see. On many small, similar records (image tiles, token sequences) this is a large win: a smooth-image set that plain zstd takes to 7.6x compresses 16.5x with a large dictionary. The dictionary is loaded once on open and shared, lock-free, across all reader threads. The dictionary size is chosen from the DICT_TIERS presets (see Codec notes).
    • Records stored with zstd_dict are explicitly tagged; they cannot be read by a store that lacks the dictionary. Plain zstd records never use a dictionary even if one is present.

Persistence format

Zrecord storage is metadata plus chunked data:

zrecord/
  ├── meta.zr
  ├── 0.zr
  └── 1.zr

Metadata (meta.zr)

meta.zr is used as the values it holds, not decoded into them. Both structs below are extern, 16 bytes, and naturally aligned; an mmap is page aligned, so the header is a *Header and the record table is a []RecordLoc. Looking up a record is table[idx], and there is no serializer anywhere in the code.

The fields are deliberately wider than the limits need — chunk_id is a u16 for 4096 chunks, the lengths are u32 for a 1 MiB cap. Bit-packing them would save 5 bytes per record and cost a hand-written codec on the hottest lookup path. The slack buys a machine-shaped array; it is worth it.

1. Header — 16 bytes of global state.

  • magic (ZREC) and version are ordinary fields, so opening a directory that is not a Zrecord store fails immediately instead of decoding garbage.
  • length is the total number of records | tail_chunk/tail_offset mark the last write position.
  • There is no chunk count. Chunks are created in order and the frontier is always in the last one, so the store holds exactly chunks 0..=tail_chunk — a count would be a second copy of that fact to keep in sync.
const Header = extern struct {
    magic: [4]u8, version: u16,
    tail_chunk: u16, tail_offset: u32,
    length: u32,
};

2. Record table — 16 bytes per entry, indexed directly. Mapping an index to a physical address is what makes random access efficient.

  • chunk_id is the containing chunk | offset is the position within it | phys_length/logic_length are the stored and original sizes | compress is the algorithm.
const Codec = enum(u8) { raw = 0, zstd = 1, zstdict = 2, _ };
const RecordLoc = extern struct {
    offset: u32, phys_length: u32, logic_length: u32,
    chunk_id: u16, compress: Codec, _reserved: u8,
};

There is no liveness flag. Every entry below length is live, because deletion swaps the tail into the hole rather than tombstoning.

3. Maximum length. Running out of space is effectively impossible, so the metadata is sized statically at the maximum.

  • Current design: up to 2^12 (4096) chunks, 2^32 (4 GiB) per chunk, 2^20 (1 MiB) per record.
  • Derivation: N = chunks × 2^32 (chunk size) / 2^20 (max record size) ⇒ a maximum length of 2^24 (16777216). Equality here is the point: the store can never run out of chunks before it runs out of record slots, which is what lets the table be sized statically. It is a compile-time assertion.
  • meta.zr is a fixed 16 + 2^24 × 16 bytes (256 MiB). It is sparse — a store with one record allocates 4 KiB of it — and the mapping does not prefault.

Chunk data (x.zr)

Densely packed record data.

Executor

1. Write. Writes are append-only; everything else is offset redirection.

  • Append: compress concurrently → assign physical locations serially → flush concurrently → commit metadata. Data is durable-ordered before the record table, and the table before length, so a crash truncates rather than corrupts. A record never straddles two chunks; one that would not fit rolls over to a fresh chunk.
  • Delete: swap the last table entry into the deleted slot and drop the length by one. A batch is applied in descending index order, so each swap pulls from a slot no later target refers to. The index space stays dense — which is what the sampler needs, since it draws uniformly from 0..N and would otherwise keep hitting holes. The deleted record's bytes become garbage.

2. Read. Fill the destination memory concurrently, in place from the Python side (executed on async threads).

  • Committed records are immutable, so the read path is lock free; length is published to readers through an atomic.
  • Every record is read at the offset its table entry records — the meta table is mmap'd, so random access is one array subscript and one positional read, with no batching assumptions about layout. Compressed records are read into a per-shard staging buffer and decompressed in place into the destination.

3. Concurrency model. Io.Group.async shards work by CPU count, and shards beyond the limit run inline on the calling thread.

  • Shards receive contiguous blocks rather than a strided subset, keeping each worker's reads and writes sequential.
  • Each shard creates one zstd context (ZSTD_CCtx to write, ZSTD_DCtx to read) and reuses it across every record it handles, rather than paying that setup per record. The dictionary (ZSTD_CDict/ZSTD_DDict) is immutable, so all shards share one, lock-free.
  • Decompression writes straight into the caller's destination buffer, so there is no intermediate copy.

4. Garbage collection. Deletion leaves the record's bytes stranded, so space is reclaimed by an offline compact that rewrites the live records in place.

  • Records are visited in physical order — which after swap-last deletes no longer matches table order — and repacked densely in that same order. A record therefore never moves to a higher address than it already had.
  • Two things follow. Writing a record can never land on the bytes of a record not yet moved, so the rewrite is safe in place with no scratch copy of the store. And each table entry can be updated the instant its record lands, so the store is consistent at every point: an interrupted compaction leaves some records moved and the rest where they were, and re-running finishes the job.
  • Records that are already in the right place are skipped, so a store with a small amount of garbage near the end is cheap to compact.
  • Chunk files past the new frontier are closed and deleted.
  • stats() reports live_bytes against chunk_bytes so callers can decide when it is worth running. Note the difference is an upper bound: a record never straddles a chunk boundary, so up to one record's worth per chunk is slack that compaction cannot remove.

5. File access.

  • Metadata: a 256 MiB file created at init, accessed by mmap thereafter.
  • Chunk data: 4 GiB files created at init, accessed concurrently through readPositionalAll/writePositionalAll.

Concurrency contract. gather and append are safe to call concurrently from many threads. delete and compact mutate the table in ways a lock-free reader would observe half-applied, so they require exclusive access to the store.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

loaderx-1.0.0.tar.gz (584.4 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

loaderx-1.0.0-py3-none-win_arm64.whl (378.1 kB view details)

Uploaded Python 3Windows ARM64

loaderx-1.0.0-py3-none-win_amd64.whl (522.0 kB view details)

Uploaded Python 3Windows x86-64

loaderx-1.0.0-py3-none-musllinux_1_2_x86_64.whl (450.9 kB view details)

Uploaded Python 3musllinux: musl 1.2+ x86-64

loaderx-1.0.0-py3-none-musllinux_1_2_aarch64.whl (379.6 kB view details)

Uploaded Python 3musllinux: musl 1.2+ ARM64

loaderx-1.0.0-py3-none-manylinux_2_17_x86_64.whl (440.4 kB view details)

Uploaded Python 3manylinux: glibc 2.17+ x86-64

loaderx-1.0.0-py3-none-manylinux_2_17_aarch64.whl (370.8 kB view details)

Uploaded Python 3manylinux: glibc 2.17+ ARM64

loaderx-1.0.0-py3-none-macosx_11_0_x86_64.whl (417.8 kB view details)

Uploaded Python 3macOS 11.0+ x86-64

loaderx-1.0.0-py3-none-macosx_11_0_arm64.whl (357.0 kB view details)

Uploaded Python 3macOS 11.0+ ARM64

File details

Details for the file loaderx-1.0.0.tar.gz.

File metadata

  • Download URL: loaderx-1.0.0.tar.gz
  • Upload date:
  • Size: 584.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.6

File hashes

Hashes for loaderx-1.0.0.tar.gz
Algorithm Hash digest
SHA256 b4ae58e8dfe8e4c2034a736081199526e58ce1fa99337377ed02b83e3ac698e3
MD5 e1db2662b4f619780ff83c9736b90daf
BLAKE2b-256 4387b01e0a0614030807fb0612d8b0c71d337430f31ecd99df60bd85e4c68072

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-win_arm64.whl.

File metadata

  • Download URL: loaderx-1.0.0-py3-none-win_arm64.whl
  • Upload date:
  • Size: 378.1 kB
  • Tags: Python 3, Windows ARM64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.6

File hashes

Hashes for loaderx-1.0.0-py3-none-win_arm64.whl
Algorithm Hash digest
SHA256 f662c0b239f4b6b8f6ed87f6ec0ee1e233397be3aceff6f75c1307135a1fc649
MD5 c64aa34a828510c1291d6957275c84a1
BLAKE2b-256 485fd4a3e0b6a2db9986410320f3fb465efb3221974255c48d2865a8b07880e0

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-win_amd64.whl.

File metadata

  • Download URL: loaderx-1.0.0-py3-none-win_amd64.whl
  • Upload date:
  • Size: 522.0 kB
  • Tags: Python 3, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.6

File hashes

Hashes for loaderx-1.0.0-py3-none-win_amd64.whl
Algorithm Hash digest
SHA256 9af11805214ef6fe80ef75e90bbaeced938af547a6ea2e362d7431ebb5fdcc58
MD5 425a48db4e66fd3a9c8d6b3b0fe9537a
BLAKE2b-256 431859b9fa76a29238e33df43dfc5734f3f5f4c9df46d3112d2a38d0a3210388

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 a0992ae3eb434919d4417a5d470f6f37fb8e658dc1a61eaedec07158c47a88aa
MD5 52ddfdb6f4e39c5e36e19a23b4535da1
BLAKE2b-256 b39e3b36e5243e3c301367057b8730f76007243977d686db68f84c4a6009c515

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 6d6c43f3c9f9c5d8a280b69da3a30c4983403f8a112a8f4821ea3b31d3717db3
MD5 cfff3614b4ce7ae74391f5ce5dbf0733
BLAKE2b-256 851d8ca19aa1dcc7b83ef001d2871ffbb21026509f7acde02501a1d7eac19fb5

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-manylinux_2_17_x86_64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-manylinux_2_17_x86_64.whl
Algorithm Hash digest
SHA256 3be88b80d0e12bbc58cb134440a25a4876a22944bb34244d29217f31e9198a06
MD5 0a3ff9762319a9809003ebb27031ff4e
BLAKE2b-256 0445840647bf99106fdee7e24e05290061541eb8447d90adca7e55faa2e7db84

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-manylinux_2_17_aarch64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-manylinux_2_17_aarch64.whl
Algorithm Hash digest
SHA256 d673512244d68346bf15f3f3ac6ed5a8b9c67ca81ff6c73b16b803bb23c0186e
MD5 edf328ee684aa3174fa3e40e58b07085
BLAKE2b-256 590afa89e95c4174689d0d5b169d49e344849946d289b40f3a3306684524a31f

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-macosx_11_0_x86_64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-macosx_11_0_x86_64.whl
Algorithm Hash digest
SHA256 b404fbcc0c3f114dd9d1cd774c537503e19d349178bfee189aaaf89f0b8f2f37
MD5 bdaa16fab7ffddbf2205079e24288634
BLAKE2b-256 16006908233a1c8affa5bada61fa3b618cf18fa8fa38fc707d9b32ba2d9d822d

See more details on using hashes here.

File details

Details for the file loaderx-1.0.0-py3-none-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for loaderx-1.0.0-py3-none-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 85ac2d1276b2030a83f7cd26fbcecd06c3641aace49b77bddbad30678bac133d
MD5 05cd125488b275b64fd345e0781b69a0
BLAKE2b-256 6c64809368c35b7473d16f774ad2fb6a37d535c223e5c438c2adc00c946e4afe

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page