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/ui.py ADDED
@@ -0,0 +1,526 @@
1
+ """basal-serve --ui on (2.5): a live page of the server at GET /ui (status, traffic since start, state cache, telemetry,
2
+ configuration, recent requests), read from GET /ui/state.
3
+
4
+ The page (ui.html and its fonts, shipped in the package; no build step, no CDN) is open, so it can ask for the API key;
5
+ GET /ui/state needs a key when --api-keys is set. A decision request pays one append to a bounded ring: its metadata
6
+ (end time, endpoint, status, seconds, questions, options; never the request's text). Everything else (totals since
7
+ start, percentiles, rates, telemetry, configuration) is computed when GET /ui/state is read, at most once a second
8
+ however many pages poll it, and lives in memory only: every start begins at zero. GPU telemetry (NVML, from
9
+ nvidia-ml-py) and host telemetry (psutil) are read when installed, once a second in a side thread that runs only while a
10
+ page polled in the last 10 seconds; never a torch.cuda call. With --ui off (the default) none of this module is
11
+ imported and basal-serve handles requests as without it.
12
+
13
+ --ui full also keeps references to the last RECENT requests' parsed bodies and their answers (the bytes already sent),
14
+ no copy and no serialisation on the request path, at most FULL_BYTES of them (their bodies and answers as sent, the
15
+ newest always); GET /ui/request/<id> serialises one of them when the page asks
16
+ (behind the same key check as /ui/state; with --api-keys, only for the key that made the request or an admin key: the
17
+ keys are clients, who do not read each other's documents). They live in memory only, like everything here."""
18
+ import bisect
19
+ import itertools
20
+ import json
21
+ import math
22
+ import os
23
+ import sys
24
+ import threading
25
+ import time
26
+ from collections import deque
27
+ from importlib import metadata
28
+ from operator import itemgetter
29
+ from pathlib import Path
30
+ from urllib.parse import urlsplit, urlunsplit
31
+
32
+ HERE = Path(__file__).parent
33
+ RING = 16384 # requests kept (recent rows, the last minute's rates and percentiles; folded into the totals at a read)
34
+ FOLD = 2048 # requests folded into the totals at one read at most (a read's work stays bounded; the rest at the next)
35
+ RECENT = 200 # rows of the recent-requests table
36
+ FULL_BYTES = 256 * 2**20 # --ui full: the kept requests' bodies and answers together (as sent), the oldest dropped first
37
+ MEMO_S = 1.0 # GET /ui/state is built at most once per MEMO_S, however many pages poll it
38
+ IDLE_S = 10.0 # telemetry stops sampling this long after the last GET /ui/state
39
+ DECISIONS = ("/v1/systemone", "/v1/basal", "/v1/decisions") # the routes whose requests are recorded
40
+ FONTS = ("dm-sans-latin.woff2", "dm-sans-latin-ext.woff2", "space-grotesk-latin.woff2",
41
+ "space-grotesk-latin-ext.woff2", "OFL-DMSans.txt", "OFL-SpaceGrotesk.txt")
42
+ SECRET = {"key", "keys", "token", "secret", "password", "passwd", "auth", "credentials"} # words of a secret's name
43
+ PACKAGES = ("torch", "transformers", "vllm", "sglang", "mlx", "mlx-lm", "llama-cpp-python", "torchao", "triton",
44
+ "flash-attn", "starlette", "uvicorn", "nvidia-ml-py", "psutil")
45
+ END = itemgetter(0) # a ring row's end time
46
+ HEADERS = { # the page: nothing from outside this server, never framed, no referrer
47
+ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
48
+ "font-src 'self'; connect-src 'self'; img-src 'self' data:; frame-ancestors 'none'; "
49
+ "base-uri 'none'; form-action 'none'",
50
+ "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", "Cache-Control": "no-cache"}
51
+
52
+
53
+ def size(body):
54
+ """(questions, options) of a decision request body for the recent-requests table: the options of a question are its
55
+ criteria, choices, levels or tools (2 for a yes / no question without them). Never raises: (None, None) for a body
56
+ it cannot read (not parsed, not JSON)."""
57
+ try:
58
+ qs = body["questions"]
59
+ n = k = 0
60
+ for q in qs.values() if isinstance(qs, dict) else qs: # /v1/systemone, /v1/basal: a dict; /v1/decisions: a list
61
+ c = q.get("criteria") or q.get("choices") or q.get("levels") or q.get("tools")
62
+ n, k = n + 1, k + (len(c) if c else 2)
63
+ return n, k
64
+ except Exception: # noqa: BLE001
65
+ return None, None
66
+
67
+
68
+ class Hist:
69
+ """Latencies (ms) in log-spaced bins 1% wide: percentiles since start in bounded memory, within 1%."""
70
+ STEP = math.log(1.01)
71
+
72
+ def __init__(self):
73
+ self.bins, self.n, self.sum, self.max = {}, 0, 0.0, 0.0
74
+
75
+ @classmethod
76
+ def bin(cls, ms):
77
+ return math.floor(math.log(max(ms, 1e-3)) / cls.STEP)
78
+
79
+ def add(self, ms, i=None):
80
+ i = self.bin(ms) if i is None else i
81
+ self.bins[i] = self.bins.get(i, 0) + 1
82
+ self.n, self.sum, self.max = self.n + 1, self.sum + ms, max(self.max, ms)
83
+
84
+ def quantiles(self, qs=(0.5, 0.95, 0.99)):
85
+ """Nearest-rank quantiles: the geometric middle of the bin that holds each rank (at most the maximum)."""
86
+ if not self.n:
87
+ return [None] * len(qs)
88
+ ranks, out, acc = [max(1, math.ceil(q * self.n)) for q in qs], [None] * len(qs), 0
89
+ for i, c in sorted(self.bins.items()):
90
+ acc += c
91
+ for j, r in enumerate(ranks):
92
+ if out[j] is None and acc >= r:
93
+ out[j] = min(math.exp((i + 0.5) * self.STEP), self.max)
94
+ if out[-1] is not None:
95
+ break
96
+ return out
97
+
98
+
99
+ def exact(values, qs=(0.5, 0.95, 0.99)):
100
+ """Nearest-rank quantiles of a list of values."""
101
+ if not values:
102
+ return [None] * len(qs)
103
+ v = sorted(values)
104
+ return [v[max(1, math.ceil(q * len(v))) - 1] for q in qs]
105
+
106
+
107
+ def redact(name, value):
108
+ """An option's value for the configuration view: secrets (an option named key, token, secret, password, auth or
109
+ credentials, and the --api-keys file) as "(set)", URLs without user, password, query or fragment."""
110
+ if value is None or isinstance(value, bool):
111
+ return value
112
+ if name == "api_keys" or SECRET & set(name.lower().split("_")):
113
+ return "(set)"
114
+ if isinstance(value, (list, tuple)):
115
+ return [redact(name, v) for v in value]
116
+ if isinstance(value, (int, float)):
117
+ return value if math.isfinite(value) else str(value)
118
+ value = str(value)
119
+ if "://" in value:
120
+ try:
121
+ u = urlsplit(value)
122
+ return urlunsplit((u.scheme, u.hostname + (f":{u.port}" if u.port else "") if u.hostname else "", u.path,
123
+ "", ""))
124
+ except ValueError:
125
+ return "(set)"
126
+ return value
127
+
128
+
129
+ def versions(packages=PACKAGES):
130
+ """Installed versions of the packages basal can serve with (metadata only: nothing is imported); basal-router's UI
131
+ asks for its own packages."""
132
+ out = {}
133
+ for p in packages:
134
+ try:
135
+ out[p] = metadata.version(p)
136
+ except metadata.PackageNotFoundError:
137
+ pass
138
+ torch = sys.modules.get("torch")
139
+ cuda = getattr(getattr(torch, "version", None), "cuda", None) # the build's CUDA (a constant, not a device call)
140
+ if cuda:
141
+ out["CUDA (torch build)"] = cuda
142
+ return out
143
+
144
+
145
+ def revision(srv, a):
146
+ """--revision, else the commit of a Hugging Face cache snapshot the model was resolved to, else None."""
147
+ if a.revision:
148
+ return a.revision
149
+ md = getattr(srv, "md", None)
150
+ return md.name if md is not None and md.parent.name == "snapshots" else None
151
+
152
+
153
+ def facts(srv, a, mode):
154
+ """What the options resolved to at start-up: calibration, prepared start-up, compile, attention, prompt, packages."""
155
+ from .server import MODES
156
+ m = str(mode or "")
157
+ if m.startswith("llamagraph"):
158
+ kind, quant, comp = "graph", (m.split(".", 1)[1] if "." in m else None), True
159
+ elif m.startswith("mlx.metal"):
160
+ parts = m.split(".")
161
+ kind, quant, comp = "mlx", (parts[2] if len(parts) >= 3 else None), False
162
+ else:
163
+ kind, quant, comp = MODES.get(mode, (None, None, False))
164
+ b = srv.backend
165
+ cal = getattr(srv, "cal_file", None)
166
+ fitted = (getattr(srv, "cal", None) or {}).get("fitted_on") or {}
167
+ prep = getattr(srv, "prepared", None)
168
+ ctx = getattr(srv, "context", None)
169
+ out = [
170
+ ["calibration", "off" if a.no_calibration else None if cal is None else cal.name if cal.exists() else
171
+ "none (no file found)"],
172
+ ["calibration fitted on", " @ ".join(str(fitted[k])[:12] if k == "revision" else str(fitted[k])
173
+ for k in ("model", "revision") if fitted.get(k)) or None],
174
+ ["calibration warning", getattr(srv, "cal_mismatch", None) or getattr(srv, "cal_unvalidated", None)
175
+ or getattr(srv, "cal_foreign", None)],
176
+ ["prepared start-up", None if prep is None else
177
+ f"loaded ({prep['inductor']} compiled kernels)" if isinstance(prep.get("inductor"), int) else "loaded"],
178
+ ["engine", f"{type(b).__name__} ({kind})" if kind else type(b).__name__],
179
+ ["quantisation", quant or getattr(a, "quant", None)],
180
+ ["compile", ("torch.compile" + (" per layer" if getattr(a, "compile_scope", "model") == "layer" else "")
181
+ + " + CUDA graphs") if comp else "off"],
182
+ ["attention", getattr(b, "attn", None)],
183
+ ["compact rows", getattr(b, "compact_kernel", None)],
184
+ ["convolution", getattr(b, "conv_kernel", None)],
185
+ ["fla kernel configs", getattr(b, "fla_configs", None)],
186
+ ["vLLM preset", getattr(b, "preset", None)],
187
+ ["device", str(getattr(b, "dev", "")) or None],
188
+ ["prompt format", getattr(srv, "fmt", None)],
189
+ ["layout", getattr(srv, "layout", None)],
190
+ ["option orders", getattr(srv, "orders", None)],
191
+ ["two-way", getattr(srv, "two_way", None)],
192
+ ["state once, ask many", getattr(srv, "soam", None)],
193
+ ["context limit", f"{ctx[0]} tokens ({ctx[1]})" if ctx else None],
194
+ ["context overflow", getattr(srv, "overflow", None)],
195
+ ["state cache", f"{a.state_cache_gb:g} GB, {a.state_cache_bits}-bit" if getattr(a, "state_cache_gb", 0)
196
+ else "off"],
197
+ ["max batch", getattr(srv, "max_batch", None)],
198
+ ["python", sys.version.split()[0]],
199
+ ["platform", f"{sys.platform} {os.uname().machine}" if hasattr(os, "uname") else sys.platform],
200
+ ]
201
+ out += [[name, v] for name, v in versions().items()]
202
+ return [[k, v] for k, v in out if v not in (None, "")]
203
+
204
+
205
+ class Telemetry:
206
+ """GPU (NVML) and host (psutil) readings for the page, sampled every `every` seconds in a side thread that runs only
207
+ while a page polled GET /ui/state in the last `idle` seconds. Never a torch.cuda call. A missing library or a
208
+ machine without NVIDIA's driver leaves its part empty with a note."""
209
+
210
+ def __init__(self, idle=IDLE_S, every=1.0):
211
+ self.idle, self.every = idle, every
212
+ self.viewed_at, self.thread, self.opened = 0.0, None, False
213
+ self.nvml = self.ps = self.proc = None
214
+ self.handles = []
215
+ self.gpu_note = self.host_note = None
216
+ self.sample = {"gpus": [], "gpu_note": None, "host": {}, "host_note": None, "at": None}
217
+
218
+ def view(self):
219
+ """A page read the state: sample (again) for the next `idle` seconds."""
220
+ self.viewed_at = time.monotonic()
221
+ if self.thread is None or not self.thread.is_alive():
222
+ self.thread = threading.Thread(target=self._run, name="basal-ui-telemetry", daemon=True)
223
+ self.thread.start()
224
+
225
+ def _run(self):
226
+ if not self.opened:
227
+ self.open()
228
+ while time.monotonic() - self.viewed_at < self.idle:
229
+ self.sample = self.read()
230
+ time.sleep(self.every)
231
+
232
+ def open(self):
233
+ self.opened = True
234
+ try:
235
+ import pynvml
236
+ pynvml.nvmlInit()
237
+ self.nvml = pynvml # (CUDA index, handle, NVML index, PCI bus id): the last two name the physical GPU
238
+ self.handles = [(j, h, k, pci_id(pynvml, h)) for j, h, k in visible(pynvml)]
239
+ except ImportError:
240
+ self.gpu_note = "GPU telemetry needs nvidia-ml-py (pip install nvidia-ml-py)"
241
+ except Exception as e: # noqa: BLE001 (no NVIDIA driver: Apple, AMD, CPU)
242
+ self.gpu_note = f"no NVIDIA GPU telemetry on this machine ({type(e).__name__})"
243
+ try:
244
+ import psutil
245
+ self.ps, self.proc = psutil, psutil.Process()
246
+ psutil.cpu_percent(None) # the first readings start the intervals
247
+ self.proc.cpu_percent(None)
248
+ except ImportError:
249
+ self.host_note = "CPU and memory need psutil (pip install psutil)"
250
+
251
+ def read(self):
252
+ gpus = [dict(gpu(self.nvml, j, h), nvml_index=k, pci=pci) for j, h, k, pci in self.handles] \
253
+ if self.nvml is not None else []
254
+ host = {"cpus": os.cpu_count(), "load": _try(lambda: [round(x, 2) for x in os.getloadavg()])}
255
+ if self.ps is not None:
256
+ vm = self.ps.virtual_memory()
257
+ mem = _try(self.proc.memory_info)
258
+ host.update(cpu=self.ps.cpu_percent(None), ram_used=vm.total - vm.available, ram_total=vm.total,
259
+ rss=mem.rss if mem else None, proc_cpu=_try(lambda: self.proc.cpu_percent(None)),
260
+ threads=_try(self.proc.num_threads))
261
+ return {"gpus": gpus, "gpu_note": self.gpu_note, "host": host, "host_note": self.host_note,
262
+ "at": round(time.time(), 3)}
263
+
264
+
265
+ def _ms(seconds):
266
+ return None if seconds is None else round(seconds * 1000, 3)
267
+
268
+
269
+ def _try(fn, default=None):
270
+ try:
271
+ return fn()
272
+ except Exception: # noqa: BLE001
273
+ return default
274
+
275
+
276
+ def visible(nvml):
277
+ """[(CUDA index, NVML handle, NVML index)] of the GPUs this process sees (CUDA_VISIBLE_DEVICES as indices or UUIDs;
278
+ every GPU without it, or when none of its entries is found). The NVML index names the physical GPU: a process pinned
279
+ to one GPU sees it as cuda:0 whichever it is."""
280
+ n = nvml.nvmlDeviceGetCount()
281
+ ids = [x.strip() for x in os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",") if x.strip()]
282
+ out = []
283
+ for j, s in enumerate(ids):
284
+ if s.startswith(("GPU-", "MIG-")):
285
+ h = _try(lambda: nvml.nvmlDeviceGetHandleByUUID(s))
286
+ k = None if h is None else _try(lambda: nvml.nvmlDeviceGetIndex(h))
287
+ else:
288
+ k = _try(lambda: int(s))
289
+ h = None if k is None else _try(lambda: nvml.nvmlDeviceGetHandleByIndex(k))
290
+ if h is not None:
291
+ out.append((j, h, k))
292
+ return out or [(i, nvml.nvmlDeviceGetHandleByIndex(i), i) for i in range(n)]
293
+
294
+
295
+ def pci_id(nvml, h):
296
+ """A GPU's PCI bus id, short: domain (last 4 digits):bus:device, e.g. 0000:61:00 (None when NVML has none)."""
297
+ bus = _try(lambda: nvml.nvmlDeviceGetPciInfo(h).busId)
298
+ bus = bus.decode() if isinstance(bus, bytes) else bus
299
+ parts = bus.split(":") if isinstance(bus, str) else []
300
+ return f"{parts[0][-4:]}:{parts[1]}:{parts[2].split('.')[0]}" if len(parts) == 3 else bus
301
+
302
+
303
+ def gpu(nvml, i, h):
304
+ """One GPU's reading: utilisation (%), memory (bytes; this process's part when NVML reports it), temperature (C),
305
+ power and its limit (W), SM clock (MHz)."""
306
+ name = _try(lambda: nvml.nvmlDeviceGetName(h))
307
+ util = _try(lambda: nvml.nvmlDeviceGetUtilizationRates(h))
308
+ mem = _try(lambda: nvml.nvmlDeviceGetMemoryInfo(h))
309
+ power = _try(lambda: nvml.nvmlDeviceGetPowerUsage(h))
310
+ limit = _try(lambda: nvml.nvmlDeviceGetEnforcedPowerLimit(h))
311
+ pid = os.getpid()
312
+ own = _try(lambda: sum(p.usedGpuMemory or 0 for p in nvml.nvmlDeviceGetComputeRunningProcesses(h) if p.pid == pid))
313
+ return {"index": i, "name": name.decode() if isinstance(name, bytes) else name,
314
+ "util": getattr(util, "gpu", None), "mem_util": getattr(util, "memory", None),
315
+ "mem_used": getattr(mem, "used", None), "mem_total": getattr(mem, "total", None), "mem_own": own or None,
316
+ "temp": _try(lambda: nvml.nvmlDeviceGetTemperature(h, nvml.NVML_TEMPERATURE_GPU)),
317
+ "power": None if power is None else round(power / 1000, 1),
318
+ "power_limit": None if limit is None else round(limit / 1000, 1),
319
+ "sm_clock": _try(lambda: nvml.nvmlDeviceGetClockInfo(h, nvml.NVML_CLOCK_SM))}
320
+
321
+
322
+ def with_page(app, html):
323
+ """app with GET /ui (html, a page next to this module) and its fonts in front of it, for basal-serve's UI and
324
+ basal-router's. The files are read once, here."""
325
+ from starlette.responses import Response
326
+ files = {"/ui": ((HERE / html).read_bytes(), "text/html; charset=utf-8", HEADERS)}
327
+ for name in FONTS:
328
+ kind = "font/woff2" if name.endswith(".woff2") else "text/plain; charset=utf-8"
329
+ files[f"/ui/fonts/{name}"] = ((HERE / "fonts" / name).read_bytes(), kind,
330
+ {"Cache-Control": "max-age=86400", "X-Content-Type-Options": "nosniff"})
331
+
332
+ async def page(scope, receive, send):
333
+ f = files.get(scope["path"]) if scope["type"] == "http" and scope["method"] == "GET" else None
334
+ if f is None:
335
+ await app(scope, receive, send)
336
+ return
337
+ await Response(f[0], media_type=f[1], headers=f[2])(scope, receive, send)
338
+ return page
339
+
340
+
341
+ class UI:
342
+ """The state behind the page of one basal-serve process. Built when the server is ready (start-up work such as
343
+ reading package versions is done here, not at a request); http_app takes its routes, main its page."""
344
+
345
+ def __init__(self, srv, a, mode, defaults=None, started=None, full=False):
346
+ from . import __version__
347
+ self.srv, self.a, self.mode, self.version = srv, a, mode, __version__
348
+ self.ring = deque(maxlen=RING) # (end perf_counter, endpoint, status, seconds, questions, options[, id])
349
+ # --ui full: (id, the body's bytes as sent (parsed when GET /ui/request/<id> reads it), answer bytes, ring row,
350
+ # the name of the API key that made it or None, bytes of body and answer as sent) of the last RECENT,
351
+ # FULL_BYTES of them at most
352
+ self.bodies, self.ids = (deque(maxlen=RECENT), itertools.count(1)) if full else (None, None)
353
+ self.kept_bytes = 0
354
+ self.wall0, self.perf0 = time.time(), time.perf_counter()
355
+ self.started = started or self.wall0
356
+ self.memo, self.memo_at = None, -math.inf
357
+ self.folded, self.seen = self.perf0, 0 # end time of the last request in the totals, and their count
358
+ self.total, self.endpoints, self.codes = Hist(), {}, {}
359
+ self.cache = None # the last state-cache snapshot read
360
+ self.telemetry = Telemetry()
361
+ defaults = defaults or {}
362
+ self.config = {"options": [[k, redact(k, v), k in defaults and defaults[k] != v] for k, v in vars(a).items()],
363
+ "facts": facts(srv, a, mode)}
364
+
365
+ def record(self, handler, endpoint):
366
+ """handler with its request's metadata appended to the ring once it is answered: all the work --ui on adds to
367
+ a request. The body was parsed by the handler (Starlette keeps it on the request); its text is not kept. --ui
368
+ full: also a reference to that body and to the answer's bytes (no copy), under a request id."""
369
+ ring, clock, bodies, ids = self.ring, time.perf_counter, self.bodies, self.ids
370
+
371
+ async def recorded(request):
372
+ t = clock()
373
+ response = await handler(request)
374
+ t1 = clock()
375
+ ring.append((t1, endpoint, response.status_code, t1 - t, *size(getattr(request, "_json", None))))
376
+ return response
377
+
378
+ async def recorded_full(request):
379
+ t = clock()
380
+ response = await handler(request)
381
+ t1 = clock()
382
+ body, rid = getattr(request, "_json", None), next(ids)
383
+ row = (t1, endpoint, response.status_code, t1 - t, *size(body), rid)
384
+ ring.append(row)
385
+ key = (getattr(request, "scope", None) or {}).get("basal.api_key") # (set by protect with --api-keys)
386
+ raw, answer = getattr(request, "_body", None), getattr(response, "body", None)
387
+ n = len(raw or b"") + len(answer or b"")
388
+ if len(bodies) == bodies.maxlen:
389
+ self.kept_bytes -= bodies[0][5]
390
+ # the bytes the budget counts, not the parsed body: that one is many times larger in memory (an array of
391
+ # empty objects: ~19x) and would hold several GB within the budget
392
+ bodies.append((rid, raw if raw is not None else body, answer, row, key.get("name") if key else None, n))
393
+ self.kept_bytes += n
394
+ while self.kept_bytes > FULL_BYTES and len(bodies) > 1: # (a large body pushes the older ones out)
395
+ self.kept_bytes -= bodies.popleft()[5]
396
+ return response
397
+ out = recorded if bodies is None else recorded_full
398
+ out.__name__ = f"recorded_{handler.__name__}"
399
+ return out
400
+
401
+ def routes(self, routes, counts):
402
+ """http_app's routes with the decision routes recorded, and GET /ui/state. counts: http_app's totals (the
403
+ ones GET /metrics reports)."""
404
+ from starlette.responses import JSONResponse, Response
405
+ from starlette.routing import Route
406
+
407
+ async def state(_):
408
+ return Response(self.state(counts), media_type="application/json", headers={"Cache-Control": "no-store"})
409
+
410
+ async def one(request):
411
+ data = self.request_json(request.path_params["rid"], request.scope.get("basal.api_key"))
412
+ if data is False:
413
+ return JSONResponse({"error": "this request was made with another API key (an admin key reads every "
414
+ "request)", "code": "FORBIDDEN"}, status_code=403)
415
+ if data is None:
416
+ return JSONResponse({"error": f"not kept: --ui full keeps the last {RECENT} requests "
417
+ f"({FULL_BYTES // 2**20} MiB of bodies and answers at most)",
418
+ "code": "NOT_FOUND"}, status_code=404)
419
+ return Response(data, media_type="application/json", headers={"Cache-Control": "no-store"})
420
+ out = [Route(r.path, self.record(r.endpoint, r.path), methods=sorted(r.methods))
421
+ if isinstance(r, Route) and r.path in DECISIONS else r for r in routes]
422
+ return out + [Route("/ui/state", state)] + ([Route("/ui/request/{rid:int}", one)] if self.bodies is not None else [])
423
+
424
+ def request_json(self, rid, key=None):
425
+ """GET /ui/request/<id> (--ui full): the request's metadata, its body as parsed (a body that was not JSON as
426
+ text) and the answer it got (the bytes sent, as JSON), or None when it is no longer kept. key: the caller's API
427
+ key record (--api-keys; None without): False when it is neither the key that made the request nor an admin
428
+ key."""
429
+ kept = next((b for b in self.bodies if b[0] == rid), None)
430
+ if kept is None:
431
+ return None
432
+ _, body, answer, row, owner, _ = kept
433
+ if key is not None and not key.get("admin", False) and key.get("name") != owner:
434
+ return False
435
+ if isinstance(body, (bytes, bytearray)): # (as sent: parsed here, as the route parsed it; else as text)
436
+ try:
437
+ body = json.loads(body)
438
+ except (ValueError, RecursionError):
439
+ body = body.decode("utf-8", "replace")
440
+ meta = {"id": rid, "time": round(self.wall0 + row[0] - self.perf0, 3), "endpoint": row[1], "status": row[2],
441
+ "ms": _ms(row[3]), "questions": row[4], "options": row[5]}
442
+ try:
443
+ answer = answer if answer is not None and json.loads(answer) is not None else b"null"
444
+ except ValueError:
445
+ answer = json.dumps(answer.decode("utf-8", "replace")).encode()
446
+ # (a lone surrogate the request held, refused with 422, is written as its \u escape: it is no UTF-8)
447
+ return (json.dumps(meta)[:-1] + ', "request": ' + json.dumps(body, ensure_ascii=False) + ', "answer": ').encode(
448
+ "utf-8", "backslashreplace") + answer + b"}"
449
+
450
+ def page(self, app):
451
+ """app with GET /ui (the page) and its fonts in front of it, open (the page asks for the key when GET
452
+ /ui/state needs one)."""
453
+ return with_page(app, "ui.html")
454
+
455
+ def fold(self, rows):
456
+ """Requests answered since the last read (rows: the ring's rows, oldest first) into the totals since start,
457
+ the oldest first and at most FOLD of them (the rest at the next reads). A request that left the ring before it
458
+ was folded (more than RING requests between two reads) is not in the totals: "seen" counts the ones that are."""
459
+ new = rows[bisect.bisect_right(rows, self.folded, key=END):][:FOLD]
460
+ if not new:
461
+ return
462
+ self.folded = new[-1][0]
463
+ self.seen += len(new)
464
+ bin_of, total, endpoints, codes = Hist.bin, self.total, self.endpoints, self.codes
465
+ for _, ep, status, s, *_ in new:
466
+ ms = s * 1000
467
+ i = bin_of(ms)
468
+ total.add(ms, i)
469
+ e = endpoints.get(ep)
470
+ if e is None:
471
+ e = endpoints[ep] = {"requests": 0, "failed": 0, "hist": Hist()}
472
+ e["requests"] += 1
473
+ e["failed"] += status >= 400
474
+ e["hist"].add(ms, i)
475
+ codes[status] = codes.get(status, 0) + 1
476
+
477
+ def state(self, counts):
478
+ """GET /ui/state: the JSON snapshot, built at most once per MEMO_S."""
479
+ self.telemetry.view()
480
+ now = time.perf_counter()
481
+ if now - self.memo_at < MEMO_S:
482
+ return self.memo
483
+ srv, a = self.srv, self.a
484
+ rows = list(self.ring) # one copy; the rows are in the order of their end times
485
+ self.fold(rows)
486
+ i60 = bisect.bisect_left(rows, now - 60, key=END)
487
+ w60 = [r[3] for r in rows[i60:]] # seconds of the requests answered in the last 60 and 10 s
488
+ w10 = w60[bisect.bisect_left(rows, now - 10, lo=i60, key=END) - i60:]
489
+ up = now - self.perf0
490
+ q50, q95, q99 = self.total.quantiles()
491
+ load = srv.load()
492
+ cache = getattr(srv.backend, "state_cache", None)
493
+ if cache is not None:
494
+ self.cache = cache.stats(blocking=False) or self.cache # never waits for the engine's lock
495
+ d = {
496
+ # "now" on the rows' clock (wall0 + perf_counter): time.time() can disagree with it by a timer tick
497
+ # (Windows), and a row would then end after "now"
498
+ "now": round(self.wall0 + time.perf_counter() - self.perf0, 3), "started": round(self.started, 3),
499
+ "ready_at": round(self.wall0, 3),
500
+ "uptime": round(up, 3),
501
+ "status": {"state": "ready", "model": srv.name, "source": a.model, "revision": revision(srv, a),
502
+ "mode": self.mode, "version": self.version, "think": getattr(a, "think", "off"),
503
+ "running": load["running"], "queued": load["queued"],
504
+ "ui": "full" if self.bodies is not None else "on",
505
+ "auth": bool(getattr(a, "api_keys", None))},
506
+ "traffic": {
507
+ "requests": counts["requests"], "failed": counts["failed"], "seconds": round(counts["seconds"], 6),
508
+ "seen": self.seen, "ring": RING,
509
+ "rate10": round(len(w10) / min(10.0, up), 3) if up > 0 else 0,
510
+ "rate60": round(len(w60) / min(60.0, up), 3) if up > 0 else 0,
511
+ "latency": {"p50": q50, "p95": q95, "p99": q99, "max": self.total.max or None,
512
+ "mean": self.total.sum / self.total.n if self.total.n else None},
513
+ "w10": dict(zip(("p50", "p95", "p99"), map(_ms, exact(w10))), n=len(w10)),
514
+ "w60": dict(zip(("p50", "p95", "p99"), map(_ms, exact(w60))), n=len(w60)),
515
+ "endpoints": [{"endpoint": ep, "requests": e["requests"], "failed": e["failed"],
516
+ **dict(zip(("p50", "p95"), e["hist"].quantiles((0.5, 0.95)))),
517
+ "mean": e["hist"].sum / e["hist"].n} for ep, e in sorted(self.endpoints.items())],
518
+ "codes": {str(k): v for k, v in sorted(self.codes.items())}},
519
+ "cache": self.cache,
520
+ "telemetry": self.telemetry.sample,
521
+ "config": self.config,
522
+ "recent": [[round(self.wall0 + r[0] - self.perf0, 3), r[1], r[2], _ms(r[3]), *r[4:]]
523
+ for r in reversed(rows[-RECENT:])], # (--ui full: and the request id)
524
+ }
525
+ self.memo, self.memo_at = json.dumps(d, separators=(",", ":")).encode(), now
526
+ return self.memo