serve/server.py: 230 definitions move unchanged into serve/server_parts/ (file split, 2,498 of 11,310 lines)

Made by tools/layout/split/split_server_run.py on the moved tree. A definition moves only when no test replaces it, nothing rebinds
it at run time (two global statements, no globals() or __dict__ writes, no assignment from other non-test code), and everything it uses
moves with it. The text is copied unchanged into seven modules (base, core, engines, http_api, openai_api, anthropic_api, end_tokens);
serve/server.py imports the names back, so serve.server.<name> works as before. The script checks that every moved definition's syntax
tree equals the original's and that every other statement is unchanged.

tests/terminal/test_no_debugger_children.py: the table that counts process-start sites per file lists the two that moved
(serve/server.py 7 -> 5, serve/server_parts/engines.py 2).
This commit is contained in:
Niko1221 committed 2026-11-17 13:22:08 +01:00
1 parent 4058aa782b
commit 7d77f51caa
10 files changed
+3285 -2854

No files matched your search

+245 -2853
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
"""Parts moved unchanged out of serve/server.py (file split, cleanup step 5)."""
@@ -0,0 +1,46 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the Anthropic part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
import json
def anthropic_collect(events) -> dict:
msg, blocks = None, []
for item in events:
if item is None: # a heartbeat
continue
name, e = item
if name == "message_start":
msg = e["message"]
elif name == "content_block_start":
blocks.append(dict(e["content_block"]))
elif name == "content_block_delta":
d, b = e["delta"], blocks[-1]
if d["type"] == "text_delta":
b["text"] += d["text"]
elif d["type"] == "thinking_delta":
b["thinking"] += d["thinking"]
else: # input_json_delta pieces: parsed when complete
b["_json"] = b.get("_json", "") + d["partial_json"]
elif name == "content_block_stop" and blocks and "_json" in blocks[-1]:
b = blocks[-1]
try:
b["input"] = json.loads(b.pop("_json") or "{}")
except ValueError: # a call the output ended inside (#211): it has no input to give
blocks.pop()
elif name == "message_delta":
msg["stop_reason"] = e["delta"]["stop_reason"]
msg["stop_sequence"] = e["delta"].get("stop_sequence")
msg["usage"].update(e["usage"])
if e.get("strata_rejected_tool_calls"):
msg["strata_rejected_tool_calls"] = e["strata_rejected_tool_calls"]
if e.get("strata_unread_tool_markup"):
msg["strata_unread_tool_markup"] = e["strata_unread_tool_markup"]
for i in range(len(blocks) - 1): # a turn with no </think>: the text is the answer; it is not also a thinking block
a, b = blocks[i], blocks[i + 1]
if a.get("type") == "thinking" and b.get("type") == "text" and a.get("thinking", "").strip() == b.get("text", "").strip():
del blocks[i]
break
msg["content"] = blocks
return msg
+302
View File
@@ -0,0 +1,302 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the head part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
import collections
import os
import re
import sys
from pathlib import Path
PICTURE_FORMATS = ("JPEG", "PNG", "GIF", "BMP", "WEBP", "TIFF", "AVIF") # the picture formats a request may send (Pillow decodes them)
IM_END = "<|im_end|>"
IMAGE_PAD = "<|image_pad|>"
def rttime_limit_note() -> str:
"""#3238: Linux only. A hard RLIMIT_RTTIME that is not unlimited (PipeWire's client module sets it to 0 when rtkit is
missing; every program started from that desktop inherits it) makes the kernel SIGKILL a process as soon as it
checks a thread with an armed CPU timer, with no OOM kill and no message. Returns one sentence naming the cause and
the fix, or "" when the limit is unlimited, the platform has no such limit or it cannot be read."""
try:
import resource
soft, hard = resource.getrlimit(resource.RLIMIT_RTTIME)
except (ImportError, AttributeError, OSError, ValueError):
return ""
if hard == resource.RLIM_INFINITY:
return ""
return (f"This session has a real-time CPU limit (RLIMIT_RTTIME hard limit {hard}; the desktop's audio system sets "
"it to 0 when rtkit is not installed). Linux can then end a program with signal 9 for no visible reason. "
"Install rtkit, or start Strata outside the desktop session's limits, for example: "
"systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ...")
LEFTOVER_SETTLE_S = 120.0 # #4051: how long an engine ended at a start is waited for to give its memory back
def listen_problem(host: str, port: int, e: OSError) -> str:
"""#769: why the server cannot listen. Only an address that is taken says "already in use"; anything else (a port
Windows keeps reserved, an address this PC does not have, no permission) says what the OS said."""
import errno
code = getattr(e, "winerror", None) or e.errno
if code in (errno.EADDRINUSE, 10048):
return (f"port {port} is already in use - is Strata (or another server) already running? "
f"Close it, or start this one with a different --port")
what = e.strerror or str(e)
if code in (10013, errno.EACCES):
if sys.platform == "win32":
hint = ("Windows may keep this port for itself (see `netsh int ipv4 show excludedportrange protocol=tcp`) "
"or a firewall rule forbids it: start this one with a different --port")
else:
hint = ("This system does not allow it (on Linux and macOS, ports below 1024 need administrator rights): "
"start this one with a different --port")
elif code in (10049, errno.EADDRNOTAVAIL):
hint = f"{host} is not an address of this PC: check \"host\" in the model's strata-<model>.json or --host"
else:
hint = "check --host and --port"
return f"cannot listen on {host}:{port}: {what} [{code}]. {hint}"
def write_temporary(path: Path, parts: list) -> None:
"""#874: write `parts` (files) one after the other into `path`; on Windows with FILE_ATTRIBUTE_TEMPORARY
(os.O_SHORT_LIVED), so the file normally never reaches the drive before it is deleted."""
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) | getattr(os, "O_SHORT_LIVED", 0)
with os.fdopen(os.open(path, flags, 0o600), "wb") as f:
for part in parts:
f.write(Path(part).read_bytes())
# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the
# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top
EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n"
EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the "
"conclusion without unnecessary elaboration.",
"medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary "
"elaboration.",
# the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one
"xhigh": "Reasoning effort is set to xhigh. Please think carefully through the task, validate key "
"assumptions, consider plausible alternatives, and prioritize correctness, consistency, and "
"clarity in the final answer."}
VISION_START = "<|vision_start|>"
# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a
# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens"
# sets it; 0 turns it off.
REPEAT_STOP_TOKENS = 256
ANSWER_ROOM_MIN_CAP = 1024 # 0.1.45: from this max_tokens on, thinking without a budget is closed early enough to leave room to answer
ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens
FIT_MIN_ROOM = 1024 # #5924: fit_max_tokens never shortens max_tokens below this (a 400 instead; see fit_floor)
def fit_floor(ctx: int) -> int:
"""#5924: the least room fit_max_tokens shortens a max_tokens to: FIT_MIN_ROOM (thinking plus an answer or a tool
call), at most a quarter of a small context (test and tiny contexts keep their shortening)."""
return max(1, min(FIT_MIN_ROOM, (ctx - CTX_SLACK) // 4))
# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)
# #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside <think>, with no answer
# and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it)
REASONING_CLOSE = "\n</think>\n\n"
REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"
# The budget's pass to an engine that says "hold" in READY carries GEN hold=N:ID (N: the reasoning tokens left, ID: the one
# token of </think>): the engine stops there with its session at exactly the tokens it sent, so the next pass (+ the wrap-up)
# continues from the live session. Without it the engine ran a window or two past the cut, and the next pass read the
# whole reasoning again from the checkpoint before it. The server's own key in `sampling`, never a client's.
HOLD_KEY = "_strata_hold"
# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see).
# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the
# low-effort instruction in place of the xhigh one. Both off by default.
HIGH_EFFORT = EFFORT_TEXT["xhigh"]
LOW_EFFORT = EFFORT_TEXT["low"]
LOOP_CHECK_EVERY = 512 # output tokens between two looks at the reasoning (at a clean parser boundary)
LOOP_COVERAGE = 0.25 # the share of the last 2,000 words inside 12-word passages seen three times
LOOP_HISTORY_WORDS = 30000 # how far back the passages are counted (bounds the cost of a look)
LOOP_TAIL_CHARS = 2048 # chars at the end of the reasoning also checked for a short period (#1753)
LOOP_TAIL_PERIOD = 64 # a period at most this long in that tail reads as a fully repeated window
def reasoning_repeat_coverage(text):
"""Coverage of recent words by 12-word passages seen at least three times.
Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes
separated by long code drafts; the recent window excludes old repetitions. #1753: a loop can also be one long
word (a 24k-digit string cycling an 11-digit pattern): the word split makes it a single word and no word count
grows, and #606's token run never grows either (the tokenizer has no multi-digit tokens), so before the word
count the last LOOP_TAIL_CHARS chars are checked for a period of at most LOOP_TAIL_PERIOD, and a periodic tail
reads as full coverage: it is all of the recent output, repeated.
"""
tail = text[-LOOP_TAIL_CHARS:].lower()
if len(tail) == LOOP_TAIL_CHARS and any(tail[p:] == tail[:-p] for p in range(1, LOOP_TAIL_PERIOD + 1)):
return 1.0
words = re.findall(r"\w+|[^\w\s]", text.lower())[-LOOP_HISTORY_WORDS:]
width, window = 12, 2000
if len(words) < window:
return 0.0
grams = [tuple(words[i:i + width]) for i in range(len(words) - width + 1)]
counts = collections.Counter(grams)
start = max(0, len(words) - window)
covered = set()
for i in range(start, len(grams)):
if counts[grams[i]] >= 3:
covered.update(range(i, i + width))
return len(covered) / (len(words) - start)
def focused_recovery_prompt(tok, ids, generated):
"""The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then
every token generated so far. A splice of token ids: the prompt is never decoded and encoded again, so a literal
`</think>` or vision marker in it (#537, #554) stays what it was. None when the sentence is not there as whole
tokens in the first system message (a user's text never counts). No answer or end-of-thinking is inserted."""
end = tok.encode(IM_END, parse_special=True)
if len(end) != 1 or end[0] not in ids:
return None
head = ids[:ids.index(end[0])]
if not tok.decode(head).startswith("<|im_start|>system\n"):
return None
old, new = tok.encode(HIGH_EFFORT, parse_special=False), tok.encode(LOW_EFFORT, parse_special=False)
for i in range(len(head) - len(old) + 1):
if head[i:i + len(old)] == old:
return ids[:i] + new + ids[i + len(old):] + list(generated)
return None
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
KEEPALIVE_S = 10.0 # a held-back tool argument leaves the stream quiet: ping at least this often
# Anthropic clients add /v1/messages to their base URL themselves. A base URL that already ends in /v1 (copied from an OpenAI-style
# setup) makes them post /v1/v1/messages; these two paths mean the same as the real ones. Nothing else is aliased.
V1_V1_ALIASES = {"/v1/v1/messages": "/v1/messages", "/v1/v1/messages/count_tokens": "/v1/messages/count_tokens"}
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
class ContextOverflow(ValueError):
"""A request that does not fit the context (a 400 on every API). It keeps the numbers, so /v1/messages can also say it the way Anthropic's API
does: a client that decides from the wording (Claude Code compacts on "prompt is too long", and shortens max_tokens on "input length and
`max_tokens` exceed context limit") then does what it does for Anthropic's own error (#4838)."""
def __init__(self, text, *, prompt, context, max_new=None, min_room=None):
super().__init__(text)
self.prompt, self.context, self.max_new, self.min_room = prompt, context, max_new, min_room
def anthropic_text(self) -> str:
if self.min_room: # #5924: room left, but less than an answer needs: the client should compact
return f"prompt is too long: {self.prompt} tokens > {self.context - CTX_SLACK - self.min_room} maximum; {self}"
if self.max_new is None or self.prompt > self.context - CTX_SLACK - 1: # the prompt alone leaves no room: the largest one that still leaves a token
return f"prompt is too long: {self.prompt} tokens > {self.context - CTX_SLACK - 1} maximum; {self}"
return f"input length and `max_tokens` exceed context limit: {self.prompt} + {self.max_new} > {self.context - CTX_SLACK}; {self}"
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
RATE_WINDOW_S = 2.0
RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean so far, with the span floored here
# #481: a running request whose engine prints nothing (no T, PP or any other line) for this long has lost step with the
# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails;
# the next request starts it again. The config's "engine_silence_s" sets it (0: wait forever, as before).
ENGINE_SILENCE_S = 300.0
# Disk sessions: the longest allowance an engine may announce (`SWAIT <phase> <s>`) for one step that blocks in a
# single call (a file flush, the host->device transfer); the engine's own bound is the same (session_phase_limit_s).
SESSION_WAIT_MAX_S = 3600
# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue
# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line. Until the first
# PP the wait adds the chunk's tokens at PP_FLOOR_TOK_S; after one, a chunk may take PP_SLACK x the last one's time.
PP_CHUNK_MAX = 32768
PP_FLOOR_TOK_S = 50.0
PP_SLACK = 3.0
def _timeout_env(name: str, default: float) -> float | None:
try:
v = float(os.environ.get(name, default))
except ValueError:
v = default
return None if v <= 0 else v
PAR_COUNTERS = os.environ.get("STRATA_PAR_COUNTERS") == "1" # research counters (queue wait for a slot), shown in /v1/status
# STRATA_COALESCE_PREFILL=N (research, PAR-H; needs the engine's BCO / BCOK lines): a request that takes the control lines
# for its admission also sends the prompts of up to N-1 requests still waiting for them (BCO <slot> <ids>, into free slots
# it reserves for them); the engine reads all the prompts in ONE layer-major pass, so the experts a layer streams are
# read once for all of them, and each waiting request then finds its prompt in its slot. 0 / unset: off.
COALESCE_PREFILL = max(0, int(os.environ.get("STRATA_COALESCE_PREFILL") or 0))
COALESCE_TOKENS = max(256, int(os.environ.get("STRATA_COALESCE_TOKENS") or 16384)) # prompt tokens read together at most
COALESCE_WAIT_MS = max(0, int(os.environ.get("STRATA_COALESCE_WAIT_MS") or 0)) # a burst's later requests register within this long
# Adaptive: a read is shared (and the leader waits for its followers) only when this engine has seen at least
# COALESCE_MIN_REQS requests arrive within COALESCE_BURST_MS (the leader's own included). Fewer than that - one or two
# requests per engine, as 8 requests on 4 replicas - read plainly, with no wait: nothing to share, and the wait and the
# longer pass only cost (measured 4 x 1 replicas at 8 requests: 168 against 196 tok/s with an unconditional wait).
COALESCE_MIN_REQS = max(2, int(os.environ.get("STRATA_COALESCE_MIN_REQS") or 3))
COALESCE_BURST_MS = max(10, int(os.environ.get("STRATA_COALESCE_BURST_MS") or 250))
STALL_CPU_EPS_S = 0.5 # CPU seconds the engine may use in the whole stall window and still count as frozen
STALL_IO_EPS_B = 1 << 20 # bytes read or written in that window
def engine_frozen(base: tuple[float, int], now: tuple[float, int]) -> bool:
"""#1317: True when two (cpu seconds, io bytes) samples of the engine show no work between them."""
return (now[0] - base[0]) <= STALL_CPU_EPS_S and (now[1] - base[1]) <= STALL_IO_EPS_B
+444
View File
@@ -0,0 +1,444 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the core part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
import codecs
import os
import re
from serve.frontend import CALL_END, CALL_START, FUNC_END, FUNC_START, Event
from serve.server_parts.base import RATE_MIN_SPAN_S
class Detokenizer:
"""Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete
characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become
U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of
every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer
without `token_bytes` (the tests' byte tokenizer) keeps the re-decode."""
def __init__(self, tok):
self.tok, self.ids, self.sent = tok, [], 0
self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None
def pending(self) -> bool:
"""A character is split across the tokens so far: its first bytes are held."""
if self.inc is not None:
return bool(self.inc.getstate()[0])
return self.tok.decode(self.ids).endswith("\ufffd")
def push(self, t: int) -> str:
if self.inc is not None:
return self.inc.decode(self.tok.token_bytes(t))
self.ids.append(t)
text = self.tok.decode(self.ids)
if text.endswith("�"):
return ""
delta, self.sent = text[self.sent:], len(text)
return delta
OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop`
#: What a request may ask for that the all-cards split engine cannot do (its GEN parser has no such keys): answered with a 400 before anything is sent, not with an error in
#: the middle of a reply. logit_bias is refused the same way by logit_bias.validate_request (the split engine does not report logit_bias=1).
SPLIT_REFUSED_FEATURES = ("logprobs", "logit_bias")
def top_logprobs(req: dict):
"""The K for the engine's logprobs=K, or None when the request did not ask.
OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form,
"logprobs": N, is taken as N."""
lp = req.get("logprobs")
if lp is True:
k = req.get("top_logprobs")
return max(0, min(20, k)) if isinstance(k, int) and not isinstance(k, bool) else 0
if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0:
return min(20, lp)
return None
def allowed_ids(req: dict) -> list:
"""`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries)."""
ids = req.get("allowed_token_ids")
if not isinstance(ids, (list, tuple)):
return []
return [x for x in ids if isinstance(x, int) and not isinstance(x, bool) and x >= 0]
def batch_slots_on(engine) -> bool:
"""Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)?
Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it
counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel`
has none, and reads every reply by the GEN path, which does write them."""
return any(int(getattr(e, "batch", 0) or 0) for e in (getattr(engine, "engines", None) or [engine]))
NO_LINE = object() # StrataEngine.generate: no line held after a token
def token_limit(value, name: str):
"""#4037: a reply's token limit (max_tokens, max_completion_tokens) is a whole number: 1 or more, or -1 / 0 for no cap
(docs/DETAILS.md). None (absent or null) stays None. A whole number written as a float (4096.0) or as a string of
digits with an optional sign ("1024": clients rely on it, as int() always took it) is converted. A boolean, a fraction
(2.5, "2.5"), any other string or any other type is refused: int() used to turn true into 1 and 2.5 into 2.
ValueError = a 400."""
if value is None:
return None
if isinstance(value, str) and re.fullmatch(r"[+-]?[0-9]+", value):
value = int(value)
if isinstance(value, bool) or not isinstance(value, (int, float)) or (isinstance(value, float) and not value.is_integer()) \
or value < -1:
raise ValueError(f"{name} must be a whole number, 1 or more, or -1 or 0 for no cap")
return int(value)
def stop_strings(req: dict) -> list[str]:
"""The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences`
(a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated."""
req = req or {}
if req.get("stop") is not None:
stop = req["stop"]
stop = [stop] if isinstance(stop, str) else stop
if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop):
raise ValueError("stop must be a string or a list of strings")
if len(stop) > OPENAI_MAX_STOP:
raise ValueError(f"stop takes at most {OPENAI_MAX_STOP} strings")
elif req.get("stop_sequences") is not None:
stop = req["stop_sequences"]
if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop):
raise ValueError("stop_sequences must be a list of strings")
else:
return []
return [x for x in stop if x]
class StopMatcher:
"""Cuts the answer's text at the first stop string. Text that could still be the start of a stop string is held
back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent."""
def __init__(self, stops: list[str]):
self.stops, self.held, self.hit = stops, "", None
def push(self, text: str) -> str:
"""-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes."""
if self.hit is not None:
return ""
buf = self.held + text
first = None
for s in self.stops:
i = buf.find(s)
if i >= 0 and (first is None or i < first[0]):
first = (i, s)
if first is not None:
self.held, self.hit = "", first[1]
return buf[:first[0]]
keep = 0 # the longest end of buf that a stop string starts with
for s in self.stops:
for k in range(min(len(s) - 1, len(buf)), keep, -1):
if buf.endswith(s[:k]):
keep = k
break
self.held = buf[len(buf) - keep:] if keep else ""
return buf[:len(buf) - keep]
def flush(self) -> str:
held, self.held = self.held, ""
return held
# Windows names that open a device whatever their extension or folder (Microsoft, "Naming Files, Paths, and Namespaces")
_WIN_DEVICES = {"con", "prn", "aux", "nul", "conin$", "conout$", *(f"com{i}" for i in "123456789\u00b9\u00b2\u00b3"),
*(f"lpt{i}" for i in "123456789\u00b9\u00b2\u00b3")}
def slot_filename_problem(name) -> str | None:
"""/slots/0 {"filename": NAME}: why NAME is not one plain file name inside the slot save path, on Linux and on
Windows alike (None when it is). No separator or drive (`D:x`), no stream (`a:b`), no device (`NUL.txt`), no
trailing dot or space (Windows drops them), no control character, no leading dot (temporary files use it)."""
if not isinstance(name, str) or not name:
return "must be a non-empty string"
if len(name.encode("utf-8", "surrogatepass")) > 200:
return "is too long (at most 200 bytes)"
if any(ord(c) < 32 or ord(c) == 127 for c in name):
return "must not contain control characters"
if any(c in name for c in '/\\:*?"<>|'):
return "must be a plain file name (no / \\ : * ? \" < > |)"
if name.startswith("."):
return "must not start with a dot"
if name.endswith((".", " ")):
return "must not end with a dot or a space"
if name.split(".")[0].rstrip(" ").lower() in _WIN_DEVICES:
return "names a Windows device"
try:
name.encode("utf-8")
except UnicodeEncodeError:
return "is not valid Unicode"
return None
def slot_save_dir(value, base: str | None = None) -> str:
"""The slot save path as one absolute, normalized directory (relative to `base`, else the server's working
directory), created private to this user when missing. ValueError for anything else."""
if not isinstance(value, str) or not value.strip():
raise ValueError("slot_save_path must be a directory path (a string)")
if any(ord(c) < 32 for c in value):
raise ValueError("slot_save_path must not contain control characters")
path = os.path.abspath(os.path.join(base, value) if base and not os.path.isabs(value) else value)
os.makedirs(path, mode=0o700, exist_ok=True)
if not os.path.isdir(path):
raise ValueError(f"slot_save_path {path} is not a directory")
return path
def closest_declared(name: str, declared: list[str]) -> str | None:
"""#5904 / #5933: the declared tool name an undeclared one comes closest to (`read_file` -> `read`), for the hint in
strata_rejected_tool_calls; None when none is clearly close. The one declared name the written one contains or is
contained in (ignoring case and `_` / `-` / `.`), else the best difflib match at a ratio of 0.75 or more."""
import difflib
if not name or not declared:
return None
norm = lambda s: re.sub(r"[_\-.\s]", "", s.lower()) # noqa: E731
n = norm(name)
inside = [d for d in declared if norm(d) and (norm(d) in n or n in norm(d))]
if len(inside) == 1:
return inside[0]
best = difflib.get_close_matches(name.lower(), [d.lower() for d in declared], n=1, cutoff=0.75)
if best:
return next(d for d in declared if d.lower() == best[0])
return None
TOOL_RETRY_MIN_ROOM = 64 # (a): the retry runs only with this many output tokens left after its note
_MARKUP_OPENER = re.compile(r"<tool_call>|<function=")
def _line_start(s: str, i: int) -> bool:
head = s[:i].rstrip(" \t")
return not head or head.endswith("\n")
def dead_markup_tail(text: str) -> tuple[int, str] | None:
"""The tool-call markup a reply's text ends in: (where the run of blocks at the end starts, "cut_off" | "unreadable"),
or None when the text does not end in one. A block opens with `<tool_call>` (or a bare `<function=`) at a line
start, outside a ``` fence; "cut_off": the last block has no closer (`</tool_call>`, or `</function>` for a bare one),
"unreadable": it closed (the parser read it as no call). Text after a block's closer means the reply went on: None."""
s = text.rstrip()
start, reason, end = None, None, len(s)
while True:
part = s[:end]
iw = max((m.start() for m in re.finditer(re.escape(CALL_START), part) if _line_start(part, m.start())), default=-1)
ib = max((m.start() for m in re.finditer(re.escape(FUNC_START), part) if _line_start(part, m.start())), default=-1)
bare = ib > iw and (iw < 0 or CALL_END in part[iw:ib])
i = ib if bare else iw
if i < 0:
break
body = part[i:]
closer = FUNC_END if bare else CALL_END
k = body.find(closer)
if k >= 0 and body[k + len(closer):].strip():
break # the block closed and text follows it: not the reply's end
closed = k >= 0
if reason is None:
reason = "unreadable" if closed or body.endswith(FUNC_END) else "cut_off"
elif not closed:
break # an unclosed block before the last one: the run starts after it
start, end = i, len(part[:i].rstrip())
if start is None or s[:start].count("```") % 2:
return None
return start, reason
def markup_names(text: str) -> list[str]:
"""The names written in the `<function=NAME>` openers of a piece of text."""
return [m.group(1).strip() for m in re.finditer(r"<function=([^<>\n]+?)>", text)]
def tool_retry_note(reason: str, names: list[str], declared: list[str], near: str | None) -> str:
"""(a): the user-turn note the one retry reads: why the call was not run, the declared tools, the hint."""
what = {"rejected": "it names " + ", ".join(f"`{x}`" for x in names) + ", which is not one of the tools you can call",
"cut_off": "it was cut off before its end",
"unreadable": "it is not in a form that can be read"}[reason]
listed = ", ".join(declared[:40]) + (f" and {len(declared) - 40} more" if len(declared) > 40 else "")
hint = f" Did you mean `{near}`?" if near else ""
return (f"[Strata server] Your last reply ended with a tool call that was not run: {what}.{hint} The tools you can "
f"call are: {listed}. Write the call again in this form, with a tool from that list:\n"
f"{CALL_START}\n{FUNC_START}TOOL_NAME>\n<parameter=PARAMETER_NAME>\nvalue\n</parameter>\n{FUNC_END}\n{CALL_END}\n"
"or answer in plain text if no tool is needed.")
class ToolMarkupHold:
"""(a) The answer's text from a tool-call opener at a line start is held back until the reply goes on past the block
(then it is sent as it is) or ends in it (then the server may write the reply's end again, once, in place of it).
Unarmed it holds nothing; it always keeps the text it sent, for strata_unread_tool_markup."""
def __init__(self, armed: bool):
self.armed = armed
self.held: list[Event] = []
self.text = ""
self.closed = False # a closer (`</tool_call>` / `</function>`) is in the held text
self.sent: list[str] = []
self.prev = "" # the last characters sent (a line start at the reply's start)
self.fences = 0 # ``` marks sent so far
self.calls = False # a tool call came out: the reply does not end in dead markup
self.started: set = set() # the ids of calls announced (tool_start) ...
self.finished: set = set() # ... and of those whose final tool_call came
def _send(self, ev: Event) -> Event:
if ev.text:
self.sent.append(ev.text)
self.prev = (self.prev + ev.text)[-16:]
self.fences += ev.text.count("```")
return ev
def _opener(self, text: str) -> int:
for m in _MARKUP_OPENER.finditer(text):
seen = self.prev + text[:m.start()]
if _line_start(seen, len(seen)) and (self.fences + text[:m.start()].count("```")) % 2 == 0:
return m.start()
return -1
def push(self, evs: list) -> list:
out = []
for ev in evs:
if ev.kind != "content":
if ev.kind in ("tool_start", "tool_call"):
self.calls = True
(self.started if ev.kind == "tool_start" else self.finished).add(ev.call.id)
out += self.release()
out.append(ev)
continue
text = ev.text or ""
if not self.held:
p = self._opener(text) if self.armed and text else -1
if p < 0:
out.append(self._send(ev))
continue
if p:
out.append(self._send(Event("content", text[:p])))
ev, text = Event("content", text[p:]), text[p:]
self.held.append(ev)
self.text += text
if not self.closed: # (until a closer arrives the block is open: held, no scan)
near = self.text[-(len(text) + len(CALL_END)):]
self.closed = CALL_END in near or FUNC_END in near
if self.closed and text.strip() and dead_markup_tail(self.text) is None:
out += self.release() # text after the block: the reply goes on
return out
def release(self) -> list:
evs, self.held, self.text, self.closed = self.held, [], "", False
return [self._send(ev) for ev in evs]
def drop(self) -> str:
text, self.held, self.text, self.closed = self.text, [], "", False
return text
def reply_text(self) -> str:
return "".join(self.sent)
def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:
"""#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped
its prompt read part-way (then the reused ones plus those read). /metrics' history and totals count these, so a
cancelled read is neither recorded as the whole prompt nor given a rate from tokens it never read. An engine
before 0.1.36 does not say (no `prompt_read`): the whole prompt, as before."""
read = last.get("prompt_read")
if read is None or last.get("finish") != "cancel":
return prompt_tokens
return min(prompt_tokens, int(last.get("reused") or 0) + int(read))
def carry_leg(carry: dict, leg: dict) -> None:
"""#1869: a request that decoded in a batch slot and went back to the solo path ends with the solo path's DONE, which
replaces the engine's figures: keep the slot leg's decode time, tokens and prompt figures to add to it."""
for key in ("decode_ms", "generated"):
previous, value = carry.get(key, 0), leg.get(key)
carry[key] = previous + value if previous is not None and value is not None else None
carry.setdefault("prompt_ms", float(leg.get("prompt_ms") or 0.0))
if leg.get("prompt_read") is not None:
carry.setdefault("prompt_read", int(leg["prompt_read"]))
def add_carry(carry: dict, last: dict) -> dict:
"""The request's totals: the earlier legs' decode time and tokens plus the final one's; the prompt figures of the leg
that read the prompt (the solo continuation reads next to nothing)."""
out = {**last, "prompt_ms": max(float(last.get("prompt_ms") or 0.0), carry.get("prompt_ms", 0.0))}
for key in ("decode_ms", "generated"):
previous, value = carry.get(key, 0), last.get(key)
out[key] = previous + value if previous is not None and value is not None else None
if "prompt_read" in carry:
out["prompt_read"] = carry["prompt_read"]
return out
def answer_speed(last: dict, generated: int, wall_s: float | None = None) -> float | None:
"""The one definition of "answer speed": every token the model produced (thinking and answer, the tokens it kept - not
the MTP drafts it threw away) over the decode time, first generated token to last. The engine's DONE line holds both
numbers; /metrics (`decode_tok_s`), the timings (`predicted_per_second`), the Terminal monitor and the app all use them.
Only an engine that sent no DONE falls back to the server's own clock from the first token, and a clock younger than
RATE_MIN_SPAN_S says nothing (it printed 1000000 tok/s for a one-token reply). Prompt reading is never in it."""
produced, decode_ms = last.get("generated"), last.get("decode_ms")
if produced and produced >= 2 and decode_ms and decode_ms > 0: # one token has no first-to-last span (a 1-token probe printed 1,250 tok/s)
return round(produced / (decode_ms / 1000), 1)
if generated and wall_s is not None and wall_s >= RATE_MIN_SPAN_S:
return round(generated / wall_s, 1)
return None
def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None:
"""One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock
(StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held. None when the
engine keeps no clock (MockEngine)."""
if last.get("prompt_ms") is None:
return None
cache_n = int(last.get("reused") or 0)
if last.get("prompt_read") is not None and last.get("finish") != "cancel":
# #1870: the engine says how many prompt tokens it read: the slot's own session may have held the rest
# (not the conversation cache), so the rate is not made of tokens it never read
cache_n = max(cache_n, max(0, prompt_tokens - int(last["prompt_read"])))
prompt_n, prompt_ms, decode_ms = max(0, prompt_tokens - cache_n), float(last["prompt_ms"]), last.get("decode_ms")
decoded = last.get("generated") # explicit zero and missing native work are not the API's output count
return {"cache_n": cache_n, "prompt_n": prompt_n, "prompt_ms": round(prompt_ms, 1),
"prompt_per_token_ms": round(prompt_ms / prompt_n, 3) if prompt_n else None,
"prompt_per_second": round(prompt_n / (prompt_ms / 1000), 1) if prompt_n and prompt_ms > 0 else None,
"predicted_n": generated, "predicted_ms": round(decode_ms, 1) if decode_ms is not None else None,
"predicted_per_token_ms": round(decode_ms / decoded, 3) if decoded and decode_ms is not None else None,
"predicted_per_second": round(decoded / (decode_ms / 1000), 1) if decoded and decode_ms and decode_ms > 0 else None,
# the speculative drafts, as llama.cpp names them (from PR #83, @mikicvi): only when the engine reported them
**({"draft_n": int(last["drafts_offered"]), "draft_n_accepted": int(last["drafts_accepted"])}
if last.get("drafts_offered") is not None else {})}
def request_stats(segments: list[dict]) -> dict:
"""Keep input/cache accounting at the original API boundary and total native work across continuations."""
if not segments:
return {}
result = dict(segments[-1])
for key in ("reused", "prompt_read", "chunk"):
if key in segments[0]:
result[key] = segments[0][key]
else:
result.pop(key, None)
for key in ("prompt_ms", "decode_ms", "generated", "drafts_offered", "drafts_accepted",
"hits", "lookups", "offloaded", "ram_blobs", "file_blobs", "file_mb", "experts_streamed"):
if key in ("decode_ms", "generated") and any(segment.get(key) is None for segment in segments):
result[key] = None
elif any(segment.get(key) is not None for segment in segments):
result[key] = sum(segment.get(key) or 0 for segment in segments)
return result
def prefill_leg_stats(earlier: list[dict], last: dict, prompt_tokens: int) -> dict:
"""Total yielded reads once, retaining only reuse from before this API request."""
legs = [*earlier, last]
total = request_stats(legs)
if all(leg.get("prompt_read") is not None for leg in legs):
fresh = max(0, prompt_tokens - int(total.get("reused") or 0))
total["prompt_read"] = min(fresh, sum(int(leg["prompt_read"]) for leg in legs))
return total
+25
View File
@@ -0,0 +1,25 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the end tokens part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
from serve.server_parts.base import IM_END
def end_token_ids(tokenizer) -> set[int]:
"""The ids that end a reply for a tokenizer whose family was not named.
Qwen's <|im_end|> and <|endoftext|> end a reply only where each is ONE token. A tokenizer without them (one that
splits "<|im_end|>" into '<', '|', 'im', '_end', '|', '>') would make every piece of them a stop id: the reply ended in front
of the first "|", ">", "end", "of", "text" or "im" it wrote, so "Nerazim" came out as "Neraz" (#4576, and a table's first
"|" in #4137). Those ids are left out, and the end token the tokenizer names (special_ids "eos") ends the reply instead."""
ids: set[int] = set()
for marker in (IM_END, "<|endoftext|>"):
got = tokenizer.encode(marker, parse_special=True)
if len(got) == 1:
ids.add(int(got[0]))
if not ids:
eos = (getattr(tokenizer, "special_ids", None) or {}).get("eos")
if eos is not None:
ids.add(int(eos))
return ids
File diff suppressed because it is too large. Load diff
+812
View File
@@ -0,0 +1,812 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the HTTP part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
import hmac
import json
import os
import re
import socket
import socketserver
import sys
from http.server import ThreadingHTTPServer
from pathlib import Path
from strata_control import engine_component
from strata_control import reader_room
from strata_control import hipblaslt_tuning
from serve.server_parts.base import LOOPBACK_NAMES
class BadBody(Exception):
"""A request body that cannot be read (a malformed or oversized chunked body): the status and the sentence."""
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
def anthropic_error_type(code: int, current) -> str:
"""error.type on /v1/messages, by the status rows of platform.claude.com/docs/en/api/errors. 502 and 503 have no
row and keep their type: a 503 must not read as overloaded_error, which Claude Code treats as an overload."""
known = {401: "authentication_error", 403: "permission_error", 404: "not_found_error", 409: "conflict_error",
413: "request_too_large", 429: "rate_limit_error", 500: "api_error"}.get(code)
return known or ("invalid_request_error" if code < 500 else current or "api_error")
class Server(ThreadingHTTPServer):
# On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on
# either one (a forgotten second start of run-<model>.bat). Without it the second start fails loudly instead.
allow_reuse_address = os.name != "nt"
# socketserver listens with a backlog of 5: a burst of 30-40 clients at once got "connection reset by peer" on the
# first ones (measured on 4 x R9700, also with one request at a time); the requests wait in the server, not the kernel
# (STRATA_HTTP_BACKLOG overrides it)
request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256))
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
if ":" in server_address[0]:
self.address_family = socket.AF_INET6
super().__init__(server_address, RequestHandlerClass, bind_and_activate)
def server_bind(self):
# http.server's own server_bind also asks socket.getfqdn(host) for a server_name nothing here reads; on a Mac whose reverse lookup
# stalls (GitHub's macOS runner: 35 s on the first lookup of every new process) each start waited that long before it listened
socketserver.TCPServer.server_bind(self)
self.server_name, self.server_port = self.server_address[:2]
def handle_error(self, request, client_address):
if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace
super().handle_error(request, client_address)
def server_close(self):
# the hardware sampler serve() started for this server stops with it (test isolation: every Service a test
# started used to leave its sampler running, 21 of them after test_responses, which slowed test_parallel's timing)
tel = getattr(getattr(self, "svc", None), "telemetry", None)
if tel is not None and hasattr(tel, "close"):
tel.close()
super().server_close()
def warn_tight_ram(arena_mib) -> None:
"""The model's experts live in RAM (INFO arena_mib, engine 0.1.10+). With less than ~6 GB left beside them for the
system, the engine and this server, Linux ends the engine mid-answer when memory runs out (issue #27) and Windows
pages to disk; say so at start instead of after a lost answer."""
if not isinstance(arena_mib, int) or arena_mib <= 0:
return
try:
import psutil
total = psutil.virtual_memory().total
except Exception: # noqa: BLE001 - psutil is optional here
return
left = total / 2**30 - arena_mib / 1024
if left < 6:
print(f"[strata] WARNING: RAM is tight - the model's experts take {arena_mib / 1024:.1f} GB of this PC's "
f"{total / 2**30:.0f} GB, leaving {left:.1f} GB for everything else. "
+ ("Linux may stop the engine in the middle of an answer. " if os.name != "nt" else
"Windows will slow down (paging to disk). ")
+ "Close other programs, or run START-HERE --setup and pick a smaller size (Q2_0 / IQ2_XS).", flush=True)
def warn_budget_over_ram(args) -> str | None:
"""#1080: an explicit `--resident-budget-gib N` bigger than the RAM this PC has free (or than its total beside
~6 GB for everything else) pushes experts into swap or the file tier: decode that is "dead slow" until the number is
removed. A warning at start, never a refusal (recommend, never force). -> the sentence printed, or None."""
try:
budget = float(args[list(args).index("--resident-budget-gib") + 1])
except (ValueError, IndexError):
return None
try:
import psutil
vm = psutil.virtual_memory()
total, free = vm.total / 2**30, vm.available / 2**30
except Exception: # noqa: BLE001 - psutil is optional here
return None
if budget <= free and budget <= total - 6:
return None
msg = (f"WARNING: the RAM budget for experts is {budget:g} GiB (--resident-budget-gib), but this PC has "
f"{free:.0f} GiB free of {total:.0f} GiB: what does not fit goes to swap or is read from disk, which can make "
"decoding very slow. Lower it (setup sizes it for this PC) or remove the argument to let the engine choose.")
print("[strata] " + msg, flush=True)
return msg
DESKTOP_FREE_MIB = 2048 # #560 #516: below this, an AMD card that also drives a Linux desktop can run out
DESKTOP_RESERVE_MIB = 3072 # what kept KDE/Wayland alive beside a full expert cache in both reports
def linux_desktop(env=None) -> bool:
"""A graphical session on Linux (Wayland or X): its compositor, browser and apps take VRAM after the model has."""
env = os.environ if env is None else env
return os.name != "nt" and sys.platform != "darwin" and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY"))
def desktop_vram_note(backend, vram_free_mib, args: list, desktop: bool) -> str:
"""#560 #516: on Linux, when the desktop needs VRAM the AMD card does not have, amdgpu moves GPU memory (the expert
cache, ~24 GB) to system RAM, which the experts already fill - the OOM killer then ends the compositor. The
default reserve (700 MiB) is sized for a card without a desktop. A recommendation, nothing changes: "" when it
does not apply."""
if backend != "hip" or not desktop or not isinstance(vram_free_mib, int) or vram_free_mib >= DESKTOP_FREE_MIB:
return ""
try:
reserve = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args else 700
except (ValueError, IndexError):
reserve = 700
if reserve >= DESKTOP_RESERVE_MIB:
return ""
return (f"[strata] note: {vram_free_mib} MiB of VRAM free with the model loaded. If this AMD card also drives your "
"desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and "
"the OOM killer ends the session), keep more VRAM free: ./setup.sh --vram-reserve-mib "
f"{DESKTOP_RESERVE_MIB} (remembered; the expert cache gets "
f"{(DESKTOP_RESERVE_MIB - reserve) / 1024:.1f} GB less, a few % of speed)")
def host_name(value) -> str:
"""The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com",
"[::1]:8095" -> "::1"; "" when it is malformed."""
v = (value or "").strip().lower()
if v.startswith("["):
name, sep, rest = v[1:].partition("]")
return name if sep and (not rest or (rest[:1] == ":" and rest[1:].isdigit())) else ""
if v.count(":") == 1:
v, port = v.split(":")
if not port.isdigit():
return ""
elif ":" in v: # a bare IPv6 address (a config entry)
return v
v = v.rstrip(".")
return v if v and all(c.isalnum() or c in "-._" for c in v) else ""
def _is_ip(name: str) -> bool:
import ipaddress
try:
ipaddress.ip_address(name)
return True
except ValueError:
return False
def _name_in(name: str, names) -> bool:
"""`name` is one of `names`, or below an entry that starts with a dot (".example.com")."""
return name in names or any(n.startswith(".") and (name.endswith(n) or name == n[1:]) for n in names)
def allowed_hosts_of(value, env: str = "") -> list[str]:
"""The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or
".example.com" (it and every name below it). A scheme, port or path is dropped ("https://a.example.com:8443/"
-> "a.example.com"); a wrong entry stops the start (ValueError)."""
items = [] if value in (None, "") else [value] if isinstance(value, str) else value
if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
raise ValueError("allowed_hosts: expected a host name or a list of them")
out = []
for raw in items + [x for x in env.split(",") if x.strip()]:
x = raw.strip().lower()
if x == "*":
out.append(x)
continue
x = x.split("://", 1)[-1].split("/", 1)[0]
dot = x.startswith(".")
name = host_name(x[1:] if dot else x)
if not name:
raise ValueError(f"allowed_hosts: {raw!r} is not a host name like strata.example.com")
out.append("." + name if dot else name)
return list(dict.fromkeys(out))
def host_allowed(host, names, any_host=False) -> bool:
"""DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the
same origin, so the browser lets it read every answer. Its requests carry that site's name in Host, so only
the names this server answers to pass. An IP address passes (a page served from an IP is that IP's own page;
rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host
header (HTTP/1.0 clients; browsers always send one)."""
if any_host or not (host or "").strip():
return True
name = host_name(host)
return bool(name) and (_is_ip(name) or name == "localhost" or name.endswith(".localhost")
or _name_in(name, names))
def key_list(value) -> list[str]:
"""#1344: the keys a server accepts. --api-key / STRATA_API_KEY / "api_key" take llama.cpp's form, several keys
separated by commas ("k1,k2"; spaces around each are dropped), or a list in the config ("api_key": ["k1", "k2"],
the way to give a key that contains a comma). A list is taken as it is."""
if value is None or value == "":
return []
if isinstance(value, (list, tuple)):
return [str(k) for k in value if str(k)]
return [k.strip() for k in str(value).split(",") if k.strip()]
def explicit_no_key(value) -> bool:
"""The owner chose to serve without a key: "api_key": "none" in the config, STRATA_API_KEY=none or --api-key none
(or --no-api-key, handled by the caller). Never a key called "none"."""
return isinstance(value, str) and value.strip().lower() == "none"
def open_server_warning(port, public=False, tools=False) -> str:
"""The one plain warning for a server on the network with no API key (recommend, never force)."""
msg = f"no API key: anyone who can reach port {port} can use the model" + (" and its tools" if tools else "") + "."
if tools:
msg += " The tools can read and change files on this computer."
if public:
msg += " This address is on the public internet, so anyone who finds it can use it."
return msg + " Add an API key to keep others out."
def api_key_of(value):
"""The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a
key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no
request: every client got 401 with the right key. A value that is only such characters raises ValueError, it
never means "no key" (#213). #1344: a config list of keys returns the list (each key stripped, none empty); a
string stays a string (its commas separate keys, see key_list)."""
if isinstance(value, (list, tuple)):
keys = [str(k).strip() for k in value]
if not keys or any(not k for k in keys):
raise ValueError("an API key was given but it is empty")
return keys
key = "" if value is None else str(value)
if key and not key_list(key):
raise ValueError("an API key was given but it is empty")
return key.strip()
def key_matches(given: str, key) -> bool:
"""given: a header's value as http.server read it, each byte one character. A key with characters outside ASCII
arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the
bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213). #1344: `key` may name several
keys (see key_list); the given one must match any, and every key is compared whatever the outcome."""
raw = given.encode("latin-1", "replace")
ok = False
for k in key_list(key):
ok |= hmac.compare_digest(raw, k.encode())
try:
ok |= hmac.compare_digest(raw, k.encode("latin-1"))
except UnicodeEncodeError:
pass
return ok
def origin_allowed(origin: str, host, names, origins=()) -> bool:
"""A browser page's Origin that may use the model without an API key: this server's own page (the Origin is the
request's own Host), a page on one of the names this server answers to (any port), or an origin the config lists
(trusted_origins, cors_origins). Unlike the Host check no IP passes on trust: a page served from any other IP is
another site. "null" (a sandboxed frame, a file:// page) does not pass: any site can send it. An origin of another
scheme (chrome-extension://, moz-extension://, an Electron app's app://) does: no web site can send one."""
origin = (origin or "").strip().rstrip("/")
if origin in origins or "*" in origins: # cors_origins ["*"]: the config lets every page in
return True
scheme, sep, rest = origin.lower().partition("://")
if not sep or not scheme:
return False
if scheme not in ("http", "https"):
return True
if host and rest == host.strip().lower():
return True
name = host_name(rest)
return bool(name) and (name in LOOPBACK_NAMES or name.endswith(".localhost") or _name_in(name, names))
def origins_of(value, key: str, wildcard: bool) -> list[str]:
"""#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path;
"*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant."""
if value is None or value == "" or value == []:
return []
items = [value] if isinstance(value, str) else value
if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
raise SystemExit(f"[strata] {key}: expected an origin or a list of origins")
out = []
for x in items:
x = x.strip().rstrip("/")
if x == "*" and wildcard:
out.append(x)
continue
scheme, sep, rest = x.partition("://")
if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest:
raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com"
+ ("" if wildcard else " (no wildcards here)"))
out.append(x)
return out
SHARED_KEYS = ("reasoning_effort", "reasoning_budget_tokens", "temperature", "top_p", "top_k", "seed", "max_tokens",
"experimental_speed_projection")
def load_shared_settings(path, warn=print) -> dict:
"""The Chat settings kept next to a config between starts, read so that one bad key cannot erase the others.
The strict reader below belongs to POST /settings, where a client is there to be told which key is wrong and can
fix it. At start-up nobody is there: the old code called the same strict reader and caught its ValueError with
`svc.shared = {}`, so a single unknown key - a typo, a key from a newer version, or a setting the server does not
know - discarded every OTHER setting in the file, `reasoning_effort` included, without a word in the log (#4933).
So the two failures are told apart here: a file that cannot be read, or is not a JSON object, is still ignored as
a whole (nothing in it can be trusted); a file that IS an object keeps every key the server understands, and each
key it does not is named on one line and skipped."""
try:
doc = json.loads(Path(path).read_text(encoding="utf-8"))
except FileNotFoundError:
return {} # no file yet: the normal case on a first start, nothing to report
except (OSError, ValueError) as e:
warn(f"[strata] the Chat settings in {path} are ignored ({e}); other apps use their own settings")
return {}
if not isinstance(doc, dict):
warn(f"[strata] the Chat settings in {path} are ignored (a JSON object was expected, found "
f"{type(doc).__name__}); other apps use their own settings")
return {}
out = {}
for key, value in doc.items():
try:
out.update(clean_shared_defaults({key: value}))
except ValueError as e:
warn(f"[strata] one Chat setting in {path} is skipped ({e}); the others still apply")
return out
def clean_shared_defaults(d) -> dict:
"""The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one."""
if d is None:
return {}
if not isinstance(d, dict):
raise ValueError("defaults must be an object")
out = {}
for key, value in d.items():
if value is None or value == "":
continue
number = isinstance(value, (int, float)) and not isinstance(value, bool)
if key == "reasoning_effort":
if value not in ("none", "low", "medium", "high"):
raise ValueError("reasoning_effort: none, low, medium or high")
elif key == "temperature":
if not number or not 0 <= value <= 2:
raise ValueError("temperature: 0..2")
elif key == "top_p":
if not number or not 0 < value <= 1:
raise ValueError("top_p: 0 < top_p <= 1")
elif key == "top_k":
if not number or value != int(value) or not 1 <= value <= 64:
raise ValueError("top_k: an integer 1..64")
value = int(value)
elif key in ("seed", "max_tokens"):
if not number or value != int(value) or value <= 0:
raise ValueError(f"{key}: a positive integer")
value = int(value)
elif key == "reasoning_budget_tokens": # #123: 0 means no budget, so 0 is allowed here
if not number or value != int(value) or value < 0:
raise ValueError("reasoning_budget_tokens: a whole number of tokens (0: no budget)")
value = int(value)
elif key == "experimental_speed_projection":
if not isinstance(value, bool):
raise ValueError("experimental_speed_projection: true or false")
else:
raise ValueError(f"unknown setting {key!r}")
out[key] = float(value) if key in ("temperature", "top_p") else value
return out
def split_joined_args(cfg: dict) -> None:
"""#2267: an engine option written as ONE element of the config's "args" - "--ple-io mmap" or "--ple-io=mmap" - reaches
the engine as a single argument ("unknown argument: --ple-io mmap"; the usual form is two elements, "--ple-io",
"mmap"). Recommend, never force: such an element is split into the flag and its value, and said at startup. Only an
element that starts with a flag name (--letters-digits-dashes) followed by a space or "=" is touched, and never one
that sits in the value place of the flag before it."""
args = cfg.get("args")
if not isinstance(args, list):
return
out, changed = [], []
for a in args:
m = re.match(r"^(--[A-Za-z0-9][A-Za-z0-9-]*)(?:\s+|=)(\S.*)$", a) if isinstance(a, str) else None
prev = out[-1] if out else None
in_value_place = isinstance(prev, str) and re.match(r"^--[A-Za-z0-9][A-Za-z0-9-]*$", prev) is not None
if m is None or in_value_place:
out.append(a)
continue
out += [m.group(1), m.group(2).strip()]
changed.append(a)
if changed:
cfg["args"] = out
print("[strata] the config's args hold " + ", ".join(repr(c) for c in changed) + " as one element each: split into the "
'flag and its value (write them as two elements, e.g. "--ple-io", "mmap")', flush=True)
def read_config(path) -> dict:
"""The run config's JSON. A mistake in it (a missing comma between two args, a trailing comma) is said with its
place in the file instead of a traceback (#2267: editing "args" by hand is where it happens)."""
return parse_config_text(Path(path).read_text(encoding="utf-8-sig"), path) # Notepad adds a BOM
def parse_config_text(text: str, path) -> dict:
"""read_config on text already read (the owner-launched server hashes the bytes it parses, launch attestation)."""
try:
return json.loads(text)
except json.JSONDecodeError as e:
raise SystemExit(f"[strata] {path} is not valid JSON: {e.msg} at line {e.lineno}, column {e.colno}. Check the commas "
'between the entries of "args" (each option and each value is its own quoted entry, e.g. '
'"--ple-io", "mmap",) and that no entry is followed by a comma at the end of a list.') from None
def lift_reasoning_effort_arg(cfg: dict) -> None:
"""#1641: "--reasoning-effort high" in a config's "args" is meant for the thinking level, which is not an engine
option (the engine stopped at the unknown flag). It is the config's "reasoning_effort" (none, low, medium or high:
the level for requests that name none), so the flag is taken out of the engine's arguments and becomes that key
unless the config already has one; said at startup."""
args = cfg.get("args")
if not isinstance(args, list):
return
out, value, i = [], None, 0
while i < len(args):
a = args[i]
if a == "--reasoning-effort" and i + 1 < len(args):
value, i = args[i + 1], i + 2
elif isinstance(a, str) and a.startswith("--reasoning-effort="):
value, i = a.partition("=")[2], i + 1
else:
out.append(a)
i += 1
if value is None:
return
cfg["args"] = out
if cfg.get("reasoning_effort") is None:
cfg["reasoning_effort"] = value
print("[strata] '--reasoning-effort' in the config's args is not an engine option: taken out of them. The thinking "
"level is the config's 'reasoning_effort' key (outside 'args'); it is used as " +
f"{cfg['reasoning_effort']!r}", flush=True)
# #1819: llama.cpp clients call the repetition penalty and its window repeat_penalty / repeat_last_n; they are the
# same settings as repetition_penalty / penalty_last_n (the /props answer already reports them under those names)
SAMPLING_ALIASES = {"repeat_penalty": "repetition_penalty", "repeat_last_n": "penalty_last_n"}
def apply_saved_tuning(cfg: dict, *, say=None) -> dict:
"""The run config with the active saved tuning for its choices put on top (strata_control/presets.py), with no measurement.
Every start path runs this (the Terminal, `runtime start`, the app's load, a restart of the app, an unload and a load), so the
tuning is applied every time and never re-measured. A tune's own worker sets STRATA_NO_PRESET so that it measures the
configuration it was given. Never fails a start: a store that cannot be read means the configuration as it is."""
if os.environ.get("STRATA_NO_PRESET"):
return cfg
say = say or (lambda line: print(line, flush=True))
try:
from strata_control import presets as _presets
out, applied = _presets.overlay(cfg)
if applied.get("applied"):
changes = {**(applied.get("args") or {}), **(applied.get("env") or {})}
note = applied.get("notice") or ""
say(f"[strata] saved tuning '{applied['preset']['name']}' applied: "
f"{' '.join(f'{k} {v}' for k, v in changes.items()) or 'the standard settings (nothing to change)'}"
f"{'; ' + note if note and 'identical' not in note else ''}")
for warning in applied.get("warnings") or []: # #3844: outside the range the tuner tries, kept
say(f"[strata] warning: {warning}")
if applied.get("state") == "soft":
say("[strata] this PC or engine changed since it was saved (" + "; ".join(applied["reasons"]) +
"): a short re-check is available (strata presets recheck)")
elif applied.get("why_not"):
say(f"[strata] saved tuning '{applied['preset']['name']}' {applied['why_not']}; re-tune with strata tune auto")
return out
except Exception as e: # noqa: BLE001
say(f"[strata] saved tuning could not be read ({type(e).__name__}); starting with the configuration as it is")
return cfg
def sampling_defaults_from_config(cfg: dict) -> dict:
"""The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, so
a plain client gets configured sampling instead of greedy. Supported: temperature, top_p, top_k, min_p,
presence_penalty, repetition_penalty (also written repeat_penalty), frequency_penalty, penalty_last_n (also
repeat_last_n), seed. The request's own fields
always win - an explicit temperature=0 still means greedy, a field set to null falls back to the default.
A bad value refuses to start the server (a typo'd config should not quietly change sampling); unknown keys
are named at startup and ignored."""
out = {}
block = dict(cfg.get("sampling") or {})
for alias, canon in SAMPLING_ALIASES.items(): # #1819: llama.cpp's names for the same two fields
if block.get(alias) is not None:
if block.get(canon) is not None:
raise SystemExit(f"[strata] config sampling: both {alias!r} and {canon!r} are set; they are the same "
f"setting, keep one")
block[canon] = block.pop(alias)
for key, value in block.items():
if value is None:
continue
number = isinstance(value, (int, float)) and not isinstance(value, bool)
if key == "temperature":
if not number or value < 0:
raise SystemExit(f"[strata] config sampling.temperature={value!r}: expected a number >= 0 (0 = greedy)")
out[key] = float(value)
elif key == "top_p":
if not number or not 0 < value <= 1:
raise SystemExit(f"[strata] config sampling.top_p={value!r}: expected 0 < top_p <= 1")
out[key] = float(value)
elif key == "min_p":
if not number or not 0 <= value <= 1:
raise SystemExit(f"[strata] config sampling.min_p={value!r}: expected 0 <= min_p <= 1")
out[key] = float(value)
elif key == "top_k":
if not number or value != int(value) or not 1 <= value <= 64:
raise SystemExit(f"[strata] config sampling.top_k={value!r}: the sampled path takes an integer 1..64")
out[key] = int(value)
elif key == "presence_penalty":
if not number or value < 0:
raise SystemExit(f"[strata] config sampling.presence_penalty={value!r}: expected a number >= 0")
out[key] = float(value)
elif key == "frequency_penalty":
if not number or value < 0:
raise SystemExit(f"[strata] config sampling.frequency_penalty={value!r}: expected a number >= 0")
out[key] = float(value)
elif key == "repetition_penalty":
if not number or value <= 0:
raise SystemExit(f"[strata] config sampling.repetition_penalty={value!r}: expected a number > 0 (1 = off)")
out[key] = float(value)
elif key == "penalty_last_n":
if not number or value != int(value) or value < 0:
raise SystemExit(f"[strata] config sampling.penalty_last_n={value!r}: expected a non-negative integer")
out[key] = int(value)
elif key == "seed":
if not number or value != int(value) or value <= 0:
raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer")
out[key] = int(value)
elif key == "strata_tune": # a saved tuning's per-request settings (strata_control/presets.py)
if not isinstance(value, dict):
raise SystemExit(f"[strata] config sampling.strata_tune={value!r}: expected an object")
out[key] = {k: v for k, v in value.items() if k in ("pcie_frac", "spec_min_p", "aux_cpus")}
elif key == "experimental_speed_projection":
if not isinstance(value, bool):
raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or "
"false (the default for requests that leave it out, when the engine has the vector)")
out[key] = value
else:
print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True)
return out
SPLIT_KEYS = ("split_fallback", "split_engine_note")
def check_request_sampling(req) -> None:
"""A request's sampling field of the wrong JSON type ("temperature": "0.7", "top_k": 40.0, "seed": true) is a 400
that names the field, as the same value is through POST /settings or the run config. Unchecked, the value
replaced the configured default in run()'s merge and sampling_keys dropped it, so the reply was greedy. Only
types are checked: a number (int or float, never bool) for temperature, top_p, min_p and the three penalties; an
integer (never bool or float) for top_k, penalty_last_n and seed. Ranges behave as before (a temperature <= 0 is
greedy, top_k 0 or above 64 is clamped, a seed <= 0 is unset), and an absent or null field is not checked."""
if isinstance(req, dict): # #1819: llama.cpp's names; the OpenAI-style field wins when both are sent
if req.get("repeat_penalty") is not None and req.get("repetition_penalty") is None:
req["repetition_penalty"] = req["repeat_penalty"]
rl = req.get("repeat_last_n")
if req.get("penalty_last_n") is None and isinstance(rl, int) and not isinstance(rl, bool) and rl > 0:
req["penalty_last_n"] = rl # 0 and -1 (off / the whole context) keep the engine's default window
for key, integer in (("temperature", False), ("top_p", False), ("min_p", False), ("presence_penalty", False),
("frequency_penalty", False), ("repetition_penalty", False), ("top_k", True),
("penalty_last_n", True), ("seed", True)):
value = (req or {}).get(key)
if value is None:
continue
if isinstance(value, str) and value.strip(): # some clients send numbers as strings: read and used
try:
num = float(value)
num = int(num) if integer and num == int(num) else (num if not integer else None)
if integer and num is None:
raise ValueError
if not integer and re.fullmatch(r"\s*[+-]?\d+\s*", value):
num = int(value)
except (ValueError, OverflowError):
raise ValueError(f"{key}: {'an integer' if integer else 'a number'}") from None
if num != num or num in (float("inf"), float("-inf")):
raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
req[key] = value = num
if isinstance(value, bool) or not isinstance(value, int if integer else (int, float)):
raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
# the API's model name per model family (the GGUF architecture, "arch" in the config) when the config names none
FAMILY_MODEL_NAMES = {"qwen4exp": "qwen3.8-flash-next", "qwen35moe": "qwen3.6-35b-a3b"}
# The sampling each model card recommends ("Best Practices"), used when neither the request, the Chat settings nor the
# run config's `sampling` block says otherwise. Greedy is only for a request or config that asks for temperature 0.
# min_p 0, repetition_penalty 1 and presence_penalty 0 are the engine's own "off", so they are not listed.
MODEL_CARD_SAMPLING = {
# Qwen3.8-Flash-Next (and Gyro, the same base model)
"qwen4exp": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20},
"instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
# Qwen3.6-35B-A3B: the general-task sets (the card's precise-coding set is temperature 0.6, presence_penalty 0)
"qwen35moe": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "presence_penalty": 1.5},
"instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
}
# The card's penalties: a greedy request must not get them (see model_card_sampling)
CARD_PENALTIES = ("presence_penalty", "frequency_penalty", "repetition_penalty")
def model_card_sampling(arch, thinking, greedy=False) -> dict:
"""The model card's sampling for the family `arch` and the thinking state ({} for an unknown or unset family).
`greedy` (temperature 0 asked for, see asks_greedy): without the card's penalties, so a greedy request stays greedy.
A penalty makes the engine sample from its logits: the answer is no longer the greedy one, and the MTP drafts
(greedy requests only) never run - with Qwen3.6's presence_penalty 1.5, 0 drafts on every temperature-0 request."""
sets = MODEL_CARD_SAMPLING.get(arch) if arch else None
card = dict(sets["thinking" if thinking else "instruct"]) if sets else {}
if greedy:
for k in CARD_PENALTIES:
card.pop(k, None)
return card
def asks_greedy(*layers) -> bool:
"""True when greedy is asked for: the first of `layers` (highest precedence first - the request, the shared Chat
settings, the config's `sampling` block) that sets a temperature sets 0."""
for layer in layers:
t = (layer or {}).get("temperature")
if t is not None:
return isinstance(t, (int, float)) and not isinstance(t, bool) and float(t) <= 0.0
return False
def default_model_name(cfg: dict) -> str:
"""The config's "model_name", else its family's name ("arch": qwen4exp, qwen35moe), else Flash-Next's."""
return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
def with_current_reader(cfg: dict, package: Path) -> dict:
"""The picture reader (vision "exe", "cpu_exe") is written into the run config as an absolute path inside the engine package's folder,
and that folder is named after the engine version: after an engine update, or in a container made for another card, the path is gone
and the server would stop with "server_exited". Use the same file of the package that is installed now (the reader ships in the package)."""
vision = cfg.get("vision")
if not isinstance(vision, dict):
return cfg
fixed = dict(vision)
for key in ("exe", "cpu_exe"):
old = fixed.get(key)
if isinstance(old, str) and old and not engine_component.is_reference(old) and os.path.isabs(old):
new = package / old.replace("\\", "/").rsplit("/", 1)[-1]
gone = not os.path.exists(old)
# #4658: the old engine folder is kept after `strata update`, so the old reader still exists; one in a SIBLING engine folder
# (components/engine/<version>-...) is the engine's reader from before the update, and the engine in use has its own
older = (not gone and Path(old).parent != package and Path(old).parent.parent == package.parent
and package.parent.name.lower() == "engine")
if (gone or older) and new.is_file():
print(f"[strata] the picture reader {old} " + ("is not there any more" if gone else "belongs to an older engine")
+ f"; using {new} from the engine package in use", flush=True)
fixed[key] = str(new)
if fixed == vision:
return cfg
return {**cfg, "vision": fixed}
READER_NEEDS_MIB = reader_room.READER_NEEDS_MIB # what the GPU picture reader takes from the card (1,342 MiB measured on an RTX A6000 and an R9700)
#: Owner rule 2026-11-01: the picture reader lives in RAM, not VRAM. On an NVIDIA card with one GPU the GPU reader is started by the first
#: picture and stopped after vision.elastic_idle_s, inside a reserve of VISION_RESERVE_MIB; a start that finds no room is read by the CPU reader.
#: Measured on an RTX A6000 as a 24 GB card (Qwen3.8-Flash-Next IQ3_S, 5 interleaved pairs): the same 20,623 expert slots and the same text speed as
#: the reader on the card, 1.3 GB less VRAM in use between pictures. The expert cache that gives its room (vram_elastic) held 8.5% more slots
#: and was 2.2% slower in text (4 pairs of 5) in that first measurement; 11-11 it is the default (VISION_NO_RESERVE_BY_DEFAULT): on an RTX
#: PRO 5000 held to a 32 GB card (IQ3_S streamed, 5 rotated rounds) its text was level with the processor reader (2K / 8K / 20K 0.998 /
#: 0.997 / 0.998) and 2.9% faster than the room held back at 2K (12,719 against 12,022 slots), level when the model fits.
VISION_ON_DEMAND_BY_DEFAULT = True
VISION_RESERVE_MIB = 2048
_ON_DEMAND_NOT_WITH = ("--kv-grow", "--batch", "--slots", "--peer-device", "--expert-cache-device1", "--expert-cache-device2",
"--expert-cache-device3")
def with_component_engine(cfg: dict) -> dict:
"""A run config that names "component:strata-engine" gets the engine package for this PC: the path in `exe`, and
the package's own folder first on the library path (the GPU runtime libraries ship beside the binary)."""
if not engine_component.is_reference(cfg.get("exe")):
return cfg
cfg = dict(cfg)
cfg["exe"] = _component_exe(cfg["exe"], cfg)
cfg["lib_dirs"] = [*engine_component.package_lib_dirs(Path(cfg["exe"]).parent), *(cfg.get("lib_dirs") or [])]
cfg = with_current_reader(cfg, Path(cfg["exe"]).parent)
if cfg.get("backend") == "hip": # AMD: the package's own hipBLASLt tuning table for this card, when its hipBLASLt version matches
cfg = hipblaslt_tuning.apply(cfg, Path(cfg["exe"]).parent, say=lambda line: print(line, flush=True))
return cfg
def _history_call_names(req) -> list:
"""The tool names a request's own conversation called, in order, on any of the three routes: Chat Completions (an assistant
message's tool_calls), Anthropic (an assistant message's tool_use blocks) and Responses (function_call / custom_tool_call
input items, a namespace in front as `namespace.name`)."""
names = []
for message in req.get("messages") or []:
if not isinstance(message, dict) or message.get("role") != "assistant":
continue
for call in message.get("tool_calls") or []:
names.append((call.get("function") or {}).get("name") if isinstance(call, dict) else None)
content = message.get("content")
for block in content if isinstance(content, list) else []:
if isinstance(block, dict) and block.get("type") == "tool_use":
names.append(block.get("name"))
items = req.get("input")
for item in items if isinstance(items, list) else []:
if isinstance(item, dict) and item.get("type") in ("function_call", "custom_tool_call"):
name = item.get("name")
if isinstance(name, str) and name and isinstance(item.get("namespace"), str) and item["namespace"]:
name = f"{item['namespace']}.{name}"
names.append(name)
return names
def with_history_tools(tools, req) -> list:
"""#4663: an agent's tool set changes between turns (deferred tools, MCP servers, a compacted history), and the model calls a tool it used
earlier in this conversation that this turn's `tools` no longer lists. That call came back as raw text with finish_reason "stop", and the
client took it for prose and stopped. A name the conversation's own assistant turns called is a tool the client has, so it counts as
declared (the call comes back as a tool call; the client says what it does with it) - on Chat Completions, Anthropic and Responses.
Nothing is added when the request declared no tools at all, or for a name that is already declared."""
if not tools or not isinstance(req, dict):
return tools
try:
have = {t.get("name") for t in tools if isinstance(t, dict)}
extra = []
for name in _history_call_names(req):
if isinstance(name, str) and name and name not in have:
have.add(name)
extra.append({"name": name, "parameters": {"type": "object", "properties": {}}})
return [*tools, *extra] if extra else tools
except Exception:
return tools
def _component_exe(reference: str, cfg: dict) -> str:
"""The engine a run config names as "component:strata-engine". No engine for this PC is a clear notice and exit 5;
the server never goes looking on the internet for one (strata_control/engine_component.py)."""
try:
return engine_component.expand(reference, cfg)
except engine_component.EngineMissing as e:
print(f"[strata] {e}", file=sys.stderr, flush=True)
raise SystemExit(e.exit_code) from None
def undeclared_tool_calls_setting(cfg: dict) -> str:
"""#4622: the config's "undeclared_tool_calls": "text" (the default, when the config does not name it) keeps a well-formed call of a tool the request
did not declare as the text the model wrote, with strata_rejected_tool_calls beside it; "call" returns it as a tool call, for a client that has
its own policy for unknown names (it answers the model with the tool names it has). Anything else stops the start."""
mode = cfg.get("undeclared_tool_calls")
if mode is None: # the environment names it too (STRATA_UNDECLARED_TOOL_CALLS); the config wins
mode = os.environ.get("STRATA_UNDECLARED_TOOL_CALLS") or "text"
if mode not in ("text", "call"):
raise SystemExit(f"[strata] config \"undeclared_tool_calls\" must be \"text\" or \"call\", not {mode!r}")
return mode
def tool_call_recovery_setting(cfg: dict) -> bool:
"""The config's "tool_call_recovery" (see OutputParser's recover): ON when the config does not name it (since 0.2.8; 0.2.7 and before: off),
"tool_call_recovery": false turns it off. Anything but true or false stops the start."""
recovery = cfg.get("tool_call_recovery", True)
if not isinstance(recovery, bool):
raise SystemExit(f"[strata] config \"tool_call_recovery\" must be true or false, not {recovery!r}")
return recovery
#: #5787: the switch that turns the server's own crash reporter off.
FAULTHANDLER_OFF = "STRATA_NO_FAULTHANDLER"
def arm_faulthandler(env: dict | None = None) -> bool:
"""#5787: arm CPython's faulthandler for this process, on its own output, and say whether it armed.
The reports of the serve process dying natively (`0xC0000005` / `0xC0000409` on Windows, SIGSEGV / SIGBUS on Linux
and Mac) all have the same shape: the host log carries an exit code, the crash guard restarts the server in about
two minutes, and nothing names the Python line. #5787's ten restarts in three days needed the reporter to set
`PYTHONFAULTHANDLER=1` in his own launcher, plus the private `python312.pdb` from the package, to read anything.
Armed here, in the server, every launcher (the app, the Terminal, a source start) leaves the stack of the dying
thread, and of the request workers beside it, in the log a person can already send.
It writes nothing while the process runs. `STRATA_NO_FAULTHANDLER=1` turns it off. A faulthandler that cannot arm
(no module, a closed output) is answered with False and never stops a start. The process still dies by the same
signal with the same exit code, so the crash guard, the app's restart and the OS's own dump are unchanged.
"""
target = os.environ if env is None else env
if target.get(FAULTHANDLER_OFF) == "1":
return False
try:
import faulthandler
faulthandler.enable(all_threads=True) # the request workers' stacks are what names a shared cause
return True
except Exception: # noqa: BLE001 - arming a crash reporter never breaks a start
return False
+274
View File
@@ -0,0 +1,274 @@
"""Moved unchanged out of serve/server.py (file split, cleanup step 5): the OpenAI part. `serve.server` imports these names back,
so every caller and test still reaches them as `serve.server.<name>`."""
from __future__ import annotations
import collections
import codecs
import json
import math
from serve.structured import extract_json
# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by
# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole
# prompt. A PP that close to the end says the prompt is read. It matters because a prompt shorter than one `--prefill`
# chunk sends exactly one PP, that one: a client would see a bar that appears already full. Such a line is dropped, and
# the answer's first token ends the progress for the client anyway.
PP_DONE_TAIL = 64
class LPLines(collections.deque):
"""One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler
through Service.run to Engine.generate). The last events of a request - the parser's and the stop strings'
tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines
with its own: LogprobEntries reads only the lines tagged with its own request's Event."""
def __init__(self, owner=None):
super().__init__()
self.owner = owner
class LogprobEntries:
"""The engine's LP lines as OpenAI's logprobs.content entries.
Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's
text is made), so a character split across tokens lands in the token that finishes it and
the tokens, joined, spell the reply. "bytes" are the token's own bytes. The stop token
ends the reply and is not listed (OpenAI does not list it either). Tokens that make no
text of the reply are left out, because spell() gives each piece of text the tokens that
spell it.
`allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them,
so a caller asking about specific candidates gets a distribution over exactly those instead
of a top-K list it has to hope contains them. vLLM, which named the field, masks generation
with these ids instead (every other logit -inf before sampling) and reports the unmasked
distribution; here they filter what is reported, so the chosen token can be outside them.
On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path
that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts.
"""
def __init__(self, svc, allowed=(), owner=None):
self.tok, self.stop_ids = svc.tok, svc.stop_ids
self.allowed = [i for i in allowed]
self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace")
self.pending = [] # entries read but not yet given to a piece of text
self.owner = owner # the request's cancel Event (LPLines)
self.lines = None # this request's current LPLines, kept once seen
def spell(self, eng, text: str) -> list:
"""The entries whose tokens spell `text`, the next piece of the reply."""
self.pending += self.take(eng)
at = [0]
for e in self.pending:
at.append(at[-1] + len(e["token"]))
joined = "".join(e["token"] for e in self.pending)
i = joined.find(text)
while i >= 0 and text:
if i in at:
a = at.index(i) # the first token there
end = i + len(text)
b = next((j for j in range(a + 1, len(at)) if at[j] == end), None)
if b is not None:
out, self.pending = self.pending[a:b], self.pending[b:]
return out
i = joined.find(text, i + 1)
out, self.pending = self.pending, []
return out
def raw(self, t):
if hasattr(self.tok, "token_bytes"):
return self.tok.token_bytes(t)
return self.tok.decode([t]).encode("utf-8")
def take(self, eng) -> list:
# the engine's current lines are this request's only when they carry its Event (a later generate pass
# of the same request makes new ones: the old ones are read to the end first); another request's never are.
# A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and
# the next request to read control lines may already have replaced it.
own = getattr(self.owner, "_strata_lp_lines", None)
cur, old = (own if own is not None else getattr(eng, "lp_lines", None)), None
if cur is not self.lines and getattr(cur, "owner", None) is self.owner:
old, self.lines = self.lines, cur
out = []
for lines in (old, self.lines):
while lines:
t, line = lines.popleft()
if t in self.stop_ids:
continue
f = line.split()
if len(f) < 2:
continue
try: # "nan" (no head logits for that window row), "-nan(ind)"
lp = float(f[1]) # (MSVC) or a cut line: no entry for that token
alts = [(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])]
except ValueError:
continue
if not math.isfinite(lp) or not all(math.isfinite(v) for _, v in alts):
continue
b = self.raw(t)
e = {"token": self.inc.decode(b), "logprob": lp, "bytes": list(b),
"top_logprobs": []}
if self.allowed:
alts = [(i, v) for i, v in alts if i in self.allowed]
for i, v in alts:
alt = self.raw(i)
e["top_logprobs"].append({"token": alt.decode("utf-8", "replace"),
"logprob": v, "bytes": list(alt)})
if self.allowed:
e = self._renormalise(e, t, lp)
out.append(e)
return out
def _renormalise(self, e, t, lp):
"""Keep only the named ids and normalise over them, so they sum to 1.
The line carries the chosen token's own logprob on its head and the named ids after it, and never
repeats the chosen one among them. So the chosen token is put back when the caller named it: with
`allowed_token_ids` naming only the token the model chose, that token is then the whole distribution,
at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over,
which returned None, the entry was appended all the same, and the reply failed on e["token"]. A line
that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen
token and its own logprob, with no alternatives. It is never None and never dropped, because the
reply's tokens have to keep spelling its text.
"""
cand = e["top_logprobs"]
own = None
if t in self.allowed: # named, and not repeated on the line: it is a candidate
b = self.raw(t)
own = {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)}
cand = [own] + cand
if not cand:
return e # no named id observed for this token: its own logprob, no top
mx = max(x["logprob"] for x in cand)
se = sum(math.exp(x["logprob"] - mx) for x in cand)
lse = mx + math.log(se)
for x in cand:
x["logprob"] -= lse
cand.sort(key=lambda x: -x["logprob"]) # most likely first, as the unfiltered top-k already is
e["top_logprobs"] = cand
if own is not None: # the chosen token is in the distribution: report its own value
e["logprob"] = own["logprob"] # (it used to copy the first alternative's, another token's)
return e
def _is_json(text: str) -> bool:
try:
json.loads(text)
return True
except ValueError:
return False
def openai_collect(chunks) -> dict:
content, reasoning, by_index, last, mcp = [], [], {}, None, []
lps = {} # "content" / "reasoning_content" -> logprob entries
for c in chunks:
if c is None: # a heartbeat
continue
if c.get("strata_mcp"):
mcp.append(c["strata_mcp"])
for k, v in (c["choices"][0].get("logprobs") or {}).items():
lps.setdefault(k, []).extend(v)
d = c["choices"][0]["delta"]
content.append(d.get("content") or "")
reasoning.append(d.get("reasoning_content") or "")
for tc in d.get("tool_calls") or []: # streamed calls arrive in pieces: merge them by index
cur = by_index.setdefault(tc.get("index", len(by_index)), {"id": None, "type": "function",
"function": {"name": "", "arguments": ""}})
cur["id"] = tc.get("id") or cur["id"]
fn = tc.get("function") or {}
cur["function"]["name"] += fn.get("name") or ""
cur["function"]["arguments"] += fn.get("arguments") or ""
last = c
calls = [by_index[i] for i in sorted(by_index)]
if last["choices"][0]["finish_reason"] != "tool_calls":
calls = [c for c in calls if _is_json(c["function"]["arguments"])] # a call the output ended inside (#211)
msg = {"role": "assistant", "content": "".join(content) or None}
if "".join(reasoning).strip() and "".join(reasoning).strip() == "".join(content).strip():
reasoning = [] # a turn with no </think>: the text is the answer; it is not also reasoning
if "".join(reasoning):
msg["reasoning_content"] = "".join(reasoning)
if calls:
msg["tool_calls"] = calls
if mcp:
msg["strata_mcp"] = mcp
out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"],
"choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}],
"usage": last["usage"]}
if lps:
out["choices"][0]["logprobs"] = {"content": lps.get("content", []), "refusal": None, **(
{"reasoning_content": lps["reasoning_content"]} if lps.get("reasoning_content") else {})}
if last.get("timings"):
out["timings"] = last["timings"]
if last.get("strata_rejected_tool_calls"):
out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"]
if last.get("strata_unread_tool_markup"):
out["strata_unread_tool_markup"] = last["strata_unread_tool_markup"]
return out
def logprob_span(text: str, part: str, entries: list):
"""The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not
spell `text` or no token boundary falls at both ends of `part`."""
if "".join(e["token"] for e in entries) != text:
return None
start = text.find(part)
if start < 0:
return None
at, first = 0, None
for i, e in enumerate(entries):
if at == start and first is None:
first = i
if at == start + len(part) and first is not None:
return entries[first:i]
at += len(e["token"])
return entries[first:] if first is not None and at == start + len(part) else None
def _same_json(a: str, b: str) -> bool:
"""Are two strings the same JSON value (whitespace and key order aside)? No -> False."""
try:
return json.loads(a) == json.loads(b)
except Exception:
return False
def _structured_logprobs(choice: dict, content: str):
"""`content`'s logprobs, and the content the tokens actually spell.
Returns `(content, logprobs)`: on failure `(the content as validated, None)`.
`structured_chunks` returns the canonical JSON the validator produced, which the model never
generated, so its tokens do not spell it. Two honest outcomes:
1. a run of tokens spells what is being returned -> use it as it is;
2. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces
case, the common one) -> return the model's form, so `''.join(token) == content` again.
Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no
logprobs: a caller that joins the tokens must not silently get something that does not match.
"""
lps = choice.get("logprobs")
if not lps or not lps.get("content"):
return content, None
raw = choice["message"]["content"] or ""
entries = lps["content"]
if raw == content: # not rewritten: the entries are already its
return content, _with_reasoning(lps, entries)
span = logprob_span(raw, content, entries)
if span is not None:
return content, _with_reasoning(lps, span)
inner = extract_json(raw)
if inner and _same_json(inner, content):
span = logprob_span(raw, inner, entries)
if span is not None:
return inner, _with_reasoning(lps, span) # the model's own form: the tokens spell it
return content, None
def _with_reasoning(lps: dict, entries: list) -> dict:
out = {"content": entries}
if lps.get("reasoning_content"):
out["reasoning_content"] = lps["reasoning_content"]
return out
@@ -142,7 +142,8 @@ class EntryPointsSetItForEveryChild(unittest.TestCase):
# listed here (and, when it starts a Strata program - the engine, the picture reader, sd-cli, setup, a worker - it builds its environment with
# quiet_crash_env or inherits the one an entry point set).
STRATA_PROGRAMS = {
"serve/server.py": 7, # the engine, the picture reader (env from child_env / vision_env), the strata-device probe, before_load commands
"serve/server.py": 5, # the engine, the picture reader (env from child_env / vision_env), the strata-device probe, before_load commands
"serve/server_parts/engines.py": 2, # (moved out of serve/server.py unchanged, file split)
"serve/images.py": 1, # sd-cli (image_env)
"serve/lifeline.py": 4, # the wrapper every child goes through (ps, a watcher); no program of ours of its own
"serve/winjob.py": 2, # lifeline.popen's Windows start inside the job (suspended, then resumed) + the plain Popen off Windows: the caller's env as given