datashoal 0.1.0__py3-none-any.whl

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.
datashoal/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Cache-first calibration datasets and model artifacts."""
4
+
5
+ from . import hf_compat
6
+ from .api import ArrowIPC, DownloadConfig, Parquet, SafeTensors, load, upload
7
+ from .dataset import Dataset
8
+
9
+ __all__ = ["ArrowIPC", "Dataset", "DownloadConfig", "Parquet", "SafeTensors", "hf_compat", "load", "upload"]
datashoal/_blake3.py ADDED
@@ -0,0 +1,53 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """One-shot, 32-byte keyed BLAKE3 for Xet's bounded chunks and Merkle nodes."""
4
+
5
+ import struct
6
+
7
+ _IV = (0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A)
8
+ _PERMUTE = (2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8)
9
+ _MASK = 0xffffffff
10
+
11
+
12
+ def _rotate(value, distance):
13
+ return ((value >> distance) | (value << (32 - distance))) & _MASK
14
+
15
+
16
+ def _mix(v, a, b, c, d, x, y):
17
+ v[a] = (v[a] + v[b] + x) & _MASK
18
+ v[d] = _rotate(v[d] ^ v[a], 16)
19
+ v[c] = (v[c] + v[d]) & _MASK
20
+ v[b] = _rotate(v[b] ^ v[c], 12)
21
+ v[a] = (v[a] + v[b] + y) & _MASK
22
+ v[d] = _rotate(v[d] ^ v[a], 8)
23
+ v[c] = (v[c] + v[d]) & _MASK
24
+ v[b] = _rotate(v[b] ^ v[c], 7)
25
+
26
+
27
+ def _compress(cv, words, counter, length, flags):
28
+ v = [*cv, *_IV, counter & _MASK, counter >> 32, length, flags]
29
+ for _ in range(7):
30
+ for i in range(4):
31
+ _mix(v, i, i+4, i+8, i+12, words[2*i], words[2*i+1])
32
+ for i in range(4):
33
+ _mix(v, i, 4+(i+1)%4, 8+(i+2)%4, 12+(i+3)%4, words[8+2*i], words[9+2*i])
34
+ words = [words[i] for i in _PERMUTE]
35
+ return tuple(v[i] ^ v[i+8] for i in range(8))
36
+
37
+
38
+ def keyed(data, key):
39
+ key_words = struct.unpack("<8I", key)
40
+ def subtree(start, end, root):
41
+ if end - start > 1024:
42
+ chunks = (end - start + 1023) // 1024
43
+ middle = start + 1024 * (1 << ((chunks - 1).bit_length() - 1))
44
+ words = subtree(start, middle, False) + subtree(middle, end, False)
45
+ return _compress(key_words, words, 0, 64, 16 | 4 | (8 if root else 0))
46
+ cv = key_words
47
+ for offset in range(start, max(start + 1, end), 64):
48
+ block = data[offset:min(end, offset+64)]
49
+ final = offset+64 >= end
50
+ flags = 16 | int(offset == start) | (2 if final else 0) | (8 if final and root else 0)
51
+ cv = _compress(cv, struct.unpack("<16I", block.ljust(64, b"\0")), start//1024, len(block), flags)
52
+ return cv
53
+ return struct.pack("<8I", *subtree(0, len(data), True))
datashoal/_compact.py ADDED
@@ -0,0 +1,123 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Thrift compact protocol used by Parquet footers and page headers."""
4
+
5
+ import struct
6
+
7
+ BOOL, BYTE, I16, I32, I64, DOUBLE, BINARY, LIST, SET, MAP, STRUCT = 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
8
+
9
+
10
+ def exact(stream, n):
11
+ if n < 0:
12
+ raise ValueError("Negative Parquet length")
13
+ data = stream.read(n)
14
+ if len(data) != n:
15
+ raise ValueError("Truncated Parquet data")
16
+ return data
17
+
18
+
19
+ def uint(stream):
20
+ value = 0
21
+ for shift in range(0, 70, 7):
22
+ b = exact(stream, 1)[0]
23
+ if shift == 63 and b > 1:
24
+ raise ValueError("Invalid compact integer")
25
+ value |= (b & 127) << shift
26
+ if b < 128:
27
+ return value
28
+ raise ValueError("Invalid compact integer")
29
+
30
+
31
+ def varint(value):
32
+ out = bytearray()
33
+ while value >= 128:
34
+ out.append(128 | (value & 127))
35
+ value >>= 7
36
+ out.append(value)
37
+ return bytes(out)
38
+
39
+
40
+ def _value(stream, kind, depth, budget):
41
+ if depth > 64:
42
+ raise ValueError("Parquet metadata nested too deeply")
43
+ if kind in (1, 2):
44
+ return kind == 1
45
+ if kind == BYTE:
46
+ return int.from_bytes(exact(stream, 1), "little", signed=True)
47
+ if kind in (I16, I32, I64):
48
+ n = uint(stream)
49
+ return (n >> 1) ^ -(n & 1)
50
+ if kind == DOUBLE:
51
+ return struct.unpack("<d", exact(stream, 8))[0]
52
+ if kind == BINARY:
53
+ size = uint(stream)
54
+ if size > 64 << 20:
55
+ raise ValueError("Oversized Parquet metadata string")
56
+ return exact(stream, size)
57
+ if kind in (LIST, SET):
58
+ head = exact(stream, 1)[0]
59
+ count = head >> 4
60
+ if count == 15:
61
+ count = uint(stream)
62
+ budget[0] -= count
63
+ if budget[0] < 0 or count > 1000000:
64
+ raise ValueError("Oversized Parquet metadata list")
65
+ if head & 15 in (1, 2):
66
+ values = exact(stream, count)
67
+ if any(v not in (1, 2) for v in values):
68
+ raise ValueError("Invalid compact boolean")
69
+ return [v == 1 for v in values]
70
+ return [_value(stream, head & 15, depth + 1, budget) for _ in range(count)]
71
+ if kind == STRUCT:
72
+ return fields(stream, depth + 1, budget)
73
+ raise ValueError(f"Unsupported Parquet compact type {kind}")
74
+
75
+
76
+ def fields(stream, depth=0, budget=None):
77
+ if budget is None:
78
+ budget = [1 << 20]
79
+ out = {}
80
+ last = 0
81
+ while head := exact(stream, 1)[0]:
82
+ budget[0] -= 1
83
+ if budget[0] < 0:
84
+ raise ValueError("Oversized compact metadata")
85
+ delta, kind = divmod(head, 16)
86
+ last = last + delta if delta else _value(stream, I16, depth, budget)
87
+ if not -32768 <= last <= 32767:
88
+ raise ValueError("Invalid compact field id")
89
+ if last in out:
90
+ raise ValueError("Duplicate compact field")
91
+ out[last] = _value(stream, kind, depth, budget)
92
+ return out
93
+
94
+
95
+ def _encode(kind, value):
96
+ if kind in (I16, I32, I64):
97
+ return varint(value * 2 if value >= 0 else -value * 2 - 1)
98
+ if kind == BINARY:
99
+ return varint(len(value)) + value
100
+ if kind == STRUCT:
101
+ return encode(value)
102
+ if kind == LIST:
103
+ item, values = value
104
+ n = len(values)
105
+ head = bytes([min(n, 15) * 16 + item])
106
+ return head + (varint(n) if n >= 15 else b"") + b"".join(_encode(item, v) for v in values)
107
+ raise ValueError(f"Unsupported compact type {kind}")
108
+
109
+
110
+ def encode(entries):
111
+ out = bytearray()
112
+ previous = 0
113
+ for number, kind, value in entries:
114
+ delta = number - previous
115
+ if 0 < delta < 16:
116
+ out.append(delta * 16 + kind)
117
+ else:
118
+ out.append(kind)
119
+ out.extend(_encode(I16, number))
120
+ out.extend(_encode(kind, value))
121
+ previous = number
122
+ out.append(0)
123
+ return bytes(out)
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Opt-in datasets import surface."""
4
+
5
+ from .hf_compat import Dataset, DatasetDict, IterableDataset, IterableDatasetDict, load_dataset
6
+
7
+ __all__ = ["Dataset", "DatasetDict", "IterableDataset", "IterableDatasetDict", "load_dataset"]
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Opt-in huggingface_hub import surface."""
4
+
5
+ from .hf_compat import hf_hub_download, snapshot_download, upload_file
6
+
7
+ __all__ = ["hf_hub_download", "snapshot_download", "upload_file"]
@@ -0,0 +1,78 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """``safetensors.safe_open`` spelling over DataShoal's targeted, validated mappings."""
4
+
5
+ import os
6
+ from typing import Dict, List, Optional
7
+
8
+ import torch
9
+
10
+ from .tensor_layout import layout as parse_safetensors
11
+ from .torch_ranges import CheckpointIndex, TensorRef, _load_one
12
+
13
+
14
+ class _SafeTensorsSlice:
15
+ """``safe_open(...).get_slice(name)`` equivalent."""
16
+
17
+ def __init__(self, ref: TensorRef, device: torch.device):
18
+ self._ref = ref
19
+ self._device = device
20
+
21
+ def get_shape(self) -> List[int]:
22
+ return list(self._ref.wire.shape)
23
+
24
+ def get_dtype(self) -> str:
25
+ return self._ref.wire.dtype
26
+
27
+ def __getitem__(self, index) -> torch.Tensor:
28
+ leading = index[0] if isinstance(index, tuple) and index else index
29
+ rest = index[1:] if isinstance(index, tuple) else ()
30
+ shape = self._ref.shape
31
+ if (
32
+ shape
33
+ and isinstance(leading, slice)
34
+ and leading.step in (None, 1)
35
+ and all(isinstance(part, slice) and part == slice(None) for part in rest)
36
+ ):
37
+ start, stop, _ = leading.indices(shape[0])
38
+ stop = max(start, stop)
39
+ return _load_one(self._ref, self._device, rows=(start, stop))
40
+ return _load_one(self._ref, self._device)[index]
41
+
42
+
43
+ class SafeTensorsHandle:
44
+ """``safetensors.safe_open`` replacement: validated, targeted, lifetime-bound.
45
+
46
+ Every ``get_tensor`` maps only that tensor's bytes; a CPU tensor >= 1 MiB is
47
+ a zero-copy view whose mapping is released when the tensor is freed, smaller
48
+ tensors and non-CPU reads are owning copies. Closing the handle releases
49
+ nothing that is still in use, because nothing whole-file is held.
50
+ """
51
+
52
+ def __init__(self, path, framework: str = "pt", device="cpu"):
53
+ if framework not in ("pt", "torch", "pytorch"):
54
+ raise ValueError(f"safe_open supports framework='pt' only, got {framework!r}.")
55
+ if isinstance(device, int) and not isinstance(device, bool):
56
+ device = torch.device("cuda", device)
57
+ self._device = torch.device(device)
58
+ self._index = CheckpointIndex([os.fspath(path)])
59
+
60
+ self._metadata = parse_safetensors(os.fspath(path)).wire.metadata
61
+
62
+ def __enter__(self) -> "SafeTensorsHandle":
63
+ return self
64
+
65
+ def __exit__(self, *exc) -> None:
66
+ return None
67
+
68
+ def keys(self) -> List[str]:
69
+ return list(self._index.keys())
70
+
71
+ def metadata(self) -> Optional[Dict[str, str]]:
72
+ return None if self._metadata is None else dict(self._metadata)
73
+
74
+ def get_tensor(self, name: str) -> torch.Tensor:
75
+ return _load_one(self._index[name], self._device)
76
+
77
+ def get_slice(self, name: str) -> _SafeTensorsSlice:
78
+ return _SafeTensorsSlice(self._index[name], self._device)
datashoal/_gear.py ADDED
@@ -0,0 +1,73 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Xet CDC protocol constants from the specified rust-gearhash default table.
4
+
5
+ https://raw.githubusercontent.com/srijs/rust-gearhash/adad44e7141cfd29d898cf6e0858f50b995db286/src/table.rs
6
+ """
7
+
8
+ TABLE = (
9
+ 0xb088d3a9e840f559, 0x5652c7f739ed20d6, 0x45b28969898972ab, 0x6b0a89d5b68ec777,
10
+ 0x368f573e8b7a31b7, 0x1dc636dce936d94b, 0x207a4c4e5554d5b6, 0xa474b34628239acb,
11
+ 0x3b06a83e1ca3b912, 0x90e78d6c2f02baf7, 0xe1c92df7150d9a8a, 0x8e95053a1086d3ad,
12
+ 0x5a2ef4f1b83a0722, 0xa50fac949f807fae, 0x0e7303eb80d8d681, 0x99b07edc1570ad0f,
13
+ 0x689d2fb555fd3076, 0x00005082119ea468, 0xc4b08306a88fcc28, 0x3eb0678af6374afd,
14
+ 0xf19f87ab86ad7436, 0xf2129fbfbe6bc736, 0x481149575c98a4ed, 0x0000010695477bc5,
15
+ 0x1fba37801a9ceacc, 0x3bf06fd663a49b6d, 0x99687e9782e3874b, 0x79a10673aa50d8e3,
16
+ 0xe4accf9e6211f420, 0x2520e71f87579071, 0x2bd5d3fd781a8a9b, 0x00de4dcddd11c873,
17
+ 0xeaa9311c5a87392f, 0xdb748eb617bc40ff, 0xaf579a8df620bf6f, 0x86a6e5da1b09c2b1,
18
+ 0xcc2fc30ac322a12e, 0x355e2afec1f74267, 0x2d99c8f4c021a47b, 0xbade4b4a9404cfc3,
19
+ 0xf7b518721d707d69, 0x3286b6587bf32c20, 0x0000b68886af270c, 0xa115d6e4db8a9079,
20
+ 0x484f7e9c97b2e199, 0xccca7bb75713e301, 0xbf2584a62bb0f160, 0xade7e813625dbcc8,
21
+ 0x000070940d87955a, 0x8ae69108139e626f, 0xbd776ad72fde38a2, 0xfb6b001fc2fcc0cf,
22
+ 0xc7a474b8e67bc427, 0xbaf6f11610eb5d58, 0x09cb1f5b6de770d1, 0xb0b219e6977d4c47,
23
+ 0x00ccbc386ea7ad4a, 0xcc849d0adf973f01, 0x73a3ef7d016af770, 0xc807d2d386bdbdfe,
24
+ 0x7f2ac9966c791730, 0xd037a86bc6c504da, 0xf3f17c661eaa609d, 0xaca626b04daae687,
25
+ 0x755a99374f4a5b07, 0x90837ee65b2caede, 0x6ee8ad93fd560785, 0x0000d9e11053edd8,
26
+ 0x9e063bb2d21cdbd7, 0x07ab77f12a01d2b2, 0xec550255e6641b44, 0x78fb94a8449c14c6,
27
+ 0xc7510e1bc6c0f5f5, 0x0000320b36e4cae3, 0x827c33262c8b1a2d, 0x14675f0b48ea4144,
28
+ 0x267bd3a6498deceb, 0xf1916ff982f5035e, 0x86221b7ff434fb88, 0x9dbecee7386f49d8,
29
+ 0xea58f8cac80f8f4a, 0x008d198692fc64d8, 0x6d38704fbabf9a36, 0xe032cb07d1e7be4c,
30
+ 0x228d21f6ad450890, 0x635cb1bfc02589a5, 0x4620a1739ca2ce71, 0xa7e7dfe3aae5fb58,
31
+ 0x0c10ca932b3c0deb, 0x2727fee884afed7b, 0xa2df1c6df9e2ab1f, 0x4dcdd1ac0774f523,
32
+ 0x000070ffad33e24e, 0xa2ace87bc5977816, 0x9892275ab4286049, 0xc2861181ddf18959,
33
+ 0xbb9972a042483e19, 0xef70cd3766513078, 0x00000513abfc9864, 0xc058b61858c94083,
34
+ 0x09e850859725e0de, 0x9197fb3bf83e7d94, 0x7e1e626d12b64bce, 0x520c54507f7b57d1,
35
+ 0xbee1797174e22416, 0x6fd9ac3222e95587, 0x0023957c9adfbf3e, 0xa01c7d7e234bbe15,
36
+ 0xaba2c758b8a38cbb, 0x0d1fa0ceec3e2b30, 0x0bb6a58b7e60b991, 0x4333dd5b9fa26635,
37
+ 0xc2fd3b7d4001c1a3, 0xfb41802454731127, 0x65a56185a50d18cb, 0xf67a02bd8784b54f,
38
+ 0x696f11dd67e65063, 0x00002022fca814ab, 0x8cd6be912db9d852, 0x695189b6e9ae8a57,
39
+ 0xee9453b50ada0c28, 0xd8fc5ea91a78845e, 0xab86bf191a4aa767, 0x0000c6b5c86415e5,
40
+ 0x267310178e08a22e, 0xed2d101b078bca25, 0x3b41ed84b226a8fb, 0x13e622120f28dc06,
41
+ 0xa315f5ebfb706d26, 0x8816c34e3301bace, 0xe9395b9cbb71fdae, 0x002ce9202e721648,
42
+ 0x4283db1d2bb3c91c, 0xd77d461ad2b1a6a5, 0xe2ec17e46eeb866b, 0xb8e0be4039fbc47c,
43
+ 0xdea160c4d5299d04, 0x7eec86c8d28c3634, 0x2119ad129f98a399, 0xa6ccf46b61a283ef,
44
+ 0x2c52cedef658c617, 0x2db4871169acdd83, 0x0000f0d6f39ecbe9, 0x3dd5d8c98d2f9489,
45
+ 0x8a1872a22b01f584, 0xf282a4c40e7b3cf2, 0x8020ec2ccb1ba196, 0x6693b6e09e59e313,
46
+ 0x0000ce19cc7c83eb, 0x20cb5735f6479c3b, 0x762ebf3759d75a5b, 0x207bfe823d693975,
47
+ 0xd77dc112339cd9d5, 0x9ba7834284627d03, 0x217dc513e95f51e9, 0xb27b1a29fc5e7816,
48
+ 0x00d5cd9831bb662d, 0x71e39b806d75734c, 0x7e572af006fb1a23, 0xa2734f2f6ae91f85,
49
+ 0xbf82c6b5022cddf2, 0x5c3beac60761a0de, 0xcdc893bb47416998, 0x6d1085615c187e01,
50
+ 0x77f8ae30ac277c5d, 0x917c6b81122a2c91, 0x5b75b699add16967, 0x0000cf6ae79a069b,
51
+ 0xf3c40afa60de1104, 0x2063127aa59167c3, 0x621de62269d1894d, 0xd188ac1de62b4726,
52
+ 0x107036e2154b673c, 0x0000b85f28553a1d, 0xf2ef4e4c18236f3d, 0xd9d6de6611b9f602,
53
+ 0xa1fc7955fb47911c, 0xeb85fd032f298dbd, 0xbe27502fb3befae1, 0xe3034251c4cd661e,
54
+ 0x441364d354071836, 0x0082b36c75f2983e, 0xb145910316fa66f0, 0x021c069c9847caf7,
55
+ 0x2910dfc75a4b5221, 0x735b353e1c57a8b5, 0xce44312ce98ed96c, 0xbc942e4506bdfa65,
56
+ 0xf05086a71257941b, 0xfec3b215d351cead, 0x00ae1055e0144202, 0xf54b40846f42e454,
57
+ 0x00007fd9c8bcbcc8, 0xbfbd9ef317de9bfe, 0xa804302ff2854e12, 0x39ce4957a5e5d8d4,
58
+ 0xffb9e2a45637ba84, 0x55b9ad1d9ea0818b, 0x00008acbf319178a, 0x48e2bfc8d0fbfb38,
59
+ 0x8be39841e848b5e8, 0x0e2712160696a08b, 0xd51096e84b44242a, 0x1101ba176792e13a,
60
+ 0xc22e770f4531689d, 0x1689eff272bbc56c, 0x00a92a197f5650ec, 0xbc765990bda1784e,
61
+ 0xc61441e392fcb8ae, 0x07e13a2ced31e4a0, 0x92cbe984234e9d4d, 0x8f4ff572bb7d8ac5,
62
+ 0x0b9670c00b963bd0, 0x62955a581a03eb01, 0x645f83e5ea000254, 0x41fce516cd88f299,
63
+ 0xbbda9748da7a98cf, 0x0000aab2fe4845fa, 0x19761b069bf56555, 0x8b8f5e8343b6ad56,
64
+ 0x3e5d1cfd144821d9, 0xec5c1e2ca2b0cd8f, 0xfaf7e0fea7fbb57f, 0x000000d3ba12961b,
65
+ 0xda3f90178401b18e, 0x70ff906de33a5feb, 0x0527d5a7c06970e7, 0x22d8e773607c13e9,
66
+ 0xc9ab70df643c3bac, 0xeda4c6dc8abe12e3, 0xecef1f410033e78a, 0x0024c2b274ac72cb,
67
+ 0x06740d954fa900b4, 0x1d7a299b323d6304, 0xb3c37cb298cbead5, 0xc986e3c76178739b,
68
+ 0x9fabea364b46f58a, 0x6da214c5af85cc56, 0x17a43ed8b7a38f84, 0x6eccec511d9adbeb,
69
+ 0xf9cab30913335afb, 0x4a5e60c5f415eed2, 0x00006967503672b4, 0x9da51d121454bb87,
70
+ 0x84321e13b9bbc816, 0xfb3d6fb6ab2fdd8d, 0x60305eed8e160a8d, 0xcbbf4b14e9946ce8,
71
+ 0x00004f63381b10c3, 0x07d5b7816fcc4e10, 0xe5a536726a6a8155, 0x57afb23447a07fdd,
72
+ 0x18f346f7abc9d394, 0x636dc655d61ad33d, 0xcc8bab4939f7f3f6, 0x63c7a906c1dd187b,
73
+ )
datashoal/_jit.py ADDED
@@ -0,0 +1,176 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Compile DataShoal's bundled codec on first use and cache it per user and ABI."""
4
+
5
+ import hashlib
6
+ import importlib.util
7
+ import logging
8
+ import os
9
+ import platform
10
+ import shlex
11
+ import shutil
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import sysconfig
16
+ import tempfile
17
+ from contextlib import contextmanager
18
+ from pathlib import Path
19
+ from threading import Lock
20
+
21
+ from ._gear import TABLE
22
+
23
+ _UNSET = object()
24
+ _module = _UNSET
25
+ _lock = Lock()
26
+
27
+
28
+ def _after_fork():
29
+ global _lock
30
+ _lock = Lock()
31
+
32
+
33
+ if hasattr(os, "register_at_fork"):
34
+ os.register_at_fork(after_in_child=_after_fork)
35
+
36
+
37
+ @contextmanager
38
+ def _build_lock(path):
39
+ with path.open("a+b") as handle:
40
+ if os.name == "nt":
41
+ import msvcrt
42
+
43
+ handle.seek(0)
44
+ msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
45
+ else:
46
+ import fcntl
47
+
48
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
49
+ yield
50
+
51
+
52
+ def _check_cache_entry(path, expected):
53
+ if os.name != "nt":
54
+ entry = path.lstat()
55
+ if not expected(entry.st_mode) or entry.st_uid != os.getuid() or entry.st_mode & 0o022:
56
+ raise PermissionError(f"Unsafe JIT cache entry: {path}")
57
+
58
+
59
+ def _compile_or_load():
60
+ if sys.implementation.name != "cpython":
61
+ raise RuntimeError("the native codec requires CPython")
62
+ sources = Path(__file__).with_name("native")
63
+ gear = "static const uint64_t gear[256] = {" + ",".join(f"UINT64_C({v})" for v in TABLE) + "};"
64
+ suffix = sysconfig.get_config_var("EXT_SUFFIX")
65
+ cc = os.environ.get("CC") or ("cl" if os.name == "nt" else sysconfig.get_config_var("CC") or "cc")
66
+ include = sysconfig.get_path("include")
67
+ target = os.environ.get("MACOSX_DEPLOYMENT_TARGET") or sysconfig.get_config_var(
68
+ "MACOSX_DEPLOYMENT_TARGET"
69
+ )
70
+ digest = hashlib.sha256()
71
+ for part in (*sorted(sources.glob("*.h")), sources / "codec.c", Path(__file__)):
72
+ digest.update(part.read_bytes())
73
+ digest.update(
74
+ repr(
75
+ (gear, sys.version, suffix, platform.machine(), sysconfig.get_platform(), include, cc, target)
76
+ ).encode()
77
+ )
78
+ default = Path(
79
+ os.environ.get("LOCALAPPDATA" if os.name == "nt" else "XDG_CACHE_HOME") or Path.home() / ".cache"
80
+ )
81
+ root = Path(os.environ.get("DATASHOAL_JIT_CACHE") or default / "datashoal" / "jit")
82
+ root.mkdir(mode=0o700, parents=True, exist_ok=True)
83
+ _check_cache_entry(root, stat.S_ISDIR)
84
+ directory = root / digest.hexdigest()
85
+ directory.mkdir(mode=0o700, exist_ok=True)
86
+ _check_cache_entry(directory, stat.S_ISDIR)
87
+ library = directory / ("_native" + suffix)
88
+ if not library.is_file():
89
+ with _build_lock(directory / "build.lock"):
90
+ if not library.is_file():
91
+ compiler = [cc] if Path(cc).is_file() else shlex.split(cc, posix=os.name != "nt")
92
+ if not compiler or not shutil.which(compiler[0]):
93
+ raise FileNotFoundError(f"C compiler {cc!r} was not found on PATH")
94
+ if not (Path(include) / "Python.h").is_file():
95
+ raise FileNotFoundError(f"CPython development header {include}/Python.h is missing")
96
+ with tempfile.TemporaryDirectory(dir=directory) as tmp:
97
+ out = Path(tmp) / library.name
98
+ (Path(tmp) / "gear.h").write_text(gear, encoding="ascii")
99
+ if os.name == "nt":
100
+ args = [
101
+ "/nologo",
102
+ "/LD",
103
+ "/MD",
104
+ "/O2",
105
+ "/std:c11",
106
+ "/I" + include,
107
+ "/I" + tmp,
108
+ str(sources / "codec.c"),
109
+ "/link",
110
+ "/OUT:" + str(out),
111
+ "/LIBPATH:" + str(Path(sys.base_prefix) / "libs"),
112
+ ]
113
+ else:
114
+ args = [
115
+ "-std=c11",
116
+ "-O3",
117
+ "-fPIC",
118
+ "-shared",
119
+ "-I" + include,
120
+ "-I" + tmp,
121
+ str(sources / "codec.c"),
122
+ "-o",
123
+ str(out),
124
+ ]
125
+ if sys.platform == "darwin":
126
+ args.extend(["-undefined", "dynamic_lookup", "-arch", platform.machine()])
127
+ if target:
128
+ args.append("-mmacosx-version-min=" + target)
129
+ result = subprocess.run(
130
+ [*compiler, *args], cwd=tmp, capture_output=True, text=True, errors="replace"
131
+ )
132
+ if result.returncode:
133
+ detail = (result.stderr or result.stdout).strip()[-1200:]
134
+ raise RuntimeError(f"{cc} exited with status {result.returncode}: {detail}")
135
+ out.chmod(0o700)
136
+ os.replace(out, library)
137
+ _check_cache_entry(library, stat.S_ISREG)
138
+ spec = importlib.util.spec_from_file_location("datashoal._native", library)
139
+ module = importlib.util.module_from_spec(spec)
140
+ spec.loader.exec_module(module)
141
+ return module
142
+
143
+
144
+ def _warn(reason):
145
+ message = (
146
+ f"DataShoal could not load its JIT accelerator ({reason}). Using the much slower Python codecs. "
147
+ "Install a C11 compiler on PATH and matching CPython development headers, then restart Python."
148
+ )
149
+ try:
150
+ from logbar import LogBar
151
+ except ImportError:
152
+ logging.getLogger("datashoal").warning(message)
153
+ else:
154
+ LogBar.shared().warning(message)
155
+
156
+
157
+ def native():
158
+ global _module
159
+ if _module is _UNSET:
160
+ with _lock:
161
+ if _module is _UNSET:
162
+ try:
163
+ _module = _compile_or_load()
164
+ except (OSError, RuntimeError, ImportError, ValueError) as exc:
165
+ _module = None
166
+ _warn(exc)
167
+ return _module
168
+
169
+
170
+ def accelerate(fallback, name=None):
171
+ def dispatch(*args):
172
+ module = native()
173
+ method = getattr(module, name or fallback.__name__) if module is not None else fallback
174
+ return method(*args)
175
+
176
+ return dispatch
datashoal/_mapped.py ADDED
@@ -0,0 +1,151 @@
1
+ # SPDX-FileCopyrightText: 2026 ModelCloud.ai, @qubitiium (https://x.com/qubitium), and DataShoal contributors
2
+
3
+ """Independent cursors over bounded, read-only regions of one open file."""
4
+
5
+ import io
6
+ import mmap
7
+ import os
8
+ import stat
9
+ from contextlib import contextmanager
10
+ from pathlib import Path
11
+ from threading import Lock
12
+
13
+ # Round to a mapping boundary on every supported platform.
14
+ _WINDOW = max(8 << 20, mmap.ALLOCATIONGRANULARITY)
15
+
16
+
17
+ class _Source:
18
+ def __init__(self, file):
19
+ self.file = file
20
+ self.fd = file.fileno()
21
+ self.size = os.fstat(self.fd).st_size
22
+ self.lock = Lock()
23
+ self.windows = {}
24
+
25
+ def acquire(self, offset):
26
+ with self.lock:
27
+ entry = self.windows.get(offset)
28
+ if entry is None:
29
+ length = min(_WINDOW, self.size - offset)
30
+ region = mmap.mmap(self.fd, length, access=mmap.ACCESS_READ, offset=offset)
31
+ entry = self.windows[offset] = [region, 0]
32
+ entry[1] += 1
33
+ return entry[0]
34
+
35
+ def release(self, offset):
36
+ with self.lock:
37
+ entry = self.windows[offset]
38
+ entry[1] -= 1
39
+ if entry[1] == 0:
40
+ entry[0].close()
41
+ del self.windows[offset]
42
+
43
+
44
+ class MappedReader(io.RawIOBase):
45
+ """One window per cursor. Returned bytes never borrow a mapping."""
46
+
47
+ def __init__(self, source):
48
+ super().__init__()
49
+ self.source = source
50
+ self.pos = 0
51
+ self.offset = 0
52
+ self.region = None
53
+
54
+ def fileno(self):
55
+ return self.source.fd
56
+
57
+ def fork(self):
58
+ return MappedReader(self.source)
59
+
60
+ def release(self):
61
+ if self.region is not None:
62
+ self.source.release(self.offset)
63
+ self.region = None
64
+
65
+ def close(self):
66
+ self.release()
67
+ super().close()
68
+
69
+ def readable(self):
70
+ return True
71
+
72
+ def seekable(self):
73
+ return True
74
+
75
+ def tell(self):
76
+ self._checkClosed()
77
+ return self.pos
78
+
79
+ def seek(self, offset, whence=os.SEEK_SET):
80
+ self._checkClosed()
81
+ if whence == os.SEEK_CUR:
82
+ offset += self.pos
83
+ elif whence == os.SEEK_END:
84
+ offset += self.source.size
85
+ elif whence != os.SEEK_SET:
86
+ raise ValueError("Invalid seek mode")
87
+ if offset < 0:
88
+ raise ValueError("Negative seek offset")
89
+ if self.region is not None and not self.offset <= offset < self.offset + len(self.region):
90
+ self.release()
91
+ self.pos = offset
92
+ return offset
93
+
94
+ def _map(self):
95
+ if self.closed:
96
+ raise ValueError("Read from closed mapped cursor")
97
+ if self.region is None:
98
+ self.offset = (self.pos // _WINDOW) * _WINDOW
99
+ self.region = self.source.acquire(self.offset)
100
+ return self.pos - self.offset
101
+
102
+ def decode_snappy(self, length, size, codec):
103
+ if length > 0 and length <= self.source.size - self.pos:
104
+ start = self._map()
105
+ if length <= len(self.region) - start:
106
+ data = codec.snappy_region(self.region, start, length, size)
107
+ self.pos += length
108
+ if start + length == len(self.region):
109
+ self.release()
110
+ return data
111
+ return codec.snappy(self.read(length), size)
112
+
113
+ def _piece(self, count):
114
+ start = self._map()
115
+ stop = min(start + count, len(self.region))
116
+ piece = self.region[start:stop]
117
+ self.pos += stop - start
118
+ if stop == len(self.region):
119
+ self.release()
120
+ return piece
121
+
122
+ def read(self, size=-1):
123
+ self._checkClosed()
124
+ remaining = max(0, self.source.size - self.pos)
125
+ size = remaining if size < 0 else min(size, remaining)
126
+ if not size:
127
+ return b""
128
+ first = self._piece(size)
129
+ if len(first) == size:
130
+ return first
131
+ output = io.BytesIO()
132
+ output.write(first)
133
+ del first
134
+ while output.tell() < size:
135
+ output.write(self._piece(size - output.tell()))
136
+ return output.getvalue()
137
+
138
+ def readinto(self, buffer):
139
+ data = self.read(len(buffer))
140
+ buffer[: len(data)] = data
141
+ return len(data)
142
+
143
+
144
+ @contextmanager
145
+ def mapped_file(path, *, allow_stream=False):
146
+ with Path(path).open("rb") as file:
147
+ if allow_stream and not stat.S_ISREG(os.fstat(file.fileno()).st_mode):
148
+ yield file
149
+ else:
150
+ with MappedReader(_Source(file)) as cursor:
151
+ yield cursor