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.
- basal/__init__.py +7 -0
- basal/adapter.py +420 -0
- basal/adapters.py +8 -0
- basal/agree.py +393 -0
- basal/attach.py +160 -0
- basal/attn512.py +132 -0
- basal/auth.py +194 -0
- basal/bench.py +367 -0
- basal/blockquant.py +227 -0
- basal/calibrate.py +2198 -0
- basal/chat.py +175 -0
- basal/cli.py +70 -0
- basal/client.py +8 -0
- basal/decision_log.py +189 -0
- basal/decision_rules.py +569 -0
- basal/decisions.py +158 -0
- basal/derive.py +98 -0
- basal/disconnect.py +85 -0
- basal/engine.py +6023 -0
- basal/evidence.py +133 -0
- basal/examples/choice.jsonl +8 -0
- basal/examples/complex.jsonl +5 -0
- basal/examples/labelled_tickets.jsonl +500 -0
- basal/examples/local_backend.py +34 -0
- basal/examples/noul.jsonl +8 -0
- basal/examples/questions.jsonl +20 -0
- basal/examples/score.jsonl +8 -0
- basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
- basal/examples/selfcheck_basal-omni-pico.json +1 -0
- basal/examples/types_demo.py +74 -0
- basal/facts.py +497 -0
- basal/feedback.py +234 -0
- basal/file_identity.py +39 -0
- basal/finetune.py +321 -0
- basal/fit_decisions.py +944 -0
- basal/fla_configs.json +1822 -0
- basal/fold.py +206 -0
- basal/fonts/OFL-DMSans.txt +93 -0
- basal/fonts/OFL-SpaceGrotesk.txt +93 -0
- basal/fonts/dm-sans-latin-ext.woff2 +0 -0
- basal/fonts/dm-sans-latin.woff2 +0 -0
- basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
- basal/fonts/space-grotesk-latin.woff2 +0 -0
- basal/fp8block.py +100 -0
- basal/gdn_graph.py +1792 -0
- basal/gemma4.py +726 -0
- basal/gemma4_graph.py +931 -0
- basal/gguf_export.py +497 -0
- basal/identity.py +217 -0
- basal/int8block.py +50 -0
- basal/interpolate.py +330 -0
- basal/jsonl.py +172 -0
- basal/lean.py +204 -0
- basal/llama_attn.py +252 -0
- basal/llama_attn_kernels.py +266 -0
- basal/llama_graph.py +587 -0
- basal/llama_kernels.py +593 -0
- basal/loadtest.py +189 -0
- basal/mcp_server.py +432 -0
- basal/media.py +138 -0
- basal/metrics.py +16 -0
- basal/mlx_attn_kernels.py +1057 -0
- basal/mlx_forward.py +326 -0
- basal/mlx_kernels.py +543 -0
- basal/mlx_metal.py +510 -0
- basal/navcut.py +283 -0
- basal/navigate.py +646 -0
- basal/navtree.py +397 -0
- basal/nvfp4.py +245 -0
- basal/ordercheck.py +165 -0
- basal/pdf.py +183 -0
- basal/prepared.py +355 -0
- basal/presets.py +8 -0
- basal/prompt.py +462 -0
- basal/rank.py +373 -0
- basal/readout.py +121 -0
- basal/request.py +327 -0
- basal/response_cache.py +105 -0
- basal/router.py +1551 -0
- basal/router_ui.html +902 -0
- basal/router_ui.py +277 -0
- basal/run.py +376 -0
- basal/selfcheck.py +215 -0
- basal/server.py +5279 -0
- basal/sets.py +214 -0
- basal/signals.py +28 -0
- basal/state_disk.py +942 -0
- basal/strix.py +505 -0
- basal/synth.py +92 -0
- basal/tasks.py +848 -0
- basal/textio.py +21 -0
- basal/think.py +390 -0
- basal/tools.py +171 -0
- basal/tpu.py +336 -0
- basal/tpu_kernels.py +129 -0
- basal/trace.py +125 -0
- basal/ui.html +861 -0
- basal/ui.py +526 -0
- basal/varloop.py +813 -0
- basal/varloop_graph.py +1377 -0
- basal/varloop_kernels.py +907 -0
- basal/viz.html +660 -0
- basal/viz.py +375 -0
- basal/vllm_unified.py +100 -0
- basal_engine-3.0.3.dist-info/METADATA +416 -0
- basal_engine-3.0.3.dist-info/RECORD +111 -0
- basal_engine-3.0.3.dist-info/WHEEL +5 -0
- basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
- basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
- basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
- basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/request.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""What a request body is checked for before any work, shared by basal-serve's routes (POST /v1/systemone, /v1/basal,
|
|
2
|
+
/v1/decisions and the MCP tools); no torch, so basal-router can use it too.
|
|
3
|
+
|
|
4
|
+
A body is JSON that a client may have built by hand: it can nest deeper than the code that reads it recurses, carry an
|
|
5
|
+
escape such as "\\udead" (a lone surrogate: not Unicode text, which the tokenizer and the UTF-8 response refuse) or,
|
|
6
|
+
in a question, a NaN or an infinity (Python's json reads them, and an answer keyed or computed by one cannot be
|
|
7
|
+
written). Each is the request's fault, answered 422 (400 on /v1/decisions) before anything is rendered or run.
|
|
8
|
+
|
|
9
|
+
Also the request helpers both read alike: a value as text (text_of), the options as the model sees them
|
|
10
|
+
(named_options) and a body read once (read_json for basal-serve, parse_body for the router)."""
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from collections import Counter
|
|
14
|
+
|
|
15
|
+
from .prompt import RequestError
|
|
16
|
+
|
|
17
|
+
MAX_BODY_BYTES = 256 * 2**20 # --max-body-mb: a request body (8 media items of 20 MB are ~214 MB in base64)
|
|
18
|
+
MAX_DEPTH = 256 # objects and arrays nested in a request body (JSON states nest a few levels; Python's parser and
|
|
19
|
+
# the recursive readers after it stop near 1,000, with a 500)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _text_ok(s, where):
|
|
23
|
+
if not s.isascii():
|
|
24
|
+
try:
|
|
25
|
+
s.encode("utf-8")
|
|
26
|
+
except UnicodeEncodeError as e:
|
|
27
|
+
bad = s[e.start: e.end].encode("utf-8", "backslashreplace").decode("ascii")
|
|
28
|
+
raise RequestError(f"{where}: {bad} is a lone surrogate (half of a UTF-16 pair), not text") from None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _not_text(s):
|
|
32
|
+
"""A string that holds a lone surrogate (not UTF-8 text)."""
|
|
33
|
+
if s.isascii():
|
|
34
|
+
return False
|
|
35
|
+
try:
|
|
36
|
+
s.encode("utf-8")
|
|
37
|
+
except UnicodeEncodeError:
|
|
38
|
+
return True
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _refused(body, max_depth, finite):
|
|
43
|
+
"""Whether check_json refuses the body, found without naming where: no location text or stack entry per element
|
|
44
|
+
(the walk that names one took 5.5 s and 45 times the body's size in memory on 32 MiB of [{}, ...], on the event
|
|
45
|
+
loop). A stack of iterators, one per open container: its memory follows the nesting, not the breadth."""
|
|
46
|
+
if not isinstance(body, (dict, list)):
|
|
47
|
+
return isinstance(body, str) and _not_text(body)
|
|
48
|
+
is_dict = isinstance(body, dict)
|
|
49
|
+
stack = [(iter(body.items()) if is_dict else iter(body), 1, False, is_dict)]
|
|
50
|
+
while stack:
|
|
51
|
+
it, depth, fin, is_dict = stack[-1]
|
|
52
|
+
for e in it:
|
|
53
|
+
if is_dict:
|
|
54
|
+
k, v = e
|
|
55
|
+
if isinstance(k, str) and _not_text(k):
|
|
56
|
+
return True
|
|
57
|
+
f = fin or depth == 1 and k in finite
|
|
58
|
+
else:
|
|
59
|
+
v, f = e, fin
|
|
60
|
+
if isinstance(v, str):
|
|
61
|
+
if _not_text(v):
|
|
62
|
+
return True
|
|
63
|
+
elif isinstance(v, float):
|
|
64
|
+
if f and not math.isfinite(v):
|
|
65
|
+
return True
|
|
66
|
+
elif isinstance(v, (dict, list)):
|
|
67
|
+
if depth + 1 > max_depth:
|
|
68
|
+
return True
|
|
69
|
+
if v: # (descend; this container's iterator goes on after it)
|
|
70
|
+
d = isinstance(v, dict)
|
|
71
|
+
stack.append((iter(v.items()) if d else iter(v), depth + 1, f, d))
|
|
72
|
+
break
|
|
73
|
+
else:
|
|
74
|
+
stack.pop()
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def check_json(body, max_depth=MAX_DEPTH, finite=("questions",)):
|
|
79
|
+
"""A parsed request body -> RequestError when its objects / arrays nest deeper than max_depth, a string (a key or a
|
|
80
|
+
value) holds a lone surrogate, or a number under one of the top-level fields `finite` is NaN or infinite. Iterative:
|
|
81
|
+
a deep body cannot exhaust the stack here. A body it takes is walked once, fast (_refused); only a refused one is
|
|
82
|
+
walked again, to name where the problem is (_locate)."""
|
|
83
|
+
if max_depth < 1 or _refused(body, max_depth, finite):
|
|
84
|
+
_locate(body, max_depth, finite)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _locate(body, max_depth, finite):
|
|
88
|
+
"""check_json's refusal of a body, with where it is (the walk check_json was before _refused)."""
|
|
89
|
+
stack = [(body, 1, "the request body", False)]
|
|
90
|
+
while stack:
|
|
91
|
+
x, depth, where, fin = stack.pop()
|
|
92
|
+
if isinstance(x, str):
|
|
93
|
+
_text_ok(x, where)
|
|
94
|
+
elif isinstance(x, float):
|
|
95
|
+
if fin and not math.isfinite(x):
|
|
96
|
+
raise RequestError(f"{where}: {x} is not a finite number")
|
|
97
|
+
elif isinstance(x, (dict, list)):
|
|
98
|
+
if depth > max_depth:
|
|
99
|
+
raise RequestError(f"the request body nests objects and arrays more than {max_depth} levels deep")
|
|
100
|
+
if isinstance(x, dict):
|
|
101
|
+
for k, v in x.items():
|
|
102
|
+
if isinstance(k, str):
|
|
103
|
+
_text_ok(k, where)
|
|
104
|
+
at = repr(k) if depth > 1 else k
|
|
105
|
+
stack.append((v, depth + 1, at if depth == 1 else f"{where}[{at}]",
|
|
106
|
+
fin or depth == 1 and k in finite))
|
|
107
|
+
else:
|
|
108
|
+
stack.extend((v, depth + 1, f"{where}[{i}]", fin) for i, v in enumerate(x))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def read_json(raw):
|
|
112
|
+
"""A request body (bytes) -> its JSON value; RequestError for one that is not JSON, not UTF-8 or nested beyond what
|
|
113
|
+
the parser reads (RecursionError)."""
|
|
114
|
+
try:
|
|
115
|
+
return json.loads(raw)
|
|
116
|
+
except (ValueError, RecursionError) as e: # (UnicodeDecodeError is a ValueError)
|
|
117
|
+
raise RequestError(f"the request body is not valid JSON: {e}") from None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def request_json(request):
|
|
121
|
+
"""A Starlette request's body as read_json reads it, kept on the request as request.json() keeps it (--ui reads
|
|
122
|
+
it there)."""
|
|
123
|
+
try:
|
|
124
|
+
return await request.json()
|
|
125
|
+
except (ValueError, RecursionError) as e:
|
|
126
|
+
raise RequestError(f"the request body is not valid JSON: {e}") from None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
MAX_PARTS = 16 # parts of a multipart request (one "request" and at most media.MAX_ITEMS files fit)
|
|
130
|
+
MEDIA_TYPES = {"image": "image", "audio": "audio"} # a media part's Content-Type major type -> its media item type
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def is_multipart(content_type):
|
|
134
|
+
return (content_type or "").split(";")[0].strip().lower() == "multipart/form-data"
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _param(header, value, param):
|
|
138
|
+
"""A parameter of a MIME header value (quoted or not, RFC 2231 forms too), None without it."""
|
|
139
|
+
from email.message import Message
|
|
140
|
+
m = Message()
|
|
141
|
+
m[header] = value
|
|
142
|
+
v = m.get_param(param, header=header)
|
|
143
|
+
if isinstance(v, tuple): # (an RFC 2231 value: charset, language, text)
|
|
144
|
+
from email.utils import collapse_rfc2231_value
|
|
145
|
+
v = collapse_rfc2231_value(v)
|
|
146
|
+
return v
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def read_multipart(raw, content_type):
|
|
150
|
+
"""A multipart/form-data body (bytes) -> [(name, Content-Type or None, bytes)], in order; RequestError when it is
|
|
151
|
+
not one (no boundary, a part without its headers' end, no closing boundary, more than MAX_PARTS parts)."""
|
|
152
|
+
boundary = _param("content-type", content_type, "boundary")
|
|
153
|
+
if not boundary:
|
|
154
|
+
raise RequestError("a multipart/form-data request needs a boundary in its Content-Type")
|
|
155
|
+
sep = b"--" + boundary.encode("latin-1", "replace")
|
|
156
|
+
pos = raw.find(sep)
|
|
157
|
+
if pos < 0:
|
|
158
|
+
raise RequestError("the multipart body has no part (its boundary is not in it)")
|
|
159
|
+
pos += len(sep)
|
|
160
|
+
parts = []
|
|
161
|
+
while not raw.startswith(b"--", pos): # (the closing boundary ends with "--")
|
|
162
|
+
if not raw.startswith(b"\r\n", pos):
|
|
163
|
+
raise RequestError("the multipart body is malformed (a boundary not followed by a line break)")
|
|
164
|
+
end = raw.find(b"\r\n" + sep, pos + 2)
|
|
165
|
+
if end < 0:
|
|
166
|
+
raise RequestError("the multipart body has no closing boundary")
|
|
167
|
+
head, gap, data = raw[pos + 2:end].partition(b"\r\n\r\n")
|
|
168
|
+
if not gap:
|
|
169
|
+
raise RequestError("a multipart part has no blank line after its headers")
|
|
170
|
+
headers = {}
|
|
171
|
+
for line in head.decode("utf-8", "replace").split("\r\n"):
|
|
172
|
+
k, colon, v = line.partition(":")
|
|
173
|
+
if colon:
|
|
174
|
+
headers[k.strip().lower()] = v.strip()
|
|
175
|
+
disposition = headers.get("content-disposition", "")
|
|
176
|
+
if disposition.split(";")[0].strip().lower() != "form-data":
|
|
177
|
+
raise RequestError("a multipart part needs Content-Disposition: form-data with a name")
|
|
178
|
+
parts.append((_param("content-disposition", disposition, "name"), headers.get("content-type"), data))
|
|
179
|
+
if len(parts) > MAX_PARTS:
|
|
180
|
+
raise RequestError(f"a multipart request has at most {MAX_PARTS} parts")
|
|
181
|
+
pos = end + 2 + len(sep)
|
|
182
|
+
return parts
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def multipart_body(raw, content_type, parts=None):
|
|
186
|
+
"""A multipart/form-data decision request (3.0) -> the JSON body it stands for: the part named "request" is the
|
|
187
|
+
request as JSON (application/json; without "media", or with media items that come first), and every part named
|
|
188
|
+
"media" is one media item, its type from its Content-Type (image/... or audio/...), its bytes base64-encoded as
|
|
189
|
+
in a JSON request, so every check, limit and the decision log key are those of the same request sent as JSON.
|
|
190
|
+
parts: read_multipart(raw, content_type), when the caller has read them."""
|
|
191
|
+
import base64
|
|
192
|
+
body, media = None, []
|
|
193
|
+
for name, ctype, data in read_multipart(raw, content_type) if parts is None else parts:
|
|
194
|
+
if name == "request":
|
|
195
|
+
if body is not None:
|
|
196
|
+
raise RequestError('a multipart request has one part named "request"')
|
|
197
|
+
if ctype and ctype.split(";")[0].strip().lower() not in ("application/json", "text/plain"):
|
|
198
|
+
raise RequestError('the "request" part is the request as JSON (Content-Type application/json)')
|
|
199
|
+
body = read_json(data)
|
|
200
|
+
if not isinstance(body, dict):
|
|
201
|
+
raise RequestError('the "request" part must be a JSON object')
|
|
202
|
+
elif name == "media":
|
|
203
|
+
kind = MEDIA_TYPES.get((ctype or "").split("/")[0].strip().lower())
|
|
204
|
+
if kind is None:
|
|
205
|
+
raise RequestError(f"media part {len(media)}: its Content-Type must be image/... or audio/..., not "
|
|
206
|
+
f"{ctype!r}")
|
|
207
|
+
media.append({"type": kind, "data": base64.b64encode(data).decode("ascii")})
|
|
208
|
+
else:
|
|
209
|
+
raise RequestError(f'a multipart part is named "request" (the JSON request) or "media" (a file), not '
|
|
210
|
+
f"{name!r}")
|
|
211
|
+
if body is None:
|
|
212
|
+
raise RequestError('a multipart request needs a part named "request" (the request as JSON)')
|
|
213
|
+
if media:
|
|
214
|
+
if body.get("images") is not None:
|
|
215
|
+
raise RequestError('give media or images, not both (the media parts are "media")')
|
|
216
|
+
if body.get("media") is not None and not isinstance(body["media"], list):
|
|
217
|
+
raise RequestError('"media" must be a list')
|
|
218
|
+
body["media"] = list(body.get("media") or []) + media
|
|
219
|
+
return body
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def multipart_key(parts):
|
|
223
|
+
"""What --response-cache-mb keys a multipart/form-data request by (3.0): its parts as multipart_body reads them,
|
|
224
|
+
[(head, bytes)] in order, each head the part's name, the media kind of a media part and the length of its bytes;
|
|
225
|
+
not the boundary or the part headers that do not count (a file name), which a client picks (the boundary at random
|
|
226
|
+
for each request), so the same request sent again is the same entry."""
|
|
227
|
+
out = []
|
|
228
|
+
for name, ctype, data in parts:
|
|
229
|
+
kind = MEDIA_TYPES.get((ctype or "").split("/")[0].strip().lower(), "") if name == "media" else ""
|
|
230
|
+
out.append((f"{name}\0{kind}\0{len(data)}\0".encode("utf-8", "surrogatepass"), data))
|
|
231
|
+
return out
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def parse_body(raw):
|
|
235
|
+
"""A request body read once for basal-router (routing, the cascade, the blend, the fallback): the JSON object, or
|
|
236
|
+
None when it is not one basal-serve would take (not JSON, not an object, nested too deeply, a lone surrogate); the
|
|
237
|
+
replica it goes to then answers it with its own error."""
|
|
238
|
+
try:
|
|
239
|
+
body = read_json(raw)
|
|
240
|
+
if not isinstance(body, dict):
|
|
241
|
+
return None
|
|
242
|
+
check_json(body, finite=())
|
|
243
|
+
except RequestError:
|
|
244
|
+
return None
|
|
245
|
+
return body
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def text_of(x):
|
|
249
|
+
"""Strings as they are; structured values (objects, lists, numbers) as compact JSON, as the model sees them."""
|
|
250
|
+
return x if isinstance(x, str) else json.dumps(x, ensure_ascii=False)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def named_options(crit, option_keys="show"):
|
|
254
|
+
"""{key: description} -> (keys, option texts shown to the model).
|
|
255
|
+
|
|
256
|
+
option_keys="show" (default): every described option is shown as "key: description", because only the caller knows
|
|
257
|
+
whether a key is meaningful (a service code "B", a decision name "approve"); the server never guesses. A key without
|
|
258
|
+
a description is shown by itself.
|
|
259
|
+
option_keys="hide": the caller states that the keys are placeholders and the descriptions alone define the options
|
|
260
|
+
(the format of the training data and of our PL/EN evaluation clients); descriptions that are not unique within the
|
|
261
|
+
question still get their key, otherwise the options could not be told apart."""
|
|
262
|
+
if option_keys not in ("show", "hide"):
|
|
263
|
+
raise RequestError(f'option_keys must be "show" or "hide", got {option_keys!r}')
|
|
264
|
+
texts = [str(k) if v is None else text_of(v) for k, v in crit.items()]
|
|
265
|
+
dup = {t for t, n in Counter(texts).items() if n > 1} # (once: texts.count per option took 4.5 s for 32,000)
|
|
266
|
+
shown = [t if v is None or (option_keys == "hide" and t not in dup) else f"{k}: {t}"
|
|
267
|
+
for (k, v), t in zip(crit.items(), texts)]
|
|
268
|
+
return list(crit), shown
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
OPENAI_PATHS = ("/v1/decisions", "/decisions", "/v1/chat/completions") # their clients read OpenAI's error object
|
|
272
|
+
OPENAI_TYPES = {401: "authentication_error", 403: "permission_error"}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def error_object(path, status, message, code=None):
|
|
276
|
+
"""An error made before a route (auth, the body limit, the Host check, the router) in the shape its clients read:
|
|
277
|
+
OpenAI's {"error": {"message", "type", "param", "code"}} on OPENAI_PATHS (/v1/decisions, the chat completions of
|
|
278
|
+
--chat-classify on; a code below 500 kept, none at 5xx, as their routes answer), else basal's {"error"[, "code"]}."""
|
|
279
|
+
if path in OPENAI_PATHS:
|
|
280
|
+
kind = OPENAI_TYPES.get(status, "invalid_request_error" if status < 500 else "server_error")
|
|
281
|
+
return {"error": {"message": message, "type": kind, "param": None, "code": code if status < 500 else None}}
|
|
282
|
+
return {"error": message, "code": code} if code else {"error": message}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def limit_body(app, max_bytes):
|
|
286
|
+
"""ASGI: a request body over max_bytes answers 413 before the app reads it (its Content-Length), or as soon as more
|
|
287
|
+
of it arrived (a body sent without one: the app sees the client gone, and its answer is replaced by the 413)."""
|
|
288
|
+
async def too_large(scope, send):
|
|
289
|
+
msg = f"the request body is larger than this server's limit of {max_bytes} bytes (--max-body-mb)"
|
|
290
|
+
body = error_object(scope["path"], 413, msg, "PAYLOAD_TOO_LARGE")
|
|
291
|
+
await send({"type": "http.response.start", "status": 413,
|
|
292
|
+
"headers": [(b"content-type", b"application/json"), (b"connection", b"close")]})
|
|
293
|
+
await send({"type": "http.response.body", "body": json.dumps(body).encode()})
|
|
294
|
+
|
|
295
|
+
async def limited(scope, receive, send):
|
|
296
|
+
if scope["type"] != "http":
|
|
297
|
+
await app(scope, receive, send)
|
|
298
|
+
return
|
|
299
|
+
length = dict(scope.get("headers", ())).get(b"content-length", b"")
|
|
300
|
+
if length.isdigit() and int(length) > max_bytes:
|
|
301
|
+
await too_large(scope, send)
|
|
302
|
+
return
|
|
303
|
+
seen, over = 0, False
|
|
304
|
+
|
|
305
|
+
async def counted():
|
|
306
|
+
nonlocal seen, over
|
|
307
|
+
if over:
|
|
308
|
+
return {"type": "http.disconnect"}
|
|
309
|
+
message = await receive()
|
|
310
|
+
if message["type"] == "http.request":
|
|
311
|
+
seen += len(message.get("body", b""))
|
|
312
|
+
if seen > max_bytes:
|
|
313
|
+
over = True
|
|
314
|
+
return {"type": "http.disconnect"}
|
|
315
|
+
return message
|
|
316
|
+
|
|
317
|
+
async def answer(message):
|
|
318
|
+
if not over:
|
|
319
|
+
await send(message)
|
|
320
|
+
try:
|
|
321
|
+
await app(scope, counted, answer)
|
|
322
|
+
except Exception: # noqa: BLE001 (the app's error over a body it never got whole)
|
|
323
|
+
if not over:
|
|
324
|
+
raise
|
|
325
|
+
if over:
|
|
326
|
+
await too_large(scope, send)
|
|
327
|
+
return limited
|
basal/response_cache.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""basal-serve --response-cache-mb (3.0): answers to requests already answered, from memory.
|
|
2
|
+
|
|
3
|
+
A decision request (POST /v1/systemone, /v1/basal, /v1/decisions) whose path and body bytes, under the same served
|
|
4
|
+
model, adapter and calibration, were answered before (HTTP 200) within --response-cache-ttl seconds gets the bytes of
|
|
5
|
+
that response again, byte for byte, without the engine; the response header x-basal-cache says hit or miss. The key
|
|
6
|
+
is the sha256 of the server's identity, the path and the body as sent (so every field of the request counts: the
|
|
7
|
+
state, the questions, lang, facts, media, think, trace, errors, ...; the same request written with other spacing is
|
|
8
|
+
another key; a multipart/form-data request: its request part as sent and each media part's kind and bytes, not its
|
|
9
|
+
boundary, which a client picks at random for each request) and, with --api-keys, of the key the client presented:
|
|
10
|
+
clients of different keys never share an entry.
|
|
11
|
+
Without --api-keys the cache is shared by every client, so a client can tell (x-basal-cache, and the time) whether the
|
|
12
|
+
same request was answered before: keep it off where clients must not learn about each other's requests. At most --response-cache-mb MiB of responses are kept, the least recently used dropped first. A hit
|
|
13
|
+
writes the --log-decisions lines of the request that computed it again (with the time of the hit), so the log still
|
|
14
|
+
has one line per request served. Off by default; nothing is kept or hashed without it."""
|
|
15
|
+
import collections
|
|
16
|
+
import hashlib
|
|
17
|
+
import json
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
ENTRY_BYTES = 256 # what an entry costs besides its response and log lines (key, tuple, dict slot), counted
|
|
21
|
+
TTL_S = 600.0 # --response-cache-ttl default
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ResponseCache:
|
|
25
|
+
def __init__(self, max_bytes, ttl=TTL_S, identity="", clock=time.monotonic):
|
|
26
|
+
self.max_bytes, self.ttl, self.clock = int(max_bytes), float(ttl), clock
|
|
27
|
+
self.identity = hashlib.sha256(identity.encode("utf-8", "surrogatepass")).digest()
|
|
28
|
+
self.entries = collections.OrderedDict() # key -> (expires at, response bytes, log lines, size)
|
|
29
|
+
self.bytes = 0
|
|
30
|
+
self.hits = self.misses = 0
|
|
31
|
+
self.evicted = {"size": 0, "ttl": 0}
|
|
32
|
+
|
|
33
|
+
def key(self, path, raw, client="", parts=None):
|
|
34
|
+
"""The entry of a request: path and body bytes, under the server's identity and, with --api-keys, the client's
|
|
35
|
+
key (client: the sha256 hex of the key it presented), so clients of different keys never share an entry.
|
|
36
|
+
parts: a multipart/form-data request's parts (request.multipart_key), keyed instead of its body bytes."""
|
|
37
|
+
h = hashlib.sha256(self.identity)
|
|
38
|
+
h.update(client.encode("ascii", "replace") + b"\0")
|
|
39
|
+
h.update(path.encode() + b"\0")
|
|
40
|
+
if parts is None:
|
|
41
|
+
h.update(raw)
|
|
42
|
+
else: # (a marker first: no JSON body starts with a NUL)
|
|
43
|
+
h.update(b"\0multipart/form-data\0")
|
|
44
|
+
for head, data in parts:
|
|
45
|
+
h.update(head)
|
|
46
|
+
h.update(data)
|
|
47
|
+
return h.digest()
|
|
48
|
+
|
|
49
|
+
def get(self, key):
|
|
50
|
+
"""(response bytes, log lines) of a live entry, or None (counted as a hit or a miss)."""
|
|
51
|
+
e = self.entries.get(key)
|
|
52
|
+
if e is not None and e[0] <= self.clock():
|
|
53
|
+
self._drop(key)
|
|
54
|
+
self.evicted["ttl"] += 1
|
|
55
|
+
e = None
|
|
56
|
+
if e is None:
|
|
57
|
+
self.misses += 1
|
|
58
|
+
return None
|
|
59
|
+
self.entries.move_to_end(key)
|
|
60
|
+
self.hits += 1
|
|
61
|
+
return e[1], e[2]
|
|
62
|
+
|
|
63
|
+
def put(self, key, body, logged=()):
|
|
64
|
+
"""Keep a response (bytes) and the log lines its request wrote (dicts without their time); one larger than
|
|
65
|
+
the whole cache is not kept."""
|
|
66
|
+
lines = tuple(json.dumps(x, ensure_ascii=False).encode("utf-8") for x in logged)
|
|
67
|
+
size = len(body) + sum(map(len, lines)) + ENTRY_BYTES
|
|
68
|
+
if size > self.max_bytes:
|
|
69
|
+
return
|
|
70
|
+
if key in self.entries:
|
|
71
|
+
self._drop(key)
|
|
72
|
+
self.entries[key] = (self.clock() + self.ttl, body, lines, size)
|
|
73
|
+
self.bytes += size
|
|
74
|
+
while self.bytes > self.max_bytes:
|
|
75
|
+
self._drop(next(iter(self.entries)))
|
|
76
|
+
self.evicted["size"] += 1
|
|
77
|
+
|
|
78
|
+
def _drop(self, key):
|
|
79
|
+
self.bytes -= self.entries.pop(key)[3]
|
|
80
|
+
|
|
81
|
+
def metrics(self):
|
|
82
|
+
"""/metrics families of the cache (basal.metrics.prometheus rows)."""
|
|
83
|
+
return [
|
|
84
|
+
("basal_response_cache_hits_total", "decision requests answered from --response-cache-mb", "counter",
|
|
85
|
+
[({}, self.hits)]),
|
|
86
|
+
("basal_response_cache_misses_total", "decision requests looked up and not found (or expired)", "counter",
|
|
87
|
+
[({}, self.misses)]),
|
|
88
|
+
("basal_response_cache_entries", "responses kept", "gauge", [({}, len(self.entries))]),
|
|
89
|
+
("basal_response_cache_bytes", "bytes kept (responses, their log lines, per-entry overhead)", "gauge",
|
|
90
|
+
[({}, self.bytes)]),
|
|
91
|
+
("basal_response_cache_evictions_total", "responses dropped, by reason (size: least recently used to fit "
|
|
92
|
+
"--response-cache-mb; ttl: older than --response-cache-ttl)", "counter",
|
|
93
|
+
[({"reason": k}, n) for k, n in self.evicted.items()])]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def relog(log, lines, request_id=None):
|
|
97
|
+
"""The log lines of a cached response written again, each with the time of the hit (first, as log_decision writes
|
|
98
|
+
it), the hit's own request id (a line that has one: basal/decision_log.py) and "cache": "hit", so a join of the
|
|
99
|
+
log with labels (basal/feedback.py) can tell the decision computed once from its repetitions."""
|
|
100
|
+
for line in lines:
|
|
101
|
+
rec = {"ts": time.time(), **json.loads(line)}
|
|
102
|
+
if "request_id" in rec:
|
|
103
|
+
rec["request_id"] = request_id or rec["request_id"]
|
|
104
|
+
rec["cache"] = "hit"
|
|
105
|
+
log.write(json.dumps(rec, ensure_ascii=False) + "\n")
|