basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/state_disk.py ADDED
@@ -0,0 +1,942 @@
1
+ """The disk tier of the state cache (basal-serve --state-cache-dir DIR, the CUDA graph engine): every state the cache
2
+ stores with its token ids is also written to DIR as one file, and read back on a memory miss (an exact state, or the
3
+ longest cached prefix of one), also after a restart.
4
+
5
+ Layout: DIR/<signature digest>/<first hex digit of the key>/<key>.state, one file per state: a safetensors-style file
6
+ (8-byte little-endian header length, a JSON header, the tensors' bytes) with per layer k.{i} and v.{i} [kv heads,
7
+ tokens, head size] as the memory entry holds them, and in the header's metadata the format, the signature, the state's
8
+ token ids and a blake2b digest of each tensor's bytes. No pickle: JSON and raw tensor bytes only.
9
+
10
+ DIR is trusted like the model's files: anyone who can write it as the server's user can put a state there that the
11
+ server will use. What the tier checks, and only that:
12
+ - DIR, its signature directory and their 16 subdirectories: created 0700, opened as directories without following a
13
+ symlink and checked on the open descriptor (a directory owned by this user, no group or other permissions); every
14
+ later file operation is relative to those descriptors, so a directory swapped after start-up is not followed. A
15
+ directory above DIR that others (not only its group) can write without the sticky bit refuses start-up; one its
16
+ group can write, or of another owner than root and this user, is named in a warning. Directories above DIR that do
17
+ not exist yet are made 0700. On network filesystems (NFS, SMB) owners and modes may mean little: not covered.
18
+ - One server per DIR and signature at a time (a lock file, flock). A second one waits up to LOCK_WAIT seconds for it
19
+ (a rolling restart: the old server writing what it queued), then starts without the tier and prints one line.
20
+ - The budget covers all of DIR: at start-up, the other signature directories (16 hex digits, with a lock file) are
21
+ counted, and while DIR is over budget_bytes, files of those no server holds (their lock free) that were not used for
22
+ OTHERS_AGE are removed, oldest first; one line totals them. No directory or lock file is ever removed.
23
+ - Files: created 0600 (O_EXCL, no symlink followed), synced before they replace their name, the directory synced
24
+ after (a filesystem that cannot sync a directory: one warning, the file kept); read only when opened without
25
+ following a symlink and without blocking (a FIFO), and when the descriptor shows a regular file of this user, 0600
26
+ or stricter.
27
+ - The signature (state_signature): what the keys and values depend on. The model's files (config.json and basal.json
28
+ whole; for each weight file the blob a Hugging Face snapshot's symlink names, its content hash (a snapshot's files
29
+ are trusted to be immutable), else the file's size, modification time and inode; and its full content digest), the adapter's identity, the dtype, quantisation and kernel
30
+ options, the state cache's bit depth (a state continued from a quantised prefix holds its rounding), and the basal,
31
+ torch, CUDA, transformers and GPU versions. A file must name it in its metadata, and it salts the keys.
32
+ - Before use: the token ids are a list of integers, the key is their keyed hash (StateCache.key), the token ids are
33
+ those the file was indexed with, every tensor's data has its digest, and every layer's keys / values the shape and
34
+ dtype this engine computes for a state of that many tokens (check). A file failing one of these content checks is
35
+ removed; one gone or not this user's any more is forgotten (written again at its next store); a read failing for
36
+ another reason (an I/O error, out of memory) keeps it and counts it.
37
+
38
+ Writes run on a background thread: save() copies the state into a pinned host arena of QUEUE_BYTES allocated at
39
+ start-up (on a side stream of the state's device, non-blocking) and queues that copy, never the GPU tensors; at most
40
+ QUEUE states. A state larger than the arena is written only when nothing else is queued (from a host buffer of its
41
+ own); a write dropped (the arena or queue full, or within RESERVE_BYTES of a full filesystem) keeps the file it would
42
+ have replaced, and is counted. A write or read that fails never fails a request: the state is then computed as without
43
+ the tier, the failure counted (errors) and its first occurrence of each kind printed as one line. The tier's lock
44
+ guards its index only: files are removed and written by the writer thread, outside it. A disk hit reads its file on the
45
+ engine thread (a hung network mount hangs those requests); the event loop and /metrics never wait on the disk. The
46
+ tier keeps at most budget_bytes of files, least recently used out first (a file read is touched, so a restart keeps
47
+ that order)."""
48
+ import hashlib
49
+ import json
50
+ import os
51
+ import queue
52
+ import stat
53
+ import struct
54
+ import sys
55
+ import threading
56
+ import time
57
+ import uuid
58
+ from collections import OrderedDict, deque
59
+ from concurrent.futures import ThreadPoolExecutor
60
+ from pathlib import Path
61
+
62
+ import numpy as np
63
+ import torch
64
+
65
+ try:
66
+ import fcntl
67
+ except ImportError: # (Windows: refused by supported())
68
+ fcntl = None
69
+
70
+ FORMAT = "3" # the file layout: bump when tensor names, metadata or the layout change
71
+ SUFFIX = ".state"
72
+ LOCK = ".basal-state-cache.lock" # in a signature directory: flock'ed by the server using it, never removed
73
+ DTYPES = {torch.bfloat16: "BF16", torch.float16: "F16", torch.float32: "F32"}
74
+ BY_NAME = {v: k for k, v in DTYPES.items()}
75
+ MAX_HEADER = 64 << 20 # a header holds the token ids as JSON: 64 MB is millions of tokens
76
+ MAX_TOKEN = 1 << 31
77
+ ALIGN = 64 # bytes: each tensor's copy in the arena starts on such a boundary
78
+ SAMPLES, SAMPLE = 16, 1 << 16 # bytes of each weight file hashed for the signature: 16 slices of 64 KiB
79
+ DIR_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
80
+ READ_FLAGS = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_CLOEXEC", 0)
81
+ WRITE_FLAGS = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0))
82
+ # blake2b of each tensor (hashlib releases the GIL): one pool for the writer, one for reads (a disk hit's digests never
83
+ # wait behind a background write's)
84
+ _DIGESTS_WRITE = ThreadPoolExecutor(max_workers=2, thread_name_prefix="basal-state-digest-w")
85
+ _DIGESTS_READ = ThreadPoolExecutor(max_workers=4, thread_name_prefix="basal-state-digest-r")
86
+
87
+
88
+ POSIX = "--state-cache-dir needs a POSIX system (Linux, macOS); on Windows run without it"
89
+
90
+
91
+ def supported():
92
+ """Whether the tier can run here: POSIX file owners and modes, flock and directory descriptors (Linux, macOS)."""
93
+ return fcntl is not None and hasattr(os, "getuid") and os.open in os.supports_dir_fd and os.unlink in \
94
+ os.supports_dir_fd
95
+
96
+
97
+ class Foreign(Exception):
98
+ """A file or directory this server does not own outright (another user's, open to others, not a regular file or
99
+ directory, a symlink): never used, never removed."""
100
+
101
+
102
+ class Busy(ValueError):
103
+ """DIR's signature directory stays locked by another server (LOCK_WAIT): the server runs without the tier."""
104
+
105
+
106
+ def _owned(st, what, kind):
107
+ """fstat checks: the kind (stat.S_ISDIR / S_ISREG), owned by this user, no group / other permissions."""
108
+ if not kind(st.st_mode):
109
+ raise Foreign(f"{what}: not a {'directory' if kind is stat.S_ISDIR else 'regular file'}")
110
+ if st.st_uid != os.getuid():
111
+ raise Foreign(f"{what}: owned by uid {st.st_uid}, not by this user ({os.getuid()})")
112
+ if st.st_mode & 0o077:
113
+ raise Foreign(f"{what}: open to other users (mode {stat.S_IMODE(st.st_mode):o})")
114
+
115
+
116
+ def check_ancestors(path):
117
+ """The directories above path (symlinks resolved): ValueError for one that others can write without the sticky
118
+ bit (anyone could rename DIR away and put another in its place); -> warnings (one line each) for one its group can
119
+ write, or of another owner than root and this user (they could do the same), which start-up accepts (user-private
120
+ groups, Kubernetes fsGroup and OpenShift volumes)."""
121
+ real = Path(os.path.realpath(path)).parent
122
+ warnings = []
123
+ for d in (real, *real.parents):
124
+ st = os.stat(d)
125
+ mode, sticky = stat.S_IMODE(st.st_mode), st.st_mode & stat.S_ISVTX
126
+ if mode & 0o002 and not sticky:
127
+ raise ValueError(f"--state-cache-dir: {d}, above DIR, is writable by all users (mode {mode:o}) without "
128
+ f"the sticky bit, so anyone could replace DIR: chmod o-w {d}, or add the sticky bit "
129
+ f"(chmod +t {d}), or choose a DIR under a directory only you can write")
130
+ if mode & 0o020 and not sticky:
131
+ warnings.append(f"basal: --state-cache-dir: {d}, above DIR, is writable by its group (mode {mode:o}): its "
132
+ f"members could replace DIR before a start-up (chmod g-w {d}, or a DIR under a directory "
133
+ "only you can write, if they are not to be trusted)")
134
+ if st.st_uid not in (0, os.getuid()):
135
+ warnings.append(f"basal: --state-cache-dir: {d}, above DIR, is owned by uid {st.st_uid}: that user could "
136
+ "replace DIR before a start-up")
137
+ return warnings
138
+
139
+
140
+ def private_dir(name, dir_fd=None, label=None):
141
+ """A directory only this user can use, created 0700 if missing -> its descriptor (O_DIRECTORY | O_NOFOLLOW),
142
+ checked on the descriptor: ValueError (what to fix, naming label: its full path) unless a directory of this user
143
+ with no group / other permissions. name is relative to dir_fd (None: a path)."""
144
+ label = label or name
145
+ if not supported():
146
+ raise ValueError(POSIX)
147
+ try:
148
+ os.mkdir(name, 0o700, dir_fd=dir_fd)
149
+ except FileExistsError:
150
+ pass
151
+ try:
152
+ fd = os.open(name, DIR_FLAGS, dir_fd=dir_fd)
153
+ except OSError as e:
154
+ raise ValueError(f"--state-cache-dir: {label} cannot be opened as a directory, not following a symlink "
155
+ f"({e.strerror})") from None
156
+ try:
157
+ _owned(os.fstat(fd), f"--state-cache-dir: {label}", stat.S_ISDIR)
158
+ except Foreign as e:
159
+ os.close(fd)
160
+ raise ValueError(f"{e}: chmod 700 {label}, or choose another directory" if "mode" in str(e) else str(e)) \
161
+ from None
162
+ return fd
163
+
164
+
165
+ def preflight(root):
166
+ """The checks of DIR that need no model, made before a server loads one (basal-serve): ValueError (what to fix,
167
+ one line) for a DIR under a directory all users can write without the sticky bit, or a DIR there already that is a
168
+ symlink, not a directory, another user's or open to others; OSError when a directory above it cannot be read.
169
+ Nothing is created (a missing DIR is made at start-up, 0700); the warnings of check_ancestors come at start-up."""
170
+ if not supported():
171
+ raise ValueError(POSIX)
172
+ base = Path(root).absolute()
173
+ top = base # (DIR, or the first part of it that does not exist yet: the directories above it are checked)
174
+ while not os.path.lexists(top.parent) and top.parent != top:
175
+ top = top.parent
176
+ check_ancestors(top)
177
+ if os.path.lexists(base):
178
+ parent = os.open(os.path.realpath(base.parent), DIR_FLAGS)
179
+ try:
180
+ os.close(private_dir(base.name, parent, str(base)))
181
+ finally:
182
+ os.close(parent)
183
+
184
+
185
+ def weights_identity(model_dir):
186
+ """Bind disk entries to complete local weight contents and the configuration."""
187
+ from .file_identity import verified_file
188
+ md = Path(model_dir)
189
+ h = hashlib.sha256()
190
+ for name in ("config.json", "basal.json"):
191
+ f = md / name
192
+ h.update(name.encode() + b"\0" + (f.read_bytes() if f.is_file() else b"-") + b"\0")
193
+ for f in sorted(list(md.glob("*.safetensors")) + list(md.glob("*.bin"))):
194
+ st = f.stat()
195
+ if f.is_symlink():
196
+ h.update(f"{f.name}\0blob\0{os.path.basename(os.readlink(f))}\0{st.st_size}\0".encode())
197
+ else:
198
+ h.update(f"{f.name}\0file\0{st.st_size}\0{st.st_mtime_ns}\0{st.st_ino}\0".encode())
199
+ _, digest = verified_file(f)
200
+ h.update(digest.encode())
201
+ return h.hexdigest()
202
+
203
+
204
+ def state_signature(model_dir, options, device=None):
205
+ """The signature of a server's cached states on disk, a JSON string: a server reads only files of its own.
206
+ options: what the engine was built with (dtype, quantisation, kernels, the adapter's identity, ...); device: where
207
+ it runs (its GPU name and compute capability)."""
208
+ import transformers
209
+
210
+ from . import __version__
211
+ gpu = None
212
+ if device is not None and torch.device(device).type == "cuda":
213
+ gpu = [torch.cuda.get_device_name(device), list(torch.cuda.get_device_capability(device))]
214
+ payload = {"format": FORMAT, "weights": weights_identity(model_dir), "options": options, "basal": __version__,
215
+ "torch": torch.__version__, "cuda": torch.version.cuda, "transformers": transformers.__version__,
216
+ "gpu": gpu}
217
+ return json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
218
+
219
+
220
+ def _strict_tokens(raw):
221
+ """Token ids from a file's metadata: a JSON list of non-negative integers below MAX_TOKEN, else ValueError."""
222
+ try:
223
+ tokens = json.loads(raw)
224
+ except (TypeError, ValueError, RecursionError) as e:
225
+ raise ValueError(f"token ids: {type(e).__name__}") from None
226
+ if not isinstance(tokens, list) or not all(type(t) is int and 0 <= t < MAX_TOKEN for t in tokens):
227
+ raise ValueError("token ids: not a list of integers")
228
+ return np.asarray(tokens, dtype=np.int64)
229
+
230
+
231
+ def _read_header(fd, size, what):
232
+ """(header JSON object, data offset) of an open file of size bytes; ValueError if malformed."""
233
+ raw = os.pread(fd, 8, 0)
234
+ if len(raw) != 8:
235
+ raise ValueError(f"{what}: truncated")
236
+ n = struct.unpack("<Q", raw)[0]
237
+ if n > MAX_HEADER or 8 + n > size:
238
+ raise ValueError(f"{what}: a header of {n} bytes")
239
+ raw = os.pread(fd, n, 8)
240
+ try:
241
+ header = json.loads(raw)
242
+ except (ValueError, RecursionError) as e:
243
+ raise ValueError(f"{what}: header: {type(e).__name__}") from None
244
+ if not isinstance(header, dict) or not isinstance(header.get("__metadata__"), dict):
245
+ raise ValueError(f"{what}: no metadata")
246
+ return header, 8 + n
247
+
248
+
249
+ def _digest(view):
250
+ return hashlib.blake2b(view, digest_size=32).hexdigest()
251
+
252
+
253
+ def _digests_written(items):
254
+ """The digests of a state's tensors, on the writer's pool; one after another once the interpreter is exiting:
255
+ Python shuts its pools down before the atexit callbacks, among them close, which writes what is still queued."""
256
+ try:
257
+ jobs = [_DIGESTS_WRITE.submit(_digest, x) for x in items]
258
+ except RuntimeError: # (cannot schedule new futures after interpreter shutdown)
259
+ return [_digest(x) for x in items]
260
+ return [j.result() for j in jobs]
261
+
262
+
263
+ def _lock(fd, wait):
264
+ """flock(fd) exclusively, waiting up to wait seconds -> whether it was taken."""
265
+ deadline = time.monotonic() + wait
266
+ while True:
267
+ try:
268
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
269
+ return True
270
+ except BlockingIOError:
271
+ if time.monotonic() >= deadline:
272
+ return False
273
+ time.sleep(0.25)
274
+
275
+
276
+ class DiskTier:
277
+ """See the module docstring. key(tokens): the cache's keyed hash; blocks(tokens): its chained block hashes (both
278
+ StateCache's); check(n, kv): raises ValueError unless kv is what this engine computes for a state of n tokens;
279
+ device: where loaded tensors go and where saved ones come from."""
280
+
281
+ QUEUE = 16
282
+ QUEUE_BYTES = 2 << 30 # the pinned host arena of the states queued for writing
283
+ RESERVE_BYTES = 1 << 30 # free space a write must leave on DIR's filesystem
284
+ LOCK_WAIT = 60.0 # seconds a server waits for DIR's lock (a rolling restart) before starting without the tier
285
+ OTHERS_AGE = 7 * 86400 # seconds: files of another signature unused for longer may go for the budget of all of DIR
286
+ SUBDIRS = "0123456789abcdef"
287
+
288
+ def __init__(self, root, budget_bytes, signature, key, blocks, check, device="cpu"):
289
+ self.signature, self.keyfn, self.blocksfn, self.check = signature, key, blocks, check
290
+ self.device = torch.device(device)
291
+ if not supported(): # (basal-serve refuses it before loading the model: state_disk_supported)
292
+ raise ValueError(POSIX)
293
+ base = Path(root).absolute()
294
+ for d in reversed([p for p in base.parents if not p.exists()]): # (made 0700, whatever the umask)
295
+ try:
296
+ os.mkdir(d, 0o700)
297
+ except FileExistsError:
298
+ pass
299
+ for line in check_ancestors(base):
300
+ print(line, file=sys.stderr, flush=True)
301
+ self.fds = [] # every descriptor this tier holds, closed by close() or a failed start
302
+ try:
303
+ self._start(base, budget_bytes)
304
+ except BaseException:
305
+ self._close_fds()
306
+ raise
307
+ self.thread = threading.Thread(target=self._writer, name="basal-state-cache-disk", daemon=True)
308
+ self.thread.start()
309
+
310
+ def _start(self, base, budget_bytes):
311
+ parent = os.open(os.path.realpath(base.parent), DIR_FLAGS)
312
+ try:
313
+ self.base_fd = private_dir(base.name, parent, str(base))
314
+ finally:
315
+ os.close(parent)
316
+ self.fds.append(self.base_fd)
317
+ self.base = base
318
+ self.digest = hashlib.sha256(self.signature.encode()).hexdigest()[:16]
319
+ self.root = base / self.digest # (for messages and tests; every operation goes through the descriptors)
320
+ self.fd = private_dir(self.digest, self.base_fd, str(self.root))
321
+ self.fds.append(self.fd)
322
+ self.lock_fd = self._lock_file(self.fd, self.root)
323
+ if not _lock(self.lock_fd, self.LOCK_WAIT):
324
+ raise Busy(f"basal: --state-cache-dir: {base} is in use by another server of this model and settings "
325
+ f"(still after {self.LOCK_WAIT:.0f} s): this server runs without the disk tier (give each "
326
+ "server its own DIR)")
327
+ self.dirs = {}
328
+ for s in self.SUBDIRS:
329
+ self.dirs[s] = private_dir(s, self.fd, str(self.root / s))
330
+ self.fds.append(self.dirs[s])
331
+ self.budget, self.used = int(budget_bytes), 0
332
+ self.entries, self.index, self.lock = OrderedDict(), {}, threading.Lock() # key -> (size, tokens, blocks)
333
+ self.loads = self.prefix_loads = self.writes = self.write_drops = self.errors = self.evictions = 0
334
+ self.closed, self.pending, self.cancelled, self.oversize = False, set(), set(), False
335
+ self.trash, self.touch = [], [] # keys whose files the writer removes / touches (read: recently used)
336
+ self.warned = set() # the kinds of failure printed once already (warn)
337
+ self.last_stats = None
338
+ self.stream = None # the side stream of the host copies (CUDA)
339
+ cuda = self.device.type == "cuda"
340
+ self.arena = torch.empty(self.QUEUE_BYTES, dtype=torch.uint8, pin_memory=cuda) # (allocated once, here)
341
+ self.regions = deque() # arena spans (start, end) of the queued states, in queue order
342
+ self.queue = queue.Queue(maxsize=self.QUEUE)
343
+ self.scan()
344
+ try:
345
+ self._scan_others()
346
+ except Exception as e: # (housekeeping never fails start-up)
347
+ print(f"basal: --state-cache-dir: the other signature directories under {self.base} were not counted "
348
+ f"({type(e).__name__}: {e})", file=sys.stderr, flush=True)
349
+
350
+ def _lock_file(self, d, where):
351
+ fd = os.open(LOCK, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0),
352
+ 0o600, dir_fd=d)
353
+ self.fds.append(fd)
354
+ try:
355
+ _owned(os.fstat(fd), f"{where}/{LOCK}", stat.S_ISREG)
356
+ except Foreign as e:
357
+ raise ValueError(f"--state-cache-dir: {e}") from None
358
+ return fd
359
+
360
+ def _close_fds(self):
361
+ for fd in reversed(self.fds):
362
+ try:
363
+ os.close(fd) # (the lock's: the flock is released with it)
364
+ except OSError:
365
+ pass
366
+ self.fds = []
367
+
368
+ @staticmethod
369
+ def _name(key):
370
+ return f"{key.hex()}{SUFFIX}"
371
+
372
+ def _dir(self, key):
373
+ return self.dirs[key.hex()[0]]
374
+
375
+ def warn(self, what, e):
376
+ """Counts a failure; prints its first occurrence of this kind (what, the exception's type and errno) as one
377
+ line, and says that the server goes on without the tier for that state."""
378
+ kind = (what, type(e).__name__, getattr(e, "errno", None))
379
+ with self.lock:
380
+ self.errors += 1
381
+ if kind in self.warned:
382
+ return
383
+ self.warned.add(kind)
384
+ print(f"basal: --state-cache-dir: a state was not {what} ({type(e).__name__}: {e}); the request is answered "
385
+ "as without it (further failures of this kind are counted in basal_state_cache_disk_errors_total, not "
386
+ "printed)", file=sys.stderr, flush=True)
387
+
388
+ def _verify(self, md, key, what):
389
+ """A file's metadata -> its token ids [n] int64, or ValueError: another format or signature, token ids that
390
+ are not a list of integers, or a key that is not their keyed hash."""
391
+ if md.get("format") != FORMAT or md.get("signature") != self.signature:
392
+ raise ValueError(f"{what}: another format or signature")
393
+ tokens = _strict_tokens(md.get("tokens"))
394
+ if self.keyfn(tokens) != key:
395
+ raise ValueError(f"{what}: its key is not the hash of its token ids")
396
+ return tokens
397
+
398
+ @staticmethod
399
+ def _open(d, name):
400
+ """A file opened for reading (no symlink followed, no blocking on a FIFO) and checked on its descriptor ->
401
+ (fd, its stat); Foreign if not a regular file of this user, 0600 or stricter."""
402
+ fd = os.open(name, READ_FLAGS, dir_fd=d)
403
+ try:
404
+ st = os.fstat(fd)
405
+ _owned(st, name, stat.S_ISREG)
406
+ except BaseException:
407
+ os.close(fd)
408
+ raise
409
+ return fd, st
410
+
411
+ def scan(self):
412
+ """Indexes this signature's files from their headers (not their tensors), oldest first; removes temporary files
413
+ (a crashed writer's: this server holds the directory's lock). A file failing a content check is removed, one
414
+ that is not this user's (Foreign) or cannot be read is left; each is counted, and the total printed. (Before
415
+ the writer starts: the files are removed here.)"""
416
+ found, refused, bad = [], 0, []
417
+ for s, d in self.dirs.items():
418
+ for entry in os.scandir(d):
419
+ name = entry.name
420
+ try:
421
+ if ".tmp-" in name:
422
+ if entry.is_file(follow_symlinks=False):
423
+ os.unlink(name, dir_fd=d)
424
+ continue
425
+ if not name.endswith(SUFFIX):
426
+ continue
427
+ key = bytes.fromhex(name[: -len(SUFFIX)])
428
+ if key.hex()[0] != s:
429
+ raise ValueError(f"{name}: in the wrong directory")
430
+ fd, st = self._open(d, name)
431
+ try:
432
+ header, _ = _read_header(fd, st.st_size, name)
433
+ finally:
434
+ os.close(fd)
435
+ tokens = self._verify(header["__metadata__"], key, name)
436
+ found.append((st.st_mtime, key, st.st_size, tokens))
437
+ except FileNotFoundError:
438
+ continue
439
+ except ValueError: # (a content check: one of ours, damaged)
440
+ refused += 1
441
+ bad.append((d, name))
442
+ except Exception: # (Foreign, an I/O error, ...: left as it is)
443
+ refused += 1
444
+ for d, name in bad:
445
+ try:
446
+ os.unlink(name, dir_fd=d)
447
+ except OSError:
448
+ pass
449
+ if refused:
450
+ print(f"basal: --state-cache-dir: {refused} file(s) under {self.root} not used (not this user's, open to "
451
+ "others, not a regular file, of another signature or damaged; the damaged ones removed)",
452
+ file=sys.stderr, flush=True)
453
+ with self.lock:
454
+ self.errors += refused
455
+ for _, key, size, tokens in sorted(found, key=lambda x: x[0]):
456
+ if key not in self.entries:
457
+ self._add(key, size, tokens, self.blocksfn(tokens))
458
+ self._evict()
459
+ keys, self.trash = self.trash, []
460
+ for key in keys:
461
+ try:
462
+ os.unlink(self._name(key), dir_fd=self._dir(key))
463
+ except OSError:
464
+ pass
465
+
466
+ def _scan_others(self):
467
+ """The budget over all of DIR: the other signature directories (16 hex digits, with a lock file: another model's
468
+ files, version or setting) are counted, and, while DIR is over budget_bytes, files of those no server holds
469
+ (their lock free) that were not used for OTHERS_AGE (a read touches a file) are removed, oldest first. A
470
+ directory another server holds is counted, never touched; no lock file and no directory is ever removed.
471
+ One line totals them. A file or directory that cannot be read is skipped."""
472
+ others, held, files = 0, [], []
473
+ now = time.time()
474
+ try:
475
+ for entry in os.scandir(self.base_fd):
476
+ name = entry.name
477
+ try:
478
+ if name == self.digest or len(name) != 16 or any(c not in "0123456789abcdef" for c in name) \
479
+ or not entry.is_dir(follow_symlinks=False):
480
+ continue
481
+ fd = os.open(name, DIR_FLAGS, dir_fd=self.base_fd)
482
+ except OSError:
483
+ continue
484
+ try:
485
+ _owned(os.fstat(fd), name, stat.S_ISDIR)
486
+ lock = os.open(LOCK, os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0),
487
+ dir_fd=fd) # (no lock file: not a signature directory)
488
+ except (OSError, Foreign):
489
+ os.close(fd)
490
+ continue
491
+ others += 1
492
+ free = _lock(lock, 0)
493
+ held.append((name, fd, lock, free))
494
+ for sub in self.SUBDIRS:
495
+ try:
496
+ sd = os.open(sub, DIR_FLAGS, dir_fd=fd)
497
+ except OSError:
498
+ continue
499
+ try:
500
+ for f in os.scandir(sd):
501
+ try:
502
+ if f.name.endswith(SUFFIX) and f.is_file(follow_symlinks=False):
503
+ st = f.stat(follow_symlinks=False)
504
+ files.append((st.st_mtime, st.st_size, name, sub, f.name, free))
505
+ except OSError: # (removed meanwhile by the server that holds it)
506
+ continue
507
+ except OSError:
508
+ pass
509
+ finally:
510
+ os.close(sd)
511
+ total = sum(x[1] for x in files)
512
+ over, removed = self.used + total - self.budget, 0
513
+ for mtime, size, name, sub, fname, free in sorted(files):
514
+ if over <= 0:
515
+ break
516
+ if not free or now - mtime < self.OTHERS_AGE:
517
+ continue
518
+ fd = next(h[1] for h in held if h[0] == name)
519
+ try:
520
+ sd = os.open(sub, DIR_FLAGS, dir_fd=fd)
521
+ try:
522
+ os.unlink(fname, dir_fd=sd)
523
+ finally:
524
+ os.close(sd)
525
+ over -= size
526
+ removed += size
527
+ except OSError:
528
+ pass
529
+ if others:
530
+ print(f"basal: --state-cache-dir: {others} other signature director{'y' if others == 1 else 'ies'} "
531
+ f"(other model files, versions or settings) under {self.base} held {total / 2 ** 30:.2f} GB in "
532
+ f"{len(files)} files; {removed / 2 ** 30:.2f} GB of files unused for "
533
+ f"{self.OTHERS_AGE / 86400:.0f} days removed to keep DIR within --state-cache-disk-gb",
534
+ file=sys.stderr, flush=True)
535
+ finally:
536
+ for _, fd, lock, _ in held:
537
+ for x in (lock, fd):
538
+ try:
539
+ os.close(x)
540
+ except OSError:
541
+ pass
542
+
543
+ def _add(self, key, size, tokens, blocks):
544
+ """Indexes a file (lock held)."""
545
+ if key in self.entries:
546
+ self.used -= self.entries.pop(key)[0]
547
+ self.entries[key] = (size, tokens, blocks)
548
+ self.used += size
549
+ for h in blocks:
550
+ self.index.setdefault(h, {})[key] = None
551
+
552
+ def _evict(self):
553
+ """Least recently used files out of the index until the tier fits its budget (lock held; removed by the
554
+ writer)."""
555
+ while self.used > self.budget and self.entries:
556
+ self._forget(next(iter(self.entries)))
557
+ self.evictions += 1
558
+
559
+ def _forget(self, key, trash=True):
560
+ """Takes an entry off the index, and (trash) its file onto the writer's trash (lock held: no I/O)."""
561
+ e = self.entries.pop(key, None)
562
+ if e is None:
563
+ return
564
+ size, _, blocks = e
565
+ self.used -= size
566
+ for h in blocks:
567
+ keys = self.index.get(h)
568
+ if keys is not None:
569
+ keys.pop(key, None)
570
+ if not keys:
571
+ del self.index[h]
572
+ if trash:
573
+ self.trash.append(key)
574
+
575
+ def _empty_trash(self):
576
+ """Removes the trashed files and touches the files read (the writer thread only; no lock held meanwhile)."""
577
+ with self.lock:
578
+ keys, self.trash = self.trash, []
579
+ touch, self.touch = self.touch, []
580
+ for key in keys:
581
+ try:
582
+ os.unlink(self._name(key), dir_fd=self._dir(key))
583
+ except FileNotFoundError:
584
+ pass
585
+ except OSError as e:
586
+ self.warn("removed", e)
587
+ for key in touch:
588
+ try:
589
+ os.utime(self._name(key), dir_fd=self._dir(key), follow_symlinks=False)
590
+ except OSError:
591
+ pass
592
+
593
+ def _carve(self, n):
594
+ """An arena span of n bytes after the queued ones (a ring: written in queue order, so freed in that order) ->
595
+ its start, or None if the arena has no room (lock held)."""
596
+ cap = self.arena.numel()
597
+ if n > cap:
598
+ return None
599
+ if not self.regions:
600
+ start = 0
601
+ else:
602
+ first, last_end = self.regions[0][0], self.regions[-1][1]
603
+ if self.regions[-1][0] < first: # wrapped: free is [last_end, first)
604
+ start = last_end if last_end + n <= first else None
605
+ else: # free is [last_end, cap) and [0, first)
606
+ start = last_end if last_end + n <= cap else 0 if n <= first else None
607
+ if start is not None:
608
+ self.regions.append((start, start + n))
609
+ return start
610
+
611
+ def _host(self, kv, start):
612
+ """Copies of a state's tensors in host memory -> (copies, CUDA event or None): views of the arena from start
613
+ (None: a buffer of its own, for a state larger than the arena), filled on a side stream of the device after
614
+ its current stream (non-blocking; the GPU tensors marked as used by that stream, so their memory is not reused
615
+ before the copy ran). The queue then holds these copies only."""
616
+ cuda = any(t.is_cuda for k, v in kv for t in (k, v))
617
+ sizes = [t.numel() * t.element_size() for k, v in kv for t in (k, v)]
618
+ spans = np.cumsum([0] + [-(-n // ALIGN) * ALIGN for n in sizes])
619
+ buf = self.arena[start:] if start is not None else torch.empty(int(spans[-1]), dtype=torch.uint8,
620
+ pin_memory=cuda)
621
+ flat = [t for k, v in kv for t in (k, v)]
622
+ dst = [buf[int(a): int(a) + n].view(t.dtype).view(t.shape) for t, a, n in zip(flat, spans, sizes)]
623
+ if not cuda:
624
+ for h, t in zip(dst, flat):
625
+ h.copy_(t)
626
+ return list(zip(dst[0::2], dst[1::2])), None
627
+ dev = flat[0].device
628
+ with torch.cuda.device(dev):
629
+ if self.stream is None or self.stream.device != dev:
630
+ self.stream = torch.cuda.Stream(device=dev)
631
+ s = self.stream
632
+ s.wait_stream(torch.cuda.current_stream(dev))
633
+ with torch.cuda.stream(s):
634
+ for h, t in zip(dst, flat):
635
+ h.copy_(t.detach(), non_blocking=True)
636
+ t.record_stream(s)
637
+ ev = torch.cuda.Event()
638
+ ev.record(s)
639
+ return list(zip(dst[0::2], dst[1::2])), ev
640
+
641
+ def save(self, key, kv, tokens, replaces=None):
642
+ """Queues a state for writing (per layer (K, V) [kv heads, tokens, head size]) as host copies; False when the
643
+ write is dropped (the arena or the queue full, or the tier closed): the file it would replace is kept.
644
+ replaces: the key of a state this one extends; its file goes once this one is written."""
645
+ size = sum(-(-t.numel() * t.element_size() // ALIGN) * ALIGN for k, v in kv for t in (k, v))
646
+ with self.lock:
647
+ if self.closed:
648
+ self.write_drops += 1
649
+ return False
650
+ if key in self.entries: # on disk already (a file's content is a function of its key)
651
+ self.entries.move_to_end(key)
652
+ if replaces is not None and replaces != key:
653
+ self._forget(replaces)
654
+ return True
655
+ self.cancelled.discard(key)
656
+ if key in self.pending:
657
+ if replaces is not None and replaces != key:
658
+ self._delete(replaces)
659
+ return True
660
+ if self.queue.full():
661
+ self.write_drops += 1
662
+ return False
663
+ start = self._carve(size)
664
+ if start is None and (size <= self.arena.numel() or self.regions or not self.queue.empty()
665
+ or self.oversize):
666
+ self.write_drops += 1 # (one larger than the arena: only when nothing else is queued)
667
+ return False
668
+ self.pending.add(key)
669
+ if start is not None:
670
+ try: # (under the lock: the arena's spans and the queue in one order)
671
+ host, ev = self._host(kv, start)
672
+ self.queue.put_nowait((key, host, ev, np.asarray(tokens, dtype=np.int64), replaces, start))
673
+ except BaseException as e:
674
+ self.regions.pop()
675
+ self.pending.discard(key)
676
+ self.write_drops += 1
677
+ if isinstance(e, queue.Full): # (a flush() marker took the last place meanwhile)
678
+ return False
679
+ raise
680
+ return True
681
+ self.oversize = True # (one at a time; copied below, outside the lock)
682
+ try:
683
+ host = [(k.detach().to("cpu", copy=True), v.detach().to("cpu", copy=True)) for k, v in kv] # (pageable)
684
+ with self.lock:
685
+ self.queue.put_nowait((key, host, None, np.asarray(tokens, dtype=np.int64), replaces, None))
686
+ except BaseException as e:
687
+ with self.lock:
688
+ self.pending.discard(key)
689
+ self.write_drops += 1
690
+ self.oversize = False
691
+ if isinstance(e, queue.Full):
692
+ return False
693
+ raise
694
+ return True
695
+
696
+ def _meta(self, layers, tokens, digests):
697
+ return {"format": FORMAT, "signature": self.signature, "tokens": json.dumps([int(t) for t in tokens]),
698
+ "layers": str(layers), "digests": json.dumps(digests), "created": str(int(time.time()))}
699
+
700
+ def _write(self, d, name, kv, tokens):
701
+ """A state file name in directory d (created 0600, exclusive, no symlink followed), synced -> its size."""
702
+ header, items, offset = {}, [], 0
703
+ for i, (k, v) in enumerate(kv):
704
+ for x, t in ((f"k.{i}", k), (f"v.{i}", v)):
705
+ data = memoryview(t.view(torch.uint8).numpy()).cast("B") if t.numel() else memoryview(b"")
706
+ header[x] = {"dtype": DTYPES[t.dtype], "shape": list(t.shape),
707
+ "data_offsets": [offset, offset + len(data)]}
708
+ items.append(data)
709
+ offset += len(data)
710
+ header["__metadata__"] = self._meta(len(kv), tokens, _digests_written(items))
711
+ raw = json.dumps(header, separators=(",", ":")).encode()
712
+ raw += b" " * (-len(raw) % 8)
713
+ fd = os.open(name, WRITE_FLAGS, 0o600, dir_fd=d)
714
+ try:
715
+ with os.fdopen(fd, "wb", closefd=False) as f:
716
+ f.write(struct.pack("<Q", len(raw)))
717
+ f.write(raw)
718
+ for data in items:
719
+ f.write(data)
720
+ os.fsync(fd)
721
+ finally:
722
+ os.close(fd)
723
+ return 8 + len(raw) + offset
724
+
725
+ _FLUSH = object() # a queue item that only empties the trash (flush)
726
+
727
+ def _writer(self):
728
+ while True:
729
+ try:
730
+ item = self.queue.get(timeout=0.5)
731
+ except queue.Empty:
732
+ self._empty_trash()
733
+ continue
734
+ try:
735
+ if item is None:
736
+ self._empty_trash()
737
+ return
738
+ if item is not self._FLUSH:
739
+ self._write_one(*item)
740
+ finally:
741
+ item = None # (the host copies are released here, not at the next item)
742
+ self._empty_trash()
743
+ self.queue.task_done()
744
+
745
+ def _write_one(self, key, host, ev, tokens, replaces, start):
746
+ d, name = self._dir(key), self._name(key)
747
+ tmp = f"{name}.tmp-{uuid.uuid4().hex}"
748
+ try:
749
+ if ev is not None:
750
+ ev.synchronize()
751
+ fs = os.fstatvfs(d)
752
+ size = sum(k.nbytes + v.nbytes for k, v in host)
753
+ if fs.f_bavail * fs.f_frsize < size + self.RESERVE_BYTES:
754
+ raise OSError(28, f"less than {self.RESERVE_BYTES >> 20} MiB would be left free")
755
+ written = self._write(d, tmp, host, tokens)
756
+ os.replace(tmp, name, src_dir_fd=d, dst_dir_fd=d)
757
+ except Exception as e: # (a full disk) the server goes on without this file
758
+ self.warn("written", e)
759
+ with self.lock:
760
+ self.pending.discard(key)
761
+ self.cancelled.discard(key)
762
+ if start is not None:
763
+ self.regions.popleft()
764
+ else:
765
+ self.oversize = False
766
+ try:
767
+ os.unlink(tmp, dir_fd=d)
768
+ except OSError:
769
+ pass
770
+ return
771
+ finally:
772
+ host = None
773
+ try:
774
+ os.fsync(d) # (the new name on disk)
775
+ except OSError as e: # (a filesystem that cannot sync a directory: the file is in place, kept and indexed)
776
+ self.warn("synced to disk with its directory", e)
777
+ with self.lock:
778
+ self.pending.discard(key)
779
+ if start is not None:
780
+ self.regions.popleft()
781
+ else:
782
+ self.oversize = False
783
+ if key in self.cancelled: # deleted while queued
784
+ self.cancelled.discard(key)
785
+ self.trash.append(key)
786
+ return
787
+ if key in self.trash: # (its earlier file, forgotten before this one was stored: the name holds this one)
788
+ self.trash = [k for k in self.trash if k != key]
789
+ if replaces is not None and replaces != key:
790
+ self._forget(replaces)
791
+ self._add(key, written, tokens, self.blocksfn(tokens))
792
+ self.writes += 1
793
+ self._evict()
794
+
795
+ def _read(self, key, own):
796
+ """A file's keys / values on self.device and its token ids, every check of the module docstring passed;
797
+ ValueError (a content check), Foreign, FileNotFoundError or another exception (I/O, memory) otherwise. Each
798
+ tensor's digest is computed on a thread pool while the next one is read."""
799
+ d, name = self._dir(key), self._name(key)
800
+ fd, st = self._open(d, name)
801
+ size = st.st_size
802
+ try:
803
+ header, start = _read_header(fd, size, name)
804
+ md = header.pop("__metadata__")
805
+ tokens = self._verify(md, key, name)
806
+ if not np.array_equal(tokens, own):
807
+ raise ValueError(f"{name}: not the indexed state")
808
+ try:
809
+ layers = int(md.get("layers", -1))
810
+ digests = json.loads(md.get("digests", "null"))
811
+ if set(header) != {f"{x}.{i}" for i in range(layers) for x in "kv"} \
812
+ or not isinstance(digests, list) or len(digests) != 2 * layers:
813
+ raise ValueError(f"{name}: not {layers} layers of keys and values with their digests")
814
+ end, spans = size - start, []
815
+ for i in range(layers):
816
+ for x in "kv":
817
+ h = header[f"{x}.{i}"]
818
+ dt = BY_NAME.get(h.get("dtype"))
819
+ shape, (a, b) = [int(s) for s in h["shape"]], [int(o) for o in h["data_offsets"]]
820
+ n = int(np.prod(shape)) if shape else 1
821
+ if dt is None or min(shape, default=0) < 0 or not 0 <= a <= b <= end \
822
+ or b - a != n * torch.empty((), dtype=dt).element_size():
823
+ raise ValueError(f"{name}: {x}.{i}: dtype, shape or data offsets")
824
+ spans.append((dt, shape, a, b))
825
+ except (TypeError, KeyError, AttributeError) as e:
826
+ raise ValueError(f"{name}: header: {type(e).__name__}") from None
827
+ buf = torch.empty(max([b for *_, b in spans], default=0), dtype=torch.uint8)
828
+ view, jobs = memoryview(buf.numpy()), []
829
+ os.lseek(fd, start, os.SEEK_SET)
830
+ with os.fdopen(fd, "rb", buffering=0, closefd=False) as f:
831
+ for _, _, a, b in spans:
832
+ done = a
833
+ while done < b:
834
+ got = f.readinto(view[done:b])
835
+ if not got:
836
+ raise ValueError(f"{name}: truncated data")
837
+ done += got
838
+ jobs.append(_DIGESTS_READ.submit(_digest, view[a:b]))
839
+ finally:
840
+ os.close(fd)
841
+ if [j.result() for j in jobs] != digests:
842
+ raise ValueError(f"{name}: its data does not match its digests")
843
+ flat = [buf[a:b].view(dt).view(shape) for dt, shape, a, b in spans]
844
+ kv = list(zip(flat[0::2], flat[1::2]))
845
+ self.check(len(tokens), kv) # (the shapes and dtype this engine computes for that many tokens)
846
+ return [(k.to(self.device), v.to(self.device)) for k, v in kv], tokens
847
+
848
+ def load(self, key):
849
+ """A state's (keys / values, token ids) read from its file, or None: not on disk, or not usable (counted; one
850
+ that fails a content check is removed by the writer, one gone or not this user's any more is forgotten, so
851
+ that it is written again, one unreadable for another reason kept)."""
852
+ with self.lock:
853
+ e = self.entries.get(key)
854
+ if e is None:
855
+ return None
856
+ self.entries.move_to_end(key)
857
+ own = e[1]
858
+ try:
859
+ kv, tokens = self._read(key, own)
860
+ except ValueError as x: # a content check: the file is wrong
861
+ self.warn("read", x)
862
+ with self.lock:
863
+ if self.entries.get(key) is e:
864
+ self._forget(key)
865
+ return None
866
+ except (FileNotFoundError, Foreign) as x: # (removed or chmodded behind the server's back)
867
+ self.warn("read", x)
868
+ with self.lock:
869
+ if self.entries.get(key) is e:
870
+ self._forget(key, trash=False)
871
+ return None
872
+ except Exception as x: # (an I/O error, out of memory: kept)
873
+ self.warn("read", x)
874
+ return None
875
+ with self.lock:
876
+ self.loads += 1
877
+ self.touch.append(key)
878
+ return kv, tokens
879
+
880
+ def best(self, tokens, blocks):
881
+ """(key, matched length) of the file sharing the longest prefix with tokens (the most recent of equals), or
882
+ None: the deepest of these chained block hashes any file holds, only that block's files compared."""
883
+ t = np.asarray(tokens, dtype=np.int64)
884
+ with self.lock:
885
+ for h in reversed(blocks):
886
+ keys = self.index.get(h)
887
+ if not keys:
888
+ continue
889
+ best, matched = None, -1
890
+ for key in reversed(keys):
891
+ own = self.entries[key][1]
892
+ n = min(len(own), len(t))
893
+ diff = np.nonzero(own[:n] != t[:n])[0]
894
+ m = int(diff[0]) if len(diff) else n
895
+ if m > matched:
896
+ best, matched = key, m
897
+ return best, matched
898
+ return None
899
+
900
+ def has(self, key):
901
+ with self.lock:
902
+ return key in self.entries
903
+
904
+ def delete(self, key):
905
+ """Removes a state's file (by the writer thread); one still queued is removed once written."""
906
+ with self.lock:
907
+ self._delete(key)
908
+
909
+ def _delete(self, key):
910
+ if key in self.pending:
911
+ self.cancelled.add(key)
912
+ self._forget(key)
913
+
914
+ def flush(self):
915
+ """Waits until every queued write is on disk and the writer has emptied the trash."""
916
+ self.queue.put(self._FLUSH)
917
+ self.queue.join()
918
+
919
+ def close(self):
920
+ """Writes what is queued, then stops the writer and closes the directories (releasing the lock); later saves
921
+ are dropped."""
922
+ with self.lock:
923
+ if self.closed:
924
+ return
925
+ self.closed = True
926
+ self.queue.put(None)
927
+ self.thread.join()
928
+ self._close_fds()
929
+
930
+ def stats(self, blocking=True):
931
+ """A snapshot of the counters; nonblocking readers get the last one while the index is busy."""
932
+ if not self.lock.acquire(blocking=blocking):
933
+ return self.last_stats
934
+ try:
935
+ self.last_stats = dict(disk_entries=len(self.entries), disk_bytes=self.used,
936
+ disk_budget_bytes=self.budget, disk_loads=self.loads,
937
+ disk_prefix_loads=self.prefix_loads, disk_writes=self.writes,
938
+ disk_write_drops=self.write_drops, disk_errors=self.errors,
939
+ disk_evictions=self.evictions)
940
+ return self.last_stats
941
+ finally:
942
+ self.lock.release()