bitcask-dataset 0.1.0__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.
- bitcask_dataset-0.1.0/PKG-INFO +126 -0
- bitcask_dataset-0.1.0/README.md +111 -0
- bitcask_dataset-0.1.0/pyproject.toml +81 -0
- bitcask_dataset-0.1.0/pyproject.toml.orig +53 -0
- bitcask_dataset-0.1.0/src/bitcask_dataset/__init__.py +3 -0
- bitcask_dataset-0.1.0/src/bitcask_dataset/dataset.py +381 -0
- bitcask_dataset-0.1.0/src/bitcask_dataset/py.typed +0 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitcask-dataset
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small, mmap-backed dataset for keyed byte blobs
|
|
5
|
+
Keywords: dataset,mmap,machine-learning,pytorch
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Classifier: Development Status :: 3 - Alpha
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Dist: lz4>=4.4.5
|
|
12
|
+
Requires-Dist: numpy>=2.1
|
|
13
|
+
Requires-Python: >=3.13
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# bitcask-dataset
|
|
17
|
+
|
|
18
|
+
Basically a disk-backed collection of byte blobs, optionally keyed by bytes. Data is
|
|
19
|
+
append-only, split into shards, LZ4-compressed, and mmap'd when opened.
|
|
20
|
+
|
|
21
|
+
This is mostly for training data where serialization is somebody else's problem.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install bitcask-dataset
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Example
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from bitcask_dataset import BitcaskDataset
|
|
33
|
+
|
|
34
|
+
ds = BitcaskDataset("my-dataset", keyed=True) # creates the directory if needed
|
|
35
|
+
ds.extend([
|
|
36
|
+
(b"image/1", image_bytes),
|
|
37
|
+
(b"image/2", more_image_bytes),
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
value = ds[b"image/1"] # decompressed bytes
|
|
41
|
+
|
|
42
|
+
# insertion order is available too
|
|
43
|
+
value = ds.at(0)
|
|
44
|
+
key = ds.key_at(0)
|
|
45
|
+
|
|
46
|
+
len(ds)
|
|
47
|
+
b"image/1" in ds
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Keys are optional:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
ds = BitcaskDataset("my-keyless-dataset")
|
|
54
|
+
ds.extend([image_bytes, more_image_bytes])
|
|
55
|
+
value = ds.at(0)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Keys and values can be anything with the buffer protocol.
|
|
59
|
+
|
|
60
|
+
## API
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
BitcaskDataset(path, keyed=False, compression="lz4")
|
|
64
|
+
ds.extend(entries, max_shard_size=1 << 30)
|
|
65
|
+
ds[key]
|
|
66
|
+
ds.at(index)
|
|
67
|
+
ds.key_at(index)
|
|
68
|
+
len(ds)
|
|
69
|
+
key in ds
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
A missing or empty path is initialized. An existing non-dataset directory is an
|
|
73
|
+
error.
|
|
74
|
+
|
|
75
|
+
In keyed mode, `extend` takes `(key, value)` pairs and duplicate keys are errors. In
|
|
76
|
+
keyless mode it takes values directly. It only creates new shards; it never adds data
|
|
77
|
+
to an old one. Records aren't split, so a record over `max_shard_size` gets a shard
|
|
78
|
+
to itself.
|
|
79
|
+
|
|
80
|
+
Compressed values come back as `bytes`. Pass `compression=None` to store values
|
|
81
|
+
uncompressed and get zero-copy, read-only `memoryview`s instead. Keys are always
|
|
82
|
+
uncompressed. `at` and `key_at` support negative indexes. Key lookup and `key_at`
|
|
83
|
+
raise `TypeError` in keyless mode.
|
|
84
|
+
|
|
85
|
+
There is no metadata file yet, so remember to use the same `keyed` and `compression`
|
|
86
|
+
arguments every time you open a dataset. The defaults are `keyed=False` and
|
|
87
|
+
`compression="lz4"`. Opening a dataset with the wrong settings may misread it.
|
|
88
|
+
|
|
89
|
+
## Format
|
|
90
|
+
|
|
91
|
+
```text
|
|
92
|
+
my-dataset/
|
|
93
|
+
index.bin
|
|
94
|
+
shards/
|
|
95
|
+
000000.bin
|
|
96
|
+
000001.bin
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The keyed index is little-endian `uint32` pairs:
|
|
100
|
+
|
|
101
|
+
```text
|
|
102
|
+
key_size, value_size, key_size, value_size, ...
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The keyless index is one `uint32` stored-value size per item. Keyed shards are
|
|
106
|
+
`key || value || key || value ...`; keyless shards only contain values. Values are
|
|
107
|
+
independent LZ4 blocks using high-compression mode, with the original size in each
|
|
108
|
+
block. Empty values stay empty. There are no record headers or padding. NumPy does a
|
|
109
|
+
cumsum at startup and works out the shard/offset for each record.
|
|
110
|
+
|
|
111
|
+
Keyed datasets copy keys into a Python dict at startup. Each key and uncompressed
|
|
112
|
+
value is limited to `2**32 - 1` bytes.
|
|
113
|
+
|
|
114
|
+
## Missing stuff
|
|
115
|
+
|
|
116
|
+
No delete, overwrite, compaction, or concurrent writers. Also not
|
|
117
|
+
actually an implementation of the Bitcask paper.
|
|
118
|
+
|
|
119
|
+
## Dev
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
uv sync
|
|
123
|
+
make format
|
|
124
|
+
make lint
|
|
125
|
+
make test
|
|
126
|
+
```
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# bitcask-dataset
|
|
2
|
+
|
|
3
|
+
Basically a disk-backed collection of byte blobs, optionally keyed by bytes. Data is
|
|
4
|
+
append-only, split into shards, LZ4-compressed, and mmap'd when opened.
|
|
5
|
+
|
|
6
|
+
This is mostly for training data where serialization is somebody else's problem.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install bitcask-dataset
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Example
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from bitcask_dataset import BitcaskDataset
|
|
18
|
+
|
|
19
|
+
ds = BitcaskDataset("my-dataset", keyed=True) # creates the directory if needed
|
|
20
|
+
ds.extend([
|
|
21
|
+
(b"image/1", image_bytes),
|
|
22
|
+
(b"image/2", more_image_bytes),
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
value = ds[b"image/1"] # decompressed bytes
|
|
26
|
+
|
|
27
|
+
# insertion order is available too
|
|
28
|
+
value = ds.at(0)
|
|
29
|
+
key = ds.key_at(0)
|
|
30
|
+
|
|
31
|
+
len(ds)
|
|
32
|
+
b"image/1" in ds
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Keys are optional:
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
ds = BitcaskDataset("my-keyless-dataset")
|
|
39
|
+
ds.extend([image_bytes, more_image_bytes])
|
|
40
|
+
value = ds.at(0)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Keys and values can be anything with the buffer protocol.
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
BitcaskDataset(path, keyed=False, compression="lz4")
|
|
49
|
+
ds.extend(entries, max_shard_size=1 << 30)
|
|
50
|
+
ds[key]
|
|
51
|
+
ds.at(index)
|
|
52
|
+
ds.key_at(index)
|
|
53
|
+
len(ds)
|
|
54
|
+
key in ds
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A missing or empty path is initialized. An existing non-dataset directory is an
|
|
58
|
+
error.
|
|
59
|
+
|
|
60
|
+
In keyed mode, `extend` takes `(key, value)` pairs and duplicate keys are errors. In
|
|
61
|
+
keyless mode it takes values directly. It only creates new shards; it never adds data
|
|
62
|
+
to an old one. Records aren't split, so a record over `max_shard_size` gets a shard
|
|
63
|
+
to itself.
|
|
64
|
+
|
|
65
|
+
Compressed values come back as `bytes`. Pass `compression=None` to store values
|
|
66
|
+
uncompressed and get zero-copy, read-only `memoryview`s instead. Keys are always
|
|
67
|
+
uncompressed. `at` and `key_at` support negative indexes. Key lookup and `key_at`
|
|
68
|
+
raise `TypeError` in keyless mode.
|
|
69
|
+
|
|
70
|
+
There is no metadata file yet, so remember to use the same `keyed` and `compression`
|
|
71
|
+
arguments every time you open a dataset. The defaults are `keyed=False` and
|
|
72
|
+
`compression="lz4"`. Opening a dataset with the wrong settings may misread it.
|
|
73
|
+
|
|
74
|
+
## Format
|
|
75
|
+
|
|
76
|
+
```text
|
|
77
|
+
my-dataset/
|
|
78
|
+
index.bin
|
|
79
|
+
shards/
|
|
80
|
+
000000.bin
|
|
81
|
+
000001.bin
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The keyed index is little-endian `uint32` pairs:
|
|
85
|
+
|
|
86
|
+
```text
|
|
87
|
+
key_size, value_size, key_size, value_size, ...
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
The keyless index is one `uint32` stored-value size per item. Keyed shards are
|
|
91
|
+
`key || value || key || value ...`; keyless shards only contain values. Values are
|
|
92
|
+
independent LZ4 blocks using high-compression mode, with the original size in each
|
|
93
|
+
block. Empty values stay empty. There are no record headers or padding. NumPy does a
|
|
94
|
+
cumsum at startup and works out the shard/offset for each record.
|
|
95
|
+
|
|
96
|
+
Keyed datasets copy keys into a Python dict at startup. Each key and uncompressed
|
|
97
|
+
value is limited to `2**32 - 1` bytes.
|
|
98
|
+
|
|
99
|
+
## Missing stuff
|
|
100
|
+
|
|
101
|
+
No delete, overwrite, compaction, or concurrent writers. Also not
|
|
102
|
+
actually an implementation of the Bitcask paper.
|
|
103
|
+
|
|
104
|
+
## Dev
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
uv sync
|
|
108
|
+
make format
|
|
109
|
+
make lint
|
|
110
|
+
make test
|
|
111
|
+
```
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bitcask-dataset"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A small, mmap-backed dataset for keyed byte blobs"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"lz4>=4.4.5",
|
|
9
|
+
"numpy>=2.1",
|
|
10
|
+
]
|
|
11
|
+
license = "BSD-3-Clause"
|
|
12
|
+
keywords = [
|
|
13
|
+
"dataset",
|
|
14
|
+
"mmap",
|
|
15
|
+
"machine-learning",
|
|
16
|
+
"pytorch",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["uv_build>=0.12.0,<0.13.0"]
|
|
27
|
+
build-backend = "uv_build"
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = [
|
|
31
|
+
"mypy>=2.3.0",
|
|
32
|
+
"pytest>=9.1.1",
|
|
33
|
+
"ruff>=0.16.1",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[tool.pytest.ini_options]
|
|
37
|
+
testpaths = ["tests"]
|
|
38
|
+
|
|
39
|
+
[tool.mypy]
|
|
40
|
+
files = [
|
|
41
|
+
"src",
|
|
42
|
+
"tests",
|
|
43
|
+
]
|
|
44
|
+
explicit_package_bases = true
|
|
45
|
+
mypy_path = "src"
|
|
46
|
+
strict = true
|
|
47
|
+
follow_untyped_imports = true
|
|
48
|
+
ignore_missing_imports = true
|
|
49
|
+
python_version = "3.13"
|
|
50
|
+
warn_unreachable = true
|
|
51
|
+
|
|
52
|
+
[tool.ruff]
|
|
53
|
+
indent-width = 4
|
|
54
|
+
line-length = 120
|
|
55
|
+
preview = true
|
|
56
|
+
target-version = "py313"
|
|
57
|
+
|
|
58
|
+
[tool.ruff.lint]
|
|
59
|
+
ignore = [
|
|
60
|
+
"B028",
|
|
61
|
+
"B905",
|
|
62
|
+
"C408",
|
|
63
|
+
"E203",
|
|
64
|
+
"FURB118",
|
|
65
|
+
"SIM102",
|
|
66
|
+
"SIM108",
|
|
67
|
+
]
|
|
68
|
+
preview = true
|
|
69
|
+
select = [
|
|
70
|
+
"B",
|
|
71
|
+
"C4",
|
|
72
|
+
"E",
|
|
73
|
+
"F",
|
|
74
|
+
"FURB",
|
|
75
|
+
"I",
|
|
76
|
+
"PT",
|
|
77
|
+
"Q",
|
|
78
|
+
"SIM",
|
|
79
|
+
"U",
|
|
80
|
+
"YTT",
|
|
81
|
+
]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "bitcask-dataset"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A small, mmap-backed dataset for keyed byte blobs"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.13"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"lz4>=4.4.5",
|
|
9
|
+
"numpy>=2.1",
|
|
10
|
+
]
|
|
11
|
+
license = "BSD-3-Clause"
|
|
12
|
+
keywords = ["dataset", "mmap", "machine-learning", "pytorch"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3.13",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[build-system]
|
|
21
|
+
requires = ["uv_build>=0.12.0,<0.13.0"]
|
|
22
|
+
build-backend = "uv_build"
|
|
23
|
+
|
|
24
|
+
[dependency-groups]
|
|
25
|
+
dev = [
|
|
26
|
+
"mypy>=2.3.0",
|
|
27
|
+
"pytest>=9.1.1",
|
|
28
|
+
"ruff>=0.16.1",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
testpaths = ["tests"]
|
|
33
|
+
|
|
34
|
+
[tool.mypy]
|
|
35
|
+
files = ["src", "tests"]
|
|
36
|
+
explicit_package_bases = true
|
|
37
|
+
mypy_path = "src"
|
|
38
|
+
strict = true
|
|
39
|
+
follow_untyped_imports = true
|
|
40
|
+
ignore_missing_imports = true
|
|
41
|
+
python_version = "3.13"
|
|
42
|
+
warn_unreachable = true
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
indent-width = 4
|
|
46
|
+
line-length = 120
|
|
47
|
+
preview = true
|
|
48
|
+
target-version = "py313"
|
|
49
|
+
|
|
50
|
+
[tool.ruff.lint]
|
|
51
|
+
ignore = ["B028", "B905", "C408", "E203", "FURB118", "SIM102", "SIM108"]
|
|
52
|
+
preview = true
|
|
53
|
+
select = ["B", "C4", "E", "F", "FURB", "I", "PT", "Q", "SIM", "U", "YTT"]
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import mmap
|
|
2
|
+
import os
|
|
3
|
+
import struct
|
|
4
|
+
import tempfile
|
|
5
|
+
from collections.abc import Buffer, Iterable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import BinaryIO, Literal
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import numpy.typing as npt
|
|
11
|
+
from lz4 import block
|
|
12
|
+
|
|
13
|
+
DEFAULT_MAX_SHARD_SIZE = 1 << 30
|
|
14
|
+
MAX_FIELD_SIZE = np.iinfo(np.uint32).max
|
|
15
|
+
INDEX_DTYPE = np.dtype("<u4")
|
|
16
|
+
EMPTY_VIEW = memoryview(b"")
|
|
17
|
+
|
|
18
|
+
type Entry = tuple[Buffer, Buffer]
|
|
19
|
+
type Compression = Literal["lz4"] | None
|
|
20
|
+
type UIntArray = npt.NDArray[np.unsignedinteger]
|
|
21
|
+
type Shard = mmap.mmap | memoryview
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class BitcaskDataset:
|
|
25
|
+
"""An append-oriented, mmap-backed collection of byte blobs."""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
path: str | Path,
|
|
30
|
+
*,
|
|
31
|
+
keyed: bool = False,
|
|
32
|
+
compression: Compression = "lz4",
|
|
33
|
+
) -> None:
|
|
34
|
+
self.path = Path(path)
|
|
35
|
+
self.keyed = keyed
|
|
36
|
+
self.compression = _validate_compression(compression)
|
|
37
|
+
|
|
38
|
+
if not self.path.exists():
|
|
39
|
+
_initialize_empty_dataset(self.path)
|
|
40
|
+
elif not self.path.is_dir():
|
|
41
|
+
raise ValueError(f"dataset path is not a directory: {self.path}")
|
|
42
|
+
elif not any(self.path.iterdir()):
|
|
43
|
+
_initialize_empty_dataset(self.path)
|
|
44
|
+
else:
|
|
45
|
+
_validate_layout(self.path, keyed=keyed)
|
|
46
|
+
|
|
47
|
+
self._load()
|
|
48
|
+
|
|
49
|
+
def extend(
|
|
50
|
+
self,
|
|
51
|
+
entries: Iterable[Buffer | Entry],
|
|
52
|
+
*,
|
|
53
|
+
max_shard_size: int = DEFAULT_MAX_SHARD_SIZE,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""Add values, or unique key/value pairs for a keyed dataset."""
|
|
56
|
+
if max_shard_size <= 0:
|
|
57
|
+
raise ValueError("max_shard_size must be positive")
|
|
58
|
+
|
|
59
|
+
_extend_dataset(
|
|
60
|
+
self.path,
|
|
61
|
+
entries,
|
|
62
|
+
keyed=self.keyed,
|
|
63
|
+
compression=self.compression,
|
|
64
|
+
existing_keys=self._keys,
|
|
65
|
+
first_shard_id=len(self._shards),
|
|
66
|
+
max_shard_size=max_shard_size,
|
|
67
|
+
)
|
|
68
|
+
self._load()
|
|
69
|
+
|
|
70
|
+
def __len__(self) -> int:
|
|
71
|
+
return self._sizes.shape[0]
|
|
72
|
+
|
|
73
|
+
def __contains__(self, key: object) -> bool:
|
|
74
|
+
if not self.keyed:
|
|
75
|
+
return False
|
|
76
|
+
try:
|
|
77
|
+
normalized = _as_key(key)
|
|
78
|
+
except (TypeError, ValueError):
|
|
79
|
+
return False
|
|
80
|
+
return normalized in self._keys
|
|
81
|
+
|
|
82
|
+
def __getitem__(self, key: Buffer) -> bytes | memoryview:
|
|
83
|
+
if not self.keyed:
|
|
84
|
+
raise TypeError("key lookup is disabled for this dataset")
|
|
85
|
+
normalized = _as_key(key)
|
|
86
|
+
try:
|
|
87
|
+
index = self._keys[normalized]
|
|
88
|
+
except KeyError:
|
|
89
|
+
raise KeyError(normalized) from None
|
|
90
|
+
return self._value_at(index)
|
|
91
|
+
|
|
92
|
+
def at(self, index: int) -> bytes | memoryview:
|
|
93
|
+
"""Return a value by insertion position."""
|
|
94
|
+
return self._value_at(self._normalize_index(index))
|
|
95
|
+
|
|
96
|
+
def key_at(self, index: int) -> memoryview:
|
|
97
|
+
"""Return a key by insertion position."""
|
|
98
|
+
if not self.keyed:
|
|
99
|
+
raise TypeError("keys are disabled for this dataset")
|
|
100
|
+
return self._key_at(self._normalize_index(index))
|
|
101
|
+
|
|
102
|
+
def __getstate__(self) -> tuple[Path, bool, Compression]:
|
|
103
|
+
return self.path, self.keyed, self.compression
|
|
104
|
+
|
|
105
|
+
def __setstate__(self, state: tuple[Path, bool, Compression]) -> None:
|
|
106
|
+
self.path, self.keyed, self.compression = state
|
|
107
|
+
self._load()
|
|
108
|
+
|
|
109
|
+
def _load(self) -> None:
|
|
110
|
+
index_path = self.path / "index.bin"
|
|
111
|
+
columns = 2 if self.keyed else 1
|
|
112
|
+
if index_path.stat().st_size:
|
|
113
|
+
raw_sizes = np.memmap(index_path, dtype=INDEX_DTYPE, mode="r")
|
|
114
|
+
self._sizes = raw_sizes.reshape(-1, columns)
|
|
115
|
+
else:
|
|
116
|
+
self._sizes = np.empty((0, columns), dtype=INDEX_DTYPE)
|
|
117
|
+
|
|
118
|
+
shard_paths = _shard_paths(self.path / "shards")
|
|
119
|
+
shard_sizes = np.asarray([path.stat().st_size for path in shard_paths], dtype=np.uint64)
|
|
120
|
+
expected_size = int(self._sizes.astype(np.uint64).sum())
|
|
121
|
+
actual_size = int(shard_sizes.sum())
|
|
122
|
+
if actual_size != expected_size:
|
|
123
|
+
raise ValueError(f"shard data size is {actual_size}, expected {expected_size}")
|
|
124
|
+
|
|
125
|
+
shards = [_mmap_readonly(path) for path in shard_paths]
|
|
126
|
+
shard_ids, record_offsets = _build_locations(self._sizes, shard_sizes)
|
|
127
|
+
|
|
128
|
+
self._shards = shards
|
|
129
|
+
self._shard_ids = shard_ids
|
|
130
|
+
self._record_offsets = record_offsets
|
|
131
|
+
self._keys: dict[bytes, int] = {}
|
|
132
|
+
if self.keyed:
|
|
133
|
+
for index in range(len(self)):
|
|
134
|
+
key = bytes(self._key_at(index))
|
|
135
|
+
if key in self._keys:
|
|
136
|
+
raise ValueError(f"duplicate key in dataset: {key!r}")
|
|
137
|
+
self._keys[key] = index
|
|
138
|
+
|
|
139
|
+
def _key_at(self, index: int) -> memoryview:
|
|
140
|
+
key_size = int(self._sizes[index, 0])
|
|
141
|
+
if key_size == 0:
|
|
142
|
+
return EMPTY_VIEW
|
|
143
|
+
|
|
144
|
+
shard_id = int(self._shard_ids[index])
|
|
145
|
+
offset = int(self._record_offsets[index])
|
|
146
|
+
return memoryview(self._shards[shard_id])[offset : offset + key_size]
|
|
147
|
+
|
|
148
|
+
def _value_at(self, index: int) -> bytes | memoryview:
|
|
149
|
+
key_size = int(self._sizes[index, 0]) if self.keyed else 0
|
|
150
|
+
value_column = 1 if self.keyed else 0
|
|
151
|
+
value_size = int(self._sizes[index, value_column])
|
|
152
|
+
if value_size == 0:
|
|
153
|
+
return b"" if self.compression else EMPTY_VIEW
|
|
154
|
+
|
|
155
|
+
shard_id = int(self._shard_ids[index])
|
|
156
|
+
offset = int(self._record_offsets[index]) + key_size
|
|
157
|
+
value = memoryview(self._shards[shard_id])[offset : offset + value_size]
|
|
158
|
+
if self.compression == "lz4":
|
|
159
|
+
return block.decompress(value) # type: ignore[attr-defined, no-any-return]
|
|
160
|
+
return value
|
|
161
|
+
|
|
162
|
+
def _normalize_index(self, index: int) -> int:
|
|
163
|
+
if not isinstance(index, int):
|
|
164
|
+
raise TypeError("position must be an integer")
|
|
165
|
+
if index < 0:
|
|
166
|
+
index += len(self)
|
|
167
|
+
if index < 0 or index >= len(self):
|
|
168
|
+
raise IndexError(index)
|
|
169
|
+
return index
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _validate_compression(compression: str | None) -> Compression:
|
|
173
|
+
if compression == "lz4":
|
|
174
|
+
return "lz4"
|
|
175
|
+
if compression is None:
|
|
176
|
+
return None
|
|
177
|
+
raise ValueError(f"unsupported compression: {compression!r}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _initialize_empty_dataset(path: Path) -> None:
|
|
181
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
(path / "shards").mkdir()
|
|
183
|
+
(path / "index.bin").touch()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _validate_layout(path: Path, *, keyed: bool) -> None:
|
|
187
|
+
index_path = path / "index.bin"
|
|
188
|
+
shards_path = path / "shards"
|
|
189
|
+
if not index_path.is_file():
|
|
190
|
+
raise ValueError(f"missing dataset index: {index_path}")
|
|
191
|
+
if not shards_path.is_dir():
|
|
192
|
+
raise ValueError(f"missing shards directory: {shards_path}")
|
|
193
|
+
|
|
194
|
+
entry_size = 8 if keyed else 4
|
|
195
|
+
if index_path.stat().st_size % entry_size:
|
|
196
|
+
raise ValueError(f"index size is not a multiple of {entry_size} bytes")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _extend_dataset(
|
|
200
|
+
path: Path,
|
|
201
|
+
entries: Iterable[Buffer | Entry],
|
|
202
|
+
*,
|
|
203
|
+
keyed: bool,
|
|
204
|
+
compression: Compression,
|
|
205
|
+
existing_keys: dict[bytes, int],
|
|
206
|
+
first_shard_id: int,
|
|
207
|
+
max_shard_size: int,
|
|
208
|
+
) -> None:
|
|
209
|
+
shards_path = path / "shards"
|
|
210
|
+
temporary_shards: list[tuple[Path, Path]] = []
|
|
211
|
+
new_keys: set[bytes] = set()
|
|
212
|
+
shard_file = None
|
|
213
|
+
shard_size = 0
|
|
214
|
+
next_shard_id = first_shard_id
|
|
215
|
+
|
|
216
|
+
index_fd, index_name = tempfile.mkstemp(prefix=".index-", dir=path)
|
|
217
|
+
index_temp = Path(index_name)
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
with os.fdopen(index_fd, "wb") as index_file:
|
|
221
|
+
with (path / "index.bin").open("rb") as old_index:
|
|
222
|
+
_copy_file(old_index, index_file)
|
|
223
|
+
|
|
224
|
+
for entry in entries:
|
|
225
|
+
if keyed:
|
|
226
|
+
key, value = _entry_views(entry)
|
|
227
|
+
key_copy = bytes(key)
|
|
228
|
+
if key_copy in existing_keys or key_copy in new_keys:
|
|
229
|
+
raise ValueError(f"duplicate key: {key_copy!r}")
|
|
230
|
+
new_keys.add(key_copy)
|
|
231
|
+
if key.nbytes > MAX_FIELD_SIZE:
|
|
232
|
+
raise ValueError("key must fit in uint32")
|
|
233
|
+
else:
|
|
234
|
+
if not isinstance(entry, Buffer):
|
|
235
|
+
raise TypeError("keyless datasets require an iterable of buffers")
|
|
236
|
+
key = EMPTY_VIEW
|
|
237
|
+
value = _as_bytes_view(entry)
|
|
238
|
+
|
|
239
|
+
if value.nbytes > MAX_FIELD_SIZE:
|
|
240
|
+
raise ValueError("value must fit in uint32")
|
|
241
|
+
|
|
242
|
+
stored_value: bytes | memoryview
|
|
243
|
+
if compression == "lz4" and value.nbytes:
|
|
244
|
+
stored_value = block.compress( # type: ignore[attr-defined]
|
|
245
|
+
value, mode="high_compression", store_size=True
|
|
246
|
+
)
|
|
247
|
+
else:
|
|
248
|
+
stored_value = value
|
|
249
|
+
stored_value_size = len(stored_value)
|
|
250
|
+
if stored_value_size > MAX_FIELD_SIZE:
|
|
251
|
+
raise ValueError("encoded value must fit in uint32")
|
|
252
|
+
|
|
253
|
+
record_size = key.nbytes + stored_value_size
|
|
254
|
+
if shard_file is None or (shard_size and shard_size + record_size > max_shard_size):
|
|
255
|
+
if shard_file is not None:
|
|
256
|
+
_finish_file(shard_file)
|
|
257
|
+
final_path = shards_path / f"{next_shard_id:06d}.bin"
|
|
258
|
+
fd, temp_name = tempfile.mkstemp(prefix=f".{next_shard_id:06d}-", dir=shards_path)
|
|
259
|
+
shard_file = os.fdopen(fd, "wb")
|
|
260
|
+
temporary_shards.append((Path(temp_name), final_path))
|
|
261
|
+
next_shard_id += 1
|
|
262
|
+
shard_size = 0
|
|
263
|
+
|
|
264
|
+
shard_file.write(key)
|
|
265
|
+
shard_file.write(stored_value)
|
|
266
|
+
shard_size += record_size
|
|
267
|
+
if keyed:
|
|
268
|
+
index_file.write(struct.pack("<II", key.nbytes, stored_value_size))
|
|
269
|
+
else:
|
|
270
|
+
index_file.write(struct.pack("<I", stored_value_size))
|
|
271
|
+
|
|
272
|
+
if shard_file is not None:
|
|
273
|
+
_finish_file(shard_file)
|
|
274
|
+
shard_file = None
|
|
275
|
+
|
|
276
|
+
index_file.flush()
|
|
277
|
+
os.fsync(index_file.fileno())
|
|
278
|
+
|
|
279
|
+
for temporary, final in temporary_shards:
|
|
280
|
+
os.replace(temporary, final)
|
|
281
|
+
os.replace(index_temp, path / "index.bin")
|
|
282
|
+
except BaseException:
|
|
283
|
+
if shard_file is not None:
|
|
284
|
+
shard_file.close()
|
|
285
|
+
index_temp.unlink(missing_ok=True)
|
|
286
|
+
for temporary, _ in temporary_shards:
|
|
287
|
+
temporary.unlink(missing_ok=True)
|
|
288
|
+
raise
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _build_locations(
|
|
292
|
+
sizes: npt.NDArray[np.uint32],
|
|
293
|
+
shard_sizes: npt.NDArray[np.uint64],
|
|
294
|
+
) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.uint64]]:
|
|
295
|
+
record_sizes = sizes.sum(axis=1, dtype=np.uint64)
|
|
296
|
+
record_ends = np.cumsum(record_sizes, dtype=np.uint64)
|
|
297
|
+
global_starts = np.empty_like(record_ends)
|
|
298
|
+
if global_starts.size:
|
|
299
|
+
global_starts[0] = 0
|
|
300
|
+
global_starts[1:] = record_ends[:-1]
|
|
301
|
+
|
|
302
|
+
shard_ids = np.zeros(record_sizes.size, dtype=np.uint32)
|
|
303
|
+
record_offsets = np.zeros(record_sizes.size, dtype=np.uint64)
|
|
304
|
+
nonempty = record_sizes != 0
|
|
305
|
+
if not np.any(nonempty):
|
|
306
|
+
return shard_ids, record_offsets
|
|
307
|
+
|
|
308
|
+
shard_ends = np.cumsum(shard_sizes, dtype=np.uint64)
|
|
309
|
+
if not shard_ends.size:
|
|
310
|
+
raise ValueError("index references data but there are no shards")
|
|
311
|
+
|
|
312
|
+
resolved_ids = np.searchsorted(shard_ends, global_starts[nonempty], side="right")
|
|
313
|
+
if np.any(resolved_ids >= shard_ends.size):
|
|
314
|
+
raise ValueError("index references data beyond the shards")
|
|
315
|
+
if shard_ends.size > MAX_FIELD_SIZE:
|
|
316
|
+
raise ValueError("dataset has too many shards")
|
|
317
|
+
|
|
318
|
+
shard_starts = shard_ends - shard_sizes
|
|
319
|
+
resolved_offsets = global_starts[nonempty] - shard_starts[resolved_ids]
|
|
320
|
+
if np.any(resolved_offsets + record_sizes[nonempty] > shard_sizes[resolved_ids]):
|
|
321
|
+
raise ValueError("an indexed record crosses a shard boundary")
|
|
322
|
+
|
|
323
|
+
shard_ids[nonempty] = resolved_ids.astype(np.uint32)
|
|
324
|
+
record_offsets[nonempty] = resolved_offsets
|
|
325
|
+
return shard_ids, record_offsets
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _shard_paths(path: Path) -> list[Path]:
|
|
329
|
+
numbered: list[tuple[int, Path]] = []
|
|
330
|
+
for candidate in path.iterdir():
|
|
331
|
+
if candidate.name.startswith("."):
|
|
332
|
+
continue
|
|
333
|
+
if candidate.suffix != ".bin" or not candidate.stem.isdecimal():
|
|
334
|
+
raise ValueError(f"invalid shard filename: {candidate.name}")
|
|
335
|
+
numbered.append((int(candidate.stem), candidate))
|
|
336
|
+
|
|
337
|
+
numbered.sort()
|
|
338
|
+
if [number for number, _ in numbered] != list(range(len(numbered))):
|
|
339
|
+
raise ValueError("shard numbers must be contiguous starting at zero")
|
|
340
|
+
return [candidate for _, candidate in numbered]
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _mmap_readonly(path: Path) -> Shard:
|
|
344
|
+
if path.stat().st_size == 0:
|
|
345
|
+
return EMPTY_VIEW
|
|
346
|
+
with path.open("rb") as file:
|
|
347
|
+
return mmap.mmap(file.fileno(), length=0, access=mmap.ACCESS_READ)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _entry_views(entry: Buffer | Entry) -> tuple[memoryview, memoryview]:
|
|
351
|
+
if isinstance(entry, Buffer):
|
|
352
|
+
raise TypeError("keyed datasets require an iterable of (key, value) pairs")
|
|
353
|
+
key, value = entry
|
|
354
|
+
return _as_bytes_view(key), _as_bytes_view(value)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _as_key(value: object) -> bytes:
|
|
358
|
+
if not isinstance(value, Buffer):
|
|
359
|
+
raise TypeError("keys must support the buffer protocol")
|
|
360
|
+
return bytes(_as_bytes_view(value))
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _as_bytes_view(value: Buffer) -> memoryview:
|
|
364
|
+
try:
|
|
365
|
+
view = memoryview(value)
|
|
366
|
+
except TypeError:
|
|
367
|
+
raise TypeError("keys and values must support the buffer protocol") from None
|
|
368
|
+
if not view.contiguous:
|
|
369
|
+
raise ValueError("keys and values must be contiguous")
|
|
370
|
+
return view.cast("B")
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _copy_file(source: BinaryIO, destination: BinaryIO) -> None:
|
|
374
|
+
while chunk := source.read(1024 * 1024):
|
|
375
|
+
destination.write(chunk)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _finish_file(file: BinaryIO) -> None:
|
|
379
|
+
file.flush()
|
|
380
|
+
os.fsync(file.fileno())
|
|
381
|
+
file.close()
|
|
File without changes
|