model-runtime 0.5.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.
saturn/shared_store.py ADDED
@@ -0,0 +1,257 @@
1
+ """Immutable whole-file sharing without changing StateCut or array identities.
2
+
3
+ Local paths remain regular files (hardlinks), so legacy readers and manifests
4
+ need no changes. The pool is local and on the same filesystem as its clients.
5
+ This is byte sharing, not semantic equivalence or BF16/FP32 conversion.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import stat
14
+ import tempfile
15
+ import uuid
16
+ from pathlib import Path
17
+
18
+ CONFIG_NAME = ".mdb-storage.json"
19
+ SCHEMA = "saturn-pub-shared-files-v1"
20
+ TENSOR_SUFFIXES = frozenset({".safetensors", ".npy", ".npyb"})
21
+
22
+
23
+ def safe_path(path):
24
+ path = Path(os.path.abspath(path))
25
+ for part in [path, *path.parents]:
26
+ if part.is_symlink():
27
+ raise ValueError("shared storage refuses symbolic links: " + str(part))
28
+ return path
29
+
30
+
31
+ def _identity(st):
32
+ return st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns
33
+
34
+
35
+ def file_identity(path):
36
+ """Hash a stable regular file; fail if its inode or contents change."""
37
+ path = safe_path(path)
38
+ before = path.stat()
39
+ if not stat.S_ISREG(before.st_mode):
40
+ raise ValueError("shared storage requires a regular file")
41
+ digest = hashlib.sha256()
42
+ with path.open("rb") as stream:
43
+ if _identity(os.fstat(stream.fileno())) != _identity(before):
44
+ raise ValueError("source changed before hashing")
45
+ while chunk := stream.read(4 << 20):
46
+ digest.update(chunk)
47
+ if _identity(os.fstat(stream.fileno())) != _identity(before):
48
+ raise ValueError("source changed while hashing")
49
+ if _identity(path.stat()) != _identity(before):
50
+ raise ValueError("source path changed while hashing")
51
+ return digest.hexdigest(), before
52
+
53
+
54
+ def _fsync_dir(path):
55
+ try:
56
+ descriptor = os.open(path, os.O_RDONLY)
57
+ try:
58
+ os.fsync(descriptor)
59
+ finally:
60
+ os.close(descriptor)
61
+ except OSError:
62
+ pass # Some supported filesystems do not expose directory fsync.
63
+
64
+
65
+ class SharedStore:
66
+ """No automatic GC; all managed payloads are read-only and hash verified."""
67
+
68
+ def __init__(self, root):
69
+ self.root = safe_path(root)
70
+ self.root.mkdir(parents=True, exist_ok=True)
71
+ self.objects = self.root / "sha256"
72
+ self.objects.mkdir(exist_ok=True)
73
+
74
+ def object_path(self, digest):
75
+ if (
76
+ not isinstance(digest, str)
77
+ or len(digest) != 64
78
+ or any(c not in "0123456789abcdef" for c in digest)
79
+ ):
80
+ raise ValueError("expected a lowercase SHA-256")
81
+ return safe_path(self.objects / digest[:2] / digest)
82
+
83
+ def _check(self, path, digest, size):
84
+ actual, st = file_identity(path)
85
+ if actual != digest or st.st_size != size:
86
+ raise ValueError("shared object content-address mismatch: " + str(path))
87
+ if st.st_mode & 0o222:
88
+ raise ValueError("shared object must be read-only: " + str(path))
89
+ return st
90
+
91
+ def intern(self, path, *, expected_sha256=None):
92
+ """Atomically replace one sealed file by a byte-identical shared link.
93
+
94
+ Source stays available throughout, including on EXDEV or interruption.
95
+ Inputs must be closed evidence, never active mutable model checkpoints.
96
+ """
97
+ path = safe_path(path)
98
+ digest, before = file_identity(path)
99
+ if expected_sha256 is not None and digest != expected_sha256:
100
+ raise ValueError("source differs from frozen storage plan: " + str(path))
101
+ target = self.object_path(digest)
102
+ target.parent.mkdir(exist_ok=True)
103
+ if before.st_dev != self.root.stat().st_dev:
104
+ raise ValueError("shared storage requires the same filesystem")
105
+ # Seal before publication. Byte identity does not include permission bits.
106
+ os.chmod(path, stat.S_IMODE(before.st_mode) & ~0o222)
107
+ try:
108
+ os.link(path, target)
109
+ _fsync_dir(target.parent)
110
+ except FileExistsError:
111
+ pass
112
+ stored = self._check(target, digest, before.st_size)
113
+ current = path.stat()
114
+ if _identity(current) != _identity(before):
115
+ raise ValueError("source changed before shared-link replacement")
116
+ changed = (current.st_dev, current.st_ino) != (stored.st_dev, stored.st_ino)
117
+ released = current.st_size if changed and current.st_nlink == 1 else 0
118
+ blocks = current.st_blocks * 512 if changed and current.st_nlink == 1 else 0
119
+ if changed:
120
+ temporary = path.parent / (".mdb-share-" + uuid.uuid4().hex)
121
+ try:
122
+ os.link(target, temporary)
123
+ if _identity(path.stat()) != _identity(before):
124
+ raise ValueError("source changed during shared-link replacement")
125
+ os.replace(temporary, path)
126
+ _fsync_dir(path.parent)
127
+ finally:
128
+ temporary.unlink(missing_ok=True)
129
+ if not os.path.samefile(path, target):
130
+ raise ValueError("shared-link verification failed")
131
+ return {
132
+ "path": str(path),
133
+ "sha256": digest,
134
+ "bytes": before.st_size,
135
+ "object": str(target),
136
+ "relinked": changed,
137
+ "released_inode_logical_bytes": released,
138
+ "released_inode_stat_allocated_bytes": blocks,
139
+ }
140
+
141
+ def publish(self, path, raw):
142
+ """Publish immutable bytes via the pool; return local admission status."""
143
+ path = safe_path(path)
144
+ digest = hashlib.sha256(raw).hexdigest()
145
+ target = self.object_path(digest)
146
+ path.parent.mkdir(parents=True, exist_ok=True)
147
+ target.parent.mkdir(exist_ok=True)
148
+ if path.parent.stat().st_dev != self.root.stat().st_dev:
149
+ raise ValueError("shared storage requires the same filesystem")
150
+ if not target.exists():
151
+ fd, name = tempfile.mkstemp(dir=target.parent, prefix=".publish-")
152
+ temporary = Path(name)
153
+ try:
154
+ with os.fdopen(fd, "wb") as stream:
155
+ stream.write(raw)
156
+ stream.flush()
157
+ os.fsync(stream.fileno())
158
+ os.fchmod(stream.fileno(), 0o444)
159
+ try:
160
+ os.link(temporary, target)
161
+ _fsync_dir(target.parent)
162
+ except FileExistsError:
163
+ pass
164
+ finally:
165
+ temporary.unlink(missing_ok=True)
166
+ self._check(target, digest, len(raw))
167
+ try:
168
+ os.link(target, path)
169
+ _fsync_dir(path.parent)
170
+ return True
171
+ except FileExistsError:
172
+ actual, st = file_identity(path)
173
+ if actual != digest or st.st_size != len(raw):
174
+ raise ValueError("existing artifact differs from immutable shared bytes")
175
+ self.intern(path, expected_sha256=digest)
176
+ return False
177
+
178
+
179
+ def configure(scope, root):
180
+ scope, root = safe_path(scope), safe_path(root)
181
+ scope.mkdir(parents=True, exist_ok=True)
182
+ pool = SharedStore(root)
183
+ if scope.stat().st_dev != pool.root.stat().st_dev:
184
+ raise ValueError("configuration requires the same filesystem")
185
+ config = scope / CONFIG_NAME
186
+ body = (
187
+ json.dumps({"schema": SCHEMA, "root": str(root)}, sort_keys=True, indent=2) + "\n"
188
+ ).encode()
189
+ if config.exists():
190
+ if config.read_bytes() != body:
191
+ raise ValueError("storage scope is already configured differently")
192
+ else:
193
+ # Exclusive, small configuration file; existing configuration is never replaced.
194
+ with config.open("xb") as stream:
195
+ stream.write(body)
196
+ stream.flush()
197
+ os.fsync(stream.fileno())
198
+ _fsync_dir(scope)
199
+ return config
200
+
201
+
202
+ _EXPLICIT_ROOT = []
203
+
204
+
205
+ def set_shared_store(root):
206
+ """Name this process's shared tensor pool explicitly (``None`` clears it).
207
+
208
+ ``configured_store`` then uses ``root`` for every path, before the
209
+ ``MDB_SHARED_TENSOR_STORE`` environment fallback and any ``.mdb-storage.json``.
210
+ The root must be absolute (the pool and its clients share one filesystem).
211
+ """
212
+ if root is None:
213
+ _EXPLICIT_ROOT.clear()
214
+ return None
215
+ root = Path(root).expanduser()
216
+ if not root.is_absolute():
217
+ raise ValueError("a shared tensor store root must be an absolute path")
218
+ _EXPLICIT_ROOT[:] = [root]
219
+ return root
220
+
221
+
222
+ def shared_store_root():
223
+ """The explicitly set pool root, or None (environment and files are not consulted)."""
224
+ return _EXPLICIT_ROOT[0] if _EXPLICIT_ROOT else None
225
+
226
+
227
+ def configured_store(path):
228
+ """The pool for ``path``: the explicit root (``set_shared_store``), else the
229
+ ``MDB_SHARED_TENSOR_STORE`` environment variable, else the nearest ancestor
230
+ ``.mdb-storage.json``; None when none is configured."""
231
+ if _EXPLICIT_ROOT:
232
+ return SharedStore(_EXPLICIT_ROOT[0])
233
+ override = os.environ.get("MDB_SHARED_TENSOR_STORE")
234
+ if override:
235
+ return SharedStore(override)
236
+ path = safe_path(path)
237
+ for parent in path.parents:
238
+ config = parent / CONFIG_NAME
239
+ if config.exists():
240
+ config = safe_path(config)
241
+ value = json.loads(config.read_text())
242
+ if value.get("schema") != SCHEMA or not Path(value["root"]).is_absolute():
243
+ raise ValueError("invalid shared storage configuration")
244
+ return SharedStore(value["root"])
245
+ return None
246
+
247
+
248
+ def publish_configured(path, raw):
249
+ """None means unconfigured, preserving the caller's legacy publication."""
250
+ pool = configured_store(path)
251
+ return None if pool is None else pool.publish(path, raw)
252
+
253
+
254
+ def share_configured_file(path):
255
+ """Admit a closed NPY/safetensors export from an external scientific writer."""
256
+ pool = configured_store(path)
257
+ return None if pool is None else pool.intern(path)