loaderx 0.4.1__tar.gz → 0.5.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loaderx-0.5.4/MANIFEST.in +11 -0
- loaderx-0.5.4/PKG-INFO +417 -0
- loaderx-0.5.4/README.md +371 -0
- loaderx-0.5.4/build.zig +113 -0
- loaderx-0.5.4/build.zig.zon +10 -0
- loaderx-0.5.4/loaderx/__init__.py +5 -0
- loaderx-0.5.4/loaderx/_lib.py +45 -0
- loaderx-0.5.4/loaderx/_sampler.py +55 -0
- loaderx-0.5.4/loaderx/_zrecord.py +283 -0
- {loaderx-0.4.1 → loaderx-0.5.4}/loaderx/dataloader.py +24 -4
- loaderx-0.5.4/loaderx/dataset.py +222 -0
- loaderx-0.5.4/loaderx.egg-info/PKG-INFO +417 -0
- {loaderx-0.4.1 → loaderx-0.5.4}/loaderx.egg-info/SOURCES.txt +11 -1
- {loaderx-0.4.1 → loaderx-0.5.4}/loaderx.egg-info/requires.txt +1 -2
- {loaderx-0.4.1 → loaderx-0.5.4}/pyproject.toml +11 -4
- loaderx-0.5.4/scripts/bench.py +919 -0
- loaderx-0.5.4/scripts/build_wheels.py +159 -0
- loaderx-0.5.4/setup.py +67 -0
- loaderx-0.5.4/src/zrecord.zig +1543 -0
- loaderx-0.5.4/src/zsampler.zig +94 -0
- loaderx-0.5.4/tests/test_loaderx.py +301 -0
- loaderx-0.4.1/PKG-INFO +0 -98
- loaderx-0.4.1/README.md +0 -54
- loaderx-0.4.1/loaderx/__init__.py +0 -4
- loaderx-0.4.1/loaderx/_sampler.py +0 -97
- loaderx-0.4.1/loaderx/dataset.py +0 -39
- loaderx-0.4.1/loaderx/lib/libsampler.so +0 -0
- loaderx-0.4.1/loaderx.egg-info/PKG-INFO +0 -98
- {loaderx-0.4.1 → loaderx-0.5.4}/LICENSE +0 -0
- {loaderx-0.4.1 → loaderx-0.5.4}/loaderx.egg-info/dependency_links.txt +0 -0
- {loaderx-0.4.1 → loaderx-0.5.4}/loaderx.egg-info/top_level.txt +0 -0
- {loaderx-0.4.1 → loaderx-0.5.4}/setup.cfg +0 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# The sdist ships sources, not binaries: the shared objects are platform
|
|
2
|
+
# specific and `setup.py` rebuilds them with Zig when they are missing.
|
|
3
|
+
include build.zig
|
|
4
|
+
include build.zig.zon
|
|
5
|
+
include LICENSE
|
|
6
|
+
recursive-include src *.zig
|
|
7
|
+
recursive-include tests *.py
|
|
8
|
+
recursive-include scripts *.py
|
|
9
|
+
|
|
10
|
+
exclude loaderx/lib/lib_here
|
|
11
|
+
recursive-exclude loaderx/lib *.so *.dylib *.dll *.pdb *.lib
|
loaderx-0.5.4/PKG-INFO
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loaderx
|
|
3
|
+
Version: 0.5.4
|
|
4
|
+
Summary: 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
|
|
5
|
+
Author-email: Ben0i0d <ben0i0d@foxmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2025 EOELAB AI Research
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://codeberg.org/eoelab/loaderx
|
|
29
|
+
Project-URL: Documentation, https://codeberg.org/eoelab/loaderx
|
|
30
|
+
Project-URL: Source, https://codeberg.org/eoelab/loaderx
|
|
31
|
+
Project-URL: Bug Tracker, https://codeberg.org/eoelab/loaderx
|
|
32
|
+
Keywords: flax,python,dataloader
|
|
33
|
+
Classifier: Development Status :: 3 - Alpha
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Programming Language :: Python :: 3
|
|
37
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
38
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
39
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
40
|
+
Requires-Python: >=3.10
|
|
41
|
+
Description-Content-Type: text/markdown
|
|
42
|
+
License-File: LICENSE
|
|
43
|
+
Requires-Dist: numpy
|
|
44
|
+
Requires-Dist: cffi
|
|
45
|
+
Dynamic: license-file
|
|
46
|
+
|
|
47
|
+
# Loaderx
|
|
48
|
+
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
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
pip install loaderx
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Wheels are published for Linux (glibc ≥ 2.17 and musl, x86-64 and arm64), macOS
|
|
55
|
+
(≥ 11.0, Intel and Apple Silicon) and Windows (x64 and arm64). The bindings use
|
|
56
|
+
cffi in ABI mode, so nothing links against the CPython ABI and one wheel per
|
|
57
|
+
platform serves every supported Python.
|
|
58
|
+
|
|
59
|
+
## Design Philosophy
|
|
60
|
+
|
|
61
|
+
loaderx is built around several core principles:
|
|
62
|
+
|
|
63
|
+
1. A pragmatic approach that prioritizes minimal memory overhead and minimal dependencies.
|
|
64
|
+
2. A strong focus on single-machine training workflows.
|
|
65
|
+
3. We implement based on NumPy semantics, persisted through the Zrecord storage runtime.
|
|
66
|
+
4. An **immortal (endless) step-based data loader**, rather than the traditional epoch-based design—better aligned with modern ML training practices.
|
|
67
|
+
|
|
68
|
+
## Quick Start
|
|
69
|
+
```python
|
|
70
|
+
from loaderx import Dataset, DataLoader
|
|
71
|
+
|
|
72
|
+
dataset = Dataset('train_data.zr')
|
|
73
|
+
labelset = Dataset('train_label.zr')
|
|
74
|
+
|
|
75
|
+
loader = DataLoader(dataset, labelset)
|
|
76
|
+
|
|
77
|
+
for i, batch in enumerate(loader):
|
|
78
|
+
if i >= 256:
|
|
79
|
+
break
|
|
80
|
+
|
|
81
|
+
print(batch['data'].shape)
|
|
82
|
+
print(batch['label'].shape)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### Converting a NumPy tensor
|
|
86
|
+
```python
|
|
87
|
+
import numpy as np
|
|
88
|
+
from loaderx import Dataset
|
|
89
|
+
|
|
90
|
+
Dataset.write('train_data.zr', np.load('data.npy', mmap_mode='r'))
|
|
91
|
+
Dataset.write('train_label.zr', np.load('label.npy', mmap_mode='r'))
|
|
92
|
+
```
|
|
93
|
+
One record per slice along axis 0; a 1-D array (the usual shape of a label set)
|
|
94
|
+
becomes a dataset of scalars. The conversion streams in bounded chunks, so an
|
|
95
|
+
mmapped array is never fully materialized.
|
|
96
|
+
|
|
97
|
+
`Dataset` keeps a single `schema.json` inside the store recording the per-sample
|
|
98
|
+
dtype and shape — that is the only loaderx-level metadata. Everything beneath it
|
|
99
|
+
is plain Zrecord, reachable through `loaderx.Zrecord` when you want raw byte
|
|
100
|
+
records (ragged samples, pre-encoded images) instead of tensors.
|
|
101
|
+
|
|
102
|
+
### Removing samples
|
|
103
|
+
```python
|
|
104
|
+
ds = Dataset('train_data.zr')
|
|
105
|
+
ds.delete([7, 12, 40]) # len shrinks; survivors stay addressable as 0..len
|
|
106
|
+
ds.compact() # reclaim the freed space on disk
|
|
107
|
+
print(ds.stats()) # {'records': ..., 'live_bytes': ..., 'reclaimable': ...}
|
|
108
|
+
```
|
|
109
|
+
Deletion keeps the index space dense, which is what the sampler needs — but it
|
|
110
|
+
does so by moving the tail into the hole, so surviving samples may change index.
|
|
111
|
+
Do not hold indices across a delete. Both calls require exclusive access; do not
|
|
112
|
+
run them while a `DataLoader` is iterating the dataset.
|
|
113
|
+
|
|
114
|
+
### Integrating with JAX/Flax
|
|
115
|
+
|
|
116
|
+
For practical integration examples, please refer to the **[Data2Latent](https://codeberg.org/eoelab/Data2Latent)** repository
|
|
117
|
+
|
|
118
|
+
## Benchmarks
|
|
119
|
+
|
|
120
|
+
`scripts/bench.py` measures loaderx against the alternatives in three layers —
|
|
121
|
+
the index sampler, the record store, and the full data loader — each through the
|
|
122
|
+
binding a client actually uses, so cffi, the GIL and the NumPy allocation are all
|
|
123
|
+
inside the timings. The numbers below are one run on a 24-core machine, Python
|
|
124
|
+
3.14, warm page cache. Reproduce with `python3 scripts/bench.py all`.
|
|
125
|
+
|
|
126
|
+
**1. Sampler** — index generation on its own, IID (with replacement), 1M index
|
|
127
|
+
space, against both NumPy random APIs.
|
|
128
|
+
|
|
129
|
+
| sampler | batch | per batch | indices | vs default_rng |
|
|
130
|
+
|-------------------|-------|-----------|-----------|----------------|
|
|
131
|
+
| numpy randint | 256 | 5.9 µs | 44 M/s | 0.64x |
|
|
132
|
+
| numpy default_rng | 256 | 3.7 µs | 69 M/s | 1.00x |
|
|
133
|
+
| **zsampler** | 256 | 1.9 µs | 138 M/s | **2.01x** |
|
|
134
|
+
| numpy randint | 1024 | 7.2 µs | 142 M/s | 0.83x |
|
|
135
|
+
| numpy default_rng | 1024 | 6.0 µs | 171 M/s | 1.00x |
|
|
136
|
+
| **zsampler** | 1024 | 3.0 µs | 340 M/s | **1.99x** |
|
|
137
|
+
| numpy randint | 8192 | 25.6 µs | 320 M/s | 0.65x |
|
|
138
|
+
| numpy default_rng | 8192 | 16.6 µs | 493 M/s | 1.00x |
|
|
139
|
+
| **zsampler** | 8192 | 7.8 µs | 1048 M/s | **2.13x** |
|
|
140
|
+
|
|
141
|
+
Zsampler draws indices about 2x faster than NumPy's faster API — more against the
|
|
142
|
+
legacy `randint` most code still calls — and the lead is widest at the small
|
|
143
|
+
batches a loader actually draws, where a batch is one cffi call either way and
|
|
144
|
+
NumPy's vectorised fill has nothing to amortise. The one concession: zsampler's
|
|
145
|
+
IID draw is modulo-biased where NumPy's is not, ~1e-13 over a u64 draw into a
|
|
146
|
+
million-record space, which is below anything training will notice.
|
|
147
|
+
|
|
148
|
+
**2. Store** — random batch gather, 20000 records × 12 KiB `uint8(3,64,64)`,
|
|
149
|
+
batch 256 × 200, structured (mildly compressible) data.
|
|
150
|
+
|
|
151
|
+
| store | write | gather | per batch | on disk | ratio |
|
|
152
|
+
|---------------|------------|-------------|------------|---------|-------|
|
|
153
|
+
| loaderx-flate | 362 MiB/s | 1671 MiB/s | 1.80 ms | 209 MiB | 1.12x |
|
|
154
|
+
| loaderx-raw | 784 MiB/s | 21997 MiB/s | 0.14 ms | 235 MiB | 1.00x |
|
|
155
|
+
| npy-mmap | 3064 MiB/s | 13692 MiB/s | 0.22 ms | 234 MiB | 1.00x |
|
|
156
|
+
| arrayrecord | 374 MiB/s | 847 MiB/s | 3.54 ms | 217 MiB | 1.08x |
|
|
157
|
+
| hdf5 | 1327 MiB/s | 511 MiB/s | 5.87 ms | 236 MiB | 0.99x |
|
|
158
|
+
| hdf5-gzip | 83 MiB/s | 206 MiB/s | 14.57 ms | 211 MiB | 1.11x |
|
|
159
|
+
| lmdb | 677 MiB/s | 5337 MiB/s | 0.56 ms | 313 MiB | 0.75x |
|
|
160
|
+
| lmdb-zlib | 71 MiB/s | 336 MiB/s | 8.93 ms | 235 MiB | 1.00x |
|
|
161
|
+
| blosc2 | 32 MiB/s | 226 MiB/s | 13.27 ms | 216 MiB | 1.09x |
|
|
162
|
+
| zarr | 83 MiB/s | 28 MiB/s | 107.36 ms | 217 MiB | 1.08x |
|
|
163
|
+
| tensorstore | 531 MiB/s | 98 MiB/s | 30.69 ms | 214 MiB | 1.09x |
|
|
164
|
+
|
|
165
|
+
The gather column is what the store is built for. loaderx-raw returns a scattered
|
|
166
|
+
batch faster than everything here, a memory-mapped `.npy` included, because it
|
|
167
|
+
copies straight into the destination across all cores with the GIL released;
|
|
168
|
+
loaderx-flate keeps most of that speed *while* decompressing, and still gathers
|
|
169
|
+
several times faster than any other compressed store (hdf5-gzip, lmdb-zlib,
|
|
170
|
+
blosc2, zarr, tensorstore). The array stores lag on gather because a scattered
|
|
171
|
+
single-record read fights a layout meant for contiguous slabs — which is exactly
|
|
172
|
+
the access pattern a training loader has. Where loaderx does not lead is write: it
|
|
173
|
+
pays compression and its own layout up front, a one-time cost it does not chase.
|
|
174
|
+
Compression is modest (1.12x) only because this data is barely compressible; the
|
|
175
|
+
row's point is that turning it on costs almost nothing on read.
|
|
176
|
+
|
|
177
|
+
The reads are not all single-threaded: loaderx and blosc2 decompress across cores,
|
|
178
|
+
the rest one record at a time. Zarr and TensorStore are sharded so `on disk`
|
|
179
|
+
reflects compression rather than per-file block rounding, and TensorStore is given
|
|
180
|
+
gzip (its zarr3 default is uncompressed). `on disk` is allocated blocks, which is
|
|
181
|
+
why LMDB's preallocated map lands below 1.00x.
|
|
182
|
+
|
|
183
|
+
**3. Loader** — the full input pipeline end to end (sample, fetch, collate, hand
|
|
184
|
+
over a batch), same workload, 4 workers. Each loader reads from what it is built
|
|
185
|
+
for: loaderx from Zrecord, Grain from ArrayRecord, torch from a memory-mapped
|
|
186
|
+
`.npy`, jax-dataloader from an in-memory array.
|
|
187
|
+
|
|
188
|
+
| loader | batches/s | per batch | samples/s | throughput |
|
|
189
|
+
|----------------|-----------|-----------|-----------|-------------|
|
|
190
|
+
| **loaderx** | 724.2 | 1.38 ms | 185,406 | 2173 MiB/s |
|
|
191
|
+
| loaderx-raw | 5271.0 | 0.19 ms | 1,349,378 | 15813 MiB/s |
|
|
192
|
+
| grain | 67.3 | 14.85 ms | 17,240 | 202 MiB/s |
|
|
193
|
+
| torch | 832.2 | 1.20 ms | 213,038 | 2497 MiB/s |
|
|
194
|
+
| jax-dataloader | 3284.6 | 0.30 ms | 840,864 | 9854 MiB/s |
|
|
195
|
+
|
|
196
|
+
End to end, loaderx-raw serves batches several times faster than torch or Grain
|
|
197
|
+
and ahead of jax-dataloader — and it does so from disk-backed storage, where
|
|
198
|
+
jax-dataloader's number is an in-memory ceiling with no storage path at all. The
|
|
199
|
+
default loaderx trades some of that for on-disk compression and still lands in
|
|
200
|
+
torch's range while reading compressed records. loaderx and jax use threads;
|
|
201
|
+
torch and Grain use worker processes that escape the GIL but pay IPC per batch.
|
|
202
|
+
loaderx never ends an epoch, so no step waits on a boundary; the others restart
|
|
203
|
+
per epoch, a cost that is in their numbers as it would be in training.
|
|
204
|
+
|
|
205
|
+
## Current Limitations
|
|
206
|
+
* Single-host only; multi-host training is not supported.
|
|
207
|
+
* A single sample must be at most 1 MiB, and a store holds at most 2^24
|
|
208
|
+
(16777216) records.
|
|
209
|
+
* Metadata is mapped and used in place, so a store carries the host's byte
|
|
210
|
+
order and is not portable to a machine of the opposite endianness. Every
|
|
211
|
+
published platform is little-endian, so this only matters if you build for
|
|
212
|
+
one yourself.
|
|
213
|
+
|
|
214
|
+
## Build
|
|
215
|
+
```
|
|
216
|
+
zig build # host shared objects, into loaderx/lib/
|
|
217
|
+
zig build test # Zrecord suite, in both Debug and ReleaseFast
|
|
218
|
+
python3 tests/test_loaderx.py # Python layer, against whichever build is importable
|
|
219
|
+
python3 scripts/bench.py # throughput, against other stores
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The Zig side is tested for behaviour only; throughput is measured from Python,
|
|
223
|
+
through the binding a client actually uses. `scripts/bench.py` runs in three
|
|
224
|
+
layers (`sampler`, `store`, `loader`, or `all`) and skips contenders that are not
|
|
225
|
+
installed. See [Benchmarks](#benchmarks).
|
|
226
|
+
|
|
227
|
+
### Publishing
|
|
228
|
+
Zig cross-compiles every target from one machine, so releases need no CI matrix:
|
|
229
|
+
|
|
230
|
+
```
|
|
231
|
+
zig build dist # every platform, into zig-out/dist/<wheel tag>/
|
|
232
|
+
python3 scripts/build_wheels.py # one wheel per platform, plus the sdist
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
The dist directories are named after their Python wheel platform tag, so the tag
|
|
236
|
+
mapping lives in exactly one place (`dist_targets` in `build.zig`). glibc and
|
|
237
|
+
macOS minimums are pinned in the target triple, which is what makes
|
|
238
|
+
`manylinux_2_17` and `macosx_11_0` honest rather than aspirational. Each wheel is
|
|
239
|
+
checked after packing: it must carry this platform's libraries and no others.
|
|
240
|
+
|
|
241
|
+
The sdist ships sources only. Installing from it runs `zig build` through
|
|
242
|
+
`setup.py`, so it needs the Zig compiler; wheel users never hit that path.
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
# Zsampler
|
|
247
|
+
Index Generator: a high-performance sampler implemented in Zig
|
|
248
|
+
|
|
249
|
+
1. Sequential generation: indices are produced by traversing the index space in order.
|
|
250
|
+
* Sliding traversal: indices are obtained using a fixed-size sliding window. Note that in this case, the index space is treated as a circular queue to avoid truncation at the tail.
|
|
251
|
+
2. Random generation: indices are sampled randomly from the index space.
|
|
252
|
+
* Global random: a set of samples is drawn randomly from the entire index space.
|
|
253
|
+
|
|
254
|
+
---
|
|
255
|
+
|
|
256
|
+
# Zrecord
|
|
257
|
+
A record-based data runtime, focused on delivering extreme throughput and low latency.
|
|
258
|
+
|
|
259
|
+
1. Zrecord is an unordered physical store made of N records. Records are
|
|
260
|
+
independent and carry no ordering, so every index and slice operation is
|
|
261
|
+
equivalent to a gather.
|
|
262
|
+
2. Zrecord hands the client a dense index space: the live records are always
|
|
263
|
+
exactly `0..N`. Deletion preserves that by swapping the tail into the hole,
|
|
264
|
+
which means an index is stable only until something is deleted. A
|
|
265
|
+
multi-stream dataset is purely a client-side notion; the client keeps its
|
|
266
|
+
own stream index table pointing at records.
|
|
267
|
+
3. Zrecord returns byte arrays. Type interpretation is the client's job.
|
|
268
|
+
4. For performance, the IO model (`append | read | delete`) is batch-oriented;
|
|
269
|
+
a single-record operation is just the `batch_size == 1` case.
|
|
270
|
+
5. Zrecord owns its memory internally — allocation and release are explicit.
|
|
271
|
+
6. Each record is compressed and decompressed independently:
|
|
272
|
+
|
|
273
|
+
```
|
|
274
|
+
| tag | name | algorithm |
|
|
275
|
+
|-------|---------|-----------|
|
|
276
|
+
| 0 | raw | none |
|
|
277
|
+
| 1 | flate | Deflate |
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
7. Compression is transparent to the client:
|
|
281
|
+
* Compression runs concurrently across all cores. A record that fails to
|
|
282
|
+
shrink is stored raw automatically, so reading never costs more than the
|
|
283
|
+
data itself.
|
|
284
|
+
* Decompression writes straight into the caller's destination memory
|
|
285
|
+
(`gather`), with no intermediate buffer and no extra copy.
|
|
286
|
+
|
|
287
|
+
## Persistence format
|
|
288
|
+
Zrecord storage is metadata plus chunked data:
|
|
289
|
+
```
|
|
290
|
+
zrecord/
|
|
291
|
+
├── meta.zr
|
|
292
|
+
├── 0.zr
|
|
293
|
+
└── 1.zr
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
### Metadata (meta.zr)
|
|
297
|
+
|
|
298
|
+
meta.zr is **used as the values it holds, not decoded into them**. Both structs
|
|
299
|
+
below are `extern`, 16 bytes, and naturally aligned; an mmap is page aligned, so
|
|
300
|
+
the header is a `*Header` and the record table is a `[]RecordLoc`. Looking up a
|
|
301
|
+
record is `table[idx]`, and there is no serializer anywhere in the code.
|
|
302
|
+
|
|
303
|
+
The fields are deliberately wider than the limits need — `chunk_id` is a `u16`
|
|
304
|
+
for 4096 chunks, the lengths are `u32` for a 1 MiB cap. Bit-packing them would
|
|
305
|
+
save 5 bytes per record and cost a hand-written codec on the hottest lookup
|
|
306
|
+
path. The slack buys a machine-shaped array; it is worth it.
|
|
307
|
+
|
|
308
|
+
**1. Header** — 16 bytes of global state.
|
|
309
|
+
* `magic` (`ZREC`) and `version` are ordinary fields, so opening a directory
|
|
310
|
+
that is not a Zrecord store fails immediately instead of decoding garbage.
|
|
311
|
+
* `length` is the total number of records | `tail_chunk`/`tail_offset` mark the
|
|
312
|
+
last write position.
|
|
313
|
+
* There is no chunk count. Chunks are created in order and the frontier is
|
|
314
|
+
always in the last one, so the store holds exactly chunks `0..=tail_chunk` —
|
|
315
|
+
a count would be a second copy of that fact to keep in sync.
|
|
316
|
+
|
|
317
|
+
```zig
|
|
318
|
+
const Header = extern struct {
|
|
319
|
+
magic: [4]u8, version: u16,
|
|
320
|
+
tail_chunk: u16, tail_offset: u32,
|
|
321
|
+
length: u32,
|
|
322
|
+
};
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
**2. Record table** — 16 bytes per entry, indexed directly. Mapping an index to
|
|
326
|
+
a physical address is what makes random access efficient.
|
|
327
|
+
* `chunk_id` is the containing chunk | `offset` is the position within it |
|
|
328
|
+
`phys_length`/`logic_length` are the stored and original sizes | `compress` is
|
|
329
|
+
the algorithm.
|
|
330
|
+
|
|
331
|
+
```zig
|
|
332
|
+
const Codec = enum(u8) { raw = 0, flate = 1, _ };
|
|
333
|
+
const RecordLoc = extern struct {
|
|
334
|
+
offset: u32, phys_length: u32, logic_length: u32,
|
|
335
|
+
chunk_id: u16, compress: Codec, _reserved: u8,
|
|
336
|
+
};
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
There is no liveness flag. Every entry below `length` is live, because deletion
|
|
340
|
+
swaps the tail into the hole rather than tombstoning.
|
|
341
|
+
|
|
342
|
+
**3. Maximum length.** Running out of space is effectively impossible, so the
|
|
343
|
+
metadata is sized statically at the maximum.
|
|
344
|
+
* Current design: up to 2^12 (4096) chunks, 2^32 (4 GiB) per chunk, 2^20 (1 MiB)
|
|
345
|
+
per record.
|
|
346
|
+
* Derivation: N = chunks × 2^32 (chunk size) / 2^20 (max record size) ⇒ a
|
|
347
|
+
maximum length of 2^24 (16777216). Equality here is the point: the store can
|
|
348
|
+
never run out of chunks before it runs out of record slots, which is what
|
|
349
|
+
lets the table be sized statically. It is a compile-time assertion.
|
|
350
|
+
* meta.zr is a fixed 16 + 2^24 × 16 bytes (256 MiB). It is sparse — a store
|
|
351
|
+
with one record allocates 4 KiB of it — and the mapping does not prefault.
|
|
352
|
+
|
|
353
|
+
### Chunk data (x.zr)
|
|
354
|
+
Densely packed record data.
|
|
355
|
+
|
|
356
|
+
## Executor
|
|
357
|
+
|
|
358
|
+
**1. Write.** Writes are append-only; everything else is offset redirection.
|
|
359
|
+
* Append: compress concurrently → assign physical locations serially → flush
|
|
360
|
+
concurrently → commit metadata. Data is durable-ordered before the record
|
|
361
|
+
table, and the table before `length`, so a crash truncates rather than
|
|
362
|
+
corrupts. A record never straddles two chunks; one that would not fit rolls
|
|
363
|
+
over to a fresh chunk.
|
|
364
|
+
* Delete: swap the last table entry into the deleted slot and drop the length by
|
|
365
|
+
one. A batch is applied in descending index order, so each swap pulls from a
|
|
366
|
+
slot no later target refers to. The index space stays dense — which is what
|
|
367
|
+
the sampler needs, since it draws uniformly from `0..N` and would otherwise
|
|
368
|
+
keep hitting holes. The deleted record's bytes become garbage.
|
|
369
|
+
|
|
370
|
+
**2. Read.** Fill the destination memory concurrently, in place from the Python
|
|
371
|
+
side (executed on async threads).
|
|
372
|
+
* Committed records are immutable, so the read path is lock free; `length` is
|
|
373
|
+
published to readers through an atomic.
|
|
374
|
+
|
|
375
|
+
**3. Concurrency model.** `Io.Group.async` shards work by CPU count, and shards
|
|
376
|
+
beyond the limit run inline on the calling thread.
|
|
377
|
+
* Shards receive contiguous blocks rather than a strided subset, keeping each
|
|
378
|
+
worker's reads and writes sequential.
|
|
379
|
+
* Each shard reuses one compressor scratch (`flate.Compress` is ~230 KiB — far
|
|
380
|
+
too large to rebuild per record, let alone to place on a task stack).
|
|
381
|
+
* Decompression runs in direct mode: matches are resolved against the bytes
|
|
382
|
+
already written into the destination, so there is no window buffer.
|
|
383
|
+
|
|
384
|
+
**4. Garbage collection.** Deletion leaves the record's bytes stranded, so space
|
|
385
|
+
is reclaimed by an offline `compact` that rewrites the live records in place.
|
|
386
|
+
* Records are visited in *physical* order — which after swap-last deletes no
|
|
387
|
+
longer matches table order — and repacked densely in that same order. A record
|
|
388
|
+
therefore never moves to a higher address than it already had.
|
|
389
|
+
* Two things follow. Writing a record can never land on the bytes of a record
|
|
390
|
+
not yet moved, so the rewrite is safe in place with no scratch copy of the
|
|
391
|
+
store. And each table entry can be updated the instant its record lands, so
|
|
392
|
+
the store is consistent at every point: an interrupted compaction leaves some
|
|
393
|
+
records moved and the rest where they were, and re-running finishes the job.
|
|
394
|
+
* Records that are already in the right place are skipped, so a store with a
|
|
395
|
+
small amount of garbage near the end is cheap to compact.
|
|
396
|
+
* Chunk files past the new frontier are closed and deleted.
|
|
397
|
+
* `stats()` reports `live_bytes` against `chunk_bytes` so callers can decide when
|
|
398
|
+
it is worth running. Note the difference is an upper bound: a record never
|
|
399
|
+
straddles a chunk boundary, so up to one record's worth per chunk is slack
|
|
400
|
+
that compaction cannot remove.
|
|
401
|
+
|
|
402
|
+
**5. File access.**
|
|
403
|
+
* Metadata: a 192 MiB file created at init, accessed by mmap thereafter.
|
|
404
|
+
* Chunk data: 4 GiB files created at init, accessed concurrently through
|
|
405
|
+
`readPositionalAll`/`writePositionalAll`.
|
|
406
|
+
|
|
407
|
+
**Concurrency contract.** `gather` and `append` are safe to call concurrently
|
|
408
|
+
from many threads. `delete` and `compact` mutate the table in ways a lock-free
|
|
409
|
+
reader would observe half-applied, so they require exclusive access to the
|
|
410
|
+
store.
|
|
411
|
+
|
|
412
|
+
## Distributed extension
|
|
413
|
+
**Not implemented yet; architecture noted in advance.**
|
|
414
|
+
|
|
415
|
+
1. A cluster layer is added; a node becomes a shard holding several chunks.
|
|
416
|
+
2. An indirection table maps a global path to a specific node, so the index path
|
|
417
|
+
becomes `idx → indirection[idx] = node, lidx → offset[lidx]`.
|