okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
660.0 KiB10909 linesraw
1"""serve/server.py - plan v0.3 P8: OpenAI and Anthropic endpoints over any engine that maps token ids to tokens.
2
3    python -m serve.server --engine mock --port 8095            (a scripted engine, for clients and tests)
4    python -m serve.server --engine strata --config strata.json --port 8080   (the real engine, resident)
5
6Endpoints: POST /v1/chat/completions (OpenAI, stream and non-stream), POST /v1/messages (Anthropic, stream and
7non-stream), GET /v1/models, GET /models, GET /props, GET /slots, GET /health, GET /mcp. One sequence at a time behind a FIFO (plan: one resident sequence).
8Image generation (optional, when the config has an "images" section): POST /v1/images/generations (OpenAI's shape,
9plus seed and steps) runs stable-diffusion.cpp's sd-cli for Qwen-Image-2.1-Turbo, one job at a time on the GPU the
10text engine uses (serve/images.py).
11Tools from MCP servers (serve/mcp.py, `"mcp_servers"` in the config or --mcp-config) are offered only to requests that
12ask for them with `"strata_mcp": true` - the web app does; other clients see exactly the API they always saw.
13Images (optional, when the config has a "vision" entry): OpenAI image_url parts and Anthropic image blocks (base64
14data, http(s) URLs or local file paths) go through `strata-vision` (the model's mmproj file) and reach the engine as
15embeddings (`GENI`).  JPEG/PNG/BMP/GIF go straight in; WebP, TIFF, AVIF, ... (agents like omp send WebP) are
16converted to PNG first with Pillow.
17A request whose prompt alone does not fit the engine's context is REJECTED with 400, never truncated.  When the prompt
18fits but prompt plus max tokens does not (Claude Code asks for 32000, the Harness for 16384), max tokens is shortened to
19the room left (less CTX_SLACK) and the thinking budget follows it; `--no-fit-max-tokens` / `"fit_max_tokens": false`
20brings back the strict 400 of llama.cpp.
21An unset (or 0, or -1) max tokens means "unlimited": whatever the prompt leaves of the context.
22
23The engine boundary is `Engine.generate(prompt_ids, max_new, sampling, cancel) -> iterator of token ids`.
24`StrataEngine` keeps one `strata --serve` process resident (weights, expert arena and VRAM tier load once) and
25talks to it over stdin/stdout; `MockEngine` is a scripted stand-in that makes every API path testable without a GPU.
26"""
27from __future__ import annotations
28
29import argparse
30import contextlib
31import collections
32import base64
33import hashlib
34import hmac
35import codecs
36import json
37import math
38import os
39import platform
40import queue
41import re
42import select
43import signal
44import socket
45import socketserver
46import struct
47import shutil
48import subprocess
49import sys
50import tempfile
51import threading
52import time
53import urllib.request
54import uuid
55from http.client import HTTPException
56from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
57from pathlib import Path
58from typing import Iterator, Protocol
59from urllib.parse import parse_qs, urlsplit
60
61ROOT = Path(__file__).resolve().parents[1]
62sys.path.insert(0, str(ROOT / "tools"))
63sys.path.insert(0, str(ROOT))   # run as a script (run-<model>.bat) as well as a module
64from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, parser_for_template, anthropic_to_messages, anthropic_tools,  # noqa: E402
65                            forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, require_messages,
66                            tool_choice_of, unmark_think_literals)
67from serve.mcp import McpCancelled, hub_from_config  # noqa: E402
68from serve import runconfig  # noqa: E402
69from serve.webfiles import subtree_file as web_subtree_file  # noqa: E402
70from strata_control import engine_component  # noqa: E402
71from strata_control import tls  # noqa: E402
72from strata_control.childenv import quiet_crash_env  # noqa: E402
73from strata_control import reader_room  # noqa: E402
74
75tls.install()       # #3722: image URLs and tool servers over HTTPS are checked against the operating system's certificates
76from strata_control import hipblaslt_tuning  # noqa: E402
77from strata_control import vision_reader  # noqa: E402
78from serve.ds_pictures import PICTURE_FORMATS, DsPictures  # noqa: E402
79from strata_control import draft_layer  # noqa: E402
80from strata_control import drafting  # noqa: E402
81from strata_control import vram_fit  # noqa: E402
82from strata_control import user_args  # noqa: E402
83from strata_control import gpu_roles  # noqa: E402
84from serve import ready as ready_file  # noqa: E402
85from serve import owner_guard  # noqa: E402
86from serve import launch_identity  # noqa: E402
87from serve import logit_bias as bias_api  # noqa: E402
88from serve import lifeline  # noqa: E402
89from serve.structured import StructuredOutputError, prepare_format, validated_json, extract_json  # noqa: E402
90from serve import responses as responses_api  # noqa: E402
91from serve.responses import ResponsesError, error_body as responses_error_body  # noqa: E402
92from serve import images as images_api  # noqa: E402
93from serve import ds4_vision  # noqa: E402
94
95IM_END = "<|im_end|>"
96IMAGE_PAD = "<|image_pad|>"
97
98
99def popen(what: str, args: list, role: str = "engine", **kw):
100    """#735: subprocess.Popen, but Windows' refusal to start a program (WinError 4551, or 1260 when a policy blocks it:
101    Smart App Control on a clean Windows 11 blocks an exe that is not signed) is said in words instead of a bare
102    OSError."""
103    try:
104        return lifeline.popen(args, role, **kw)       # a child that cannot outlive this server (serve/lifeline.py)
105    except OSError as e:
106        if getattr(e, "winerror", None) in (4551, 1260):
107            raise OSError(f"Windows blocked {what} ({args[0]}): Smart App Control, or an application-control policy, does "
108                          "not let a program that is not signed run. Turn Smart App Control off (Windows Security > App "
109                          "& browser control > Smart App Control settings), or - for the image encoder only - run setup "
110                          "with --vision no (see docs/TROUBLESHOOTING.md)") from e
111        raise
112
113
114# How long close() gives the engine at each step of ending it (seconds). Module values so that a test can shorten them.
115ENGINE_QUIT_WAIT_S, ENGINE_TERM_WAIT_S, ENGINE_KILL_WAIT_S = 20, 5, 20
116
117
118def rttime_limit_note() -> str:
119    """#3238: Linux only. A hard RLIMIT_RTTIME that is not unlimited (PipeWire's client module sets it to 0 when rtkit is
120    missing; every program started from that desktop inherits it) makes the kernel SIGKILL a process as soon as it
121    checks a thread with an armed CPU timer, with no OOM kill and no message. Returns one sentence naming the cause and
122    the fix, or "" when the limit is unlimited, the platform has no such limit or it cannot be read."""
123    try:
124        import resource
125        soft, hard = resource.getrlimit(resource.RLIMIT_RTTIME)
126    except (ImportError, AttributeError, OSError, ValueError):
127        return ""
128    if hard == resource.RLIM_INFINITY:
129        return ""
130    return (f"This session has a real-time CPU limit (RLIMIT_RTTIME hard limit {hard}; the desktop's audio system sets "
131            "it to 0 when rtkit is not installed). Linux can then end a program with signal 9 for no visible reason. "
132            "Install rtkit, or start Strata outside the desktop session's limits, for example: "
133            "systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ...")
134
135
136LEFTOVER_SETTLE_S = 120.0       # #4051: how long an engine ended at a start is waited for to give its memory back
137
138
139def end_leftover_engines(exe: str) -> None:
140    """Before an engine starts: end the ones a lost server left running (strata_control/procs.py). Only a process
141    this install recorded whose starter is gone, or an orphan of exactly this executable running --serve, and only
142    after its PID, start time and command line are checked again at the moment of the signal. Never raises.
143    #4051: the new engine is not started while the old one still holds its memory (tens of GB take longer than the
144    10 s this used to wait): a 40 GiB arena loaded beside 50 GiB the old engine had not returned put a 60 GiB PC into
145    memory reclaim for good.  One still there after LEFTOVER_SETTLE_S is said in plain words, and the start goes on
146    (the engine waits for the RAM itself and warns; nothing is refused)."""
147    if os.environ.get("STRATA_KEEP_LEFTOVERS") == "1":
148        return
149    try:
150        from strata_control import procs
151        say = lambda text: print(text, flush=True)        # noqa: E731
152        stuck = [r["pid"] for r in procs.end_leftovers(say=say, settle=LEFTOVER_SETTLE_S)["stuck"]]
153        stuck += [r["pid"] for r in procs.end_orphans(exe, say=say, settle=LEFTOVER_SETTLE_S) if r["outcome"] == "stuck"]
154        if stuck:
155            print(f"[strata] WARNING: the engine from an earlier run (process {', '.join(map(str, stuck))}) was told to stop "
156                  f"but still holds its memory after {LEFTOVER_SETTLE_S:.0f} s. Starting the next one now can leave this PC "
157                  "short of RAM and very slow: wait until that process is gone (it is shown by `ps`/Task Manager), "
158                  "or restart the PC if it does not go.", flush=True)
159    except Exception as e:  # noqa: BLE001 - a failed check must not stop a start
160        print(f"[strata] could not check for engines left by an earlier run: {type(e).__name__}", flush=True)
161
162
163def listen_problem(host: str, port: int, e: OSError) -> str:
164    """#769: why the server cannot listen.  Only an address that is taken says "already in use"; anything else (a port
165    Windows keeps reserved, an address this PC does not have, no permission) says what the OS said."""
166    import errno
167    code = getattr(e, "winerror", None) or e.errno
168    if code in (errno.EADDRINUSE, 10048):
169        return (f"port {port} is already in use - is Strata (or another server) already running? "
170                f"Close it, or start this one with a different --port")
171    what = e.strerror or str(e)
172    if code in (10013, errno.EACCES):
173        if sys.platform == "win32":
174            hint = ("Windows may keep this port for itself (see `netsh int ipv4 show excludedportrange protocol=tcp`) "
175                    "or a firewall rule forbids it: start this one with a different --port")
176        else:
177            hint = ("This system does not allow it (on Linux and macOS, ports below 1024 need administrator rights): "
178                    "start this one with a different --port")
179    elif code in (10049, errno.EADDRNOTAVAIL):
180        hint = f"{host} is not an address of this PC: check \"host\" in the model's strata-<model>.json or --host"
181    else:
182        hint = "check --host and --port"
183    return f"cannot listen on {host}:{port}: {what} [{code}]. {hint}"
184
185
186def combined_embeddings_path(vision_dir: Path, nbytes: int) -> Path:
187    """#874: where one request's combined image-embeddings file goes.  Every request with images rewrites it (it is
188    deleted after the request), which on a disk is steady heavy writing: on Linux it goes to /dev/shm when that has
189    room (the engine reads it back at once), on Windows the file is opened short-lived (the cache is not forced out
190    to the drive).  Anywhere else, or when /dev/shm is too small (Docker's default is 64 MB), it stays in the encoder's
191    own directory, as before."""
192    name = f"req-{uuid.uuid4().hex[:12]}.sve"
193    shm = Path("/dev/shm")
194    if os.name != "nt" and shm.is_dir() and os.access(shm, os.W_OK):
195        try:
196            if shutil.disk_usage(shm).free > 2 * nbytes + (16 << 20):
197                return shm / f"strata-vision-{os.getpid()}-{name}"
198        except OSError:
199            pass
200    return Path(vision_dir) / name
201
202
203def write_temporary(path: Path, parts: list) -> None:
204    """#874: write `parts` (files) one after the other into `path`; on Windows with FILE_ATTRIBUTE_TEMPORARY
205    (os.O_SHORT_LIVED), so the file normally never reaches the drive before it is deleted."""
206    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_BINARY", 0) | getattr(os, "O_SHORT_LIVED", 0)
207    with os.fdopen(os.open(path, flags, 0o600), "wb") as f:
208        for part in parts:
209            f.write(Path(part).read_bytes())
210# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the
211# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top
212EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n"
213EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the "
214                      "conclusion without unnecessary elaboration.",
215               "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary "
216                         "elaboration.",
217               # the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one
218               "xhigh": "Reasoning effort is set to xhigh. Please think carefully through the task, validate key "
219                        "assumptions, consider plausible alternatives, and prioritize correctness, consistency, and "
220                        "clarity in the final answer."}
221VISION_START = "<|vision_start|>"
222# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a
223# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens"
224# sets it; 0 turns it off.
225REPEAT_STOP_TOKENS = 256
226ANSWER_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
227DS41_DEFAULT_BUDGET = 32768   # DeepSeek-V4.1 only: the thinking budget when neither the request nor the config names one
228DS41_SMALL_CAP_MIN = 48       # DeepSeek-V4.1 only: from this max_tokens up to ANSWER_ROOM_MIN_CAP, thinking is capped at half of it
229ANSWER_RESERVE_MIN = 512     # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens
230# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)
231# #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside <think>, with no answer
232# and no call, is continued once with the thinking closed (the same way the budget's wrap-up closes it)
233REASONING_CLOSE = "\n</think>\n\n"
234REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"
235# 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
236# token of </think>): the engine stops there with its session at exactly the tokens it sent, so the next pass (+ the wrap-up)
237# continues from the live session.  Without it the engine ran a window or two past the cut, and the next pass read the
238# whole reasoning again from the checkpoint before it.  The server's own key in `sampling`, never a client's.
239HOLD_KEY = "_strata_hold"
240# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see).
241# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the
242# low-effort instruction in place of the xhigh one.  Both off by default.
243HIGH_EFFORT = EFFORT_TEXT["xhigh"]
244LOW_EFFORT = EFFORT_TEXT["low"]
245LOOP_CHECK_EVERY = 512           # output tokens between two looks at the reasoning (at a clean parser boundary)
246LOOP_COVERAGE = 0.25             # the share of the last 2,000 words inside 12-word passages seen three times
247LOOP_HISTORY_WORDS = 30000       # how far back the passages are counted (bounds the cost of a look)
248LOOP_TAIL_CHARS = 2048           # chars at the end of the reasoning also checked for a short period (#1753)
249LOOP_TAIL_PERIOD = 64            # a period at most this long in that tail reads as a fully repeated window
250
251
252def reasoning_repeat_coverage(text):
253    """Coverage of recent words by 12-word passages seen at least three times.
254
255    Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes
256    separated by long code drafts; the recent window excludes old repetitions.  #1753: a loop can also be one long
257    word (a 24k-digit string cycling an 11-digit pattern): the word split makes it a single word and no word count
258    grows, and #606's token run never grows either (the tokenizer has no multi-digit tokens), so before the word
259    count the last LOOP_TAIL_CHARS chars are checked for a period of at most LOOP_TAIL_PERIOD, and a periodic tail
260    reads as full coverage: it is all of the recent output, repeated.
261    """
262    tail = text[-LOOP_TAIL_CHARS:].lower()
263    if len(tail) == LOOP_TAIL_CHARS and any(tail[p:] == tail[:-p] for p in range(1, LOOP_TAIL_PERIOD + 1)):
264        return 1.0
265    words = re.findall(r"\w+|[^\w\s]", text.lower())[-LOOP_HISTORY_WORDS:]
266    width, window = 12, 2000
267    if len(words) < window:
268        return 0.0
269    grams = [tuple(words[i:i + width]) for i in range(len(words) - width + 1)]
270    counts = collections.Counter(grams)
271    start = max(0, len(words) - window)
272    covered = set()
273    for i in range(start, len(grams)):
274        if counts[grams[i]] >= 3:
275            covered.update(range(i, i + width))
276    return len(covered) / (len(words) - start)
277
278
279def focused_recovery_prompt(tok, ids, generated):
280    """The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then
281    every token generated so far.  A splice of token ids: the prompt is never decoded and encoded again, so a literal
282    `</think>` or vision marker in it (#537, #554) stays what it was.  None when the sentence is not there as whole
283    tokens in the first system message (a user's text never counts).  No answer or end-of-thinking is inserted."""
284    end = tok.encode(IM_END, parse_special=True)
285    if len(end) != 1 or end[0] not in ids:
286        return None
287    head = ids[:ids.index(end[0])]
288    if not tok.decode(head).startswith("<|im_start|>system\n"):
289        return None
290    old, new = tok.encode(HIGH_EFFORT, parse_special=False), tok.encode(LOW_EFFORT, parse_special=False)
291    for i in range(len(head) - len(old) + 1):
292        if head[i:i + len(old)] == old:
293            return ids[:i] + new + ids[i + len(old):] + list(generated)
294    return None
295
296
297LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
298QUEUE_BEAT_S = 10.0         # a request waiting for the single turn sends a keep-alive this often (#1619)
299KEEPALIVE_S = 10.0          # a held-back tool argument leaves the stream quiet: ping at least this often
300# Anthropic clients add /v1/messages to their base URL themselves. A base URL that already ends in /v1 (copied from an OpenAI-style
301# setup) makes them post /v1/v1/messages; these two paths mean the same as the real ones. Nothing else is aliased.
302V1_V1_ALIASES = {"/v1/v1/messages": "/v1/messages", "/v1/v1/messages/count_tokens": "/v1/messages/count_tokens"}
303CTX_SLACK = 8               # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
304
305
306class ContextOverflow(ValueError):
307    """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
308    does: a client that decides from the wording (Claude Code compacts on "prompt is too long", and shortens max_tokens on "input length and
309    `max_tokens` exceed context limit") then does what it does for Anthropic's own error (#4838)."""
310
311    def __init__(self, text, *, prompt, context, max_new=None):
312        super().__init__(text)
313        self.prompt, self.context, self.max_new = prompt, context, max_new
314
315    def anthropic_text(self) -> str:
316        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
317            return f"prompt is too long: {self.prompt} tokens > {self.context - CTX_SLACK - 1} maximum; {self}"
318        return f"input length and `max_tokens` exceed context limit: {self.prompt} + {self.max_new} > {self.context - CTX_SLACK}; {self}"
319# 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
320# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
321RATE_WINDOW_S = 2.0
322RATE_MIN_SPAN_S = 0.25      # younger than this there is no rate yet: the mean so far, with the span floored here
323# #481: a running request whose engine prints nothing (no T, PP or any other line) for this long has lost step with the
324# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails;
325# the next request starts it again.  The config's "engine_silence_s" sets it (0: wait forever, as before).
326ENGINE_SILENCE_S = 300.0
327# #4271: a streaming client that stops reading (a hung process, a network that dropped) leaves the thread that writes to
328# it blocked once the socket buffers are full - and that thread holds the engine's turn.  A write that makes no progress
329# for this long ends the request as a disconnect (the engine is stopped, the turn given back).  0: no limit, as before.
330STREAM_WRITE_TIMEOUT_S = float(os.environ.get("STRATA_STREAM_WRITE_TIMEOUT_S", "60") or 0)
331# Disk sessions: the longest allowance an engine may announce (`SWAIT <phase> <s>`) for one step that blocks in a
332# single call (a file flush, the host->device transfer); the engine's own bound is the same (session_phase_limit_s).
333SESSION_WAIT_MAX_S = 3600
334# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue
335# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line.  Until the first
336# 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.
337PP_CHUNK_MAX = 32768
338PP_FLOOR_TOK_S = 50.0
339PP_SLACK = 3.0
340# Reads that had no timeout (#1317).  A blocking read of the image encoder's pipe or of the engine's READY line that
341# never returned held the request turn for good: the engine then sat idle in its command loop, so no watchdog could
342# fire and every later request queued behind it (the "lost step" class of #481).  Generous on purpose: a cold model
343# load, a slow disk or a slow CPU encode is not a hang.  Only a process that says nothing at all for this long is
344# ended; the next request starts it again.
345# STRATA_ENGINE_READY_S / STRATA_VISION_READY_S / STRATA_VISION_ENCODE_S override them (0 = wait for ever, as before).
346
347
348def _timeout_env(name: str, default: float) -> float | None:
349    try:
350        v = float(os.environ.get(name, default))
351    except ValueError:
352        v = default
353    return None if v <= 0 else v
354
355
356# #1317 part 2: the quick watchdog for a FROZEN engine.  engine_silence_s (above) is generous on purpose: a slow PC reads a
357# prompt chunk for minutes without a line.  But an engine that prints nothing for ENGINE_STALL_S and also uses no CPU time and
358# moves no bytes of I/O in that time is not slow, it is idle or frozen (a deadlock in a CUDA call, a driver stall, a lost
359# step), and waiting longer cannot help: it is ended, and the next request starts it again.  An engine that is silent but
360# still working is never ended by this, only reported once (the recommendation: engine_silence_s, or this variable).
361# STRATA_ENGINE_STALL_S overrides it (0 = off).  Needs psutil (setup installs it); without it nothing is ended.
362ENGINE_STALL_S = _timeout_env("STRATA_ENGINE_STALL_S", 90.0)
363PAR_COUNTERS = os.environ.get("STRATA_PAR_COUNTERS") == "1"   # research counters (queue wait for a slot), shown in /v1/status
364# --batch: new requests take the control lines (one prompt read at a time) short prompts first: a prompt of at most
365# STRATA_ADMIT_SHORT_FIRST tokens goes before longer ones (opt-in; unset or 0: whoever gets the lock first), and a
366# longer one that waited STRATA_ADMIT_MAX_WAIT_S (default 30) counts as short.  A chat question then waits for the one
367# read in progress, not for every agent read that came before it.
368try:
369    ADMIT_SHORT_FIRST = max(0, int(os.environ.get("STRATA_ADMIT_SHORT_FIRST") or 0))
370except ValueError:
371    ADMIT_SHORT_FIRST = 0
372ADMIT_MAX_WAIT_S = _timeout_env("STRATA_ADMIT_MAX_WAIT_S", 30.0) or 0.0
373# STRATA_COALESCE_PREFILL=N (research, PAR-H; needs the engine's BCO / BCOK lines): a request that takes the control lines
374# for its admission also sends the prompts of up to N-1 requests still waiting for them (BCO <slot> <ids>, into free slots
375# it reserves for them); the engine reads all the prompts in ONE layer-major pass, so the experts a layer streams are
376# read once for all of them, and each waiting request then finds its prompt in its slot.  0 / unset: off.
377COALESCE_PREFILL = max(0, int(os.environ.get("STRATA_COALESCE_PREFILL") or 0))
378COALESCE_TOKENS = max(256, int(os.environ.get("STRATA_COALESCE_TOKENS") or 16384))   # prompt tokens read together at most
379COALESCE_WAIT_MS = max(0, int(os.environ.get("STRATA_COALESCE_WAIT_MS") or 0))       # a burst's later requests register within this long
380# Adaptive: a read is shared (and the leader waits for its followers) only when this engine has seen at least
381# COALESCE_MIN_REQS requests arrive within COALESCE_BURST_MS (the leader's own included).  Fewer than that - one or two
382# requests per engine, as 8 requests on 4 replicas - read plainly, with no wait: nothing to share, and the wait and the
383# longer pass only cost (measured 4 x 1 replicas at 8 requests: 168 against 196 tok/s with an unconditional wait).
384COALESCE_MIN_REQS = max(2, int(os.environ.get("STRATA_COALESCE_MIN_REQS") or 3))
385COALESCE_BURST_MS = max(10, int(os.environ.get("STRATA_COALESCE_BURST_MS") or 250))
386STALL_CPU_EPS_S = 0.5       # CPU seconds the engine may use in the whole stall window and still count as frozen
387STALL_IO_EPS_B = 1 << 20    # bytes read or written in that window
388
389
390def engine_frozen(base: tuple[float, int], now: tuple[float, int]) -> bool:
391    """#1317: True when two (cpu seconds, io bytes) samples of the engine show no work between them."""
392    return (now[0] - base[0]) <= STALL_CPU_EPS_S and (now[1] - base[1]) <= STALL_IO_EPS_B
393
394
395VISION_READY_S = _timeout_env("STRATA_VISION_READY_S", 300.0)
396VISION_ENCODE_S = _timeout_env("STRATA_VISION_ENCODE_S", 300.0)
397ENGINE_READY_S = _timeout_env("STRATA_ENGINE_READY_S", 900.0)
398
399
400# ------------------------------------------------------------------------------------------------ engines
401class Engine(Protocol):
402    max_context: int
403    def generate(self, ids: list[int], max_new: int, sampling: dict, cancel: threading.Event) -> Iterator[int]: ...
404
405
406class MockEngine:
407    """Replays a scripted completion (text) as token ids, one per step, then the end-of-turn token.  Given a list of
408    scripts, each request gets the next one and the last one repeats (a tool call, then the answer after it)."""
409
410    def __init__(self, tokenizer, script: str | list[str], max_context: int = 32768, delay_s: float = 0.0,
411                 cycle: bool = False):
412        self.tok, self.max_context, self.delay = tokenizer, max_context, delay_s
413        end = tokenizer.encode(IM_END, parse_special=True)
414        self.scripts = [tokenizer.encode(x, parse_special=True) + end for x in ([script] if isinstance(script, str)
415                                                                                 else script)]
416        self.script, self.turns = self.scripts[0], 0
417        # `cycle` picks the script by request position instead of advancing to the last one and staying
418        # there. A harness adds requests the script author did not plan for -- a session title, a re-ask
419        # after a tool result -- and with the default behaviour one extra request shifts every later
420        # reply, so a run looks like a model that simply chose differently.
421        self.cycle = bool(cycle)
422        self.last_prompt: list[int] = []
423
424    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
425        self.last_prompt = list(ids)
426        self.last_embeddings = embeddings
427        if len(self.scripts) > 1:
428            if self.cycle:
429                self.script = self.scripts[self.turns % len(self.scripts)]
430            else:
431                self.script = self.scripts[min(self.turns, len(self.scripts) - 1)]
432            self.turns += 1
433        for t in self.script[:max_new]:
434            if cancel.is_set():
435                return
436            if self.delay:
437                time.sleep(self.delay)
438            yield t
439
440
441class EngineDied(RuntimeError):
442    """The engine process ended in the middle of a request (issue #27: on Linux, the out-of-memory killer)."""
443    restarts = True        # the engine is gone, so the next request starts it again; False for an error raised while the engine is left running (#3961)
444
445
446def died_note(e: Exception) -> str:
447    """What an API error says about an EngineDied: the cause, and that the next request restarts the engine - only where it really is ended."""
448    return f"{e}; the next request restarts it" if getattr(e, "restarts", True) else str(e)
449
450
451class EngineStarting(RuntimeError):
452    """The engine is (re)starting and has not said READY yet (#344): no context size to plan a request with - a 503,
453    not a 400 about the prompt."""
454
455
456class ClientGone(Exception):
457    """#1999: the client hung up while its request was being prepared (an image URL downloading, a picture encoding or
458    waiting for its turn): nothing is left to answer."""
459
460
461class ModelBusy(RuntimeError):
462    """Explicit model controls must not interrupt active or queued requests."""
463
464
465class QueueWaitExpired(RuntimeError):
466    """An inference call waited too long for its first engine turn."""
467
468
469class QueueCancelled(RuntimeError):
470    """The client left before its first serial engine turn."""
471
472
473class EngineSilent(EngineDied):
474    """#481: the engine said nothing for too long during a request (or never acknowledged a STOP): the two sides lost
475    step - the engine waiting for its next command, the server for this request's end - and the server ended it.  An
476    EngineDied, so the request ends with an error and the next one starts the engine again."""
477
478
479class EngineNonFinite(ValueError):
480    """#879: the engine's DONE (or a slot's BDONE) said `nonfinite`: a window's logits held a NaN or an infinity.  The
481    engine wrote none of that window's tokens and drops every cached state that may carry the poison, so its next
482    request reads the prompt from token 0.  Service.run sends a request that had produced nothing yet once more, and
483    ends one that had started (as "length").  A ValueError, so a stream that has started reports it as an error event."""
484
485
486class SessionRefused(ValueError):
487    """Disk sessions: the engine refused or failed a SAVE / RESTORE and is still in step (`SERR <kind> <published>
488    <reason>`).  `kind` is the engine's category - invalid (400), storage (507), memory (503), io (500); `published`:
489    a save whose new file already replaced the old one before a later step (the folder flush) failed."""
490
491    STATUS = {"invalid": 400, "storage": 507, "memory": 503, "io": 500}
492
493    def __init__(self, kind: str, message: str, published: bool = False):
494        super().__init__(message)
495        self.kind = kind if kind in self.STATUS else "io"
496        self.published = published
497
498    @property
499    def status(self) -> int:
500        return self.STATUS[self.kind]
501
502
503class EngineStuck(RuntimeError):
504    """The engine process did not end after QUIT, terminate and kill: the server keeps it (and says so) rather than
505    reporting its GPU and RAM as given back."""
506
507
508class GpuBusy(RuntimeError):
509    """The model is unloaded and the GPU has less free VRAM than min_free_vram_mib: something else (a game, another
510    model server) is using it, so the engine is not started into the little that is left.  `retry_after`: seconds
511    for the Retry-After header of the 503."""
512
513    def __init__(self, message="", retry_after=None):
514        super().__init__(message)
515        self.retry_after = retry_after
516
517
518# The page's only CSP directive: its preview frames (srcdoc) may not load any address. Other directives are left out
519# on purpose: a frame made from srcdoc inherits the page's policy, and the opt-in "run scripts" preview needs its own inline script.
520PAGE_CSP = "frame-src 'none'"
521
522
523def unload_wait(value, default: float) -> float:
524    """#1997: the `wait` of POST /unload?wait=...: absent / 0 / false: 0 (answer "busy" at once, as before); 1 / true /
525    yes: `default` seconds; a number of seconds above 1: that long (at most an hour)."""
526    if value is None:
527        return 0.0
528    v = str(value).strip().lower()
529    if v in ("", "0", "false", "no", "off"):
530        return 0.0
531    if v in ("1", "true", "yes", "on"):
532        return default
533    try:
534        return min(3600.0, max(0.0, float(v)))
535    except ValueError:
536        return default
537
538
539ENGINE_REQUEST = re.compile(
540    # "+ 12288 of 98179 read": a request cancelled while its prompt was read (#471)
541    r"prompt (?P<prompt>\d+) tokens = (?P<reused>\d+) reused \+ \d+(?: of \d+)? read in (?P<read>[\d.]+) ms "
542    r"\((?P<pp>[\d.]+) tok/s\), "
543    r"(?P<gen>\d+) generated in (?P<gen_ms>[\d.]+) ms \((?P<tg>[\d.]+) tok/s\)")
544
545
546ENGINE_SCR = re.compile(r"SCR cached (?P<cached>\d+) scr (?P<scr>\d+) prefilled (?P<prefilled>\d+) of (?P<prompt>\d+)")
547
548
549_echoing: set[str] = set()      # the logs echo_requests already follows (restart() runs StrataEngine.__init__ again)
550
551DRAFT_HEAD_FAIL = "the draft head does not fit"
552DRAFT_HEAD_HINT = ("a smaller draft vocabulary needs less VRAM: --draft-vocab cyrillic (English, code and the Cyrillic "
553                   "script) or --draft-vocab en (English and code, ~215 MiB less than the default). Start once with "
554                   "it - START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model "
555                   "keeps it; or a smaller --context in setup.")
556
557
558def start_failure_hint(log: str | None, offset: int) -> str:
559    """#474: what to change when the engine stopped at the start because the MTP draft head did not fit the VRAM
560    left: the engine's own `strata mtp:` lines after that failure (0.1.36+: what it needs, what is free, the smaller
561    subsets), else the same advice in words for an older engine.  "" for any other failure: the log says why."""
562    if not log:
563        return ""
564    try:
565        with open(log, "rb") as f:
566            f.seek(offset)
567            text = f.read().decode("utf-8", "replace")
568    except (OSError, ValueError):
569        return ""
570    if DRAFT_HEAD_FAIL not in text:
571        return ""
572    said = [x.strip()[len("strata mtp: "):] for x in text.splitlines()
573            if x.strip().startswith("strata mtp: ") and ("draft head over" in x or "hint:" in x)]
574    return ". mtp: " + DRAFT_HEAD_FAIL + ". " + (" ".join(said) if said else "Hint: " + DRAFT_HEAD_HINT)
575
576
577def start_log_text(log: str | None, offset: int, limit: int = 1 << 20) -> str:
578    """Everything this engine start has written to the log so far (at most `limit` bytes), "" when there is no log."""
579    if not log:
580        return ""
581    try:
582        with open(log, "rb") as f:
583            f.seek(max(0, offset))
584            return f.read(limit).decode("utf-8", "replace")
585    except (OSError, ValueError):
586        return ""
587
588
589def start_log_tail(log: str | None, offset: int, n: int = 20) -> str:
590    """#496: the last n lines this start wrote to the engine log, for the error when the engine ended before READY -
591    whatever the failure, the engine's own reason is in them (people posted the traceback without the log).  "" when
592    there is no log or nothing in it from this start."""
593    if not log:
594        return ""
595    try:
596        with open(log, "rb") as f:
597            f.seek(0, 2)
598            start = max(offset, f.tell() - 64 * 1024)   # enough for 20 lines, never an earlier start's
599            f.seek(start)
600            text = f.read().decode("utf-8", "replace")
601    except (OSError, ValueError):
602        return ""
603    lines = text.splitlines()[1 if start > offset else 0:]   # not a line cut in half
604    lines = [x.rstrip() for x in lines if x.strip()][-n:]
605    if not lines:
606        return ""
607    return "\nthe engine log's last lines:\n" + "\n".join("  " + x for x in lines)
608
609
610# Windows NTSTATUS exit codes of a process the system ended (a crash, not an error the engine reported)
611_WIN_CRASH = {0xC000001D: "illegal instruction (the CPU lacks an instruction the program uses)",
612              0xC0000005: "access violation", 0xC0000409: "stack buffer overrun / fast-fail",
613              0xC0000135: "a DLL the program needs was not found", 0xC0000139: "entry point not found in a DLL",
614              0xC0000142: "a DLL failed to initialize", 0xC000007B: "bad image (32-bit / 64-bit mix-up)",
615              0xC00000FD: "stack overflow", 0xC0000094: "integer division by zero", 0xC0000096: "privileged instruction"}
616
617
618def engine_exit_words(rc: int | None) -> str:
619    """What a process's exit status says, in words: "killed by signal 4 (SIGILL, Illegal instruction)" (a negative status
620    on Linux / macOS), a Windows NTSTATUS crash code, or "exit code N".  "" when there is no status."""
621    if rc is None:
622        return ""
623    if rc < 0 and os.name != "nt":
624        try:
625            sig = signal.Signals(-rc)
626            return f"killed by signal {-rc} ({sig.name}, {signal.strsignal(sig) or sig.name})"
627        except (ValueError, AttributeError):
628            return f"killed by signal {-rc}"
629    code = rc & 0xFFFFFFFF
630    if code in _WIN_CRASH:
631        return f"exit code 0x{code:08X}: {_WIN_CRASH[code]}"
632    if 0xC0000000 <= code < 0xD0000000:
633        return f"exit code 0x{code:08X} (a system error status)"
634    return f"exit code {rc}"
635
636
637def engine_crashed(rc: int | None) -> bool:
638    """True when the engine process was ended by the system (an illegal instruction, a bad memory access, the
639    out-of-memory killer, a missing DLL ...) rather than leaving by itself: nothing a second try fixes."""
640    if rc is None:
641        return False
642    if rc < 0 and os.name != "nt":
643        return -rc in {int(getattr(signal, n)) for n in ("SIGILL", "SIGSEGV", "SIGBUS", "SIGFPE", "SIGKILL")
644                       if hasattr(signal, n)}
645    return 0xC0000000 <= (rc & 0xFFFFFFFF) < 0xD0000000      # an NTSTATUS error code
646
647
648def cpu_isa_words() -> tuple:
649    """(text, missing): the CPU's model and which of AVX / AVX2 / FMA / F16C it reports (Linux: /proc/cpuinfo), and the
650    ones of those it lacks.  ("", []) where it cannot be read."""
651    try:
652        text = Path("/proc/cpuinfo").read_text(errors="replace")
653    except OSError:
654        return "", []
655    model = next((x.split(":", 1)[1].strip() for x in text.splitlines() if x.lower().startswith("model name")), "")
656    flags = next((x.split(":", 1)[1].split() for x in text.splitlines() if x.lower().startswith("flags")), [])
657    have = ", ".join(f"{f} {'yes' if f in flags else 'NO'}" for f in ("avx", "avx2", "fma", "f16c", "avx512f"))
658    missing = [f for f in ("avx", "avx2", "fma", "f16c") if f not in flags]
659    return f"{model or 'this CPU'} ({have})", missing
660
661
662def start_exit_note(rc: int | None, exe=None) -> str:
663    """The sentence the start error carries about how the engine process ended (the engine log is silent when the
664    system ends it): "" without a status, else a line, with the CPU's AVX flags after an illegal instruction."""
665    words = engine_exit_words(rc)
666    if not words:
667        return ""
668    note = f"\nthe engine process ended: {words}"
669    try:                                            # 0xC0000135: say which DLL (the loader prints nothing)
670        from serve.loader_diag import missing_note
671        note += missing_note(rc, exe)
672    except Exception:
673        pass
674    if rc is not None and ((rc < 0 and os.name != "nt" and -rc == int(getattr(signal, "SIGILL", 4))) or
675                           (rc & 0xFFFFFFFF) == 0xC000001D):
676        isa, missing = cpu_isa_words()
677        note += "\n  An illegal instruction: the engine ran an instruction this CPU cannot execute"
678        if isa and missing:
679            note += f" ({', '.join(m.upper() for m in missing)} missing; {isa})"
680        elif isa:
681            note += f"; the CPU reports AVX, AVX2, FMA and F16C ({isa}), so this is a bug in the engine"
682        note += ".  Please report it with the CPU model (github.com/Niko1221/Strata/issues)."
683    return note
684
685
686def start_log_marks(log: str | None, offset: int) -> list:
687    """The GPU runtime failure texts (TRANSIENT_START_MARKS) this start wrote to the log: what lets a retry notice say the
688    GPU runtime failed.  [] when none, or no log."""
689    if not log:
690        return []
691    try:
692        with open(log, "rb") as f:
693            f.seek(offset)
694            text = f.read(64 * 1024).decode("utf-8", "replace")
695    except (OSError, ValueError):
696        return []
697    return [m for m in TRANSIENT_START_MARKS if m in text]
698
699
700# A start that ends at once with the GPU runtime's own failure and none of the engine's lines: on ROCm, a start right
701# after the previous engine exited can fail inside the runtime's device/queue set-up while the old process's queues are
702# still being torn down ("terminate called after throwing an instance of 'rocr::AMD::hsa_exception'", or an exit with
703# nothing in the log).  Such a start is tried again after a short wait (STRATA_START_RETRIES, default 3; 0: never).
704TRANSIENT_START_MARKS = ("hsa_exception", "HSA_STATUS_ERROR", "hsaKmt")
705START_RETRIES = max(0, int(os.environ.get("STRATA_START_RETRIES", "3") or 0))
706
707
708def transient_start_failure(log: str | None, offset: int, elapsed_s: float, rc: int | None = None) -> bool:
709    """True when the start that wrote the log from `offset` failed the transient way above: within 30 s, and its lines
710    are only the launcher's own "engine started" line plus (optionally) a GPU runtime failure.  An exit with no line
711    at all counts only when it was not the engine's own error exit (1: it said why on stdout)."""
712    if not log or elapsed_s > 30.0:
713        return False
714    try:
715        with open(log, "rb") as f:
716            f.seek(offset)
717            text = f.read(64 * 1024).decode("utf-8", "replace")
718    except (OSError, ValueError):
719        return False
720    lines = [x.strip() for x in text.splitlines() if x.strip()]
721    engine_lines = [x for x in lines if not x.startswith("[strata]")]
722    if any(m in text for m in TRANSIENT_START_MARKS):
723        return all(x.startswith("terminate called") or x.startswith("what()") or
724                   any(m in x for m in TRANSIENT_START_MARKS) for x in engine_lines)
725    # it exited without writing a single line of its own - but not when the system ended it (an illegal instruction, a
726    # bad memory access, the OOM killer, a missing DLL): that is a crash a second try repeats, and the retry notice
727    # must not call it a GPU runtime start (#2324: an old CPU's illegal instruction was retried 3 times as "GPU
728    # runtime" and the real reason never shown)
729    return not engine_lines and rc != 1 and not engine_crashed(rc)
730
731
732def echo_requests(log_path: str, offset: int) -> None:
733    """STRATA_REQUEST_LINES=1: one stdout line per finished request, from the engine's own summary in its log.
734
735    The engine's stderr goes to the log file (the start narrator reads it), so a supervisor that only sees this
736    process's output - a tray, llama-swap - has no per-request numbers. This re-states the engine's line with the
737    total the two times make: `request prompt P cached C output O prompt_read R ms total S ms prefill X tok/s decode Y
738    tok/s` (prompt_read: the time the engine spent reading the prompt's new tokens, not a time to first token).
739    """
740    with open(log_path, "r", encoding="utf-8", errors="replace") as f:
741        f.seek(offset)
742        while True:
743            line = f.readline()
744            if not line:
745                time.sleep(0.2)
746                continue
747            s = ENGINE_SCR.search(line)
748            if s:
749                print("[strata] request scr cached %s scr %s prefilled %s of %s" % (s["cached"], s["scr"], s["prefilled"], s["prompt"]),
750                      flush=True)
751            m = ENGINE_REQUEST.search(line)
752            if m:
753                read_ms, gen_ms = float(m["read"]), float(m["gen_ms"])
754                print("[strata] request prompt %s cached %s output %s prompt_read %.0f ms total %.0f ms prefill %s "
755                      "tok/s decode %s tok/s" % (m["prompt"], m["reused"], m["gen"], read_ms, read_ms + gen_ms, m["pp"],
756                                                 m["tg"]), flush=True)
757
758
759def experts_loading_words(args: list, size: str) -> str:
760    """#505: what the start does with the experts, by the engine's flags (generate.cpp's option parsing): a RAM budget
761    copies the hottest N GiB into RAM (--resident-budget-gib), the resident low-RAM mode the ones the GPU does not hold
762    (--resident-experts), plain --mmap-experts reads them from the model files through the OS file cache (nothing is
763    loaded into RAM up front); otherwise all of them go into RAM."""
764    if "--resident-budget-gib" in args:
765        try:
766            n = f"up to {float(args[args.index('--resident-budget-gib') + 1]):g} GiB"
767        except (IndexError, ValueError):
768            n = "a RAM budget"
769        return (f"loading the most-used experts into RAM ({n}; the rest are read from the model files as needed) "
770                "and locking part of them for the GPU.")
771    if "--resident-experts" in args:
772        return (f"loading the experts the GPU does not hold into RAM (of {size}) and locking part of them for the "
773                "GPU.")
774    if "--mmap-experts" in args:
775        return (f"mapping the experts from the model files ({size}, --mmap-experts): they are not loaded into RAM - "
776                "the OS file cache reads them as the GPU's expert cache fills and as requests need them.")
777    return f"loading the experts into RAM ({size}) and locking part of them for the GPU."
778
779
780OPENS_BROWSER = False        # set in main() when the server was started with --open: only then may a message say a browser opens
781
782
783# STRATA_DS4_RESTORE_POINTS (4): the DeepSeek engine keeps restore points where a later prompt is likely to leave this
784# one - its GEN line carries marks=<pos>,..., tail=<pos> and shared=<pos> - besides the end of the last prompt, the
785# position before it and the anchor it keeps anyway.  N (1-16) turns them on, and is also the engine's cap a
786# conversation (it reads the same setting); 0: no keys, every GEN line as before.  STRATA_DS4_RESTORE_TAIL (512): how
787# far before the prompt's end the tail point sits (0: none).  (Project Maya #639, restore points.)
788RESTORE_LEAST = 1024        # no point before this many tokens: such a start is read again in about the time a point costs
789
790
791def restore_point_settings(env=None) -> tuple[bool, int]:
792    """(on, tail) from STRATA_DS4_RESTORE_POINTS and STRATA_DS4_RESTORE_TAIL."""
793    env = os.environ if env is None else env
794
795    def whole(name, default):
796        try:
797            return max(0, int(str(env.get(name, default)).strip()))
798        except ValueError:
799            return default
800    return whole("STRATA_DS4_RESTORE_POINTS", 4) > 0, whole("STRATA_DS4_RESTORE_TAIL", 512)
801
802
803def deepseek_restore_points(ids, user_id, system_id=None, tail=512, least=RESTORE_LEAST) -> dict:
804    """Where the DeepSeek engine keeps restore points for this prompt -> {"marks": [pos, ...], "tail": pos, "shared":
805    pos} (any may be missing; {}: none).  From the prompt's ids as the template wrote them: a turn opens with its role's
806    special token (<|User|>, a tool result's turn too; <|System|> for a system message after the first user turn), and
807    text inside a message never encodes to one, so the positions are the template's own.
808
809    - the start of the last user turn: its last message edited, or sent again after another answer, goes back there;
810    - "tail": `tail` tokens before the end, when the last turn is longer than that: a new question after the same long
811      document in the same message;
812    - "shared": the end of the system prompt and its tools (the first user turn): another conversation behind the same
813      start goes back there, and the engine gives that point up last.
814    Positions under `least` are left out: a start that short is read again in about the time a point costs."""
815    if user_id is None or len(ids) < 2:
816        return {}
817    first = last = None
818    for i, t in enumerate(ids):
819        if t == user_id:
820            first = i if first is None else first
821            last = i
822        elif t == system_id and first is not None:
823            last = i
824    marks, out = [], {}
825    if first is not None and first >= least:
826        out["shared"] = first
827    if last is not None and last >= least and last != first:
828        marks.append(last)
829    t = len(ids) - tail
830    if tail > 0 and t >= least and (last is None or t > last):
831        out["tail"] = t
832    if marks:
833        out["marks"] = sorted(marks)
834    return out
835
836
837def narrate_start(log_path: str, offset: int, args: list, done: threading.Event, heartbeat=20.0) -> None:
838    """While the engine starts, say in the server window what it is doing, from its log: the start reads tens of GB
839    into RAM and locks part of it for the GPU, and on many PCs everything is slow or frozen for a minute or more -
840    people closed the window thinking it had hung.  The warning comes at that step, not after it."""
841    gb = 0.0
842    if "--native" in args:                              # about the size of the experts it will read
843        try:
844            gb = os.path.getsize(args[args.index("--native") + 1]) / 1e9
845        except (OSError, IndexError):
846            pass
847    size = f"about {gb:.0f} GB" if gb >= 1 else "tens of GB"
848    loading = experts_loading_words(args, size)
849    t0 = last = time.time()
850    said = set()
851
852    def say(key, text):
853        nonlocal last
854        if key not in said:
855            said.add(key)
856            last = time.time()
857            print(text, flush=True)
858
859    say("weights", "[strata] starting the engine: reading the model's weights ...")
860    pos = offset
861    while not done.wait(0.5):
862        try:
863            with open(log_path, "rb") as f:
864                f.seek(pos)
865                chunk = f.read()
866        except OSError:
867            chunk = b""
868        if chunk.count(b"\n"):
869            cut = chunk.rfind(b"\n") + 1
870            pos += cut
871            for line in chunk[:cut].decode("utf-8", "replace").splitlines():
872                if "PLE on" in line or "expert arena:" in line or "experts via mmap" in line:   # #505: mapped
873                    say("arena", f"[strata] {loading}\n"
874                                 "         YOUR PC CAN BE SLOW OR STOP RESPONDING FOR 1-3 MINUTES NOW - this is normal.\n"
875                                 "         Please wait and don't close this window"
876                                 + ("; the browser opens when it is ready." if OPENS_BROWSER else "; the server says when it is ready."))
877                elif " loaded " in line and "GiB at" in line:
878                    say("loaded", "[strata] experts loaded: " + line.split(" loaded ", 1)[1].strip() +
879                        f" ({time.time() - t0:.0f} s so far)")
880                elif "expert cache " in line and " slots, " in line and "auto" not in line:
881                    n = line.split("expert cache ", 1)[1].split(";")[0].replace(" slots,", " experts,").strip()
882                    say("cache", f"[strata] filling the GPU's expert cache ({n}) ...")
883                elif "session is up" in line:
884                    say("up", "[strata] almost ready ...")
885        if time.time() - last > heartbeat:
886            last = time.time()
887            print(f"[strata] still starting ({time.time() - t0:.0f} s) - please wait ...", flush=True)
888
889
890class ConvCacheLog:
891    """#596: the engine's conversation cache as its log tells it (the engine writes "strata serve: conversation
892    cache: parked N tokens ...; parked=P bytes=B evictions=E" and "restored N tokens ...; parked=P bytes=B" to stderr,
893    which is the log): read on from where it was last read, from the start of the engine's current run."""
894    EVENT = re.compile(r"conversation cache: (parked|skipped|restored) (\d+) tokens.*?parked=(\d+) bytes=(\d+)"
895                       r"(?: evictions=(\d+))?")
896    DROPPED = re.compile(r"conversation cache: dropped \d+ superseded .*?parked=(\d+)")
897    READ_MAX = 1 << 20                                  # at most the last MiB of new lines per read
898
899    def __init__(self):
900        self.key, self.pos = None, 0
901        self.lock = threading.Lock()                    # polls come from several request / monitor threads at once
902        self.reset()
903
904    def reset(self):
905        self.state = {"parked": 0, "bytes": 0, "evictions": 0, "parks": 0, "restores": 0, "last_event": None,
906                      "last_tokens": None, "last_at": None}
907
908    def poll(self, path, start) -> dict:
909        """The state after the log's new lines; `start` is where the engine's current run began in it.  One poll at a
910        time: a second one moved `pos` between the size check and the seek and raised ValueError (negative seek)."""
911        with self.lock:
912            return self._poll(path, start)
913
914    def _poll(self, path, start) -> dict:
915        if not path or start is None:
916            return dict(self.state)
917        if self.key != (path, start):                   # another start of the engine: its cache starts empty
918            self.key, self.pos = (path, start), start
919            self.reset()
920        try:
921            size = os.path.getsize(path)
922            if size < self.pos:                         # the log was emptied or replaced
923                self.pos = 0
924            if size - self.pos > self.READ_MAX:
925                self.pos = size - self.READ_MAX
926            with open(path, "rb") as f:
927                f.seek(self.pos)
928                data = f.read(size - self.pos)
929        except OSError:
930            return dict(self.state)
931        end = data.rfind(b"\n") + 1                     # whole lines only: the rest is read next time
932        self.pos += end
933        now = time.time()
934        for line in data[:end].decode("utf-8", "replace").splitlines():
935            if "conversation cache:" not in line:
936                continue
937            m = self.EVENT.search(line)
938            if m:
939                st = self.state
940                st["parked"], st["bytes"] = int(m.group(3)), int(m.group(4))
941                if m.group(5) is not None:
942                    st["evictions"] = int(m.group(5))
943                if m.group(1) != "skipped":
944                    st["parks" if m.group(1) == "parked" else "restores"] += 1
945                    st["last_event"], st["last_tokens"], st["last_at"] = m.group(1), int(m.group(2)), now
946                continue
947            m = self.DROPPED.search(line)
948            if m:
949                self.state["parked"] = int(m.group(1))
950        return dict(self.state)
951
952
953def conversation_slots(engine) -> int | None:
954    """How many conversations the engine's cache holds: its --conversation-cache-slots argument, which is known
955    before the engine has started (a lazy start has reported no INFO line yet), else the INFO line it reported."""
956    args = engine.spawn[1] if hasattr(engine, "spawn") else []
957    if "--conversation-cache-slots" in args[:-1]:
958        try:
959            return int(args[args.index("--conversation-cache-slots") + 1])
960        except ValueError:
961            pass
962    slots = (getattr(engine, "info", None) or {}).get("conversation_cache_slots")
963    return slots if isinstance(slots, int) else None
964
965
966def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict:
967    """#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in
968    --conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back."""
969    mib = info.get("conversation_cache_mib")
970    last = hist[-1] if hist else None
971    return {"enabled": isinstance(mib, int) and mib > 0, "budget_mib": mib if isinstance(mib, int) else None,
972            "slots": info.get("conversation_cache_slots"), **parked,
973            "requests": len(hist), "requests_reused": sum(1 for r in hist if (r.get("reused") or 0) > 0),
974            "reused_tokens": totals.get("reused", 0), "prompt_tokens": totals.get("prompt_tokens", 0),
975            "last_reused": last.get("reused") if last else None,
976            "last_prompt": last.get("prompt_tokens") if last else None}
977
978
979_BTRACE = bool(os.environ.get("STRATA_BATCH_TRACE"))
980
981
982def btrace(*a):
983    if _BTRACE:
984        print("[batch-trace]", threading.get_ident() % 10000, *a, file=sys.stderr, flush=True)
985
986
987EOS_IDS = {248044, 248046}   # <|endoftext|>, <|im_end|>: the engine's default --eos-ids
988
989
990# The engine's own words for a verifier that cannot go on (its GPU waits were released, or an earlier window never
991# finished, #267): the process may stay alive and even print DONE, but it must not take another request.
992FATAL_PREFIXES = ("ERR verify: timed out at layer ", "ERR verify batch: timed out at layer ",
993                  "ERR verify: an earlier window never finished", "ERR verify batch: an earlier window never finished")
994
995
996def parse_engine_stage_line(line: str) -> list[dict] | None:
997    """Accept only the engine's final, contiguous stage plan (inclusive layer ends)."""
998    prefix = "strata serve: layer split: layers "
999    suffix = ", one hand-off per window"
1000    if not line.startswith(prefix) or not line.rstrip("\r\n").endswith(suffix):
1001        return None
1002    body = line.rstrip("\r\n")[len(prefix):-len(suffix)]
1003    parts = body.split(", ")
1004    if not 2 <= len(parts) <= 16:
1005        return None
1006    stages, next_layer = [], 0
1007    for i, part in enumerate(parts):
1008        match = re.fullmatch(r"([0-9]{1,5})-([0-9]{1,5}) \(CUDA([0-9]{1,2})\)", part)
1009        if match is None:
1010            return None
1011        first, last, ordinal = map(int, match.groups())
1012        if first != next_layer or last < first or last > 65535 or ordinal > 15:
1013            return None
1014        stages.append({"stage": i, "layer_start": first, "layer_end": last,
1015                       "engine_ordinal": ordinal})
1016        next_layer = last + 1
1017    return stages
1018
1019
1020def read_engine_stage_log(path: str | None, start: int, limit: int = 2 << 20) -> list[dict]:
1021    """Read this engine start only; oversized/unavailable logs leave placement unknown."""
1022    if not path or start < 0:
1023        return []
1024    try:
1025        with open(path, "rb") as source:
1026            source.seek(start)
1027            data = source.read(limit + 1)
1028    except OSError:
1029        return []
1030    if len(data) > limit:
1031        return []
1032    for line in reversed(data.decode("utf-8", errors="replace").splitlines()):
1033        stages = parse_engine_stage_line(line)
1034        if stages is not None:
1035            return stages
1036    return []
1037
1038
1039def visible_device_order(env: dict | None, backend: str | None) -> list[int]:
1040    """Map engine ordinals to OS GPU indices only when the visibility list is unambiguous."""
1041    if backend not in (None, "cuda", "hip"):
1042        return []
1043    if backend != "hip" and (env or {}).get("CUDA_DEVICE_ORDER") != "PCI_BUS_ID":
1044        return []
1045    name = "HIP_VISIBLE_DEVICES" if backend == "hip" else "CUDA_VISIBLE_DEVICES"
1046    value = (env or {}).get(name)
1047    if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,5}(?:,[0-9]{1,5}){0,15}", value):
1048        return []
1049    devices = [int(part) for part in value.split(",")]
1050    return devices if all(0 <= device <= 65535 for device in devices) and len(set(devices)) == len(devices) else []
1051
1052
1053def configure_batch_telemetry_env(env: dict, cfg: dict, override: bool | None) -> None:
1054    """Only an explicit setting changes the inherited opt-in engine environment."""
1055    choice = override if override is not None else cfg.get("batch_telemetry")
1056    if choice is True:
1057        env["STRATA_BATCH_TELEMETRY"] = "1"
1058    elif choice is False:
1059        env.pop("STRATA_BATCH_TELEMETRY", None)
1060
1061
1062def parse_batch_window_sample(line: str) -> dict | None:
1063    """Read an opt-in engine BSTAT sample; rows are verifier work, not emitted tokens."""
1064    if len(line) > 80:
1065        return None
1066    match = re.fullmatch(r"BSTAT ([1-9][0-9]{0,8}) ([1-9][0-9]{0,9}) "
1067                         r"([1-9][0-9]{0,9}) ([1-9][0-9]{0,9})\r?\n?", line)
1068    if match is None:
1069        return None
1070    windows, rows, active, elapsed_ms = map(int, match.groups())
1071    if rows > windows * 8 or active > rows or elapsed_ms > 86_400_000:
1072        return None
1073    return {"windows": windows, "processed_rows": rows, "active_rows": active,
1074            "elapsed_ms": elapsed_ms}
1075
1076
1077def parse_stage_in_flight_sample(line: str) -> dict | None:
1078    """Read bounded PSTAT host scheduling spans; these are not GPU utilization."""
1079    if len(line) > 256 or re.fullmatch(
1080            r"PSTAT (?:[2-9]|1[0-6]) [1-9][0-9]{0,10}(?: (?:0|[1-9][0-9]{0,10})){2,16}\r?\n?", line) is None:
1081        return None
1082    parts = line.strip().split(" ")
1083    stages, elapsed_us = int(parts[1]), int(parts[2])
1084    in_flight_us = [int(value) for value in parts[3:]]
1085    if len(in_flight_us) != stages or elapsed_us > 86_400_000_000 or \
1086            any(value > elapsed_us for value in in_flight_us):
1087        return None
1088    return {"elapsed_us": elapsed_us, "in_flight_us": in_flight_us}
1089
1090
1091class _RequestOwned:
1092    """#4451: a per-request control field of a --batch engine.  With batch slots several requests run on their own
1093    threads, and the control lines serve one at a time; a field every request writes (`_ctl_mode`, `_ctl_result`,
1094    `_yielded`, `_last_done`, `_ctl_erred`) must not be seen by another request that gets the lines next.  So each
1095    thread has its own copy; one request at a time, it is the one attribute as before."""
1096
1097    def __init__(self, default=None):
1098        self.default = default
1099
1100    def __set_name__(self, owner, name):
1101        self.name = name
1102
1103    def _store(self, obj):
1104        d = obj.__dict__
1105        if d.get("batch"):
1106            return d.setdefault("_own_tl", threading.local()).__dict__
1107        return d.setdefault("_own_plain", {})
1108
1109    def __get__(self, obj, owner=None):
1110        if obj is None:
1111            return self
1112        return self._store(obj).get(self.name, self.default)
1113
1114    def __set__(self, obj, value):
1115        self._store(obj)[self.name] = value
1116
1117
1118class StrataEngine:
1119    """The resident engine: `strata --serve` reads `GEN <max_new> <ids>` lines and streams `T <id>` lines, then
1120    `DONE ...`.  Requests are serialized by the service's FIFO, so one pipe is enough.
1121
1122    Per-request sampling rides the same line as engine-side keys between max_new and the ids
1123    (`temperature=F top_p=F top_k=N seed=N`, the engine's own spelling).  An absent temperature keeps the
1124    engine's default, which is greedy; `temperature=0` means the same thing, so it is not forwarded.
1125    """
1126    silence_s = ENGINE_SILENCE_S         # #481: main() sets the config's engine_silence_s (survives restart())
1127    silent_note = None                   # #481: why the server ended a silent engine (death_note says it)
1128    gpu_busy = None                      # #1317: () -> bool, "the GPU is working" (the telemetry's reading); a GPU at work is not frozen
1129    last_err = None                      # #997: an ERR that was its last stdout line (death_note says it)
1130    batch = 0                            # --batch: the engine's batch slots (0: one request at a time)
1131    _ctl_mode = _RequestOwned()          # the request that has the control lines: solo / batch (see _RequestOwned)
1132    _ctl_result = _RequestOwned()
1133    _yielded = _RequestOwned()
1134    _last_done = _RequestOwned()
1135    _ctl_erred = _RequestOwned(False)
1136    _ctl_held = _RequestOwned(False)     # this thread already holds the control lines (Service.vram takes them itself)
1137    CONTROL_WAIT_S = 300.0               # how long vram() / session_file() wait for the control lines of a batch engine
1138    DRAIN_TIMEOUT_S = 300.0              # how long an interrupted request waits, with no line from its engine, for DONE / BADM
1139    QUARANTINE_S = 600.0                 # ... and how long a slot or the control lines stay held after that with no line
1140    multi = 0                            # DeepSeek --parallel (READY ... multi=N): conversations the engine holds at once (batch = N too)
1141
1142    # `last`: the figures of the engine's last DONE line.  With batch slots several requests run at once, each on its
1143    # own thread, so each one reads its own request's figures (Service.run records them); one at a time, the one dict.
1144    @property
1145    def last(self):
1146        if self.batch:
1147            tl = self.__dict__.setdefault("_tl", threading.local())
1148            if not hasattr(tl, "last"):
1149                tl.last = {}
1150            return tl.last
1151        return self.__dict__.get("_last", {})
1152
1153    @last.setter
1154    def last(self, value):
1155        self.__dict__["_last"] = value
1156        if self.batch:
1157            tl = self.__dict__.setdefault("_tl", threading.local())
1158            tl.last = value
1159
1160    def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,
1161                 env: dict | None = None, lazy: bool = False, cpus: list[int] | None = None, _attempt: int = 0,
1162                 retry_args: list[str] | None = None, retry_vram_args: list[str] | None = None):
1163        # retry_args: the arguments to start again with, once, when this start ends before the engine is ready (an Auto start that picked DFlash2: mtp_retry_args)
1164        # retry_vram_args: the same start with no drafter (nodraft_retry_args), used instead when the engine ended because a card ran out of memory: swapping DFlash2 for
1165        # the MTP takes MORE memory from a card that is already short, so that direction is never taken then
1166        self.spawn = (exe, list(args), cwd, log, env, False, cpus)   # to start it again after it died (issue #27)
1167        # the all-cards split engine (sFNX, strata-split-N[-arch]): its GEN parser accepts fewer keys than Strata's engine (tests/split/test_split_gen_keys.py pins them)
1168        self.split_engine = os.path.basename(str(exe)).startswith("strata-split")
1169        self.session_save_reclaim = '--session-save-reclaim' in args
1170        paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}
1171        self.model_path = paths.get("--native") or paths.get("--pack", "pack/full")
1172        self.log_path = log
1173        self.proc, self.pump, self.log = None, None, None
1174        self.ended, self.unloaded = True, True
1175        self.max_context = int(args[args.index("--max-context") + 1]) if "--max-context" in args else 4096
1176        self.can_stop = False            # the engine honours a STOP line mid-request (READY <ctx> stop)
1177        self.can_hold = False            # the engine takes GEN hold=N:ID (READY <ctx> ... hold)
1178        self.can_hold_batch = False      # ... and its --batch slots end at the hold too, BDONE hold (READY ... holdb)
1179        self.last = {}
1180        self.info = {}                   # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)
1181        self.terminal_stages: list[dict] = []  # final layer ranges from this engine start's bounded stderr log
1182        self.terminal_batch_sample: dict | None = None
1183        self.terminal_stage_sample: dict | None = None
1184        self.prefill_tok_s_mean = None
1185        self.progress = None             # (read, total) prompt tokens while a prompt is read, from PP lines
1186        self.progress_ms = 0             # PP's own milliseconds since the prompt started (its third field)
1187        self.reused = 0                  # RESUME: prompt tokens not read again (a client takes them out of the work)
1188        self.silent_note = None
1189        self.last_err = None
1190        try:                            # a ready-made engine's BUILD.json says its version
1191            self.info["version"] = json.loads((Path(exe).parent / "BUILD.json").read_text()).get("version")
1192        except (OSError, ValueError):
1193            self.info["version"] = None
1194        if lazy:
1195            return
1196        self.unloaded = False            # `ended` stays True until READY (below): not alive while starting (#344)
1197        self.log = open(log, "a", encoding="utf-8") if log else subprocess.DEVNULL
1198        loading = threading.Event()                     # set once READY: the narrator below stops
1199        log_start = os.path.getsize(log) if log else 0  # where this start's lines begin (start_failure_hint)
1200        self.log_start = log_start                      # #596: the Monitor's conversation cache reads from here
1201        if log:
1202            threading.Thread(target=narrate_start, args=(log, os.path.getsize(log), args, loading),
1203                             daemon=True).start()
1204            # once per log: the follower keeps reading the same (appended) log across restarts and reloads
1205            if os.environ.get("STRATA_REQUEST_LINES") and os.path.abspath(log) not in _echoing:
1206                _echoing.add(os.path.abspath(log))
1207                threading.Thread(target=echo_requests, args=(log, os.path.getsize(log)), daemon=True).start()
1208        if log:                                          # #779: when an engine started (a crash report has the time)
1209            try:
1210                self.log.write(f"[strata] {time.strftime('%Y-%m-%d %H:%M:%S')} engine started: {exe} --serve "
1211                               f"{' '.join(args)}\n")
1212                self.log.flush()
1213            except OSError:
1214                pass
1215        self.max_context = 0                             # before the new process is visible: never its predecessor's
1216        pin = {}
1217        if cpus and hasattr(os, "sched_setaffinity"):    # replicas: this engine's own physical cores (serve/replicas.py)
1218            pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus)
1219        nice = engine_nice(env)                          # Linux with built-in Radeon graphics: the desktop keeps its share of the CPU
1220        if nice:
1221            say_nice = pin.get("preexec_fn")
1222            pin["preexec_fn"] = lambda: (say_nice() if say_nice else None, os.nice(nice))[0]
1223            print(f"[strata] engine priority: nice +{nice} (this PC has built-in Radeon graphics that usually draw the desktop; "
1224                  "STRATA_ENGINE_NICE=0 turns it off)", flush=True)
1225        end_leftover_engines(exe)                        # one an earlier run lost still holds the GPU and the memory
1226        spawned_at = time.monotonic()
1227        try:
1228            self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE,
1229                              stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", errors="replace",
1230                              bufsize=1, env=env, **pin)    # (#5044: a byte that is not UTF-8 killed the reader thread)
1231        except OSError:                                  # nothing started: the narrator stops, the log handle goes back
1232            loading.set()
1233            if log:
1234                self.log.close()
1235            raise
1236        proc = self.proc                                 # THIS start's process: a close() from another thread may set self.proc to None meanwhile (#4792)
1237        # the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream
1238        # stays for _pump (one reader at a time)
1239        ready_q: queue.Queue = queue.Queue()
1240        threading.Thread(target=self._ready_pump, args=(self.proc, ready_q), daemon=True).start()
1241        ready_deadline = None if ENGINE_READY_S is None else time.monotonic() + ENGINE_READY_S
1242        timed_out = False
1243        while True:
1244            left = None if ready_deadline is None else ready_deadline - time.monotonic()
1245            if left is not None and left <= 0:
1246                timed_out = True
1247                break
1248            try:
1249                line = ready_q.get(timeout=left)
1250            except queue.Empty:
1251                continue
1252            if line is None:
1253                break
1254            if line.startswith("INFO "):
1255                for kv in line.split()[1:]:
1256                    k, _, v = kv.partition("=")
1257                    self.info[k] = int(v) if v.lstrip("-").isdigit() else v
1258            if line.startswith("READY"):
1259                f = line.split()
1260                self.max_context = int(f[1])
1261                self.can_stop = "stop" in f[2:]
1262                self.can_hold = "hold" in f[2:]
1263                self.can_hold_batch = "holdb" in f[2:]
1264                self.multi = next((int(x[6:]) for x in f[2:] if x.startswith("multi=") and x[6:].isdigit()), 0)
1265                break
1266        loading.set()
1267        if self.max_context <= 0:
1268            if timed_out:                               # still loading, or hung: end it, so the turn is not held for good
1269                try:
1270                    proc.kill()
1271                except OSError:
1272                    pass
1273            try:                                        # its pipes and our handle on its log (the log stays)
1274                proc.wait(timeout=5)
1275                proc.stdin.close()
1276                proc.stdout.close()
1277                if log:
1278                    self.log.close()
1279            except (OSError, subprocess.TimeoutExpired):
1280                pass
1281            if not timed_out and _attempt < START_RETRIES and \
1282                    transient_start_failure(log, log_start, time.monotonic() - spawned_at, proc.returncode):
1283                wait_s = 2.0 * (2 ** _attempt)              # 2, 4, 8 s: the previous process's GPU queues go away
1284                exit_words = engine_exit_words(proc.returncode)
1285                if start_log_marks(log, log_start):         # the runtime said so itself (hsa_exception ...)
1286                    print(f"[strata] the engine stopped while the GPU runtime was starting (most often right after "
1287                          f"another engine exited, whose GPU queues were still being released"
1288                          f"{'; ' + exit_words if exit_words else ''}): starting it again in {wait_s:.0f} s "
1289                          f"(try {_attempt + 2} of {START_RETRIES + 1})", flush=True)
1290                else:                                       # an exit with nothing in the log: say only what is known
1291                    print(f"[strata] the engine exited before it wrote anything to its log"
1292                          f"{' (' + exit_words + ')' if exit_words else ''}; it may be a GPU runtime that was not "
1293                          f"ready yet: starting it again in {wait_s:.0f} s (try {_attempt + 2} of {START_RETRIES + 1})",
1294                          flush=True)
1295                time.sleep(wait_s)
1296                StrataEngine.__init__(self, exe, args, cwd, log, env, lazy, cpus, _attempt + 1, retry_args, retry_vram_args)
1297                return
1298            short_reason = None if timed_out else vram_fit.engine_stop_reason(start_log_text(log, log_start).splitlines())
1299            if short_reason and retry_vram_args and retry_vram_args != list(args):
1300                # a card ran out of memory (the engine's own reason is in its log): one more start with no drafter, in one quiet line
1301                print(f"[strata] {drafting.line('off', drafting.SHORT_OF_VRAM)}: starting again without a drafter ({short_reason})", flush=True)
1302                try:
1303                    with open(log, "a", encoding="utf-8") as handle:
1304                        handle.write(f"[strata] {time.strftime('%Y-%m-%d %H:%M:%S')} the engine ended before it was ready because a card was short of memory "
1305                                     f"(exit code {proc.returncode}); starting it again without a drafter\n")
1306                except (OSError, TypeError):
1307                    pass
1308                drafting.remember_note(drafting.SHORT_OF_VRAM)
1309                StrataEngine.__init__(self, exe, retry_vram_args, cwd, log, env, lazy, cpus, 0, None, None)
1310                return
1311            if not timed_out and not short_reason and retry_args and retry_args != list(args):
1312                # Auto picked DFlash2 and the engine ended before it was ready (an engine that does not take one of its flags, a drafter file it cannot read...):
1313                # one more start with the MTP, said in one quiet line. The person named DFlash2 themselves: no retry, the start fails with its reason below.
1314                print(f"[strata] {drafting.line('mtp', drafting.DIDNT_START)}: starting again with the MTP", flush=True)
1315                try:
1316                    with open(log, "a", encoding="utf-8") as handle:
1317                        handle.write(f"[strata] {time.strftime('%Y-%m-%d %H:%M:%S')} the engine ended before it was ready with the DFlash2 drafter "
1318                                     f"(exit code {proc.returncode}); starting it again with the MTP\n")
1319                except (OSError, TypeError):
1320                    pass
1321                drafting.remember_note(drafting.DIDNT_START)
1322                StrataEngine.__init__(self, exe, retry_args, cwd, log, env, lazy, cpus, 0, None, None)
1323                return
1324            why = (f"the engine did not report READY within {ENGINE_READY_S:.0f} s" if timed_out else
1325                   "the engine exited before it was ready")
1326            # EngineDied, not bare RuntimeError: a request waiting on this load must end with a 503
1327            # through the request path's handler - a RuntimeError there left the turn with no answer (#1527)
1328            note = "" if timed_out else start_exit_note(proc.returncode, exe)
1329            tail = start_log_tail(log, log_start)
1330            lines = [x for x in tail.split("\n")[2:] if x.strip()]
1331            if tail and lines and all(x.strip().startswith("[strata]") for x in lines):
1332                tail += "\n  (those are the launcher's own lines: the engine itself wrote nothing)"
1333            raise EngineDied(why + (f" (see {log})" if log else "") + note +
1334                             start_failure_hint(log, log_start) + tail)
1335        self.known_ctx = self.max_context   # survives a failed restart: requests keep their limit and restart it
1336        # (from PR #41, midhatn) a locally built engine can sit next to another release's BUILD.json: engines that
1337        # report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones
1338        if self.info.get("engine"):
1339            self.info["version"] = str(self.info["engine"])
1340        self.terminal_stages = read_engine_stage_log(log, log_start) if log else []
1341        try:                                            # which drafter runs, and in plain words why not the one that was asked for
1342            self.info.update(drafting.engine_info(args, start_log_text(log, log_start), drafting.take_note()))
1343        except Exception:                               # noqa: BLE001 - a note must never stop a start
1344            pass
1345        self.ended = False                              # READY: alive from here (restart() set it True, #344)
1346        # the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks)
1347        self.gen = self.__dict__.get("gen", 0) + 1      # which engine process this is (a request notes its own); first, so
1348        #                                                 a request that sees the new number sees the new queues (#4451)
1349        self.lines: queue.Queue = queue.Queue()
1350        # --batch: concurrent requests in the engine's batch slots (see generate_batched).  The engine says how many
1351        # it runs (INFO batch_slots=N: it may have fewer than asked, or none, when they do not fit)
1352        asked = next((int(args[args.index(k) + 1]) for k in ("--batch", "--slots", "--parallel") if k in args), 0)
1353        self.batch = int(self.info.get("batch_slots") or 0)
1354        if self.multi:                                  # DeepSeek --parallel: several requests at once, in its own protocol
1355            self.batch = self.multi                     # (the server's parallel paths key on it: no FIFO, a request's own figures)
1356        if asked and self.batch != asked:
1357            print(f"[strata] parallel requests: {asked} asked, the engine runs {self.batch or 'one at a time'} "
1358                  "(its log says why)", flush=True)
1359        _bg = args[args.index("--batch-groups") + 1] if "--batch-groups" in args else "default"
1360        # no `--batch-groups` (the default on a layer split) or `auto`: the engine picks the groups and says so
1361        # (INFO batch_groups=G); a number is the group count asked for (1 = off)
1362        groups = int(self.info.get("batch_groups") or 1) if _bg in ("auto", "default") else int(_bg)
1363        groups = groups if self.batch and groups > 0 and self.batch % groups == 0 else 1
1364        gs = self.batch // groups if self.batch else 0
1365        # slots in the order that spreads requests over the pipeline's groups first: 0, gs, 2gs, .., 1, gs+1, ..
1366        self.slot_order = [g * gs + t for t in range(gs) for g in range(groups)]
1367        self.slot_group = [b // gs if gs else 0 for b in range(self.batch)]   # each slot's pipeline group
1368        self.slot_groups = groups
1369        # pipelined groups (the engine says how many it runs: INFO batch_groups; older engines: the args).  A pipelined
1370        # group's window spans its slots up to its last busy one, and the engine keeps no pipelined slot as a
1371        # conversation cache - see pick_slot
1372        groups_run = int(self.info.get("batch_groups") or groups)
1373        self.slot_gs = gs if groups > 1 and groups_run > 1 else 0
1374        self.slot_q = [queue.Queue() for _ in range(self.batch)]
1375        self.slot_busy = [False] * self.batch
1376        # #1603: who owns a busy flag.  slot_claims: slots a request of this server picked or reserved and has not
1377        # given back; slot_releasing: slots handed to the background BDONE wait.  A busy slot in neither has no owner
1378        # (its flag leaked) and would keep every later request waiting for a slot that nothing will free.
1379        self.slot_claims: set[int] = set()
1380        self.slot_releasing: set[int] = set()
1381        self._orphan_seen: dict[int, float] = {}
1382        # what each slot's sessions hold (prompt + every token a window fed), so a conversation's next turn goes to
1383        # the slot that has its start (the engine checks it again); when the slot was last used
1384        self.slot_held: list[list[int]] = [[] for _ in range(self.batch)]
1385        self.slot_used = [0.0] * self.batch
1386        self.slot_live: list[dict | None] = [None] * self.batch   # /metrics: the request in each slot
1387        # #1012: the admission state belongs to the server, not to one engine process.  restart() runs this again
1388        # while requests still wait on it (they hold these very objects), so it is made once and kept: new ones
1389        # would leave the waiters on a lock and a condition nobody notifies, with their counts missing from the
1390        # new lists.
1391        if "slot_cv" not in self.__dict__:
1392            self.slot_cv = threading.Condition()
1393            self.waiting = 0                            # requests waiting for the control lines (ctl)
1394            self.admitting = 0                          # #1603: ... and those that gave the lines back to wait for a slot
1395            self.par_counters = {"queued": 0, "queue_wait_s": 0.0}
1396            self.wait_lens: list[list[int]] = []        # ... their prompt lengths (a long read gives way to short ones)
1397            self.arrivals = collections.deque(maxlen=64)   # monotonic times of the last requests that came for the control lines (STRATA_COALESCE_*)
1398            self.ctl_epoch = 0                          # how often the control lines were taken
1399            self.ctl = threading.Lock()                 # one admission or solo request on the control lines at a time
1400        if "rid_lock" not in self.__dict__:
1401            self.rid_lock = threading.Lock()
1402            self.rid_n = 0                              # --parallel requests' ids (rid=): never reused, a restart goes on from here
1403        self.rid_q: dict[int, queue.Queue] = {}         # this process's: rid -> that request's lines (T / PP / DONE / ERR, rid taken out)
1404        self.multi_stat = ""                            # the engine's last STAT line over everything it wrote
1405        self._ctl_erred = False                         # #1059: the control lines ended on an ERR
1406        self._yielded = None                            # (slot, tokens read): the last request on them gave way
1407        self.wlock = threading.Lock()                   # stdin writes from several request threads
1408        self.pump = threading.Thread(target=self._pump, daemon=True)
1409        self.pump.start()
1410
1411    def _pump(self):
1412        proc, lines = self.proc, self.lines             # this process's: a restart replaces both (#344)
1413        slot_q = self.slot_q
1414        slot_busy = self.slot_busy                      # this process's (a restart makes new ones)
1415        rid_q = self.rid_q
1416        multi = self.multi
1417        line = None
1418        for line in proc.stdout:
1419            # checked before batch routing: a fatal line is never a slot's own
1420            if line.startswith(FATAL_PREFIXES):
1421                # release_gpu_waits invalidates the verifier, even if the native
1422                # process stays alive and prints DONE afterwards.
1423                if self.proc is proc:
1424                    self.silent_note = "Unrecoverable native verification failure: " + line[4:].strip()
1425                    self.ended = True
1426                try:
1427                    proc.terminate()
1428                except OSError:
1429                    pass
1430                break                           # publish EOF, never the trailing DONE
1431            if line.startswith("BSTAT"):
1432                sample = parse_batch_window_sample(line)
1433                if sample is not None and self.proc is proc:
1434                    self.terminal_batch_sample = {**sample, "observed_monotonic": time.monotonic()}
1435                continue                        # control telemetry never enters a request's token stream
1436            if line.startswith("PSTAT"):
1437                sample = parse_stage_in_flight_sample(line)
1438                if sample is not None and self.proc is proc:
1439                    self.terminal_stage_sample = {**sample, "observed_monotonic": time.monotonic()}
1440                continue
1441            if multi:                                   # DeepSeek --parallel: `T <rid> <id>`, `PP <rid> ...`, `DONE <rid> ...`, `ERR <rid> ...`
1442                head, _, rest = line.partition(" ")
1443                if head in ("T", "PP", "DONE", "ERR") and rest[:1].isdigit():
1444                    rid_s, _, tail = rest.partition(" ")
1445                    rq = rid_q.get(int(rid_s))
1446                    if rq is not None:                  # (a request that has ended: its late lines go nowhere)
1447                        rq.put(head + (" " + tail if tail else "\n"))
1448                    continue
1449                if head == "STAT":                      # over everything the engine wrote, not one request's
1450                    self.multi_stat = line
1451                    continue
1452            if line.startswith(("BT ", "BDONE ")) and slot_q:   # --batch: a batch slot's own lines
1453                try:
1454                    b = int(line.split()[1])
1455                    if 0 <= b < len(slot_q) and not slot_busy[b]:
1456                        # #4451: a frame for a slot that no request has claimed belongs to a request that is over (its
1457                        # slot was given back too early, or never claimed): the next request on the slot must not read it
1458                        self.stale_frames = getattr(self, "stale_frames", 0) + 1
1459                        btrace("stale frame dropped", line.strip()[:60])
1460                        continue
1461                    slot_q[b].put(line)
1462                    continue
1463                except (IndexError, ValueError):
1464                    pass
1465            lines.put(line)
1466        if self.proc is proc:                           # a killed engine's pump must not mark its successor dead
1467            self.ended = True                           # its output closed: it is gone, even before the OS says so
1468            if line and line.startswith("ERR"):         # #997 #890: why it exited, though no request may read it
1469                self.last_err = line[4:].strip()        # (a failed batch window: every request reads its slot)
1470        lines.put(None)
1471        for q in slot_q:
1472            q.put(None)
1473        for q in list(rid_q.values()):
1474            q.put(None)
1475
1476    def death_note(self) -> str:
1477        """Why the engine most likely ended, from the end of its log: its own watchdog (issue #29), else RAM."""
1478        if getattr(self, "silent_note", None):          # #481: the server ended it, not the OS or the engine itself
1479            return self.silent_note
1480        tail = wide = ""
1481        try:
1482            with open(self.log_path, "rb") as f:
1483                f.seek(0, 2)
1484                f.seek(max(0, f.tell() - 262144))
1485                wide = f.read().decode("utf-8", "replace")
1486            tail = wide[-4096:]
1487        except (OSError, TypeError):
1488            pass
1489        # #1705: STRATA_VERIFY_TRACE dumps are ~30 KB and push the watchdog's line out of a 4 KB tail
1490        for line in reversed(wide.splitlines()):
1491            if "issue #29" in line:
1492                return ("The engine stopped itself because it had stopped making progress - a hang it caught. Its log "
1493                        "line: " + line.strip() + " - please report it at github.com/Niko1221/Strata/issues.")
1494        if (self.last_err or "").startswith("fatal GPU error"):    # #4350: the engine ended itself; the next request starts it again
1495            return ("The graphics card reported a fatal error (" + self.last_err[len("fatal GPU error:"):].strip()[:160] + "), so the engine "
1496                    "ended. The next request starts it again. If this repeats, please report it at github.com/Niko1221/Strata/issues "
1497                    "with the log.")
1498        proc = self.proc                                 # None while a restart has not started the next one yet
1499        rc = proc.poll() if proc is not None else None
1500        if rc is not None and rc >= 0 and self.last_err:  # its own last words on stdout: they say why
1501            return (f"The engine exited (code {rc}) after it reported: {self.last_err} - please report it at "
1502                    "github.com/Niko1221/Strata/issues with the log.")
1503        last = next((x.strip() for x in reversed(tail.splitlines()) if x.strip().startswith(("strata", "ERR"))), "")
1504        if rc is not None and rc >= 0 and last:          # it ended by itself: its own last words say why (#215)
1505            return (f"The engine exited (code {rc}). Its last log line: {last} - if that does not explain it, please "
1506                    "report it at github.com/Niko1221/Strata/issues with the log.")
1507        rt_note = rttime_limit_note() if rc == -9 else ""
1508        if rt_note:                                       # #3238: the kernel killed it, but not for RAM
1509            return ("The engine was ended by signal 9. " + rt_note + " If dmesg (sudo dmesg | grep -i -E 'killed "
1510                    "process|out of memory') shows an out-of-memory kill instead, close other programs or use a smaller "
1511                    "model (Q2_0 / IQ2_XS).")
1512        return ("The usual cause is running out of RAM: Linux then ends the biggest program (check: sudo dmesg | "
1513                "grep -i -E 'killed process|out of memory'); Windows slows down instead. Close other programs or use a "
1514                "smaller model (Q2_0 / IQ2_XS).")
1515
1516    def alive(self) -> bool:
1517        proc = self.proc                                 # read once: restart() / close() may set it to None meanwhile
1518        return proc is not None and not getattr(self, "ended", False) and proc.poll() is None
1519
1520    def exit_code(self):
1521        if self.proc is None:
1522            return None
1523        try:
1524            return self.proc.wait(timeout=5)
1525        except subprocess.TimeoutExpired:
1526            return None
1527
1528    def unload(self):
1529        """Release GPU/RAM between requests, retaining the spawn config for automatic reloading."""
1530        self.close()
1531        self.unloaded = True
1532
1533    RESTART_RETRY_S = 15.0   # between the tries of restart(): a dying engine's VRAM may take a while to come back
1534
1535    @staticmethod
1536    def _ready_pump(proc, out: queue.Queue) -> None:
1537        """The engine's first lines up to READY, for a read that can time out; None when its output closed first."""
1538        done = False
1539        try:
1540            for line in proc.stdout:
1541                out.put(line)
1542                if line.startswith("READY"):
1543                    done = True
1544                    return
1545        except (OSError, ValueError):                   # the pipe closed under us (the engine was killed)
1546            pass
1547        finally:
1548            if not done:
1549                out.put(None)
1550
1551    def restart(self, tries: int = 3):
1552        """Start the engine again (the same command) after it died; the new process has its own line queue.
1553        close() ends and waits for the old process first (EngineStuck when it cannot be ended).  A start that still
1554        exits before READY - a dead engine's VRAM can take a while to come back, notably on ROCm - is retried
1555        (PR #637)."""
1556        info = dict(self.info)
1557        self.starting = True                     # prepare() answers 503 "starting" meanwhile (#344)
1558        try:
1559            self.close()
1560            for i in range(tries):
1561                # #344: not alive until READY - __init__ sets max_context to 0 and blocks until the engine says
1562                # READY, and a request that saw alive() in that window skipped load() and failed with "context
1563                # (0)".  __init__ clears `ended` itself once READY (before its pump thread can set it again).
1564                self.ended = True
1565                try:
1566                    self.__init__(*self.spawn)
1567                    break
1568                except RuntimeError:
1569                    try:
1570                        self.proc.wait(timeout=60)
1571                    except (subprocess.TimeoutExpired, OSError):
1572                        pass
1573                    if i == tries - 1:
1574                        raise
1575                    print(f"[strata] the engine did not start (try {i + 1} of {tries}); again in "
1576                          f"{self.RESTART_RETRY_S:g} s", flush=True)
1577                    time.sleep(self.RESTART_RETRY_S)
1578        finally:
1579            self.starting = False
1580            # a lazy first start never reached the post-READY __init__ where slot_cv is made (#1527)
1581            if "slot_cv" in self.__dict__:
1582                with self.slot_cv:               # #1012: wake the requests that waited through it: they go on with the
1583                    self.slot_cv.notify_all()    # new engine, or (it did not start) end with a clean EngineDied
1584        self.info = {**info, **self.info}
1585
1586    def _parse_done(self, line):
1587        f = line.split()
1588        self.last = {"generated": int(f[1]), "prompt_tokens": int(f[2]), "prompt_ms": float(f[3]),
1589                     "decode_ms": float(f[4]), "finish": f[5]}
1590        if len(f) >= 9:                                   # the conversation cache's fields (engine 0.1.3+)
1591            self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8]))
1592        if len(f) >= 11:                                  # decode hit rate fields
1593            self.last.update(hits=int(f[9]), lookups=int(f[10]))
1594        if len(f) >= 14:                                  # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB
1595            self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13]))
1596        if len(f) >= 15:                                  # #471 (engine 0.1.36+): the prompt tokens actually read
1597            self.last.update(prompt_read=int(f[14]))
1598        if len(f) >= 16:                                  # #588 (engine 0.1.39+): routed experts read over PCIe
1599            self.last.update(offloaded=int(f[15]))
1600        for tok in f[16:]:                                # key=value fields after the positional ones (the prompt's
1601            key, eq, value = tok.partition("=")           # first chunk and its streamed expert blobs)
1602            if eq and key in ("chunk", "experts_streamed", "cached", "scr", "prefilled"):   # (SCR: cached/scr/prefilled)
1603                try:
1604                    self.last[key] = int(value)
1605                except ValueError:
1606                    pass
1607
1608    @contextlib.contextmanager
1609    def _exclusive_control(self):
1610        """#4451 (same class): on a batch engine the control lines carry one exchange at a time, and every request takes
1611        them (`ctl`) before it sends or reads anything there.  VRAM and SAVE / RESTORE read the same lines for their
1612        answer; run beside an admission they took its PP / T / BADM lines, and the admission its answer.  They take the
1613        lines like a request does.  One request at a time: nothing to take."""
1614        ctl = self.__dict__.get("ctl")
1615        if not self.batch or ctl is None or self._ctl_held:
1616            yield
1617            return
1618        if not ctl.acquire(timeout=self.CONTROL_WAIT_S):
1619            raise ValueError("a request is still running; try again when it has finished")
1620        try:
1621            yield
1622        finally:
1623            ctl.release()
1624
1625    def vram(self, reserve_mib: int | None, timeout: float = 120.0) -> dict:
1626        with self._exclusive_control():
1627            return self._vram(reserve_mib, timeout)
1628
1629    def _vram(self, reserve_mib: int | None, timeout: float = 120.0) -> dict:
1630        """#533: `VRAM <reserve_mib>` between requests (the caller holds the service's FIFO): the engine shrinks its
1631        expert cache until that much VRAM is free, or grows it back when more is free; None: back to the reserve it
1632        started with.  -> the engine's figures (expert_slots, expert_cache_mib, vram_free_mib, ...); raises ValueError
1633        with the engine's reason (e.g. it was not started with --vram-elastic), EngineDied when it ended."""
1634        if not self.alive():
1635            raise EngineDied("the engine is not running")
1636        self.proc.stdin.write("VRAM" + ("" if reserve_mib is None else f" {int(reserve_mib)}") + "\n")
1637        self.proc.stdin.flush()
1638        deadline = time.time() + timeout
1639        while True:
1640            try:
1641                line = self.lines.get(timeout=max(0.1, deadline - time.time()))
1642            except queue.Empty:
1643                raise EngineDied("the engine did not answer the VRAM command") from None
1644            if line is None:
1645                raise EngineDied("the engine ended")
1646            line = line.strip()
1647            if line.startswith("ERR"):
1648                raise ValueError(line[4:].strip() or "the engine refused the VRAM command")
1649            if line.startswith("VRAM "):
1650                out = {}
1651                for kv in line.split()[1:]:
1652                    k, _, v = kv.partition("=")
1653                    out[k] = int(v) if v.lstrip("-").isdigit() else v
1654                self.info.update({k: out[k] for k in ("expert_slots", "vram_free_mib") if k in out})
1655                self.info["vram"] = out
1656                return out
1657            if time.time() > deadline:
1658                raise EngineDied("the engine did not answer the VRAM command")
1659
1660    def pen_from_key(self, orig_len: int, prompt_len: int) -> str:
1661        """` pen_from=N` for a leg that continues a request (prompt + what it generated): where the reply began, Strata's penalty window start. The all-cards split engine
1662        (sFNX) counts its penalty window over the last penalty_last_n tokens of the whole context, so the continued prompt gives it the same window and the engine refuses the
1663        key (GEN: unknown key pen_from): it is not sent."""
1664        if self.split_engine or prompt_len <= orig_len:
1665            return ""
1666        return f" pen_from={orig_len - 1}"
1667
1668    @staticmethod
1669    def sampling_keys(sampling: dict) -> str:
1670        keys = ""
1671        t = sampling.get("temperature")
1672        if isinstance(t, (int, float)) and float(t) > 0.0:
1673            keys += f" temperature={float(t)!r}"
1674        tp = sampling.get("top_p")
1675        if isinstance(tp, (int, float)) and float(tp) < 1.0:
1676            keys += f" top_p={float(tp)!r}"
1677        tk = sampling.get("top_k")
1678        if isinstance(tk, int) and not isinstance(tk, bool) and tk >= 0:
1679            # the engine's sampled path keeps at most 64 candidates: 0 ("off") and wider lists get all 64
1680            keys += f" top_k={tk if 1 <= tk <= 64 else 64}"
1681        mp = sampling.get("min_p")
1682        if isinstance(mp, (int, float)) and 0.0 < float(mp) <= 1.0:
1683            keys += f" min_p={float(mp)!r}"
1684        rp = sampling.get("repetition_penalty")
1685        rp_on = isinstance(rp, (int, float)) and float(rp) != 1.0
1686        pf = sampling.get("frequency_penalty")
1687        pf_on = isinstance(pf, (int, float)) and float(pf) != 0.0
1688        pp = sampling.get("presence_penalty")
1689        pp_on = isinstance(pp, (int, float)) and float(pp) != 0.0
1690        if rp_on:
1691            keys += f" penalty_repeat={float(rp)!r}"
1692        if pf_on:
1693            keys += f" penalty_freq={float(pf)!r}"
1694        if pp_on:
1695            keys += f" penalty_present={float(pp)!r}"
1696        if rp_on or pf_on or pp_on:
1697            # a penalty without a window counts over nothing: the engine's default is the last 64 tokens
1698            pln = sampling.get("penalty_last_n")
1699            if isinstance(pln, int) and not isinstance(pln, bool) and pln > 0:
1700                keys += f" penalty_last_n={pln}"
1701            else:
1702                keys += " penalty_last_n=64"
1703        seed = sampling.get("seed")
1704        if isinstance(seed, int) and seed > 0:
1705            keys += f" seed={seed}"
1706        # setup's calibration (tools/calibrate.py): engine settings for this request only, measured without a restart
1707        tune = sampling.get("strata_tune")
1708        if isinstance(tune, dict):
1709            for k in ("pcie_frac", "spec_min_p"):
1710                v = tune.get(k)
1711                if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 1.0:
1712                    keys += f" {k}={float(v)!r}"
1713            # a layer split's prompt chunks (--prefill-pipe): 0 off, 1 evened out, > 1 the rig's b/a in tokens
1714            v = tune.get("prefill_pipe")
1715            if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 <= float(v) <= 262144.0:
1716                keys += f" pipe={float(v)!r}"
1717            # --aux-cpus for this request: 1 puts the engine's threads that are neither pool workers nor the host on the
1718            # spare CPUs, 0 leaves them where they were created (true/false or 1/0; the engine started without a spare CPU
1719            # ignores a 1).  Anything else is not sent.
1720            ac = tune.get("aux_cpus")
1721            if isinstance(ac, bool) or (isinstance(ac, (int, float)) and ac in (0, 1)):
1722                keys += f" aux_cpus={int(ac)}"
1723        # the thinking budget's hold (HOLD_KEY): set by the server for an engine that says "hold", never by a client
1724        hold = sampling.get(HOLD_KEY)
1725        if (isinstance(hold, tuple) and len(hold) == 2 and all(isinstance(x, int) and not isinstance(x, bool) for x in hold)
1726                and hold[0] > 0 and hold[1] >= 0):
1727            keys += f" hold={hold[0]}:{hold[1]}"
1728        # "strata_checkpoint": false - a one-shot call (a classification, a probe) whose turn no later request
1729        # extends: no conversation checkpoint for it (#830).  It still reuses a cached prefix.  Absent = as before.
1730        if sampling.get("strata_checkpoint") is False:
1731            keys += " ckpt=0"
1732        # #2228: the pictures' keys (hex, in prompt order): the engine matches a picture by them, not by its embeddings
1733        ik = sampling.get("strata_img_keys")
1734        if isinstance(ik, list) and ik and all(isinstance(k, str) and k and all(c in "0123456789abcdef" for c in k)
1735                                               for k in ik):
1736            keys += " img_keys=" + ",".join(ik)
1737        # "strata_prefix" (resolved by Service.resolve_prefix to {"tokens": N}): the first N prompt tokens are a shared
1738        # prefix - the engine pins the checkpoint there.  Absent or unresolved = as before.
1739        prefix = sampling.get("strata_prefix")
1740        if isinstance(prefix, dict):
1741            pn = prefix.get("tokens")
1742            if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0:
1743                keys += f" pin={pn}"
1744        # restore points (Service.prepare puts them in `_restore`; only the DeepSeek engine gets them)
1745        keys += StrataEngine.restore_keys(sampling)
1746        # logprobs: the engine writes an `LP` line after each `T` line (an engine without them ignores
1747        # the key, so an older engine answers exactly as it did).  Absent = no LP lines at all.
1748        k = top_logprobs(sampling)
1749        if k is not None:
1750            keys += f" logprobs={k}"
1751            ids = allowed_ids(sampling)
1752            if ids:
1753                # only these ids are printed; the engine's comma-separated list, renormalised below
1754                keys += " allowed=" + ",".join(str(i) for i in ids)
1755        return keys + StrataEngine.projection_key(sampling) + bias_api.engine_key(sampling.get("logit_bias"))
1756
1757    @staticmethod
1758    def restore_keys(sampling: dict) -> str:
1759        """`marks=<pos>,...`, `tail=<pos>` and `shared=<pos>`: the DeepSeek engine's restore points for this prompt
1760        (Service.prepare puts them in `_restore` with STRATA_DS4_RESTORE_POINTS; no other engine gets them).  "" without:
1761        the line as before."""
1762        pts = sampling.get("_restore")
1763        if not isinstance(pts, dict):
1764            return ""
1765
1766        def pos(v):
1767            return isinstance(v, int) and not isinstance(v, bool) and v > 0
1768        marks = [p for p in pts.get("marks") or () if pos(p)]
1769        tail, shared = pts.get("tail"), pts.get("shared")
1770        return ((" marks=" + ",".join(str(p) for p in marks) if marks else "") +
1771                (f" tail={tail}" if pos(tail) else "") + (f" shared={shared}" if pos(shared) else ""))
1772
1773    @staticmethod
1774    def projection_key(sampling: dict) -> str:
1775        """`cvec=0|1`: the experimental-speed-projection control vector for this request, when the engine was
1776        started with one (--control-vector-scaled; an engine without one ignores the key).  Absent = on."""
1777        on = sampling.get("experimental_speed_projection")
1778        return f" cvec={int(on)}" if isinstance(on, bool) else ""
1779
1780    def _send(self, text: str):
1781        btrace("send>", text[:60])
1782        try:
1783            with self.wlock:
1784                self.proc.stdin.write(text + "\n")
1785                self.proc.stdin.flush()
1786        except (OSError, AttributeError):                # the pipe is gone (or a restart's close() took the process):
1787            raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None
1788
1789    def _send_for(self, born: int, text: str):
1790        """#4451: a line meant for the engine process `born`.  After a restart the same slot number belongs to another
1791        request of the new process: a BSTOP or BYIELD that followed the old request would end that one."""
1792        if self.gen != born:
1793            raise EngineDied("the engine restarted while this request was running; it was not completed")
1794        self._send(text)
1795
1796    def _quarantine_control(self, until: str, born: int, lines_q, slot, holding: bool) -> None:
1797        """#4451: a request left (cancel, disconnect, error) and the engine has not yet given the line that ends its
1798        exchange (`until`: DONE of a solo read, BADM of an admission) while it said nothing for DRAIN_TIMEOUT_S.  The control lines (and the
1799        admission's slot) stay with this exchange - nobody else is given them - until the engine confirms, so what it
1800        still prints can not reach a later request.  The engine silent for QUARANTINE_S more: it is ended.  (Only after a STOP or
1801        BSTOP, and only for silence: a generation that is still producing lines is never cut off.)"""
1802        if slot is not None:
1803            with self.slot_cv:
1804                self.slot_releasing.add(slot)           # busy stays: no request may take the slot
1805                self.slot_claims.discard(slot)
1806
1807        def run():
1808            try:
1809                line = self._drain_control(until, timeout=self.QUARANTINE_S, born=born, lines_q=lines_q)
1810                if line is None:
1811                    self._end_out_of_step(born, "the engine did not end an interrupted request (STOP) in time")
1812                cont = bool(until == "BADM" and line and line.startswith("BADM ") and line.split()[2:3] == ["1"])
1813                if slot is not None and self.gen == born:
1814                    if cont and self.alive():
1815                        self._release_slot_when_done(slot, None, born)      # it went on in the slot: BSTOP, free at BDONE
1816                    else:
1817                        with self.slot_cv:
1818                            self.slot_busy[slot] = False
1819                            self.slot_releasing.discard(slot)
1820                            self.slot_cv.notify_all()
1821            finally:
1822                if holding:
1823                    self.ctl.release()
1824                with self.slot_cv:
1825                    self.slot_cv.notify_all()
1826        threading.Thread(target=run, daemon=True).start()
1827
1828    def _control(self, cancel, on_token, stop_when=None, on_quiet=None, want_lp=False, lines_q=None):
1829        """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats.  Calls on_token(id)
1830        for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE).  `stop_when()`
1831        true sends STOP once (the request is then read to its DONE).  `on_quiet()` runs whenever the engine has been
1832        quiet for half a second: between two PP lines of a read whose chunks take longer than that.
1833
1834        `want_lp`: a batch admission's token is the only one this reader ever sees with an `LP` line after it (a
1835        slot's `BT` lines carry none), so a request asking for logprobs there is a `max_tokens` 1 one: read the
1836        line here, for the request itself (its own lines: the engine's is shared by the slots' readers)."""
1837        stopped = False
1838        beat = time.monotonic()
1839        held = NO_LINE                               # a line read while looking for a token's LP line
1840        lines_q = self.lines if lines_q is None else lines_q   # #4451: the request's own engine's lines (a restart makes new ones)
1841
1842        def send_stop():
1843            if lines_q is self.lines:               # (a STOP to the engine that replaced this one would stop another request)
1844                self._send("STOP")
1845        while True:
1846            if held is not NO_LINE:
1847                line, held = held, NO_LINE
1848            else:
1849                try:
1850                    # A client can leave before the first PP/token.  Poll its Event as often as _take_control does;
1851                    # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine.
1852                    line = lines_q.get(timeout=0.5)
1853                except queue.Empty:
1854                    if cancel.is_set() and not stopped:
1855                        send_stop()
1856                        stopped = True
1857                    if on_quiet is not None:
1858                        on_quiet()
1859                    if time.monotonic() - beat >= 10.0:
1860                        beat = time.monotonic()
1861                        yield None
1862                    continue
1863            beat = time.monotonic()
1864            if line is None:
1865                raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
1866            if not line.startswith(("PP ", "INFO")):
1867                btrace("ctl<", self._ctl_mode, line.strip()[:60])
1868            if line.startswith("T "):
1869                t = int(line[2:])
1870                if want_lp:
1871                    # the engine writes the token and its LP line in one flush: the next line is that one, or a
1872                    # line this reader must still see (held for the next turn, as generate() does)
1873                    try:
1874                        held = lines_q.get(timeout=0.5)
1875                    except queue.Empty:
1876                        held = NO_LINE
1877                    if isinstance(held, str) and held.startswith("LP "):
1878                        own = getattr(cancel, "_strata_lp_lines", None)
1879                        if own is not None:
1880                            own.append((t, held))
1881                        held = NO_LINE
1882                on_token(t)
1883                if not stopped and (cancel.is_set() or (stop_when is not None and stop_when())):
1884                    send_stop()
1885                    stopped = True
1886                yield False                              # a token is pending (not a heartbeat)
1887            elif line.startswith("PP "):
1888                f = line.split()
1889                if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():
1890                    self.progress = (int(f[1]), int(f[2]))
1891                    self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0
1892                    self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None
1893                if not stopped and cancel.is_set():
1894                    # #879: a Stop during the prompt read went out only after the first token (or after 10 s of
1895                    # silence, which a stream of PP lines never allows): the engine read the whole prompt first
1896                    send_stop()
1897                    stopped = True
1898                yield None
1899            elif line.startswith("DONE"):
1900                self._parse_done(line)
1901                self._last_done = line
1902            elif line.startswith("BADM "):
1903                f = line.split()
1904                self._ctl_result = ("badm", len(f) >= 3 and f[2] == "1")
1905                return
1906            elif line.startswith("BCOK "):               # STRATA_COALESCE_PREFILL: <slot> <tokens>: the slot holds a waiting prompt
1907                pass
1908            elif line.startswith("YIELDED "):            # the read gave way (BYIELD): <slot> <tokens read>
1909                f = line.split()
1910                if len(f) >= 3 and f[1].lstrip("-").isdigit() and f[2].isdigit():
1911                    self._yielded = (int(f[1]), int(f[2]))
1912            elif line.startswith("ERR"):
1913                self._ctl_erred = True                   # #1059: the engine refused it and is idle: no DONE follows
1914                self._raise_if_fatal_gpu(line)
1915                raise ValueError(line[4:].strip())
1916            if line.startswith("DONE") and self._ctl_mode == "solo":
1917                self._ctl_result = ("done", None)
1918                return
1919
1920    def _done_finish(self) -> str | None:
1921        """The finish field of the DONE line the control lines read last (None: none since it was cleared)."""
1922        f = (getattr(self, "_last_done", None) or "").split()
1923        return f[5] if len(f) > 5 else None
1924
1925    def _drain_control(self, until: str, timeout: float | None = None, born: int | None = None, lines_q=None):
1926        """After a consumer left early: read the control lines up to the next `until` line (DONE or BADM) so the next
1927        request does not read this one's leftovers.  Returns that line (None: the engine ended or never answered).
1928        `born`: the engine process (self.gen) the request started on; once that one is gone there is nothing to
1929        drain - its end line was read already (by the request's own EngineDied), and waiting for another one held
1930        a request that had failed for the whole 300 s (#1012), or read the lines of the engine that replaced it.
1931        `timeout` (DRAIN_TIMEOUT_S) is a NO-PROGRESS limit: it counts from the last line the engine wrote, so an engine that
1932        is still talking (PP / T lines of a read or a decode it was told to stop but has not yet) is never given up on;
1933        only one that says nothing for that long is."""
1934        wait_s = self.DRAIN_TIMEOUT_S if timeout is None else timeout
1935        end = time.monotonic() + wait_s
1936        lines_q = self.lines if lines_q is None else lines_q
1937        while time.monotonic() < end:
1938            if born is not None and (self.gen != born or not self.alive()):
1939                return None
1940            try:
1941                line = lines_q.get(timeout=max(0.1, min(1.0, end - time.monotonic())))
1942            except queue.Empty:
1943                continue
1944            if line is None:
1945                return None
1946            end = time.monotonic() + wait_s                  # any line is progress
1947            if line.startswith("DONE"):
1948                self._parse_done(line)
1949            if line.startswith(until) or line.startswith("ERR"):
1950                return line
1951        return None
1952
1953    def _apply_bdone(self, f: list[str]) -> None:
1954        """BDONE counts the admission token too, but its clock starts after the admission's DONE."""
1955        if len(f) >= 5 and isinstance(self.last, dict):
1956            admission_ms = self.last.get("decode_ms")
1957            self.last = {**self.last, "finish": f[3],
1958                         "decode_ms": admission_ms + float(f[4]) if admission_ms is not None else None,
1959                         "generated": int(f[2]) if f[2].isdigit() else None}
1960
1961    def _raise_if_fatal_gpu(self, line: str) -> None:
1962        """#4350: the engine's ERR line "fatal GPU error: ..." means it is ending (its GPU context is gone).  The request in flight fails
1963        as an engine death (a 503 the client can send again), not as a bad request (400), and the engine counts as ended, so the next
1964        request starts it again at once instead of finding a closed pipe."""
1965        text = line[4:].strip()
1966        if not text.startswith("fatal GPU error"):
1967            return
1968        self.last_err = text
1969        self.ended = True
1970        raise EngineDied("the GPU reported a fatal error and the engine ended: " + text[len("fatal GPU error:"):].strip()[:200])
1971
1972    def _bdone_after_eos(self, slot: int, wait_s: float = 2.0, q=None):
1973        """#1869: a request in a slot whose consumer left at the stop token has its BDONE right behind it (the engine prints it
1974        in the same window).  Read it here, so the request's figures are the slot leg's (the background wait would eat it,
1975        and the request kept the admission's single token).  None when it does not come in `wait_s`: then the background
1976        wait takes over."""
1977        if q is None and slot >= len(self.slot_q):
1978            return None
1979        q = self.slot_q[slot] if q is None else q
1980        end = time.monotonic() + wait_s
1981        while time.monotonic() < end:
1982            try:
1983                line = q.get(timeout=max(0.05, end - time.monotonic()))
1984            except queue.Empty:
1985                return None
1986            if line is None:
1987                return None
1988            if line.startswith("BDONE "):
1989                return line
1990        return None
1991
1992    def _end_out_of_step(self, born: int, what: str) -> None:
1993        """#4451: the engine did not give a line it owes (a BDONE after BSTOP, a DONE / BADM after STOP) within the
1994        quarantine: what it may still print can not be told from a later request's lines, so the engine is ended (the
1995        same end as a silent one, #481) and the next request starts it again.  Only the engine process it concerns."""
1996        if self.gen == born and self.alive():
1997            self._silent(what)
1998
1999    def _release_slot_when_done(self, slot: int, stream: list[int] | None = None, born: int | None = None):
2000        """A slot whose consumer left (a stop token, a stop string, a disconnect): BSTOP it and free it once the engine
2001        says BDONE (in the background).  `stream`: the prompt and every token of it so far - with the tokens still to
2002        come before BDONE, all but the last are what the slot holds then (the next turn of its conversation)."""
2003        if slot >= len(self.slot_q):                    # the engine restarted with fewer slots: this one is gone
2004            return
2005        if born is not None and self.gen != born:       # #4451: the engine this slot belonged to is gone; BSTOP now would stop
2006            return                                      # (and the wait below would read) a request of the NEW engine
2007        born = self.gen if born is None else born
2008        try:
2009            self._send(f"BSTOP {slot}")
2010        except EngineDied:
2011            pass
2012        q, busy, held = self.slot_q[slot], self.slot_busy, self.slot_held   # this process's: restart() replaces them
2013        releasing = self.slot_releasing
2014        releasing.add(slot)
2015
2016        def wait():
2017            end = time.monotonic() + self.QUARANTINE_S      # no-progress limit: every line of the slot starts it again
2018            tail = list(stream or [])
2019            confirmed = False
2020            while time.monotonic() < end:
2021                try:
2022                    line = q.get(timeout=5.0)
2023                except queue.Empty:
2024                    if self.gen != born or not self.alive():
2025                        break
2026                    continue
2027                if line is None:
2028                    tail = []
2029                    break
2030                end = time.monotonic() + self.QUARANTINE_S
2031                if line.startswith("BT "):
2032                    try:
2033                        tail.append(int(line.split()[2]))
2034                    except (IndexError, ValueError):
2035                        tail = []
2036                if line.startswith("BDONE "):
2037                    confirmed = True
2038                    if line.split()[3:4] == ["nonfinite"]:   # #879: the engine dropped the slot's state
2039                        tail = []
2040                    break
2041            if not confirmed:
2042                tail = []
2043                # #4451: no BDONE in the quarantine from an engine that still runs: the slot is NOT handed on with its
2044                # lines still to come - the engine is ended instead (a dead engine's slots are free by being gone)
2045                self._end_out_of_step(born, "the engine did not end a stopped batch slot (BSTOP) in time")
2046            held[slot] = tail[:-1] if stream and tail else []
2047            with self.slot_cv:
2048                busy[slot] = False
2049                releasing.discard(slot)
2050                self.slot_cv.notify_all()
2051        threading.Thread(target=wait, daemon=True).start()
2052
2053    BGEN_REFUSALS_MAX = 6    # #1994: how often one request tries another slot after the engine refused a BGEN
2054    SLOT_PARK_S = 2.0        # ... and how long a refused slot stays out of the picks
2055
2056    def _park_slot(self, slot: int) -> None:
2057        """#1994: the engine refused a BGEN for `slot`.  Keep it busy here for SLOT_PARK_S (no request owns it), then
2058        give it back: the engine's view has caught up, or the next refusal parks it again."""
2059        with self.slot_cv:
2060            self.slot_claims.discard(slot)
2061            self.slot_busy[slot] = True
2062        busy = self.slot_busy
2063
2064        def free():
2065            with self.slot_cv:
2066                if slot not in self.slot_claims and slot not in self.slot_releasing:
2067                    busy[slot] = False
2068                self.slot_cv.notify_all()
2069        t = threading.Timer(self.SLOT_PARK_S, free)
2070        t.daemon = True
2071        t.start()
2072
2073    ORPHAN_SLOT_S = 3.0   # #1603: a busy flag nobody owns this long is a leak and is given back
2074
2075    def _reap_orphan_slots(self) -> list[int]:
2076        """#1603: free the slots whose busy flag has no owner (no request holds or reserves them and no BDONE wait is
2077        running for them).  The caller holds slot_cv.  A flag that leaked kept every later request waiting for a slot
2078        that nothing would free - with nothing running, nothing queued and nothing for the frozen-engine check to see.
2079        A slot is only given back after it has looked ownerless for ORPHAN_SLOT_S, so a flag set a moment before its
2080        owner registers is never taken."""
2081        now = time.monotonic()
2082        freed = []
2083        for b, busy in enumerate(self.slot_busy):
2084            if busy and b not in self.slot_claims and b not in self.slot_releasing:
2085                first = self._orphan_seen.setdefault(b, now)
2086                if now - first >= self.ORPHAN_SLOT_S:
2087                    self.slot_busy[b] = False
2088                    self._orphan_seen.pop(b, None)
2089                    freed.append(b)
2090            else:
2091                self._orphan_seen.pop(b, None)
2092        if freed:
2093            print(f"[strata] parallel: slot(s) {', '.join(map(str, freed))} were marked busy with no request using them "
2094                  "(issue #1603); freed, the waiting request goes on", flush=True)
2095            self.slot_cv.notify_all()
2096        return freed
2097
2098    YIELDS_MAX = 2   # #656: how often one request's prompt read gives way to a shorter waiting one
2099
2100    def _take_control(self, cancel, plen: int, after_epoch: int | None = None, new: bool = False, prompt=None):
2101        """Waits for the control lines (one prompt read at a time), yielding None heartbeats; False when cancelled.
2102        `after_epoch`: a request whose read gave way lets the requests waiting then go first.
2103        `new`: the request's first admission (STRATA_ADMIT_SHORT_FIRST orders only these)."""
2104        entry = [plen, time.monotonic(), new, prompt, cancel]           # (length, arrival, ordered: STRATA_ADMIT_SHORT_FIRST; the prompt and request, for STRATA_COALESCE_PREFILL)
2105        with self.slot_cv:
2106            self.waiting += 1
2107            self.wait_lens.append(entry)
2108            self.arrivals.append(entry[1])
2109        beat = time.monotonic()
2110        try:
2111            while True:
2112                deadline = getattr(cancel, "_strata_queue_deadline", None)
2113                if deadline is not None and time.monotonic() >= deadline:
2114                    raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
2115                if not self.alive() and not getattr(self, "starting", False):
2116                    # #1012: the engine is gone and nobody is starting it again: this request was not sent, so it
2117                    # ends now (a clean 503) instead of waiting for control lines nothing will answer on.  While a
2118                    # restart is under way it keeps waiting and goes on with the new engine.
2119                    raise EngineDied("the engine stopped while this request waited; it was not sent")
2120                with self.slot_cv:
2121                    turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1
2122                    if turn and new and ADMIT_SHORT_FIRST > 0:
2123                        turn = self._admit_next() is entry
2124                left = deadline - time.monotonic() if deadline is not None else 0.5
2125                if turn and left > 0 and self.ctl.acquire(timeout=min(0.5, left)):
2126                    if new and ADMIT_SHORT_FIRST > 0:
2127                        with self.slot_cv:              # a shorter one came while this one waited in acquire()
2128                            first = self._admit_next() is entry
2129                        if not first:
2130                            self.ctl.release()
2131                            with self.slot_cv:
2132                                self.slot_cv.notify_all()
2133                            continue
2134                    if self.alive():
2135                        if deadline is not None and time.monotonic() >= deadline:
2136                            self.ctl.release()
2137                            raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
2138                        break
2139                    self.ctl.release()                  # it died (or is being restarted) while this one was getting
2140                    turn = False                        # the lines: not the engine this request was meant for
2141                if not turn:
2142                    with self.slot_cv:
2143                        # #4738 (PR #4738's approach): the turn was read, and the lock given up, before this wait: a
2144                        # notification sent in between is gone.  Read it again under the lock and only wait when this
2145                        # request still has to.
2146                        eligible = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1
2147                        if eligible and new and ADMIT_SHORT_FIRST > 0:
2148                            eligible = self._admit_next() is entry
2149                        if not eligible or not self.alive():
2150                            self.slot_cv.wait(timeout=min(0.5, max(0, left)))
2151                if cancel.is_set():
2152                    return False
2153                if time.monotonic() - beat >= 10.0:     # a heartbeat every 10 s, as the engine's own wait
2154                    beat = time.monotonic()
2155                    yield None
2156        finally:
2157            with self.slot_cv:
2158                previous_waiting = self.waiting
2159                self.waiting = max(0, self.waiting - 1)
2160                if entry in self.wait_lens:
2161                    self.wait_lens.remove(entry)
2162                if (previous_waiting > 1 and self.waiting <= 1) or (new and ADMIT_SHORT_FIRST > 0):
2163                    # a waiter that leaves (cancelled, closed) can make another one the next in turn: tell it
2164                    self.slot_cv.notify_all()
2165        with self.slot_cv:
2166            self.ctl_epoch += 1
2167            self.slot_cv.notify_all()
2168        return True
2169
2170    def _release_preslot(self, cancel):
2171        """STRATA_COALESCE_PREFILL: the request that was given a slot ahead of its turn left before using it."""
2172        slot = getattr(cancel, "_strata_preslot", None)
2173        if slot is None:
2174            return
2175        cancel._strata_preslot = None
2176        with self.slot_cv:
2177            self.slot_busy[slot] = False
2178            self.slot_claims.discard(slot)
2179            self.slot_cv.notify_all()
2180
2181    def _coalesce(self, cancel, lead_prompt):
2182        """STRATA_COALESCE_PREFILL (the caller holds the control lines and sends its BGEN right after): reserve free slots
2183        for requests still waiting for the control lines and send their prompts as BCO lines; the engine reads them in the
2184        same layer-major pass as the BGEN's prompt.  Each follower finds its slot in cancel._strata_preslot."""
2185        picked = []
2186        total = len(lead_prompt)
2187        def seen() -> int:
2188            now = time.monotonic()
2189            with self.slot_cv:
2190                return max(sum(1 for t in self.arrivals if now - t <= COALESCE_BURST_MS / 1000.0), 1 + len(self.wait_lens))
2191        recent = seen()
2192        if recent < COALESCE_MIN_REQS and COALESCE_WAIT_MS > 0:
2193            time.sleep(0.010)                        # (the first request of a burst holds the lines before its neighbours have arrived)
2194            recent = seen()
2195        if recent < COALESCE_MIN_REQS:
2196            return                                   # one or two requests on this engine: a plain read, at most 10 ms lost
2197        if COALESCE_WAIT_MS > 0:
2198            time.sleep(COALESCE_WAIT_MS / 1000.0)    # the requests of a burst reach the server a few ms apart
2199        with self.slot_cv:
2200            for e in list(self.wait_lens):
2201                if len(picked) >= COALESCE_PREFILL - 1:
2202                    break
2203                prompt = e[3] if len(e) > 4 else None
2204                rq = e[4] if len(e) > 4 else None
2205                if prompt is None or rq is None or rq is cancel or getattr(rq, "_strata_preslot", None) is not None:
2206                    continue
2207                if getattr(rq, "_strata_co", False) or len(prompt) < 32 or total + len(prompt) > COALESCE_TOKENS:
2208                    continue
2209                slot = self.pick_slot(prompt)
2210                if slot is None:
2211                    break
2212                self.slot_busy[slot] = True
2213                self.slot_claims.add(slot)
2214                self.slot_held[slot] = []
2215                rq._strata_preslot = slot
2216                rq._strata_co = True
2217                total += len(prompt)
2218                picked.append((slot, prompt))
2219        for slot, prompt in picked:
2220            self._send(f"BCO {slot} {','.join(str(int(t)) for t in prompt)}")
2221        if picked:
2222            print(f"[strata] coalesce: {len(picked)} waiting prompt(s) ({total - len(lead_prompt)} tokens) read with this "
2223                  f"request's {len(lead_prompt)}", flush=True)
2224
2225    def _admit_next(self):
2226        """STRATA_ADMIT_SHORT_FIRST=<tokens> (the caller holds slot_cv): the new request that takes the control lines
2227        next - one whose prompt is at most that long (it reads little) before a longer one, in arrival order within
2228        each; a longer one that has waited STRATA_ADMIT_MAX_WAIT_S counts as short (it is never held back for good).
2229        Off (unset or 0): whoever gets the lock first, as before.  Only the order changes, never what is read."""
2230        now = time.monotonic()
2231        ordered = [e for e in self.wait_lens if len(e) > 2 and e[2]]
2232        if not ordered:
2233            return None
2234        return min(ordered, key=lambda e: (0 if e[0] <= ADMIT_SHORT_FIRST or now - e[1] >= ADMIT_MAX_WAIT_S else 1,
2235                                           e[1]))
2236
2237    SOLO_AGAIN_MAX = 2      # how often a request left alone in a slot goes back to the solo path
2238    SOLO_AGAIN_MIN_LEFT = 32  # ... only with at least this many tokens still allowed (max_tokens)
2239
2240    def _may_go_solo(self, left: int, times: int, embeddings) -> bool:
2241        """A request decoding in a slot that is alone now (no other slot busy, nobody waiting) goes back to the solo
2242        path with its MTP drafts: the engine continues it from the slot's sessions (its slot cache; INFO
2243        slot_cache=1).  STRATA_PARALLEL_SOLO=0 keeps it in the slot."""
2244        if (embeddings or times >= self.SOLO_AGAIN_MAX or left < self.SOLO_AGAIN_MIN_LEFT or
2245                not (self.info or {}).get("slot_cache") or os.environ.get("STRATA_PARALLEL_SOLO") == "0"):
2246            return False
2247        with self.slot_cv:
2248            return sum(1 for b in self.slot_busy if b) == 1 and self.waiting == 0
2249
2250    def _shorter_waiting(self, plen: int) -> bool:
2251        """#656: someone waits for the control lines with a prompt under half this one's: worth giving way to."""
2252        with self.slot_cv:
2253            return any(e[0] * 2 <= plen for e in self.wait_lens)
2254
2255    def generate_batched(self, ids, max_new, sampling, cancel, embeddings=None):
2256        """--batch.  Alone (no slot busy, nobody waiting): the solo path (GEN, with drafts: the fastest stream)
2257        - and when another request arrives meanwhile, this one is STOPped and continues in a batch slot (BGEN with
2258        its prompt + what it generated: the engine reuses that prefix).  Otherwise: BGEN into a free slot, then the
2259        slot's own BT lines until BDONE.  Several requests run at once; the control lines (prompt reading, admission)
2260        are taken one request at a time - and a long prompt read gives way at a chunk boundary to a waiting request
2261        with a much shorter prompt (#656: `BYIELD <slot>`; the part read waits in a slot and the read goes on after).
2262        A consumer that stops early leaves the engine in step: the solo request is STOPped and read to its DONE, an
2263        admission to its BADM, a slot is BSTOPped and freed at its BDONE."""
2264        if not self.alive():
2265            raise EngineDied("the engine is unavailable; this request was not sent")
2266        self.progress, self.progress_ms, self.reused = None, 0, 0
2267        born = self.gen                                 # the engine process this request is sent to
2268        hold = (sampling or {}).get(HOLD_KEY)           # the thinking budget's hold (P2b): the reasoning tokens left when this pass starts, and </think>'s id
2269        keys0 = self.sampling_keys({k: v for k, v in (sampling or {}).items() if k != HOLD_KEY})   # (the hold's key goes on per leg: leg_keys below)
2270        # logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the
2271        # server refuses these requests unless max_tokens is 1.  The lines go to the request itself, through its
2272        # cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute.
2273        want_lp = top_logprobs(sampling or {}) is not None
2274        if want_lp:
2275            cancel._strata_lp_lines = LPLines(cancel)
2276        out: list[int] = []
2277        pending: list[int] = []
2278        prompt, left = list(ids), int(max_new)
2279
2280        def leg_keys() -> str:
2281            """The budget's hold counts what this pass still has: a leg that starts after `out` tokens of it holds the rest (at least one);
2282            once </think> is in `out` the hold is over and no key goes."""
2283            if isinstance(hold, tuple) and len(hold) == 2 and hold[0] > 0 and hold[1] >= 0 and hold[1] not in out:
2284                return keys0 + f" hold={max(1, hold[0] - len(out))}:{hold[1]}"
2285            return keys0
2286        orig_len = len(prompt)  # a leg that continues (prompt + what it generated) names where the reply began: pen_from, the penalty window's start
2287        reused0 = None      # the first read's reused tokens: a continued leg's count includes this request's own output
2288        carry = {}          # #1869: the figures of the legs that ended in a hand-back to the solo path (the final DONE adds to them)
2289        yielded_legs = []    # prompt reads that gave way before producing output
2290        ok = yield from self._take_control(cancel, len(prompt), new=True,
2291                                           prompt=prompt if (COALESCE_PREFILL > 1 and not embeddings) else None)
2292        if not ok:
2293            self._release_preslot(cancel)
2294            return
2295        holding, born = True, self.gen                  # (the engine it now has the control lines of)
2296        lines_q, sq = self.lines, self.slot_q           # #4451: ... and its queues; a restart makes new ones, and a request
2297        #                                                 of the old process must never read (or answer on) the new ones
2298        btrace("ctl acquired")
2299        slot, gen0, reserved = None, None, None
2300        pre = getattr(cancel, "_strata_preslot", None)
2301        if pre is not None:                             # STRATA_COALESCE_PREFILL: a request before this one read the prompt into this slot
2302            slot, cancel._strata_preslot = pre, None
2303        phase = "none"            # solo -> (admit -> slot) ; "done" once the engine has finished with this request
2304        stop_sent = False
2305        admission_pending, admission_before = False, None   # the admission's DONE is partial until BADM 0 or BDONE
2306        yields, solo_again, refused = 0, 0, 0
2307        admit_wait, admit_since, admit_said = False, 0.0, False   # #1603: waiting for a slot, since when, said
2308        try:
2309            while True:   # a request in a slot that is left alone goes back to the solo path
2310                if not holding:
2311                    ok = yield from self._take_control(cancel, len(prompt))
2312                    if not ok:
2313                        return
2314                    holding, born = True, self.gen                  # (the engine it now has the control lines of)
2315                    lines_q, sq = self.lines, self.slot_q           # (it holds no slot of the engine before: nothing to lose)
2316                with self.slot_cv:
2317                    alone = not any(self.slot_busy) and self.waiting == 0
2318                if alone and left > 1:
2319                    pf = self.pen_from_key(orig_len, len(prompt))
2320                    head = f"GENI {left}{leg_keys()}{pf} {embeddings}" if embeddings else f"GEN {left}{leg_keys()}{pf}"
2321                    self._last_done = None                  # (#879: this request's DONE decides below)
2322                    deadline = getattr(cancel, "_strata_queue_deadline", None)
2323                    if deadline is not None and time.monotonic() >= deadline:
2324                        raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
2325                    self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
2326                    if deadline is not None:
2327                        cancel._strata_queue_deadline = None
2328                    started = getattr(cancel, "_strata_queue_started", None)
2329                    if started is not None:
2330                        started()
2331                    phase = "solo"
2332                    self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None
2333                    self._ctl_erred = False
2334                    def others():
2335                        with self.slot_cv:
2336                            return self.waiting > 0
2337
2338                    def give_way():   # at a PP line, and between two far apart (the engine takes it at its next boundary)
2339                        nonlocal reserved
2340                        if (reserved is None and not out and not embeddings and yields < self.YIELDS_MAX and
2341                                self._shorter_waiting(len(prompt))):
2342                            with self.slot_cv:          # the slot the part read will wait in
2343                                reserved = self.pick_slot(prompt)
2344                                if reserved is not None:
2345                                    self.slot_busy[reserved] = True
2346                                    self.slot_claims.add(reserved)
2347                            if reserved is not None:
2348                                self._send_for(born, f"BYIELD {reserved}")
2349                    for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way,
2350                                           want_lp=want_lp, lines_q=lines_q):
2351                        while pending:
2352                            t = pending.pop(0)
2353                            out.append(t)
2354                            yield t
2355                        if x is None:                       # a heartbeat (False: a token, flushed above)
2356                            give_way()
2357                            yield None
2358                    phase = "none"                          # its DONE is read
2359                    while pending:
2360                        t = pending.pop(0)
2361                        out.append(t)
2362                        yield t
2363                    if self._done_finish() == "nonfinite":    # #879 (never promoted to a slot)
2364                        raise EngineNonFinite("the engine's logits became non-finite (#879)")
2365                    if self._yielded is not None and reserved is not None and self._yielded[0] == reserved:
2366                        yielded_legs.append(self.last)
2367                        slot, reserved = reserved, None     # gave way: the read goes on in that slot (below)
2368                    elif reserved is not None:              # it did not give way: the slot is free again
2369                        with self.slot_cv:
2370                            self.slot_busy[reserved] = False
2371                            self.slot_claims.discard(reserved)
2372                            self.slot_cv.notify_all()
2373                        reserved = None
2374                    if slot is None:
2375                        finish = (self.last or {}).get("finish") if isinstance(self.last, dict) else None
2376                        left = int(max_new) - len(out)
2377                        if cancel.is_set() or left <= 0 or finish in ("stop", "length", "hold") or (out and out[-1] in EOS_IDS):
2378                            return                          # ("hold": the budget's cut: the caller wraps up or asks for more)
2379                        if reused0 is None:
2380                            reused0 = (self.last or {}).get("reused")
2381                        carry_leg(carry, self.last)         # #1869: the solo leg's figures; the slot's admission (a copy of
2382                                                            # the held prefix: prompt_read 1) and BDONE replace them
2383                        prompt = list(ids) + out            # promoted: it continues in a batch slot from here
2384                while True:
2385                    if slot is None:
2386                        # a free slot (they free themselves at BDONE, which needs no control lines): the one that holds
2387                        # the start of this prompt (its conversation's last turn), else the one used longest ago.
2388                        # With none free the control lines are given back while waiting: a slot can be held by a read
2389                        # that gave way (BYIELD) and needs them to go on, so waiting with them is a deadlock - long,
2390                        # long, short at 0.25 s steps under parallel: 2 (ENGINE_REVIEW finding 1, reproduced in 0.1.41).
2391                        while True:
2392                            deadline = getattr(cancel, "_strata_queue_deadline", None)
2393                            if deadline is not None and time.monotonic() >= deadline:
2394                                raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
2395                            with self.slot_cv:
2396                                slot = self.pick_slot(prompt)
2397                                if slot is not None:
2398                                    self.slot_busy[slot] = True
2399                                    self.slot_claims.add(slot)
2400                                    if admit_wait:
2401                                        admit_wait = False
2402                                        self.admitting = max(0, self.admitting - 1)
2403                                        if PAR_COUNTERS:                # STRATA_PAR_COUNTERS=1: time spent waiting for a free slot
2404                                            self.par_counters["queued"] += 1
2405                                            self.par_counters["queue_wait_s"] += time.monotonic() - admit_since
2406                                    break
2407                                if not admit_wait:          # #1603: counted while it waits for a slot (it holds no
2408                                    admit_wait, admit_since = True, time.monotonic()   # control lines then)
2409                                    self.admitting += 1
2410                            if holding:
2411                                self.ctl.release()
2412                                holding = False
2413                            with self.slot_cv:
2414                                if self.pick_slot(prompt) is None:
2415                                    if (ENGINE_STALL_S or 0) > 0 and time.monotonic() - admit_since >= ENGINE_STALL_S:
2416                                        # the stall check of #1317 only watches a request on the control lines; one
2417                                        # waiting here is covered by looking for a slot nobody owns, and by saying so
2418                                        if not admit_said:
2419                                            admit_said = True
2420                                            busy = [b for b, v in enumerate(self.slot_busy) if v]
2421                                            print(f"[strata] parallel: a request has waited {time.monotonic() - admit_since:.0f} s "
2422                                                  f"for a free slot (busy: {busy}, in use: {sorted(self.slot_claims)}, "
2423                                                  f"ending: {sorted(self.slot_releasing)}) (issue #1603)", flush=True)
2424                                    self._reap_orphan_slots()
2425                                if self.pick_slot(prompt) is None:
2426                                    wait_remaining = deadline - time.monotonic() if deadline is not None else 1.0
2427                                    self.slot_cv.wait(timeout=min(1.0, max(0, wait_remaining)))
2428                            if cancel.is_set():
2429                                return
2430                            if not holding:
2431                                ok = yield from self._take_control(cancel, len(prompt))
2432                                if not ok:
2433                                    return
2434                                holding, born = True, self.gen
2435                                lines_q, sq = self.lines, self.slot_q   # (a slot is claimed below, on this engine)
2436                    if self._yielded is not None:           # it gave way: the others waiting then go first
2437                        self.slot_held[slot] = list(prompt[:self._yielded[1]])
2438                        self._yielded = None
2439                        yields += 1
2440                        self.ctl.release()
2441                        holding = False
2442                        with self.slot_cv:
2443                            epoch = self.ctl_epoch
2444                        ok = yield from self._take_control(cancel, len(prompt), after_epoch=epoch)
2445                        if not ok:
2446                            return
2447                        if self.gen != born:                    # #4451: the slot it holds was the old engine's
2448                            holding = True
2449                            raise EngineDied("the engine restarted while this request waited for it; it was not completed")
2450                        holding, born = True, self.gen                  # (the engine it now has the control lines of)
2451                    while not sq[slot].empty():
2452                        sq[slot].get_nowait()
2453                    pf = self.pen_from_key(orig_len, len(prompt))
2454                    head = f"BGENI {slot} {left}{leg_keys()}{pf} {embeddings}" if embeddings else f"BGEN {slot} {left}{leg_keys()}{pf}"
2455                    live = {"slot": slot, "request_id": getattr(cancel, "_strata_request_id", None),
2456                            "state": "reading", "prompt_tokens": len(prompt), "prompt_read": 0, "generated": 0,
2457                            "started": time.time(), "first_token": None}
2458                    deadline = getattr(cancel, "_strata_queue_deadline", None)
2459                    if deadline is not None and time.monotonic() >= deadline:
2460                        raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
2461                    self.slot_live[slot] = live
2462                    self._last_done = None                  # (#879: this admission's DONE decides below)
2463                    if COALESCE_PREFILL > 1 and not embeddings:
2464                        self._coalesce(cancel, prompt)
2465                    self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
2466                    if deadline is not None:
2467                        cancel._strata_queue_deadline = None
2468                    started = getattr(cancel, "_strata_queue_started", None)
2469                    if started is not None:
2470                        started()
2471                    self.slot_held[slot] = []               # the admission overwrites what the slot held
2472                    admission_pending, admission_before = True, self.last
2473                    phase = "admit"
2474                    self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None
2475                    self._ctl_erred = False
2476                    asked = False
2477
2478                    def ask():        # as give_way above, for the slot this admission reads into
2479                        nonlocal asked
2480                        if (not asked and not embeddings and yields < self.YIELDS_MAX and
2481                                self._shorter_waiting(len(prompt))):
2482                            self._send_for(born, f"BYIELD {slot}")
2483                            asked = True
2484
2485                    def note_progress():
2486                        # the terminal layer's live prompt counter (the batch admission path)
2487                        if self.progress and live["state"] == "reading":
2488                            live["prompt_read"] = self.progress[0]
2489                    try:
2490                        for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress()),
2491                                               want_lp=want_lp, lines_q=lines_q):
2492                            while pending:
2493                                t = pending.pop(0)
2494                                out.append(t)
2495                                yield t
2496                            if x is None:
2497                                ask()
2498                                note_progress()
2499                                yield None
2500                    except ValueError as e:
2501                        # #1994: the engine says this slot is not free (its view and ours differ for a moment, or a
2502                        # slot it still holds).  That is not the request's fault and nothing was read: park the slot
2503                        # for a moment (busy here too), and wait for another one - never a 400 for the conversation.
2504                        if not (self._ctl_erred and str(e).startswith("BGEN:") and left >= 1 and not cancel.is_set()):
2505                            raise
2506                        refused += 1
2507                        print(f"[strata] parallel: the engine refused slot {slot} ({e}); trying another slot "
2508                              f"({refused}/{self.BGEN_REFUSALS_MAX}) (issue #1994)", flush=True)
2509                        if refused > self.BGEN_REFUSALS_MAX:
2510                            raise GpuBusy("the engine's batch slots are not free right now; try again in a moment",
2511                                      retry_after=5) from e
2512                        self.slot_live[slot] = None
2513                        self.slot_held[slot] = []
2514                        phase = "none"
2515                        self._ctl_erred = False
2516                        self._park_slot(slot)
2517                        slot = None
2518                        continue
2519                    cont = bool(self._ctl_result and self._ctl_result[1])
2520                    admission_pending = cont
2521                    phase = "slot" if cont else "none"
2522                    while pending:
2523                        t = pending.pop(0)
2524                        out.append(t)
2525                        yield t
2526                    if not cont and self._done_finish() == "nonfinite":   # #879
2527                        raise EngineNonFinite("the engine's logits became non-finite (#879)")
2528                    if not cont and self._yielded is not None and self._yielded[0] == slot and not cancel.is_set():
2529                        yielded_legs.append(self.last)
2530                        continue                            # gave way: again once the shorter request is in
2531                    break
2532                self.ctl.release()
2533                holding = False
2534                if not cont:
2535                    return
2536                live.update(state="decoding", first_token=time.time(), generated=len(out))
2537                gen0 = len(out) - 1                         # the admission's own token: the slot feeds it first
2538                going_solo = False
2539                while True:
2540                    try:
2541                        line = sq[slot].get(timeout=10.0)
2542                    except queue.Empty:
2543                        if self.gen != born:                # #4451: the engine it was admitted on is gone (and so is its slot)
2544                            phase = "none"
2545                            raise EngineDied("the engine restarted while this request was running; it was not completed")
2546                        if cancel.is_set() and not stop_sent:
2547                            self._send_for(born, f"BSTOP {slot}")
2548                            stop_sent = True
2549                        yield None
2550                        continue
2551                    if line is None:
2552                        phase = "none"
2553                        raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
2554                    if line.startswith("BT "):
2555                        t = int(line.split()[2])
2556                        out.append(t)
2557                        live["generated"] = len(out)
2558                        if cancel.is_set():
2559                            if not stop_sent:
2560                                self._send_for(born, f"BSTOP {slot}")
2561                                stop_sent = True
2562                            continue
2563                        yield t
2564                        if not going_solo and not stop_sent and self._may_go_solo(int(max_new) - len(out), solo_again,
2565                                                                                  embeddings):
2566                            self._send_for(born, f"BSTOP {slot}")   # alone now: on with the drafts (below)
2567                            going_solo = True
2568                    elif line.startswith("BDONE "):
2569                        phase = "none"
2570                        f = line.split()
2571                        self._apply_bdone(f)
2572                        admission_pending = False
2573                        # what the slot's sessions hold now: the prompt and every token fed (all but the last one)
2574                        self.slot_held[slot] = list(prompt) + out[gen0:-1] if len(out) > gen0 else []
2575                        if f[3:4] == ["nonfinite"]:              # #879: the engine dropped the slot's state
2576                            self.slot_held[slot] = []
2577                            raise EngineNonFinite("the engine's logits became non-finite (#879)")
2578                        if (going_solo and f[3:4] == ["cancel"] and not cancel.is_set() and len(out) < int(max_new)
2579                                and not (out and out[-1] in EOS_IDS)):
2580                            # the solo path continues it: the engine copies the slot's sessions back (all but the
2581                            # last token are in them) and decodes with MTP drafts again
2582                            carry_leg(carry, self.last)         # #1869: the solo path's DONE replaces these figures
2583                            self.slot_live[slot] = None
2584                            self.slot_used[slot] = time.time()
2585                            with self.slot_cv:
2586                                self.slot_busy[slot] = False
2587                                self.slot_claims.discard(slot)
2588                                self.slot_cv.notify_all()
2589                            slot, gen0 = None, None
2590                            if reused0 is None:
2591                                reused0 = (self.last or {}).get("reused")
2592                            prompt, left = list(ids) + out, int(max_new) - len(out)
2593                            solo_again += 1
2594                            btrace("back to the solo path")
2595                            break
2596                        return
2597        finally:
2598            # a consumer that left early (or an error): keep the engine and this server in step
2599            btrace("finally phase", phase, "slot", slot, "holding", holding)
2600            same = self.gen == born                     # #4451: the slot state below is this engine's; after a restart it is the NEW
2601            #                                             engine's lists and flags, which belong to other requests
2602            undrained = None                            # the line this request's exchange still owes, from an engine that runs
2603            try:
2604                if phase in ("solo", "admit") and (self.gen != born or not self.alive()):
2605                    phase = "none"                      # #1012: its engine is gone: nothing to stop or drain
2606                if phase in ("solo", "admit") and self._ctl_erred:
2607                    phase = "none"                      # #1059: it ended on the engine's ERR: no DONE to wait 300 s for
2608                if phase == "solo":
2609                    self._send("STOP")
2610                    if self._drain_control("DONE", born=born, lines_q=lines_q) is None and self.gen == born and self.alive():
2611                        undrained = "DONE"
2612                elif phase == "admit":
2613                    line = self._drain_control("BADM", born=born, lines_q=lines_q)
2614                    if line and line.startswith("BADM "):
2615                        admission_pending = line.split()[2:3] == ["1"]
2616                    if line and line.startswith("BADM ") and line.split()[2:3] == ["1"]:
2617                        phase = "slot"
2618                    elif line is None and self.gen == born and self.alive():
2619                        undrained = "BADM"
2620            except EngineDied:
2621                pass
2622            handed = False
2623            if undrained is not None:
2624                # #4451: the engine has not said it is done with this request; whatever it prints later must not be read
2625                # by the next one.  The control lines (and the admission's slot) stay quarantined until it does.
2626                self._quarantine_control(undrained, born, lines_q, slot if undrained == "BADM" else None, holding)
2627                holding, handed = False, True
2628            bdone_in = False
2629            if phase == "slot" and slot is not None and out and out[-1] in EOS_IDS and same:
2630                bd = self._bdone_after_eos(slot, q=sq[slot])    # (#1869) the slot's figures, not the admission's
2631                if bd is not None:
2632                    self._apply_bdone(bd.split())
2633                    admission_pending = False
2634                    bdone_in = True
2635            ended_on_yield = bool(yielded_legs and self.last is yielded_legs[-1])
2636            if admission_pending and isinstance(self.last, dict) and (self.last is not admission_before or carry):
2637                # A background drain owns the rest. The admission's one token and time are not this request's totals.
2638                self.last = {**self.last, "generated": None, "decode_ms": None}
2639            if reused0 is not None and isinstance(self.last, dict):
2640                self.last = {**self.last, "reused": reused0}
2641            if carry and isinstance(self.last, dict):
2642                self.last = add_carry(carry, self.last)
2643            earlier_reads = yielded_legs[:-1] if ended_on_yield else yielded_legs
2644            if earlier_reads and isinstance(self.last, dict):
2645                self.last = prefill_leg_stats(earlier_reads, self.last, len(ids))
2646            if holding:
2647                self.ctl.release()
2648            if admit_wait:
2649                with self.slot_cv:
2650                    self.admitting = max(0, self.admitting - 1)
2651            if reserved is not None and same:
2652                with self.slot_cv:
2653                    self.slot_busy[reserved] = False
2654                    self.slot_claims.discard(reserved)
2655                    self.slot_cv.notify_all()
2656            if slot is not None and same and not handed:
2657                self.slot_live[slot] = None
2658                self.slot_used[slot] = time.time()
2659                if phase == "slot" and bdone_in:
2660                    stream = list(prompt) + out[gen0:] if gen0 is not None and len(out) > gen0 else None
2661                    self.slot_held[slot] = stream[:-1] if stream else []     # as the BDONE wait leaves it
2662                    with self.slot_cv:
2663                        self.slot_busy[slot] = False
2664                        self.slot_claims.discard(slot)
2665                        self.slot_cv.notify_all()
2666                elif phase == "slot":
2667                    self.slot_held[slot] = []
2668                    stream = list(prompt) + out[gen0:] if gen0 is not None and len(out) > gen0 else None
2669                    self._release_slot_when_done(slot, stream, born)    # freed at its BDONE
2670                    self.slot_claims.discard(slot)                # (the BDONE wait owns it now)
2671                else:
2672                    with self.slot_cv:
2673                        self.slot_busy[slot] = False
2674                        self.slot_claims.discard(slot)
2675                        self.slot_cv.notify_all()
2676
2677    slot_groups = 1         # --batch-groups (set when the engine starts)
2678    SLOT_PREFIX_MIN = 512   # a held prefix shorter than this is not worth unbalancing the pipeline's groups
2679    BRANCH_BOUNDARY_MIN = 8192   # the engine's message-boundary checkpoint (STRATA_CACHE_MESSAGE_BOUNDARY) starts at this many tokens
2680    TURN_ID = 248045        # <|im_start|>: the engine's default --turn-token (its turn checkpoint sits at the last one)
2681
2682    def pick_slot(self, prompt: list[int]) -> int | None:
2683        """A free slot for `prompt` (the caller holds slot_cv): the one whose held tokens are the longest start of the
2684        prompt (the engine then reads only the rest), else an empty one, else the one used longest ago - so the
2685        conversations other slots hold stay for their next turns.  None: every slot is busy."""
2686        free = [b for b in self.slot_order if not self.slot_busy[b]]
2687        if not free:
2688            return None
2689        gs = getattr(self, "slot_gs", 0)
2690        if gs > 1:
2691            # pipelined groups of several slots: the engine keeps no idle slot below a busy one as a conversation cache
2692            # (its pad row writes the slot), so nothing is worth keeping free for a next turn.  A group's window spans
2693            # its slots up to its last busy one, so first fill a hole below a busy slot of the same group (it costs no
2694            # extra row), then follow the spreading order
2695            # (reported on #793: least-recently-used picks left leading holes, [_ B], that cost a whole row each)
2696            def fills_hole(b):
2697                g0 = b - b % gs
2698                return any(self.slot_busy[x] for x in range(b + 1, g0 + gs))
2699            return min(free, key=lambda b: (not fills_hole(b), self.slot_order.index(b)))
2700        agreed = {}
2701        def agree(b):
2702            # how many leading tokens slot b's held stream and the prompt share (slice compares: streams reach 100k tokens)
2703            if b not in agreed:
2704                h = self.slot_held[b]
2705                lo, hi = 0, min(len(h), len(prompt))
2706                while lo < hi:
2707                    mid = (lo + hi + 1) // 2
2708                    if h[:mid] == prompt[:mid]:
2709                        lo = mid
2710                    else:
2711                        hi = mid - 1
2712                agreed[b] = lo
2713            return agreed[b]
2714        def held_prefix(b):
2715            # what of `prompt` the slot's cache serves: the slot's whole held stream (the prompt and what it decoded)
2716            # when this prompt continues it, else its turn checkpoint - the engine takes one at the last <|im_start|> of
2717            # a prompt (the next request of the chat renders the history again, but not the reply it decoded or the
2718            # assistant header), so a prompt that agrees with the held tokens up to there is that chat's next turn
2719            # too (#2518: it was only found by the engine's own source search, after pick_slot had sent it to another
2720            # slot and the request in that slot had overwritten the chat whose cache the next one needed)
2721            h = self.slot_held[b]
2722            if not h:
2723                return 0
2724            if len(h) < len(prompt) and prompt[:len(h)] == h:
2725                return len(h)
2726            if self.TURN_ID not in h:
2727                return 0
2728            lo = agree(b)
2729            last = len(h) - 1 - h[::-1].index(self.TURN_ID)
2730            if 0 < last < len(prompt) and last <= lo:
2731                return last
2732            # a branch: the same history with the last question replaced agrees with the held stream only up to an
2733            # EARLIER message boundary, where the engine may hold a checkpoint of this chat
2734            # (STRATA_CACHE_MESSAGE_BOUNDARY, prefixes of at least BRANCH_BOUNDARY_MIN tokens).  The engine finds that
2735            # source itself but copies it into the slot chosen here, so another chat's slot would be overwritten (#2518).
2736            i = min(lo, len(prompt) - 1, last - 1)
2737            if i < self.BRANCH_BOUNDARY_MIN:
2738                return 0
2739            window = h[self.BRANCH_BOUNDARY_MIN:i + 1]
2740            if self.TURN_ID not in window:
2741                return 0
2742            i -= window[::-1].index(self.TURN_ID)
2743            # a boundary every other held conversation shares as well (the system prompt and tools of one client) says
2744            # nothing about whose it is: the old order (an empty slot, then the least recent one) keeps all chats
2745            if not any(agree(c) < i for c in range(self.batch) if c != b and self.slot_held[c]):
2746                return 0
2747            return i
2748        best = max(free, key=held_prefix)
2749        # without --batch-groups a held prefix of any length is taken, as before
2750        if held_prefix(best) >= (self.SLOT_PREFIX_MIN if self.slot_groups > 1 else 1):
2751            return best
2752        # with --batch-groups: the group with the fewest busy slots first, so the requests spread over the
2753        # pipeline's stages (two requests in one group leave the other stage idle); then empty, then least recent
2754        busy_in = {}
2755        for b in range(self.batch):
2756            if self.slot_busy[b]:
2757                busy_in[self.slot_group[b]] = busy_in.get(self.slot_group[b], 0) + 1
2758        return min(free, key=lambda b: (busy_in.get(self.slot_group[b], 0) if self.slot_groups > 1 else 0,
2759                                        bool(self.slot_held[b]), self.slot_used[b]))
2760
2761    def slots_view(self) -> list[dict]:
2762        """/metrics: each batch slot - idle (with the tokens it holds for a next turn), reading or decoding."""
2763        now, view = time.time(), []
2764        for b in range(self.batch):
2765            r = self.slot_live[b]
2766            if r is None:
2767                view.append({"slot": b, "state": "idle", "held_tokens": len(self.slot_held[b])})
2768                continue
2769            ft = r.get("first_token")
2770            view.append({"slot": b, "state": r["state"], "prompt_tokens": r["prompt_tokens"],
2771                         "prompt_read": r.get("prompt_read") if r["state"] == "reading" else None,
2772                         "generated": r["generated"], "elapsed_s": round(now - r["started"], 1),
2773                         "tok_s": round(r["generated"] / max(1e-6, now - ft), 1) if ft else None})
2774        return view
2775
2776    def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only=False):
2777        """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt):
2778        the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that
2779        has gone.  A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new."""
2780        if not self.alive():
2781            raise EngineDied("the engine is unavailable; this request was not sent")
2782        bias_api.validate_request(sampling or {}, self, None)
2783        refuse_for_split(self, sampling or {})
2784        if getattr(self, "batch", 0) and not self.multi:
2785            yield from self.generate_batched(ids, max_new, sampling, cancel, embeddings)
2786            return
2787        self.progress, self.progress_ms, self.reused = None, 0, 0
2788        self.prefill_tok_s_mean = None
2789        # DeepSeek --parallel: the engine holds several conversations; this request is one of them (GEN ... rid=<id>), its
2790        # lines come on a queue of their own and its STOP names it.  One at a time (self.multi 0): the one queue, as before.
2791        rid, lines_q, stop_line = None, self.lines, "STOP\n"
2792        if self.multi:
2793            with self.rid_lock:
2794                self.rid_n += 1
2795                rid = self.rid_n
2796            lines_q = queue.Queue()
2797            self.rid_q[rid] = lines_q
2798            stop_line = f"STOP {rid}\n"
2799        # logprobs: the engine writes "LP <logprob> [id:logprob ...]" right after each "T <id>" (the same
2800        # flush), read here before the token is yielded, so whoever takes the token finds its line in
2801        # lp_lines.  Not asked for = the deque stays empty and nothing on this path changes.
2802        want_lp = top_logprobs(sampling or {}) is not None
2803        self.lp_lines = LPLines(cancel)
2804        carry = NO_LINE                  # a line read for a token's LP line, held until it is used
2805        # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked)
2806        rid_key = f" rid={rid}" if rid is not None else ""
2807        head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})}{rid_key} {embeddings}" if embeddings else \
2808            f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}{rid_key}"
2809        if prefill_only:                                 # split serving (serve/split.py): read the prompt, make no token
2810            if embeddings or int(max_new) != 0:
2811                raise ValueError("prefill_only is a text prompt and max_new 0")
2812            head = f"GEN 0 prefill=1{rid_key}"
2813        try:
2814            if rid is not None:                          # several requests write to the engine at once
2815                self._send(f"{head} {','.join(str(int(t)) for t in ids)}")
2816            else:
2817                self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n")
2818                self.proc.stdin.flush()
2819        except (OSError, EngineDied):                    # the pipe is gone: the engine died (not the client)
2820            if rid is not None:
2821                self.rid_q.pop(rid, None)
2822            raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None
2823        done = False
2824        # #481: how long the engine may stay silent from here.  Until the first line: the request's first prompt
2825        # chunk at the slowest prompt reading on top of silence_s; a PP line resets it to its own chunk's time.
2826        silence = float(self.silence_s or 0)
2827        allow = silence + min(len(ids), PP_CHUNK_MAX) / PP_FLOOR_TOK_S if silence > 0 else 0.0
2828        heard, read_to = time.monotonic(), 0
2829        beat = heard
2830        stall_s = ENGINE_STALL_S or 0.0
2831        stall_state: dict = {}
2832        try:
2833            while True:
2834                wait = 10.0
2835                if allow > 0:
2836                    wait = min(wait, allow - (time.monotonic() - heard))
2837                    if wait <= 0:
2838                        done = True                       # no STOP and no drain: nothing is listening
2839                        raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during "
2840                                           "the request")
2841                try:
2842                    if carry is not NO_LINE:              # the line read after a token for its LP line
2843                        line, carry = carry, NO_LINE
2844                    else:
2845                        line = lines_q.get(timeout=min(wait, 0.5))
2846                except queue.Empty:
2847                    if cancel.is_set():
2848                        return
2849                    if stall_s > 0:
2850                        try:
2851                            self._stall_check(heard, stall_state, stall_s)
2852                        except EngineSilent:
2853                            done = True                   # as above: nothing is listening
2854                            raise
2855                    if allow > 0 and time.monotonic() - heard >= allow:
2856                        continue                          # enforce the expired deadline before another heartbeat
2857                    if time.monotonic() - beat >= 10.0:
2858                        beat = time.monotonic()
2859                        yield None                        # polling cancellation does not add HTTP heartbeats
2860                    continue
2861                if line is None:
2862                    done = True
2863                    raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
2864                heard = time.monotonic()                  # any line is output: T, PP, RESUME, INFO ...
2865                beat = heard
2866                if stall_state:
2867                    stall_state.clear()
2868                if line.startswith("T "):
2869                    allow = silence
2870                    if cancel.is_set():
2871                        return
2872                    t = int(line[2:])
2873                    if want_lp:
2874                        # the engine writes the token and its `LP` line in one flush, so the line is
2875                        # here now; an engine without logprobs leaves the next line a normal one
2876                        try:
2877                            carry = lines_q.get(timeout=0.5)
2878                        except queue.Empty:
2879                            carry = NO_LINE
2880                        if isinstance(carry, str) and carry.startswith("LP "):
2881                            self.lp_lines.append((t, carry))
2882                            carry = NO_LINE
2883                    yield t
2884                elif line.startswith("PP "):
2885                    f = line.split()
2886                    if len(f) >= 3 and f[1].isdigit() and f[2].isdigit():
2887                        self.progress = (int(f[1]), int(f[2]))             # prompt progress, one per chunk: also a heartbeat (the
2888                        self.progress_ms = float(f[3]) if len(f) >= 4 else 0.0
2889                        self.prefill_tok_s_mean = float(f[4]) if len(f) >= 5 else None
2890                        rate, chunk = self.prefill_tok_s_mean or 0.0, int(f[1]) - read_to
2891                        read_to = int(f[1])
2892                        if silence > 0 and rate > 0 and chunk > 0:   # #481: the next chunk, as long as this one
2893                            allow = max(silence, PP_SLACK * chunk / rate)
2894                    if cancel.is_set():                   # lines reset the 10 s wait, so without this a long prompt
2895                        return                            # would send no keep-alives at all)
2896                    yield None
2897                elif line.startswith("RESUME "):          # the reused tokens: the first chunk starts after them
2898                    try:
2899                        read_to = self.reused = int(line.split()[1])
2900                    except (IndexError, ValueError):
2901                        pass
2902                elif line.startswith("DONE"):
2903                    self._parse_done(line)
2904                    done = True
2905                    if self.last.get("finish") == "nonfinite":   # #879
2906                        raise EngineNonFinite("the engine's logits became non-finite (#879)")
2907                    return
2908                elif line.startswith("ERR"):
2909                    done = True
2910                    self._raise_if_fatal_gpu(line)
2911                    self._swallow_trailing_done(lines_q)  # an engine that ended the request on ERR may still print its DONE
2912                    raise ValueError(line[4:].strip())
2913        finally:
2914            if not done:                                  # the consumer stopped early: stop the engine, drain to DONE
2915                # the engine can be ended or restarted on another thread meanwhile: Engine.close() closes stdin (a
2916                # write then raises ValueError) before it clears `proc` (None then) - the STOP has nobody to reach, and
2917                # the request's own outcome must not be replaced by that error
2918                proc = self.proc
2919                if self.can_stop and proc is not None:
2920                    try:
2921                        proc.stdin.write(stop_line)
2922                        proc.stdin.flush()
2923                    except (OSError, ValueError):
2924                        pass
2925                # #481: never an untimed wait here - it holds the request FIFO, and an engine that lost step never
2926                # answers.  An engine that honours STOP gets the current allowance in all (a STOP during a prompt
2927                # chunk is seen after it); an older one runs on to max_new, so each line only has to come in time.
2928                heard = time.monotonic()
2929                while True:
2930                    left = allow - (time.monotonic() - heard) if allow > 0 else None
2931                    try:
2932                        if carry is not NO_LINE:          # read already, after the last token
2933                            line, carry = carry, NO_LINE
2934                        elif left is not None and left <= 0:
2935                            raise queue.Empty
2936                        else:
2937                            line = lines_q.get(timeout=left)
2938                    except queue.Empty:
2939                        raise self._silent("the engine did not finish the request after it was stopped (STOP) "
2940                                           f"within {allow:.0f} s") from None
2941                    if line is None or line.startswith("ERR"):
2942                        break
2943                    if line.startswith("DONE"):
2944                        self._parse_done(line)
2945                        break
2946                    if not self.can_stop:
2947                        heard = time.monotonic()
2948            if rid is not None:                           # this request's lines are over (a late one goes nowhere)
2949                self.rid_q.pop(rid, None)
2950
2951    @staticmethod
2952    def _swallow_trailing_done(lines_q, wait: float = 0.3) -> None:
2953        """A request that ends on `ERR ...` is over, but an engine that also prints the request's `DONE` after it (the DeepSeek
2954        engine did, after its NaN stop) would hand that DONE to the NEXT request as its own: 0 tokens at once, and every answer
2955        after it one request late.  So a short wait for a trailing DONE (or ERR) of the same request, taken off the queue and
2956        dropped, before the request is reported failed and the FIFO released.  An engine that prints only the ERR costs the wait."""
2957        end = time.monotonic() + wait
2958        while True:
2959            left = end - time.monotonic()
2960            if left <= 0:
2961                return
2962            try:
2963                late = lines_q.get(timeout=left)
2964            except queue.Empty:
2965                return
2966            if late is None or late.startswith(("DONE", "ERR")):
2967                return
2968
2969    def _activity(self) -> tuple[float, int] | None:
2970        """#1317: (CPU seconds, I/O bytes) the engine process has used so far, or None when they cannot be read."""
2971        try:
2972            import psutil
2973            pr = psutil.Process(self.proc.pid)
2974            t = pr.cpu_times()
2975            io = pr.io_counters()
2976            return (t.user + t.system, io.read_bytes + io.write_bytes)
2977        except Exception:  # noqa: BLE001 - psutil missing, the process gone, no permission: no reading
2978            return None
2979
2980    def _stall_check(self, heard: float, state: dict, stall_s: float) -> None:
2981        """#1317: called while the engine is silent.  Takes a baseline soon after the last line, and at stall_s of silence
2982        compares: no CPU and no I/O in all that time -> the engine is ended (EngineSilent); work going on -> one warning."""
2983        age = time.monotonic() - heard
2984        if state.get("base") is None:
2985            state["base"] = self._activity()
2986            return
2987        if age < state.get("next", stall_s) or state["base"] is None:
2988            return
2989        now = self._activity()
2990        try:
2991            gpu_working = bool(self.gpu_busy()) if self.gpu_busy is not None else False
2992        except Exception:  # noqa: BLE001 - a telemetry hiccup must not decide anything
2993            gpu_working = False
2994        if now is not None and not gpu_working and engine_frozen(state["base"], now):
2995            raise self._silent(f"the engine said nothing for {age:.0f} s and used no CPU or disk in that time (frozen; "
2996                               "STRATA_ENGINE_STALL_S sets this, 0 = off)")
2997        if now is not None:   # working: look again after another window from here, and say so once
2998            state["base"], state["next"] = now, age + stall_s
2999            if not state.get("warned"):
3000                state["warned"] = True
3001                print(f"[strata] the engine has said nothing for {age:.0f} s but is still working; it is not ended (the "
3002                      "limit is engine_silence_s). If it is stuck, \"engine_silence_s\" can be set lower.", flush=True)
3003        else:
3004            state["next"] = float("inf")   # no reading (psutil missing): nothing to decide on
3005
3006    def _silent(self, what: str) -> EngineSilent:
3007        """#481: end an engine that lost step with the server (its main thread waits for a command the server never
3008        sends), so the next request starts it again: killed now, its GPU and RAM go back with the process."""
3009        self.silent_note = ("The engine and the server lost step (issue #481; a very slow PC can raise "
3010                            "\"engine_silence_s\" in the config, 0 = wait forever). If it happens again, please add "
3011                            "the end of the engine log to github.com/Niko1221/Strata/issues/481.")
3012        self.ended = True                               # not alive from now: the next request restarts it
3013        proc = self.proc
3014        try:
3015            proc.kill()
3016            proc.wait(timeout=20)                       # restart() -> close() handles one that is still exiting
3017        except (OSError, AttributeError, subprocess.TimeoutExpired):
3018            pass
3019        return EngineSilent(f"{what}; the server ended the engine")
3020
3021    def end_for_restart(self) -> None:
3022        """End the engine now and mark it ended, so the next request starts it again (#3961: a run that stopped without its end event left the two sides
3023        out of step; the restart is what puts them back)."""
3024        self.ended = True
3025        try:
3026            self.proc.kill()
3027            self.proc.wait(timeout=20)
3028        except (OSError, AttributeError, subprocess.TimeoutExpired):
3029            pass
3030
3031    def session_file(self, action: str, path: str) -> dict:
3032        with self._exclusive_control():
3033            return self._session_file(action, path)
3034
3035    def _session_file(self, action: str, path: str) -> dict:
3036        """Disk sessions: `SAVE <path>` / `RESTORE <path>` between requests (the caller holds the service FIFO).
3037        -> {"tokens", "bytes", "ms"}.  SessionRefused (kind, published) when the engine refused or failed the file and
3038        is still in step (`SERR <kind> <0|1> <reason>`).  Any line this exchange does not allow - an unknown or
3039        malformed one, a bare ERR, an answer with negative counts or a non-finite time - means the two sides lost
3040        step: the engine is ended (EngineDied) and the next request starts it again.  EngineDied also when it ended
3041        by itself (a restore transfer that failed after the device state changed ends it on purpose: FATAL), and
3042        EngineSilent (#481) when it printed nothing valid for engine_silence_s - a SESSION progress line (one per
3043        block of the file moved, at most 16 MiB) counts only when its numbers are.  `SWAIT <phase> <seconds>` announces
3044        a step that blocks in one call (a flush, the device transfer): until the next line the wait is that step's
3045        explicit allowance (at most SESSION_WAIT_MAX_S) when it is longer than engine_silence_s - no more, so a step
3046        that never ends is still ended."""
3047        if action not in ("save", "restore") or any(c in path for c in "\r\n\0"):
3048            raise ValueError("invalid session command")
3049        try:
3050            self.proc.stdin.write(f"{'SAVE' if action == 'save' else 'RESTORE'} {path}\n")
3051            self.proc.stdin.flush()
3052        except OSError:
3053            raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None
3054        silence = float(self.silence_s or 0)
3055        heard = time.monotonic()
3056        want = "SAVED" if action == "save" else "RESTORED"
3057
3058        def out_of_step(line: str) -> EngineDied:
3059            self.ended = True                               # not alive from now: the next request restarts it
3060            try:
3061                self.proc.kill()
3062                self.proc.wait(timeout=20)
3063            except (OSError, AttributeError, subprocess.TimeoutExpired):
3064                pass
3065            return EngineDied(f"the engine answered a session {action} with {line.strip()[:200]!r}; "
3066                              "the server ended the engine")
3067
3068        def count(s: str) -> int:
3069            if not s.isdigit():                             # no sign, no blank, no fraction
3070                raise ValueError
3071            return int(s)
3072
3073        last_done = -1
3074        allow = 0.0                                         # the announced blocking step's allowance, seconds
3075        while True:
3076            limit = max(silence, allow)
3077            left = limit - (time.monotonic() - heard) if silence > 0 else None
3078            try:
3079                if left is not None and left <= 0:
3080                    raise queue.Empty
3081                line = self.lines.get(timeout=left)
3082            except queue.Empty:
3083                raise self._silent(f"the engine said nothing for {limit:.0f} s during a session {action}"
3084                                   + (f" (in a blocking step allowed {allow:.0f} s)" if allow > silence else "")) from None
3085            if line is None:
3086                raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
3087            f = line.split()
3088            head = f[0] if f else ""
3089            if head == "SESSION":                          # a large file moving: progress, and a heartbeat
3090                try:
3091                    if len(f) != 3:
3092                        raise ValueError
3093                    done, total = count(f[1]), count(f[2])
3094                    if done > total or done < last_done:
3095                        raise ValueError
3096                except ValueError:
3097                    raise out_of_step(line) from None
3098                last_done = done
3099                heard, allow = time.monotonic(), 0.0
3100                continue
3101            if head == "SWAIT":                            # a blocking step starts: its bounded allowance
3102                try:
3103                    if len(f) != 3 or not f[1].isalpha() or not f[1].isascii():
3104                        raise ValueError
3105                    seconds = count(f[2])
3106                    if not 0 < seconds <= SESSION_WAIT_MAX_S:
3107                        raise ValueError
3108                except ValueError:
3109                    raise out_of_step(line) from None
3110                heard, allow = time.monotonic(), float(seconds)
3111                continue
3112            if head == "FATAL":
3113                raise EngineDied(line[6:].strip() or "the engine ended during a session restore")
3114            if head == "SERR":
3115                parts = line.rstrip("\r\n").split(" ", 3)
3116                if len(parts) != 4 or parts[1] not in SessionRefused.STATUS or parts[2] not in ("0", "1"):
3117                    raise out_of_step(line)
3118                raise SessionRefused(parts[1], parts[3].strip(), parts[2] == "1")
3119            if head == want:
3120                try:
3121                    if len(f) != 4:
3122                        raise ValueError
3123                    tokens, size, ms = count(f[1]), count(f[2]), float(f[3])
3124                    if not math.isfinite(ms) or ms < 0:
3125                        raise ValueError
3126                except ValueError:
3127                    raise out_of_step(line) from None
3128                return {"tokens": tokens, "bytes": size, "ms": ms}
3129            if head == "INFO" or head == "WARN":          # engine log lines may interleave; they are not answers
3130                heard = time.monotonic()
3131                continue
3132            raise out_of_step(line)
3133
3134    def close(self):
3135        """End the engine process: STOP + QUIT first (the engine frees its memory itself - unpinning tens of GB can take
3136        a while; ENGINE_QUIT_WAIT_S), then terminate (ENGINE_TERM_WAIT_S), then kill (ENGINE_KILL_WAIT_S).  Raises
3137        EngineStuck when it still runs after all three."""
3138        if self.proc is None:
3139            return
3140        try:
3141            if self.proc.poll() is None:
3142                try:
3143                    # STOP first: a request still running ends at its next step instead of being waited for (the
3144                    # engine reads stdin on its own thread; QUIT behind a long answer would sit in its queue)
3145                    self.proc.stdin.write("STOP\nQUIT\n")
3146                    self.proc.stdin.flush()
3147                    self.proc.stdin.close()  # Windows' detached stdin reader must see EOF before shutdown
3148                    self.proc.wait(timeout=ENGINE_QUIT_WAIT_S)
3149                except (OSError, ValueError, subprocess.TimeoutExpired):
3150                    self.proc.terminate()
3151                    self.proc.wait(timeout=ENGINE_TERM_WAIT_S)
3152        except subprocess.TimeoutExpired:
3153            self.proc.kill()
3154            try:
3155                self.proc.wait(timeout=ENGINE_KILL_WAIT_S)
3156            except subprocess.TimeoutExpired:
3157                raise EngineStuck("Strata is still releasing GPU/RAM; retry unloading after it exits") from None
3158        except OSError:
3159            pass
3160        finally:
3161            if self.proc.poll() is not None:
3162                if self.pump is not None and self.pump.ident is not None:   # a restart can stop before starting it
3163                    self.pump.join(timeout=2)
3164                try:
3165                    self.proc.stdin.close()             # buffered data may flush again after the engine has exited
3166                except OSError:
3167                    pass
3168                self.proc.stdout.close()
3169                if self.log not in (None, subprocess.DEVNULL):
3170                    self.log.close()
3171                self.proc = None
3172                self.ended = True
3173                self.progress, self.last = None, {}
3174                self.progress_ms, self.reused = 0, 0
3175
3176
3177IMAGE_URL_MAX = 32 << 20        # an image URL is read up to this (the web app attaches pictures of up to 20 MB)
3178
3179
3180def network_path(path: str) -> bool:
3181    r"""A path to another computer: \\host\share or //host/share (either slash), \\?\UNC\host\..., \\.\UNC\host\...
3182    or the NT form \??\UNC\host\...  Windows connects to that host at the first look at the path (os.path.isfile is
3183    enough) and signs in with the user's NTLM credentials.  \\?\ and \??\ name local files too; no client needs them."""
3184    p = path.replace("/", "\\")
3185    return p.startswith("\\\\") or p.startswith("\\??\\")
3186
3187
3188def vision_log_size(log=None) -> int:
3189    """How long the encoder's stderr file is now (0 when there is none): a start reads only what it wrote after this."""
3190    try:
3191        name = getattr(log, "name", None)
3192        return os.path.getsize(name) if name else 0
3193    except (OSError, TypeError):
3194        return 0
3195
3196
3197def vision_log_tail(log=None, limit: int = 16384, since: int = 0) -> str:
3198    """The last `limit` bytes of the encoder's stderr file (`log` is the file object it was started with; "" when there
3199    is none or it cannot be read), but nothing from before `since` (the file's size when this start began: a log that several starts share)."""
3200    try:
3201        name = getattr(log, "name", None)
3202        if name:
3203            with open(name, "rb") as f:
3204                f.seek(0, 2)
3205                f.seek(max(since, f.tell() - limit))
3206                return f.read().decode("utf-8", "replace")
3207    except (OSError, ValueError):
3208        pass
3209    return ""
3210
3211
3212# What the CUDA / HIP runtimes print when the reader has no code for the card it runs on (a binary built without that
3213# architecture: #3669, the Windows cuda12 package's reader on a Pascal card).
3214_VISION_ARCH_SIGNS = ("device kernel image is invalid", "no kernel image is available", "im2col failed",
3215                      "unsupported gpu architecture", "invalid device function", "unknown gpu architecture")
3216
3217
3218def vision_start_error(line: str, log=None, code: int | None = None, waited: float | None = None, strays=(), since: int = 0) -> str:
3219    """The message when the image encoder answered something other than READY.  #1445: a card in the Exclusive_Process
3220    compute mode (or one another process holds) refuses the encoder's CUDA context with "busy or unavailable"; that
3221    cause is named instead of leaving the user the first line of a traceback.  `log` is the encoder's stderr file, whose
3222    tail is searched too (the CUDA error is printed there).  An encoder that dies before it prints anything (#3645, #3444,
3223    #3669, #3697) used to give a blank sentence: now the last lines of its stderr, its exit status (`code`) and, for a
3224    kernel-image error, the card/architecture hint come with it.  `waited`: it said nothing for that many seconds.  `strays`: lines it printed on
3225    its output before it ended that were not an answer (a debugger's, a library's); they are searched for the causes below and named in the message."""
3226    text = line.strip()
3227    tail = vision_log_tail(log, since=since)
3228    both = (text + chr(10) + chr(10).join(strays) + chr(10) + tail).lower()
3229    if "busy or unavailable" in both:
3230        return ("the vision encoder did not start: the GPU refused a second CUDA context (\"CUDA-capable device(s) "
3231                "is/are busy or unavailable\"). This is usually the compute mode Exclusive_Process: only one process "
3232                "may use the card, and the engine already holds it. Check with: nvidia-smi --query-gpu=compute_mode "
3233                "--format=csv; set it back with: sudo nvidia-smi -c DEFAULT (or run the encoder on another card). "
3234                "First line from the encoder: " + (text or "(none)"))
3235    lines = [x.strip() for x in tail.splitlines() if x.strip()]
3236    room = reader_room.find((text + chr(10) + chr(10).join(strays) + chr(10) + tail).splitlines())
3237    if room:                                           # a card another program filled: ggml's cudaMalloc line, then an abort the reader cannot answer for
3238        asked = (f" (it asked for {room.need_mib:.0f} MiB" + (f" on its card {room.device}" if room.device is not None else "") + ")") if room.need_mib else ""
3239        said = [text, *strays, *lines]
3240        evidence = (next((x for x in reversed(said) if "malloc failed" in x.lower()), None)
3241                    or next((x for x in reversed(said) if "failed to allocate" in x.lower()), text))
3242        return "the vision encoder did not start: the graphics card has no room for it" + asked + ". From the encoder: " + evidence.strip()[:300]
3243    if any(sign in both for sign in _VISION_ARCH_SIGNS):
3244        evidence = next((x for x in reversed(lines) if any(sign in x.lower() for sign in _VISION_ARCH_SIGNS)), text)
3245        return ("the vision encoder did not start: it has no code for this graphics card (a kernel-image error: the "
3246                "picture reader in this engine package was built for other card generations than yours). Update the "
3247                "engine, or read pictures on the CPU (Models, Read pictures, Image encoder device: CPU; or run setup "
3248                "again with --vision cpu). From the encoder: " + evidence[:300])
3249    if text:
3250        msg = "the vision encoder did not start: " + text
3251    elif waited is not None:
3252        msg = f"the vision encoder did not start: it said nothing for {waited:g} s (it never reported READY)"
3253    else:
3254        msg = "the vision encoder did not start: it ended without saying anything"
3255    extra = []
3256    if code is not None:
3257        words = engine_exit_words(code)
3258        if words:
3259            extra.append(words)
3260    if strays:
3261        extra.append("it also printed on its output: " + " | ".join(x[:120] for x in list(strays)[-3:]))
3262    shown = [x for x in lines[-3:] if x != text]
3263    if shown:
3264        extra.append("last lines of its log: " + " | ".join(x[:200] for x in shown))
3265    if extra:
3266        msg += " (" + "; ".join(extra) + ")"
3267    return msg
3268
3269
3270def card_free_mib(index: int | None, amd: bool = False) -> int | None:
3271    """Free memory of one card in MiB, from the backend's reader (NVML, the amdgpu files); None when it cannot be read (nothing is refused for that)."""
3272    try:
3273        from serve.telemetry import gpu_reader
3274        g = gpu_reader(int(index or 0), amd=amd)
3275        if not g.ok():
3276            return None
3277        r = g.read()
3278        if r.get("mem_total") is None or r.get("mem_used") is None:
3279            return None
3280        return int((r["mem_total"] - r["mem_used"]) >> 20)
3281    except Exception:                                  # noqa: BLE001
3282        return None
3283
3284
3285class VisionNoRoom(RuntimeError):
3286    """The picture reader could not start because its card has no room for it (`room`: strata_control.reader_room.NoRoom)."""
3287
3288    def __init__(self, message: str, room):
3289        super().__init__(message)
3290        self.room = room
3291
3292
3293class Vision:
3294    """The resident image encoder: `strata-vision` (llama.cpp mtmd + the mmproj file) reads `ENC <image> <out>`
3295    lines and writes each image's embeddings; results are cached by the image's hash, so a conversation that
3296    sends the same picture again (every turn, with most clients) encodes it once."""
3297
3298    @staticmethod
3299    def work_dir() -> Path:
3300        """#480: the directory for the encoder's files.  The engine reads the embeddings file named in a `GENI` line
3301        and the encoder the output named in an `ENC <image> <out>` line, both split at spaces, so a space in the path
3302        (a %TEMP% under a user name with a space) broke every image.  The system temp directory is used while its path
3303        has no space, then the working directory, then the system drive's root; the plain temp directory is the last
3304        resort (the encoder's own files are then named relative to it, see `_start`)."""
3305        for parent in (None, Path.cwd(), Path(os.environ.get("SystemDrive", "C:") + os.sep)):
3306            try:
3307                d = Path(tempfile.mkdtemp(prefix="strata-vision-", dir=parent))
3308            except OSError:
3309                continue                                       # not writable, or no such drive
3310            if " " not in str(d):
3311                return d
3312            try:
3313                d.rmdir()                                      # just created, so still empty
3314            except OSError:
3315                pass
3316        return Path(tempfile.mkdtemp(prefix="strata-vision-"))
3317
3318    def __init__(self, cfg: dict, log=None, env: dict | None = None, lazy: bool = False):
3319        args = self.reader_args(cfg)
3320        self.dir = self.work_dir()
3321        self.spawn = (args, log, env)                   # to start it again after an unload
3322        # AMD: the GPU reader (strata-vision-hip) has the CPU reader (strata-vision, same program, no GPU runtime) to
3323        # fall back on when it does not start; _start switches to it by itself
3324        # the NVIDIA reader (strata-vision) is the CPU reader too, without --gpu: a GPU reader that does not start, resident or on demand, reads on the
3325        # processor instead of ending the launch (owner, 2026-11-10); the person's image limit stays
3326        cpu = vision_reader.cpu_fallback(cfg, same_program=True)
3327        self.fallback = (self.reader_args(cpu), log, env) if cpu else None
3328        self.gpu_spawn, self.cpu_spawn = self.spawn, self.fallback   # an on-demand reader tries the GPU one again at every start
3329        self.on_cpu = False                             # the CPU reader is what runs (the GPU one did not start, or there was no room)
3330        self.cpu_note = None                            # why, in words for the person (strata_control/reader_room.py), when the card had no room
3331        self.reader = None                              # "own" (Strata's) or "mtmd" (llama.cpp's) from the READY line; None for an older reader
3332        self.proc = None
3333        self.stopped = True
3334        self.lock = threading.Lock()
3335        self.cache: dict[str, tuple[Path, int]] = {}
3336        # opt-in (the vision section's "elastic": true, with the config's "vram_elastic"): the encoder starts with the
3337        # first picture and stops after elastic_idle_s without one; while it runs, the engine's expert cache keeps
3338        # elastic_mib of VRAM free for it (Service._vision_up / _vision_idle_down)
3339        self.max_tokens = self.token_limit(cfg)
3340        self.elastic = cfg.get("elastic") is True
3341        self.elastic_mib = self.elastic_ask_mib(cfg, self.max_tokens)
3342        self.elastic_idle_s = float(cfg.get("elastic_idle_s") or 120)
3343        if not lazy and not self.elastic:
3344            self._start()
3345
3346    # What a picture may become when the config does not say (setup writes the same numbers, setup.VISION): an old, hand-edited or migrated
3347    # config without vision.max_tokens left the reader unclamped, and #3690 saw one picture become 93,700 image tokens (I7).  A key that is
3348    # there is the person's: 0 means no limit, as before.
3349    DEFAULT_MAX_TOKENS = {"gpu": 1024, "cpu": 300}
3350
3351    @staticmethod
3352    def elastic_ask_mib(cfg: dict, max_tokens: int) -> int:
3353        """The VRAM the expert cache keeps free for an elastic reader: the config's elastic_mib when the person set one, else the reader's
3354        need at its image limit (strata_control/reader_room.py; 0 = no limit counts as 16,384), never below 2,048.  At the default limit of
3355        1,024 tokens that is 2,048; at 16,384 it is 3,674 (a 2,048 ask left the encoder out of memory for one large picture on an RTX A6000)."""
3356        if cfg.get("elastic_mib"):
3357            return int(cfg["elastic_mib"])
3358        return max(2048, math.ceil(reader_room.reader_needs_mib(max_tokens)))
3359
3360    @staticmethod
3361    def token_limit(cfg: dict) -> int:
3362        """The --max-tokens of a reader config: its max_tokens, else the default of its kind (GPU 1024, CPU 300)."""
3363        if cfg.get("max_tokens") is not None:
3364            try:
3365                return max(0, int(cfg["max_tokens"]))
3366            except (TypeError, ValueError):
3367                pass
3368        return Vision.DEFAULT_MAX_TOKENS["gpu" if cfg.get("gpu") else "cpu"]
3369
3370    @staticmethod
3371    def reader_args(cfg: dict) -> list:
3372        absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p   # the encoder runs in its own dir (#480)  # noqa: E731
3373        args = [absolute(cfg["exe"]), "--mmproj", absolute(cfg["mmproj"]), "--model", absolute(cfg["model"])]
3374        if cfg.get("gpu"):
3375            args.append("--gpu")
3376        if cfg.get("threads"):
3377            args += ["--threads", str(cfg["threads"])]
3378        limit = Vision.token_limit(cfg)
3379        if limit:
3380            args += ["--max-tokens", str(limit)]
3381        if cfg.get("min_tokens"):                       # #767: mtmd's image_min_tokens (a hand-edited key)
3382            args += ["--min-tokens", str(cfg["min_tokens"])]
3383        return args
3384
3385    def _ensure_dir(self):
3386        """#3370: a temp cleaner (Windows Storage Sense) removes the empty work folder while the encoder is unloaded; the next
3387        start then failed with WinError 267 for as long as the server lived.  Make it again; pictures cached in it are gone."""
3388        if not self.dir.is_dir():
3389            self.dir.mkdir(parents=True, exist_ok=True)
3390            self.cache.clear()
3391
3392    def _start(self):
3393        """Start the reader.  When a GPU reader that has a CPU reader to fall back on does not start (the GPU runtime does not
3394        load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line
3395        and no question."""
3396        try:
3397            self._start_gpu_reader()
3398        except (RuntimeError, OSError) as e:
3399            fallback = getattr(self, "fallback", None)
3400            if fallback is None:
3401                raise
3402            why = " ".join(str(e).split())[:240]
3403            again = " until it is idle" if getattr(self, "elastic", False) else ""
3404            self.cpu_note = self.no_room_note(e.room) if isinstance(e, VisionNoRoom) else self.not_started_note()
3405            print(f"[strata] the GPU picture reader did not start ({why}); pictures are read on the CPU{again}", flush=True)
3406            self.spawn, self.fallback, self.on_cpu = fallback, None, True
3407            self._start_reader()
3408
3409    def _start_gpu_reader(self):
3410        """`_start_reader`, tried again when the start failed in the GPU context itself on a Linux Arm machine with shared memory (DGX Spark; see
3411        vision_reader.retry_gpu_start): a new spawn may start while less than CONTEXT_RETRY_BUDGET_S have passed since the first one started, at most CONTEXT_RETRIES
3412        times, CONTEXT_RETRY_WAIT_S apart.  Every other start, and the last failure, are `_start_reader`'s as before (the CPU reader follows in `_start`).
3413        STRATA_VIT_PROF=1 (the reader's diagnostic switch) prints the retry count and the time of a start that needed one."""
3414        args, log, _env = self.spawn
3415        retries = 0
3416        first = time.monotonic()                      # the first spawn's start: a new spawn may start only within vision_reader.CONTEXT_RETRY_BUDGET_S of it
3417        prof = bool(os.environ.get("STRATA_VIT_PROF"))
3418        while True:
3419            since = vision_log_size(log)
3420            try:
3421                res = self._start_reader()
3422                if prof and retries:
3423                    print(f"vit-prof: GPU reader started after {retries} retries, {time.monotonic() - first:.2f} s", flush=True)
3424                return res
3425            except (RuntimeError, OSError) as e:
3426                text = str(e) + chr(10) + vision_log_tail(log, since=since)
3427                if not vision_reader.retry_gpu_start(linux=sys.platform.startswith("linux"), arm=platform.machine().lower() in ("aarch64", "arm64"),
3428                                                     hip="hip" in Path(str(args[0])).name.lower(), text=text, retries_done=retries,
3429                                                     next_start_s=time.monotonic() - first + vision_reader.CONTEXT_RETRY_WAIT_S):
3430                    if prof and retries:
3431                        print(f"vit-prof: GPU reader did not start after {retries} retries, {time.monotonic() - first:.2f} s", flush=True)
3432                    raise
3433                retries += 1
3434                time.sleep(vision_reader.CONTEXT_RETRY_WAIT_S)
3435
3436    def no_room_note(self, room) -> str:
3437        """The sentence for the person when the card had no room for the reader and the processor reads instead: which card (as nvidia-smi numbers it), what
3438        the reader needed, what is free now that it is gone."""
3439        amd, visible = self.visible_cards()
3440        card = reader_room.physical_card(room.device, visible)
3441        need = reader_room.whole_need_mib(room.need_mib, getattr(self, "max_tokens", None))       # the reader's whole need at its limit, not the one allocation that failed
3442        return reader_room.on_processor(card, need, card_free_mib(card, amd) if card is not None else None)
3443
3444    def not_started_note(self) -> str:
3445        """The sentence for the person when the GPU reader did not start for any other reason and the processor reads instead: the card it would have used
3446        (the first one it is shown), and where the reason is (the engine log, which is the reader's stderr)."""
3447        _amd, visible = self.visible_cards()
3448        card = None if sys.platform == "darwin" else reader_room.physical_card(0, visible)       # a Mac has no numbered cards
3449        return reader_room.not_started_on_processor(card, getattr(self.spawn[1], "name", None))
3450
3451    def visible_cards(self):
3452        """(is it the AMD reader, the cards its environment shows it: CUDA_VISIBLE_DEVICES / HIP_VISIBLE_DEVICES or None)."""
3453        args, _log, env = self.spawn
3454        amd = "hip" in Path(str(args[0])).name.lower()
3455        return amd, (env if env is not None else os.environ).get("HIP_VISIBLE_DEVICES" if amd else "CUDA_VISIBLE_DEVICES")
3456
3457    def use_cpu(self) -> bool:
3458        """The next start is the CPU reader's (the card has no room for the GPU one): False when there is no CPU reader to use."""
3459        if self.fallback is None:
3460            return False
3461        self.spawn, self.fallback, self.on_cpu = self.fallback, None, True
3462        return True
3463
3464    def _start_reader(self):
3465        args, log, env = self.spawn
3466        self._ensure_dir()
3467        # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line)
3468        since = vision_log_size(log)                      # this start's own lines of a log that earlier starts wrote to as well
3469        self.proc = popen("the image encoder", args, role="vision", stdin=subprocess.PIPE, stdout=subprocess.PIPE,
3470                          stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", bufsize=1,
3471                          env=env, cwd=self.dir)
3472        strays: list[str] = []
3473        try:
3474            line = self._await_ready(VISION_READY_S, strays)
3475        except RuntimeError as e:                       # silent for VISION_READY_S: it was ended, and it is not left half-started
3476            self.proc, self.stopped = None, True
3477            if VISION_READY_S:
3478                raise RuntimeError(vision_start_error("", log, waited=VISION_READY_S, strays=strays, since=since)) from None
3479            raise RuntimeError(str(e)) from None
3480        if not line.startswith("READY"):
3481            proc, self.proc = self.proc, None
3482            self.stopped = True
3483            code = proc.poll() if hasattr(proc, "poll") else None   # an encoder that died by itself has its status already
3484            try:
3485                proc.kill()
3486                proc.wait(timeout=5)
3487            except (OSError, subprocess.TimeoutExpired):
3488                pass
3489            if code is None:
3490                code = getattr(proc, "returncode", None)
3491            message = vision_start_error(line, log, code, strays=strays, since=since)
3492            room = reader_room.find((line + chr(10) + chr(10).join(strays) + chr(10) + vision_log_tail(log, since=since)).splitlines())
3493            raise (VisionNoRoom(message, room) if room else RuntimeError(message))
3494        self.stopped = False
3495        # "READY <n_embd> <reader> [fallback]": the reader that runs (own: Strata's, mtmd: llama.cpp's; an older strata-vision says only "READY <n_embd>"),
3496        # and "fallback" when Strata's reader did not start and llama.cpp's took its place (strata-vision wrote the reason to the log)
3497        words = line.split()
3498        self.reader = words[2] if len(words) > 2 else None
3499        if "fallback" in words[3:]:
3500            print("[strata] Strata's picture reader did not start; pictures are read with llama.cpp's reader. Details are in the log.", flush=True)
3501
3502    #: how long a reader that has already ended may still hold its output pipe open (a debugger attached to it, a child it started) before the start is
3503    #: judged: the pipe's end does not come, the process's end is what counts.
3504    READY_GRACE_S = 2.0
3505    #: lines kept from a reader's output before its answer (and written to the log): enough to see what it said, not a flood
3506    STRAY_KEEP = 20
3507
3508    def _await_ready(self, timeout: float | None, strays: list) -> str:
3509        """The reader's answer to its start: "READY ..." or "ERR ..." (what strata-vision prints on stdout; everything else it says goes to stderr),
3510        or "" when it has ended.  Any other line on stdout is a stray line - a debugger a crashing reader started, a library's banner - and is not an
3511        answer: it is kept in `strays` (the last STRAY_KEEP), written to the log, and the wait goes on.  A reader that is only printing is never killed.
3512        The wait has ONE deadline of `timeout` s (None: for ever); on it the reader is killed and the read raises RuntimeError, as `_readline` does.  A
3513        reader whose process has ended while a debugger or a child still holds its pipe open counts as ended after READY_GRACE_S.  The thread that
3514        reads stops at the answer, so the encode answers that follow are never taken by it."""
3515        proc = self.proc
3516        got: queue.Queue = queue.Queue()
3517
3518        def read():
3519            while True:
3520                try:
3521                    line = proc.stdout.readline()
3522                except (OSError, ValueError):           # killed under the read
3523                    line = ""
3524                got.put(line)
3525                if not line or line.startswith(("READY", "ERR")):
3526                    return
3527
3528        threading.Thread(target=read, daemon=True).start()
3529        deadline = None if timeout is None else time.monotonic() + timeout
3530        ended_at = None
3531        said = 0
3532        while True:
3533            now = time.monotonic()
3534            if deadline is not None and now >= deadline:
3535                try:
3536                    proc.kill()
3537                except OSError:
3538                    pass
3539                raise RuntimeError(f"the vision encoder did not start: it said nothing for {timeout:.0f} s")
3540            try:
3541                line = got.get(timeout=0.25 if deadline is None else max(0.01, min(0.25, deadline - now)))
3542            except queue.Empty:
3543                code = proc.poll() if hasattr(proc, "poll") else None
3544                if code is not None:
3545                    ended_at = now if ended_at is None else ended_at
3546                    if now - ended_at >= self.READY_GRACE_S:
3547                        return ""
3548                continue
3549            if not line or line.startswith(("READY", "ERR")):
3550                return line
3551            stray = line.strip()
3552            if stray:
3553                strays.append(stray[:300])
3554                del strays[:-self.STRAY_KEEP]
3555                said += 1
3556                if said <= self.STRAY_KEEP:
3557                    print(f"[strata] the image encoder printed on its output, not an answer: {stray[:200]}", flush=True)
3558
3559    def _readline(self, timeout: float, what: str) -> str:
3560        """One line from the encoder, waiting at most `timeout` s (#1317).  On a timeout the encoder is killed, so the
3561        next request starts a fresh one, and the read raises RuntimeError instead of holding the request turn."""
3562        proc = self.proc
3563        got: queue.Queue = queue.Queue()
3564
3565        def read():
3566            try:
3567                got.put(proc.stdout.readline())
3568            except (OSError, ValueError):               # killed under the read
3569                got.put("")
3570
3571        threading.Thread(target=read, daemon=True).start()
3572        try:
3573            return got.get(timeout=timeout)
3574        except queue.Empty:
3575            try:
3576                proc.kill()
3577            except OSError:
3578                pass
3579            raise RuntimeError(f"{what}: it said nothing for {timeout:.0f} s") from None
3580
3581    def alive(self) -> bool:
3582        return self.proc is not None and not self.stopped and self.proc.poll() is None
3583
3584    def unload(self):
3585        """Stop the encoder process (its VRAM or RAM goes back); the encoded images stay cached on disk."""
3586        self.close()
3587        self.stopped = True
3588        if self.elastic and self.on_cpu:                # the next start tries the card again
3589            self.spawn, self.fallback, self.on_cpu = self.gpu_spawn, self.cpu_spawn, False
3590            self.cpu_note = None
3591
3592    def all_cached(self, sources: list) -> bool:
3593        """Every picture of `sources` was encoded already (a conversation sends its pictures with each turn): no reader has to run."""
3594        try:
3595            with self.lock:
3596                self._ensure_dir()
3597                return all(hashlib.sha256(self.normalize(src if isinstance(src, bytes) else self.load(src))).hexdigest()[:32] in self.cache
3598                           for src in sources)
3599        except (ValueError, OSError):
3600            return False                                # encode() says what is wrong with it
3601
3602    def restart(self):
3603        """Start the encoder again after an unload (or if it died); the cache of encoded images is kept."""
3604        if self.proc is not None:
3605            try:
3606                self.proc.kill()
3607            except OSError:
3608                pass
3609        self.proc = None
3610        self.stopped = True
3611        self._start()
3612
3613    @staticmethod
3614    def load(source: str) -> bytes:
3615        if source.startswith("data:"):
3616            try:
3617                return base64.b64decode(source.split(",", 1)[1])
3618            except (IndexError, ValueError) as e:                # no comma, or not base64
3619                raise ValueError(f"the image's data: URL could not be read ({e})") from None
3620        if source.startswith(("http://", "https://")):
3621            return Vision.download(source)
3622        path = source[7:] if source.startswith("file://") else source
3623        # refused before anything looks at the path: file://host/share/x.png is \\host\share\x.png ("file://C:/x.png",
3624        # a drive, is a client's spelling of file:///C:/x.png)
3625        host = re.split(r"[/\\]", path, maxsplit=1)[0] if source.startswith("file://") else ""
3626        if network_path(path) or host and not re.fullmatch(r"[A-Za-z]:|localhost", host, re.IGNORECASE):
3627            raise ValueError("an image file must be on this computer: network paths (\\\\host\\share, //host/share, "
3628                             "file://host/...) are not read")
3629        if path and os.path.isfile(path):
3630            try:
3631                return Path(path).read_bytes()
3632            except OSError as e:
3633                raise ValueError(f"the image could not be read from {path} ({e})") from None
3634        raise ValueError("an image must be a data: URL, an http(s) URL or a local file path")
3635
3636    @staticmethod
3637    def download(url: str) -> bytes:
3638        """An image URL's bytes, at most IMAGE_URL_MAX of them: the whole response was read, so a huge or endless one
3639        filled the memory.  One that cannot be read is a ValueError (a 400 that says so), not a dropped connection."""
3640        too_big = f"the image URL's file is over {IMAGE_URL_MAX >> 20} MiB"
3641        try:
3642            with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "strata"}), timeout=60) as r:
3643                size = r.headers.get("Content-Length") or ""
3644                if size.isdigit() and int(size) > IMAGE_URL_MAX:
3645                    raise ValueError(too_big)
3646                data = r.read(IMAGE_URL_MAX + 1)
3647        except (OSError, HTTPException) as e:
3648            raise ValueError(f"the image URL could not be read: {e}") from None
3649        if len(data) > IMAGE_URL_MAX:
3650            raise ValueError(too_big)
3651        return data
3652
3653    @staticmethod
3654    def _exif_rotated(data: bytes) -> bool:
3655        """A JPEG whose EXIF Orientation says it is stored turned (phones do this for portrait photos): the decoder
3656        (stb_image) ignores the tag.  False without Pillow, or when the tag is missing, 1 or unreadable (#1229)."""
3657        try:
3658            import io
3659            from PIL import Image
3660            with Image.open(io.BytesIO(data), formats=PICTURE_FORMATS) as im:
3661                return im.getexif().get(0x0112, 1) not in (None, 0, 1)
3662        except Exception:  # noqa: BLE001 - any failure leaves the image as it was sent
3663            return False
3664
3665    @staticmethod
3666    def normalize(data: bytes) -> bytes:
3667        """The formats strata-vision's decoder (stb_image) reads pass through; anything else is converted to PNG.
3668        A JPEG with an EXIF Orientation other than 1 is turned upright first (needs Pillow)."""
3669        jpeg = data[:3] == b"\xff\xd8\xff"
3670        if (jpeg and not Vision._exif_rotated(data)) or data[:8] == b"\x89PNG\r\n\x1a\n" or data[:2] == b"BM" or \
3671                data[:6] in (b"GIF87a", b"GIF89a"):
3672            return data
3673        try:
3674            import io
3675            from PIL import Image
3676        except ImportError:
3677            raise ValueError("this image format needs Pillow (python -m pip install pillow); JPEG, PNG, BMP and "
3678                             "GIF work without it") from None
3679        try:
3680            im = Image.open(io.BytesIO(data), formats=PICTURE_FORMATS)
3681            im.load()
3682            from PIL import ImageOps
3683            im = ImageOps.exif_transpose(im)             # the camera's orientation tag, applied (#1229)
3684        except Exception as e:
3685            raise ValueError(f"the image could not be read ({e})") from None
3686        if im.mode in ("RGBA", "LA", "P") and "transparency" in im.info or im.mode in ("RGBA", "LA"):
3687            im = im.convert("RGBA")
3688            bg = Image.new("RGB", im.size, (255, 255, 255))   # transparent areas become white, not black
3689            bg.paste(im, mask=im.split()[-1])
3690            im = bg
3691        elif im.mode != "RGB":
3692            im = im.convert("RGB")
3693        out = io.BytesIO()
3694        im.save(out, format="PNG")
3695        return out.getvalue()
3696
3697    def encode_all(self, sources: list, cancel=None) -> list[tuple[Path, int]]:
3698        """encode() for every image of one request: the files of this request's earlier images are never evicted to
3699        make room for a later one (#1072: with more than 64 unique images the first was deleted before the request
3700        had read it).  `cancel` (#1999): a request whose client left does not encode its next pictures."""
3701        out: list[tuple[Path, int]] = []
3702        for src in sources:
3703            if cancel is not None and cancel.is_set():
3704                raise ClientGone()
3705            out.append(self.encode(src, keep=[p for p, _ in out]))
3706        return out
3707
3708    def encode(self, source: str | bytes, keep=()) -> tuple[Path, int]:
3709        """-> (embeddings file, number of image tokens).  `source`: what load() reads, or the image's bytes.
3710        `keep`: files the caller still needs (never evicted by this call)."""
3711        data = self.normalize(source if isinstance(source, bytes) else self.load(source))
3712        key = hashlib.sha256(data).hexdigest()[:32]
3713        with self.lock:
3714            self._ensure_dir()
3715            if key in self.cache:
3716                self.cache[key] = self.cache.pop(key)                  # most recently used last
3717                return self.cache[key]
3718            if self.proc is None or self.proc.stdin is None:           # an elastic encoder not started yet, or one that was unloaded
3719                raise ValueError("the picture reader is not running")
3720            img, out = self.dir / f"{key}.img", self.dir / f"{key}.sve"
3721            img.write_bytes(data)
3722            try:
3723                self.proc.stdin.write(f"ENC {img.name} {out.name}\n")      # relative to the encoder's cwd (#480)
3724                self.proc.stdin.flush()
3725                try:
3726                    line = self._readline(VISION_ENCODE_S, "the image could not be read").strip()
3727                except RuntimeError as e:                 # silent for VISION_ENCODE_S: the encoder was ended (#1317)
3728                    self.stopped = True                   # alive() is False, so the next request starts it again
3729                    raise ValueError(str(e)) from None
3730            finally:                                                   # #352: also when the encoder's pipe is gone
3731                img.unlink(missing_ok=True)
3732            if not line.startswith("OK"):
3733                raise ValueError("the image could not be read: " + (line[4:] if line.startswith("ERR") else
3734                                                                     "the vision encoder stopped"))
3735            self.cache[key] = (out, int(line.split()[1]))
3736            self.warn_if_over_limit(self.cache[key][1])
3737            held = {str(p) for p in keep} | {str(out)}
3738            for old in list(self.cache):                               # oldest first, but never one still in use
3739                if len(self.cache) <= 64:
3740                    break
3741                if str(self.cache[old][0]) not in held:
3742                    self.cache.pop(old)[0].unlink(missing_ok=True)
3743            return self.cache[key]
3744
3745    def warn_if_over_limit(self, tokens: int) -> None:
3746        """I7: one picture that became more than 4 times the limit is logged with the numbers, so the next report has them (the reader's own
3747        stderr has the warm-up line).  A reader built before the limit was enforced inside it (strata-vision refuses these now) still lets them by."""
3748        limit = getattr(self, "max_tokens", 0)
3749        if limit and tokens > 4 * limit:
3750            print(f"[strata] images: one picture became {tokens} image tokens, more than 4 times the limit of {limit} (vision.max_tokens); "
3751                  "the picture reader is not applying its limit. Update the engine, and send the line 'strata-vision: warmed up at N image "
3752                  "tokens' from the reader's log with the report", flush=True)
3753
3754    def close(self):
3755        proc, self.proc = self.proc, None
3756        if proc is None:
3757            self.stopped = True
3758            return
3759        try:
3760            proc.stdin.write("QUIT\n")
3761            proc.stdin.flush()
3762            proc.wait(timeout=10)
3763        except Exception:
3764            try:
3765                proc.kill()
3766            except OSError:
3767                pass
3768            try:
3769                proc.wait(timeout=10)
3770            except (OSError, subprocess.TimeoutExpired):
3771                pass
3772        self.stopped = True
3773
3774    def shutdown(self):
3775        """#914: close() for good: the server ends, so the encoder's directory (one ~10 MB .sve per image, on a tmpfs
3776        /tmp that is RAM) goes with it instead of piling up with every start.  unload() keeps it for the restart."""
3777        self.close()
3778        shutil.rmtree(self.dir, ignore_errors=True)
3779
3780
3781def gpu_list(cfg: dict) -> list[int]:
3782    """The config's "gpu": one card (2), or several for a layer split ([0, 2] or "0,2"), numbered as nvidia-smi
3783    numbers them; [] when it names none."""
3784    roles, _ = gpu_roles.saved_roles(cfg)       # "gpu_roles" (Main / Helper / Off per card) wins unless "gpu" was edited by hand
3785    if roles is not None:
3786        legacy = _gpu_numbers(cfg.get("gpu"))
3787        return legacy if legacy else gpu_roles.engine_order(roles)     # Main LAST; Off cards left out; [] when every card is Off
3788    return _gpu_numbers(cfg.get("gpu"))
3789
3790
3791def _gpu_numbers(g) -> list[int]:
3792    if g is None or g == "":
3793        return []
3794    items = g if isinstance(g, (list, tuple)) else str(g).split(",")
3795    return [int(str(x).strip()) for x in items if str(x).strip() != ""]
3796
3797
3798def gpu_roles_active(cfg: dict) -> bool:
3799    """True when the run settings carry usable "gpu_roles": the card order is the person's (Main last), never re-sorted by speed."""
3800    return gpu_roles.saved_roles(cfg)[0] is not None
3801
3802
3803def gpu_all_off(cfg: dict) -> bool:
3804    """Every card is set to Off ("gpu_roles" with no card on, or "gpu_none": true)."""
3805    roles, _ = gpu_roles.saved_roles(cfg)
3806    return roles is not None and not any(r != "off" for r in roles.values())
3807
3808
3809def card_roles_lines(cfg: dict) -> list[str]:
3810    """The plain lines printed at start: the roles (cards numbered as nvidia-smi numbers them), a hand-edited "gpu" that beat them, and the
3811    all-Off case.  SystemExit when every card is Off and the engine cannot start without one (the CUDA, HIP and SYCL engines)."""
3812    roles, problem = gpu_roles.saved_roles(cfg)
3813    out = [f"[strata] {problem}"] if problem else []
3814    if roles is None:
3815        return out
3816    if gpu_all_off(cfg):
3817        if cfg.get("backend") in ("cpu", "metal") or sys.platform == "darwin":
3818            out.append("[strata] every graphics card is Off: " + gpu_roles.CPU_ONLY_LINE)
3819            return out
3820        raise SystemExit("[strata] every graphics card is set to Off, and this engine cannot start without one. Turn a card on "
3821                         "(Main or Helper) in the app or with strata launch --gpu-roles.")
3822    word = {"main": "Main", "helper": "Helper", "off": "Off"}
3823    out.append("[strata] card roles: " + ", ".join(f"{word[r]} GPU {i}" for r in ("main", "helper", "off")
3824                                                    for i in sorted(roles) if roles[i] == r) + " (numbers as nvidia-smi gives them)")
3825    return out
3826
3827
3828def engine_binary(exe: str, cfg: dict | None = None) -> str:
3829    """The file that holds the engine's own option strings, for a feature check that reads it.  The Intel launcher
3830    (sycl/serve/strata-sycl.sh) is a shell script that runs its repo's STRATA_SYCL_BIN (default build-sycl-aot/strata)
3831    in a container, so the check reads that binary, not the script.  Any other `exe` is the engine itself."""
3832    p = Path(exe)
3833    if p.name == "strata-sycl.sh":
3834        rel = ((cfg or {}).get("env") or {}).get("STRATA_SYCL_BIN") or os.environ.get("STRATA_SYCL_BIN") \
3835            or "build-sycl-aot/strata"
3836        b = p.resolve().parents[2] / rel
3837        if b.is_file():
3838            return str(b)
3839    return exe
3840
3841
3842def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None:
3843    """#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so
3844    the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the
3845    default) or the engine is too old for it (said once; the prompt stays the default one).  ValueError for a value
3846    other than "start" / "end"."""
3847    pos = cfg.get("effort_position", "start")
3848    if pos not in ("start", "end"):
3849        raise ValueError(f'"effort_position" must be "start" (the default) or "end", not {pos!r}')
3850    if pos == "start":
3851        return None
3852    try:
3853        with open(engine_binary(exe, cfg), "rb") as f:
3854            known = b"--tail-role-token" in f.read()
3855    except OSError:
3856        known = False
3857    role = tok.encode("system", parse_special=True)
3858    if not known or len(role) != 1:
3859        print("[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning "
3860              "effort stays at the top of the prompt", flush=True)
3861        return None
3862    print("[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so "
3863          "changing it keeps the cached conversation", flush=True)
3864    return ["--tail-role-token", str(role[0])]
3865
3866
3867def engine_silence_s(cfg: dict) -> float:
3868    """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server
3869    ends it (default ENGINE_SILENCE_S; 0 = wait forever).  ValueError for anything but a number >= 0."""
3870    v = cfg.get("engine_silence_s")
3871    if v is None:
3872        return ENGINE_SILENCE_S
3873    if isinstance(v, bool) or not isinstance(v, (int, float)) or v < 0:
3874        raise ValueError(f'"engine_silence_s" must be a number of seconds >= 0 (0 = no limit), not {v!r}')
3875    return float(v)
3876
3877
3878def layer_split_value(cfg: dict) -> str:
3879    """#644: the config's "layer_split" as the engine's --layer-split value: "auto" (the default), or the FIRST LAYER of
3880    each later GPU's share - one rising number per GPU after the first, e.g. "24,36,42" for 4 GPUs (layers 0-23 on the
3881    first card, 24-35, 36-41, 42 to the end) - as a string or a JSON list ([24, 36, 42]).  ValueError with the format
3882    and an example for anything else, such as per-card layer counts ("24,16,12,12")."""
3883    v = cfg.get("layer_split")
3884    if v is None or (isinstance(v, str) and v.strip().lower() in ("", "auto")):
3885        return "auto"
3886    n = len(gpu_list(cfg))
3887    items = v if isinstance(v, (list, tuple)) else str(v).split(",") if isinstance(v, (str, int)) else None
3888    vals = []
3889    for x in items or []:
3890        try:
3891            if isinstance(x, bool) or isinstance(x, float):
3892                raise ValueError
3893            vals.append(int(str(x).strip()))
3894        except ValueError:
3895            vals = None
3896            break
3897    want = max(n - 1, 1)
3898    example = ",".join(str(round(48 * (i + 1) / (want + 1))) for i in range(want))
3899    hint = (f'"layer_split" is the first layer of each later GPU, one rising number per GPU after the first '
3900            f'({want} for {n} GPUs), not a count of layers per card - e.g. "{example}" (or [{example.replace(",", ", ")}])'
3901            f' for an even share of 48 layers, or "auto" (the default) to place them by each card\'s free VRAM')
3902    if not vals:
3903        raise ValueError(f"{hint}; got {v!r}")
3904    if n > 1 and len(vals) != n - 1:
3905        raise ValueError(f"{hint}; got {len(vals)} number(s) ({v!r}) for {n} GPUs")
3906    if vals[0] < 2 or any(b <= a for a, b in zip(vals, vals[1:])):
3907        raise ValueError(f"{hint}; got {v!r}, which does not rise from 2 or more")
3908    return ",".join(str(x) for x in vals)
3909
3910
3911def apply_ready_timeout(cfg: dict) -> None:
3912    """The config's "engine_ready_s": how long a start may take before READY (default ENGINE_READY_S, 900).  A model of 300+ GB read
3913    from a slow disk (DeepSeek-V4.1-Flash: setup writes 3600) needs more.  ValueError for anything but a number > 0."""
3914    global ENGINE_READY_S
3915    v = cfg.get("engine_ready_s")
3916    if v is None:
3917        return
3918    if isinstance(v, bool) or not isinstance(v, (int, float)) or not v > 0:
3919        raise ValueError(f'"engine_ready_s" must be a number of seconds above 0, not {v!r}')
3920    ENGINE_READY_S = float(v)
3921
3922
3923def layer_split_of(cfg: dict) -> bool:
3924    """Several GPUs in the config are a layer split, unless the args put the later card(s) to another use: with
3925    --peer-device the second card is an expert-cache tier, and the engine refuses that beside --layer-split (#665)."""
3926    return len(gpu_list(cfg)) > 1 and "--peer-device" not in cfg["args"]
3927
3928
3929_CARD_CLASS: list = []
3930
3931
3932def drafting_card_class() -> str:
3933    """The class of this computer's graphics card for the drafter table (strata_control/drafting.py), looked up once."""
3934    if not _CARD_CLASS:
3935        archs: list[str] = []
3936        try:
3937            from strata_control import engine_component
3938            archs = list(engine_component.cuda_archs_present()) + list(engine_component.hip_archs_present())
3939        except Exception:                                    # noqa: BLE001 - an unknown card is the "other" class, never an error
3940            pass
3941        _CARD_CLASS.append(drafting.card_class(archs))
3942    return _CARD_CLASS[0]
3943
3944
3945def ds4_engine_vision(cfg: dict, engine) -> "ds4_vision.Ds4Vision | None":
3946    """DeepSeek-V4.1's own vision tower, in the engine: on when the pack has one (pack_gguf.py --mmproj) and the
3947    args do not say --vision off.  None when the engine reported that its tower did not load (INFO vision=off)."""
3948    args = list(cfg.get("args") or [])
3949    opts = dict(zip(args, args[1:]))
3950    if opts.get("--vision") == "off" or "--pack" not in opts:
3951        return None
3952    pack = opts["--pack"] if os.path.isabs(opts["--pack"]) else os.path.join(cfg.get("cwd") or ".", opts["--pack"])
3953    geo = ds4_vision.pack_geometry(pack)
3954    if geo is None:
3955        return None
3956    if (getattr(engine, "info", None) or {}).get("vision") == "off":
3957        print("[strata] images: OFF - the engine's vision tower did not load (see its log)", flush=True)
3958        return None
3959    print(f"[strata] images: DeepSeek's vision tower in the engine (up to {geo.get('vision.max_image_tokens')} "
3960          "tokens a picture)", flush=True)
3961    return ds4_vision.Ds4Vision(geo, Vision.work_dir(), Vision.load)
3962
3963
3964def drafting_vram_mib(cfg: dict, backend: str | None, archs) -> float | None:
3965    """MiB of graphics memory of the ONE card DFlash2 would run on, for the drafter's confidence (drafting.expected_slots); None for several cards, a
3966    chip that shares the computer's memory (Strix Halo, the Spark: their experts are all "resident") or a card the driver does not answer for."""
3967    try:
3968        gl = gpu_list(cfg)
3969        arch = str((list(archs or [""]) or [""])[0]).lower()
3970        if len(gl) > 1 or arch in HIP_IGPU_ARCHS or arch == "sm_121":
3971            return None
3972        got = gpu_vram_mib(gl or [0], hip=(backend == "hip"))
3973        return float(next(iter(got.values()))) if got else None
3974    except Exception:                                        # noqa: BLE001 - an unreadable card keeps the plain 0.35, never stops a start
3975        return None
3976
3977
3978def own_path_context_warning(cfg: dict, args: list, vram_mib: float | None) -> str | None:
3979    """The sentence for a Qwen3.6 start whose --max-context does not fit its one card (strata_control/own_path_fit.py, the rule setup's menu
3980    uses); None for any other model, a context that fits, or a card that is not known.  Nothing about the start changes."""
3981    try:
3982        from strata_control import own_path_fit
3983        fit = own_path_fit.from_model_name(cfg.get("model_name"))
3984        if not fit or not vram_mib or "--max-context" not in args:
3985            return None
3986        ctx = int(args[args.index("--max-context") + 1])
3987        return own_path_fit.warning(fit, float(vram_mib) / 1024, ctx, own_path_fit.MENU)
3988    except Exception:                                        # noqa: BLE001 - an estimate that fails says nothing; the engine still says what does not fit
3989        return None
3990
3991
3992def mtp_retry_args(cfg: dict, exe: str | None, extra: list[str] | None = None) -> list[str] | None:
3993    """The arguments to start again with when an Auto start that picked DFlash2 ends before the engine is ready: the same start with the MTP (or no drafter, when
3994    the MTP layer is not on this computer). None when there is nothing to retry: the person named DFlash2 themselves (that start fails with its reason, as it
3995    should), the choice was not DFlash2, or the MTP arguments are the same. Builds the arguments without any line or note (engine_args announce=False)."""
3996    if drafting.normalize(cfg.get("drafting")) != "auto" or "args" not in cfg:
3997        return None
3998    try:
3999        first = engine_args(cfg, exe, announce=False)
4000        if "--draft" not in first or first[first.index("--draft") + 1:first.index("--draft") + 2] != ["dflash2"]:
4001            return None
4002        alt = engine_args({**cfg, "drafting": "mtp"}, exe, announce=False) + list(extra or [])
4003    except Exception:                                  # noqa: BLE001 - a retry that cannot be worked out is no retry
4004        return None
4005    return alt if alt != first + list(extra or []) else None
4006
4007
4008def nodraft_retry_args(cfg: dict, exe: str | None, extra: list[str] | None = None) -> list[str] | None:
4009    """The arguments to start again with when an Auto start ends before the engine is ready because a card ran out of memory: the same start with no drafter
4010    (the draft layer and DFlash2's buffers are the biggest optional part on a card that is short), never the MTP in place of DFlash2.  None when the drafting
4011    was not Auto (the person named a drafter: that start fails with the engine's reason), when the first start has no drafter anyway, or when nothing differs."""
4012    if drafting.normalize(cfg.get("drafting")) != "auto" or "args" not in cfg:
4013        return None
4014    try:
4015        first = engine_args(cfg, exe, announce=False)
4016        if "--draft" not in first and "--mtp" not in first:
4017            return None
4018        alt = engine_args({**cfg, "drafting": "off"}, exe, announce=False) + list(extra or [])
4019    except Exception:                                  # noqa: BLE001 - a retry that cannot be worked out is no retry
4020        return None
4021    return alt if alt != first + list(extra or []) else None
4022
4023
4024def engine_args(cfg: dict, exe: str | None = None, *, announce: bool = True) -> list[str]:
4025    """The engine's arguments: the config's, and with several GPUs the layer split across them ("layer_split" in the
4026    config: "auto" by default, or the first layer of each later GPU's share, e.g. "18" or "16,32"; see
4027    layer_split_value). `exe` is the engine program that will start: the drafter's flags follow what that program takes
4028    (strata_control/drafting.py engine_form). `announce=False` builds the arguments without the "[strata] drafting" lines
4029    and without leaving a note for the next engine start (the retry arguments of mtp_retry_args)."""
4030    args = list(cfg["args"])
4031    # "user_args" (strata_control/user_args.py): the options the person set by hand, over the generated ones at every start,
4032    # so a setup run or the app rewriting "args" cannot undo them (#3216 #3215 #3270)
4033    if cfg.get("user_args"):
4034        args = user_args.merge(args, cfg["user_args"])
4035    # "drafting": auto | mtp | dflash2 | off (strata_control/drafting.py; the Models screen and `strata launch --drafting` write it): which drafter
4036    # guesses ahead. ONE drafter per run: DFlash2 alone (no --mtp, --draft-fallback none) or the MTP alone (no DFlash2 option). Auto is DFlash2 where the engine
4037    # has it, on one card and on a layer split over several cards. A choice that cannot be applied (no drafter file yet, several requests at once) starts the other one if it is on this computer,
4038    # else none, and says why in the engine's /metrics ("drafting_note"). The start never downloads.
4039    shaped = {**cfg, "args": args}
4040    backend, archs = drafting.detect_hardware()
4041    parallel_n = cfg.get("parallel")
4042    decision = drafting.apply(shaped, klass=drafting_card_class(), data_dir=drafting.data_dir_of(args), backend=backend, archs=archs,
4043                              vram_mib=drafting_vram_mib(cfg, backend, archs),
4044                              slots=parallel_n if isinstance(parallel_n, int) and not isinstance(parallel_n, bool) else 0, engine=exe)
4045    args = shaped["args"]
4046    if announce:
4047        drafting.remember_note(decision.note)
4048        if decision.note:
4049            print(f"[strata] {drafting.line(decision.drafter, decision.note)}", flush=True)
4050            hint = drafting.fetch_hint(decision, model_name=cfg.get("model_name"), backend=backend, archs=archs, data_dir=drafting.data_dir_of(args), args=args,
4051                                       vram_mib=drafting_vram_mib(cfg, backend, archs))
4052            if hint:
4053                print(f"[strata] {hint}", flush=True)
4054        elif decision.flags and drafting.slot_drafts_run(args, parallel_n, layer_split_of(cfg)):
4055            print(f"[strata] {drafting.SLOT_DRAFTS_LINE}", flush=True)
4056        elif decision.flags:
4057            print(f"[strata] drafting: DFlash2 alone ({' '.join(decision.flags[:2])}, --draft-conf {args[args.index('--draft-conf') + 1] if '--draft-conf' in args else '-'})", flush=True)
4058        if decision.vocab:                                   # log only (a support log shows which draft vocabulary was used and why)
4059            print(f"[strata] drafting: {decision.vocab}", flush=True)
4060    # A card that is short of VRAM for this start (a single request on a small card, or "parallel" 2 or more, every request slot a session of its own) gets work moved off
4061    # the GPU, never a smaller context and never fewer requests (owner, 2026-11-02): a smaller KV window on CUDA, a smaller prompt chunk and reserve on Arc, and the
4062    # engine sizes the rest; one plain note says it is slower (strata_control/vram_fit.py fit_start).  The person's own values are kept.  Nothing changes without one
4063    # card's memory, on a layer split, or for DeepSeek.
4064    try:
4065        args, fit_parallel, fit_note = vram_fit.fit_start(cfg, args, drafting_vram_mib(cfg, backend, archs), backend)
4066    except Exception:                                        # noqa: BLE001 - an estimate that fails decides nothing; the engine still refuses what does not fit
4067        fit_parallel, fit_note = None, ""
4068    if fit_note and announce:                                # (announce=False builds the arguments without any line)
4069        print(f"[strata] {fit_note}", flush=True)
4070    if announce:                                             # #5715: Qwen3.6 with a context its card cannot hold: said before the start, nothing changed
4071        too_big = own_path_context_warning(cfg, args, drafting_vram_mib(cfg, backend, archs))
4072        if too_big:
4073            print(f"[strata] {too_big}", flush=True)
4074    if fit_parallel is not None:
4075        cfg = {**cfg, "parallel": fit_parallel}
4076    # "mtp": false (the Models settings, `strata launch --mtp off`, or by hand): no draft layer, whatever the args say.  A setup run
4077    # that writes --mtp back into the args cannot undo it, because this is applied at every start. (A DFlash2 start keeps its own --mtp DIR, which only names
4078    # the vocabulary for an engine that takes it that way.)
4079    if draft_layer.is_off(cfg) and not decision.flags:
4080        args, removed = draft_layer.strip(args)
4081        if removed:
4082            print(f'[strata] "mtp": false - starting without the draft layer ({" ".join(removed)} left out)', flush=True)
4083    # #1322: a config with a "vision" section but without --vision in its args (written by an older setup run, or edited by
4084    # hand) advertised images and then refused every picture ("this engine was started without --vision").  The section
4085    # says images are wanted: start the engine with them, and keep the encoder's VRAM free as setup does for a GPU encoder
4086    # (only when the config has no reserve of its own).
4087    if isinstance(cfg.get("vision"), dict) and "--vision" not in args:
4088        args.append("--vision")
4089        note = "added --vision"
4090        if cfg["vision"].get("gpu") and "--vram-reserve-mib" not in args:
4091            args += ["--vram-reserve-mib", "700"]
4092            note += " and --vram-reserve-mib 700"
4093        print(f'[strata] the config has a "vision" section but no --vision in its args: {note} (run setup again with '
4094              "--vision to write them)", flush=True)
4095    if layer_split_of(cfg) and "--layer-split" not in args:
4096        args += ["--layer-split", layer_split_value(cfg)]
4097    # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV
4098    if layer_split_of(cfg) and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args:
4099        args.append("--split-skip-if-fits")
4100    # #533 (opt-in): "vram_elastic": true - the expert cache in segments, so POST /v1/vram can give VRAM back to other
4101    # programs and take it back; "vram_segment_mib" sets the segment size (the engine's default: 512)
4102    if cfg.get("vram_elastic") is True and "--vram-elastic" not in args:
4103        args.append("--vram-elastic")
4104        seg = cfg.get("vram_segment_mib")
4105        if isinstance(seg, int) and not isinstance(seg, bool) and seg > 0 and "--vram-segment-mib" not in args:
4106            args += ["--vram-segment-mib", str(seg)]
4107    args += parallel_args(cfg, args)
4108    args += pool_cores_args(cfg, args)
4109    return draft_costs_args(cfg, learned_profile_args(cfg, args), exe or cfg.get("exe"))
4110
4111
4112PARALLEL_MAX = 8      # without a layer split the engine's batch window holds at most 8 rows (kVerifyNarrowT); --batch-mtp waves more through it
4113
4114
4115SPLIT_MAX_LANES = 8   # the all-cards split engine runs 1..8 lanes (strata_control/split_engine.py MAX_LANES)
4116
4117
4118def parallel_flag_conflicts(cfg: dict) -> bool:
4119    """`--parallel N` next to the saved engine args' own --batch/--slots is refused, except for the all-cards split engine's run config (split_config's
4120    "split_engine_note"): its --batch is its lane count, and "parallel" sets it (parallel_args). The app's Concurrent requests reaches the server this way."""
4121    args = cfg.get("args", [])
4122    return ("--batch" in args or "--slots" in args) and not cfg.get("split_engine_note")
4123
4124
4125def parallel_args(cfg: dict, args: list[str]) -> list[str]:
4126    """#465 (opt-in): "parallel": N in the config - up to N requests decode together in the engine's batch slots
4127    (--batch N); more wait their turn.  1 or absent: one request at a time, as before.  A value the engine cannot use
4128    is said and passed on: the engine warns and adjusts (recommend, never force)."""
4129    ds = (cfg.get("arch") or "") == "deepseek41"
4130    if cfg.get("split_engine_note") and "--batch" in args:
4131        # the all-cards split engine: its run config carries --batch N (its lanes); "parallel" (the Terminal's --parallel, the app's Concurrent requests) sets N
4132        n = cfg.get("parallel")
4133        if isinstance(n, int) and not isinstance(n, bool) and n >= 1:
4134            args[args.index("--batch") + 1] = str(min(n, SPLIT_MAX_LANES))
4135        return []
4136    if "--batch" in args or "--slots" in args or (ds and "--parallel" in args):
4137        return []
4138    n = cfg.get("parallel")
4139    if n is None or n is False:
4140        return []
4141    if isinstance(n, bool) or not isinstance(n, int):
4142        print(f'[strata] "parallel" must be a whole number of requests (2..{PARALLEL_MAX}), not {n!r}: ignored',
4143              flush=True)
4144        return []
4145    if n <= 1:
4146        return []
4147    if ds:
4148        # DeepSeek: --parallel N (the engine holds N conversations at once, each its own rings and KV in VRAM, taken out of the
4149        # experts' room; their tokens are decoded together).  Not --batch: that is the Qwen engine's slots.
4150        # An engine package from before this flag would stop at the start on it ("unknown option"): asked of the engine itself, and said.
4151        try:
4152            from strata_control import dsv41_flags
4153            old_engine = dsv41_flags.takes_parallel(cfg.get("exe")) is False
4154        except Exception:                                # noqa: BLE001 - a probe that fails decides nothing
4155            old_engine = False
4156        if old_engine:
4157            print(f'[strata] "parallel": {n} - this DeepSeek engine ({cfg.get("exe")}) is from before --parallel, so it answers one request at a '
4158                  "time. Update the engine (strata update) to answer several at once.", flush=True)
4159            return []
4160        if n > PARALLEL_MAX:
4161            print(f'[strata] "parallel": {n} - the DeepSeek engine runs at most {PARALLEL_MAX} conversations at once; it will use '
4162                  f"{PARALLEL_MAX}", flush=True)
4163        return ["--parallel", str(min(n, PARALLEL_MAX))]
4164    # (on a layer split the pipelined groups each hold up to 8 slots - 16 in a HIP engine with wide windows - so more than 8 is
4165    # not a limit there: the engine says how many slots it runs, INFO batch_slots)
4166    if (n > PARALLEL_MAX and "--batch-mtp" not in args and os.environ.get("STRATA_BATCH_MTP", "0") in ("", "0")
4167            and not layer_split_of(cfg)):
4168        print(f'[strata] "parallel": {n} - the engine runs at most {PARALLEL_MAX} requests together; it will use '
4169              f"{PARALLEL_MAX}", flush=True)
4170    return ["--batch", str(n)]
4171
4172
4173_POOL_CORES_OK = re.compile(r"^[0-9]+(-[0-9]+(:[0-9]+)?)?(,[0-9]+(-[0-9]+(:[0-9]+)?)?)*$")
4174
4175
4176def pool_cores_args(cfg: dict, args: list[str]) -> list[str]:
4177    """Experimental, off by default: "pool_cores": "0,2,4,6" (or "2-14:2", or a list of numbers) in the config pins the CPU
4178    expert workers to exactly those logical processors (--pool-cores; docs/DETAILS.md, "Which logical processors the CPU
4179    workers use").  The engine warns about two entries on one core or the host's own and leaves out processors the process may
4180    not use; a text this cannot read is said here and ignored (recommend, never force).  An engine option already in the args wins."""
4181    value = cfg.get("pool_cores")
4182    if value is None or value is False or value == "" or value == []:
4183        return []
4184    if "--pool-cores" in args:
4185        return []
4186    if isinstance(value, list) and value and all(isinstance(v, int) and not isinstance(v, bool) and v >= 0 for v in value):
4187        text = ",".join(str(v) for v in value)
4188    elif isinstance(value, str):
4189        text = value.replace(" ", "")
4190    else:
4191        text = ""
4192    if not _POOL_CORES_OK.match(text):
4193        print(f'[strata] "pool_cores" must be logical processor numbers like "0,2,4,6" or "2-14:2", not {value!r}: ignored '
4194              "(the CPU workers keep their default placement)", flush=True)
4195        return []
4196    return ["--pool-cores", text]
4197
4198
4199def profile_shape(path: str) -> tuple[int, int] | None:
4200    """An expert profile's (layers, experts per layer), from its header (tools/make_profile.py's format), or None
4201    when the file is missing, is not one or is shorter than the pairs its header promises."""
4202    try:
4203        with open(path, "rb") as f:
4204            head = f.read(24)
4205            size = os.fstat(f.fileno()).st_size
4206    except OSError:
4207        return None
4208    if len(head) < 24 or head[:4] != b"STRP":
4209        return None
4210    _, nl, ne, _, n = struct.unpack("<5I", head[4:])
4211    return (nl, ne) if size >= 24 + 4 * n else None
4212
4213
4214def learned_profile_args(cfg: dict, args: list[str]) -> list[str]:
4215    """#477 (opt-in): "expert_profile_save": "<path>" in the config has the engine (0.1.36+) save what its adaptive
4216    tier learned there - on QUIT and every "expert_profile_save_every" minutes (10 by default, 0 = at QUIT only) -
4217    and the next start begins from it instead of the config's --expert-profile, when it is a profile of the same
4218    model (its header's layers and experts match); otherwise from the config's own, as before.  A relative path is
4219    the engine's (the config's "cwd").  Without the key, the arguments are the config's, unchanged."""
4220    save = cfg.get("expert_profile_save")
4221    if not isinstance(save, str) or not save.strip() or "--expert-profile-save" in args:
4222        return args
4223    args = args + ["--expert-profile-save", save]
4224    every = cfg.get("expert_profile_save_every")
4225    if isinstance(every, (int, float)) and not isinstance(every, bool) and every >= 0:
4226        args += ["--expert-profile-save-every", str(every)]
4227    if "--expert-profile" in args[:-1]:
4228        i = args.index("--expert-profile") + 1
4229        here = cfg.get("cwd") or "."
4230        learned = profile_shape(save if os.path.isabs(save) else os.path.join(here, save))
4231        base = profile_shape(args[i] if os.path.isabs(args[i]) else os.path.join(here, args[i]))
4232        if learned is not None and learned == base:
4233            args[i] = save
4234    return args
4235
4236
4237DRAFT_COSTS_DEFAULT_PLATFORMS = ("darwin",)   # Metal: the taken-over table measured above live costs there (M5 Max: Q2_0 code +2.6 %, chat +2.4 %, JSON +0.2 %; IQ3_S +0.2 / +0.6 / +0.7 %)
4238
4239
4240def draft_costs_default(platform: str | None = None) -> bool:
4241    """Repeatable output (owner decision) is the default only where the table was measured at or above live costs: Metal.  On CUDA (RTX PRO 5000, IQ3_S: code
4242    -1.5 %, chat -1.5 %, JSON +1.9 % against live costs) and HIP the engine keeps live costs, as an engine started without --draft-costs does.  `"draft_costs": true`
4243    in a config turns the table on anywhere (tests and A/Bs), `"draft_costs": false` turns it off."""
4244    return (platform or sys.platform) in DRAFT_COSTS_DEFAULT_PLATFORMS
4245
4246
4247DRAFT_COSTS_DEFAULT = draft_costs_default()    # "draft_costs": true / false in a config overrides it
4248_engine_texts: dict = {}
4249
4250
4251def engine_has_text(exe: str, needle: bytes) -> bool | None:
4252    """Does the engine program contain `needle` (an option it knows)?  None when it cannot be read.  Read once per path, size and time."""
4253    import mmap
4254    try:
4255        st = os.stat(exe)
4256    except (OSError, ValueError):
4257        return None
4258    key = (str(exe), st.st_size, st.st_mtime_ns, needle)
4259    if key not in _engine_texts:
4260        try:
4261            with open(exe, "rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
4262                _engine_texts[key] = data.find(needle) >= 0
4263        except (OSError, ValueError):
4264            _engine_texts[key] = None
4265    return _engine_texts[key]
4266
4267
4268def draft_costs_dir() -> Path:
4269    """Where the learned draft cost tables live: beside the saved tunings (strata_control/presets.py), in the user's Strata settings folder
4270    (%APPDATA%\\Strata\\draft-costs, ~/.config/strata/draft-costs), which the Windows uninstaller's "remove my data" deletes with them.
4271    STRATA_DRAFT_COSTS_DIR: another folder (tests and test jobs, which never write into a real settings folder)."""
4272    explicit = os.environ.get("STRATA_DRAFT_COSTS_DIR")
4273    if explicit:
4274        return Path(explicit).expanduser()
4275    from strata_control import profiles
4276    return profiles.profile_dir().parent / "draft-costs"
4277
4278
4279def draft_costs_args(cfg: dict, args: list[str], exe: str | None = None) -> list[str]:
4280    """Repeatable output: the engine (0.1.60+ with --draft-costs) fixes its draft window costs to a table it learned once on this computer, so
4281    the same request gives the same answer on every start; until the table exists it learns it in the background with today's policy.
4282    "draft_costs": true / false in the config overrides DRAFT_COSTS_DEFAULT.  The file name follows the model and every engine argument, so
4283    another model or setting gets its own table; the engine itself checks the card, the driver and its own version inside the file and
4284    learns again when they changed.  An engine that does not know the flag is not given it."""
4285    explicit = "draft_costs" in cfg
4286    want = cfg.get("draft_costs", DRAFT_COSTS_DEFAULT)
4287    if want is not True or "--draft-costs" in args:
4288        return args
4289    knows = engine_has_text(exe, b"--draft-costs") if exe else None
4290    # by default only an engine that is seen to have the option gets it; a config that asks for it by name gets it unless the engine is seen without it
4291    if knows is False or (not explicit and knows is not True):
4292        return args
4293    name = re.sub(r"[^A-Za-z0-9._-]+", "-", str(cfg.get("model_name") or "model"))[:64]
4294    digest = hashlib.sha256("\0".join(map(str, args)).encode("utf-8", "replace")).hexdigest()[:12]
4295    out = args + ["--draft-costs", str(draft_costs_dir() / f"{name}-{digest}.costs")]
4296    try:
4297        size = os.path.getsize(exe) if exe else None
4298    except OSError:
4299        size = None
4300    if size:
4301        out += ["--draft-costs-key", f"engine file {size} bytes"]
4302    return out
4303
4304
4305def hip_visible(cfg: dict) -> list[int]:
4306    """AMD: the devices the engine should see, as the HIP runtime numbers them (HIP_VISIBLE_DEVICES).
4307
4308    On Linux setup's KFD order is HIP's order, so the config's "gpu" is it.  On Windows setup finds the cards in the
4309    display-adapter order, and an integrated Radeon that HIP also enumerates takes ordinal 0 and pushes the discrete
4310    card to 1 (#325): setup records the ordinal `strata-device --list-devices` gave the card as "hip_ordinal", which
4311    wins for a one-card config.  Without it (a config from before), the config's "gpu"."""
4312    ordinal = cfg.get("hip_ordinal")
4313    if ordinal is not None and str(ordinal).strip() != "" and len(gpu_list(cfg)) <= 1:
4314        try:
4315            return [int(str(ordinal).strip())]
4316        except ValueError:
4317            pass
4318    return ordered_gpus(cfg)
4319
4320
4321def gpu_speed_scores(indices: list[int]) -> dict[int, float] | None:
4322    """Multiprocessors x max clock for each NVIDIA card, numbered as nvidia-smi numbers them (the CUDA driver API,
4323    which every driver ships: no toolkit needed); None when it cannot say for every one of them."""
4324    code = (
4325        "import ctypes,sys,os\n"
4326        "os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'\n"
4327        "lib=ctypes.CDLL('nvcuda.dll' if os.name=='nt' else 'libcuda.so.1')\n"
4328        "assert lib.cuInit(0)==0\n"
4329        "n=ctypes.c_int()\n"
4330        "assert lib.cuDeviceGetCount(ctypes.byref(n))==0\n"
4331        "for i in range(n.value):\n"
4332        "    d=ctypes.c_int()\n"
4333        "    assert lib.cuDeviceGet(ctypes.byref(d),i)==0\n"
4334        "    sm=ctypes.c_int(); mhz=ctypes.c_int()\n"
4335        "    lib.cuDeviceGetAttribute(ctypes.byref(sm),16,d)\n"
4336        "    lib.cuDeviceGetAttribute(ctypes.byref(mhz),13,d)\n"
4337        "    print(i,sm.value,mhz.value)\n")
4338    try:
4339        env = dict(os.environ)
4340        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
4341        env.pop("CUDA_VISIBLE_DEVICES", None)
4342        r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30, env=env)
4343        got = {}
4344        for line in r.stdout.splitlines():
4345            i, sm, khz = (int(x) for x in line.split())
4346            got[i] = float(sm) * float(khz)
4347    except (OSError, ValueError, subprocess.SubprocessError):
4348        return None
4349    return got if all(i in got and got[i] > 0 for i in indices) else None
4350
4351
4352def hip_speed_scores(indices: list[int], root: str = "/sys/class/kfd/kfd/topology/nodes") -> dict[int, float] | None:
4353    """AMD on Linux: SIMDs x max engine clock of each card, from the KFD topology (the order setup and the engine use
4354    for "gpu" there: the GPU nodes in node order).  None when the files are not there (Windows, no ROCm driver)."""
4355    try:
4356        nodes = sorted((int(n) for n in os.listdir(root) if n.isdigit()))
4357    except OSError:
4358        return None
4359    cards = []
4360    for n in nodes:
4361        try:
4362            with open(os.path.join(root, str(n), "properties")) as fh:
4363                props = dict(line.split() for line in fh if len(line.split()) == 2)
4364            simd, clk = int(props.get("simd_count", 0)), int(props.get("max_engine_clk_fcompute", 0))
4365        except (OSError, ValueError):
4366            continue
4367        if simd > 0:
4368            cards.append(float(simd) * float(clk or 1))
4369    got = dict(enumerate(cards))
4370    return got if all(i in got for i in indices) else None
4371
4372
4373def engine_nice(env: dict | None = None, archs: dict[int, str] | None = None, platform: str | None = None) -> int:
4374    """Linux only: the nice value the engine starts with.  The engine's CPU pool spins at 100% on every physical core but one and its host
4375    thread on another; with the desktop drawn by a built-in Radeon (HIP_IGPU_ARCHS: Strix Halo and the other APUs) the compositor then
4376    competes with them for the CPU, which reads as a frozen screen.  +5 gives the desktop its share and costs nothing when nothing else
4377    runs.  STRATA_ENGINE_NICE=N sets it (0 = off, also for any PC without such a chip).  Not on Windows / macOS."""
4378    if not (platform or sys.platform).startswith("linux"):
4379        return 0
4380    asked = (env or os.environ).get("STRATA_ENGINE_NICE")
4381    if asked is not None and str(asked).strip() != "":
4382        try:
4383            return max(0, min(19, int(str(asked).strip())))
4384        except ValueError:
4385            return 0
4386    ar = archs if archs is not None else hip_gpu_archs()
4387    return 5 if ar and any(a in HIP_IGPU_ARCHS for a in ar.values()) else 0
4388
4389
4390def hip_gpu_archs(root: str = "/sys/class/kfd/kfd/topology/nodes") -> dict[int, str] | None:
4391    """AMD on Linux: {HIP ordinal: "gfx1151"} from the KFD topology (GPU nodes in node order, as hip_speed_scores and setup number them).
4392    None when the files are not there (Windows, no ROCm driver)."""
4393    try:
4394        nodes = sorted(int(n) for n in os.listdir(root) if n.isdigit())
4395    except OSError:
4396        return None
4397    out: dict[int, str] = {}
4398    for n in nodes:
4399        try:
4400            with open(os.path.join(root, str(n), "properties")) as fh:
4401                props = dict(line.split() for line in fh if len(line.split()) == 2)
4402            ver, simd = int(props.get("gfx_target_version", 0)), int(props.get("simd_count", 0))
4403        except (OSError, ValueError):
4404            continue
4405        if simd > 0 and ver > 0:
4406            out[len(out)] = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}"
4407    return out or None
4408
4409
4410def igpu_cards(indices: list[int], archs: dict[int, str] | None) -> set[int]:
4411    """The cards of `indices` that are integrated (their memory is the system RAM, and they usually draw the desktop)."""
4412    return {i for i in indices if archs and archs.get(i) in HIP_IGPU_ARCHS}
4413
4414
4415def gpu_vram_mib(indices: list[int], hip: bool = False) -> dict[int, int] | None:
4416    """Total VRAM of each card in MiB (NVML / amdgpu sysfs); None when any of them cannot be read."""
4417    try:
4418        from serve.telemetry import gpu_reader
4419    except ImportError:
4420        return None
4421    out = {}
4422    for i in indices:
4423        g = gpu_reader(i, amd=hip)
4424        if not g.ok():
4425            return None
4426        total = g.read().get("mem_total")
4427        if total is None:
4428            return None
4429        out[i] = int(total) >> 20
4430    return out
4431
4432
4433def ordered_gpus(cfg: dict, scores=None, vrams=None, archs=None) -> list[int]:
4434    """#1352: the cards of a layer split in the order the engine stages them.  With "layer_split": "auto" (the
4435    default) the faster card goes LAST - the last stage runs the head, the draft layer and the verify, and a prompt
4436    chunk waits on it (the reporter's 4070 Ti SUPER + 5060 Ti: a 6K prompt took 50 s one way round and 15 s the
4437    other); "faster" is multiprocessors x max clock.  Equal cards - scores within 5% - keep the config's order, and
4438    so does anything we cannot measure.  "gpu_order": "as_given" keeps the config's order whatever the cards.  A
4439    manual "layer_split" ("24") also keeps it: the user placed the layers.  #1576: the reorder is skipped when it
4440    would land the last stage on a card with less total VRAM than the one the config put there - that stage's head,
4441    draft and verify have a floor the smaller card cannot afford.  scores/vrams: {index: value} (tests); None asks
4442    the driver - injected scores without injected vrams means no VRAM check (a test seam is a test seam)."""
4443    gl = gpu_list(cfg)
4444    if len(gl) < 2 or cfg.get("gpu_order") == "as_given" or gpu_roles_active(cfg):
4445        return gl
4446    args = cfg.get("args") or []
4447    if "--peer-device" in args or "--layer-split" in args or layer_split_value(cfg) != "auto":
4448        return gl
4449    hip = cfg.get("backend") == "hip"
4450    if hip:
4451        # An integrated Radeon (Strix Halo beside an R9700) is never the LAST stage: that stage runs the head, the draft layer and the
4452        # check of the guesses, and the iGPU usually draws the desktop.  Its "VRAM" is the BIOS carve-out (up to 96 GB), which made the
4453        # #1576 memory guard below keep it last.  It goes first, the cards with memory of their own follow in speed order.
4454        # archs: {index: "gfx1151"} (tests); None asks the KFD topology, unless scores were injected (a test seam).
4455        ar = archs if archs is not None else (hip_gpu_archs() if scores is None else None)
4456        ig = igpu_cards(gl, ar)
4457        if ig and len(ig) < len(gl):
4458            sc0 = scores if scores is not None else hip_speed_scores(gl)
4459            rest = [i for i in gl if i not in ig]
4460            if sc0 and all(i in sc0 for i in rest):
4461                rest = sorted(rest, key=lambda i: sc0[i]) if max(sc0[i] for i in rest) >= 1.05 * min(sc0[i] for i in rest) else rest
4462            out = [i for i in gl if i in ig] + rest
4463            if out != gl:
4464                print(f"[strata] layer split: card order {','.join(map(str, out))} (GPU {','.join(str(i) for i in sorted(ig))} is built-in "
4465                      f"graphics: it takes the first layers, never the last stage; \"gpu_order\": \"as_given\" keeps {','.join(map(str, gl))})",
4466                      flush=True)
4467            return out
4468    sc = scores if scores is not None else (hip_speed_scores(gl) if hip else gpu_speed_scores(gl))
4469    if not sc or any(i not in sc for i in gl):
4470        return gl
4471    # the decision itself (5% rule #1760, faster card last #1352, VRAM guard #1576) is strata_control/gpu_roles.speed_stage_order, which `strata launch --plan`
4472    # calls too (gpu_roles.from_legacy), so the plan names the same Main card as this start
4473    out, why, seen = gpu_roles.speed_stage_order(
4474        gl, sc, vrams if vrams is not None else (None if scores is not None else (lambda: gpu_vram_mib(gl, hip))))
4475    if why == "kept-vram":
4476        print(f"[strata] layer split: keeping card order {','.join(map(str, gl))} - the faster card has "
4477              f"less VRAM than the one the split ends on ({seen[0]} vs {seen[1]} MiB, #1576)",
4478              flush=True)
4479    elif why == "faster-last":
4480        print(f"[strata] layer split: card order {','.join(map(str, out))} (the faster card last; "
4481              f'"gpu_order": "as_given" keeps {",".join(map(str, gl))}, #1352)', flush=True)
4482    return out
4483
4484
4485#: AMD chips that share the system memory (an iGPU): never preferred over a card that has memory of its own.
4486HIP_IGPU_ARCHS = ("gfx1035", "gfx1036", "gfx1037", "gfx1103", "gfx1150", "gfx1151", "gfx1152", "gfx90c")
4487
4488
4489def parse_hip_devices(text: str) -> list[dict]:
4490    """`strata-device --list-devices`: [{"index", "name", "arch", "vram_gb", "integrated", "cannot_run"}], numbered as the HIP runtime numbers them."""
4491    found: list[dict] = []
4492    for line in text.splitlines():
4493        s = line.strip()
4494        m = re.match(r"device\s+(\d+):\s*(.*)$", s)
4495        if m:
4496            found.append({"index": int(m.group(1)), "name": m.group(2).strip(), "arch": "", "vram_gb": 0.0, "integrated": False, "cannot_run": None})
4497            continue
4498        if not found:
4499            continue
4500        a = re.match(r"arch\s+(gfx[0-9a-f]+)\s*,\s*([\d.]+)\s*GiB(.*)$", s)
4501        if a and not found[-1]["arch"]:
4502            found[-1]["arch"], found[-1]["vram_gb"] = a.group(1), float(a.group(2))
4503            found[-1]["integrated"] = "integrated" in a.group(3)      # a newer engine says so itself
4504        elif s.startswith("cannot run:"):
4505            found[-1]["cannot_run"] = s[len("cannot run:"):].strip()
4506    for d in found:
4507        d["integrated"] = d["integrated"] or d["arch"] in HIP_IGPU_ARCHS
4508    return found
4509
4510
4511def hip_no_card_message(devices: list[dict]) -> str:
4512    """The plain line when the engine has code for none of the computer's cards."""
4513    cards = ", ".join(f"{d['name'] or 'graphics card'} ({d['arch'] or 'unknown'}{', integrated' if d['integrated'] else ''})" for d in devices)
4514    built = next((m.group(1) for d in devices for m in [re.search(r"compiled for \(([^)]*)\)", d["cannot_run"] or "")] if m), "")
4515    text = f"[strata] none of this computer's graphics cards has code in this Strata engine{f' (it is built for {built})' if built else ''}. Cards found: {cards}."
4516    note = engine_component.no_package_note([d["arch"] for d in devices])
4517    return text + (f" {note}" if note else "")
4518
4519
4520def pick_hip_devices(devices: list[dict]) -> tuple[list[int] | None, str | None]:
4521    """Which card an "Automatic" start runs on: (HIP_VISIBLE_DEVICES to set, or None to leave the runtime's own order; a plain problem or
4522    None).  Cards this engine has no code for are skipped, and so are integrated chips while a card of its own can run (#3203: a mini PC's
4523    Radeon 760M is HIP's device 0 and the engine died on it; the RX 6800 XT behind it was never tried).  When device 0 is already the right
4524    kind nothing changes."""
4525    if not devices:
4526        return None, None
4527    runnable = [d for d in devices if not d["cannot_run"]]
4528    if not runnable:
4529        return None, hip_no_card_message(devices)
4530    pool = [d for d in runnable if not d["integrated"]] or runnable
4531    if devices[0] in pool:
4532        return None, None
4533    best = max(pool, key=lambda d: (round(d["vram_gb"]), -d["index"]))
4534    return [best["index"]], None
4535
4536
4537def hip_auto_devices(cfg: dict, env: dict) -> list[int] | None:
4538    """HIP_VISIBLE_DEVICES for a start that names no card (see pick_hip_devices), asked of the engine package's own `strata-device`.
4539    None leaves everything as it was: a card the config or the environment names, no probe next to the engine, or a probe that fails.
4540    SystemExit with the plain line when no card of this computer can run."""
4541    if cfg.get("backend") != "hip" or gpu_list(cfg) or gpu_all_off(cfg) or str(cfg.get("hip_ordinal") if cfg.get("hip_ordinal") is not None else "").strip() \
4542            or env.get("HIP_VISIBLE_DEVICES") or env.get("ROCR_VISIBLE_DEVICES"):
4543        return None
4544    exe = cfg.get("exe")
4545    if not isinstance(exe, str) or not exe or engine_component.is_reference(exe):
4546        return None
4547    probe = Path(exe).with_name("strata-device.exe" if os.name == "nt" else "strata-device")
4548    if not probe.is_file():
4549        return None
4550    try:
4551        done = subprocess.run([str(probe), "--list-devices"], capture_output=True, text=True, timeout=60, cwd=str(probe.parent), env=env,
4552                              creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
4553    except (OSError, subprocess.SubprocessError):
4554        return None
4555    if done.returncode != 0:
4556        return None
4557    devices = parse_hip_devices(done.stdout)
4558    visible, problem = pick_hip_devices(devices)
4559    if problem:
4560        raise SystemExit(problem)
4561    if visible:
4562        d = next(x for x in devices if x["index"] == visible[0])
4563        print(f"[strata] automatic GPU choice: GPU {d['index']} ({d['name']}, {d['arch']}); the engine skips cards it has no code for and "
4564              f"integrated chips while a card of its own can run", flush=True)
4565    return visible
4566
4567
4568DS41_SLOT_KEEP_DEFAULT = "1"      # the engine keeps a displaced conversation in RAM and in the slot folder (see below)
4569DS41_SLOT_GB_DEFAULT = "2"        # the folder's cap in GB (a 6.5K-token conversation is about 17 MB)
4570
4571
4572def deepseek_slot_env(env: dict, cfg: dict) -> None:
4573    """DeepSeek-V4.1 only.  The engine sets a conversation aside when another request takes the model and takes it back
4574    at its checkpoints (agents and sub-agents that take turns do not read their prompts again).  STRATA_DS4_SLOT_KEEP
4575    switches it (the default above; a config's env or the shell wins); the folder is `ds4-slots` next to the run log, in
4576    Strata's data folder (STRATA_DS4_SLOT_DIR names another), and the engine caps it (STRATA_DS4_SLOT_GB, 2 here, 16 in the engine) and
4577    removes what is older than a week or not this model's.  On by default; STRATA_DS4_SLOT_KEEP=0 turns it off."""
4578    env.setdefault("STRATA_DS4_SLOT_KEEP", DS41_SLOT_KEEP_DEFAULT)
4579    env.setdefault("STRATA_DS4_SLOT_GB", DS41_SLOT_GB_DEFAULT)
4580    log = cfg.get("log")
4581    if "STRATA_DS4_SLOT_DIR" not in env and log:
4582        env["STRATA_DS4_SLOT_DIR"] = str(Path(log).parent / "ds4-slots")
4583
4584
4585# 0.2.10: the two parts that need the card's free VRAM are the ENGINE's own, never an environment variable of ours: the FP16 weight
4586# cache (bit-exact; takes only VRAM beyond 3 GiB kept free) and no loan of cache slots (only when every expert is resident and the
4587# prompt path's own buffers fit beside 3 GiB; KL 0.006, QUAL-PAR2).  STRATA_PF_W16_CACHE_MIB=0 and STRATA_AUTO_NOBORROW=0 turn them off.
4588# (The parallel-request stack, the GDN prompt speedups, the Q8_0 hyper-connection read and the fp16 decode windows are the engine's own defaults now:
4589# src/core/arch_defaults.cpp, generate.cpp, metal window.cpp.  Nothing here sets them.)
4590
4591
4592def parallel_slots(cfg: dict) -> int:
4593    """How many batch slots the config asks for (0 = none): the args' own --batch/--slots, else "parallel"."""
4594    args = list(cfg.get("args") or [])
4595    for k in ("--batch", "--slots"):
4596        if k in args:
4597            try:
4598                return int(args[args.index(k) + 1])
4599            except (IndexError, ValueError):
4600                return 0
4601    n = cfg.get("parallel")
4602    return n if isinstance(n, int) and not isinstance(n, bool) and n > 1 else 0
4603
4604
4605def child_env(cfg: dict, *, offline: bool = False) -> dict:
4606    """The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that
4607    compiled it) first on the library search path."""
4608    env = quiet_crash_env(dict(os.environ))          # no debugger on a user's machine: ggml's abort path forks gdb (strata_control/childenv.py)
4609    if gpu_all_off(cfg):                             # every card Off: the engine sees none (a CPU engine runs; the others say so at start)
4610        env["CUDA_VISIBLE_DEVICES"] = ""
4611        env["HIP_VISIBLE_DEVICES"] = ""
4612    elif hip_visible(cfg) and cfg.get("backend") == "hip":   # AMD: numbered as HIP numbers them (hip_visible)
4613        env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in hip_visible(cfg))
4614    elif gpu_list(cfg):                              # issue #51: the GPU(s) to run on, numbered as nvidia-smi does; CUDA's
4615        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"      # own default order (fastest first) can number the cards otherwise
4616        env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in ordered_gpus(cfg))
4617    for k, v in (cfg.get("env") or {}).items():      # engine settings the config carries (AMD: the GEMM tuning table)
4618        env[str(k)] = str(v)
4619    if (cfg.get("arch") or "") == "deepseek41":      # (only this engine reads these; Qwen's environment is untouched)
4620        deepseek_slot_env(env, cfg)
4621    # Strict offline reaches children through the environment, because a tool subprocess or a model
4622    # loader is code this server does not own. Applied last so a profile's own `env` cannot remove
4623    # the policy by naming the same variable.
4624    if offline:
4625        try:
4626            from strata_control import offline as offline_policy
4627            env.update(offline_policy.OFFLINE_ENV)
4628        except ImportError:
4629            # The policy module is part of the application; without it, refuse rather than silently
4630            # running a child with network access under a flag that promised otherwise.
4631            env["STRATA_OFFLINE"] = "1"
4632            env["HF_HUB_OFFLINE"] = "1"
4633            env["TRANSFORMERS_OFFLINE"] = "1"
4634    dirs = [d for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()]
4635    if dirs:
4636        var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
4637        env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else []))
4638    if cfg.get("backend") == "hip":
4639        hip_env_guard(env, cfg)
4640        note = sh_stream_warning(env, cfg)
4641        if note:
4642            print(note, flush=True)
4643        auto = hip_auto_devices(cfg, env)
4644        if auto:
4645            env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in auto)
4646    return env
4647
4648
4649def _dir_writable(p: str) -> bool:
4650    try:
4651        with tempfile.TemporaryFile(dir=p):
4652            return True
4653    except OSError:
4654        return False
4655
4656
4657def sh_stream_warning(env: dict, cfg: dict) -> str | None:
4658    """#3895: the shared-expert fork (STRATA_SH_STREAM=1) together with KV streaming (--kv-resident) made one Windows RX 6900 XT fail on the first
4659    request ("verify: unspecified launch failure"); each alone, or Linux, did not. A warning, not a refusal: the person set the variable, the
4660    engine runs as asked, and the line says what to take out."""
4661    if os.name != "nt" or str(env.get("STRATA_SH_STREAM", "")).strip() in ("", "0"):
4662        return None
4663    args = [str(a) for a in cfg.get("args") or []]
4664    if "--kv-resident" not in args:
4665        return None
4666    return ("[strata] WARNING: STRATA_SH_STREAM=1 with --kv-resident (KV streaming) failed on the first request on one Windows RX 6000 PC "
4667            "(\"verify: unspecified launch failure\", #3895). If the engine stops that way, take STRATA_SH_STREAM out of the config's env "
4668            "(AMD runs without it by default) or run without --kv-resident, and tell us the card and the driver.")
4669
4670
4671def hip_env_guard(env: dict, cfg: dict) -> list[str]:
4672    """#654: two things in an AMD user's environment that crash the HIP runtime before it prints a line.  (1) HIP_PATH,
4673    HIP_DEVICE_LIB_PATH or LLVM_PATH naming a folder that is gone (a ROCm build that was deleted): the bundled runtime
4674    follows them.  They are dropped, and only when the folder does not exist.  (2) A TEMP / TMP / TMPDIR the engine cannot
4675    create a file in: the runtime's comgr JIT builds its blit kernels through temporary files and the first call
4676    crashes in amdhip64 (0xC0000005).  A writable folder next to the engine's log takes its place.  Returns what it
4677    changed (said once, on stderr); a healthy environment is left exactly as it was."""
4678    said: list[str] = []
4679    for k in ("HIP_PATH", "HIP_DEVICE_LIB_PATH", "LLVM_PATH"):
4680        v = env.get(k)
4681        if v and not Path(v).exists():
4682            del env[k]
4683            said.append(f"{k}={v} does not exist: not passed to the engine")
4684    bad = [k for k in ("TEMP", "TMP", "TMPDIR") if env.get(k) and not _dir_writable(env[k])]
4685    if bad:
4686        base = Path(cfg.get("log") or cfg.get("cwd") or ROOT).resolve()
4687        for d in (base.parent / "tmp", ROOT / "tmp"):
4688            try:
4689                d.mkdir(parents=True, exist_ok=True)
4690            except OSError:
4691                continue
4692            if _dir_writable(str(d)):
4693                for k in bad:
4694                    said.append(f"{k}={env[k]} is not writable: using {d}")
4695                    env[k] = str(d)
4696                break
4697        else:
4698            said.append(f"{', '.join(bad)} not writable (AMD's runtime needs a writable temporary folder)")
4699    for line in said:
4700        print(f"strata serve: AMD: {line}", file=sys.stderr, flush=True)
4701    return said
4702
4703
4704def igpu_split_warning(cfg: dict, archs: dict[int, str] | None = None) -> str | None:
4705    """A plain line when the layers are split over built-in Radeon graphics AND a card with memory of its own.  A recommendation, not a
4706    refusal: the split runs as asked.  The iGPU's memory is the RAM, it usually draws the desktop, and compute on it can freeze the screen."""
4707    if cfg.get("backend") != "hip":
4708        return None
4709    gl = gpu_list(cfg)
4710    if len(gl) < 2:
4711        return None
4712    ar = archs if archs is not None else hip_gpu_archs()
4713    ig = igpu_cards(gl, ar)
4714    if not ig or len(ig) == len(gl):
4715        return None
4716    return ("[strata] note: GPU " + ", ".join(str(i) for i in sorted(ig)) + " is built-in graphics (its memory is the system RAM, and it "
4717            "usually draws the desktop). Running part of the model on it can freeze the screen and uses RAM twice; the cards with memory of "
4718            "their own are faster alone (docs/STRIX_HALO.md). Turn it Off in the card roles, or name only the other card, to leave it out")
4719
4720
4721def card_note(cfg: dict, env: dict) -> str | None:
4722    """One plain line that ties the engine's own numbering to the person's: the engine counts the cards it is given from 0 ("GPU 0",
4723    "CUDA0" in its log), so a person who chose GPU 1 would read "GPU 0" and think the choice was lost.  Said only when the two differ
4724    (NVIDIA, numbered as nvidia-smi numbers them); None otherwise."""
4725    if cfg.get("backend") == "hip" or not gpu_list(cfg):
4726        return None
4727    mine = [x.strip() for x in str((env or {}).get("CUDA_VISIBLE_DEVICES", "")).split(",") if x.strip() != ""]
4728    if not mine or mine == [str(i) for i in range(len(mine))]:
4729        return None
4730    names = [f"CUDA{i}" for i in range(len(mine))]
4731    if len(mine) == 1:
4732        return f"[strata] running on GPU {mine[0]} (as nvidia-smi numbers it); the engine's log calls it GPU 0 / CUDA0"
4733    return (f"[strata] cards in stage order: GPU {', then GPU '.join(mine)} (as nvidia-smi numbers them); the engine's log calls them "
4734            f"{', '.join(names)} - the first runs the first layers and the picture reader, the last runs the head and the draft layer")
4735
4736
4737def engine_arch_note(cfg: dict, cards: dict[int, int] | None = None, built: dict | None = None) -> str | None:
4738    """#4662: a compiled engine holds code for the architectures it was built for (BUILD.json "archs"); on a card of another one a long prompt
4739    ends in "unspecified launch failure" (the kernels it needs are a trap there).  One plain line when a card this run uses is not covered
4740    (NVIDIA; a build with PTX also covers newer cards).  Said, never refused: the engine is started as asked.  `cards`: {nvidia-smi number:
4741    compute capability x 10}; `built`: the BUILD.json dict - both read here when not given.  None when everything is covered or unknown."""
4742    try:
4743        if cfg.get("backend") == "hip":
4744            return None
4745        if built is None:
4746            exe = cfg.get("exe")
4747            if not isinstance(exe, str) or engine_component.is_reference(exe):
4748                return None
4749            built = json.loads((Path(exe).parent / "BUILD.json").read_text(encoding="utf-8-sig"))
4750        archs = sorted({int(re.sub(r"\D", "", str(a))) for a in built.get("archs") or [] if re.sub(r"\D", "", str(a))})
4751        if not archs:
4752            return None
4753        if cards is None:
4754            r = subprocess.run(["nvidia-smi", "--query-gpu=index,compute_cap", "--format=csv,noheader"], capture_output=True, text=True,
4755                               errors="replace", timeout=10)
4756            cards = {int(i): int(round(float(c) * 10)) for i, c in (ln.split(",") for ln in (r.stdout or "").strip().splitlines())}
4757        used = gpu_list(cfg) or sorted(cards)
4758        miss = sorted({cards[i] for i in used if i in cards and cards[i] not in archs and not (built.get("ptx") and cards[i] > max(archs))})
4759        if not miss:
4760            return None
4761        names = ", ".join(f"sm_{m}" for m in miss)
4762        return (f"[strata] this engine was built for {', '.join(f'sm_{a}' for a in archs)}, but a graphics card in use is {names}: long prompts "
4763                "can stop with \"unspecified launch failure\". Update the engine (./update.sh, or `strata update`) so it is built for every card in this PC.")
4764    except Exception:
4765        return None
4766
4767
4768def vision_card_off_igpu(env: dict, archs: dict[int, str] | None = None) -> int | None:
4769    """AMD: the picture reader is a separate program that sees the engine's HIP_VISIBLE_DEVICES and runs on the FIRST visible card.  With a
4770    layer split that starts on a built-in Radeon (Strix Halo beside an R9700) that is the iGPU: the card that draws the desktop and whose
4771    memory is the RAM the experts live in.  Returns the HIP ordinal of the last visible card with memory of its own (the Main stage), or
4772    None when nothing needs changing (one card, no integrated chip among them, or the topology is unknown)."""
4773    vis = [x.strip() for x in str(env.get("HIP_VISIBLE_DEVICES") or "").split(",") if x.strip().isdigit()]
4774    if len(vis) < 2:
4775        return None
4776    idx = [int(x) for x in vis]
4777    ar = archs if archs is not None else hip_gpu_archs()
4778    ig = igpu_cards(idx, ar)
4779    own = [i for i in idx if i not in ig and ar and i in ar]
4780    if not ig or not own:
4781        return None
4782    print(f"[strata] the picture reader runs on GPU {own[-1]}, not on the built-in graphics (GPU {','.join(str(i) for i in sorted(ig))}) "
4783          "that draws the desktop; \"vision\": {\"cuda_device\": N} chooses another card", flush=True)
4784    return own[-1]
4785
4786
4787def vision_env(cfg: dict, env: dict, archs: dict[int, str] | None = None) -> dict:
4788    """The image encoder's environment: the engine's, unless the config's vision section names its own "cuda_device"
4789    (numbered like nvidia-smi) - then the encoder runs on that card alone, so a spare GPU can hold it while the engine
4790    keeps all of its own cards' VRAM (#408, Efs-O).  Without it, nothing changes."""
4791    dev = (cfg.get("vision") or {}).get("cuda_device")
4792    if dev is None and cfg.get("backend") == "hip":
4793        dev = vision_card_off_igpu(env, archs)
4794    if dev is None:
4795        return env
4796    env = dict(env)
4797    if cfg.get("backend") == "hip":
4798        env["HIP_VISIBLE_DEVICES"] = str(dev)
4799    else:
4800        env["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
4801        env["CUDA_VISIBLE_DEVICES"] = str(dev)
4802    return env
4803
4804
4805class ByteTokenizer:
4806    """Tiny stand-in tokenizer for tests without the pack: one id per UTF-8 byte, specials as ids >= 256."""
4807    SPECIALS = ["<|im_start|>", "<|im_end|>", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"]
4808
4809    ALWAYS = ()                                     # specials matched without parse_special (type 4, as <think>)
4810
4811    @property
4812    def max_special_len(self):
4813        return max(len(s) for s in self.SPECIALS)
4814
4815    @property
4816    def control_tokens(self):
4817        return [s for s in self.SPECIALS if s not in self.ALWAYS]
4818
4819    def encode(self, text, parse_special=False, plain=()):
4820        return self.encode_marked(text, parse_special, plain)[0]
4821
4822    def encode_marked(self, text, parse_special=False, plain=()):
4823        """encode() and its resume points (after each special), as strata_tokenizer's for PromptEncoder."""
4824        out, marks, i = [], [], 0
4825        while i < len(text):
4826            for k, s in enumerate(self.SPECIALS):
4827                if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any(
4828                        a <= i < b for a, b in plain):
4829                    out.append(256 + k)
4830                    i += len(s)
4831                    marks.append((i, len(out)))
4832                    break
4833            else:
4834                out.extend(text[i].encode("utf-8"))
4835                i += 1
4836        return out, marks
4837
4838    def decode(self, ids, errors="replace"):
4839        raw = bytearray()
4840        for t in ids:
4841            raw += self.SPECIALS[t - 256].encode() if t >= 256 else bytes([t])
4842        return raw.decode("utf-8", errors=errors)
4843
4844
4845# ------------------------------------------------------------------------------------------------ end tokens
4846def end_token_ids(tokenizer) -> set[int]:
4847    """The ids that end a reply for a tokenizer whose family was not named (Service.set_family sets them for DeepSeek).
4848
4849    Qwen's <|im_end|> and <|endoftext|> end a reply only where each is ONE token.  A tokenizer without them (DeepSeek-V4.1's
4850    splits "<|im_end|>" into '<', '|', 'im', '_end', '|', '>') would make every piece of them a stop id: the reply ended in front
4851    of the first "|", ">", "end", "of", "text" or "im" it wrote, so "Nerazim" came out as "Neraz" (#4576, and a table's first
4852    "|" in #4137).  Those ids are left out, and the end token the tokenizer names (special_ids "eos") ends the reply instead."""
4853    ids: set[int] = set()
4854    for marker in (IM_END, "<|endoftext|>"):
4855        got = tokenizer.encode(marker, parse_special=True)
4856        if len(got) == 1:
4857            ids.add(int(got[0]))
4858    if not ids:
4859        eos = (getattr(tokenizer, "special_ids", None) or {}).get("eos")
4860        if eos is not None:
4861            ids.add(int(eos))
4862    return ids
4863
4864
4865# ------------------------------------------------------------------------------------------------ core
4866class Detokenizer:
4867    """Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete
4868    characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become
4869    U+FFFD, as a whole decode with errors="replace" makes them).  Constant time per token - the old re-decode of
4870    every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1).  A tokenizer
4871    without `token_bytes` (the tests' byte tokenizer) keeps the re-decode."""
4872
4873    def __init__(self, tok):
4874        self.tok, self.ids, self.sent = tok, [], 0
4875        self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None
4876
4877    def pending(self) -> bool:
4878        """A character is split across the tokens so far: its first bytes are held."""
4879        if self.inc is not None:
4880            return bool(self.inc.getstate()[0])
4881        return self.tok.decode(self.ids).endswith("\ufffd")
4882
4883    def push(self, t: int) -> str:
4884        if self.inc is not None:
4885            return self.inc.decode(self.tok.token_bytes(t))
4886        self.ids.append(t)
4887        text = self.tok.decode(self.ids)
4888        if text.endswith("�"):
4889            return ""
4890        delta, self.sent = text[self.sent:], len(text)
4891        return delta
4892
4893
4894OPENAI_MAX_STOP = 4                                  # OpenAI's limit on `stop`
4895
4896
4897#: 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
4898#: 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).
4899SPLIT_REFUSED_FEATURES = ("logprobs", "logit_bias")
4900
4901
4902def refuse_for_split(engine, req: dict) -> None:
4903    if not getattr(engine, "split_engine", False):
4904        return
4905    if top_logprobs(req) is not None:
4906        raise ValueError("logprobs: not supported by the all-cards split engine; start with --split-engine off")
4907
4908
4909def top_logprobs(req: dict):
4910    """The K for the engine's logprobs=K, or None when the request did not ask.
4911
4912    OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form,
4913    "logprobs": N, is taken as N."""
4914    lp = req.get("logprobs")
4915    if lp is True:
4916        k = req.get("top_logprobs")
4917        return max(0, min(20, k)) if isinstance(k, int) and not isinstance(k, bool) else 0
4918    if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0:
4919        return min(20, lp)
4920    return None
4921
4922
4923def allowed_ids(req: dict) -> list:
4924    """`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries)."""
4925    ids = req.get("allowed_token_ids")
4926    if not isinstance(ids, (list, tuple)):
4927        return []
4928    return [x for x in ids if isinstance(x, int) and not isinstance(x, bool) and x >= 0]
4929
4930
4931def batch_slots_on(engine) -> bool:
4932    """Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)?
4933
4934    Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it
4935    counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel`
4936    has none, and reads every reply by the GEN path, which does write them."""
4937    return any(int(getattr(e, "batch", 0) or 0) for e in (getattr(engine, "engines", None) or [engine]))
4938
4939
4940NO_LINE = object()                                   # StrataEngine.generate: no line held after a token
4941
4942
4943def stop_strings(req: dict) -> list[str]:
4944    """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences`
4945    (a list).  Empty strings are left out.  A bad value is a ValueError, so a 400 before anything is generated."""
4946    req = req or {}
4947    if req.get("stop") is not None:
4948        stop = req["stop"]
4949        stop = [stop] if isinstance(stop, str) else stop
4950        if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop):
4951            raise ValueError("stop must be a string or a list of strings")
4952        if len(stop) > OPENAI_MAX_STOP:
4953            raise ValueError(f"stop takes at most {OPENAI_MAX_STOP} strings")
4954    elif req.get("stop_sequences") is not None:
4955        stop = req["stop_sequences"]
4956        if not isinstance(stop, list) or not all(isinstance(x, str) for x in stop):
4957            raise ValueError("stop_sequences must be a list of strings")
4958    else:
4959        return []
4960    return [x for x in stop if x]
4961
4962
4963class StopMatcher:
4964    """Cuts the answer's text at the first stop string.  Text that could still be the start of a stop string is held
4965    back (only that tail, never more), so a stop string split across tokens or chunks is still found and never sent."""
4966
4967    def __init__(self, stops: list[str]):
4968        self.stops, self.held, self.hit = stops, "", None
4969
4970    def push(self, text: str) -> str:
4971        """-> the text that is safe to send now; after a match, self.hit is the stop string and nothing more comes."""
4972        if self.hit is not None:
4973            return ""
4974        buf = self.held + text
4975        first = None
4976        for s in self.stops:
4977            i = buf.find(s)
4978            if i >= 0 and (first is None or i < first[0]):
4979                first = (i, s)
4980        if first is not None:
4981            self.held, self.hit = "", first[1]
4982            return buf[:first[0]]
4983        keep = 0                                      # the longest end of buf that a stop string starts with
4984        for s in self.stops:
4985            for k in range(min(len(s) - 1, len(buf)), keep, -1):
4986                if buf.endswith(s[:k]):
4987                    keep = k
4988                    break
4989        self.held = buf[len(buf) - keep:] if keep else ""
4990        return buf[:len(buf) - keep]
4991
4992    def flush(self) -> str:
4993        held, self.held = self.held, ""
4994        return held
4995
4996
4997
4998# Windows names that open a device whatever their extension or folder (Microsoft, "Naming Files, Paths, and Namespaces")
4999_WIN_DEVICES = {"con", "prn", "aux", "nul", "conin$", "conout$", *(f"com{i}" for i in "123456789\u00b9\u00b2\u00b3"),
5000                *(f"lpt{i}" for i in "123456789\u00b9\u00b2\u00b3")}
5001
5002
5003def slot_filename_problem(name) -> str | None:
5004    """/slots/0 {"filename": NAME}: why NAME is not one plain file name inside the slot save path, on Linux and on
5005    Windows alike (None when it is).  No separator or drive (`D:x`), no stream (`a:b`), no device (`NUL.txt`), no
5006    trailing dot or space (Windows drops them), no control character, no leading dot (temporary files use it)."""
5007    if not isinstance(name, str) or not name:
5008        return "must be a non-empty string"
5009    if len(name.encode("utf-8", "surrogatepass")) > 200:
5010        return "is too long (at most 200 bytes)"
5011    if any(ord(c) < 32 or ord(c) == 127 for c in name):
5012        return "must not contain control characters"
5013    if any(c in name for c in '/\\:*?"<>|'):
5014        return "must be a plain file name (no / \\ : * ? \" < > |)"
5015    if name.startswith("."):
5016        return "must not start with a dot"
5017    if name.endswith((".", " ")):
5018        return "must not end with a dot or a space"
5019    if name.split(".")[0].rstrip(" ").lower() in _WIN_DEVICES:
5020        return "names a Windows device"
5021    try:
5022        name.encode("utf-8")
5023    except UnicodeEncodeError:
5024        return "is not valid Unicode"
5025    return None
5026
5027
5028def slot_save_dir(value, base: str | None = None) -> str:
5029    """The slot save path as one absolute, normalized directory (relative to `base`, else the server's working
5030    directory), created private to this user when missing.  ValueError for anything else."""
5031    if not isinstance(value, str) or not value.strip():
5032        raise ValueError("slot_save_path must be a directory path (a string)")
5033    if any(ord(c) < 32 for c in value):
5034        raise ValueError("slot_save_path must not contain control characters")
5035    path = os.path.abspath(os.path.join(base, value) if base and not os.path.isabs(value) else value)
5036    os.makedirs(path, mode=0o700, exist_ok=True)
5037    if not os.path.isdir(path):
5038        raise ValueError(f"slot_save_path {path} is not a directory")
5039    return path
5040
5041class Service:
5042    def __init__(self, engine: Engine, tokenizer, template: ChatTemplate, model_name: str = "qwen3.8-flash-next",
5043                 vision: Vision | None = None, sampling_defaults: dict | None = None,
5044                 fit_max_tokens: bool = True):
5045        self.engine, self.tok, self.template, self.model, self.vision = engine, tokenizer, template, model_name, vision
5046        self.literals = literal_tags(getattr(tokenizer, "control_tokens", ()))   # texts that stay text inside a message
5047        self.fit_max_tokens = fit_max_tokens          # default: clamp the output cap to the room left; False (--no-fit-max-tokens) = 400
5048        self.aliases: list[str] = []                  # #297: other names of the model (the config's `aliases`)
5049        self.answer_room = True                       # 0.1.45: see ANSWER_ROOM_MIN_CAP (the config's "answer_room": false turns it off)
5050        self.reasoning_close_retry = False            # #1053 (opt-in): close the thinking once when a reply ends inside it
5051        self.codex_compaction_cache = False           # #924 (opt-in): a Codex compaction is rendered with its conversation's tools
5052        self.codex_thread_titles = False              # #923 (opt-in): answer Codex's thread-title turns without the engine
5053        self.sampling_defaults = dict(sampling_defaults or {})   # the run config's `sampling` block
5054        self.model_arch = None                        # the config's family ("qwen4exp", "qwen35moe"): None = no model-card defaults
5055        self.shared = {}                              # the web app's Chat settings for every client (POST /settings)
5056        self.shared_path = None                       # where they are kept between starts (next to the config)
5057        self.config_effort = None                     # #1641: the config's "reasoning_effort": the level for requests with none
5058        self.keep_awake = None                        # #1727 (opt-in): serve.keepawake.KeepAwake, the config's "prevent_sleep"
5059        self.fifo = threading.Lock()
5060        self.slot_save_path = None                    # --slot-save-path: /slots/0?action=save|restore (off when None)
5061        self.embeddings = threading.local()           # the current request's image embeddings file (GENI)
5062        self.api_key = ""                              # when set, /v1/* needs it (Bearer or x-api-key)
5063        # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system
5064        # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation
5065        self.effort_end = False
5066        self.conv_log = ConvCacheLog()                  # #596: the parked conversations, from the engine's log
5067        self.config_path = None                         # #564: the run config the web page's Settings view edits
5068        self.config_lock = threading.Lock()
5069        # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that
5070        # matters); empty = no CORS headers at all, as before
5071        self.cors_origins: list[str] = []
5072        # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a
5073        # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard
5074        self.trusted_origins: list[str] = []
5075        # DNS rebinding: extra Host names this server answers to (the config's allowed_hosts, $STRATA_ALLOWED_HOSTS;
5076        # "*" = any), and every name it answers to, which serve() works out from the address it listens on
5077        self.allowed_hosts: list[str] = []
5078        self.host_names: set[str] = set(LOOPBACK_NAMES)
5079        self.status = {"busy": False, "queued": 0}      # GET /status: what the model is doing right now
5080        self.rate = collections.deque(maxlen=32)        # (time, generated) samples for the live tok/s window
5081        # "parallel" (the engine's batch slots): every running request's own status and rate window; self.status
5082        # then says busy while any runs and shows the newest one
5083        self.live_reqs: dict[int, tuple[dict, collections.deque]] = {}
5084        # Privacy-safe correlation for terminal telemetry. No prompts, client identity or tool text is stored.
5085        self.terminal_requests: dict[str, dict] = {}
5086        self.terminal_events = collections.deque(maxlen=128)  # fixed-shape request transitions only
5087        self.terminal_event_seq = 0
5088        # HTTP admission is reserved before generation or SSE headers. This bounds pending inference calls even
5089        # while a model is loading or a request is between MCP rounds; the engine's own slots remain unchanged.
5090        self.max_queue: int | None = None
5091        self.queue_timeout_s: float | None = None
5092        self.admission_reserved = 0
5093        self.admission_rejected = 0
5094        self.queue_timeouts = 0
5095        self.client_disconnect_cancels = 0
5096        self.draining = False
5097        self.active_cancels: set[threading.Event] = set()
5098        # #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory,
5099        # so it is off unless the config's "api_monitor" (or --api-monitor) turns it on
5100        self.api_monitor = False
5101        self.api_requests = collections.deque(maxlen=100)  # bounded I/O in memory; no headers or API keys
5102        self.request_trace = threading.local()
5103        self.history = collections.deque(maxlen=500)    # the last finished requests, newest last (GET /metrics)
5104        # since the server started (the Monitor's totals, issue #35)
5105        self.totals = {"since": time.time(), "requests": 0, "prompt_tokens": 0, "reused": 0, "output_tokens": 0,
5106                       "prompt_ms": 0.0, "decode_ms": 0.0,
5107                       "drafts_offered": 0, "drafts_accepted": 0,   # #457: the MTP drafts, summed where reported
5108                       "scr_cached": 0, "scr": 0, "scr_prefilled": 0}   # SCR's split of the prompts (engine with SCR on)
5109        self.last_timings = None                         # the last finished request's, llama.cpp's names (/v1/status)
5110        # /metrics/prometheus' two throughput gauges need the totals as they stood at the last scrape, because
5111        # llama.cpp averages them over the window between two scrapes (#2341).
5112        self.scrape_bucket = (0, 0.0, 0, 0.0)
5113        from serve.prometheus import Latencies
5114        self.latencies = Latencies()                     # GET /metrics in Prometheus text: the latency histograms
5115        self.last_request_at = None                      # when a request last started or finished
5116        self.started_at = time.time()
5117        self.instance_id = uuid.uuid4().hex
5118        self.status_lock = threading.Lock()
5119        self.admission_changed = threading.Condition(self.status_lock)
5120        self.mcp = None                                  # serve/mcp.py's McpHub when MCP servers are configured
5121        self.offline = False                             # no image URL fetch or MCP subprocess in strict local mode
5122        self.telemetry_key = ""                         # optional read-only key, valid only on /v1/telemetry
5123        # sharing the GPU with other programs (all off by default): unload the engine after this many idle seconds,
5124        # only start it again when this much VRAM is free, and run this command first (e.g. to unload another
5125        # server's model); the next request after an unload starts the engine again
5126        self.idle_unload_s = 0
5127        self.min_free_vram_mib = 0
5128        self.before_load = None
5129        self.before_load_timeout_s = 120.0               # #1997: how long the before_load command may run
5130        self.before_load_ignore_failure = False          # #1997: load even when it fails, without a VRAM check
5131        self.vram_free_wait_s = 15.0                     # how long a full card is waited on (memory given back)
5132        self.before_load_strict = False                  # #1997: refuse (503) whenever it fails
5133        self.vram_reserve = None                         # #533: the last POST /v1/vram reserve (None: the start's)
5134        self.vram_reserve_asked = False                  # a POST /v1/vram was made (vram_reserve None is then asked)
5135        self.vision_held = False                         # an elastic encoder holds VRAM the expert cache gave it
5136        self.vision_no_shrink = False                    # the engine said its cache never shrinks (no --vram-elastic)
5137        self.vision_no_shrink_said = False
5138        self.last_image_at = 0.0                         # when an image turn last ended (the elastic encoder's idle)
5139        self.reasoning_loop_recovery = False
5140        self.reasoning_budget_configured = False         # the config named reasoning_budget_tokens (0 included): no family default
5141        self.reasoning_budget_tokens = 0                 # #123: the config's default thinking budget (0: none)
5142        self.repeat_stop_tokens = REPEAT_STOP_TOKENS     # #606: one token this many times in a row ends a reply (0: off)
5143        self.thinking_loop_tokens = 0                     # one token this many times in a row in the thinking closes it (0: off)
5144        self.anthropic_think_unasked = True               # #278: "anthropic_thinking": "on_request" -> False
5145        self.undeclared_tool_calls = "text"               # #4622: config "undeclared_tool_calls": "call" hands a call of an undeclared name to the client
5146        self.tool_call_recovery = True                    # default on (0.2.8): tool calls in forms next to the template's; config "tool_call_recovery": false turns it off
5147        self.images = None                                # serve/images.py's ImageGen when the config has "images"
5148        self.restore_after_load = None                    # a session file an image job saved before it unloaded
5149        self.stop_ids = end_token_ids(tokenizer)
5150        self.family = None                              # the model family ("deepseek41"): set_family() below
5151        self.parser_cls = parser_for_template(getattr(template, "source", None))   # reads the model's output (reasoning, content, tool calls): by the template's tool-call form
5152        # #567: a prompt re-encodes only what follows the last special token it shares with a recent prompt (the
5153        # same ids as a full encode: tools/strata_tokenizer.py PromptEncoder).  Tokenizers without resume points
5154        # encode in full.
5155        self.prompts = None
5156        if hasattr(tokenizer, "encode_marked") and hasattr(tokenizer, "max_special_len"):
5157            from strata_tokenizer import PromptEncoder
5158            # one kept prompt per conversation the engine's cache can hold (--conversation-cache-slots); the
5159            # encoder's own default without that setting
5160            slots = conversation_slots(engine)
5161            self.prompts = PromptEncoder(tokenizer, keep=slots) if slots is not None and slots > 0 \
5162                else PromptEncoder(tokenizer)
5163
5164    def set_family(self, family: str | None) -> None:
5165        """A family whose text differs from the Qwen form this server was written for (DeepSeek-V4.1: its own end
5166        token, DSML tool calls, reasoning-effort words).  The others keep the defaults."""
5167        self.family = family
5168        if family == "deepseek41":
5169            from serve import dsml
5170            eos = (getattr(self.tok, "special_ids", None) or {}).get("eos", 1)
5171            self.stop_ids = {int(eos)}
5172            self.parser_cls = dsml.DsmlOutputParser
5173            self._force_text = dsml.to_dsml_force
5174        import serve.frontend as _frontend
5175        _frontend.use_family(family)
5176
5177    _force_text = None
5178
5179    def force_text(self, force):
5180        """forced_call's opening of the call the reply must make, in this model's spelling."""
5181        return self._force_text(force) if self._force_text is not None else force
5182
5183    def loaded(self) -> bool:
5184        return not hasattr(self.engine, "alive") or self.engine.alive()
5185
5186    def admission_limit(self) -> int | None:
5187        if self.max_queue is None:
5188            return None
5189        return max(1, int(getattr(self.engine, "batch", 0) or 0)) + self.max_queue
5190
5191    def _terminal_event_locked(self, request_id: str, event: str, outcome: str | None = None) -> None:
5192        """Append one redacted transition while holding status_lock; never include request content."""
5193        if event not in ("queued", "admitted", "reading", "first_token", "finished", "cancelled",
5194                         "disconnected", "timeout", "error"):
5195            return
5196        if outcome is not None and outcome not in ("stop", "length", "cancel", "disconnect", "timeout", "error"):
5197            outcome = "error"
5198        self.terminal_event_seq += 1
5199        row = {"seq": self.terminal_event_seq, "at": time.time(),
5200               "request_id": request_id, "event": event}
5201        if outcome is not None:
5202            row["outcome"] = outcome
5203        self.terminal_events.append(row)
5204
5205    def reserve_inference(self) -> bool | None:
5206        """Reserve one bounded HTTP inference call before response headers are written."""
5207        with self.status_lock:
5208            if self.draining:
5209                return None
5210            limit = self.admission_limit()
5211            if limit is not None and self.admission_reserved >= limit:
5212                self.admission_rejected += 1
5213                return False
5214            self.admission_reserved += 1
5215            return True
5216
5217    def release_inference(self) -> None:
5218        with self.admission_changed:
5219            self.admission_reserved -= 1
5220            self.admission_changed.notify_all()
5221
5222    def note_client_disconnect(self, cancel: threading.Event) -> None:
5223        """Cancel once; count only work that was still queued or active when the client left."""
5224        with self.status_lock:
5225            if not cancel.is_set():
5226                request_id = getattr(cancel, "_strata_request_id", None)
5227                active = request_id in self.terminal_requests
5228                cancel.set()
5229                if active:
5230                    self.client_disconnect_cancels += 1
5231
5232    @contextlib.contextmanager
5233    def _inference_fifo(self, deadline: float | None, cancel: threading.Event | None = None):
5234        if deadline is None:
5235            with self.fifo:
5236                yield
5237            return
5238        while True:
5239            if cancel is not None and cancel.is_set():
5240                raise QueueCancelled("the client disconnected while waiting for the engine")
5241            left = deadline - time.monotonic()
5242            if left <= 0:
5243                raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
5244            if self.fifo.acquire(timeout=min(0.1, left)):
5245                break
5246        try:
5247            if cancel is not None and cancel.is_set():
5248                raise QueueCancelled("the client disconnected while waiting for the engine")
5249            if time.monotonic() >= deadline:
5250                raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
5251            yield
5252        finally:
5253            self.fifo.release()
5254
5255    def begin_drain(self) -> int:
5256        """Stop new inference admission and return the number of owned calls to drain."""
5257        with self.admission_changed:
5258            self.draining = True
5259            self.admission_changed.notify_all()
5260            return self.admission_reserved
5261
5262    def wait_for_drain(self, timeout: float) -> int:
5263        """Wait for reserved inference calls; return the number still in flight."""
5264        deadline = time.monotonic() + max(0.0, timeout)
5265        with self.admission_changed:
5266            while self.admission_reserved:
5267                left = deadline - time.monotonic()
5268                if left <= 0:
5269                    break
5270                self.admission_changed.wait(left)
5271            return self.admission_reserved
5272
5273    def cancel_owned_requests(self) -> int:
5274        """Cancel only requests admitted by this Service, never unrelated GPU work."""
5275        with self.status_lock:
5276            active = list(self.active_cancels)
5277        for cancel in active:
5278            cancel.set()
5279        return len(active)
5280
5281    def slot_action(self, slot: str, action: str, filename) -> tuple[int, dict]:
5282        """llama-server's POST /slots/{id}?action=save|restore {"filename": ...}: the conversation the engine holds,
5283        to or from a file in slot_save_path.  -> (HTTP status, body)."""
5284        def error(code, message):
5285            return code, {"error": {"code": code, "message": message,
5286                                    "type": "invalid_request_error" if code < 500 else "server_error"}}
5287        if not self.slot_save_path or not hasattr(self.engine, "session_file"):
5288            return error(501, "slot save/restore is disabled (start the server with --slot-save-path DIR)")
5289        if getattr(self.engine, "batch", 0):
5290            # #465 parallel requests do not hold the FIFO and share the engine's control lines: a session file
5291            # could interleave with a request being admitted, so the two are not combined (the engine refuses too)
5292            return error(501, "slot save/restore is not available with parallel requests (\"parallel\" / --batch)")
5293        if slot != "0":
5294            return error(400, "this server has one slot: 0")
5295        if action not in ("save", "restore"):
5296            return error(400, "action must be save or restore")
5297        why = slot_filename_problem(filename)
5298        if why:
5299            return error(400, f"filename {why}")
5300        path = os.path.join(self.slot_save_path, filename)
5301        if action == "restore":
5302            try:
5303                os.lstat(path)                              # the engine opens it without following a link
5304            except OSError:
5305                return error(404, f"no saved session named {filename}")
5306        self.last_request_at = time.time()                  # the idle unload counts this as activity
5307        with self.status_lock:
5308            self.status["queued"] += 1
5309        waiting = True
5310        try:
5311            with self.fifo:
5312                with self.status_lock:
5313                    self.status["queued"] -= 1
5314                waiting = False
5315                if not self.loaded():
5316                    return error(503, "the model is not loaded")
5317                with self.status_lock:
5318                    self.status.update(busy=True, phase="saving the session" if action == "save"
5319                                       else "restoring a session", started=time.time(), first_token=None,
5320                                       prompt_tokens=None, generated=None, max_tokens=None)
5321                try:
5322                    if action == 'save' and getattr(self.engine, 'session_save_reclaim', False):
5323                        from serve.session_save_retry import session_file
5324                        r = session_file(self, action, path, SessionRefused)
5325                    else:
5326                        r = self.engine.session_file(action, path)
5327                except SessionRefused as e:
5328                    body = error(e.status, str(e))
5329                    body[1]["error"]["kind"] = e.kind
5330                    if e.published:
5331                        body[1]["error"]["published"] = True
5332                    return body
5333                except ValueError as e:                     # the request itself (an invalid command)
5334                    return error(400, str(e))
5335                finally:
5336                    with self.status_lock:
5337                        self.status["busy"] = False
5338                    self.last_request_at = time.time()
5339        finally:
5340            if waiting:                                     # never reached the FIFO (an exception while waiting)
5341                with self.status_lock:
5342                    self.status["queued"] -= 1
5343        if action == "save":
5344            return 200, {"id_slot": 0, "filename": filename, "n_saved": r["tokens"], "n_written": r["bytes"],
5345                         "timings": {"save_ms": r["ms"]}}
5346        return 200, {"id_slot": 0, "filename": filename, "n_restored": r["tokens"], "n_read": r["bytes"],
5347                     "timings": {"restore_ms": r["ms"]}}
5348
5349    def set_aliases(self, aliases) -> None:
5350        """#297: the config's `aliases` - a list of names (or one comma-separated string), like llama-server's --alias.
5351        ValueError for anything else."""
5352        if aliases is None:
5353            aliases = []
5354        if isinstance(aliases, str):
5355            aliases = aliases.split(",")
5356        if not isinstance(aliases, list) or not all(isinstance(x, str) for x in aliases):
5357            raise ValueError(f"aliases={aliases!r}: expected a list of model names")
5358        names = []
5359        for x in (x.strip() for x in aliases):
5360            if x and x != self.model and x not in names:
5361                names.append(x)
5362        self.aliases = names
5363
5364    def model_names(self) -> list[str]:
5365        return [self.model, *self.aliases]
5366
5367    def model_for(self, req) -> str:
5368        """The name to answer with: the request's own when it is the model's name or an alias (#297), else the model's.
5369        Other names are still served, as before."""
5370        asked = req.get("model") if isinstance(req, dict) else None
5371        return asked if isinstance(asked, str) and asked in self.aliases else self.model
5372
5373    def reported_ctx(self) -> int:
5374        """The context the endpoints report (/v1/status, /v1/models, /props, /health, /slots, /metrics): the engine's,
5375        or the last one it reported while it restarts (max_context is 0 until READY, and a client that sizes its
5376        prompt from it would send nothing, #351).  Reporting only: requests are checked in prepare()."""
5377        return int(getattr(self.engine, "max_context", 0) or getattr(self.engine, "known_ctx", 0) or 0)
5378
5379    def reasoning_budget(self, req) -> int | None:
5380        """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens` (or, as
5381        llama.cpp reads it, `thinking_budget_tokens`), else the config's.  0 (or less) means no budget, so a request can
5382        turn a configured one off.  ValueError (a 400) for anything that is not a whole number."""
5383        req = req if isinstance(req, dict) else {}
5384        value = req.get("reasoning_budget_tokens")
5385        if value is None:                                # a null does not hide the other name
5386            value = req.get("thinking_budget_tokens")
5387        if value is None:
5388            value = self.reasoning_budget_tokens
5389            if not value and self.family == "deepseek41" and not self.reasoning_budget_configured:
5390                value = DS41_DEFAULT_BUDGET          # DeepSeek-V4.1 only, as Maya ships it: no budget anywhere = this one
5391        if isinstance(value, float) and value.is_integer():
5392            value = int(value)
5393        if isinstance(value, bool) or not isinstance(value, int):
5394            raise ValueError(f"reasoning_budget_tokens={value!r}: expected a whole number of tokens (0: no budget)")
5395        return value if value > 0 else None
5396
5397    def _release_orphan_encoder(self) -> bool:
5398        """The engine is not running but its picture encoder still is (the engine died under a request; the encoder is a process of its own): stop it,
5399        and its VRAM goes back, so the free-VRAM check does not count this server's own encoder as "another program" and refuse every load after
5400        it, and the load that follows starts it again together with the engine (#4352). True when an encoder was stopped."""
5401        vision = self.vision
5402        if vision is None or not hasattr(vision, "alive") or not hasattr(vision, "unload") or self.loaded():
5403            return False
5404        try:
5405            if not vision.alive():
5406                return False
5407            print("[strata] the engine is not running but its picture encoder is: stopping the encoder to give its memory back", flush=True)
5408            vision.unload()
5409            self.vision_held = False
5410            return True
5411        except Exception as e:                              # noqa: BLE001 - freeing memory never turns a request into a crash
5412            print(f"[strata] the picture encoder could not be stopped: {e}", flush=True)
5413            return False
5414
5415    def _vision_down(self) -> bool:
5416        """The encoder should run and does not (the engine's load starts it again).  An elastic encoder is down
5417        between pictures by design: it starts in the image turn (_vision_up), not with the engine."""
5418        return (self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()
5419                and not getattr(self.vision, "elastic", False))
5420
5421    def _engine_reserve(self) -> int | None:
5422        """The VRAM the engine keeps free for other programs outside an elastic encoder's turn: the last POST /v1/vram
5423        reserve, or 0 when none was asked (the cache grows back to its full size; None would leave the reserve the engine
5424        started with, a segment or more below the size it had)."""
5425        return self.vram_reserve if self.vram_reserve_asked else 0
5426
5427    def _vision_up(self):
5428        """The image turn's start for an elastic encoder that is not running (the caller holds self.fifo): the expert
5429        cache first keeps the encoder's elastic_mib of VRAM free on top of the reserve, then the encoder starts (load and
5430        warm-up, a few seconds).  If the cache cannot shrink (an engine without --vram-elastic, the resident low-RAM mode)
5431        the encoder starts anyway, as a non-elastic one would."""
5432        v = self.vision
5433        if not getattr(v, "elastic", False) or v.alive():
5434            return
5435        if hasattr(self.engine, "vram") and self.loaded() and not self.vision_no_shrink:
5436            try:
5437                out = self.engine.vram((self._engine_reserve() or 0) + v.elastic_mib)
5438                self.vision_held = True
5439                print(f"[strata] images: the expert cache keeps {v.elastic_mib} MiB free for the image encoder "
5440                      f"({out.get('expert_cache_mib')} of {out.get('expert_cache_full_mib')} MiB left)", flush=True)
5441            except ValueError as e:
5442                self.vision_no_shrink = "--vram-elastic" in str(e)     # an engine that never shrinks: not asked again
5443                note = "" if self.vision_no_shrink and self.vision_no_shrink_said else f" ({e})"
5444                self.vision_no_shrink_said = True
5445                self._vision_room_check(v, note)
5446        elif self.vision_no_shrink:
5447            self._vision_room_check(v, "")
5448        if self.vision_held:
5449            time.sleep(0.2)          # the driver's free-VRAM counter shows the cache's release a moment later
5450        free0, t0 = self.free_vram_mib(), time.time()
5451        try:
5452            v.restart()
5453        except Exception as e:      # a 503 as for a non-elastic encoder at a load, not a dropped connection
5454            raise EngineDied(f"the image encoder failed to start: {e}") from e
5455        free1 = self.free_vram_mib()
5456        took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else ""
5457        on_cpu = getattr(v, "on_cpu", False)
5458        print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{', on the CPU' if on_cpu else took}", flush=True)
5459        if on_cpu and self.vision_held and hasattr(self.engine, "vram") and self.loaded():
5460            # the CPU reader needs no VRAM: the cache takes back what it made room for
5461            try:
5462                self.engine.vram(self._engine_reserve())
5463            except ValueError as e:
5464                print(f"[strata] images: the expert cache did not grow back ({e})", flush=True)
5465            self.vision_held = False
5466
5467    def _vision_room_check(self, v, note: str):
5468        """The expert cache cannot make room: the GPU reader goes into the VRAM that is free, if that is READER_NEEDS_MIB, else the
5469        CPU reader reads (a picture is read right either way)."""
5470        free = self.free_vram_mib()
5471        need = min(v.elastic_mib, READER_NEEDS_MIB)
5472        if free is not None and free < need and getattr(v, "use_cpu", lambda: False)():
5473            print(f"[strata] images: only {free} MiB of VRAM is free and the GPU reader needs about {need}{note}: this picture is "
5474                  "read on the CPU", flush=True)
5475        elif note:
5476            print(f"[strata] images: the expert cache did not make room for the image encoder{note}; starting it anyway", flush=True)
5477
5478    def _vision_idle_down(self, force: bool = False) -> str:
5479        """An elastic encoder idle for elastic_idle_s (or force) stops, and the expert cache takes its VRAM back:
5480        "down", "busy" (a request holds the turn, or a picture came more recently) or "nothing" (not elastic or not
5481        holding anything)."""
5482        v = self.vision
5483        if not getattr(v, "elastic", False) or not (self.vision_held or v.alive()):
5484            return "nothing"
5485        if not force and time.time() - self.last_image_at < v.elastic_idle_s:
5486            return "busy"
5487        if not self.fifo.acquire(blocking=False):
5488            return "busy"
5489        try:
5490            v.unload()
5491            back = ""
5492            if self.vision_held and hasattr(self.engine, "vram") and self.loaded():
5493                out = self.engine.vram(self._engine_reserve())
5494                back = (f"; the expert cache took its VRAM back ({out.get('expert_cache_mib')} of "
5495                        f"{out.get('expert_cache_full_mib')} MiB)")
5496            # also when the cache never made room (a layer split, an engine without --vram-elastic): the stop happened
5497            print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture{back}",
5498                  flush=True)
5499            self.vision_held = False
5500            return "down"
5501        finally:
5502            self.fifo.release()
5503
5504    def start_vision_idle(self):
5505        v = self.vision
5506        if not getattr(v, "elastic", False):
5507            return
5508        print(f"[strata] images: the image encoder starts with the first picture and stops after {v.elastic_idle_s:g} s "
5509              f"without one", flush=True)
5510
5511        def loop():
5512            while True:
5513                time.sleep(max(1.0, min(30.0, v.elastic_idle_s / 4)))
5514                try:
5515                    self._vision_idle_down()
5516                except Exception as e:                 # tried again at the next turn; the thread keeps running
5517                    print(f"[strata] images: stopping the idle image encoder: {e}", flush=True)
5518        threading.Thread(target=loop, daemon=True).start()
5519
5520    def free_vram_mib(self) -> int | None:
5521        """Free VRAM on the engine's (first) GPU, from the backend's reader - NVML, the amdgpu sysfs files (#301) or
5522        IOKit on macOS (Metal backend); None when it can't be read (then nothing is refused)."""
5523        try:
5524            from serve.telemetry import gpu_reader
5525            g = gpu_reader(int(getattr(self, "gpu_index", 0) or 0), amd=getattr(self, "backend", None) == "hip")
5526            if not g.ok():
5527                return None
5528            r = g.read()
5529            if r.get("mem_total") is None or r.get("mem_used") is None:
5530                return None
5531            return int((r["mem_total"] - r["mem_used"]) >> 20)
5532        except Exception:
5533            return None
5534
5535    FATAL_GPU_MAX = 3            # fatal GPU errors of one engine within FATAL_GPU_WINDOW_S: after that it is not started again
5536    FATAL_GPU_WINDOW_S = 600.0
5537
5538    def _note_fatal_gpu_exit(self, code) -> None:
5539        """#4350: the engine ends itself after a fatal GPU error (the device context cannot be used again) and says so in its last
5540        ERR line.  The next request starts it again, like any engine death, with one plain line here; the request that was in
5541        flight already failed with a 503.  Three such deaths within ten minutes mean a restart will not help (a bad card, driver or
5542        model state): then the server stops starting it and says so (503), until the ten minutes have passed."""
5543        why = getattr(self.engine, "last_err", None) or ""
5544        if "fatal GPU error" not in why:
5545            return
5546        pid = getattr(getattr(self.engine, "proc", None), "pid", None)
5547        seen = self.__dict__.setdefault("_fatal_gpu_pids", set())
5548        times = self.__dict__.setdefault("_fatal_gpu_times", [])
5549        now = time.time()
5550        if pid not in seen:                              # one death counts once, however many requests find it dead
5551            seen.add(pid)
5552            times.append(now)
5553        times[:] = [t for t in times if now - t < self.FATAL_GPU_WINDOW_S]
5554        print(f"[strata] the GPU reported a fatal error ({why[len('fatal GPU error:'):].strip()[:160]}); the engine ended "
5555              f"(exit code {code}) and is started again; the request that was running failed and can be sent again "
5556              f"({len(times)} of {self.FATAL_GPU_MAX} allowed in {self.FATAL_GPU_WINDOW_S / 60:g} minutes)", flush=True)
5557        if len(times) >= self.FATAL_GPU_MAX:
5558            raise EngineDied(f"the GPU reported a fatal error {len(times)} times in {self.FATAL_GPU_WINDOW_S / 60:g} minutes, so "
5559                             "the engine is not started again (the last: " + why[:160] + "). Check the graphics driver, the "
5560                             "card's temperature and power, and the log; a request after "
5561                             f"{self.FATAL_GPU_WINDOW_S / 60:g} minutes tries again")
5562
5563    def ensure_loaded(self):
5564        """Start the engine if it is not running (unloaded, or it died - issue #27), after the before_load hook and
5565        the free-VRAM check.  The caller holds self.fifo."""
5566        if self.loaded() and not self._vision_down():
5567            return
5568        hook_failed = None
5569        if self.before_load:
5570            cmd = self.before_load
5571            print(f"[strata] before loading: {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True)
5572            why = None
5573            try:
5574                r = subprocess.run(cmd, shell=isinstance(cmd, str), timeout=self.before_load_timeout_s,
5575                                   stdin=subprocess.DEVNULL)
5576                if r.returncode != 0:
5577                    why = f"it exited with code {r.returncode}"
5578            except subprocess.TimeoutExpired:
5579                why = f"it did not finish in {self.before_load_timeout_s:g} s (before_load_timeout_s)"
5580            except (OSError, subprocess.SubprocessError) as e:
5581                why = f"it could not run ({e})"
5582            if why is not None:
5583                # #1997: a failing hook (e.g. the other server's /unload that is still busy) may mean the GPU was not
5584                # given back.  A peer that is simply not running also makes `curl` fail (exit 7), so the exit code alone
5585                # does not refuse: the card's free VRAM decides (min_free_vram_mib, checked just below); "strict" always
5586                # refuses, "ignore" always loads.
5587                if self.before_load_strict and not self.before_load_ignore_failure:
5588                    print(f"[strata] the before_load command failed ({why}); the model stays unloaded and this "
5589                          "request is answered 503 - try again (before_load_strict)", flush=True)
5590                    raise GpuBusy(f"the before_load command failed ({why}): the GPU was not given back, so the "
5591                                  "model was not loaded; try again in a moment", retry_after=15)
5592                hook_failed = why
5593                if self.before_load_ignore_failure or not self.min_free_vram_mib:
5594                    print(f"[strata] the before_load command failed ({why}); loading anyway"
5595                          + ("" if self.before_load_ignore_failure else
5596                             " (set min_free_vram_mib to have the free VRAM checked, or before_load_strict to refuse)"),
5597                          flush=True)
5598                else:
5599                    print(f"[strata] the before_load command failed ({why}); checking the free VRAM", flush=True)
5600        if self.min_free_vram_mib and not (hook_failed and self.before_load_ignore_failure):
5601            free = self.free_vram_mib()
5602            if free is not None and free < self.min_free_vram_mib and self._release_orphan_encoder():
5603                free = self.free_vram_mib()                      # the encoder's share is back: the card is judged without our own process (#4352)
5604            deadline = time.time() + self.vram_free_wait_s   # memory another process just gave back can take a moment
5605            while free is not None and free < self.min_free_vram_mib and time.time() < deadline:
5606                time.sleep(0.5)
5607                free = self.free_vram_mib()
5608            if free is not None and free < self.min_free_vram_mib:
5609                if hook_failed and not self.before_load_ignore_failure:
5610                    print(f"[strata] the before_load command failed ({hook_failed}) and only {free} MiB of VRAM is "
5611                          f"free (the model needs {self.min_free_vram_mib}): not loading; 503", flush=True)
5612                raise GpuBusy(f"the GPU is in use by another program: {free} MiB of VRAM free, the model needs "
5613                              f"{self.min_free_vram_mib} (min_free_vram_mib) - it stays unloaded until that is free"
5614                              + (f"; the before_load command failed ({hook_failed})" if hook_failed else ""),
5615                              retry_after=15)
5616            if hook_failed and not self.before_load_ignore_failure:
5617                print(f"[strata] the before_load command failed ({hook_failed}), but {free} MiB of VRAM is free: "
5618                      "loading", flush=True)
5619        vision_started = False
5620        if self._vision_down():                         # first, as at a start: a GPU encoder takes its VRAM before
5621            print("[strata] starting the vision encoder ...", flush=True)   # the engine sizes its cache
5622            try:
5623                self.vision.restart()
5624            except Exception as e:
5625                raise EngineDied(f"the vision encoder failed to start: {e}") from e
5626            vision_started = True
5627        if self.loaded():
5628            return
5629        if getattr(self.engine, "unloaded", False):
5630            print("[strata] loading the model again (it was unloaded) ...", flush=True)
5631        else:
5632            code = self.engine.exit_code() if hasattr(self.engine, "exit_code") else None
5633            self._note_fatal_gpu_exit(code)
5634            print(f"[strata] the engine had stopped (exit code {code}); starting it again "
5635                  "(a minute or two) ...", flush=True)
5636        try:
5637            self.engine.restart()
5638        except Exception as e:
5639            if vision_started:
5640                self.vision.unload()
5641            # the program could not be started at all (missing, not executable, or blocked by Windows - #735): the
5642            # request path answers EngineDied with a 503, but takes a bare OSError for a client that went away (#2496)
5643            if isinstance(e, OSError):
5644                raise EngineDied(f"the engine could not be started: {e}") from e
5645            raise
5646        print("[strata] the engine is running again", flush=True)
5647        if self.restore_after_load:                      # an image job unloaded it: its conversation comes back
5648            images_api.restore_session(self)
5649        if self.vram_reserve is not None and hasattr(self.engine, "vram"):   # #533: the reserve asked for last
5650            try:
5651                self.engine.vram(self.vram_reserve)
5652            except (ValueError, EngineDied) as e:
5653                print(f"[strata] the VRAM reserve ({self.vram_reserve} MiB) was not applied: {e}", flush=True)
5654
5655    vram_wait_s = 300.0                                  # #533: how long POST /v1/vram waits for a running request
5656
5657    def vram(self, reserve_mib: int | None) -> dict:
5658        """#533, POST /v1/vram: keep `reserve_mib` of VRAM free for other programs (None: the reserve the engine
5659        started with), applied between requests - a request that is running finishes first (up to wait_s).  Only an
5660        engine started with --vram-elastic (the config's "vram_elastic": true) can do it; it never resizes on its own.
5661        An unloaded engine applies it when it loads.  -> {"status": ..., and the engine's figures}."""
5662        if not hasattr(self.engine, "vram"):
5663            raise ValueError("this engine cannot resize its VRAM use")
5664        if not self.fifo.acquire(timeout=self.vram_wait_s):
5665            raise ModelBusy("a request is still running; try again when it has finished")
5666        # parallel requests do not hold the fifo: the engine's control lines (a prompt being admitted) are taken too,
5667        # and the engine refuses a resize while a slot decodes
5668        ctl = getattr(self.engine, "ctl", None) if getattr(self.engine, "batch", 0) else None
5669        if ctl is not None and not ctl.acquire(timeout=self.vram_wait_s):
5670            self.fifo.release()
5671            raise ModelBusy("a request is still running; try again when it has finished")
5672        if ctl is not None:
5673            self.engine._ctl_held = True                 # engine.vram() below must not wait for the lines this call holds
5674        try:
5675            if not self.loaded():
5676                self.vram_reserve, self.vram_reserve_asked = reserve_mib, True
5677                return {"status": "not loaded", "reserve_mib": reserve_mib,
5678                        "note": "applied when the model loads"}
5679            # an elastic encoder that runs keeps its VRAM on top of the asked reserve
5680            out = self.engine.vram((reserve_mib or 0) + self.vision.elastic_mib if self.vision_held else reserve_mib)
5681            self.vram_reserve, self.vram_reserve_asked = reserve_mib, True
5682            print(f"[strata] VRAM: {out.get('vram_free_mib')} MiB free, expert cache {out.get('expert_cache_mib')} of "
5683                  f"{out.get('expert_cache_full_mib')} MiB ({out.get('expert_slots')} experts)", flush=True)
5684            return {"status": "ok", **out}
5685        finally:
5686            if ctl is not None:
5687                self.engine._ctl_held = False
5688                ctl.release()
5689            self.fifo.release()
5690
5691    def _say_died(self, e: Exception) -> None:
5692        """The server window's line for an engine that died (or was ended, #481) in the middle of a request."""
5693        note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""
5694        log = getattr(self.engine, "log_path", None)
5695        print(f"[strata] {e}. {note} The next request starts the engine again."
5696              f"{' Its log: ' + log if log else ''}", flush=True)
5697
5698    def load(self):
5699        """POST /load and every generation request: start the engine now if it is unloaded (raises GpuBusy)."""
5700        # a request is on its way: the idle thread must not unload between this and the request's own start
5701        self.last_request_at = time.time()
5702        if self.loaded() and not self._vision_down():
5703            return
5704        trace = getattr(self.request_trace, "record", None)
5705        waiting = time.perf_counter()
5706        with self.status_lock:                          # #1603: waiting for the fifo to start the engine is queued, not nothing
5707            self.status["queued"] += 1
5708        counted = True
5709        try:
5710            with self.fifo:
5711                with self.status_lock:
5712                    self.status["queued"] -= 1
5713                counted = False
5714                loading = time.perf_counter()
5715                if trace is not None:
5716                    with self.status_lock:
5717                        trace["queue_s"] += round(loading - waiting, 3)
5718                        trace["state"] = "loading"
5719                try:
5720                    self.ensure_loaded()
5721                finally:
5722                    if trace is not None:
5723                        with self.status_lock:
5724                            trace["load_s"] += round(time.perf_counter() - loading, 3)
5725                            trace["state"] = "queued"
5726        finally:
5727            if counted:
5728                with self.status_lock:
5729                    self.status["queued"] -= 1
5730
5731    UNLOAD_WAIT_S = 300.0       # #1997: POST /unload?wait=1 waits this long for the running turn (wait=<s> to choose)
5732
5733    def end_engine_if_unchanged(self, born) -> bool:
5734        """End the engine after a request that ended without its end event (#3961), but only if it is still the engine process that request ran on
5735        (`born`, the engine's gen) and nobody is on it: the turn is taken without waiting, and held while the engine is ended, so a request admitted
5736        right after the lost one is never killed by it. A server with batch slots shares the engine between requests, so it is left alone. True when
5737        the engine was ended (the next request then starts it again)."""
5738        end = getattr(self.engine, "end_for_restart", None)
5739        if end is None or born is None or batch_slots_on(self.engine):
5740            return False
5741        if not self.fifo.acquire(blocking=False):              # the next request is already generating on it
5742            return False
5743        try:
5744            if getattr(self.engine, "gen", None) != born:      # it was ended or restarted since: that is another process
5745                return False
5746            end()
5747            return True
5748        finally:
5749            self.fifo.release()
5750
5751    def unload_waiting(self, wait_s: float) -> str:
5752        """#1997: unload(), but a running or queued request is waited for (up to wait_s) instead of answering "busy":
5753        a peer server that needs this GPU can then free the card on the server's terms.  "busy" after wait_s."""
5754        deadline = time.monotonic() + max(0.0, wait_s)
5755        while True:
5756            r = self.unload()
5757            if r != "busy" or time.monotonic() >= deadline:
5758                return r
5759            time.sleep(0.25)
5760
5761    def unload(self, idle_for: float | None = None) -> str:
5762        """Stop the engine between requests: "unloaded", "not loaded", "busy" (a request is running or waiting, or
5763        with idle_for: one ran more recently than that) or "unsupported"."""
5764        if not hasattr(self.engine, "unload"):
5765            return "unsupported"
5766        if not self.fifo.acquire(blocking=False):
5767            return "busy"
5768        try:
5769            if not self.engine.alive():
5770                self._release_orphan_encoder()                  # POST /unload gives the card back even when the engine already died (#4352)
5771                return "not loaded"
5772            with self.status_lock:
5773                if self.status.get("busy") or self.status.get("queued"):
5774                    return "busy"
5775            if idle_for is not None and time.time() - (self.last_request_at or self.started_at) < idle_for:
5776                return "busy"
5777            self.engine.unload()
5778            if self.vision is not None and hasattr(self.vision, "unload"):
5779                self.vision.unload()
5780            self.vision_held = False
5781            print(f"[strata] model unloaded{f' after {idle_for:.0f} s idle' if idle_for else ''}; "
5782                  "the next request loads it again", flush=True)
5783            return "unloaded"
5784        finally:
5785            self.fifo.release()
5786
5787    def start_idle_unload(self):
5788        if not self.idle_unload_s or not hasattr(self.engine, "unload"):
5789            return
5790        print(f"[strata] the model unloads after {self.idle_unload_s} s without requests", flush=True)
5791
5792        def loop():
5793            while True:
5794                time.sleep(max(1.0, min(30.0, self.idle_unload_s / 4)))
5795                try:
5796                    self.unload(idle_for=self.idle_unload_s)
5797                except EngineStuck as e:                # tried again at the next turn; the thread keeps running
5798                    print(f"[strata] idle unload: {e}", flush=True)
5799        threading.Thread(target=loop, daemon=True).start()
5800
5801    def set_shared(self, defaults) -> dict:
5802        """The Chat settings every client gets for what it leaves out; {} / None = clients use their own again."""
5803        self.shared = clean_shared_defaults(defaults)
5804        if self.shared_path:
5805            try:
5806                if self.shared:
5807                    Path(self.shared_path).write_text(json.dumps(self.shared, indent=1), encoding="utf-8")
5808                else:
5809                    Path(self.shared_path).unlink(missing_ok=True)
5810            except OSError as e:
5811                print(f"[strata] could not save the shared settings: {e}", flush=True)
5812        return self.shared
5813
5814    def effort_default(self) -> str | None:
5815        """The thinking level of a request that names none: the Chat settings shared with apps first, then the config's
5816        "reasoning_effort" (#1641).  Every API reads it here (the Responses API did not: 0.1.44.1)."""
5817        return self.shared.get("reasoning_effort") or self.config_effort
5818
5819    def with_shared(self, req: dict, api: str) -> dict:
5820        """The request with the shared thinking level and max tokens filled in where it has none of its own."""
5821        s = self.shared
5822        effort = self.effort_default()
5823        if not s and not effort:
5824            return req
5825        req = dict(req)
5826        if "max_tokens" in s and not req.get("max_tokens") and not req.get("max_completion_tokens"):
5827            req["max_tokens"] = s["max_tokens"]
5828        if effort:
5829            if api == "openai":
5830                ctk = req.get("chat_template_kwargs") if isinstance(req.get("chat_template_kwargs"), dict) else {}
5831                if req.get("reasoning_effort") in (None, "") and not req.get("reasoning") and \
5832                        "enable_thinking" not in ctk and "reasoning_effort" not in ctk:
5833                    req["reasoning_effort"] = effort
5834            elif not req.get("thinking") and not req.get("output_config"):
5835                if effort == "none":
5836                    req["thinking"] = {"type": "disabled"}
5837                else:
5838                    req["output_config"] = {"effort": effort}
5839        return req
5840
5841    def start_telemetry(self):
5842        """The hardware sampler behind GET /metrics (serve/telemetry.py), recording this server's tok/s too."""
5843        if getattr(self, "telemetry", None) is None:
5844            from serve.telemetry import Telemetry
5845            self.telemetry = Telemetry(extra=lambda: {"tok_s": self._tok_s(), "tok_s_mean": self._tok_s_mean(),
5846                                                    "prefill_tok_s_mean": self._prefill_tok_s_mean()},
5847                                       gpu_index=int(getattr(self, "gpu_index", 0) or 0),
5848                                       gpu_indices=getattr(self, "gpu_indices", None),
5849                                       amd=getattr(self, "backend", None) == "hip")
5850            if getattr(self, "engine", None) is not None and hasattr(self.engine, "gpu_busy"):
5851                # #1317: the quick frozen-engine check does not end an engine whose GPU is busy (a long prompt chunk on a
5852                # slow card keeps the GPU at work while the host thread sleeps)
5853                self.engine.gpu_busy = lambda: (self.telemetry.snapshot()["now"].get("gpu_util") or 0) >= 10
5854
5855    def _tok_s(self):
5856        """tok/s over the last RATE_WINDOW_S seconds.  Returns 0.0 while nothing is generating.  With parallel requests:
5857        the sum of theirs."""
5858        with self.status_lock:
5859            many = [(dict(st), list(rt)) for st, rt in self.live_reqs.values()]
5860        if many:
5861            return sum(self._rate_of(st, rt) for st, rt in many)
5862        with self.status_lock:
5863            s = dict(self.status)
5864            rate = list(self.rate)
5865        return self._rate_of(s, rate)
5866
5867    @staticmethod
5868    def _rate_of(s, rate):
5869        if not s.get("busy") or not s.get("first_token"):
5870            return 0.0
5871        now = time.time()
5872        newest = rate[-1] if rate else None
5873        oldest = next(((t, g) for t, g in rate if now - t <= RATE_WINDOW_S), None)
5874        if newest and oldest and newest[0] - oldest[0] >= RATE_MIN_SPAN_S:
5875            return max(0.0, (newest[1] - oldest[1]) / (newest[0] - oldest[0]))
5876        return s["generated"] / max(RATE_MIN_SPAN_S, now - s["first_token"])
5877
5878    def _tok_s_mean(self):
5879        """The whole-request mean since the first token (the old formula), kept so the two can be compared."""
5880        with self.status_lock:
5881            many = [dict(st) for st, _ in self.live_reqs.values()] or [dict(self.status)]
5882        return sum(s["generated"] / max(1e-6, time.time() - s["first_token"]) for s in many
5883                   if s.get("busy") and s.get("first_token"))
5884
5885    def _prefill_tok_s_mean(self):
5886        """Engine-reported mean over newly read tokens, excluding the cached prefix."""
5887        with self.status_lock:
5888            reading = self.status.get("busy") and self.status.get("first_token") is None
5889        return getattr(self.engine, "prefill_tok_s_mean", None) if reading else 0.0
5890
5891    def begin_request(self, path, req):
5892        """#332: a monitor record for this request, or None when the monitor is off (nothing is kept then)."""
5893        if not self.api_monitor:
5894            return None
5895        raw = json.dumps(req, ensure_ascii=False, indent=2)
5896        record = {"id": uuid.uuid4().hex[:12], "path": path, "model": req.get("model") or self.model,
5897                  "started_at": time.time(), "state": "queued", "stream": bool(req.get("stream")),
5898                  "response_format": (req.get("response_format") or {}).get("type")
5899                  if isinstance(req.get("response_format"), dict) else None,
5900                  "input": raw[:262144], "input_truncated": len(raw) > 262144,
5901                  "output": "", "reasoning": "", "output_truncated": False, "reasoning_truncated": False,
5902                  "queue_s": 0.0, "load_s": 0.0, "first_token_s": None,
5903                  "_clock": time.perf_counter()}
5904        with self.status_lock:
5905            self.api_requests.append(record)
5906        self.request_trace.record = record
5907        return record
5908
5909    def request_records(self, request_id=None):
5910        with self.status_lock:
5911            records = list(self.api_requests)
5912            if request_id:
5913                record = next((r for r in records if r["id"] == request_id), None)
5914                if record is None:
5915                    return None
5916                return {k: v for k, v in record.items() if not k.startswith("_")}
5917            return [{k: v for k, v in r.items()
5918                     if k not in ("input", "output", "reasoning", "response") and not k.startswith("_")}
5919                    | {"wallclock_s": r.get("wallclock_s", round(time.perf_counter() - r["_clock"], 3))}
5920                    for r in reversed(records)]
5921
5922    def metrics(self, all_requests=False) -> dict:
5923        """GET /metrics: what the Monitor tab shows - the engine's facts, what it is doing, the last requests, and
5924        the hardware (with a minute of history per series)."""
5925        with self.status_lock:
5926            s = dict(self.status)
5927            if self.live_reqs:                          # parallel requests: the newest one's status
5928                s = {**s, **dict(list(self.live_reqs.values())[-1][0]), "queued": s.get("queued", 0)}
5929            hist = list(self.history)
5930            totals = dict(self.totals)
5931        now = time.time()
5932        progress = getattr(self.engine, "progress", None)
5933        if s.get("busy") and s.get("first_token") is None:
5934            state = "reading"
5935        elif s.get("busy"):
5936            state = "generating"
5937        elif not self.loaded():
5938            state = "unloaded"
5939        else:
5940            state = "idle"
5941        live = {"state": state, "queued": s.get("queued", 0), "phase": s.get("phase") if s.get("busy") else None,
5942                "prompt_tokens": s.get("prompt_tokens") if s.get("busy") else None,
5943                "prompt_read": None, "prompt_total": None, "generated": s.get("generated") if s.get("busy") else None,
5944                "max_tokens": s.get("max_tokens") if s.get("busy") else None,
5945                "elapsed_s": round(now - s["started"], 1) if s.get("busy") and s.get("started") else None,
5946                "tok_s": round(self._tok_s(), 1) if state == "generating" else None,
5947                "tok_s_mean": round(self._tok_s_mean(), 1) if state == "generating" else None,
5948                "prefill_tok_s_mean": getattr(self.engine, "prefill_tok_s_mean", None) if s.get("busy") else None,
5949                "tok_s_window_s": RATE_WINDOW_S if state == "generating" else None}
5950        if state == "reading" and progress:
5951            live["prompt_read"], live["prompt_total"] = progress
5952        par = int(getattr(self.engine, "batch", 0) or 0)
5953        if par:                                         # #465: the requests running together, slot by slot
5954            with self.status_lock:
5955                running = len(self.live_reqs)
5956            slots = self.engine.slots_view() if hasattr(self.engine, "slots_view") else []
5957            # the requests in flight that are not in a slot: the one alone on the solo path, or waiting their turn
5958            in_slots = sum(1 for x in slots if x["state"] != "idle")
5959            if PAR_COUNTERS:
5960                live["par_counters"] = dict(self.par_counters)
5961            live.update(parallel=par, running=running, slots=slots, outside_slots=max(0, running - in_slots),
5962                        waiting=int(getattr(self.engine, "waiting", 0) or 0),
5963                        admitting=int(getattr(self.engine, "admitting", 0) or 0))
5964            if running and state == "idle":
5965                live["state"] = "generating"
5966        if hasattr(self.engine, "replica_view"):        # opt-in replicas: each one's state and requests routed to it
5967            live["replicas"] = self.engine.replica_view()
5968        if hasattr(self.engine, "split_view"):          # opt-in split serving: the hand-overs so far (serve/split.py)
5969            live["split_serve"] = self.engine.split_view()
5970        engine = {"model": self.model, "max_context": self.reported_ctx(), "images": self.vision is not None,
5971                  **dict(getattr(self.engine, "info", {}) or {})}
5972        if getattr(self.vision, "cpu_note", None):         # the card had no room for the picture reader: the Terminal says so in its summary
5973            engine["vision_note"] = self.vision.cpu_note
5974        tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}}
5975        parked = self.conv_log.poll(getattr(self.engine, "log_path", None), getattr(self.engine, "log_start", None))
5976        return {"engine": engine, "live": live, "requests": hist[::-1][:None if all_requests else 12],
5977                "conversation_cache": conversation_cache_view(engine, hist, totals, parked),
5978                "requests_kept": len(hist), "totals": totals, "hardware": tel["now"],
5979                "hardware_static":
5980                tel["static"], "history": tel["history"], "time": now}
5981
5982    def prometheus(self) -> str:
5983        """GET /metrics/prometheus: the totals and what is running in Prometheus' text format, under llama-server's
5984        metric names (llamacpp:*) so its dashboards work unchanged; the drafts and requests as strata:*."""
5985        with self.status_lock:
5986            s, t = dict(self.status), dict(self.totals)
5987            running = len(self.live_reqs) or int(bool(s.get("busy")))
5988            prompt_n = t["prompt_tokens"] - t["reused"]               # what was read, as llama.cpp counts it
5989            prompt_s, decode_s = t["prompt_ms"] / 1000, t["decode_ms"] / 1000
5990            # llama.cpp reads these two gauges from a bucket it resets on every scrape (server_metrics::bucket,
5991            # "the gauges are averaged over the window between two scrapes"), so an idle server reports 0 rather
5992            # than its lifetime average. Keep the same window here, or the names lie to llama.cpp dashboards.
5993            was_prompt_n, was_prompt_s, was_predicted_n, was_decode_s = self.scrape_bucket
5994            self.scrape_bucket = (prompt_n, prompt_s, t["output_tokens"], decode_s)
5995        d_prompt_n, d_prompt_s = prompt_n - was_prompt_n, prompt_s - was_prompt_s
5996        d_predicted_n, d_decode_s = t["output_tokens"] - was_predicted_n, decode_s - was_decode_s
5997        rows = [
5998            ("llamacpp:prompt_tokens_total", "counter", "Prompt tokens read", prompt_n),
5999            ("llamacpp:prompt_tokens_cached_total", "counter", "Prompt tokens the conversation cache already held",
6000             t["reused"]),
6001            ("llamacpp:prompt_seconds_total", "counter", "Prompt read time", prompt_s),
6002            ("llamacpp:tokens_predicted_total", "counter", "Tokens generated", t["output_tokens"]),
6003            ("llamacpp:tokens_predicted_seconds_total", "counter", "Generation time", decode_s),
6004            ("llamacpp:prompt_tokens_seconds", "gauge", "Average prompt read throughput in tokens/s, since the last scrape",
6005             d_prompt_n / d_prompt_s if d_prompt_s > 0 else 0),
6006            ("llamacpp:predicted_tokens_seconds", "gauge", "Average generation throughput in tokens/s, since the last scrape",
6007             d_predicted_n / d_decode_s if d_decode_s > 0 else 0),
6008            ("llamacpp:requests_processing", "gauge", "Requests running", running),
6009            ("llamacpp:requests_deferred", "gauge", "Requests waiting their turn", s.get("queued") or 0),
6010            ("strata:requests_total", "counter", "Requests finished", t["requests"]),
6011            ("strata:drafts_offered_total", "counter", "Speculative draft tokens offered", t["drafts_offered"]),
6012            ("strata:drafts_accepted_total", "counter", "Speculative draft tokens accepted", t["drafts_accepted"]),
6013            ("strata:tool_calls_unread_total", "counter", "<tool_call> blocks returned as text (an undeclared name or a form the template does not use)",
6014             t.get("tool_calls_unread", 0)),
6015            ("strata:tool_args_repaired_total", "counter", "Tool call arguments (a JSON array or object) that were damaged and read as written",
6016             t.get("tool_args_repaired", 0)),
6017            ("strata:scr_cached_tokens_total", "counter", "SCR: prompt tokens of an exact prefix kept", t.get("scr_cached", 0)),
6018            ("strata:scr_tokens_total", "counter", "SCR: prompt tokens moved from the cached run", t.get("scr", 0)),
6019            ("strata:scr_prefilled_tokens_total", "counter", "SCR: prompt tokens read", t.get("scr_prefilled", 0)),
6020            ("strata:model_loaded", "gauge", "1 while the model is loaded", int(self.loaded())),
6021        ]
6022        return "".join(f"# HELP {name} {help_}\n# TYPE {name} {kind}\n{name} {value}\n"
6023                       for name, kind, help_, value in rows)
6024
6025    def v1_status(self) -> dict:
6026        """GET /v1/status: what this server is and does, for a client that would rather ask than guess (a front-end
6027        that polls its OpenAI-compatible server's status, collabosm's for one): the model and its window, images,
6028        the APIs, what is running, and the last request's timings in llama.cpp's names.  /metrics has the rest."""
6029        with self.status_lock:
6030            s, totals = dict(self.status), dict(self.totals)
6031            last_t, last_at = (dict(self.last_timings) if self.last_timings else None), self.last_request_at
6032            running = len(self.live_reqs) if self.live_reqs else int(bool(s.get("busy")))
6033        tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "static": {}}
6034        hw, static = tel.get("now") or {}, tel.get("static") or {}
6035
6036        def scaled(v, unit, digits=0):
6037            return round(v / unit, digits) if isinstance(v, (int, float)) else None
6038
6039        busy, ctx = bool(s.get("busy")), self.reported_ctx()
6040        images = self.vision is not None
6041        return {
6042            "service": "strata", "model": self.model,
6043            "loaded": self.loaded(), "auto_load": hasattr(self.engine, "restart"),
6044            "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate",
6045                                  "constrained_decoding": False, "stream_buffered": True},
6046            "engine": (getattr(self.engine, "info", {}) or {}).get("version"),
6047            "started": int(self.started_at), "uptime_s": int(time.time() - self.started_at),
6048            "cache_max_tokens": ctx,
6049            "context": {"native": ctx, "max_positions": ctx},
6050            # one request at a time (more wait their turn), or "parallel": N batch slots (#465)
6051            "concurrency": {"serving": max(1, int(getattr(self.engine, "batch", 0) or 0)),
6052                            "requested": getattr(self, "requested_slots", max(1, int(getattr(self.engine, "batch", 0) or 0)))},
6053            "dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],
6054            "vision": {"enabled": images, "available": images, "error": None},
6055            "image_generation": self.images.status() if self.images is not None else {"enabled": False},
6056            "activity": {"requests": totals["requests"] + running,
6057                         "in_flight": running + int(s.get("queued") or 0),
6058                         "last_request_at": int(last_at) if last_at else None},
6059            "last_timings": last_t,
6060            "vram": dict((getattr(self.engine, "info", {}) or {}).get("vram") or {},
6061                         elastic=bool((getattr(self.engine, "info", {}) or {}).get("vram_elastic"))),
6062            "machine": {
6063                "at": int(time.time()),
6064                "gpu": {"name": static.get("gpu_name"), "used_mib": scaled(hw.get("gpu_mem_used"), 2 ** 20),
6065                        "total_mib": scaled(hw.get("gpu_mem_total"), 2 ** 20), "util_pct": hw.get("gpu_util"),
6066                        "temp_c": hw.get("gpu_temp"), "power_w": hw.get("gpu_power")} if static.get("gpu_name") else None,
6067                "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1),
6068                        "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}}
6069
6070    def render_prompt(self, messages, tools, kwargs) -> str:
6071        """The template rendered.  #458: with `effort_end`, a request with a non-default effort (low, medium or no
6072        thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache
6073        keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's
6074        empty thinking block).  The engine (--tail-role-token) checkpoints in front of that turn."""
6075        effort = kwargs.get("reasoning_effort")
6076        off = kwargs.get("enable_thinking") is False
6077        if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")):
6078            return self.template.render(messages, tools=tools, **kwargs)
6079        base = {k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")}
6080        history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base)
6081        full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs)
6082        mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs)
6083        if not full.startswith(mine):                  # a template this cannot take apart: rendered as asked
6084            return full
6085        tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"]))
6086        return history + tail + full[len(mine):]
6087
6088    def encode_prompt(self, messages, tools, kwargs, store: bool = True) -> list[int]:
6089        """The request's prompt: the template rendered and tokenized.  #537: a <think> / </think> written inside a
6090        message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).
6091        A control token's text (<|im_start|>, <|im_end|>, <|endoftext|>, ...) inside a message is text as well: only
6092        the control tokens the template writes are control tokens.  `store=False` (a token count) reuses the kept
6093        prompts without adding or replacing one."""
6094        marked, marked_tools, changed = mark_think_literals(messages, tools, self.literals)
6095        prompt = self.render_prompt(marked, marked_tools, kwargs)
6096        plain = ()
6097        if changed:
6098            prompt, plain = unmark_think_literals(prompt, self.literals)
6099        if self.prompts is not None:            # #567: only what follows the last special shared with a recent prompt
6100            return self.prompts.encode(prompt, plain, store)
6101        return self.tok.encode(prompt, parse_special=True, plain=plain) if plain else \
6102            self.tok.encode(prompt, parse_special=True)
6103
6104    @contextlib.contextmanager
6105    def _turn(self, cancel=None):
6106        """The engine's single turn (self.fifo) for an image encode.  #1999: a client that leaves while this request
6107        waits for it gives its place up (ClientGone), as a queued generation does (#1619)."""
6108        if cancel is None:
6109            self.fifo.acquire()
6110        else:
6111            while not self.fifo.acquire(timeout=0.25):
6112                if cancel.is_set():
6113                    raise ClientGone()
6114        try:
6115            yield
6116        finally:
6117            self.fifo.release()
6118
6119    def _note_unreadable_tool_images(self, messages, cancel=None):
6120        """A picture a tool returned (Claude Code's Read of an image file) that this server cannot read - it has no
6121        image encoder, or the encoder refuses that picture - becomes a short note in its place instead of a 400.
6122        Clients resend the whole history every turn, so one unreadable tool picture would fail every later request of
6123        the conversation; a picture the user sends keeps the 400.  A picture that encodes stays in the cache, so the
6124        prompt's own encode below finds it."""
6125        fetched = {}                     # a URL's bytes, so prepare() does not download the same picture again
6126        for m in messages:
6127            content = m.get("content")
6128            if m.get("role") != "tool" or not isinstance(content, list):
6129                continue
6130            for n, item in enumerate(content):
6131                if not isinstance(item, dict) or item.get("type") != "image":
6132                    continue
6133                why = "this server has no image encoder" if self.vision is None else None
6134                if why is None:
6135                    src = item["source"]
6136                    try:
6137                        if cancel is not None and cancel.is_set():
6138                            raise ClientGone()
6139                        if self.offline and src.startswith(("http://", "https://")):
6140                            raise ValueError("offline mode cannot download an image URL")
6141                        if src.startswith(("http://", "https://")):
6142                            src = fetched[item["source"]] = Vision.download(src)   # outside the FIFO, as in prepare()
6143                        with self._turn(cancel):  # the encoder takes its turn with the requests (see below)
6144                            self._vision_up()         # an elastic encoder is not running until a picture needs it
6145                            self.vision.encode(src)
6146                    except (ValueError, OSError, RuntimeError) as e:    # RuntimeError: the encoder did not start
6147                        why = str(e)
6148                if why is not None:
6149                    print(f"[strata] a picture a tool returned was left out of the prompt: {why}", flush=True)
6150                    content[n] = {"type": "text", "text": f"[image omitted: {why}]"}
6151        return fetched
6152
6153    def forget_prompt(self, ids):
6154        if self.prompts is not None:
6155            self.prompts.forget(ids)
6156
6157
6158    def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=None):
6159        """-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":
6160        the rest of the context.  `force` (forced_call): without thinking the reply starts with it, so it ends the
6161        prompt; with thinking, Service.run writes it once the thinking is over."""
6162        # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop
6163        # between pictures and raise ClientGone
6164        # Cached tool images are references in browser history, never arbitrary file paths or huge base64 strings.
6165        for message in messages:
6166            for part in message.get("content", []) if isinstance(message.get("content"), list) else []:
6167                source = part.get("source", "") if isinstance(part, dict) else ""
6168                if isinstance(part, dict) and part.get("type") == "image" and isinstance(source, str) and source.startswith("strata-tool-media:"):
6169                    name = source[len("strata-tool-media:"):]
6170                    if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name):
6171                        raise ValueError("invalid tool image reference")
6172                    # Clients resend old tool results. A removed cache or disabled feature must not poison
6173                    # every later turn; keep the other text and replace only the unavailable picture.
6174                    media_dir = self.mcp.media_dir if self.mcp is not None else None
6175                    image = Path(media_dir) / name if media_dir is not None else None
6176                    if image is None or not image.is_file():
6177                        why = "tool image cache is disabled" if image is None else "cached tool image is no longer available"
6178                        part.clear()
6179                        part.update(type="text", text=f"[image omitted: {why}]")
6180                    else:
6181                        part["source"] = str(image)
6182        fetched = self._note_unreadable_tool_images(messages, cancel)
6183        ids = encoded_ids = self.encode_prompt(messages, tools, kwargs)
6184        if force and kwargs.get("enable_thinking", True) is False:
6185            ids = ids + self.tok.encode(force, parse_special=True)
6186        self.embeddings.path = None
6187        self.embeddings.keys = None
6188        images = images_of(messages)
6189        ds_pics = False                                  # DeepSeek pictures (the engine's own tower): the file is already written
6190        if images:
6191            if self.offline and any(src.startswith(("http://", "https://")) for src in images):
6192                raise ValueError("offline mode cannot download an image URL; send a data: image instead")
6193            if self.vision is None:
6194                if self.family == "deepseek41":
6195                    raise ValueError("this server was started without pictures for DeepSeek (--vision off, or a pack made without the "
6196                                     "picture reader): run strata launch again without --vision off to read images")
6197                raise ValueError("this server was started without the vision encoder (run setup again and choose "
6198                                 "'vision'), so it cannot read images")
6199            # An image URL is downloaded first, outside the FIFO: under it, a slow server held every other request
6200            # for as long as urlopen waited.
6201            def fetch(src):
6202                if cancel is not None and cancel.is_set():
6203                    raise ClientGone()
6204                return fetched[src] if src in fetched else Vision.download(src) \
6205                    if src.startswith(("http://", "https://")) else src
6206            images = [fetch(src) for src in images]
6207            if isinstance(self.vision, DsPictures):
6208                ids, ds_file = self.vision.build(ids, [Vision.load(src) if isinstance(src, str) else src for src in images])
6209                self.embeddings.path = ds_file
6210                self.embeddings.keys = None
6211                images, ds_pics = [], True
6212        if images and isinstance(self.vision, ds4_vision.Ds4Vision):
6213            # the engine's own tower: only the sizing here (CPU), so no turn is taken; the engine encodes in the GENI
6214            encoded = []
6215            for src in images:
6216                if cancel is not None and cancel.is_set():
6217                    raise ClientGone()
6218                encoded.append(self.vision.encode(src, keep=[p for p, _ in encoded]))
6219            ids, ds4_starts = self.vision.expand(ids, encoded)
6220        elif images:
6221            pad = self.tok.encode(IMAGE_PAD, parse_special=True)[0]
6222            start = self.tok.encode(VISION_START, parse_special=True)[0]
6223            # Encode only while the engine is idle: the engine and the image encoder (a separate process) must not
6224            # run on the GPU at the same time - an encode during a running request left that request stuck at
6225            # "reading the prompt" with CPU and GPU busy, for good (reproduced).  So encoding takes its turn in the
6226            # same FIFO as the requests.
6227            with self._turn(cancel):
6228                if not (hasattr(self.vision, "all_cached") and self.vision.all_cached(images)):
6229                    self._vision_up()
6230                try:
6231                    encoded = (self.vision.encode_all(images, cancel) if hasattr(self.vision, "encode_all")
6232                               else [self.vision.encode(src) for src in images])
6233                finally:
6234                    self.last_image_at = time.time()
6235            # one <|image_pad|> per image -> one per image token.  Only the markers the template writes for an image
6236            # (right after <|vision_start|>) are images: the same text inside a message (an agent reading these docs,
6237            # #150) is kept as plain text, or it took an image's place and the counts no longer matched.
6238            literal = self.tok.encode(IMAGE_PAD, parse_special=False)
6239            out, k = [], 0
6240            for j, t in enumerate(ids):
6241                if t == pad and j > 0 and ids[j - 1] == start:
6242                    # more pairs than images: text parts that cut both markers apart (the literal marks keep whole ones text)
6243                    if k == len(encoded):
6244                        raise ValueError("the prompt and its images do not match")
6245                    out += [pad] * encoded[k][1]
6246                    k += 1
6247                elif t == pad:
6248                    out += literal
6249                else:
6250                    out.append(t)
6251            if k != len(encoded):
6252                raise ValueError("the prompt and its images do not match")
6253            ids = out
6254        ctx = self.engine.max_context
6255        if ctx <= 0:
6256            if getattr(self.engine, "starting", False):   # #344: (re)starting, not a prompt that is too long
6257                raise EngineStarting("the engine is starting (a minute or two); try again shortly")
6258            # a failed restart leaves max_context 0: check against the last known context, so the request reaches
6259            # run() - which starts the engine again - instead of failing with "exceeds the context (0)" forever
6260            ctx = getattr(self.engine, "known_ctx", 0)
6261            if ctx <= 0:
6262                raise EngineStarting("the engine is starting (a minute or two); try again shortly")
6263        room = ctx - CTX_SLACK - len(ids)
6264        if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1):
6265            if room < 1:
6266                # A prompt refused for the context is not kept (#567): the client cannot resend it unchanged.  The
6267                # other refusals (engine starting, images) keep it: the same prompt comes back and its encode is reused.
6268                self.forget_prompt(encoded_ids)
6269                raise ContextOverflow("request exceeds the context window: "
6270                                      f"prompt ({len(ids)} tokens) leaves no room to answer in the context "
6271                                      f"({ctx}); requests are never truncated", prompt=len(ids), context=ctx)
6272            max_new = room
6273        elif max_new > room:
6274            if not self.fit_max_tokens:
6275                self.forget_prompt(encoded_ids)
6276                raise ContextOverflow("request exceeds the context window: "
6277                                      f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context "
6278                                      f"({ctx}); requests are never truncated. Send a smaller "
6279                                      f"max_tokens (at most {max(0, room)} here), or add \"fit_max_tokens\": true to the "
6280                                      "model's strata-<model>.json to shorten it to the room left (#545)",
6281                                      prompt=len(ids), context=ctx, max_new=max_new)
6282            print(f"[strata] max_tokens {max_new} shortened to {max(1, room)}: the prompt ({len(ids)} tokens) leaves that much "
6283                  f"of the context ({ctx}); \"fit_max_tokens\": false answers 400 instead", flush=True)
6284            max_new = max(1, room)          # a shorter completion beats a 400 (the default)
6285        if images:
6286            # The request's images in one file for GENI (~10 MB a picture), written once nothing above refuses the
6287            # request: one refused after it (the engine starting, no room) left it in the vision directory for good,
6288            # one more for every retry of a 503.  run() deletes it; drop_embeddings() if run() never starts.
6289            combined = combined_embeddings_path(self.vision.dir, sum(Path(p).stat().st_size for p, _ in encoded))
6290            self.embeddings.path = combined             # first, so a half-written one is found as well
6291            if isinstance(self.vision, ds4_vision.Ds4Vision):   # (pixels: the engine hashes them itself)
6292                self.vision.write(combined, encoded, ds4_starts)
6293            else:
6294                # #2228: each picture's key is its normalized bytes' hash (the encoder's file name), so the engine's
6295                # conversation cache matches a picture by what it is, not by its embedding floats: a picture encoded
6296                # again (an encoder restart, the cache's eviction) with other bits still matches its checkpoints
6297                self.embeddings.keys = [Path(p).stem[:16] for p, _ in encoded]
6298                write_temporary(combined, [p for p, _ in encoded])
6299        if self.family == "deepseek41" and req is not None and req.get("strata_prefix") is None and not images and not ds_pics:
6300            lead = self.deepseek_shared_start(messages)
6301            if lead:
6302                req["strata_prefix"] = {"messages": lead}
6303        if req is not None and req.get("strata_prefix") is not None:
6304            req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images) or ds_pics)
6305        if req is not None:
6306            self.set_restore_points(req, ids, bool(images) or ds_pics)
6307        return ids, kwargs.get("enable_thinking", True) is not False, max_new
6308
6309    def deepseek_turn_ids(self):
6310        """(<|User|>'s id, <|System|>'s id) of the DeepSeek template, each None where the vocabulary has no such single token."""
6311        got = getattr(self, "_ds_turn_ids", None)
6312        if got is None:
6313            def one(text):
6314                try:
6315                    t = self.tok.encode(text, parse_special=True)
6316                except Exception:
6317                    return None
6318                return int(t[0]) if len(t) == 1 else None
6319            got = self._ds_turn_ids = (one("<|User|>"), one("<|System|>"))
6320        return got
6321
6322    def set_restore_points(self, req: dict, ids, has_images: bool) -> None:
6323        """STRATA_DS4_RESTORE_POINTS: where the DeepSeek engine keeps restore points for this prompt, in req["_restore"]
6324        (never a client's own; not with pictures, whose spans the engine reads whole).  The shared start is left to
6325        strata_prefix (pin=N) where the request has one."""
6326        req.pop("_restore", None)
6327        if self.family != "deepseek41" or has_images:
6328            return
6329        on, tail = restore_point_settings()
6330        if not on:
6331            return
6332        user_id, system_id = self.deepseek_turn_ids()
6333        pts = deepseek_restore_points(ids, user_id, system_id, tail)
6334        pref = req.get("strata_prefix")
6335        if (isinstance(pref, dict) and pref.get("tokens")) or os.environ.get("STRATA_DS4_RESTORE_SHARED") == "0":
6336            pts.pop("shared", None)   # (the system prompt is already the pin's, or STRATA_DS4_RESTORE_SHARED=0: no shared mark)
6337        if pts:
6338            req["_restore"] = pts
6339
6340    @staticmethod
6341    def deepseek_shared_start(messages) -> int:
6342        """DeepSeek-V4.1 only: how many leading messages are the system prompt (its tools are rendered with them).  An
6343        agent and its sub-agents that work behind the same system prompt and tools share exactly this start, so the
6344        engine keeps a checkpoint of its state there (pin=N): the next agent behind the same start goes back to it
6345        instead of reading it again.  0: none (STRATA_DS4_AUTO_PIN=0, no system message, or nothing after it)."""
6346        if os.environ.get("STRATA_DS4_AUTO_PIN", "1") == "0":
6347            return 0
6348        n = 0
6349        for m in messages:
6350            if isinstance(m, dict) and m.get("role") in ("system", "developer"):
6351                n += 1
6352            else:
6353                break
6354        return n if 0 < n < len(messages) else 0
6355
6356    PREFIX_END = "\u0001strata-prefix-end\u0001"          # marks where a message's shared part ends in the rendered prompt
6357
6358    def resolve_prefix(self, spec, messages, tools, kwargs, ids, has_images=False) -> dict:
6359        """R1: `"strata_prefix"` marks the start of the prompt as a shared read-only prefix: a long document that many
6360        short questions follow.  Three ways to say where it ends: `{"messages": K}` (the first K messages), `{"message":
6361        I, "chars": N}` (the first N characters of message I's text: a document and its question in one message) or
6362        `{"tokens": N}`.  The engine reads the prompt in two parts there, keeps the checkpoint at the boundary pinned
6363        (never evicted) and does not park the branch it leaves, so N questions cost one prefix.  Returns
6364        {"tokens": N} (what the engine's `pin=N` takes: always a prefix of the prompt's ids, the tokenizer's merge across
6365        the boundary included), or {} when the prefix cannot be marked (said in the log: the request is never refused for
6366        it).  A malformed field is a 400."""
6367        keys = ("messages", "message", "chars", "tokens")
6368        if (not isinstance(spec, dict) or not spec or any(k not in keys for k in spec) or
6369                set(spec) not in ({"messages"}, {"tokens"}, {"message", "chars"})):
6370            raise ValueError('strata_prefix: {"messages": K} (the first K messages), {"message": I, "chars": N} (the first '
6371                             'N characters of message I) or {"tokens": N}')
6372        for k, v in spec.items():
6373            if not isinstance(v, int) or isinstance(v, bool) or v < (0 if k == "message" else 1):
6374                raise ValueError(f"strata_prefix.{k}: a whole number ({'0' if k == 'message' else '1'} or more)")
6375        if has_images:
6376            print("[strata] strata_prefix ignored: the request has images", flush=True)
6377            return {}
6378        what = ",".join(f"{k}={v}" for k, v in spec.items())
6379
6380        def lcp(a, b):
6381            n = 0
6382            for x, y in zip(a, b):
6383                if x != y:
6384                    break
6385                n += 1
6386            return n
6387
6388        def head_ids(msgs):
6389            """The ids the rendered `msgs` start with (a message's trailing marker cut at PREFIX_END when it is there)."""
6390            marked, marked_tools, changed = mark_think_literals(msgs, tools, self.literals)
6391            effort = kwargs.get("reasoning_effort")
6392            off = kwargs.get("enable_thinking") is False        # render_prompt's rule for #458's effort_end
6393            kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")}
6394                  if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs))
6395            kw["add_generation_prompt"] = False
6396            text = self.template.render(marked, tools=marked_tools, **kw)
6397            cut = text.find(self.PREFIX_END)
6398            if cut >= 0:
6399                text = text[:cut]
6400            if changed:
6401                text, plain = unmark_think_literals(text, self.literals)
6402                return self.tok.encode(text, parse_special=True, plain=plain)
6403            return self.tok.encode(text, parse_special=True)
6404
6405        if "tokens" in spec:
6406            n = spec["tokens"]
6407        elif "messages" in spec:
6408            k = spec["messages"]
6409            if k >= len(messages):
6410                print(f"[strata] strata_prefix.messages={k} ignored: the request has {len(messages)} message(s) and the "
6411                      "prefix must leave at least the last one", flush=True)
6412                return {}
6413            head = head_ids(messages[:k])
6414            n = lcp(head, ids)
6415        else:
6416            i, chars = spec["message"], spec["chars"]
6417            text = messages[i].get("content") if 0 <= i < len(messages) else None
6418            if not isinstance(text, str) or chars > len(text):
6419                print(f"[strata] strata_prefix ignored: message {i} has no text of {chars} characters", flush=True)
6420                return {}
6421            cut = messages[:i] + [{**messages[i], "content": text[:chars] + self.PREFIX_END}]
6422            head = head_ids(cut)
6423            n = lcp(head, ids)
6424        if n < 1 or n >= len(ids) - 1:
6425            print(f"[strata] strata_prefix {what} ignored: it leaves no usable prefix of the {len(ids)}-token prompt "
6426                  f"(common start {n})", flush=True)
6427            return {}
6428        return {"tokens": n}
6429
6430    def drop_embeddings(self) -> None:
6431        """Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it
6432        ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and
6433        then nothing else would.  The handler calls this when a request is done."""
6434        path, self.embeddings.path = getattr(self.embeddings, "path", None), None
6435        if path is not None:
6436            Path(path).unlink(missing_ok=True)
6437
6438    def _note(self, n, evs, st=None, rate=None):
6439        with self.status_lock:
6440            s = self.status if st is None else st
6441            s["generated"] = n
6442            if s.get("first_token") is None:
6443                s["first_token"] = time.time()
6444            (self.rate if rate is None else rate).append((time.time(), n))   # the live rate's window (RATE_WINDOW_S)
6445            for ev in evs:
6446                if ev.kind == "reasoning":
6447                    s["phase"] = "thinking"
6448                elif ev.kind == "content":
6449                    s["phase"] = "answering"
6450                elif ev.kind == "tool_start":
6451                    s["phase"], s["tool"] = f"writing a tool call: {ev.call.name}", ev.call.name
6452                elif ev.kind == "tool_call":
6453                    s["phase"] = "tool call complete"
6454                s["tail"] = ((s.get("tail") or "") + (ev.text or ""))[-600:]
6455
6456    def _progress(self, last_print, every=1.0, st=None):
6457        """A progress line in the server window every `every` seconds while a request runs."""
6458        now = time.time()
6459        if now - last_print < every:
6460            return last_print
6461        with self.status_lock:
6462            s = dict(self.status if st is None else st)
6463        el = now - s.get("started", now)
6464        if s.get("first_token") is None:
6465            pr = getattr(self.engine, "progress", None)   # (position reached, prompt tokens): a reused prefix counts
6466            done = f"{pr[0]:,} of {pr[1]:,}" if pr and pr[1] else f"{s.get('prompt_tokens', 0):,}"   # as read (#29)
6467            print(f"[strata] reading the prompt: {done} tokens, {el:.0f} s so far", flush=True)
6468        else:
6469            rate = s["generated"] / max(RATE_MIN_SPAN_S, now - s["first_token"])
6470            # #984: while a thinking budget applies, the thinking line shows it, not the request's max_tokens
6471            limit = (f"budget {s['thinking_budget']} (max {s.get('max_tokens')})"
6472                     if s["phase"] == "thinking" and s.get("thinking_budget") else f"max {s.get('max_tokens')}")
6473            print(f"[strata] {s['phase']}: {s['generated']} of {limit} tokens, {rate:.1f} tok/s, "
6474                  f"{el:.0f} s", flush=True)
6475        return now
6476
6477    def run(self, ids, thinking, tools, max_new, sampling, cancel, force=None,
6478            declared_only=False, deferred=False) -> Iterator[tuple[str, object]]:
6479        """The request's events (see _run); with "prevent_sleep" in the config, the PC stays awake while it runs or waits."""
6480        ka = self.keep_awake
6481        if ka is not None:
6482            ka.acquire()
6483        try:
6484            yield from self._run(ids, thinking, tools, max_new, sampling, cancel, force, declared_only, deferred)
6485        finally:
6486            if ka is not None:
6487                ka.release()
6488
6489    def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None,
6490             declared_only=False, deferred=False) -> Iterator[tuple[str, object]]:
6491        """Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).
6492        `force` (forced_call): the opening of the call the reply must make - see prepare()."""
6493        # the model card's sampling for this thinking state, then the config's block, then the Chat settings shared with
6494        # apps; the request's own fields win over all of them
6495        defaults = {**model_card_sampling(self.model_arch, thinking), **self.sampling_defaults, **self.shared}
6496        if defaults:                   # the request's own fields win (explicit 0 stays greedy)
6497            req_values = {k: v for k, v in (sampling or {}).items() if v is not None}
6498            sampling = {**defaults, **req_values}
6499        # #123: read after the merge, so a budget shared through POST /settings is seen like the other keys
6500        budget = self.reasoning_budget(sampling) if thinking else None
6501        if thinking and not budget and self.answer_room and max_new and max_new >= ANSWER_ROOM_MIN_CAP:
6502            # 0.1.45: max_tokens counts the thinking too.  A client that caps the reply at 8192 (the desktop agent's
6503            # harness sends max_completion_tokens: 8192 on every request) and a task the model thinks long about got
6504            # the cut-off in the middle of the thinking and NO answer.  So thinking is closed early enough to leave
6505            # the answer its quarter of the cap (the budget's wrap-up: a short closing sentence, </think>, the answer).
6506            # A request with a budget of its own, or max_tokens below ANSWER_ROOM_MIN_CAP, is left as it was.
6507            budget = max_new - min(max(ANSWER_RESERVE_MIN, max_new // 4), max_new // 2)
6508            if max_new <= 32768: print(f"[strata] thinking limited to {budget} of max_tokens {max_new} so the answer has room "
6509                  "(\"answer_room\": false in the config turns this off)", flush=True)
6510        if (thinking and not budget and self.answer_room and self.family == "deepseek41"
6511                and max_new and DS41_SMALL_CAP_MIN <= max_new < ANSWER_ROOM_MIN_CAP):
6512            # DeepSeek-V4.1 only: a short max_tokens (/v1/messages and /v1/chat/completions with 200-600) was spent
6513            # entirely on the thinking, so no text block ever arrived.  With no budget of the client's own, the thinking
6514            # is capped at half of max_tokens; then the wrap-up, </think> and the answer follow in the other half.
6515            budget = max_new // 2
6516            print(f"[strata] thinking limited to {budget} of max_tokens {max_new} so the answer has room "
6517                  "(\"answer_room\": false in the config turns this off)", flush=True)
6518        if budget and max_new and max_new > 0:
6519            # #984: a budget at or near max_tokens never fires before the reply is cut off while still thinking, so
6520            # it has no answer.  Close the thinking early enough to leave room for one.
6521            reserve = min(max(ANSWER_RESERVE_MIN, max_new // 4), max_new // 2)
6522            if budget > max_new - reserve:
6523                print(f"[strata] thinking capped at {max_new - reserve} of max_tokens {max_new} to leave room for "
6524                      f"the answer (budget {budget})", flush=True)
6525                budget = max(1, max_new - reserve)
6526        parser = self.parser_cls(thinking=thinking, tools=with_history_tools(tools, sampling), stream_tools=True,
6527                                 recover=self.tool_call_recovery, declared_only=declared_only,
6528                                 deferred=deferred or self.undeclared_tool_calls == "call")   # #4622: opt-in, as for a deferred tool
6529        detok, n, finish = Detokenizer(self.tok), 0, "length"
6530        run_tok, run_len, repeated = None, 0, False     # #606: the current run of one repeated token
6531        thinking_n = 0                                  # tokens written while thinking (Responses' reasoning_tokens)
6532        stop_list = stop_strings(sampling)
6533        stops = StopMatcher(stop_list) if stop_list else None
6534
6535        def cut(evs):
6536            """The events with the answer's text cut at a stop string (OpenAI stop, Anthropic stop_sequences)."""
6537            if stops is None:
6538                return evs
6539            out = []
6540            for ev in evs:
6541                if stops.hit is not None:
6542                    break                               # nothing after the stop string is sent
6543                if ev.kind == "content":
6544                    text = stops.push(ev.text or "")
6545                    if text:
6546                        out.append(Event("content", text))
6547                    continue
6548                held = stops.flush()                    # a stop string does not run across a tool call or thinking
6549                if held:
6550                    out.append(Event("content", held))
6551                out.append(ev)
6552            return out
6553        opening = []                                    # without thinking the prompt ends with the forced opening:
6554        if force and not thinking:                      # the parser reads it as if the model had written it
6555            opening, force = parser.feed(force), None
6556        tail = ""                                       # the last characters written (the newlines before a call)
6557        answered, close_retried = False, False          # #1053: content or a call came out; the thinking was closed
6558        nf_retried = False                              # #879: the request was sent again after non-finite logits
6559        timings, before = None, None                    # this request's timings; the engine's `last` before it
6560        recovery_count, reasoning_text, repeat_coverage = 0, "", 0.0
6561        looped, next_loop_check = False, LOOP_CHECK_EVERY       # #728: reasoning that repeats whole passages
6562        raw_ids = []                                    # every generated id (STRATA_DEBUG: dump raw model text)
6563        admission_rejected = False                      # #3040: the engine's batch slots refused it before it read anything
6564        emb, self.embeddings.path = getattr(self.embeddings, "path", None), None   # this run's to delete now
6565        img_keys, self.embeddings.keys = getattr(self.embeddings, "keys", None), None
6566        if emb and img_keys:
6567            sampling = {**(sampling or {}), "strata_img_keys": img_keys}   # #2228: sent beside the embeddings file
6568        # Only a DONE line replaces engine.last, so a request that died, errored or was disconnected must not have
6569        # the PREVIOUS request's decode figures recorded as its own: each pass keeps its own DONE (a segment) if
6570        # one arrived.  A reasoning-budget continuation is another native generation, not another API request,
6571        # so the generated reasoning must not become this request's cached input (#615).
6572        segments = []
6573        timed_out = False
6574        trace = getattr(self.request_trace, "record", None)
6575        waiting = time.perf_counter()
6576        first_engine_token_s = None  # this request, from entering the engine queue; includes queue/prefill
6577        # #465: with "parallel" (the engine's batch slots) requests run at once: each keeps its own status and rate
6578        # window (self.status says busy while any runs); one at a time they are self.status / self.rate, as before
6579        par = bool(getattr(self.engine, "batch", 0))
6580        st = {} if par else self.status
6581        rate = collections.deque(maxlen=32) if par else self.rate
6582        request_id = uuid.uuid4().hex[:12]
6583        setattr(cancel, "_strata_request_id", request_id)
6584        deadline = time.monotonic() + self.queue_timeout_s if self.queue_timeout_s is not None else None
6585        if deadline is not None:
6586            setattr(cancel, "_strata_queue_deadline", deadline)
6587        def queue_started():
6588            with self.status_lock:
6589                row = self.terminal_requests.get(request_id)
6590                if row is not None and row["state"] != "reading":
6591                    row["state"] = "reading"
6592                    self._terminal_event_locked(request_id, "reading")
6593        setattr(cancel, "_strata_queue_started", queue_started)
6594        def replica_selected(index: int) -> None:
6595            with self.status_lock:
6596                row = self.terminal_requests.get(request_id)
6597                if row is not None:
6598                    row["replica"] = index
6599        setattr(cancel, "_strata_replica_selected", replica_selected)
6600        with self.status_lock:
6601            self.status["queued"] += 1
6602            self.terminal_requests[request_id] = {"id": request_id, "state": "queued",
6603                                                    "queued_at": time.time(), "admitted_at": None,
6604                                                    "prompt_tokens": len(ids)}
6605            self._terminal_event_locked(request_id, "queued")
6606        queued_counted = True
6607        try:
6608            # --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them)
6609            turn = contextlib.ExitStack()
6610            if not par:
6611                # #1619: a request waiting for the single turn sends a keep-alive every QUEUE_BEAT_S, so a client with
6612                # a stream idle timeout does not abort a healthy queued request (and its retry read the prompt again);
6613                # a client that left while queued gives its place up instead of taking the turn only to cancel there
6614                got = False
6615                while not got:
6616                    if cancel.is_set():
6617                        raise QueueCancelled("the client disconnected while waiting for the engine")
6618                    left = deadline - time.monotonic() if deadline is not None else QUEUE_BEAT_S
6619                    if left <= 0:
6620                        raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
6621                    got = self.fifo.acquire(timeout=min(QUEUE_BEAT_S, left))
6622                    if got:
6623                        if cancel.is_set():
6624                            self.fifo.release()
6625                            raise QueueCancelled("the client disconnected while waiting for the engine")
6626                        if deadline is not None and time.monotonic() >= deadline:
6627                            self.fifo.release()
6628                            raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
6629                        turn.callback(self.fifo.release)
6630                    else:
6631                        yield "ping", None
6632            with turn:
6633                try:
6634                    with self.status_lock:
6635                        if trace is not None:
6636                            trace["queue_s"] += round(time.perf_counter() - waiting, 3)
6637                            trace["state"] = "generating"
6638                        if not par:
6639                            self.status["queued"] -= 1
6640                            queued_counted = False
6641                            self.terminal_requests[request_id].update(state="admitted", admitted_at=time.time())
6642                            self._terminal_event_locked(request_id, "admitted")
6643                    # issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing
6644                    # (parallel requests do not hold the fifo: one of them starts it, the others wait for that).
6645                    # #1603: a parallel request stays counted as queued until it is registered as running below -
6646                    # waiting here for the fifo (an image encode, a /v1/vram resize) left it neither - and one on a
6647                    # loaded engine has nothing to start, so it does not wait for the fifo at all
6648                    if not par:
6649                        self.ensure_loaded()
6650                    elif not (self.loaded() and not self._vision_down()):
6651                        with self._inference_fifo(deadline, cancel):
6652                            self.ensure_loaded()
6653                    with self.status_lock:
6654                        if par:
6655                            self.status["queued"] -= 1
6656                            queued_counted = False
6657                            self.terminal_requests[request_id].update(state="waiting", admitted_at=time.time())
6658                            self._terminal_event_locked(request_id, "admitted")
6659                        st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids),
6660                                  generated=0, started=time.time(), first_token=None, tool=None, tail="",
6661                                  max_tokens=max_new, reasoning_recoveries=0, thinking_budget=budget)
6662                        if par:
6663                            self.live_reqs[id(st)] = (st, rate)
6664                            self.status.update(st)
6665                        self.last_request_at = time.time()
6666                        rate.clear()                    # the previous request's samples must not leak into this one
6667                    before = getattr(self.engine, "last", None)
6668                    last_print = time.time()
6669                    prompt, thought = ids, 0            # thought: the reasoning tokens so far (the budget's count)
6670                    # the engine stops at the budget itself (HOLD_KEY), when it can and </think> is one token: a --batch engine
6671                    # only when its slots say they hold too (READY holdb)
6672                    hold_end = None
6673                    if (budget and getattr(self.engine, "can_hold", False) is True
6674                            and (not getattr(self.engine, "batch", 0) or getattr(self.engine, "can_hold_batch", False) is True)
6675                            and getattr(self.engine, "split_engine", False) is not True):   # (the split engine's parser refuses the key: tests/split/test_split_gen_keys.py)
6676                        te = self.tok.encode(THINK_END, parse_special=True)
6677                        hold_end = te[0] if len(te) == 1 else None
6678                    for ev in opening:
6679                        yield "event", ev
6680                    while True:
6681                        segment_before = getattr(self.engine, "last", None)
6682                        segments_before = len(segments)     # (#879: a pass sent again leaves no segment)
6683                        held = hold_end is not None and budget is not None
6684                        if held:   # the reasoning tokens left before the budget (at least one: a cut not yet clean)
6685                            pass_sampling = {k: v for k, v in (sampling or {}).items() if k != HOLD_KEY}   # (a copy: the hold is this pass's own)
6686                            pass_sampling[HOLD_KEY] = (max(1, int(budget) - thought), int(hold_end))
6687                        elif sampling and HOLD_KEY in sampling:   # (never a client's: strip it from a copy)
6688                            pass_sampling = {k: v for k, v in sampling.items() if k != HOLD_KEY}
6689                        else:
6690                            pass_sampling = sampling   # no hold: the engine gets the caller's own sampler object, as before P2
6691                        gen = self.engine.generate(prompt, max_new - n, pass_sampling, cancel, embeddings=emb) if emb \
6692                            else self.engine.generate(prompt, max_new - n, pass_sampling, cancel)
6693                        recover_prompt = None
6694                        tloop = False                   # the wrap is for a token repeated in the thinking
6695                        seg, wrap, leaving = [], False, False   # this pass's tokens; the budget is reached; closed
6696                        nonfinite = False               # #879: the engine ended this pass on non-finite logits
6697                        opens = False                   # the thinking is over: write the forced call's opening
6698                        try:
6699                            # A value the frontend holds back (a tool call's array or object argument is sent
6700                            # whole, once complete) can keep the stream silent for minutes while tokens are
6701                            # generated; a client's idle timeout then ends the request.  Send the same keep-alive
6702                            # the engine's heartbeat sends when nothing has gone out for KEEPALIVE_S.
6703                            last_out = time.perf_counter()
6704                            for t in gen:
6705                                if t is None:               # heartbeat while the engine is quiet
6706                                    last_print = self._progress(last_print, st=st)
6707                                    last_out = time.perf_counter()
6708                                    yield "ping", None
6709                                    continue
6710                                n += 1
6711                                if first_engine_token_s is None:
6712                                    first_engine_token_s = round(time.perf_counter() - waiting, 3)
6713                                    with self.status_lock:
6714                                        row = self.terminal_requests.get(request_id)
6715                                        if row is not None:
6716                                            row["first_engine_token_s"] = first_engine_token_s
6717                                            self._terminal_event_locked(request_id, "first_token")
6718                                if trace is not None and trace["first_token_s"] is None:
6719                                    with self.status_lock:
6720                                        trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3)
6721                                if t in self.stop_ids:
6722                                    if force and parser.state == "reasoning" and parser.buf == THINK_END:
6723                                        opens = True    # #537: the held </think> was the end: the call opens there
6724                                        break
6725                                    finish = "stop"
6726                                    raw_ids.append(t)
6727                                    break
6728                                raw_ids.append(t)
6729                                seg.append(t)
6730                                thinking_n += parser.state in ("reasoning", "rcall")
6731                                run_len = run_len + 1 if t == run_tok else 1
6732                                run_tok = t
6733                                if (self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens
6734                                        and not (self.thinking_loop_tokens and parser.state == "reasoning")):
6735                                    repeated = True     # #606: a degenerate output, not an answer: end it here
6736                                    break
6737                                piece = detok.push(t)
6738                                tail = (tail + piece)[-2:]
6739                                evs = cut(parser.feed(piece))
6740                                self._note(n, evs, st, rate)
6741                                last_print = self._progress(last_print, st=st)
6742                                for ev in evs:
6743                                    if self.reasoning_loop_recovery and ev.kind == "reasoning":
6744                                        reasoning_text += ev.text or ""
6745                                    if ev.kind in ("content", "tool_start", "tool_call"):
6746                                        answered = True
6747                                    yield "event", ev
6748                                if evs:
6749                                    last_out = time.perf_counter()
6750                                elif time.perf_counter() - last_out >= KEEPALIVE_S:
6751                                    last_out = time.perf_counter()
6752                                    yield "ping", None
6753                                if stops is not None and stops.hit is not None:
6754                                    finish = "stop"         # gen.close() below STOPs the engine, as for a stop token
6755                                    break
6756                                if (self.reasoning_loop_recovery and not recovery_count and parser.state == "reasoning"
6757                                        and n >= next_loop_check and not parser.buf and not parser.pending
6758                                        and not detok.pending()):
6759                                    next_loop_check = n + LOOP_CHECK_EVERY
6760                                    repeat_coverage = reasoning_repeat_coverage(reasoning_text)
6761                                    if repeat_coverage >= LOOP_COVERAGE:
6762                                        if self.reasoning_loop_recovery == "stop":
6763                                            looped = True        # #728: end the reply here, as for a repeated token
6764                                            break
6765                                        if not emb:              # "recover": not for a request with pictures
6766                                            recover_prompt = focused_recovery_prompt(self.tok, ids, raw_ids)
6767                                            if recover_prompt is not None:
6768                                                break
6769                                if (self.thinking_loop_tokens and parser.state == "reasoning"
6770                                        and run_len >= self.thinking_loop_tokens
6771                                        and not parser.buf and not detok.pending()):
6772                                    wrap = tloop = True     # one token repeated in the thinking: close it, answer
6773                                    break
6774                                if budget and parser.state == "reasoning":
6775                                    thought += 1
6776                                    # at a clean point: no tag held back, no character split across tokens
6777                                    if thought >= budget and parser.clean and not detok.pending():
6778                                        wrap = True
6779                                        break
6780                                if force:
6781                                    if any(ev.kind in ("tool_start", "tool_call") for ev in evs):
6782                                        force = None    # the model is writing a call of its own
6783                                    elif parser.state == "content" and parser.clean and not detok.pending():
6784                                        opens = True
6785                                        break
6786                        except EngineNonFinite:
6787                            nonfinite = True
6788                        except EngineDied as e:
6789                            finish = "error"
6790                            self._say_died(e)
6791                            raise
6792                        except QueueWaitExpired:
6793                            finish = "error"
6794                            timed_out = True
6795                            raise
6796                        except ValueError as e:             # the engine's ERR line (it may have ended after it)
6797                            finish = "error"
6798                            print(f"[strata] the engine reported an error: {e}", flush=True)
6799                            raise
6800                        except GeneratorExit:               # the client went away: an engine that never acknowledges
6801                            leaving = True                  # the STOP below is ended, but no error replaces this
6802                            raise
6803                        finally:
6804                            try:
6805                                gen.close()             # STOP+drain to THIS request's DONE while still holding the
6806                                #                         fifo, so a stop-token break can't leave the shared engine
6807                                #                         queue mid-drain for the next request to read as its own DONE
6808                            except EngineSilent as e:   # #481: the STOP was never acknowledged: the engine is ended
6809                                finish = "error"
6810                                self._say_died(e)
6811                                if not leaving and not cancel.is_set():
6812                                    raise
6813                            segment_done = getattr(self.engine, "last", None)
6814                            if segment_done is not None and segment_done is not segment_before:
6815                                segments.append(dict(segment_done))
6816                        if nonfinite and not cancel.is_set():
6817                            # #879: the engine emitted none of the poisoned window's tokens and reads its next prompt
6818                            # from token 0.  Nothing sent yet: the same request once more, unseen by the client
6819                            if n == 0 and not nf_retried:
6820                                nf_retried = True
6821                                # the retry reads from token 0: its DONE, not this one's, says what was reused
6822                                del segments[segments_before:]
6823                                print("[strata] the engine's logits became non-finite before the first token (#879); it "
6824                                      "dropped its cached state: sending the request again once", flush=True)
6825                                continue
6826                            if n == 0:
6827                                finish = "error"
6828                                print("[strata] the engine's logits became non-finite again on the retry (#879): the "
6829                                      "request ends with an error", flush=True)
6830                                raise EngineNonFinite("the model's output became non-finite (NaN) twice in a row "
6831                                                      "(#879); the engine has dropped its cached state - send the "
6832                                                      "request again")
6833                            print(f"[strata] the engine's logits became non-finite after {n} tokens (#879): the reply "
6834                                  "ends here as \"length\"; the engine dropped its cached state, so the next request "
6835                                  "reads its prompt from the start", flush=True)
6836                            finish = "length"
6837                            break
6838                        if recover_prompt is not None and not cancel.is_set() and n < max_new:
6839                            recovery_count += 1
6840                            # Only the two settings that keep the same words coming are raised (temperature to at
6841                            # least 1.0, presence penalty to at least 1.5): a client's top_p and top_k are never
6842                            # touched, and its own request dict is copied, not changed.
6843                            want = (max(1.0, float((sampling or {}).get("temperature") or 0)),
6844                                    max(1.5, float((sampling or {}).get("presence_penalty") or 0)))
6845                            if want != tuple(float((sampling or {}).get(k) or 0)
6846                                             for k in ("temperature", "presence_penalty")):
6847                                sampling = {**(sampling or {}), "temperature": want[0], "presence_penalty": want[1]}
6848                            prompt = recover_prompt
6849                            with self.status_lock:
6850                                st["reasoning_recoveries"] = recovery_count
6851                            if trace is not None:
6852                                trace["reasoning_recoveries"] = recovery_count
6853                                trace["reasoning_repeat_coverage"] = round(repeat_coverage, 3)
6854                            print(f"[strata] repeated reasoning detected at {n} tokens "
6855                                  f"(coverage={repeat_coverage:.3f}); resuming the same output with the low-effort "
6856                                  "instruction (reasoning_loop_recovery)", flush=True)
6857                            continue
6858                        if (self.reasoning_close_retry and thinking and finish == "stop" and not close_retried
6859                                and not answered and not wrap and not opens and parser.state == "reasoning"
6860                                and parser.buf != THINK_END         # #537: not after a held </think>, the end
6861                                and (stops is None or stops.hit is None) and not cancel.is_set()):
6862                            # #1053: the model wrote its reasoning and stopped before </think>: the client would get
6863                            # an empty answer.  Close the thinking once and let it answer.
6864                            close_retried = True
6865                            extra = self.tok.encode(REASONING_CLOSE, parse_special=True)
6866                            if max_new - n - len(extra) >= 1:
6867                                print("[strata] the reply ended inside its thinking with no answer: closing the "
6868                                      "thinking once and continuing (reasoning_close_retry)", flush=True)
6869                                for t in extra:
6870                                    n += 1
6871                                    raw_ids.append(t)
6872                                    thinking_n += parser.state in ("reasoning", "rcall")
6873                                    evs = cut(parser.feed(detok.push(t)))
6874                                    self._note(n, evs, st, rate)
6875                                    for ev in evs:
6876                                        yield "event", ev
6877                                prompt = prompt + seg + extra
6878                                finish = "length"
6879                                continue
6880                        if (held and not (wrap or opens) and not cancel.is_set() and finish != "stop" and not repeated
6881                                and not looped and n < max_new and segments and segments[-1].get("finish") == "hold"
6882                                and len(segments) > segments_before):
6883                            # the engine stopped at the hold but the cut is not clean yet (a character split across
6884                            # tokens, a tag held back) or the reasoning count is short: on from the live session
6885                            prompt = prompt + seg
6886                            continue
6887                        if not (wrap or opens) or cancel.is_set():
6888                            break
6889                        # #123: the thinking reached reasoning_budget_tokens.  Close it the way the model would (a
6890                        # short wrap-up and </think>) and let it answer: the next pass's prompt is this one plus what
6891                        # was generated plus the wrap-up, so the engine continues from the prefix it already holds.
6892                        # A forced call (tool_choice) is opened the same way: after the wrap-up, or where the
6893                        # thinking ended, after the blank line the template puts before a call.
6894                        if wrap:
6895                            budget = st["thinking_budget"] = None
6896                            text = (REASONING_CLOSE if tloop else REASONING_WRAP_UP) + (force or "")
6897                        else:
6898                            text = "\n" * (2 - (len(tail) - len(tail.rstrip("\n")))) + force
6899                        force = None
6900                        extra = self.tok.encode(text, parse_special=True)
6901                        if max_new - n - len(extra) < 1:
6902                            break                       # no room left to answer: "length", as without a budget
6903                        if tloop:
6904                            print(f"[strata] the thinking repeated one token {run_len} times: closing it "
6905                                  "(thinking_loop_tokens)", flush=True)
6906                            run_len = 0
6907                        elif wrap:
6908                            print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking",
6909                                  flush=True)
6910                        for t in extra:
6911                            n += 1
6912                            raw_ids.append(t)
6913                            thinking_n += parser.state in ("reasoning", "rcall")
6914                            evs = cut(parser.feed(detok.push(t)))
6915                            self._note(n, evs, st, rate)
6916                            for ev in evs:
6917                                yield "event", ev
6918                        if stops is not None and stops.hit is not None:
6919                            finish = "stop"
6920                            break
6921                        prompt = prompt + seg + extra
6922                    if cancel.is_set():
6923                        finish = "cancel"
6924                    elif looped:
6925                        print(f"[strata] the thinking repeated the same passages (coverage={repeat_coverage:.3f}) at "
6926                              f"{n} tokens: ended as \"length\" (reasoning_loop_recovery: \"stop\" in "
6927                              "strata-<model>.json; remove it to turn this off)", flush=True)
6928                    elif repeated:
6929                        print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) "
6930                              f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in "
6931                              "strata-<model>.json; 0 turns this off). If a new request with a short prompt does the "
6932                              "same, restart the server and report it (#606)", flush=True)
6933                except GpuBusy:
6934                    # #3040 (PR #5044's approach): a batch engine can use up its BGEN retries before it has admitted this
6935                    # request.  The monitor keeps an error row, but it is not a completed generation: no prompt tokens
6936                    # and no part in the totals or latencies.  A continuation after native work keeps the old accounting.
6937                    if not segments and n == 0:
6938                        admission_rejected = True
6939                        finish = "error"
6940                    raise
6941                except GeneratorExit:                   # the client disconnected mid-stream
6942                    finish = "disconnect"
6943                    raise
6944                finally:
6945                    # #266: settle this request's status, history and totals while still holding the fifo: once
6946                    # it is released the next request sets its own status, which this must not record or clear
6947                    with self.status_lock:
6948                        if st.get("busy") and not timed_out:
6949                            last = request_stats(segments)          # only this request's own DONEs count
6950                            started = st.get("started", time.time())
6951                            cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0)
6952                            loaded = str(cvec) not in ("0", "", "None")
6953                            hit_rate = round(last["hits"] / last["lookups"], 3) if last.get("lookups") else None
6954                            # #588: the share the GPU read over PCIe (--pcie-frac) or another GPU computed - not in
6955                            # the hit rate's lookups, which is the VRAM share of the rest (None: an older engine)
6956                            routed = (last.get("lookups") or 0) + (last.get("offloaded") or 0)
6957                            pcie_share = round(last["offloaded"] / routed, 3) \
6958                                if last.get("offloaded") is not None and routed else None
6959                            seen = 0 if admission_rejected else prompt_tokens_seen(len(ids), last)   # #471: < len(ids) when cancelled mid-read; #3040
6960                            self.history.append({
6961                                "id": request_id,
6962                                "projection": (sampling or {}).get("experimental_speed_projection") is not False
6963                                if loaded else None,
6964                                "time": started, "duration_s": round(time.time() - started, 1), "finish": finish,
6965                                "prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n,
6966                                "first_engine_token_s": first_engine_token_s,
6967                                # the request's whole prompt, and the tokens read of it (None: an older engine)
6968                                "prompt_total": len(ids), "prompt_read": last.get("prompt_read"),
6969                                "reasoning_recoveries": recovery_count,
6970                                "reasoning_repeat_coverage": round(repeat_coverage, 3),
6971                                "engine_generated": last.get("generated"),
6972                                "prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),
6973                                "decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)
6974                                if n and (last.get("generated") or 0) >= 2 and last.get("decode_ms") else None,
6975                                "hit_rate": hit_rate, "pcie_share": pcie_share, "ram_blobs": last.get("ram_blobs"),
6976                                "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"),
6977                                # #457: the speculative drafts from the DONE line (None: the engine did not say)
6978                                "drafts_offered": last.get("drafts_offered"),
6979                                "drafts_accepted": last.get("drafts_accepted"),
6980                                # suffix cache reuse (an engine with SCR on): the prompt's exact prefix kept, the tokens
6981                                # moved from the cached run, and the ones read (None: SCR off)
6982                                "scr_cached": last.get("cached"), "scr": last.get("scr"),
6983                                "scr_prefilled": last.get("prefilled")})
6984                            if not admission_rejected:                  # #3040: a refused admission did no work
6985                                t = self.totals
6986                                t["requests"] += 1
6987                                t["prompt_tokens"] += seen
6988                                t["reused"] += last.get("reused") or 0
6989                                t["output_tokens"] += n
6990                                t["prompt_ms"] += last.get("prompt_ms") or 0.0
6991                                t["decode_ms"] += last.get("decode_ms") or 0.0
6992                                t["drafts_offered"] += last.get("drafts_offered") or 0
6993                                t["drafts_accepted"] += last.get("drafts_accepted") or 0
6994                                t["scr_cached"] += last.get("cached") or 0
6995                                t["scr"] += last.get("scr") or 0
6996                                t["scr_prefilled"] += last.get("prefilled") or 0
6997                                ft0 = st.get("first_token")             # this request's own (#465: one per request)
6998                                self.latencies.observe(ft0 - started if ft0 else None, n,
6999                                                       (last.get("decode_ms") or 0.0) / 1000, time.time() - started)
7000                                fresh = getattr(self.engine, "last", None)
7001                                if fresh is not None and fresh is not before:      # the engine's clock for THIS request
7002                                    timings = request_timings(seen, n, last)
7003                                    self.last_timings = dict(timings, at=int(time.time())) if timings else None
7004                            self.last_request_at = time.time()
7005                            now = time.time()
7006                            el = now - st.get("started", now)
7007                            ft = st.get("first_token")
7008                            rate = answer_speed(last, n, now - ft if ft else None)
7009                            hit_msg = f", expert cache {hit_rate*100:.1f}% hit" if hit_rate is not None else ""
7010                            if hit_msg and pcie_share:
7011                                hit_msg += f" (+{pcie_share*100:.1f}% of the routed experts over PCIe)"
7012                            rate_txt = f"{rate:.1f} tok/s" if rate is not None else "no speed"
7013                            print(f"[strata] done: {n} tokens in {el:.0f} s ({rate_txt}) "
7014                                  f"({finish}, cancel={cancel.is_set()}){hit_msg}", flush=True)
7015                            if finish == "length" and parser.state in ("reasoning", "rcall"):   # #530
7016                                print("[strata] the reply reached max tokens while still thinking, so it has no "
7017                                      "answer: a thinking budget (reasoning_budget_tokens, in the request or in "
7018                                      "strata-<model>.json for every request) leaves room to answer", flush=True)
7019                            if os.environ.get("STRATA_DEBUG") and raw_ids:
7020                                print(f"[strata] raw: {self.tok.decode(raw_ids)!r}", flush=True)
7021                                print(f"[strata] raw ids: {list(raw_ids)}", flush=True)
7022                        st["busy"] = False
7023                        st.pop("tail", None)                     # #212: the answer's end is not kept once it is done
7024                        st.pop("tool", None)
7025                        if par:
7026                            self.live_reqs.pop(id(st), None)
7027                            if self.live_reqs:              # the newest request still running
7028                                self.status.update(list(self.live_reqs.values())[-1][0])
7029                            else:
7030                                self.status.update(busy=False)
7031                                self.status.pop("tail", None)
7032                                self.status.pop("tool", None)
7033        except QueueCancelled:
7034            finish = "cancel"
7035            yield "done", {"finish": "cancel", "completion_tokens": 0, "reused": 0, "timings": None,
7036                           "reasoning_tokens": 0, "reasoning_recoveries": 0}
7037            return
7038        except QueueWaitExpired:
7039            finish = "timeout"
7040            with self.status_lock:
7041                self.queue_timeouts += 1
7042            raise
7043        except Exception:
7044            finish = "error"
7045            raise
7046        finally:
7047            with self.status_lock:
7048                if queued_counted:
7049                    self.status["queued"] -= 1
7050                self.terminal_requests.pop(request_id, None)
7051                event = {"stop": "finished", "length": "finished", "cancel": "cancelled",
7052                         "disconnect": "disconnected", "timeout": "timeout", "error": "error"}.get(finish, "error")
7053                self._terminal_event_locked(request_id, event, finish)
7054            if emb:
7055                Path(emb).unlink(missing_ok=True)
7056        for ev in cut(parser.finish(finish)):
7057            yield "event", ev
7058        if parser.rescued or parser.refused:
7059            self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued
7060            print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as "
7061                  f"reasoning (quoted, or the turn did not end on a stop)", flush=True)
7062        if getattr(parser, "stray_think", 0):
7063            # #4077: the model wrote a closing think tag while thinking; the reasoning after it was sent as the answer
7064            self.totals["stray_think_closers"] = self.totals.get("stray_think_closers", 0) + parser.stray_think
7065            print(f"[strata] {parser.stray_think} extra closing think tag(s) in the answer were dropped (the model wrote one "
7066                  "while thinking, so the rest of its reasoning went out as the answer; a call after it still counts)", flush=True)
7067        if getattr(parser, "notes", None):
7068            self.totals["tool_args_repaired"] = self.totals.get("tool_args_repaired", 0) + len(parser.notes)
7069            print(f"[strata] {len(parser.notes)} tool call argument(s) repaired: {'; '.join(sorted(set(parser.notes)))}", flush=True)
7070        rejected = []
7071        if parser.unread:
7072            named = getattr(parser, "unread_names", None)
7073            print(f"[strata] {parser.unread} <tool_call> block(s) in the answer did not read as a call of a declared "
7074                  "tool and went back as text (a name the request did not declare, or a form the template does "
7075                  "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else "")
7076                  + "; the response carries them as strata_rejected_tool_calls, /metrics counts them", flush=True)
7077            with self.status_lock:
7078                self.totals["tool_calls_unread"] = self.totals.get("tool_calls_unread", 0) + parser.unread
7079            # #3796: the same names for the client (a machine-readable marker next to the text, which stays as the model wrote it)
7080            rejected = [{"name": nm, "reason": "undeclared"} for nm in named or []]
7081        if stops is not None and stops.hit is None and stops.held:
7082            yield "event", Event("content", stops.flush())     # the held tail was not a stop string after all
7083        done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),
7084                "timings": timings, "reasoning_tokens": thinking_n,
7085                "reasoning_recoveries": recovery_count}
7086        if stops is not None and stops.hit is not None:
7087            done["stop_sequence"] = stops.hit
7088        if rejected:
7089            done["rejected_tool_calls"] = rejected
7090        yield "done", done
7091
7092
7093def prompt_tokens_seen(prompt_tokens: int, last: dict) -> int:
7094    """#471: the prompt tokens a request got through - all of them, unless the engine's DONE line says a cancel stopped
7095    its prompt read part-way (then the reused ones plus those read).  /metrics' history and totals count these, so a
7096    cancelled read is neither recorded as the whole prompt nor given a rate from tokens it never read.  An engine
7097    before 0.1.36 does not say (no `prompt_read`): the whole prompt, as before."""
7098    read = last.get("prompt_read")
7099    if read is None or last.get("finish") != "cancel":
7100        return prompt_tokens
7101    return min(prompt_tokens, int(last.get("reused") or 0) + int(read))
7102
7103
7104def carry_leg(carry: dict, leg: dict) -> None:
7105    """#1869: a request that decoded in a batch slot and went back to the solo path ends with the solo path's DONE, which
7106    replaces the engine's figures: keep the slot leg's decode time, tokens and prompt figures to add to it."""
7107    for key in ("decode_ms", "generated"):
7108        previous, value = carry.get(key, 0), leg.get(key)
7109        carry[key] = previous + value if previous is not None and value is not None else None
7110    carry.setdefault("prompt_ms", float(leg.get("prompt_ms") or 0.0))
7111    if leg.get("prompt_read") is not None:
7112        carry.setdefault("prompt_read", int(leg["prompt_read"]))
7113
7114
7115def add_carry(carry: dict, last: dict) -> dict:
7116    """The request's totals: the earlier legs' decode time and tokens plus the final one's; the prompt figures of the leg
7117    that read the prompt (the solo continuation reads next to nothing)."""
7118    out = {**last, "prompt_ms": max(float(last.get("prompt_ms") or 0.0), carry.get("prompt_ms", 0.0))}
7119    for key in ("decode_ms", "generated"):
7120        previous, value = carry.get(key, 0), last.get(key)
7121        out[key] = previous + value if previous is not None and value is not None else None
7122    if "prompt_read" in carry:
7123        out["prompt_read"] = carry["prompt_read"]
7124    return out
7125
7126
7127def answer_speed(last: dict, generated: int, wall_s: float | None = None) -> float | None:
7128    """The one definition of "answer speed": every token the model produced (thinking and answer, the tokens it kept - not
7129    the MTP drafts it threw away) over the decode time, first generated token to last.  The engine's DONE line holds both
7130    numbers; /metrics (`decode_tok_s`), the timings (`predicted_per_second`), the Terminal monitor and the app all use them.
7131    Only an engine that sent no DONE falls back to the server's own clock from the first token, and a clock younger than
7132    RATE_MIN_SPAN_S says nothing (it printed 1000000 tok/s for a one-token reply).  Prompt reading is never in it."""
7133    produced, decode_ms = last.get("generated"), last.get("decode_ms")
7134    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)
7135        return round(produced / (decode_ms / 1000), 1)
7136    if generated and wall_s is not None and wall_s >= RATE_MIN_SPAN_S:
7137        return round(generated / wall_s, 1)
7138    return None
7139
7140
7141def request_timings(prompt_tokens: int, generated: int, last: dict) -> dict | None:
7142    """One request's `timings` in llama.cpp's names (what its clients show as speed), from the engine's own clock
7143    (StrataEngine.last): prompt_n is what was read, cache_n what the conversation cache already held.  None when the
7144    engine keeps no clock (MockEngine)."""
7145    if last.get("prompt_ms") is None:
7146        return None
7147    cache_n = int(last.get("reused") or 0)
7148    if last.get("prompt_read") is not None and last.get("finish") != "cancel":
7149        # #1870: the engine says how many prompt tokens it read: the slot's own session may have held the rest
7150        # (not the conversation cache), so the rate is not made of tokens it never read
7151        cache_n = max(cache_n, max(0, prompt_tokens - int(last["prompt_read"])))
7152    prompt_n, prompt_ms, decode_ms = max(0, prompt_tokens - cache_n), float(last["prompt_ms"]), last.get("decode_ms")
7153    decoded = last.get("generated")          # explicit zero and missing native work are not the API's output count
7154    return {"cache_n": cache_n, "prompt_n": prompt_n, "prompt_ms": round(prompt_ms, 1),
7155            "prompt_per_token_ms": round(prompt_ms / prompt_n, 3) if prompt_n else None,
7156            "prompt_per_second": round(prompt_n / (prompt_ms / 1000), 1) if prompt_n and prompt_ms > 0 else None,
7157            "predicted_n": generated, "predicted_ms": round(decode_ms, 1) if decode_ms is not None else None,
7158            "predicted_per_token_ms": round(decode_ms / decoded, 3) if decoded and decode_ms is not None else None,
7159            "predicted_per_second": round(decoded / (decode_ms / 1000), 1) if decoded and decode_ms and decode_ms > 0 else None,
7160            # the speculative drafts, as llama.cpp names them (from PR #83, @mikicvi): only when the engine reported them
7161            **({"draft_n": int(last["drafts_offered"]), "draft_n_accepted": int(last["drafts_accepted"])}
7162               if last.get("drafts_offered") is not None else {})}
7163
7164
7165def request_stats(segments: list[dict]) -> dict:
7166    """Keep input/cache accounting at the original API boundary and total native work across continuations."""
7167    if not segments:
7168        return {}
7169    result = dict(segments[-1])
7170    for key in ("reused", "prompt_read", "chunk"):
7171        if key in segments[0]:
7172            result[key] = segments[0][key]
7173        else:
7174            result.pop(key, None)
7175    for key in ("prompt_ms", "decode_ms", "generated", "drafts_offered", "drafts_accepted",
7176                "hits", "lookups", "offloaded", "ram_blobs", "file_blobs", "file_mb", "experts_streamed"):
7177        if key in ("decode_ms", "generated") and any(segment.get(key) is None for segment in segments):
7178            result[key] = None
7179        elif any(segment.get(key) is not None for segment in segments):
7180            result[key] = sum(segment.get(key) or 0 for segment in segments)
7181    return result
7182
7183
7184def prefill_leg_stats(earlier: list[dict], last: dict, prompt_tokens: int) -> dict:
7185    """Total yielded reads once, retaining only reuse from before this API request."""
7186    legs = [*earlier, last]
7187    total = request_stats(legs)
7188    if all(leg.get("prompt_read") is not None for leg in legs):
7189        fresh = max(0, prompt_tokens - int(total.get("reused") or 0))
7190        total["prompt_read"] = min(fresh, sum(int(leg["prompt_read"]) for leg in legs))
7191    return total
7192
7193
7194def _debug_req(api, req, messages, tools, max_new, thinking, prompt_tokens):
7195    """One compact line per request while diagnosing blank/empty turns. Set STRATA_DEBUG=1 to enable."""
7196    if not os.environ.get("STRATA_DEBUG"):
7197        return
7198    last = messages[-1] if messages else {}
7199    body = last.get("content")
7200    if isinstance(body, list):
7201        body = " ".join(p.get("text", "") for p in body if isinstance(p, dict))
7202    preview = (str(body or "")[:80]).replace("\n", " ")
7203    print(f"[strata] req {api}: msgs={len(messages)} tools={len(tools or [])} "
7204          f"max_tokens_raw={req.get('max_tokens')!r}/{req.get('max_completion_tokens')!r} "
7205          f"max_new={max_new} thinking={thinking} stream={bool(req.get('stream'))} "
7206          f"prompt_tokens={prompt_tokens} last={last.get('role')!r}:{preview!r}", flush=True)
7207
7208
7209# ------------------------------------------------------------------------------------------------ MCP tool loop
7210def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, max_req, sampling, cancel,
7211                 mcp_names):
7212    """Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds
7213    the call and its result to the conversation and lets the model continue - up to `max_rounds` times.  Yields what
7214    Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and
7215    one ("done", ...) at the very end with the output tokens of every round. After the last tool round, one final
7216    reply uses the results already obtained, with no tools offered or executed.
7217
7218    `mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the
7219    turn as always (the client answers it).  MCP calls written in the same answer are then not run (their results
7220    could not reach the model before the client's)."""
7221    max_rounds = int(hub.settings["max_rounds"])
7222    total, rounds, done = 0, 0, None
7223    finalizing = False
7224    messages = list(messages)
7225    while True:
7226        text, reasoning, calls, own_calls = [], [], [], 0
7227        for kind, x in svc.run(ids, thinking, tools, max_new, sampling, cancel, declared_only=True):
7228            if kind == "done":
7229                done = x
7230                continue
7231            if kind == "event":
7232                ev: Event = x
7233                if ev.call is not None and ev.call.name in mcp_names:
7234                    if ev.kind == "tool_start":          # the model has started writing a call: say so at once
7235                        yield "mcp", {"event": "start", "id": ev.call.id, "name": ev.call.name}
7236                    elif ev.kind == "tool_call":
7237                        calls.append(ev.call)
7238                    continue                             # its argument pieces are not streamed to the client
7239                if ev.kind == "tool_call":
7240                    own_calls += 1
7241                elif ev.kind == "content":
7242                    text.append(ev.text)
7243                elif ev.kind == "reasoning":
7244                    reasoning.append(ev.text)
7245            yield kind, x
7246        total += done["completion_tokens"]
7247        run_them = calls and not own_calls and not finalizing and done["finish"] == "stop" and not cancel.is_set()
7248        if not run_them:
7249            for c in calls:                              # announced, never run: close them in the client's view
7250                yield "mcp", {"event": "result", "id": c.id, "ok": False, "skipped": True, "text": "not run",
7251                              "chars": 0, "truncated": False, "ms": 0}
7252            break
7253        rounds += 1
7254        results = []
7255        for c in calls:
7256            s, tool = hub.routes().get(c.name, (None, c.name))
7257            yield "mcp", {"event": "call", "id": c.id, "name": c.name, "server": s.name if s else None,
7258                          "tool": tool, "arguments": c.arguments, "round": rounds}
7259            # The call runs on a thread while this generator keeps yielding heartbeats: they reach the client as
7260            # keep-alives, which is how a client that went away (the web app's Stop) is noticed during a slow tool.
7261            box = {}
7262
7263            def work(c=c, box=box):
7264                try:
7265                    box["r"] = hub.call(c.name, c.arguments, cancel)
7266                except McpCancelled:
7267                    box["cancelled"] = True
7268            worker = threading.Thread(target=work, daemon=True)
7269            worker.start()
7270            try:
7271                while worker.is_alive():
7272                    worker.join(1.0)
7273                    if worker.is_alive():
7274                        yield "ping", None
7275            except GeneratorExit:
7276                cancel.set()                             # the client is gone: stop the tool too
7277                raise
7278            if "r" not in box:
7279                break
7280            r = box["r"]
7281            print(f"[strata] tool {c.name}: {'ok' if r['ok'] else 'error'}, {r['chars']:,} characters in "
7282                  f"{r['ms'] / 1000:.1f} s{' (truncated for the model)' if r['truncated'] else ''}", flush=True)
7283            results.append(r.get("model_content", r["text"]) if svc.vision is not None else r["text"])
7284            yield "mcp", {"event": "result", "id": c.id,
7285                          **({"images": r["images"], "vision": svc.vision is not None} if r.get("images") else {}),
7286                          **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}}
7287        if cancel.is_set() or len(results) < len(calls):
7288            done = {**done, "finish": "cancel"}
7289            break
7290        messages.append({"role": "assistant", "content": "".join(text).strip(),
7291                         **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}),
7292                         "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]})
7293        messages += [{"role": "tool", "content": r} for r in results]
7294        if rounds >= max_rounds:
7295            finalizing = True
7296            tools = None
7297            system_end = next((index for index, message in enumerate(messages)
7298                               if message.get("role") not in ("system", "developer")), len(messages))
7299            messages.insert(system_end, {"role": "system", "content":
7300                f"The tool-use limit of {max_rounds} rounds has been reached. No tools are available for this final "
7301                "reply. Answer the user's original request in their language using the results already obtained. "
7302                "Explain any gaps in the available evidence. Do not request or emit further tool calls."})
7303            yield "mcp", {"event": "limit", "max_rounds": max_rounds}
7304        try:
7305            ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel)
7306        except ClientGone:                                      # #1999: the client left while a picture was prepared
7307            done = {**done, "finish": "cancel"}
7308            break
7309    yield "done", {**done, "completion_tokens": total, "prompt_tokens": len(ids)}
7310
7311
7312# ------------------------------------------------------------------------------------------------ OpenAI
7313# The engine's last PP line stops short of the prompt: up to `--short-read` tokens (generate.cpp's `short_read`, 64 by
7314# default) are read through the verify windows instead of the batched path, so the batched path never reports the whole
7315# prompt.  A PP that close to the end says the prompt is read.  It matters because a prompt shorter than one `--prefill`
7316# chunk sends exactly one PP, that one: a client would see a bar that appears already full.  Such a line is dropped, and
7317# the answer's first token ends the progress for the client anyway.
7318PP_DONE_TAIL = 64
7319
7320
7321
7322class LPLines(collections.deque):
7323    """One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler
7324    through Service.run to Engine.generate).  The last events of a request - the parser's and the stop strings'
7325    tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines
7326    with its own: LogprobEntries reads only the lines tagged with its own request's Event."""
7327
7328    def __init__(self, owner=None):
7329        super().__init__()
7330        self.owner = owner
7331
7332
7333class LogprobEntries:
7334    """The engine's LP lines as OpenAI's logprobs.content entries.
7335
7336    Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's
7337    text is made), so a character split across tokens lands in the token that finishes it and
7338    the tokens, joined, spell the reply.  "bytes" are the token's own bytes.  The stop token
7339    ends the reply and is not listed (OpenAI does not list it either).  Tokens that make no
7340    text of the reply are left out, because spell() gives each piece of text the tokens that
7341    spell it.
7342
7343    `allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them,
7344    so a caller asking about specific candidates gets a distribution over exactly those instead
7345    of a top-K list it has to hope contains them.  vLLM, which named the field, masks generation
7346    with these ids instead (every other logit -inf before sampling) and reports the unmasked
7347    distribution; here they filter what is reported, so the chosen token can be outside them.
7348
7349    On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path
7350    that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts.
7351    """
7352
7353    def __init__(self, svc, allowed=(), owner=None):
7354        self.tok, self.stop_ids = svc.tok, svc.stop_ids
7355        self.allowed = [i for i in allowed]
7356        self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace")
7357        self.pending = []                          # entries read but not yet given to a piece of text
7358        self.owner = owner                         # the request's cancel Event (LPLines)
7359        self.lines = None                          # this request's current LPLines, kept once seen
7360
7361    def spell(self, eng, text: str) -> list:
7362        """The entries whose tokens spell `text`, the next piece of the reply."""
7363        self.pending += self.take(eng)
7364        at = [0]
7365        for e in self.pending:
7366            at.append(at[-1] + len(e["token"]))
7367        joined = "".join(e["token"] for e in self.pending)
7368        i = joined.find(text)
7369        while i >= 0 and text:
7370            if i in at:
7371                a = at.index(i)                    # the first token there
7372                end = i + len(text)
7373                b = next((j for j in range(a + 1, len(at)) if at[j] == end), None)
7374                if b is not None:
7375                    out, self.pending = self.pending[a:b], self.pending[b:]
7376                    return out
7377            i = joined.find(text, i + 1)
7378        out, self.pending = self.pending, []
7379        return out
7380
7381    def raw(self, t):
7382        if hasattr(self.tok, "token_bytes"):
7383            return self.tok.token_bytes(t)
7384        return self.tok.decode([t]).encode("utf-8")
7385
7386    def take(self, eng) -> list:
7387        # the engine's current lines are this request's only when they carry its Event (a later generate pass
7388        # of the same request makes new ones: the old ones are read to the end first); another request's never are.
7389        # A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and
7390        # the next request to read control lines may already have replaced it.
7391        own = getattr(self.owner, "_strata_lp_lines", None)
7392        cur, old = (own if own is not None else getattr(eng, "lp_lines", None)), None
7393        if cur is not self.lines and getattr(cur, "owner", None) is self.owner:
7394            old, self.lines = self.lines, cur
7395        out = []
7396        for lines in (old, self.lines):
7397            while lines:
7398                t, line = lines.popleft()
7399                if t in self.stop_ids:
7400                    continue
7401                f = line.split()
7402                if len(f) < 2:
7403                    continue
7404                try:                               # "nan" (no head logits for that window row), "-nan(ind)"
7405                    lp = float(f[1])               # (MSVC) or a cut line: no entry for that token
7406                    alts = [(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])]
7407                except ValueError:
7408                    continue
7409                if not math.isfinite(lp) or not all(math.isfinite(v) for _, v in alts):
7410                    continue
7411                b = self.raw(t)
7412                e = {"token": self.inc.decode(b), "logprob": lp, "bytes": list(b),
7413                     "top_logprobs": []}
7414                if self.allowed:
7415                    alts = [(i, v) for i, v in alts if i in self.allowed]
7416                for i, v in alts:
7417                    alt = self.raw(i)
7418                    e["top_logprobs"].append({"token": alt.decode("utf-8", "replace"),
7419                                              "logprob": v, "bytes": list(alt)})
7420                if self.allowed:
7421                    e = self._renormalise(e, t, lp)
7422                out.append(e)
7423        return out
7424
7425    def _renormalise(self, e, t, lp):
7426        """Keep only the named ids and normalise over them, so they sum to 1.
7427
7428        The line carries the chosen token's own logprob on its head and the named ids after it, and never
7429        repeats the chosen one among them.  So the chosen token is put back when the caller named it: with
7430        `allowed_token_ids` naming only the token the model chose, that token is then the whole distribution,
7431        at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over,
7432        which returned None, the entry was appended all the same, and the reply failed on e["token"].  A line
7433        that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen
7434        token and its own logprob, with no alternatives.  It is never None and never dropped, because the
7435        reply's tokens have to keep spelling its text.
7436        """
7437        cand = e["top_logprobs"]
7438        own = None
7439        if t in self.allowed:                      # named, and not repeated on the line: it is a candidate
7440            b = self.raw(t)
7441            own = {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)}
7442            cand = [own] + cand
7443        if not cand:
7444            return e                               # no named id observed for this token: its own logprob, no top
7445        mx = max(x["logprob"] for x in cand)
7446        se = sum(math.exp(x["logprob"] - mx) for x in cand)
7447        lse = mx + math.log(se)
7448        for x in cand:
7449            x["logprob"] -= lse
7450        cand.sort(key=lambda x: -x["logprob"])     # most likely first, as the unfiltered top-k already is
7451        e["top_logprobs"] = cand
7452        if own is not None:                        # the chosen token is in the distribution: report its own value
7453            e["logprob"] = own["logprob"]           # (it used to copy the first alternative's, another token's)
7454        return e
7455
7456def prompt_progress(svc: Service):
7457    """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the
7458    same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a
7459    client takes the reused prefix out with `cache` (llama.cpp's rule: the timed progress is
7460    `(processed-cache)/(total-cache)`).  None when there is nothing to say: no PP yet, or the line that says the prompt
7461    is read.  An engine too old to print RESUME gives `cache` 0, which only makes a reused prefix count as work."""
7462    engine = svc.engine
7463    if getattr(engine, "batch", 0):      # --batch: the engine's progress is one global line, not this request's
7464        return None
7465    progress = getattr(engine, "progress", None)
7466    if not progress:
7467        return None
7468    read, total = progress
7469    if total <= 0 or total - read <= PP_DONE_TAIL:
7470        return None
7471    return {"total": int(total), "cache": int(getattr(engine, "reused", 0) or 0), "processed": int(read),
7472            "time_ms": int(getattr(engine, "progress_ms", 0) or 0)}
7473
7474
7475def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, run=None, force=None):
7476    """`run`: the events to send instead of Service.run's (run_with_mcp); its ("mcp", {...}) items become chunks with
7477    an empty delta and a `strata_mcp` field, which only the web app reads.  `force`: see Service.run."""
7478    cid, created = "chatcmpl-" + uuid.uuid4().hex[:24], int(time.time())
7479    model = svc.model_for(req)
7480    # llama.cpp's flag, and its default: a client that wants prompt progress asks for it, and nothing changes for one
7481    # that does not.  Strata already sends a keep-alive comment on every PP line, so this only fills that line in.
7482    want_progress = bool(req.get("return_progress"))
7483
7484    def chunk(delta, finish=None):
7485        return {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model,
7486                "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
7487
7488    yield chunk({"role": "assistant", "content": ""})
7489    lp = LogprobEntries(svc, allowed_ids(req), cancel) if top_logprobs(req) is not None else None
7490
7491    def with_lp(c, key):
7492        got = lp.spell(svc.engine, c["choices"][0]["delta"][key]) if lp is not None else None
7493        if got:
7494            c["choices"][0]["logprobs"] = {key: got}
7495        return c
7496    calls = 0
7497    streamed = {}                                  # tool call id -> index, for calls sent piece by piece
7498    finished = set()                               # ... and the ones whose final tool_call came (#211)
7499    answered_done = False                          # the run's own end (its "done" event) arrived
7500    born = getattr(svc.engine, "gen", None)        # the engine process this request is on (read again with every event: a start inside the run is its own)
7501    for kind, x in run if run is not None else svc.run(ids, thinking, tools, max_new, req, cancel, force=force, declared_only=True):
7502        born = getattr(svc.engine, "gen", born)
7503        if kind == "ping":
7504            # a PP line: the prompt is being read and there is nothing to say yet.  It used to be only the SSE comment;
7505            # now it carries the progress when the client asked, and stays the comment when there is nothing to report.
7506            pp = prompt_progress(svc) if want_progress else None
7507            yield None if pp is None else {**chunk({}), "prompt_progress": pp}
7508        elif kind == "mcp":
7509            c = chunk({})
7510            c["strata_mcp"] = x
7511            yield c
7512        elif kind == "event":
7513            ev: Event = x
7514            if ev.kind == "reasoning" and ev.text:
7515                yield with_lp(chunk({"reasoning_content": ev.text}), "reasoning_content")
7516            elif ev.kind == "content" and ev.text:
7517                yield with_lp(chunk({"content": ev.text}), "content")
7518            elif ev.kind == "tool_start":
7519                streamed[ev.call.id] = calls
7520                calls += 1
7521                yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "id": ev.call.id, "type": "function",
7522                                             "function": {"name": ev.call.name, "arguments": ""}}]})
7523            elif ev.kind == "tool_args":
7524                yield chunk({"tool_calls": [{"index": streamed[ev.call.id], "function": {"arguments": ev.text}}]})
7525            elif ev.kind == "tool_call" and ev.call.id in streamed:
7526                finished.add(ev.call.id)
7527            elif ev.kind == "tool_call":
7528                yield chunk({"tool_calls": [{"index": calls, "id": ev.call.id, "type": "function",
7529                                             "function": {"name": ev.call.name,
7530                                                          "arguments": json.dumps(ev.call.arguments, ensure_ascii=False)}}]})
7531                calls += 1
7532        else:
7533            answered_done = True
7534            # a streamed call without its final tool_call is one the output ended inside: not "tool_calls" (#211)
7535            whole = calls and streamed.keys() <= finished
7536            finish = "tool_calls" if whole and x["finish"] == "stop" else {"cancel": "stop"}.get(x["finish"], x["finish"])
7537            last = chunk({}, finish)
7538            pt = x.get("prompt_tokens", len(ids))     # after MCP rounds: the last round's prompt
7539            last["usage"] = {"prompt_tokens": pt, "completion_tokens": x["completion_tokens"],
7540                             "total_tokens": pt + x["completion_tokens"],
7541                             # the part of the prompt the conversation cache already held (OpenAI's field)
7542                             "prompt_tokens_details": {"cached_tokens": x.get("reused") or 0}}
7543            if x.get("timings"):
7544                last["timings"] = x["timings"]          # llama.cpp's field: the speed its clients show
7545            if x.get("rejected_tool_calls"):
7546                last["strata_rejected_tool_calls"] = x["rejected_tool_calls"]     # #3796: only when a call was refused as undeclared
7547            yield last
7548    if not answered_done and not cancel.is_set():
7549        # Every admitted request ends with a "done" event that carries its finish reason. A run that simply stopped (a 200 with one chunk and no
7550        # finish_reason, in 0.2 s, while the engine never logged the request: #3961) used to read to the client as an empty answer that worked, and
7551        # /health stayed ok. It is an error now, counted in the log, so a client's retry can tell it from an answer.
7552        print("[strata] a request ended without an answer and without a finish reason; it is answered as an error", flush=True)
7553        # the engine is ended so "the next request restarts it" is true - but only that engine process, and only while nobody is on it (the turn is taken
7554        # without waiting): this runs after the run released its turn, and a request admitted since must not be killed by it
7555        ended = svc.end_engine_if_unchanged(born)
7556        lost = EngineDied("the engine ended the request without an answer")
7557        lost.restarts = bool(ended)                 # "the next request restarts it" only where the engine really was ended (not with batch slots, replicas, another request on it)
7558        raise lost
7559
7560
7561def _is_json(text: str) -> bool:
7562    try:
7563        json.loads(text)
7564        return True
7565    except ValueError:
7566        return False
7567
7568
7569def openai_collect(chunks) -> dict:
7570    content, reasoning, by_index, last, mcp = [], [], {}, None, []
7571    lps = {}                                       # "content" / "reasoning_content" -> logprob entries
7572    for c in chunks:
7573        if c is None:                              # a heartbeat
7574            continue
7575        if c.get("strata_mcp"):
7576            mcp.append(c["strata_mcp"])
7577        for k, v in (c["choices"][0].get("logprobs") or {}).items():
7578            lps.setdefault(k, []).extend(v)
7579        d = c["choices"][0]["delta"]
7580        content.append(d.get("content") or "")
7581        reasoning.append(d.get("reasoning_content") or "")
7582        for tc in d.get("tool_calls") or []:       # streamed calls arrive in pieces: merge them by index
7583            cur = by_index.setdefault(tc.get("index", len(by_index)), {"id": None, "type": "function",
7584                                                                        "function": {"name": "", "arguments": ""}})
7585            cur["id"] = tc.get("id") or cur["id"]
7586            fn = tc.get("function") or {}
7587            cur["function"]["name"] += fn.get("name") or ""
7588            cur["function"]["arguments"] += fn.get("arguments") or ""
7589        last = c
7590    calls = [by_index[i] for i in sorted(by_index)]
7591    if last["choices"][0]["finish_reason"] != "tool_calls":
7592        calls = [c for c in calls if _is_json(c["function"]["arguments"])]   # a call the output ended inside (#211)
7593    msg = {"role": "assistant", "content": "".join(content) or None}
7594    if "".join(reasoning).strip() and "".join(reasoning).strip() == "".join(content).strip():
7595        reasoning = []              # a turn with no </think> (serve/dsml.py): the text is the answer; it is not also reasoning
7596    if "".join(reasoning):
7597        msg["reasoning_content"] = "".join(reasoning)
7598    if calls:
7599        msg["tool_calls"] = calls
7600    if mcp:
7601        msg["strata_mcp"] = mcp
7602    out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"],
7603           "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}],
7604           "usage": last["usage"]}
7605    if lps:
7606        out["choices"][0]["logprobs"] = {"content": lps.get("content", []), "refusal": None, **(
7607            {"reasoning_content": lps["reasoning_content"]} if lps.get("reasoning_content") else {})}
7608    if last.get("timings"):
7609        out["timings"] = last["timings"]
7610    if last.get("strata_rejected_tool_calls"):
7611        out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"]
7612    return out
7613
7614
7615def logprob_span(text: str, part: str, entries: list):
7616    """The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not
7617    spell `text` or no token boundary falls at both ends of `part`."""
7618    if "".join(e["token"] for e in entries) != text:
7619        return None
7620    start = text.find(part)
7621    if start < 0:
7622        return None
7623    at, first = 0, None
7624    for i, e in enumerate(entries):
7625        if at == start and first is None:
7626            first = i
7627        if at == start + len(part) and first is not None:
7628            return entries[first:i]
7629        at += len(e["token"])
7630    return entries[first:] if first is not None and at == start + len(part) else None
7631
7632
7633def _same_json(a: str, b: str) -> bool:
7634    """Are two strings the same JSON value (whitespace and key order aside)?  No -> False."""
7635    try:
7636        return json.loads(a) == json.loads(b)
7637    except Exception:
7638        return False
7639
7640
7641def _structured_logprobs(choice: dict, content: str):
7642    """`content`'s logprobs, and the content the tokens actually spell.
7643
7644    Returns `(content, logprobs)`: on failure `(the content as validated, None)`.
7645
7646    `structured_chunks` returns the canonical JSON the validator produced, which the model never
7647    generated, so its tokens do not spell it.  Two honest outcomes:
7648
7649      1. a run of tokens spells what is being returned -> use it as it is;
7650      2. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces
7651         case, the common one) -> return the model's form, so `''.join(token) == content` again.
7652
7653    Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no
7654    logprobs: a caller that joins the tokens must not silently get something that does not match.
7655    """
7656    lps = choice.get("logprobs")
7657    if not lps or not lps.get("content"):
7658        return content, None
7659    raw = choice["message"]["content"] or ""
7660    entries = lps["content"]
7661    if raw == content:                          # not rewritten: the entries are already its
7662        return content, _with_reasoning(lps, entries)
7663    span = logprob_span(raw, content, entries)
7664    if span is not None:
7665        return content, _with_reasoning(lps, span)
7666    inner = extract_json(raw)
7667    if inner and _same_json(inner, content):
7668        span = logprob_span(raw, inner, entries)
7669        if span is not None:
7670            return inner, _with_reasoning(lps, span)   # the model's own form: the tokens spell it
7671    return content, None
7672
7673
7674def _with_reasoning(lps: dict, entries: list) -> dict:
7675    out = {"content": entries}
7676    if lps.get("reasoning_content"):
7677        out["reasoning_content"] = lps["reasoning_content"]
7678    return out
7679
7680
7681def structured_chunks(chunks, validator):
7682    """Buffer structured streams so a client never receives unvalidated content."""
7683    buffered = []
7684    heartbeat = time.monotonic()
7685    try:
7686        for chunk in chunks:
7687            progress = chunk is not None and "prompt_progress" in chunk
7688            if chunk is not None and not progress:
7689                buffered.append(chunk)      # a progress chunk carries no content: there is nothing in it to validate
7690            if chunk is None or progress or time.monotonic() - heartbeat >= 1:
7691                heartbeat = time.monotonic()
7692                yield chunk if progress else None
7693        result = openai_collect(buffered)
7694        choice = result["choices"][0]
7695        content = validated_json(choice["message"]["content"], validator, choice["finish_reason"])
7696        # logprobs: the entries spell what the model wrote, which this function replaces with the
7697        # canonical JSON.  `_structured_logprobs` gives back the form the tokens spell, or None.
7698        content, logprobs = _structured_logprobs(choice, content)
7699        yield buffered[0]
7700        delta = {"content": content}
7701        if choice["message"].get("reasoning_content"):
7702            delta["reasoning_content"] = choice["message"]["reasoning_content"]
7703        piece = {"index": 0, "delta": delta, "finish_reason": None}
7704        if logprobs:
7705            piece["logprobs"] = logprobs
7706        yield {**buffered[0], "choices": [piece]}
7707        end = buffered[-1]
7708        if end["choices"][0].get("logprobs"):
7709            # those entries went out in the piece above (or were dropped with it): the closing
7710            # chunk must not carry a second copy
7711            end = {**end, "choices": [{k: v for k, v in end["choices"][0].items() if k != "logprobs"}]}
7712        yield end
7713    finally:
7714        chunks.close()
7715
7716
7717# ------------------------------------------------------------------------------------------------ Anthropic
7718def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, cancel, force=None, deferred=False):
7719    mid = "msg_" + uuid.uuid4().hex[:24]
7720    yield "message_start", {"type": "message_start", "message": {
7721        "id": mid, "type": "message", "role": "assistant", "model": svc.model_for(req), "content": [],
7722        "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": len(ids), "output_tokens": 0}}}
7723    index, open_kind, used_tool = -1, None, False
7724
7725    def close():
7726        return ("content_block_stop", {"type": "content_block_stop", "index": index})
7727
7728    streamed, finished = set(), set()              # calls sent piece by piece; those whose final tool_call came (#211)
7729    for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel, force=force, declared_only=True,
7730                           deferred=deferred):
7731        if kind == "ping":
7732            yield None
7733            continue
7734        if kind == "event":
7735            ev: Event = x
7736            if ev.kind == "tool_args":
7737                yield "content_block_delta", {"type": "content_block_delta", "index": index,
7738                                              "delta": {"type": "input_json_delta", "partial_json": ev.text}}
7739                continue
7740            if ev.kind == "tool_call" and ev.call.id in streamed:
7741                finished.add(ev.call.id)
7742                continue
7743            want = {"reasoning": "thinking", "content": "text", "tool_call": "tool_use", "tool_start": "tool_use"}[ev.kind]
7744            if ev.kind not in ("tool_call", "tool_start") and not ev.text:
7745                continue
7746            if ev.kind == "tool_start":
7747                streamed.add(ev.call.id)
7748                used_tool = True
7749            if open_kind != want or want == "tool_use":
7750                if open_kind is not None:
7751                    yield close()
7752                index += 1
7753                open_kind = want
7754                block = {"thinking": {"type": "thinking", "thinking": "", "signature": ""},
7755                         "text": {"type": "text", "text": ""},
7756                         "tool_use": {"type": "tool_use", "id": ev.call.id if ev.call else "", "name":
7757                                      ev.call.name if ev.call else "", "input": {}}}[want]
7758                yield "content_block_start", {"type": "content_block_start", "index": index, "content_block": block}
7759            if want == "thinking":
7760                yield "content_block_delta", {"type": "content_block_delta", "index": index,
7761                                              "delta": {"type": "thinking_delta", "thinking": ev.text}}
7762            elif want == "text":
7763                yield "content_block_delta", {"type": "content_block_delta", "index": index,
7764                                              "delta": {"type": "text_delta", "text": ev.text}}
7765            elif ev.kind == "tool_start":
7766                pass                                # its input follows as tool_args pieces
7767            else:
7768                used_tool = True
7769                yield "content_block_delta", {"type": "content_block_delta", "index": index, "delta": {
7770                    "type": "input_json_delta", "partial_json": json.dumps(ev.call.arguments, ensure_ascii=False)}}
7771        else:
7772            if open_kind is not None:
7773                yield close()
7774            stop = "stop_sequence" if x.get("stop_sequence") is not None else \
7775                "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \
7776                {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]]
7777            # the final counts (message_start could only say the whole prompt): what was read now stays for the next
7778            # request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013)
7779            reused = max(0, min(x.get("reused") or 0, len(ids) - 1))
7780            read_now = len(ids) - reused
7781            delta_event = {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": x.get("stop_sequence")},
7782                           "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1,
7783                                     "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}}
7784            if x.get("rejected_tool_calls"):
7785                delta_event["strata_rejected_tool_calls"] = x["rejected_tool_calls"]     # #3796
7786            yield "message_delta", delta_event
7787            yield "message_stop", {"type": "message_stop"}
7788
7789
7790def anthropic_collect(events) -> dict:
7791    msg, blocks = None, []
7792    for item in events:
7793        if item is None:                           # a heartbeat
7794            continue
7795        name, e = item
7796        if name == "message_start":
7797            msg = e["message"]
7798        elif name == "content_block_start":
7799            blocks.append(dict(e["content_block"]))
7800        elif name == "content_block_delta":
7801            d, b = e["delta"], blocks[-1]
7802            if d["type"] == "text_delta":
7803                b["text"] += d["text"]
7804            elif d["type"] == "thinking_delta":
7805                b["thinking"] += d["thinking"]
7806            else:                                  # input_json_delta pieces: parsed when complete
7807                b["_json"] = b.get("_json", "") + d["partial_json"]
7808        elif name == "content_block_stop" and blocks and "_json" in blocks[-1]:
7809            b = blocks[-1]
7810            try:
7811                b["input"] = json.loads(b.pop("_json") or "{}")
7812            except ValueError:                     # a call the output ended inside (#211): it has no input to give
7813                blocks.pop()
7814        elif name == "message_delta":
7815            msg["stop_reason"] = e["delta"]["stop_reason"]
7816            msg["stop_sequence"] = e["delta"].get("stop_sequence")
7817            msg["usage"].update(e["usage"])
7818            if e.get("strata_rejected_tool_calls"):
7819                msg["strata_rejected_tool_calls"] = e["strata_rejected_tool_calls"]
7820    for i in range(len(blocks) - 1):    # a turn with no </think> (serve/dsml.py): the text is the answer; it is not also a thinking block
7821        a, b = blocks[i], blocks[i + 1]
7822        if a.get("type") == "thinking" and b.get("type") == "text" and a.get("thinking", "").strip() == b.get("text", "").strip():
7823            del blocks[i]
7824            break
7825    msg["content"] = blocks
7826    return msg
7827
7828
7829# ------------------------------------------------------------------------------------------------ HTTP
7830CHUNKED_BODY_MAX = 256 << 20                # #893: the most a Transfer-Encoding: chunked body may hold (read into memory)
7831
7832
7833def body_limit() -> int:
7834    """The most a request body may hold, in bytes (read into memory): 256 MiB, which is a million-token conversation
7835    with room to spare; STRATA_MAX_BODY_MIB changes it (0 or an unreadable value: the default).  A larger one is
7836    answered 413 before it is read (a Content-Length of 10 TB used to be read until the client gave up)."""
7837    try:
7838        mib = int(os.environ.get("STRATA_MAX_BODY_MIB", "0"))
7839    except ValueError:
7840        mib = 0
7841    return mib << 20 if mib > 0 else CHUNKED_BODY_MAX
7842
7843
7844class BadBody(Exception):
7845    """A request body that cannot be read (a malformed or oversized chunked body): the status and the sentence."""
7846
7847    def __init__(self, status: int, message: str):
7848        super().__init__(message)
7849        self.status = status
7850
7851
7852def make_handler(svc: Service):
7853    class Handler(BaseHTTPRequestHandler):
7854        protocol_version = "HTTP/1.0"                       # SSE ends by closing the connection
7855
7856        record = None                                       # #332: this request's monitor record, if kept
7857        watch_done = None                                   # #430 #431: stops this request's disconnect watcher
7858        cancel_event = None                                 # active generation owned by this handler
7859        body_read = False                                   # whether a handler took this request's body
7860        DRAIN_SECONDS = 5                                   # the longest an unread body is read and dropped
7861
7862        def log_message(self, fmt, *args):
7863            pass
7864
7865        def handle_one_request(self):
7866            self.answer_started = False
7867            super().handle_one_request()
7868            self._drain_body()
7869
7870        def send_response(self, code, message=None):
7871            self.answer_started = True                 # a malformed-request answer can only replace one not yet begun
7872            super().send_response(code, message)
7873
7874        def _chunked(self) -> bool:
7875            """#893: a body sent as Transfer-Encoding: chunked (a relay or proxy that does not buffer it).  By RFC 9112
7876            it wins over a Content-Length."""
7877            te = self.headers.get("Transfer-Encoding", "") or ""
7878            return te.split(",")[-1].strip().lower() == "chunked"
7879
7880        def _read_chunked(self, limit: int, keep: bool = True, deadline: float | None = None) -> bytes:
7881            """Decode a chunked body: at most `limit` bytes (BadBody 413 beyond it - the size is checked before a chunk
7882            is read, so a huge announced chunk is never allocated), BadBody 400 for a malformed one.  keep=False reads
7883            and drops it (the drain); `deadline` (monotonic) ends the read early."""
7884            parts, total = [], 0
7885            while True:
7886                if deadline is not None:
7887                    wait = deadline - time.monotonic()
7888                    if wait <= 0:
7889                        return b"".join(parts)
7890                    self.connection.settimeout(wait)
7891                line = self.rfile.readline(1025)
7892                if not line.endswith(b"\n"):
7893                    raise BadBody(400, "malformed chunked request body")
7894                try:
7895                    size = int(line.split(b";", 1)[0].strip(), 16)
7896                except ValueError:
7897                    raise BadBody(400, "malformed chunk size in the request body") from None
7898                if size < 0:
7899                    raise BadBody(400, "malformed chunk size in the request body")
7900                if size == 0:
7901                    for _ in range(64):                       # the trailers, including the final blank line
7902                        trailer = self.rfile.readline(8193)
7903                        if trailer == b"\r\n":
7904                            return b"".join(parts)
7905                        if not trailer.endswith(b"\r\n"):
7906                            raise BadBody(400, "malformed or incomplete chunked request trailers")
7907                    raise BadBody(400, "too many chunked request trailers")
7908                total += size
7909                if total > limit:
7910                    self.close_connection = True
7911                    raise BadBody(413, f"the request body is larger than {limit >> 20} MiB")
7912                left = size
7913                while left > 0:
7914                    piece = self.rfile.read(min(left, 1 << 20))
7915                    if not piece:
7916                        raise BadBody(400, "the chunked request body ended early")
7917                    left -= len(piece)
7918                    if keep:
7919                        parts.append(piece)
7920                if self.rfile.read(2) != b"\r\n":
7921                    raise BadBody(400, "malformed chunked request body")
7922
7923        def _body(self) -> bytes:
7924            self.body_read = True
7925            limit = body_limit()
7926            if self._chunked():
7927                return self._read_chunked(limit)
7928            try:
7929                length = int(self.headers.get("Content-Length", 0))
7930            except ValueError:
7931                raise BadBody(400, "invalid Content-Length") from None
7932            if length < 0:
7933                raise BadBody(400, "invalid Content-Length")
7934            if length > limit:
7935                self.close_connection = True               # the body is not read: the connection ends with the answer
7936                raise BadBody(413, f"the request body is larger than {limit >> 20} MiB "
7937                                   "(STRATA_MAX_BODY_MIB raises the limit)")
7938            return self.rfile.read(length)
7939
7940        def _drain_body(self):
7941            """An answer sent before the body was read (a 401, a 403, /load, a method with no handler) must not close
7942            the connection on unread bytes: the close then sends a reset, and a client that sends its body after the
7943            headers (http.client, urllib, requests) gets a connection error instead of the answer.  So the body is
7944            read and dropped here, once, after an answer, in pieces so that its size is never held in memory.  What
7945            has not arrived DRAIN_SECONDS later is left unread: the limit is time, so that a conversation of many
7946            megabytes, at any speed the client has, still gets its answer."""
7947            headers = getattr(self, "headers", None)
7948            if self.body_read or headers is None:
7949                return
7950            if self._chunked():
7951                try:
7952                    self._read_chunked(body_limit(), keep=False, deadline=time.monotonic() + self.DRAIN_SECONDS)
7953                except (BadBody, OSError):
7954                    self.close_connection = True
7955                return
7956            try:
7957                left = int(headers.get("Content-Length", 0))
7958            except ValueError:
7959                return
7960            if left <= 0:
7961                return
7962            deadline = time.monotonic() + self.DRAIN_SECONDS
7963            try:
7964                while left > 0 and (wait := deadline - time.monotonic()) > 0:
7965                    self.connection.settimeout(wait)         # a client that never sends what it announced
7966                    piece = self.rfile.read1(min(left, 1 << 20))   # one socket read: read() would wait for it all
7967                    if not piece:
7968                        break
7969                    left -= len(piece)
7970            except OSError:
7971                pass
7972
7973        def parse_request(self):
7974            """Without an API key, every request (any method) first passes the Host check: DNS rebinding protection
7975            (host_allowed).  With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and
7976            proxies that pass their own name on keep working."""
7977            if not super().parse_request():
7978                return False
7979            host = self.headers.get("Host")
7980            if svc.api_key or host_allowed(host, svc.host_names, "*" in svc.allowed_hosts):
7981                return True
7982            print(f"[strata] refused a request for Host {host!r} from {self.client_address[0]}: not a name this server "
7983                  f"answers to (add it to \"allowed_hosts\" in the config or STRATA_ALLOWED_HOSTS, or set an API key)",
7984                  flush=True)
7985            self._json(403, {"error": {"type": "forbidden", "message":
7986                             f"Host {host!r} is not allowed (DNS rebinding protection). Reaching Strata under this "
7987                             f"name on purpose? Add it to \"allowed_hosts\" in the config (strata-<model>.json) or to "
7988                             f"the STRATA_ALLOWED_HOSTS environment variable, or set an API key (\"api_key\"), which "
7989                             f"turns this check off"}})
7990            return False
7991
7992        def _foreign_page(self) -> bool:
7993            """Without an API key, a /v1 POST from a browser page of another site (any site can POST text/plain
7994            there without a CORS preflight) would burn GPU time: an Origin header must name an allowed page, and
7995            then the body must be JSON.  No Origin (curl, the SDKs, other servers): any content type, as before."""
7996            origin = self.headers.get("Origin")
7997            if svc.api_key or not origin:
7998                return False
7999            if not origin_allowed(origin, self.headers.get("Host"), svc.host_names,
8000                                  [*svc.trusted_origins, *svc.cors_origins]):
8001                print(f"[strata] refused an API request from the web page {origin!r} (no API key; add its host to "
8002                      f"\"allowed_hosts\" or its origin to \"cors_origins\" in the config)", flush=True)
8003                self._json(403, {"error": {"type": "forbidden", "message":
8004                                 f"web pages of {origin} may not use this server without an API key; set \"api_key\", "
8005                                 f"or add the page's host to \"allowed_hosts\" (or its origin to \"cors_origins\") "
8006                                 f"in the config"}})
8007                return True
8008            if not self.headers.get("Content-Type", "").startswith("application/json"):
8009                self._json(415, {"error": {"message": "send application/json"}})
8010                return True
8011            return False
8012
8013        def end_headers(self):
8014            # HTTP/1.0 without keep-alive: the server closes the connection after every response.  Say so, or a
8015            # client that pools connections (.NET's SocketsHttpHandler) can put its next request on this socket
8016            # before the close reaches it, and that request fails with "response ended prematurely" without the
8017            # server ever reading it (a .NET agent app, 2026-10-03: 25 of ~1000 requests, 1-24 ms after the previous answer).
8018            self.send_header("Connection", "close")
8019            super().end_headers()
8020
8021        def _watch_client(self, cancel: threading.Event) -> None:
8022            """#430 #431: cancel the request as soon as its client hangs up.  A non-streamed request writes nothing
8023            until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up
8024            usually still succeeds), so a dropped request kept the engine busy until its answer or the whole prompt
8025            was done.  Every 0.5 s: the socket readable with nothing to read (EOF) means the client closed it.  A
8026            request is HTTP/1.0 and fully read here, so no later bytes are expected - data is not a hang-up."""
8027            done = self.watch_done = threading.Event()
8028            self.cancel_event = cancel
8029            with svc.status_lock:
8030                svc.active_cancels.add(cancel)
8031            sock = self.connection
8032
8033            def watch():
8034                while not done.wait(0.5) and not cancel.is_set():
8035                    try:
8036                        readable, _, _ = select.select([sock], [], [], 0)
8037                        gone = bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
8038                    except (ConnectionError, TimeoutError):
8039                        gone = True
8040                    except (OSError, ValueError):            # the socket was closed here: the request has ended
8041                        return
8042                    if gone and not done.is_set():
8043                        self._note(outcome="disconnected")
8044                        svc.note_client_disconnect(cancel)
8045                        return
8046
8047            threading.Thread(target=watch, daemon=True, name="strata-client-watch").start()
8048
8049        def _note(self, **values):
8050            """#332: what the monitor shows about this request (nothing when the monitor is off)."""
8051            if self.record is not None:
8052                with svc.status_lock:
8053                    self.record.update(values)
8054
8055        def _cors(self):
8056            """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing
8057            otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools."""
8058            if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"):
8059                return
8060            origin = (self.headers.get("Origin") or "").rstrip("/")
8061            if "*" in svc.cors_origins:
8062                allow = "*"
8063            elif origin and origin in svc.cors_origins:
8064                allow = origin
8065                self.send_header("Vary", "Origin")
8066            else:
8067                return
8068            self.send_header("Access-Control-Allow-Origin", allow)
8069            self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
8070            # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization)
8071            asked = self.headers.get("Access-Control-Request-Headers")
8072            self.send_header("Access-Control-Allow-Headers",
8073                             asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta")
8074            self.send_header("Access-Control-Max-Age", "600")
8075
8076        def do_OPTIONS(self):
8077            # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins
8078            self.send_response(204)
8079            self._cors()
8080            self.send_header("Content-Length", "0")
8081            self.end_headers()
8082
8083        def _json(self, code, obj, headers=None, retry_after=None):
8084            if self.record is not None:
8085                with svc.status_lock:
8086                    self.record["http_status"] = code
8087                    raw = json.dumps(obj, ensure_ascii=False, indent=2)
8088                    self.record.update(response=raw[:262144], response_truncated=len(raw) > 262144)
8089                    for key in ("error", "usage", "timings"):
8090                        if key in obj:
8091                            self.record[key] = obj[key]
8092            body = json.dumps(obj, ensure_ascii=False).encode()
8093            self.send_response(code)
8094            self.send_header("Content-Type", "application/json")
8095            for k, v in (headers or {}).items():
8096                self.send_header(k, str(v))
8097            if retry_after is not None:
8098                self.send_header("Retry-After", str(retry_after))
8099            self._cors()
8100            self.send_header("Content-Length", str(len(body)))
8101            self.end_headers()
8102            self.wfile.write(body)
8103
8104        def _authorized(self) -> bool:
8105            if not svc.api_key:
8106                return True
8107            auth = self.headers.get("Authorization", "")
8108            given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")
8109            if key_matches(given, svc.api_key):
8110                return True
8111            self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}})
8112            return False
8113
8114        def _authorized_telemetry(self) -> bool:
8115            if not svc.api_key and not svc.telemetry_key:
8116                return True
8117            auth = self.headers.get("Authorization", "")
8118            given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")
8119            if (svc.api_key and key_matches(given, svc.api_key)) or \
8120                    (svc.telemetry_key and key_matches(given, svc.telemetry_key)):
8121                return True
8122            self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong telemetry key"}})
8123            return False
8124
8125        def do_GET(self):
8126            path = self.path.split("?")[0].rstrip("/")
8127            if path.startswith("/tool-media/"):
8128                if not self._authorized():
8129                    return
8130                name = path[len("/tool-media/"):]
8131                hub = svc.mcp
8132                if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name) or not hub or not hub.media_dir:
8133                    self._json(404, {"error": {"message": "not found"}})
8134                    return
8135                file = Path(hub.media_dir) / name
8136                if not file.is_file():
8137                    self._json(404, {"error": {"message": "not found"}})
8138                    return
8139                body = file.read_bytes()
8140                self.send_response(200)
8141                self.send_header("Content-Type", {".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp"}[file.suffix])
8142                self.send_header("Content-Length", str(len(body)))
8143                self.send_header("X-Content-Type-Options", "nosniff")
8144                self.send_header("Cache-Control", "private, max-age=86400")
8145                self.send_header("Cross-Origin-Resource-Policy", "same-origin")
8146                self.end_headers()
8147                self.wfile.write(body)
8148                return
8149            if path.startswith("/fonts/"):
8150                # the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font
8151                name = path[len("/fonts/"):]
8152                f = ROOT / "serve" / "web" / "fonts" / name
8153                if "/" in name or "\\" in name or not name.endswith(".woff2") or not f.is_file():
8154                    self._json(404, {"error": {"message": "not found"}})
8155                    return
8156                body = f.read_bytes()
8157                self.send_response(200)
8158                self.send_header("Content-Type", "font/woff2")
8159                self.send_header("Cache-Control", "max-age=86400")
8160                self.send_header("Content-Length", str(len(body)))
8161                self.end_headers()
8162                self.wfile.write(body)
8163                return
8164            sub = web_subtree_file(path)
8165            if path.startswith(("/web/locales/", "/web/vendor/")):
8166                # the page's translations (serve/web/locales/<lang>.json) and the vendored KaTeX (serve/web/vendor):
8167                # only whitelisted names and types, never a path out of those folders
8168                if sub is None:
8169                    self._json(404, {"error": {"message": "not found"}})
8170                    return
8171                body = sub[0].read_bytes()
8172                self.send_response(200)
8173                self.send_header("Content-Type", sub[1])
8174                self.send_header("Cache-Control", "no-cache")
8175                self.send_header("Content-Length", str(len(body)))
8176                self.end_headers()
8177                self.wfile.write(body)
8178                return
8179            if path.startswith("/web/"):
8180                # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN
8181                name = path[len("/web/"):]
8182                types = {".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8",
8183                         ".svg": "image/svg+xml"}
8184                f = ROOT / "serve" / "web" / name
8185                ext = os.path.splitext(name)[1]
8186                if "/" in name or "\\" in name or ext not in types or not f.is_file():
8187                    self._json(404, {"error": {"message": "not found"}})
8188                    return
8189                body = f.read_bytes()
8190                self.send_response(200)
8191                self.send_header("Content-Type", types[ext])
8192                self.send_header("Cache-Control", "no-cache")
8193                self.send_header("Content-Length", str(len(body)))
8194                self.end_headers()
8195                self.wfile.write(body)
8196                return
8197            if path == "/metrics/prometheus":
8198                if self._authorized():
8199                    body = svc.prometheus().encode()
8200                    self.send_response(200)
8201                    self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
8202                    self.send_header("Content-Length", str(len(body)))
8203                    self.end_headers()
8204                    self.wfile.write(body)
8205                return
8206            if path == "/metrics":
8207                from serve import prometheus
8208                if prometheus.wants_prometheus(self.headers.get("Accept", ""), urlsplit(self.path).query):
8209                    if self._authorized():   # a scraper: the text format, vLLM's names (serve/prometheus.py)
8210                        body = prometheus.render(svc.metrics(), svc.latencies.snapshot()).encode()
8211                        self.send_response(200)
8212                        self.send_header("Content-Type", prometheus.CONTENT_TYPE)
8213                        self.send_header("Content-Length", str(len(body)))
8214                        self.end_headers()
8215                        self.wfile.write(body)
8216                    return
8217                if self._authorized():
8218                    # the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35)
8219                    self._json(200, svc.metrics(all_requests="requests=all" in self.path))
8220                return
8221            if path == "/v1/telemetry":
8222                if self._authorized_telemetry():
8223                    from strata_cli.client import normalize_legacy
8224                    snapshot = normalize_legacy(svc.metrics(), svc.v1_status())
8225                    snapshot["source"] = "server-v1"
8226                    snapshot["work"]["slots_requested"] = getattr(svc, "requested_slots", None)
8227                    # Keep /metrics' established slot shape intact; enrich only this versioned contract.
8228                    replica_engines = (getattr(svc.engine, "engines", None)
8229                                       if hasattr(svc.engine, "replica_view") else None)
8230                    if replica_engines:
8231                        groups, live_slots, replica_by_slot = [], [], []
8232                        group_base = 0
8233                        all_batched = True
8234                        for replica, child in enumerate(replica_engines):
8235                            count = int(getattr(child, "batch", 0) or 0)
8236                            all_batched = all_batched and count > 0
8237                            count = max(1, count)
8238                            child_groups = getattr(child, "slot_group", [])
8239                            child_live = getattr(child, "slot_live", [])
8240                            for local in range(count):
8241                                group = child_groups[local] if local < len(child_groups) else None
8242                                groups.append(group_base + group if type(group) is int and group >= 0 else None)
8243                                live_slots.append(child_live[local] if local < len(child_live) else None)
8244                                replica_by_slot.append(replica)
8245                            group_base += int(getattr(child, "slot_groups", 0) or 0)
8246                        snapshot["work"]["groups"] = group_base if all_batched and group_base > 0 else None
8247                    else:
8248                        groups = getattr(svc.engine, "slot_group", [])
8249                        live_slots = getattr(svc.engine, "slot_live", [])
8250                        replica_by_slot = []
8251                    for slot in snapshot["work"]["slots"]:
8252                        i = slot.get("slot")
8253                        if type(i) is int and 0 <= i < len(groups):
8254                            slot["group"] = groups[i]
8255                        if type(i) is int and 0 <= i < len(replica_by_slot):
8256                            slot["replica"] = replica_by_slot[i]
8257                        if type(i) is int and 0 <= i < len(live_slots) and live_slots[i]:
8258                            slot["request_id"] = live_slots[i].get("request_id")
8259                    slot_by_id = {slot.get("request_id"): slot for slot in snapshot["work"]["slots"]
8260                                  if slot.get("request_id")}
8261                    with svc.status_lock:
8262                        active = list(svc.terminal_requests.values())
8263                        snapshot["activity"] = {"last_seq": svc.terminal_event_seq,
8264                                                "events": list(svc.terminal_events)[-32:]}
8265                        draining = svc.draining
8266                        admission_reserved = svc.admission_reserved
8267                        admission_rejected = svc.admission_rejected
8268                        queue_timeouts = svc.queue_timeouts
8269                        client_disconnect_cancels = svc.client_disconnect_cancels
8270                        in_flight_tokens = (sum(max(0, int(st.get("generated") or 0))
8271                                                for st, _ in svc.live_reqs.values())
8272                                            if svc.live_reqs else
8273                                            max(0, int(svc.status.get("generated") or 0))
8274                                            if svc.status.get("busy") else 0)
8275                        output_counter = int(svc.totals.get("output_tokens") or 0) + in_flight_tokens
8276                    snapshot["instance"]["id"] = svc.instance_id
8277                    snapshot["instance"]["state"] = "draining" if draining else "ready"
8278                    if getattr(svc, "launch_attestation", None) is not None:
8279                        snapshot["instance"]["launch_attestation"] = svc.launch_attestation
8280                    snapshot["rates"]["output_tokens_server_counter"] = output_counter
8281                    snapshot["work"]["requests_omitted"] = max(0, len(active) - 50)
8282                    snapshot["work"].update(max_queue=svc.max_queue, queue_timeout_s=svc.queue_timeout_s,
8283                                            queue_timeouts=queue_timeouts,
8284                                            client_disconnect_cancels=client_disconnect_cancels,
8285                                            admission_limit=svc.admission_limit(),
8286                                            admission_reserved=admission_reserved,
8287                                            admission_rejected=admission_rejected,
8288                                            oldest_queue_s=max((max(0, time.time() - row["queued_at"])
8289                                                                for row in active if row["state"] in ("queued", "waiting")),
8290                                                               default=0))
8291                    snapshot["work"]["requests"] = [
8292                        {**row, "state": slot_by_id[row["id"]]["state"] if row["id"] in slot_by_id else row["state"],
8293                         "slot": slot_by_id[row["id"]]["slot"] if row["id"] in slot_by_id else None,
8294                         "group": slot_by_id[row["id"]]["group"] if row["id"] in slot_by_id else None,
8295                         "replica": slot_by_id[row["id"]]["replica"] if row["id"] in slot_by_id else row.get("replica"),
8296                         "generated": slot_by_id[row["id"]].get("generated") if row["id"] in slot_by_id else None,
8297                         "prompt_read": slot_by_id[row["id"]].get("prompt_read") if row["id"] in slot_by_id else None}
8298                        for row in active[:50]]
8299                    snapshot["quality"]["request_correlation"] = "reported"
8300                    batch_sample = (getattr(svc.engine, "terminal_batch_sample", None)
8301                                    if svc.loaded() and not replica_engines else None)
8302                    if replica_engines:
8303                        replica_batches = []
8304                        for replica, child in enumerate(replica_engines[:16]):
8305                            row = {"replica": replica}
8306                            sample = (getattr(child, "terminal_batch_sample", None)
8307                                      if child.alive() else None)
8308                            if sample:
8309                                row.update(batch_sample_windows=sample["windows"],
8310                                           batch_sample_rows=sample["processed_rows"],
8311                                           batch_sample_active_rows=sample["active_rows"],
8312                                           batch_sample_span_s=sample["elapsed_ms"] / 1000.0,
8313                                           batch_sample_age_s=max(0.0, time.monotonic() -
8314                                                                  sample["observed_monotonic"]))
8315                            replica_batches.append(row)
8316                        snapshot["work"]["replica_batches"] = replica_batches
8317                    if batch_sample:
8318                        windows = batch_sample["windows"]
8319                        snapshot["work"].update(effective_rows_window=batch_sample["processed_rows"] / windows,
8320                                                batch_active_rows_window=batch_sample["active_rows"] / windows,
8321                                                batch_sample_windows=windows,
8322                                                batch_sample_rows=batch_sample["processed_rows"],
8323                                                batch_sample_active_rows=batch_sample["active_rows"],
8324                                                batch_sample_span_s=batch_sample["elapsed_ms"] / 1000.0,
8325                                                batch_sample_age_s=max(0.0, time.monotonic() -
8326                                                                       batch_sample["observed_monotonic"]))
8327                        snapshot["quality"]["batch_window_rows"] = "measured"
8328                        snapshot["quality"]["batch_window_source"] = "engine_bstat"
8329                    stage_sample = (getattr(svc.engine, "terminal_stage_sample", None)
8330                                    if svc.loaded() and not replica_engines else None)
8331                    if replica_engines:
8332                        replica_stage_samples = []
8333                        for replica, child in enumerate(replica_engines[:16]):
8334                            row = {"replica": replica}
8335                            sample = (getattr(child, "terminal_stage_sample", None)
8336                                      if child.alive() else None)
8337                            if sample:
8338                                row.update(stage_sample_elapsed_us=sample["elapsed_us"],
8339                                           stage_in_flight_us=sample["in_flight_us"],
8340                                           stage_sample_age_s=max(0.0, time.monotonic() -
8341                                                                  sample["observed_monotonic"]))
8342                            replica_stage_samples.append(row)
8343                        snapshot["work"]["replica_stage_samples"] = replica_stage_samples
8344                    if stage_sample:
8345                        snapshot["work"].update(stage_sample_elapsed_us=stage_sample["elapsed_us"],
8346                                                stage_in_flight_us=stage_sample["in_flight_us"],
8347                                                stage_sample_age_s=max(0.0, time.monotonic() -
8348                                                                       stage_sample["observed_monotonic"]))
8349                        snapshot["quality"]["stage_in_flight_source"] = "engine_pstat_host_span"
8350                    indices = list(getattr(svc, "gpu_indices", []) or [])
8351                    visibility = list(getattr(svc, "terminal_visibility_order", []) or [])
8352                    reported = (list(getattr(svc.engine, "terminal_stages", []) or [])
8353                                if svc.loaded() and not replica_engines else [])
8354                    stages = [{**stage, "device_index":
8355                               visibility[stage["engine_ordinal"]]
8356                               if stage["engine_ordinal"] < len(visibility) else None}
8357                              for stage in reported]
8358                    snapshot["topology"]["selected_devices"] = indices if replica_engines else visibility or indices
8359                    replica_devices = getattr(svc, "replica_gpu_groups", []) if replica_engines else []
8360                    snapshot["topology"]["replica_devices"] = [
8361                        {"replica": i, "devices": list(devices)}
8362                        for i, devices in enumerate(replica_devices[:16])]
8363                    replica_stages = []
8364                    for replica, child in enumerate((replica_engines or [])[:16]):
8365                        child_reported = (list(getattr(child, "terminal_stages", []) or [])
8366                                          if child.alive() else [])
8367                        spawn = getattr(child, "spawn", None)
8368                        child_env = spawn[4] if isinstance(spawn, tuple) and len(spawn) > 4 else None
8369                        child_visibility = visible_device_order(child_env, getattr(svc, "backend", None))
8370                        configured_cards = (set(replica_devices[replica])
8371                                            if replica < len(replica_devices) else set())
8372                        child_stages = []
8373                        for stage in child_reported:
8374                            ordinal = stage["engine_ordinal"]
8375                            card = (child_visibility[ordinal]
8376                                    if type(ordinal) is int and 0 <= ordinal < len(child_visibility) else None)
8377                            child_stages.append({**stage, "device_index": card if card in configured_cards else None})
8378                        replica_stages.append({"replica": replica, "stages": child_stages})
8379                    snapshot["topology"]["replica_stages"] = replica_stages
8380                    snapshot["topology"]["mode"] = ("layer split (engine reported)" if stages else
8381                                                     getattr(svc, "terminal_topology_mode", None))
8382                    snapshot["topology"]["configured_split"] = getattr(svc, "terminal_configured_split", None)
8383                    snapshot["topology"]["stages"] = stages
8384                    snapshot["topology"]["resolved"] = bool(stages) and all(
8385                        stage["device_index"] is not None for stage in stages)
8386                    snapshot["topology"]["source"] = "engine_start_log" if stages else None
8387                    snapshot["quality"]["placement"] = ("reported" if snapshot["topology"]["resolved"] else
8388                                                         "partial" if stages else "unavailable")
8389                    present = {d.get("index") for d in snapshot["devices"]}
8390                    for index in indices:
8391                        if index not in present:
8392                            snapshot["devices"].append({"index": index, "name": None, "mem_used": None,
8393                                                        "mem_total": None, "util": None, "temp": None, "power": None})
8394                    self._json(200, snapshot)
8395                return
8396            if path == "/api/requests" and svc.api_monitor:
8397                if self._authorized():
8398                    request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0]
8399                    records = svc.request_records(request_id)
8400                    self._json(404 if records is None else 200,
8401                               {"error": {"message": "request no longer retained"}} if records is None else
8402                               records if request_id else {"requests": records, "retention": 100, "persistent": False,
8403                                                          "loaded": svc.loaded(), "auto_load": hasattr(svc.engine, "restart")})
8404                return
8405            if path == "/settings":
8406                if self._authorized():
8407                    self._json(200, {"shared": bool(svc.shared), "defaults": svc.shared})
8408                return
8409            if path == "/config":                            # #564: the Settings view's keys of the run config
8410                if self._authorized():
8411                    self._config_get()
8412                return
8413            if path == "/mcp":
8414                # the MCP servers, their state and tools (the web app's switch and Monitor card)
8415                if self._authorized():
8416                    self._json(200, svc.mcp.status() if svc.mcp else {"servers": [], "tools": 0})
8417                return
8418            if path == "" or (path == "/api-monitor" and svc.api_monitor):
8419                body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes()
8420                self.send_response(200)
8421                self.send_header("Content-Type", "text/html; charset=utf-8")
8422                if not path:
8423                    # the chat's svg/html preview is a sandboxed frame; this keeps it from navigating away to a web page
8424                    # (a link or <meta refresh> inside a model's html), which no sandbox flag does (serve/web/preview.js)
8425                    self.send_header("Content-Security-Policy", PAGE_CSP)
8426                self.send_header("Content-Length", str(len(body)))
8427                self.end_headers()
8428                self.wfile.write(body)
8429            elif path in ("/health", "/api/health"):
8430                self._json(200, {"status": "ok", "max_context": svc.reported_ctx(), "model": svc.model,
8431                                 "images": svc.vision is not None, "api_key": bool(svc.api_key),
8432                                 "image_generation": svc.images is not None,
8433                                 "loaded": svc.loaded(), "service": "strata"})
8434            elif path.startswith("/v1/images/files/"):
8435                # response_format url: the name (32 random hex digits) is the access, as an OpenAI image URL is
8436                f = svc.images.file(path[len("/v1/images/files/"):]) if svc.images is not None else None
8437                if f is None:
8438                    self._json(404, {"error": {"message": "not found (the server keeps the newest images only)"}})
8439                    return
8440                body = f.read_bytes()
8441                self.send_response(200)
8442                self.send_header("Content-Type", "image/png")
8443                self.send_header("Cache-Control", "private, max-age=86400")
8444                self.send_header("Content-Length", str(len(body)))
8445                self.end_headers()
8446                self.wfile.write(body)
8447            elif path == "/status":
8448                if not self._authorized():                  # #212: it shows the end of the last answer
8449                    return
8450                with svc.status_lock:
8451                    s = dict(svc.status)
8452                now = time.time()
8453                if s.get("busy"):
8454                    s["elapsed_s"] = round(now - s["started"], 1)
8455                    if s.get("first_token"):
8456                        s["tokens_per_s"] = round(svc._tok_s(), 1)
8457                        s["tokens_per_s_mean"] = round(svc._tok_s_mean(), 1)
8458                for k in ("started", "first_token"):
8459                    s.pop(k, None)
8460                self._json(200, s)
8461            elif path in ("/v1/models", "/models"):
8462                if self._authorized():
8463                    loaded = svc.loaded()
8464                    model = {"id": svc.model, "object": "model", "status": {"value": "loaded"},
8465                             "meta": {"n_ctx": svc.reported_ctx()},
8466                             "architecture": {"input_modalities": ["text", "image"] if svc.vision is not None else ["text"],
8467                                              "output_modalities": ["text"]}}
8468                    if not loaded and (svc.idle_unload_s or getattr(svc.engine, "unloaded", False)):
8469                        model["status"] = {"value": "unloaded"}   # like llama-server's router: listed, loads on use
8470                        loaded = True
8471                    if svc.aliases:                       # #297: the aliases, and each one listed under its own id
8472                        model["aliases"] = list(svc.aliases)
8473                    data = [model, *({**model, "id": x, "alias_of": svc.model} for x in svc.aliases)]
8474                    data = data if loaded else []
8475                    if svc.images is not None:            # the image model: POST /v1/images/generations
8476                        data.append({"id": svc.images.model, "object": "model", "status": {"value": "loaded"},
8477                                     "architecture": {"input_modalities": ["text"], "output_modalities": ["image"]}})
8478                    self._json(200, {"object": "list", "data": data})
8479            elif path == "/props":
8480                if self._authorized():
8481                    self._props()
8482            elif path == "/slots":
8483                if self._authorized():
8484                    loaded = not hasattr(svc.engine, "alive") or svc.engine.alive()
8485                    with svc.status_lock:
8486                        busy = bool(svc.status.get("busy"))
8487                        # llama.cpp's name for what the slot's context holds: the running request's prompt size,
8488                        # kept after it ends (the conversation cache carries it on).  A front-end's context meter
8489                        # divides it by n_ctx; without the key it reads 0 % against Strata forever (#562).
8490                        in_use = int(svc.status.get("prompt_tokens") or 0)
8491                    if getattr(svc.engine, "batch", 0) and hasattr(svc.engine, "slots_view"):
8492                        # --batch: one entry per slot (the same view /metrics has), not one for the whole engine
8493                        n_ctx = svc.reported_ctx()
8494                        slots = [{"id": s["slot"], "n_ctx": n_ctx, "is_processing": s["state"] != "idle",
8495                                  "n_prompt_tokens": int(s.get("prompt_tokens") or s.get("held_tokens") or 0)}
8496                                 for s in svc.engine.slots_view()]
8497                    else:
8498                        slots = [{"id": 0, "n_ctx": svc.reported_ctx(), "is_processing": busy,
8499                                  "n_prompt_tokens": in_use}]
8500                    self._json(200, slots if loaded else [])
8501            elif path == "/v1/status":
8502                if self._authorized():
8503                    self._json(200, svc.v1_status())
8504            else:
8505                self._json(404, {"error": {"message": "not found"}})
8506
8507        def do_POST(self):
8508            try:
8509                self._post()
8510            except BadBody as e:                              # #893: a malformed or oversized chunked body
8511                self._json(e.status, {"error": {"type": "invalid_request_error", "message": str(e)}})
8512
8513        def _post(self):
8514            if not self._authorized():
8515                return
8516            path = self.path.split("?")[0].rstrip("/")   # issue #55: Claude Code posts /v1/messages?beta=true
8517            path = V1_V1_ALIASES.get(path, path)         # an Anthropic client given ".../v1" as its base posts /v1/v1/messages
8518            if path.startswith("/v1/") and self._foreign_page():
8519                return
8520            if path == "/settings":
8521                self._settings()
8522                return
8523            if path == "/config":
8524                self._config_post()
8525                return
8526            if path in ("/unload", "/load") and not self._control_body():
8527                return
8528            # JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model
8529            if path in ("/unload", "/load") and not self._own_page("the model can be loaded or unloaded"):
8530                return
8531            # the same for the slot files: else any site could overwrite a saved conversation or replace the live one
8532            if path.startswith("/slots/") and not self._own_page("conversations can be saved or restored"):
8533                return
8534            if path == "/unload":                            # give the GPU back now (between requests)
8535                try:
8536                    wait_s = unload_wait(parse_qs(urlsplit(self.path).query).get("wait", [None])[0],
8537                                         svc.UNLOAD_WAIT_S)
8538                    r = svc.unload_waiting(wait_s) if wait_s else svc.unload()
8539                except EngineStuck as e:
8540                    self._json(503, {"error": {"type": "server_error", "message": str(e)}})
8541                    return
8542                self._json(409 if r == "busy" else 200, {"status": r})
8543                return
8544            if path == "/load":                              # load now, e.g. ahead of a request
8545                try:
8546                    svc.load()
8547                    self._json(200, {"status": "loaded"})
8548                except GpuBusy as e:
8549                    ra = getattr(e, "retry_after", None)
8550                    self._json(503, {"error": {"type": "server_error", "message": str(e)}},
8551                               headers={"Retry-After": int(ra)} if ra else None)
8552                return
8553            reserved = False
8554            try:
8555                if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"):
8556                    reserved = svc.reserve_inference()
8557                    if reserved is None:
8558                        error = {"type": "server_error", "code": "server_draining",
8559                                 "message": "this instance is draining; retry against the next instance"}
8560                        body = responses_error_body(error["message"], "server_error", code=error["code"]) \
8561                            if path == "/v1/responses" else {"error": error}
8562                        self._json(503, body, retry_after=1)
8563                        return
8564                    if not reserved:
8565                        error = {"type": "rate_limit_error", "code": "admission_full",
8566                                 "message": "the inference admission limit is full; retry later"}
8567                        body = responses_error_body(error["message"], "server_error", code=error["code"]) \
8568                            if path == "/v1/responses" else {"error": error}
8569                        self._json(429, body, retry_after=1)
8570                        return
8571                req = json.loads(self._body() or b"{}")
8572                if not isinstance(req, dict):
8573                    raise ValueError("send a JSON object")
8574                if path.startswith("/v1/responses/"):        # retrieve/delete/cancel/compact: nothing is stored
8575                    self._json(404, responses_error_body("this server keeps no responses (stateless); send the "
8576                                                         "whole conversation to POST /v1/responses", code="not_found"))
8577                    return
8578                if path in ("/v1/load", "/v1/unload"):
8579                    if not self._own_page("the model can be loaded or unloaded"):
8580                        return
8581                    if req.get("model") not in (None, svc.model):
8582                        self._json(404, {"error": {"message": "model not found"}})
8583                        return
8584                    if path == "/v1/unload":
8585                        wait_s = unload_wait(parse_qs(urlsplit(self.path).query).get("wait", [None])[0],
8586                                             svc.UNLOAD_WAIT_S)
8587                        result = svc.unload_waiting(wait_s) if wait_s else svc.unload()
8588                        if result == "busy":
8589                            raise ModelBusy("a request is running or queued")
8590                    else:
8591                        if not svc.fifo.acquire(blocking=False):
8592                            raise ModelBusy("a request is running or queued")
8593                        try:
8594                            with svc.status_lock:
8595                                if svc.status.get("busy") or svc.status.get("queued"):
8596                                    raise ModelBusy("a request is running or queued")
8597                            svc.ensure_loaded()
8598                            svc.last_request_at = time.time()
8599                        finally:
8600                            svc.fifo.release()
8601                        result = "loaded"
8602                    self._json(200, {"status": result, **svc.v1_status()})
8603                    return
8604                if path == "/v1/vram":                       # #533: give VRAM back to other programs, or take it
8605                    if not self._own_page("the VRAM reserve can be changed"):
8606                        return
8607                    r = req.get("reserve_mib")
8608                    if r is not None and (isinstance(r, bool) or not isinstance(r, int) or r < 0):
8609                        raise ValueError("reserve_mib: a whole number of MiB (0 or more), or null for the start's")
8610                    try:
8611                        self._json(200, svc.vram(r))
8612                    except EngineDied as e:
8613                        self._json(503, {"error": {"type": "server_error", "message": str(e)}})
8614                    return
8615                if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"):
8616                    self.record = svc.begin_request(path, req)
8617                if path == "/v1/responses":
8618                    self._responses(req)
8619                elif path.startswith("/slots/"):
8620                    query = parse_qs(self.path.partition("?")[2])
8621                    try:
8622                        code, body = svc.slot_action(path[len("/slots/"):], (query.get("action") or [""])[0],
8623                                                     req.get("filename"))
8624                    except EngineDied as e:                  # EngineSilent included: the engine was ended
8625                        code, body = 500, {"error": {"code": 500, "message": str(e) + "; the next request starts "
8626                                                     "the engine again", "type": "server_error"}}
8627                    self._json(code, body)
8628                elif path == "/v1/chat/completions":
8629                    self._openai(req)
8630                elif path == "/v1/messages":
8631                    self._anthropic(req)
8632                elif path == "/v1/messages/count_tokens":
8633                    self._count_tokens(req)
8634                elif path == "/v1/images/generations":
8635                    self._images(req)
8636                else:
8637                    self._json(404, {"error": {"message": "not found"}})
8638            except EngineNonFinite as e:                    # #879, twice: not the request's fault
8639                print(f"[strata] 503: {e}", flush=True)
8640                self._json(503, responses_error_body(str(e), "server_error") if path == "/v1/responses"
8641                           else {"error": {"type": "server_error", "message": str(e)}})
8642            except ValueError as e:
8643                print(f"[strata] 400 invalid request: {e}", flush=True)
8644                if path == "/v1/responses":
8645                    self._json(400, responses_error_body(str(e)))
8646                else:
8647                    self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})
8648            except ModelBusy as e:
8649                self._json(409, {"error": {"type": "model_busy", "message": str(e)}})
8650            except QueueWaitExpired as e:
8651                error = {"type": "rate_limit_error", "code": "queue_wait_timeout", "message": str(e)}
8652                self._note(error=error)
8653                body = responses_error_body(str(e), "server_error", code="queue_wait_timeout") \
8654                    if path == "/v1/responses" else {"error": error}
8655                self._json(429, body, retry_after=1)
8656            except StructuredOutputError as e:
8657                self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed",
8658                                          "message": str(e)}})
8659            except (GpuBusy, EngineStarting) as e:
8660                ra = getattr(e, "retry_after", None)       # #1997 / #1994: a refusal that is worth retrying
8661                self._json(503, {"error": {"type": "server_error", "message": str(e)}},
8662                           headers={"Retry-After": int(ra)} if ra else None)
8663            except (TypeError, KeyError, AttributeError, IndexError, UnicodeError) as e:
8664                # a body that is JSON but the wrong shape ("messages": 5, a content part that is a number): a 400 that
8665                # says so, with the traceback in the log, instead of a dropped connection - unless the answer began
8666                if getattr(self, "answer_started", False):
8667                    raise
8668                import traceback
8669                print(f"[strata] 400 malformed request ({type(e).__name__}: {e}):\n" + traceback.format_exc(),
8670                      flush=True)
8671                body = {"error": {"type": "invalid_request_error",
8672                                  "message": f"the request is malformed ({type(e).__name__}: {e})"}}
8673                self._json(400, responses_error_body(body["error"]["message"]) if path == "/v1/responses" else body)
8674            except EngineDied as e:                          # before the answer started (not streamed)
8675                self._json(503, {"error": {"type": "server_error", "message": died_note(e)}})
8676            except EngineStuck as e:                         # an unload or restart that could not end the engine
8677                self._json(503, {"error": {"type": "server_error", "message": str(e)}})
8678
8679            except ClientGone:                               # #1999: the client left while the request was prepared
8680                self._note(outcome="disconnected")
8681            except OSError:
8682                self._note(outcome="disconnected")
8683                raise                                        # as before #332: the server's own handling
8684            finally:
8685                if reserved:
8686                    svc.release_inference()
8687                svc.drop_embeddings()                        # the images' file of a request that never got to run()
8688                if self.watch_done is not None:
8689                    self.watch_done.set()
8690                if self.cancel_event is not None:
8691                    with svc.status_lock:
8692                        svc.active_cancels.discard(self.cancel_event)
8693                record = self.record
8694                if record is not None:
8695                    with svc.status_lock:
8696                        record["wallclock_s"] = round(time.perf_counter() - record["_clock"], 3)
8697                        record["finished_at"] = time.time()
8698                        record["state"] = "error" if record.get("error") else record.get("outcome", "completed")
8699                    svc.request_trace.record = None
8700
8701        def _images(self, req):
8702            """POST /v1/images/generations (serve/images.py): one sd-cli job in the GPU's turn."""
8703            gen = svc.images
8704            if gen is None:
8705                self._json(404, {"error": {"type": "invalid_request_error", "code": "images_not_set_up",
8706                                           "message": "image generation is not set up on this server (run setup "
8707                                                      "with --images qwen-image)"}})
8708                return
8709            job = images_api.parse_request(req, gen.cfg)        # ImageRequestError (a ValueError): 400
8710            svc.last_request_at = time.time()
8711            cancel = threading.Event()
8712            self._watch_client(cancel)
8713            print(f"[strata] image: {job['width']}x{job['height']}, n={job['n']}, {job['steps']} steps, "
8714                  f"seed {job['seed']}", flush=True)
8715            try:
8716                with images_api.gpu_turn(svc, gen, job, cancel) as policy:
8717                    images, figures = gen.run(job, cancel)
8718            except images_api.ImageJobFailed as e:
8719                self._json(500, {"error": {"type": "server_error", "code": "image_generation_failed",
8720                                           "message": str(e)}})
8721                return
8722            figures["gpu_policy"] = policy
8723            print(f"[strata] image done in {figures['seconds']:.1f} s ({policy})", flush=True)
8724            host = self.headers.get("Host") or f"{self.server.server_address[0]}:{self.server.server_address[1]}"
8725            scheme = "https" if (self.headers.get("X-Forwarded-Proto") or "").lower() == "https" else "http"
8726            self._json(200, gen.response(images, job, figures, f"{scheme}://{host}"))
8727
8728        def _props(self):
8729            model = parse_qs(urlsplit(self.path).query).get("model", [svc.model])[0]
8730            if model not in svc.model_names():
8731                self._json(404, {"error": {"message": "model not found"}})
8732                return
8733            if not svc.loaded() and not getattr(svc.engine, "unloaded", False):
8734                self._json(503, {"error": {"message": "the engine is not running"}})
8735                return
8736            defaults = {**model_card_sampling(svc.model_arch, True), **svc.sampling_defaults, **svc.shared}
8737            names = {"repetition_penalty": "repeat_penalty", "penalty_last_n": "repeat_last_n"}
8738            params = {names.get(k, k): v for k, v in defaults.items()
8739                      if k in ("temperature", "top_p", "top_k", "min_p", "seed", "repetition_penalty",
8740                               "presence_penalty", "frequency_penalty", "penalty_last_n")}
8741            params["n_predict"] = svc.shared.get("max_tokens", -1)
8742            props = {"default_generation_settings": {"n_ctx": svc.reported_ctx(), "params": params},
8743                     "total_slots": max(1, int(getattr(svc.engine, "batch", 0) or 0)),   # #1004: the batch slots
8744                     "model_alias": svc.model, "chat_template": svc.template.source,
8745                     "chat_template_caps": svc.template.caps,
8746                     "modalities": {"vision": svc.vision is not None}, "models_autoload": hasattr(svc.engine, "restart"),
8747                     "is_sleeping": not svc.loaded()}
8748            if getattr(svc.engine, "model_path", None):
8749                props["model_path"] = svc.engine.model_path
8750            version = getattr(svc.engine, "info", {}).get("version")
8751            if version:
8752                props["build_info"] = "Strata " + str(version)
8753            self._json(200, props)
8754
8755        def _control_body(self) -> bool:
8756            """Consume the unused control body before replying/closing (Windows otherwise sends a TCP reset)."""
8757            if self._chunked():
8758                self.body_read = True
8759                try:
8760                    self.connection.settimeout(2.0)
8761                    self._read_chunked(65536, keep=False)
8762                except BadBody as e:
8763                    self._json(e.status, {"error": {"message": f"control request: {e}"}})
8764                    return False
8765                except OSError:
8766                    self._json(400, {"error": {"message": "incomplete control request body"}})
8767                    return False
8768                return True
8769            try:
8770                length = int(self.headers.get("Content-Length", "0"))
8771            except ValueError:
8772                self._json(400, {"error": {"message": "invalid Content-Length"}})
8773                return False
8774            if not 0 <= length <= 65536:
8775                self._json(413, {"error": {"message": "control request body is limited to 64 KiB"}})
8776                return False
8777            timeout = self.connection.gettimeout()
8778            try:
8779                self.connection.settimeout(2.0)
8780                complete = len(self.rfile.read(length)) == length
8781            except OSError:
8782                complete = False
8783            finally:
8784                self.connection.settimeout(timeout)
8785                self.body_read = True                    # nothing left for the drain to wait for (#594)
8786            if not complete:
8787                self._json(400, {"error": {"message": "incomplete control request body"}})
8788            return complete
8789
8790        def _own_page(self, what) -> bool:
8791            """Only JSON (a form or a "simple" cross-site request can't send it without a CORS preflight, which this
8792            server never grants) and no foreign Origin: a web page elsewhere must not change settings or run tools."""
8793            if not self.headers.get("Content-Type", "").startswith("application/json"):
8794                self._json(415, {"error": {"message": "send application/json"}})
8795                return False
8796            if self._foreign_origin():
8797                self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the "
8798                                                      f"config's trusted_origins)"}})
8799                return False
8800            return True
8801
8802        def _config_get(self):
8803            if not svc.config_path:
8804                self._json(404, {"error": {"message": "this server was started without a run config"}})
8805                return
8806            try:
8807                cfg = runconfig.load(svc.config_path)
8808            except (OSError, ValueError) as e:
8809                self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be read: {e}"}})
8810                return
8811            self._json(200, runconfig.view(cfg, svc.config_path))
8812
8813        def _config_post(self):
8814            """#564: change a few documented keys of the run config - JSON from Strata's own page only, as
8815            /settings (the key is checked before); every other key of the file stays as it is."""
8816            body = self._body()
8817            if not self._own_page("the run config can be changed"):
8818                return
8819            if not svc.config_path:
8820                self._json(404, {"error": {"message": "this server was started without a run config"}})
8821                return
8822            try:
8823                req = json.loads(body or b"{}")
8824                with svc.config_lock:
8825                    cfg = runconfig.load(svc.config_path)
8826                    new, changed = runconfig.apply(cfg, req.get("set") if isinstance(req, dict) else None)
8827                    if changed:
8828                        bak = runconfig.save(svc.config_path, new)
8829            except ValueError as e:
8830                self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})
8831                return
8832            except OSError as e:
8833                self._json(500, {"error": {"type": "server_error", "message": f"the run config cannot be written: {e}"}})
8834                return
8835            if changed:
8836                print(f"[strata] the Settings view changed {', '.join(changed)} in {Path(svc.config_path).name} "
8837                      f"(the earlier file: {bak.name}); used from the next start", flush=True)
8838            self._json(200, {**runconfig.view(new, svc.config_path), "changed": changed})
8839        def _foreign_origin(self) -> bool:
8840            """A web page of another origin sent this.  The Origin must be this server's own address (host and port),
8841            or an origin the config trusts (trusted_origins: the web app behind a reverse proxy or tunnel); no Origin
8842            is a client that is no browser.  Headers a proxy adds (X-Forwarded-*, CF-Ray, CF-Connecting-IP) prove
8843            nothing about the page that sent the request, so they open nothing."""
8844            origin = (self.headers.get("Origin") or "").rstrip("/")
8845            return bool(origin) and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \
8846                origin not in svc.trusted_origins
8847
8848        def _no_local_images(self, messages):
8849            """A web page of another origin must not have a file on this computer read as an image.  Without an
8850            api_key, _foreign_page refuses such a page unless cors_origins lets it in - and a page cors_origins lets
8851            in (["*"]: every page) could name any file and, CORS allowing, read what the model says about it.  data:
8852            and http(s) images are the page's own to send; files come from Strata's own page, a trusted origin or a
8853            client that is no browser.  ValueError (a 400)."""
8854            if self._foreign_origin() and any(not src.startswith(("data:", "http://", "https://"))
8855                                              for src in images_of(messages)):
8856                raise ValueError("a web page of another origin cannot have a file on this computer read as an "
8857                                 "image: send it as a data: URL (or add the page's origin to the config's "
8858                                 "trusted_origins)")
8859
8860        def _settings(self):
8861            # They change what every client gets, so only the app's own page may set them
8862            body = self._body()
8863            if not self._own_page("settings can be changed"):
8864                return
8865            try:
8866                req = json.loads(body or b"{}")
8867                if not isinstance(req, dict) or "defaults" not in req:
8868                    self._json(400, {"error": {"type": "invalid_request_error",
8869                                              "message": 'the body must be {"defaults": {...}} to set them, '
8870                                                         'or {"defaults": null} to clear them'}})
8871                    return
8872                shared = svc.set_shared(req["defaults"])
8873            except ValueError as e:
8874                self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})
8875                return
8876            print("[strata] other apps now use the Chat settings: " + ", ".join(f"{k}={v}" for k, v in shared.items())
8877                  if shared else "[strata] other apps use their own settings again", flush=True)
8878            self._json(200, {"shared": bool(shared), "defaults": shared})
8879
8880        def _sse(self):
8881            self._note(http_status=200)
8882            self.send_response(200)
8883            self.send_header("Content-Type", "text/event-stream")
8884            self.send_header("Cache-Control", "no-cache")
8885            self.send_header("X-Accel-Buffering", "no")   # nginx and similar proxies pass each event at once
8886            self._cors()
8887            self.end_headers()
8888            if STREAM_WRITE_TIMEOUT_S > 0:
8889                try:
8890                    self.connection.settimeout(STREAM_WRITE_TIMEOUT_S)     # (#4271) a stuck write ends as OSError: disconnected
8891                except OSError:
8892                    pass
8893
8894        def _capture(self, items, api):
8895            """Retain bounded input/output for the monitor without changing the API response (the items as they
8896            are when the monitor is off)."""
8897            if self.record is None:
8898                return items
8899            return self._captured(items, api)
8900
8901        def _captured(self, items, api):
8902            try:
8903                for item in items:
8904                    if item is not None:
8905                        if api == "openai":
8906                            delta = item["choices"][0]["delta"]
8907                            content, reasoning = delta.get("content", ""), delta.get("reasoning_content", "")
8908                            usage, timings = item.get("usage"), item.get("timings")
8909                        elif api == "responses":
8910                            kind = item["type"]
8911                            content = item["delta"] if kind == "response.output_text.delta" else ""
8912                            reasoning = item["delta"] if kind == "response.reasoning_text.delta" else ""
8913                            usage, timings = (item.get("response") or {}).get("usage"), None
8914                        else:
8915                            _, event = item
8916                            delta = event.get("delta", {})
8917                            content, reasoning = delta.get("text", ""), delta.get("thinking", "")
8918                            usage, timings = event.get("usage"), None
8919                        with svc.status_lock:
8920                            for name, value in (("output", content), ("reasoning", reasoning)):
8921                                if value:
8922                                    combined = self.record[name] + value
8923                                    self.record[name] = combined[:262144]
8924                                    self.record[name + "_truncated"] |= len(combined) > 262144
8925                            if usage:
8926                                self.record["usage"] = usage
8927                            if timings:
8928                                self.record["timings"] = timings
8929                    yield item
8930            finally:
8931                items.close()
8932
8933        def _openai(self, req):
8934            req = svc.with_shared(req, "openai")
8935            bias_api.normalize(req.get("logit_bias"), len(getattr(svc.tok, "tokens", ())) or None)
8936            messages, tools, kw = openai_to_messages(req)
8937            require_messages(messages)                # an empty conversation is a 400, as OpenAI answers it, not a reply to nothing
8938            self._no_local_images(messages)
8939            if tool_choice_of(req.get("tool_choice"))[0] == "none":   # as the Responses route: no tools are offered
8940                tools = None
8941            force = svc.force_text(forced_call(req.get("tool_choice"), tools))      # a bad value is a 400 before anything is sent
8942            messages, validator = prepare_format(req.get("response_format"), messages)
8943            if validator is not None and (tools or req.get("strata_mcp")):
8944                raise ValueError("structured response_format with tools/MCP is not supported")
8945            svc.load()
8946            max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0)   # 0/-1: the rest
8947            # No cap of our own on the reply's length when logprobs are asked for: the reply is already bounded by
8948            # max_tokens (by the rest of the context when it is not sent), which is the only bound OpenAI and vLLM
8949            # put on it either.  A reply that is not streamed does hold every entry (its token, bytes and up to 20
8950            # alternatives) until it ends, so a long one holds a lot: streaming hands each entry out with its chunk.
8951            refuse_for_split(svc.engine, req)                 # (before the batch-slot rule below: its message would say to run without --parallel)
8952            if top_logprobs(req) is not None and batch_slots_on(svc.engine) and max_req != 1:
8953                # --parallel/--batch: a slot's "BT <slot> <id>" lines carry no LP line, and the batched loop never
8954                # calls emit_lp_line (src/program/generate.cpp); an admission -- a max_tokens 1 request -- is read
8955                # as GEN 1, which does write them.  Past that one token a reply would hold entries for a prefix
8956                # only, which a client cannot tell from the model's own answer, so the longer one is refused.
8957                raise ValueError('logprobs is available with "parallel" (batch slots) only for max_tokens 1; '
8958                                 'run the server without "--parallel" for longer replies')
8959            n_vocab = len(getattr(svc.tok, "tokens", ())) or None
8960            if top_logprobs(req) is not None and n_vocab:
8961                # emit_lp_line indexes the logits row with each named id as given, so an id past the vocabulary
8962                # would read out of bounds: refused here, before anything is sent
8963                bad = [i for i in allowed_ids(req) if i >= n_vocab]
8964                if bad:
8965                    raise ValueError(f"allowed_token_ids: {bad[0]} is outside the vocabulary "
8966                                     f"(0..{n_vocab - 1})")
8967            bias_api.validate_request(req, svc.engine, len(getattr(svc.tok, "tokens", ())) or None)
8968            use_mcp = req.get("strata_mcp") is True and svc.mcp is not None      # the web app's opt-in (serve/mcp.py)
8969            own = {t.get("name") for t in tools or [] if isinstance(t, dict)}   # #592: a second line of defence
8970            if use_mcp:
8971                if not self._own_page("MCP tools can be used"):   # tools run with the user's rights on this PC
8972                    return
8973                svc.mcp.wait(10)                                  # servers still starting (only right after start)
8974                extra = svc.mcp.template_tools(exclude=own)       # the request's own tools win a name clash
8975                use_mcp = bool(extra)
8976                tools = (tools or []) + extra or None
8977            if force and use_mcp:
8978                raise ValueError("a forced tool_choice with MCP tools is not supported")
8979            svc.reasoning_budget(req)                         # a bad value is a 400 before anything is sent
8980            stop_strings(req)                                 # ... and so is a bad stop / stop_sequences
8981            check_request_sampling(req)                       # ... and a sampling field of the wrong type
8982            cancel = threading.Event()
8983            self._watch_client(cancel)                       # #430 #431 (#1999: before prepare, which can take long)
8984            ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel)
8985            _debug_req("openai", req, messages, tools, max_new, thinking, len(ids))
8986            run = run_with_mcp(svc, svc.mcp, messages, tools, kw, ids, thinking, max_new, max_req, req, cancel,
8987                               {t["name"] for t in extra}) if use_mcp else None
8988            chunks = openai_chunks(svc, req, ids, thinking, tools, max_new, cancel, run=run, force=force)
8989            if validator is not None:
8990                chunks = structured_chunks(chunks, validator)
8991            chunks = self._capture(chunks, "openai")
8992            if not req.get("stream"):
8993                return self._json(200, openai_collect(chunks))
8994            self._sse()
8995            last = time.monotonic()
8996            try:
8997                for c in chunks:
8998                    if c is None:
8999                        # A client whose idle timeout counts chunks (the OpenAI SDK drops SSE comments) would end a
9000                        # request while a long prompt is read: every 15 s an empty delta tells it the server is working
9001                        if time.monotonic() - last >= 15:
9002                            beat = {"id": "chatcmpl-reading", "object": "chat.completion.chunk", "created": int(time.time()),
9003                                    "model": req.get("model") or "", "choices": [{"index": 0, "delta": {}, "finish_reason": None}]}
9004                            self.wfile.write(b"data: " + json.dumps(beat).encode() + b"\n\n")
9005                            last = time.monotonic()
9006                        else:
9007                            self.wfile.write(b": keep-alive\n\n")      # an SSE comment: clients ignore it
9008                    else:
9009                        self.wfile.write(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\n\n")
9010                        last = time.monotonic()
9011                    self.wfile.flush()
9012                self.wfile.write(b"data: [DONE]\n\n")
9013            except OSError:
9014                self._note(outcome="disconnected")
9015                svc.note_client_disconnect(cancel)           # client went away: stop the engine
9016                chunks.close()
9017            except EngineDied as e:                          # mid-stream: say so, then end the stream properly
9018                err = {"error": {"type": "server_error", "message": died_note(e)}}
9019                self._note(error=err["error"])
9020                self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
9021            except QueueWaitExpired as e:
9022                err = {"error": {"type": "rate_limit_error", "code": "queue_wait_timeout", "message": str(e)}}
9023                self._note(error=err["error"])
9024                self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
9025            except StructuredOutputError as e:
9026                err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}}
9027                self._note(error=err["error"])
9028                self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
9029            except ValueError as e:                          # the engine's ERR after the stream started: the
9030                err = {"error": {"type": "server_error", "message": str(e)}}   # headers are sent, so no 400 now
9031                self._note(error=err["error"])
9032                self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
9033
9034        def _responses_ready(self, req, events):
9035            """Send a finished Responses result that did not run on the engine."""
9036            if not req.get("stream"):
9037                return self._json(200, responses_api.collect(events))
9038            self._sse()
9039            try:
9040                for e in events:
9041                    self.wfile.write(f"event: {e['type']}\n".encode() + b"data: " +
9042                                     json.dumps(e, ensure_ascii=False).encode() + b"\n\n")
9043                    self.wfile.flush()
9044            except OSError:
9045                self._note(outcome="disconnected")
9046
9047        def _responses(self, req):
9048            """#451: POST /v1/responses - OpenAI's Responses API, stateless (serve/responses.py), on the chat path.
9049            Errors use the Responses format; once the stream has started they arrive as a response.failed event."""
9050            try:
9051                title = (responses_api.thread_title_events(req, svc.model_for(req))
9052                         if svc.codex_thread_titles else None)
9053            except ResponsesError as e:
9054                return self._json(e.status, e.body())
9055            if title is not None:
9056                return self._responses_ready(req, title)
9057            cancel = threading.Event()
9058            self._watch_client(cancel)                       # #430 #431 (#1999: before prepare, which can take long)
9059            try:
9060                ids, thinking, tools, max_new, asm, validator, req = self._responses_prepare(req, cancel)
9061            except ClientGone:
9062                self._note(outcome="disconnected")
9063                return
9064            except ResponsesError as e:
9065                return self._json(e.status, e.body())
9066            except ModelBusy as e:
9067                return self._json(409, responses_error_body(str(e), "server_error", code="model_busy"))
9068            except (GpuBusy, EngineStarting, EngineStuck, EngineDied) as e:
9069                return self._json(503, responses_error_body(str(e), "server_error", code="server_error"))
9070
9071            def check(text, finish):
9072                return validated_json(text, validator, finish)
9073
9074            def events():
9075                yield from asm.start()
9076                done = None
9077                for kind, x in svc.run(ids, thinking, tools, max_new, req, cancel):
9078                    if kind == "ping":
9079                        yield None
9080                    elif kind == "event":
9081                        yield from asm.feed(x)
9082                    elif kind == "done":
9083                        done = x
9084                if done is not None and done["finish"] != "cancel" and not cancel.is_set():
9085                    yield from asm.finish(done, check)
9086            items = self._capture(events(), "responses")
9087            if not req.get("stream"):
9088                try:
9089                    result = responses_api.collect(items)
9090                except StructuredOutputError as e:
9091                    return self._json(502, responses_error_body(str(e), "server_error",
9092                                                                code="structured_output_failed"))
9093                except QueueWaitExpired as e:
9094                    return self._json(429, responses_error_body(str(e), "server_error",
9095                                                                code="queue_wait_timeout"), retry_after=1)
9096                except EngineDied as e:
9097                    return self._json(503, responses_error_body(died_note(e), "server_error",
9098                                                                code="server_error"))
9099                except EngineNonFinite as e:                 # #879, twice: not the request's fault
9100                    return self._json(503, responses_error_body(str(e), "server_error", code="server_error"))
9101                except ValueError as e:                      # the engine's ERR line
9102                    return self._json(500, responses_error_body(str(e), "server_error", code="server_error"))
9103                return self._json(200, result)
9104            self._sse()
9105            last = time.monotonic()
9106
9107            def send(e):
9108                self.wfile.write(f"event: {e['type']}\n".encode() + b"data: " +
9109                                 json.dumps(e, ensure_ascii=False).encode() + b"\n\n")
9110
9111            try:
9112                for e in items:
9113                    if e is None:
9114                        # Codex's idle timeout (5 minutes by default) counts events, not SSE comments: while a long
9115                        # prompt is read, a response.in_progress every 15 s tells it the server is still working
9116                        if time.monotonic() - last >= 15:
9117                            send(asm.in_progress())
9118                            last = time.monotonic()
9119                        else:
9120                            self.wfile.write(b": keep-alive\n\n")
9121                    else:
9122                        send(e)
9123                        last = time.monotonic()
9124                    self.wfile.flush()
9125            except OSError:
9126                self._note(outcome="disconnected")
9127                svc.note_client_disconnect(cancel)           # client went away: stop the engine
9128                items.close()
9129            except EngineDied as e:                          # mid-stream: response.failed, then the stream ends
9130                self._responses_failed(asm, died_note(e), "server_error", send)
9131            except QueueWaitExpired as e:
9132                self._responses_failed(asm, str(e), "queue_wait_timeout", send)
9133            except StructuredOutputError as e:
9134                self._responses_failed(asm, str(e), "structured_output_failed", send)
9135            except ValueError as e:                          # the engine's ERR after the stream started
9136                self._responses_failed(asm, str(e), "server_error", send)
9137
9138        def _responses_failed(self, asm, message, code, send):
9139            e = asm.failed(message, code)
9140            self._note(error=e["response"]["error"])
9141            try:
9142                send(e)
9143                self.wfile.flush()
9144            except OSError:
9145                pass
9146
9147        def _responses_prepare(self, req, cancel=None):
9148            responses_api.check_request(req)
9149            messages = responses_api.input_messages(req)
9150            tools, names, skipped = responses_api.request_tools(req)
9151            kw = responses_api.template_kwargs(req, {"reasoning_effort": svc.effort_default()})
9152            try:
9153                self._no_local_images(messages)              # as on the chat route: no file read for a foreign page
9154            except ValueError as e:
9155                raise ResponsesError(str(e), "input") from None
9156            try:
9157                messages, validator = prepare_format(responses_api.text_format(req), messages, with_tools=bool(tools))
9158            except ValueError as e:
9159                raise ResponsesError(str(e).replace("response_format", "text.format"), "text.format") from None
9160            noted = svc.__dict__.setdefault("hosted_tools_noted", set())   # said once per tool, not per request
9161            if set(skipped) - noted:
9162                print(f"[strata] /v1/responses: left out the hosted tools {', '.join(sorted(set(skipped) - noted))} "
9163                      f"(this server cannot run them)", flush=True)
9164                noted.update(skipped)
9165            if req.get("max_output_tokens") is None and "max_tokens" in svc.shared:   # the shared Chat settings
9166                req = {**req, "max_output_tokens": svc.shared["max_tokens"]}
9167            try:
9168                svc.reasoning_budget(req)                    # a bad value is a 400 before anything is sent
9169            except ValueError as e:
9170                raise ResponsesError(str(e), "reasoning_budget_tokens") from None
9171            try:
9172                stop_strings(req)
9173            except ValueError as e:
9174                raise ResponsesError(str(e), "stop") from None
9175            try:
9176                check_request_sampling(req)                   # the request is also the sampling dict (see below)
9177            except ValueError as e:                           # its message starts with the field's name: the param
9178                raise ResponsesError(str(e), str(e).partition(":")[0]) from None
9179            svc.load()
9180            # #924 (opt-in): a Codex compaction request is rendered with its conversation's tools, so its prompt
9181            # starts as the cached one did; the parser and the response keep the request's own tools
9182            shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools
9183            try:
9184                try:
9185                    ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req,
9186                                                          cancel=cancel)
9187                except ValueError:
9188                    if shown is tools:
9189                        raise
9190                    shown = tools                            # too long with the kept tools: the request as sent
9191                    ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req,
9192                                                          cancel=cancel)
9193            except ResponsesError:
9194                raise
9195            except ValueError as e:                          # too long for the context, an image without vision
9196                raise ResponsesError(str(e), "input", "context_length_exceeded" if "context" in str(e) else None) \
9197                    from None
9198            if svc.codex_compaction_cache:
9199                responses_api.prompt_made(req, shown)
9200            _debug_req("responses", req, messages, tools, max_new, thinking, len(ids))
9201            include = req.get("include") if isinstance(req.get("include"), list) else []
9202            asm = responses_api.Assembler(req, svc.model_for(req), len(ids), names,
9203                                          "reasoning.encrypted_content" in include, validator is not None)
9204            # the request is also the sampling dict, as on the chat path (temperature, top_p, top_k, seed, ...)
9205            return ids, thinking, tools, max_new, asm, validator, req
9206
9207        def _count_tokens(self, req):
9208            """Anthropic's token count, which Claude Code asks for its context figures: the prompt this server would
9209            read for the same request, rendered and tokenized - the model does not run."""
9210            req = svc.with_shared(req, "anthropic")
9211            messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)
9212            stop_strings(req)                                 # the same 400 as the request itself would get
9213            check_request_sampling(req)                       # ... likewise a sampling field of the wrong type
9214            self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw, store=False))})
9215
9216        def _anthropic(self, req):
9217            svc.load()
9218            req = svc.with_shared(req, "anthropic")
9219            messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)
9220            self._no_local_images(messages)
9221            callable_tools, deferred = anthropic_tools(req)     # #4663: the deferred tools are callable, unlisted
9222            if tool_choice_of(req.get("tool_choice"))[0] == "none":   # Anthropic's {"type": "none"}: no tools offered
9223                tools = callable_tools = None
9224            force = svc.force_text(forced_call(req.get("tool_choice"), tools))        # "any" / {"type": "tool", "name": N}
9225            max_new = int(req.get("max_tokens") or 0)                  # 0/-1: the rest of the context
9226            svc.reasoning_budget(req)                         # a bad value is a 400 before anything is sent
9227            stop_strings(req)                                 # ... and so is a bad stop / stop_sequences
9228            check_request_sampling(req)                       # ... and a sampling field of the wrong type
9229            cancel = threading.Event()
9230            self._watch_client(cancel)                       # #430 #431 (#1999: before prepare, which can take long)
9231            try:
9232                ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel)
9233            except ContextOverflow as e:
9234                raise ValueError(e.anthropic_text()) from None       # #4838: Anthropic's own wording first, Strata's sentence after it
9235            _debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
9236            events = anthropic_events(svc, req, ids, thinking, callable_tools, max_new, cancel, force=force,
9237                                      deferred=deferred)
9238            events = self._capture(events, "anthropic")
9239            if not req.get("stream"):
9240                return self._json(200, anthropic_collect(events))
9241            self._sse()
9242            try:
9243                for item in events:
9244                    if item is None:
9245                        self.wfile.write(b": keep-alive\n\n")
9246                    else:
9247                        name, e = item
9248                        self.wfile.write(f"event: {name}\n".encode() + b"data: " +
9249                                         json.dumps(e, ensure_ascii=False).encode() + b"\n\n")
9250                    self.wfile.flush()
9251            except OSError:
9252                self._note(outcome="disconnected")
9253                svc.note_client_disconnect(cancel)
9254                events.close()
9255            except EngineDied as e:                          # mid-stream: Anthropic's error event
9256                err = {"type": "error", "error": {"type": "api_error", "message": died_note(e)}}
9257                self._note(error=err["error"])
9258                self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
9259            except QueueWaitExpired as e:
9260                err = {"type": "error", "error": {"type": "rate_limit_error", "code": "queue_wait_timeout",
9261                                                   "message": str(e)}}
9262                self._note(error=err["error"])
9263                self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
9264            except ValueError as e:                          # the engine's ERR after the stream started
9265                err = {"type": "error", "error": {"type": "api_error", "message": str(e)}}
9266                self._note(error=err["error"])
9267                self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
9268
9269    return Handler
9270
9271
9272class Server(ThreadingHTTPServer):
9273    # On Windows SO_REUSEADDR lets a second server bind a port that is already serving, and requests then land on
9274    # either one (a forgotten second start of run-<model>.bat).  Without it the second start fails loudly instead.
9275    allow_reuse_address = os.name != "nt"
9276    # socketserver listens with a backlog of 5: a burst of 30-40 clients at once got "connection reset by peer" on the
9277    # first ones (measured on 4 x R9700, also with one request at a time); the requests wait in the server, not the kernel
9278    # (STRATA_HTTP_BACKLOG overrides it)
9279    request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256))
9280
9281    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
9282        if ":" in server_address[0]:
9283            self.address_family = socket.AF_INET6
9284        super().__init__(server_address, RequestHandlerClass, bind_and_activate)
9285
9286    def server_bind(self):
9287        # http.server's own server_bind also asks socket.getfqdn(host) for a server_name nothing here reads; on a Mac whose reverse lookup
9288        # stalls (GitHub's macOS runner: 35 s on the first lookup of every new process) each start waited that long before it listened
9289        socketserver.TCPServer.server_bind(self)
9290        self.server_name, self.server_port = self.server_address[:2]
9291
9292    def handle_error(self, request, client_address):
9293        if not isinstance(sys.exc_info()[1], ConnectionError):   # a client that hangs up needs no stack trace
9294            super().handle_error(request, client_address)
9295
9296    def server_close(self):
9297        # the hardware sampler serve() started for this server stops with it (test isolation: every Service a test
9298        # started used to leave its sampler running, 21 of them after test_responses, which slowed test_parallel's timing)
9299        tel = getattr(getattr(self, "svc", None), "telemetry", None)
9300        if tel is not None and hasattr(tel, "close"):
9301            tel.close()
9302        super().server_close()
9303
9304
9305def warn_tight_ram(arena_mib) -> None:
9306    """The model's experts live in RAM (INFO arena_mib, engine 0.1.10+).  With less than ~6 GB left beside them for the
9307    system, the engine and this server, Linux ends the engine mid-answer when memory runs out (issue #27) and Windows
9308    pages to disk; say so at start instead of after a lost answer."""
9309    if not isinstance(arena_mib, int) or arena_mib <= 0:
9310        return
9311    try:
9312        import psutil
9313        total = psutil.virtual_memory().total
9314    except Exception:  # noqa: BLE001 - psutil is optional here
9315        return
9316    left = total / 2**30 - arena_mib / 1024
9317    if left < 6:
9318        print(f"[strata] WARNING: RAM is tight - the model's experts take {arena_mib / 1024:.1f} GB of this PC's "
9319              f"{total / 2**30:.0f} GB, leaving {left:.1f} GB for everything else. "
9320              + ("Linux may stop the engine in the middle of an answer. " if os.name != "nt" else
9321                 "Windows will slow down (paging to disk). ")
9322              + "Close other programs, or run START-HERE --setup and pick a smaller size (Q2_0 / IQ2_XS).", flush=True)
9323
9324
9325def warn_budget_over_ram(args) -> str | None:
9326    """#1080: an explicit `--resident-budget-gib N` bigger than the RAM this PC has free (or than its total beside
9327    ~6 GB for everything else) pushes experts into swap or the file tier: decode that is "dead slow" until the number is
9328    removed.  A warning at start, never a refusal (recommend, never force).  -> the sentence printed, or None."""
9329    try:
9330        budget = float(args[list(args).index("--resident-budget-gib") + 1])
9331    except (ValueError, IndexError):
9332        return None
9333    try:
9334        import psutil
9335        vm = psutil.virtual_memory()
9336        total, free = vm.total / 2**30, vm.available / 2**30
9337    except Exception:  # noqa: BLE001 - psutil is optional here
9338        return None
9339    if budget <= free and budget <= total - 6:
9340        return None
9341    msg = (f"WARNING: the RAM budget for experts is {budget:g} GiB (--resident-budget-gib), but this PC has "
9342           f"{free:.0f} GiB free of {total:.0f} GiB: what does not fit goes to swap or is read from disk, which can make "
9343           "decoding very slow. Lower it (setup sizes it for this PC) or remove the argument to let the engine choose.")
9344    print("[strata] " + msg, flush=True)
9345    return msg
9346
9347
9348DESKTOP_FREE_MIB = 2048          # #560 #516: below this, an AMD card that also drives a Linux desktop can run out
9349DESKTOP_RESERVE_MIB = 3072       # what kept KDE/Wayland alive beside a full expert cache in both reports
9350
9351
9352def linux_desktop(env=None) -> bool:
9353    """A graphical session on Linux (Wayland or X): its compositor, browser and apps take VRAM after the model has."""
9354    env = os.environ if env is None else env
9355    return os.name != "nt" and sys.platform != "darwin" and bool(env.get("WAYLAND_DISPLAY") or env.get("DISPLAY"))
9356
9357
9358def desktop_vram_note(backend, vram_free_mib, args: list, desktop: bool) -> str:
9359    """#560 #516: on Linux, when the desktop needs VRAM the AMD card does not have, amdgpu moves GPU memory (the expert
9360    cache, ~24 GB) to system RAM, which the experts already fill - the OOM killer then ends the compositor.  The
9361    default reserve (700 MiB) is sized for a card without a desktop.  A recommendation, nothing changes: "" when it
9362    does not apply."""
9363    if backend != "hip" or not desktop or not isinstance(vram_free_mib, int) or vram_free_mib >= DESKTOP_FREE_MIB:
9364        return ""
9365    try:
9366        reserve = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args else 700
9367    except (ValueError, IndexError):
9368        reserve = 700
9369    if reserve >= DESKTOP_RESERVE_MIB:
9370        return ""
9371    return (f"[strata] note: {vram_free_mib} MiB of VRAM free with the model loaded. If this AMD card also drives your "
9372            "desktop and the desktop or apps crash after the start (the driver moves the expert cache to RAM and "
9373            "the OOM killer ends the session), keep more VRAM free: ./setup.sh --vram-reserve-mib "
9374            f"{DESKTOP_RESERVE_MIB} (remembered; the expert cache gets "
9375            f"{(DESKTOP_RESERVE_MIB - reserve) / 1024:.1f} GB less, a few % of speed)")
9376
9377
9378def lan_addresses() -> list[str]:
9379    """This PC's IPv4 addresses on its networks (what another device types in), without loopback/link-local."""
9380    import socket
9381    first, ips = None, set()
9382    try:                                                # the address of the default route; sends nothing (UDP)
9383        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
9384            s.connect(("10.255.255.255", 1))
9385            first = s.getsockname()[0]
9386    except OSError:
9387        pass
9388    try:
9389        for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET):
9390            ips.add(info[4][0])
9391    except OSError:
9392        pass
9393    ok = lambda ip: ip and not ip.startswith(("127.", "169.254.", "0."))
9394    return ([first] if ok(first) else []) + sorted(ip for ip in ips if ok(ip) and ip != first)
9395
9396
9397def host_name(value) -> str:
9398    """The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com",
9399    "[::1]:8095" -> "::1"; "" when it is malformed."""
9400    v = (value or "").strip().lower()
9401    if v.startswith("["):
9402        name, sep, rest = v[1:].partition("]")
9403        return name if sep and (not rest or (rest[:1] == ":" and rest[1:].isdigit())) else ""
9404    if v.count(":") == 1:
9405        v, port = v.split(":")
9406        if not port.isdigit():
9407            return ""
9408    elif ":" in v:                                       # a bare IPv6 address (a config entry)
9409        return v
9410    v = v.rstrip(".")
9411    return v if v and all(c.isalnum() or c in "-._" for c in v) else ""
9412
9413
9414def _is_ip(name: str) -> bool:
9415    import ipaddress
9416    try:
9417        ipaddress.ip_address(name)
9418        return True
9419    except ValueError:
9420        return False
9421
9422
9423def _name_in(name: str, names) -> bool:
9424    """`name` is one of `names`, or below an entry that starts with a dot (".example.com")."""
9425    return name in names or any(n.startswith(".") and (name.endswith(n) or name == n[1:]) for n in names)
9426
9427
9428def allowed_hosts_of(value, env: str = "") -> list[str]:
9429    """The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or
9430    ".example.com" (it and every name below it).  A scheme, port or path is dropped ("https://a.example.com:8443/"
9431    -> "a.example.com"); a wrong entry stops the start (ValueError)."""
9432    items = [] if value in (None, "") else [value] if isinstance(value, str) else value
9433    if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
9434        raise ValueError("allowed_hosts: expected a host name or a list of them")
9435    out = []
9436    for raw in items + [x for x in env.split(",") if x.strip()]:
9437        x = raw.strip().lower()
9438        if x == "*":
9439            out.append(x)
9440            continue
9441        x = x.split("://", 1)[-1].split("/", 1)[0]
9442        dot = x.startswith(".")
9443        name = host_name(x[1:] if dot else x)
9444        if not name:
9445            raise ValueError(f"allowed_hosts: {raw!r} is not a host name like strata.example.com")
9446        out.append("." + name if dot else name)
9447    return list(dict.fromkeys(out))
9448
9449
9450def host_names_for(bind_host: str, allowed_hosts=(), trusted_origins=()) -> set[str]:
9451    """Every name this server answers to besides an IP address: localhost, the address it listens on, the config's
9452    allowed_hosts and trusted_origins' hosts, and - listening beyond this PC (0.0.0.0 or a LAN address) - this PC's
9453    name and LAN addresses (the LAN addresses matter for the Origin check, which takes no IP on trust)."""
9454    names = set(LOOPBACK_NAMES)
9455    bind = host_name(bind_host)
9456    if bind and bind not in ("0.0.0.0", "::"):
9457        names.add(bind)
9458    if bind not in LOOPBACK_NAMES:
9459        try:
9460            pc = socket.gethostname().lower()
9461            names.update((pc, pc + ".local"))
9462        except OSError:
9463            pass
9464        names.update(("host.docker.internal", *lan_addresses()))
9465    names.update(x for x in allowed_hosts if x != "*")
9466    names.update(filter(None, (host_name(o.split("://", 1)[-1]) for o in trusted_origins)))
9467    return names
9468
9469
9470def host_allowed(host, names, any_host=False) -> bool:
9471    """DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the
9472    same origin, so the browser lets it read every answer.  Its requests carry that site's name in Host, so only
9473    the names this server answers to pass.  An IP address passes (a page served from an IP is that IP's own page;
9474    rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host
9475    header (HTTP/1.0 clients; browsers always send one)."""
9476    if any_host or not (host or "").strip():
9477        return True
9478    name = host_name(host)
9479    return bool(name) and (_is_ip(name) or name == "localhost" or name.endswith(".localhost")
9480                           or _name_in(name, names))
9481
9482
9483def key_list(value) -> list[str]:
9484    """#1344: the keys a server accepts.  --api-key / STRATA_API_KEY / "api_key" take llama.cpp's form, several keys
9485    separated by commas ("k1,k2"; spaces around each are dropped), or a list in the config ("api_key": ["k1", "k2"],
9486    the way to give a key that contains a comma).  A list is taken as it is."""
9487    if value is None or value == "":
9488        return []
9489    if isinstance(value, (list, tuple)):
9490        return [str(k) for k in value if str(k)]
9491    return [k.strip() for k in str(value).split(",") if k.strip()]
9492
9493
9494def explicit_no_key(value) -> bool:
9495    """The owner chose to serve without a key: "api_key": "none" in the config, STRATA_API_KEY=none or --api-key none
9496    (or --no-api-key, handled by the caller).  Never a key called "none"."""
9497    return isinstance(value, str) and value.strip().lower() == "none"
9498
9499
9500def open_server_warning(port, public=False, tools=False) -> str:
9501    """The one plain warning for a server on the network with no API key (recommend, never force)."""
9502    msg = f"no API key: anyone who can reach port {port} can use the model" + (" and its tools" if tools else "") + "."
9503    if tools:
9504        msg += " The tools can read and change files on this computer."
9505    if public:
9506        msg += " This address is on the public internet, so anyone who finds it can use it."
9507    return msg + " Add an API key to keep others out."
9508
9509
9510def api_key_of(value):
9511    """The key as a client can send it (#725).  An HTTP header loses the spaces and line ends around its value, so a
9512    key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no
9513    request: every client got 401 with the right key.  A value that is only such characters raises ValueError, it
9514    never means "no key" (#213).  #1344: a config list of keys returns the list (each key stripped, none empty); a
9515    string stays a string (its commas separate keys, see key_list)."""
9516    if isinstance(value, (list, tuple)):
9517        keys = [str(k).strip() for k in value]
9518        if not keys or any(not k for k in keys):
9519            raise ValueError("an API key was given but it is empty")
9520        return keys
9521    key = "" if value is None else str(value)
9522    if key and not key_list(key):
9523        raise ValueError("an API key was given but it is empty")
9524    return key.strip()
9525
9526
9527def key_matches(given: str, key) -> bool:
9528    """given: a header's value as http.server read it, each byte one character.  A key with characters outside ASCII
9529    arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the
9530    bytes were re-encoded before, so a UTF-8 key never matched).  Constant-time (#213).  #1344: `key` may name several
9531    keys (see key_list); the given one must match any, and every key is compared whatever the outcome."""
9532    raw = given.encode("latin-1", "replace")
9533    ok = False
9534    for k in key_list(key):
9535        ok |= hmac.compare_digest(raw, k.encode())
9536        try:
9537            ok |= hmac.compare_digest(raw, k.encode("latin-1"))
9538        except UnicodeEncodeError:
9539            pass
9540    return ok
9541
9542
9543def origin_allowed(origin: str, host, names, origins=()) -> bool:
9544    """A browser page's Origin that may use the model without an API key: this server's own page (the Origin is the
9545    request's own Host), a page on one of the names this server answers to (any port), or an origin the config lists
9546    (trusted_origins, cors_origins).  Unlike the Host check no IP passes on trust: a page served from any other IP is
9547    another site.  "null" (a sandboxed frame, a file:// page) does not pass: any site can send it.  An origin of another
9548    scheme (chrome-extension://, moz-extension://, an Electron app's app://) does: no web site can send one."""
9549    origin = (origin or "").strip().rstrip("/")
9550    if origin in origins or "*" in origins:             # cors_origins ["*"]: the config lets every page in
9551        return True
9552    scheme, sep, rest = origin.lower().partition("://")
9553    if not sep or not scheme:
9554        return False
9555    if scheme not in ("http", "https"):
9556        return True
9557    if host and rest == host.strip().lower():
9558        return True
9559    name = host_name(rest)
9560    return bool(name) and (name in LOOPBACK_NAMES or name.endswith(".localhost") or _name_in(name, names))
9561
9562
9563def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer:
9564    svc.host_names = host_names_for(host, svc.allowed_hosts, svc.trusted_origins)
9565    svc.start_telemetry()
9566    httpd = Server((host, port), make_handler(svc))
9567    httpd.svc = svc
9568    threading.Thread(target=httpd.serve_forever, daemon=True).start()
9569    return httpd
9570
9571
9572def origins_of(value, key: str, wildcard: bool) -> list[str]:
9573    """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path;
9574    "*" only where `wildcard` allows it.  A wrong entry stops the start rather than opening less or more than meant."""
9575    if value is None or value == "" or value == []:
9576        return []
9577    items = [value] if isinstance(value, str) else value
9578    if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
9579        raise SystemExit(f"[strata] {key}: expected an origin or a list of origins")
9580    out = []
9581    for x in items:
9582        x = x.strip().rstrip("/")
9583        if x == "*" and wildcard:
9584            out.append(x)
9585            continue
9586        scheme, sep, rest = x.partition("://")
9587        if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest:
9588            raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com"
9589                             + ("" if wildcard else " (no wildcards here)"))
9590        out.append(x)
9591    return out
9592
9593
9594SHARED_KEYS = ("reasoning_effort", "reasoning_budget_tokens", "temperature", "top_p", "top_k", "seed", "max_tokens",
9595               "experimental_speed_projection")
9596
9597
9598def clean_shared_defaults(d) -> dict:
9599    """The Chat settings other apps get (POST /settings): only known keys, each checked; ValueError names a bad one."""
9600    if d is None:
9601        return {}
9602    if not isinstance(d, dict):
9603        raise ValueError("defaults must be an object")
9604    out = {}
9605    for key, value in d.items():
9606        if value is None or value == "":
9607            continue
9608        number = isinstance(value, (int, float)) and not isinstance(value, bool)
9609        if key == "reasoning_effort":
9610            if value not in ("none", "low", "medium", "high"):
9611                raise ValueError("reasoning_effort: none, low, medium or high")
9612        elif key == "temperature":
9613            if not number or not 0 <= value <= 2:
9614                raise ValueError("temperature: 0..2")
9615        elif key == "top_p":
9616            if not number or not 0 < value <= 1:
9617                raise ValueError("top_p: 0 < top_p <= 1")
9618        elif key == "top_k":
9619            if not number or value != int(value) or not 1 <= value <= 64:
9620                raise ValueError("top_k: an integer 1..64")
9621            value = int(value)
9622        elif key in ("seed", "max_tokens"):
9623            if not number or value != int(value) or value <= 0:
9624                raise ValueError(f"{key}: a positive integer")
9625            value = int(value)
9626        elif key == "reasoning_budget_tokens":                 # #123: 0 means no budget, so 0 is allowed here
9627            if not number or value != int(value) or value < 0:
9628                raise ValueError("reasoning_budget_tokens: a whole number of tokens (0: no budget)")
9629            value = int(value)
9630        elif key == "experimental_speed_projection":
9631            if not isinstance(value, bool):
9632                raise ValueError("experimental_speed_projection: true or false")
9633        else:
9634            raise ValueError(f"unknown setting {key!r}")
9635        out[key] = float(value) if key in ("temperature", "top_p") else value
9636    return out
9637
9638
9639def split_joined_args(cfg: dict) -> None:
9640    """#2267: an engine option written as ONE element of the config's "args" - "--ple-io mmap" or "--ple-io=mmap" - reaches
9641    the engine as a single argument ("unknown argument: --ple-io mmap"; the usual form is two elements, "--ple-io",
9642    "mmap").  Recommend, never force: such an element is split into the flag and its value, and said at startup.  Only an
9643    element that starts with a flag name (--letters-digits-dashes) followed by a space or "=" is touched, and never one
9644    that sits in the value place of the flag before it."""
9645    args = cfg.get("args")
9646    if not isinstance(args, list):
9647        return
9648    out, changed = [], []
9649    for a in args:
9650        m = re.match(r"^(--[A-Za-z0-9][A-Za-z0-9-]*)(?:\s+|=)(\S.*)$", a) if isinstance(a, str) else None
9651        prev = out[-1] if out else None
9652        in_value_place = isinstance(prev, str) and re.match(r"^--[A-Za-z0-9][A-Za-z0-9-]*$", prev) is not None
9653        if m is None or in_value_place:
9654            out.append(a)
9655            continue
9656        out += [m.group(1), m.group(2).strip()]
9657        changed.append(a)
9658    if changed:
9659        cfg["args"] = out
9660        print("[strata] the config's args hold " + ", ".join(repr(c) for c in changed) + " as one element each: split into the "
9661              'flag and its value (write them as two elements, e.g. "--ple-io", "mmap")', flush=True)
9662
9663
9664def read_config(path) -> dict:
9665    """The run config's JSON.  A mistake in it (a missing comma between two args, a trailing comma) is said with its
9666    place in the file instead of a traceback (#2267: editing "args" by hand is where it happens)."""
9667    return parse_config_text(Path(path).read_text(encoding="utf-8-sig"), path)   # Notepad adds a BOM
9668
9669
9670def parse_config_text(text: str, path) -> dict:
9671    """read_config on text already read (the owner-launched server hashes the bytes it parses, launch attestation)."""
9672    try:
9673        return json.loads(text)
9674    except json.JSONDecodeError as e:
9675        raise SystemExit(f"[strata] {path} is not valid JSON: {e.msg} at line {e.lineno}, column {e.colno}. Check the commas "
9676                         'between the entries of "args" (each option and each value is its own quoted entry, e.g. '
9677                         '"--ple-io", "mmap",) and that no entry is followed by a comma at the end of a list.') from None
9678
9679
9680def lift_reasoning_effort_arg(cfg: dict) -> None:
9681    """#1641: "--reasoning-effort high" in a config's "args" is meant for the thinking level, which is not an engine
9682    option (the engine stopped at the unknown flag).  It is the config's "reasoning_effort" (none, low, medium or high:
9683    the level for requests that name none), so the flag is taken out of the engine's arguments and becomes that key
9684    unless the config already has one; said at startup."""
9685    args = cfg.get("args")
9686    if not isinstance(args, list):
9687        return
9688    out, value, i = [], None, 0
9689    while i < len(args):
9690        a = args[i]
9691        if a == "--reasoning-effort" and i + 1 < len(args):
9692            value, i = args[i + 1], i + 2
9693        elif isinstance(a, str) and a.startswith("--reasoning-effort="):
9694            value, i = a.partition("=")[2], i + 1
9695        else:
9696            out.append(a)
9697            i += 1
9698    if value is None:
9699        return
9700    cfg["args"] = out
9701    if cfg.get("reasoning_effort") is None:
9702        cfg["reasoning_effort"] = value
9703    print("[strata] '--reasoning-effort' in the config's args is not an engine option: taken out of them. The thinking "
9704          "level is the config's 'reasoning_effort' key (outside 'args'); it is used as " +
9705          f"{cfg['reasoning_effort']!r}", flush=True)
9706
9707
9708# #1819: llama.cpp clients call the repetition penalty and its window repeat_penalty / repeat_last_n; they are the
9709# same settings as repetition_penalty / penalty_last_n (the /props answer already reports them under those names)
9710SAMPLING_ALIASES = {"repeat_penalty": "repetition_penalty", "repeat_last_n": "penalty_last_n"}
9711
9712
9713def apply_saved_tuning(cfg: dict, *, say=None) -> dict:
9714    """The run config with the active saved tuning for its choices put on top (strata_control/presets.py), with no measurement.
9715    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
9716    tuning is applied every time and never re-measured. A tune's own worker sets STRATA_NO_PRESET so that it measures the
9717    configuration it was given. Never fails a start: a store that cannot be read means the configuration as it is."""
9718    if os.environ.get("STRATA_NO_PRESET"):
9719        return cfg
9720    say = say or (lambda line: print(line, flush=True))
9721    try:
9722        from strata_control import presets as _presets
9723        out, applied = _presets.overlay(cfg)
9724        if applied.get("applied"):
9725            changes = {**(applied.get("args") or {}), **(applied.get("env") or {})}
9726            note = applied.get("notice") or ""
9727            say(f"[strata] saved tuning '{applied['preset']['name']}' applied: "
9728                f"{' '.join(f'{k} {v}' for k, v in changes.items()) or 'the standard settings (nothing to change)'}"
9729                f"{'; ' + note if note and 'identical' not in note else ''}")
9730            for warning in applied.get("warnings") or []:   # #3844: outside the range the tuner tries, kept
9731                say(f"[strata] warning: {warning}")
9732            if applied.get("state") == "soft":
9733                say("[strata] this PC or engine changed since it was saved (" + "; ".join(applied["reasons"]) +
9734                    "): a short re-check is available (strata presets recheck)")
9735        elif applied.get("why_not"):
9736            say(f"[strata] saved tuning '{applied['preset']['name']}' {applied['why_not']}; re-tune with strata tune auto")
9737        return out
9738    except Exception as e:  # noqa: BLE001
9739        say(f"[strata] saved tuning could not be read ({type(e).__name__}); starting with the configuration as it is")
9740        return cfg
9741
9742
9743def sampling_defaults_from_config(cfg: dict) -> dict:
9744    """The run config's optional `sampling` block: defaults for the sampling fields a request leaves out, so
9745    a plain client gets configured sampling instead of greedy.  Supported: temperature, top_p, top_k, min_p,
9746    presence_penalty, repetition_penalty (also written repeat_penalty), frequency_penalty, penalty_last_n (also
9747    repeat_last_n), seed, logit_bias (token id -> bias, e.g. -100 bans a token).  The request's own fields
9748    always win - an explicit temperature=0 still means greedy, a field set to null falls back to the default.
9749    A bad value refuses to start the server (a typo'd config should not quietly change sampling); unknown keys
9750    are named at startup and ignored."""
9751    out = {}
9752    block = dict(cfg.get("sampling") or {})
9753    for alias, canon in SAMPLING_ALIASES.items():      # #1819: llama.cpp's names for the same two fields
9754        if block.get(alias) is not None:
9755            if block.get(canon) is not None:
9756                raise SystemExit(f"[strata] config sampling: both {alias!r} and {canon!r} are set; they are the same "
9757                                 f"setting, keep one")
9758            block[canon] = block.pop(alias)
9759    for key, value in block.items():
9760        if value is None:
9761            continue
9762        number = isinstance(value, (int, float)) and not isinstance(value, bool)
9763        if key == "temperature":
9764            if not number or value < 0:
9765                raise SystemExit(f"[strata] config sampling.temperature={value!r}: expected a number >= 0 (0 = greedy)")
9766            out[key] = float(value)
9767        elif key == "top_p":
9768            if not number or not 0 < value <= 1:
9769                raise SystemExit(f"[strata] config sampling.top_p={value!r}: expected 0 < top_p <= 1")
9770            out[key] = float(value)
9771        elif key == "min_p":
9772            if not number or not 0 <= value <= 1:
9773                raise SystemExit(f"[strata] config sampling.min_p={value!r}: expected 0 <= min_p <= 1")
9774            out[key] = float(value)
9775        elif key == "top_k":
9776            if not number or value != int(value) or not 1 <= value <= 64:
9777                raise SystemExit(f"[strata] config sampling.top_k={value!r}: the sampled path takes an integer 1..64")
9778            out[key] = int(value)
9779        elif key == "presence_penalty":
9780            if not number or value < 0:
9781                raise SystemExit(f"[strata] config sampling.presence_penalty={value!r}: expected a number >= 0")
9782            out[key] = float(value)
9783        elif key == "frequency_penalty":
9784            if not number or value < 0:
9785                raise SystemExit(f"[strata] config sampling.frequency_penalty={value!r}: expected a number >= 0")
9786            out[key] = float(value)
9787        elif key == "repetition_penalty":
9788            if not number or value <= 0:
9789                raise SystemExit(f"[strata] config sampling.repetition_penalty={value!r}: expected a number > 0 (1 = off)")
9790            out[key] = float(value)
9791        elif key == "penalty_last_n":
9792            if not number or value != int(value) or value < 0:
9793                raise SystemExit(f"[strata] config sampling.penalty_last_n={value!r}: expected a non-negative integer")
9794            out[key] = int(value)
9795        elif key == "seed":
9796            if not number or value != int(value) or value <= 0:
9797                raise SystemExit(f"[strata] config sampling.seed={value!r}: expected a positive integer")
9798            out[key] = int(value)
9799        elif key == "strata_tune":           # a saved tuning's per-request settings (strata_control/presets.py)
9800            if not isinstance(value, dict):
9801                raise SystemExit(f"[strata] config sampling.strata_tune={value!r}: expected an object")
9802            out[key] = {k: v for k, v in value.items() if k in ("pcie_frac", "spec_min_p", "aux_cpus")}
9803
9804        elif key == "logit_bias":
9805            try:
9806                out[key] = bias_api.normalize(value)
9807            except ValueError as e:
9808                raise SystemExit(f"[strata] config sampling.logit_bias: {e}")
9809        elif key == "experimental_speed_projection":
9810            if not isinstance(value, bool):
9811                raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or "
9812                                 "false (the default for requests that leave it out, when the engine has the vector)")
9813            out[key] = value
9814        else:
9815            print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True)
9816    return out
9817
9818
9819SPLIT_KEYS = ("split_fallback", "split_engine_note")
9820
9821
9822def start_engine_or_fallback(cfg: dict, exe: str, effort_end: list[str] | None, env: dict, lazy: bool, tok, *, offline: bool = False,
9823                             batch_telemetry=None):
9824    """Start the run config's engine. A config written for the all-cards split engine (strata_control/split_engine.py) carries the
9825    normal layer-split config under "split_fallback": if that engine refuses or fails to come up, say so in one plain line and start the
9826    normal one instead, so a start never fails because of the option. Any other config starts exactly as before."""
9827    fb = cfg.get("split_fallback")
9828    try:
9829        return StrataEngine(exe, engine_args(cfg, exe) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy,
9830                            retry_args=mtp_retry_args(cfg, exe, effort_end), retry_vram_args=nodraft_retry_args(cfg, exe, effort_end))
9831    except Exception as e:
9832        if not isinstance(fb, dict) or not fb.get("exe"):
9833            raise
9834        msg = str(e).strip()
9835        why = msg.splitlines()[0][:200] if msg else type(e).__name__
9836        # the engine's own reason ("sfnx: failed: ..." in its log tail, which the exception carries) is what a person needs to read
9837        own = next((ln.split("sfnx: failed: ", 1)[1].strip() for ln in reversed(msg.splitlines()) if "sfnx: failed: " in ln), "")
9838        if own:
9839            why = own[:300]
9840        log = cfg.get("log")
9841        if log:                                     # the normal engine writes the same log file: keep the split engine's
9842            try:
9843                os.replace(log, str(log) + ".split-engine")
9844            except OSError:
9845                pass
9846        print(f"[strata] The all-cards split engine could not start ({why}). Starting the normal layer split instead.", flush=True)
9847    cfg2 = {k: v for k, v in cfg.items() if k not in SPLIT_KEYS + ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting")}
9848    cfg2.update(fb)
9849    cfg2 = with_component_engine(cfg2)
9850    if engine_component.is_reference(cfg2["exe"]):
9851        exe2 = _component_exe(cfg2["exe"], cfg2)
9852    else:
9853        exe2 = cfg2["exe"] if os.path.isabs(cfg2["exe"]) else os.path.abspath(os.path.join(cfg2.get("cwd") or ".", cfg2["exe"]))
9854    env2 = child_env(cfg2, offline=offline)
9855    configure_batch_telemetry_env(env2, cfg2, batch_telemetry)
9856    effort2 = effort_end_args(cfg2, exe2, tok)
9857    engine = StrataEngine(exe2, engine_args(cfg2, exe2) + (effort2 or []), cwd=cfg2.get("cwd"), log=cfg2.get("log"), env=env2, lazy=lazy,
9858                          retry_args=mtp_retry_args(cfg2, exe2, effort2), retry_vram_args=nodraft_retry_args(cfg2, exe2, effort2))
9859    engine.info["split_fallback"] = True
9860    return engine
9861
9862
9863def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: list[str], lazy: bool,
9864                   *, offline: bool = False):
9865    """Opt-in data-parallel replicas (serve/replicas.py): one StrataEngine per card group, each with its own cards, log
9866    and CPU cores, started together; the ReplicaEngine in front spreads the requests."""
9867    from serve import replicas as rp
9868    n = len(groups)
9869    cpus = rp.cpu_sets(n, cfg.get("replica_cpus") is not False)
9870    print(f"[strata] {n} replicas on the cards {' | '.join(','.join(map(str, g)) for g in groups)}"
9871          f"{' (own CPU cores each)' if cpus else ''}: requests go to the least busy one, a conversation back to its own",
9872          flush=True)
9873    engines: list = [None] * n
9874    errors: list = []
9875    arena, arena_note = rp.shared_arena_plan(cfg, n)         # opt-in: one copy of the experts in RAM for all replicas
9876    if arena_note:
9877        print(f"[strata] {arena_note}", flush=True)
9878
9879    def one(i: int):
9880        rc = rp.replica_cfg(cfg, i, groups[i])
9881        if arena:
9882            rc["args"] = list(rc["args"]) + ["--shared-expert-arena", arena]
9883        try:
9884            engines[i] = StrataEngine(exe, engine_args(rc, exe) + effort_end, cwd=rc.get("cwd"), log=rc.get("log"),
9885                                      env=child_env(rc, offline=offline), lazy=lazy, cpus=cpus[i] if cpus else None,
9886                                      retry_args=mtp_retry_args(rc, exe, effort_end), retry_vram_args=nodraft_retry_args(rc, exe, effort_end))
9887        except BaseException as e:        # noqa: BLE001
9888            errors.append((i, e))
9889    rc0 = rp.replica_cfg(cfg, 0, groups[0])
9890    warn_budget_over_ram(engine_args(rc0, announce=False) if "args" in rc0 else [])
9891    if os.environ.get("STRATA_REPLICA_START", "") == "serial":
9892        for i in range(n):
9893            one(i)
9894    else:
9895        ts = [threading.Thread(target=one, args=(i,)) for i in range(n)]
9896        for t in ts:
9897            t.start()
9898        for t in ts:
9899            t.join()
9900    if errors and arena and len(errors) < n:
9901        # a replica that died while it was reading the experts into the shared arena (or any other one that failed) while
9902        # another one is up: the living engine took the read over (the state word in the arena), so start the failed ones
9903        # once more on the same arena instead of giving up the sharing
9904        failed = sorted(i for i, _ in errors)
9905        errors.clear()
9906        print(f"[strata] replica(s) {', '.join(map(str, failed))} did not start; starting again on the shared expert arena",
9907              flush=True)
9908        for i in failed:
9909            one(i)
9910    if errors:
9911        for e in engines:
9912            if e is not None:
9913                try:
9914                    e.close()
9915                except Exception:        # noqa: BLE001
9916                    pass
9917        rp.remove_arena(arena)
9918        i, e = errors[0]
9919        if arena:       # a shared arena that could not be made (no room in /dev/shm, a file of another pack): as before
9920            print(f"[strata] replica {i} did not start with the shared expert arena ({e}); starting every replica with "
9921                  "its own copy of the experts instead", flush=True)
9922            return start_replicas({**cfg, "replica_shared_arena": False}, groups, exe, effort_end, lazy, offline=offline)
9923        raise SystemExit(f"[strata] replica {i} did not start: {e}")
9924    load = int(cfg.get("replica_load_tokens") or rp.LOAD_TOKENS)
9925    eng = rp.ReplicaEngine(engines, load_tokens=load)
9926    if arena:
9927        eng.__dict__["arena_file"] = arena
9928        import atexit
9929        atexit.register(rp.remove_arena, arena)             # (a killed server leaves the file: the next start sweeps it)
9930    return eng
9931
9932
9933def start_split(cfg: dict, spec: dict, exe: str, effort_end: list[str], lazy: bool, *, offline: bool = False):
9934    """Opt-in split serving (serve/split.py): a prefill engine and a decode engine, one card each, the same model and the
9935    same session settings.  Started one after the other, so a shared expert arena is filled once; the SplitEngine in
9936    front hands a long prompt from the first to the second."""
9937    from serve import split as sp
9938    sp.check_cfg(cfg, spec)
9939    arena, arena_note = sp.arena_path(cfg, spec)
9940    work = sp.session_dir(spec)
9941    print(f"[strata] split serving: the prompt is read on card {spec['prefill_gpu']}, the answer is made on card "
9942          f"{spec['decode_gpu']} (prompts with {spec['min_prompt_tokens']}+ new tokens are handed over); {arena_note}",
9943          flush=True)
9944    engines = {}
9945    try:
9946        for role in ("prefill", "decode"):
9947            rc = sp.role_cfg(cfg, spec, role)
9948            if arena:
9949                rc["args"] = list(rc["args"]) + ["--shared-expert-arena", arena]
9950            if role == "prefill":
9951                warn_budget_over_ram(engine_args(rc, announce=False) if "args" in rc else [])
9952            engines[role] = StrataEngine(exe, engine_args(rc, exe) + effort_end, cwd=rc.get("cwd"), log=rc.get("log"),
9953                                         env=child_env(rc, offline=offline), lazy=lazy, retry_args=mtp_retry_args(rc, exe, effort_end), retry_vram_args=nodraft_retry_args(rc, exe, effort_end))
9954    except BaseException:
9955        for e in engines.values():
9956            try:
9957                e.close()
9958            except Exception:        # noqa: BLE001
9959                pass
9960        shutil.rmtree(work, ignore_errors=True)
9961        raise
9962    return sp.SplitEngine(engines["prefill"], engines["decode"], min_tokens=spec["min_prompt_tokens"], work_dir=work,
9963                          arena_file=arena)
9964
9965
9966def check_request_sampling(req) -> None:
9967    """A request's sampling field of the wrong JSON type ("temperature": "0.7", "top_k": 40.0, "seed": true) is a 400
9968    that names the field, as the same value is through POST /settings or the run config.  Unchecked, the value
9969    replaced the configured default in run()'s merge and sampling_keys dropped it, so the reply was greedy.  Only
9970    types are checked: a number (int or float, never bool) for temperature, top_p, min_p and the three penalties; an
9971    integer (never bool or float) for top_k, penalty_last_n and seed.  Ranges behave as before (a temperature <= 0 is
9972    greedy, top_k 0 or above 64 is clamped, a seed <= 0 is unset), and an absent or null field is not checked."""
9973    if isinstance(req, dict):      # #1819: llama.cpp's names; the OpenAI-style field wins when both are sent
9974        if req.get("repeat_penalty") is not None and req.get("repetition_penalty") is None:
9975            req["repetition_penalty"] = req["repeat_penalty"]
9976        rl = req.get("repeat_last_n")
9977        if req.get("penalty_last_n") is None and isinstance(rl, int) and not isinstance(rl, bool) and rl > 0:
9978            req["penalty_last_n"] = rl      # 0 and -1 (off / the whole context) keep the engine's default window
9979    for key, integer in (("temperature", False), ("top_p", False), ("min_p", False), ("presence_penalty", False),
9980                         ("frequency_penalty", False), ("repetition_penalty", False), ("top_k", True),
9981                         ("penalty_last_n", True), ("seed", True)):
9982        value = (req or {}).get(key)
9983        if value is None:
9984            continue
9985        if isinstance(value, str) and value.strip():      # some clients send numbers as strings: read and used
9986            try:
9987                num = float(value)
9988                num = int(num) if integer and num == int(num) else (num if not integer else None)
9989                if integer and num is None:
9990                    raise ValueError
9991                if not integer and re.fullmatch(r"\s*[+-]?\d+\s*", value):
9992                    num = int(value)
9993            except (ValueError, OverflowError):
9994                raise ValueError(f"{key}: {'an integer' if integer else 'a number'}") from None
9995            if num != num or num in (float("inf"), float("-inf")):
9996                raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
9997            req[key] = value = num
9998        if isinstance(value, bool) or not isinstance(value, int if integer else (int, float)):
9999            raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
10000
10001
10002# the API's model name per model family (the GGUF architecture, "arch" in the config) when the config names none
10003FAMILY_MODEL_NAMES = {"qwen4exp": "qwen3.8-flash-next", "qwen35moe": "qwen3.6-35b-a3b",
10004                      "deepseek41": "deepseek-v4.1-flash"}
10005
10006
10007# The sampling each model card recommends ("Best Practices"), used when neither the request, the Chat settings nor the
10008# run config's `sampling` block says otherwise.  Greedy is only for a request or config that asks for temperature 0.
10009# min_p 0, repetition_penalty 1 and presence_penalty 0 are the engine's own "off", so they are not listed.
10010MODEL_CARD_SAMPLING = {
10011    # Qwen3.8-Flash-Next (and Gyro, the same base model)
10012    "qwen4exp": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20},
10013                 "instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
10014    # Qwen3.6-35B-A3B: the general-task sets (the card's precise-coding set is temperature 0.6, presence_penalty 0)
10015    "qwen35moe": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "presence_penalty": 1.5},
10016                  "instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
10017    # DeepSeek-V4.1-Flash: temperature 1.0, top_p 1.0 for local use (thinking or not), no penalties
10018    "deepseek41": {"thinking": {"temperature": 1.0, "top_p": 1.0}, "instruct": {"temperature": 1.0, "top_p": 1.0}},
10019}
10020
10021
10022def model_card_sampling(arch, thinking) -> dict:
10023    """The model card's sampling for the family `arch` and the thinking state ({} for an unknown or unset family)."""
10024    sets = MODEL_CARD_SAMPLING.get(arch) if arch else None
10025    return dict(sets["thinking" if thinking else "instruct"]) if sets else {}
10026
10027
10028def arch_from_tokenizer(arch, pre) -> str | None:
10029    """#4137: the model family a config that names none is served as.  A hand-written config (serve/server.py run on its own, a gateway) often leaves
10030    "arch" out; for DeepSeek-V4.1 that meant the Qwen defaults: the stop ids of <|im_end|> (the DeepSeek tokenizer splits that into pieces, so a "|" or a
10031    ">" in the reply ended it: `finish_reason: stop` at token 19 in front of a table), no end token (the raw <|end▁of▁sentence|> came out as text)
10032    and no DSML tool calls.  The pack's tokenizer says what it is (its pre-tokenizer is "deepseek3"); an arch the config names is never changed."""
10033    if arch:
10034        return arch
10035    return "deepseek41" if str(pre or "").startswith("deepseek") else None
10036
10037
10038def default_model_name(cfg: dict) -> str:
10039    """The config's "model_name", else its family's name ("arch": qwen4exp, qwen35moe), else Flash-Next's."""
10040    return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
10041
10042
10043def with_current_reader(cfg: dict, package: Path) -> dict:
10044    """The picture reader (vision "exe", "cpu_exe") is written into the run config as an absolute path inside the engine package's folder,
10045    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
10046    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)."""
10047    vision = cfg.get("vision")
10048    if not isinstance(vision, dict):
10049        return cfg
10050    fixed = dict(vision)
10051    for key in ("exe", "cpu_exe"):
10052        old = fixed.get(key)
10053        if isinstance(old, str) and old and not engine_component.is_reference(old) and os.path.isabs(old):
10054            new = package / old.replace("\\", "/").rsplit("/", 1)[-1]
10055            gone = not os.path.exists(old)
10056            # #4658: the old engine folder is kept after `strata update`, so the old reader still exists; one in a SIBLING engine folder
10057            # (components/engine/<version>-...) is the engine's reader from before the update, and the engine in use has its own
10058            older = (not gone and Path(old).parent != package and Path(old).parent.parent == package.parent
10059                     and package.parent.name.lower() == "engine")
10060            if (gone or older) and new.is_file():
10061                print(f"[strata] the picture reader {old} " + ("is not there any more" if gone else "belongs to an older engine")
10062                      + f"; using {new} from the engine package in use", flush=True)
10063                fixed[key] = str(new)
10064    if fixed == vision:
10065        return cfg
10066    return {**cfg, "vision": fixed}
10067
10068
10069READER_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)
10070
10071#: 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
10072#: 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.
10073#: 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
10074#: 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
10075#: 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
10076#: 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 /
10077#: 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.
10078VISION_ON_DEMAND_BY_DEFAULT = True
10079#: AMD (HIP): the rule works there (the HIP reader starts on the first picture, +5.4 s on an R9700, and stops when idle) but is OFF by default: with no shrinking
10080#: expert cache on HIP the room has to stay in the reserve, so the engine gets no more slots (R9700, Qwen UD-Q4_K_XL: 7,959 against 7,943 with the reader on the card).
10081#: "elastic": true in the vision section asks for it.  Set True if the expert cache can give its room on HIP.
10082VISION_ON_DEMAND_AMD_BY_DEFAULT = False
10083VISION_RESERVE_MIB = 2048
10084#: Owner 11-11: on NVIDIA the on-demand reader holds no room back before the first picture (apply_vision_defaults); the shrinking expert cache
10085#: makes it.  In the resident RAM mode, where the cache cannot resize, the engine keeps the reader's room in its reserve itself
10086#: (include/strata/core/reader_room.hpp).
10087VISION_NO_RESERVE_BY_DEFAULT = True
10088_ON_DEMAND_NOT_WITH = ("--kv-grow", "--batch", "--slots", "--peer-device", "--expert-cache-device1", "--expert-cache-device2",
10089                       "--expert-cache-device3")
10090
10091
10092def vision_on_demand_by_default(cfg: dict) -> bool:
10093    """True when this config's GPU reader should start on demand without the config saying so: a GPU reader (vision.gpu) of the NVIDIA
10094    kind (or AMD's, with its CPU reader) on one GPU, no batch slots, no --kv-grow, no helper caches, and nothing in the vision section that says otherwise.  Not DeepSeek
10095    (its own tower), not Intel or a Mac (not measured there), not a reader pinned to another card (vision.cuda_device)."""
10096    vis = cfg.get("vision")
10097    if not VISION_ON_DEMAND_BY_DEFAULT or not isinstance(vis, dict) or vis.get("gpu") is not True or "elastic" in vis:
10098        return False
10099    if vis.get("cuda_device") is not None or sys.platform == "darwin":
10100        return False
10101    backend = cfg.get("backend")
10102    if (cfg.get("arch") or "") == "deepseek41" or backend not in (None, "cuda", "hip"):
10103        return False
10104    args = [str(a) for a in (cfg.get("args") or [])]
10105    if len(gpu_list(cfg)) > 1 or parallel_slots(cfg) or any(a in args for a in _ON_DEMAND_NOT_WITH):
10106        return False
10107    name = re.split(r"[\\/:]", str(vis.get("exe") or ""))[-1].lower()      # a path or a "component:..." reference
10108    if backend == "hip":       # AMD: the HIP reader, with the CPU reader setup wrote beside it to read when the card has no room
10109        return VISION_ON_DEMAND_AMD_BY_DEFAULT and name in (vision_reader.GPU_READER, vision_reader.GPU_READER + ".exe") and bool(vis.get("cpu_exe"))
10110    if vision_reader.shared_memory_nvidia_host():      # a DGX Spark: the reader stays loaded (owner 2026-11-11; vision_reader.shared_memory_nvidia_host)
10111        return False
10112    return name in (vision_reader.CPU_READER, vision_reader.CPU_READER + ".exe")
10113
10114
10115def apply_vision_defaults(cfg: dict) -> dict:
10116    """cfg with the on-demand reader switched on (vision.elastic) where vision_on_demand_by_default says so; the same dict.
10117    NVIDIA (owner 11-11, "picture reader loaded on demand with no memory reserve": Ok): no room is held back for the reader before the first
10118    picture.  The expert cache is started in segments ("vram_elastic": the engine's --vram-elastic) and makes the reader's room when a picture
10119    arrives, then takes it back after vision.elastic_idle_s; the reserve setup wrote (700 MiB, or none) stays as it is.  Measured on an RTX A6000
10120    (UD-Q4_K_XL partly streamed): 13,526 expert slots before any picture, as with the processor reader, against 13,077 with the room held back.
10121    A config that says "vram_elastic" itself, and AMD (no shrinking expert cache on HIP), keep the room in the reserve as before: the reserve
10122    setup writes for a GPU reader that stays on the card (700 MiB, or none) becomes VISION_RESERVE_MIB; a reserve the person or the app chose
10123    (any other number) is kept."""
10124    if not vision_on_demand_by_default(cfg):
10125        return cfg
10126    cfg["vision"] = {**cfg["vision"], "elastic": True}
10127    if VISION_NO_RESERVE_BY_DEFAULT and cfg.get("backend") != "hip" and "vram_elastic" not in cfg:
10128        cfg["vram_elastic"] = True                     # the cache gives the reader its room when a picture comes; nothing is held back before
10129        return cfg
10130    args = list(cfg.get("args") or [])
10131    if "--vram-reserve-mib" not in args[:-1]:
10132        args += ["--vram-reserve-mib", str(VISION_RESERVE_MIB)]
10133    elif args[args.index("--vram-reserve-mib") + 1] == "700":
10134        args[args.index("--vram-reserve-mib") + 1] = str(VISION_RESERVE_MIB)
10135    cfg["args"] = args
10136    return cfg
10137
10138
10139def with_component_engine(cfg: dict) -> dict:
10140    """A run config that names "component:strata-engine" gets the engine package for this PC: the path in `exe`, and
10141    the package's own folder first on the library path (the GPU runtime libraries ship beside the binary)."""
10142    if not engine_component.is_reference(cfg.get("exe")):
10143        return cfg
10144    cfg = dict(cfg)
10145    cfg["exe"] = _component_exe(cfg["exe"], cfg)
10146    cfg["lib_dirs"] = [*engine_component.package_lib_dirs(Path(cfg["exe"]).parent), *(cfg.get("lib_dirs") or [])]
10147    cfg = with_current_reader(cfg, Path(cfg["exe"]).parent)
10148    if cfg.get("backend") == "hip":     # AMD: the package's own hipBLASLt tuning table for this card, when its hipBLASLt version matches
10149        cfg = hipblaslt_tuning.apply(cfg, Path(cfg["exe"]).parent, say=lambda line: print(line, flush=True))
10150    return cfg
10151
10152
10153def _history_call_names(req) -> list:
10154    """The tool names a request's own conversation called, in order, on any of the three routes: Chat Completions (an assistant
10155    message's tool_calls), Anthropic (an assistant message's tool_use blocks) and Responses (function_call / custom_tool_call
10156    input items, a namespace in front as `namespace.name`)."""
10157    names = []
10158    for message in req.get("messages") or []:
10159        if not isinstance(message, dict) or message.get("role") != "assistant":
10160            continue
10161        for call in message.get("tool_calls") or []:
10162            names.append((call.get("function") or {}).get("name") if isinstance(call, dict) else None)
10163        content = message.get("content")
10164        for block in content if isinstance(content, list) else []:
10165            if isinstance(block, dict) and block.get("type") == "tool_use":
10166                names.append(block.get("name"))
10167    items = req.get("input")
10168    for item in items if isinstance(items, list) else []:
10169        if isinstance(item, dict) and item.get("type") in ("function_call", "custom_tool_call"):
10170            name = item.get("name")
10171            if isinstance(name, str) and name and isinstance(item.get("namespace"), str) and item["namespace"]:
10172                name = f"{item['namespace']}.{name}"
10173            names.append(name)
10174    return names
10175
10176
10177def with_history_tools(tools, req) -> list:
10178    """#4663: an agent's tool set changes between turns (deferred tools, MCP servers, a compacted history), and the model calls a tool it used
10179    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
10180    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
10181    declared (the call comes back as a tool call; the client says what it does with it) - on Chat Completions, Anthropic and Responses.
10182    Nothing is added when the request declared no tools at all, or for a name that is already declared."""
10183    if not tools or not isinstance(req, dict):
10184        return tools
10185    try:
10186        have = {t.get("name") for t in tools if isinstance(t, dict)}
10187        extra = []
10188        for name in _history_call_names(req):
10189            if isinstance(name, str) and name and name not in have:
10190                have.add(name)
10191                extra.append({"name": name, "parameters": {"type": "object", "properties": {}}})
10192        return [*tools, *extra] if extra else tools
10193    except Exception:
10194        return tools
10195
10196
10197def _component_exe(reference: str, cfg: dict) -> str:
10198    """The engine a run config names as "component:strata-engine". No engine for this PC is a clear notice and exit 5;
10199    the server never goes looking on the internet for one (strata_control/engine_component.py)."""
10200    try:
10201        return engine_component.expand(reference, cfg)
10202    except engine_component.EngineMissing as e:
10203        print(f"[strata] {e}", file=sys.stderr, flush=True)
10204        raise SystemExit(e.exit_code) from None
10205
10206
10207def undeclared_tool_calls_setting(cfg: dict) -> str:
10208    """#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
10209    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
10210    its own policy for unknown names (it answers the model with the tool names it has).  Anything else stops the start."""
10211    mode = cfg.get("undeclared_tool_calls")
10212    if mode is None:                                  # the environment names it too (STRATA_UNDECLARED_TOOL_CALLS); the config wins
10213        mode = os.environ.get("STRATA_UNDECLARED_TOOL_CALLS") or "text"
10214    if mode not in ("text", "call"):
10215        raise SystemExit(f"[strata] config \"undeclared_tool_calls\" must be \"text\" or \"call\", not {mode!r}")
10216    return mode
10217
10218
10219def tool_call_recovery_setting(cfg: dict) -> bool:
10220    """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),
10221    "tool_call_recovery": false turns it off. Anything but true or false stops the start."""
10222    recovery = cfg.get("tool_call_recovery", True)
10223    if not isinstance(recovery, bool):
10224        raise SystemExit(f"[strata] config \"tool_call_recovery\" must be true or false, not {recovery!r}")
10225    return recovery
10226
10227
10228def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> int:
10229    """Serve until stopped. For as long as it runs this server holds the shared activity lease of the runtime folder (the same one `strata serve` and
10230    a runtime host take), so `strata update` and a calibration run see an engine that was started by running this file directly - the desktop app's
10231    source install does - and wait for it or refuse, instead of test-starting a second copy of the model beside it (#4463). A lease that cannot be
10232    taken (an exclusive holder, a runtime folder that is not usable) never stops the server.
10233
10234    Its console output goes through a bounded queue (serve/nonblocking_out.py, #4479 / #2481): a console that stops taking output must not hold a
10235    request's turn, a cancel or an admission.  STRATA_BLOCKING_CONSOLE=1 turns it off (testers)."""
10236    quiet_crash_env()                                  # every child inherits it: no gdb on a user's machine (strata_control/childenv.py)
10237    lease = None
10238    try:
10239        from strata_control import runtime as _runtime
10240        lease = _runtime.acquire_activity_lease(shared=True)
10241    except Exception:                                  # noqa: BLE001 - serving never depends on the lease
10242        lease = None
10243    try:
10244        if os.environ.get("STRATA_BLOCKING_CONSOLE") == "1":
10245            return _main(argv, lifecycle_event=lifecycle_event, interrupt_exit_code=interrupt_exit_code)
10246        from serve.nonblocking_out import decoupled_console
10247        with decoupled_console():
10248            return _main(argv, lifecycle_event=lifecycle_event, interrupt_exit_code=interrupt_exit_code)
10249    finally:
10250        if lease is not None:
10251            try:
10252                os.close(lease)
10253            except OSError:
10254                pass
10255
10256
10257def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> int:
10258    try:                                               # files made by a run as administrator still belong to the user
10259        from strata_control import private_files as _pf
10260        _pf.adopt_user_defaults()
10261    except Exception:
10262        pass
10263    event_sink = lifecycle_event
10264
10265    def notify_lifecycle(kind: str, payload: dict) -> None:
10266        nonlocal event_sink
10267        if event_sink is None:
10268            return
10269        try:
10270            event_sink(kind, payload)
10271        except (OSError, ValueError):
10272            # A closed event consumer must not strand the owned engine or API.
10273            event_sink = None
10274
10275    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
10276    ap.add_argument("--engine", choices=["mock", "strata"], default="mock")
10277    ap.add_argument("--config", help="strata engine config (JSON: exe, args, cwd, tokenizer, model_name), "
10278                                     "written by setup.py")
10279    ap.add_argument("--host", default=None,
10280                    help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices "
10281                         "on your network, :: = all IPv6 interfaces (set an API key); also \"host\" in the config")
10282    ap.add_argument("--script-cycle", action="store_true",
10283                    help="with --script given more than once: repeat the scripts by position instead of advancing "
10284                         "to the last one and staying there, so extra requests a harness makes (a session title, "
10285                         "a re-ask after a tool result) cannot shift the sequence")
10286    ap.add_argument("--script-delay", type=float, default=0.0,
10287                    help="seconds to wait between the mock engine's tokens, so a turn stays live long enough for a "
10288                         "client to cancel it; the mock honours cancellation between tokens")
10289    ap.add_argument("--script", action="append",
10290                    help="the mock engine's answer (default: a short greeting); given more than once, requests get "
10291                         "them in turn and the last one repeats")
10292    ap.add_argument("--port", type=int, default=8095)
10293    ap.add_argument("--ready-file", help="write a JSON instance record once the API is bound and model state is known")
10294    ap.add_argument("--owner-fd", type=int, help=argparse.SUPPRESS)
10295    ap.add_argument("--shutdown-timeout", type=float, default=None,
10296                    help="opt-in graceful drain deadline in seconds (0..300) before owned requests are cancelled")
10297    ap.add_argument("--parallel", type=int, default=None,
10298                    help="request this many simultaneous engine slots without changing the saved config")
10299    ap.add_argument("--batch-groups", default=None,
10300                    help="pipeline groups: auto or a positive integer, without changing the saved config")
10301    ap.add_argument("--max-queue", type=int, default=None,
10302                    help="maximum inference calls waiting beyond effective engine slots; 0 refuses overload")
10303    ap.add_argument("--queue-timeout", type=float, default=None,
10304                    help="maximum seconds waiting for the first engine turn (0.1..600; off by default)")
10305    ap.add_argument("--batch-telemetry", action=argparse.BooleanOptionalAction, default=None,
10306                    help="opt in to low-rate engine decode-window samples for /v1/telemetry")
10307    ap.add_argument("--offline", action="store_true",
10308                    help="do not fetch remote image URLs or start MCP/tool subprocesses")
10309    ap.add_argument("--gpu", help="the GPU to run on, as nvidia-smi numbers them, or several for a layer split "
10310                                  "(\"0,2\"; also \"gpu\" in the config)")
10311    ap.add_argument("--tokenizer", default=str(ROOT / "pack/full/tokenizer"),
10312                    help="pack tokenizer directory (falls back to a byte tokenizer if absent)")
10313    ap.add_argument("--open", action="store_true", help="open the local page in the browser once the model is ready")
10314    ap.add_argument("--fit-max-tokens", action="store_true",
10315                    help="clamp max_tokens to the remaining context instead of rejecting the request "
10316                         "(the default; kept so older scripts keep working)")
10317    ap.add_argument("--no-fit-max-tokens", action="store_true",
10318                    help="answer 400 when prompt + max_tokens does not fit the context, like llama.cpp "
10319                         "(also \"fit_max_tokens\": false in the config). A prompt that alone does not fit is always 400")
10320    ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""),
10321                    help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. "
10322                         "Several keys: separate them with commas (key1,key2), as llama.cpp does")
10323    ap.add_argument("--no-api-key", action="store_true",
10324                    help="serve on the network without an API key (anyone who can reach the port can use the model; "
10325                         "also \"api_key\": \"none\" in the config). Warns once, never refuses")
10326    ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": "
10327                                         "{...}}); the web app's chat can use their tools (also \"mcp_servers\" in "
10328                                         "the config)")
10329    ap.add_argument("--lazy", action="store_true", help="start the API unloaded (the engine and the vision encoder start with the first request)")
10330    ap.add_argument("--api-monitor", action="store_true",
10331                    help="the API request monitor at /api-monitor: keeps the last 100 requests' prompts and answers in "
10332                         "memory (also \"api_monitor\": true in the config; off by default)")
10333    ap.add_argument("--idle-unload", type=float, default=None, metavar="SECONDS",
10334                    help="unload the model after this many seconds without requests, so other programs (games, other "
10335                         "model servers) can use the VRAM; the next request loads it again (also \"idle_unload_s\" "
10336                         "in the config; default: never)")
10337    ap.add_argument("--min-free-vram-mib", type=int, default=None,
10338                    help="load an unloaded model only when this much VRAM is free, else answer 503 (also "
10339                         "\"min_free_vram_mib\" in the config; default: always load)")
10340    ap.add_argument("--before-load", help="a command run before the model is loaded again (e.g. to unload another "
10341                                          "server's model; also \"before_load\" in the config, a string or a list)")
10342    ap.add_argument("--slot-save-path", default=None, metavar="DIR",
10343                    help="enable POST /slots/0?action=save|restore {\"filename\": NAME} (llama-server's API): the "
10344                         "conversation the engine holds, to or from DIR/NAME (also \"slot_save_path\" in the config)")
10345    ap.add_argument("--replicas", type=int, default=None, metavar="N",
10346                    help="data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on "
10347                         "each, requests spread over them (also \"replicas\" in the config: a number, or "
10348                         "[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])")
10349    ap.add_argument("--split-serve", default=None, metavar="PREFILL,DECODE",
10350                    help="split serving (opt-in): one engine on card PREFILL reads the prompt, a second on card DECODE makes "
10351                         "the answer, the session handed over in RAM (also \"split_serve\" in the config: "
10352                         "{\"prefill_gpu\": 0, \"decode_gpu\": 1}; docs/SPLIT_SERVE.md)")
10353    launch_args = list(sys.argv[1:] if argv is None else argv)
10354    a = ap.parse_args(launch_args)
10355    if a.engine == "strata" and (_rt := rttime_limit_note()):   # #3238: say it before the first unexplained -9
10356        print("[strata] WARNING: " + _rt, flush=True)
10357    global OPENS_BROWSER
10358    OPENS_BROWSER = bool(a.open)
10359    # Every ordinary way of being asked to stop takes Ctrl+C's path (QUIT to the engine, then exit): SIGTERM (#96 docker
10360    # stop; systemd), SIGHUP (the terminal closed, ssh dropped), and on Windows Ctrl+Break and the console's close,
10361    # logoff and shutdown events. They are installed before anything slow starts, so one that arrives while the model
10362    # loads is not the default "die at once". SIGINT keeps Python's own handler (a second Ctrl+C stops waiting).
10363    termination = "sigint"
10364    finished = threading.Event()                        # set when the clean stop is over (a Windows console handler waits for it)
10365
10366    def request_stop(reason: str):
10367        nonlocal termination
10368        termination = reason
10369        if threading.current_thread() is threading.main_thread():
10370            raise KeyboardInterrupt
10371        import _thread
10372        _thread.interrupt_main()
10373    lifeline.install_stop_handlers(request_stop, finished)
10374    if a.owner_fd is not None:
10375        try:
10376            owner_guard.start(a.owner_fd, grace=(a.shutdown_timeout or 0) + 40)
10377        except (OSError, ValueError) as exc:
10378            ap.error(str(exc))
10379    if a.shutdown_timeout is not None and not 0 <= a.shutdown_timeout <= 300:
10380        ap.error("--shutdown-timeout must be in 0..300 seconds")
10381    config_bytes = Path(a.config).read_bytes() if a.config else b""
10382    cfg = parse_config_text(config_bytes.decode("utf-8-sig"), a.config) if a.config else {}   # Notepad adds a BOM
10383    split_joined_args(cfg)
10384    if a.config and a.engine == "strata":
10385        cfg = apply_saved_tuning(cfg)
10386    attestation_key = os.environ.pop("STRATA_OWNER_ATTEST_KEY", None)
10387    launch_attestation = None
10388    if a.owner_fd is not None:
10389        if attestation_key is None or not re.fullmatch(r"[0-9a-f]{64}", attestation_key):
10390            ap.error("owned server needs a private launch attestation key")
10391        launch_attestation = launch_identity.attestation(bytes.fromhex(attestation_key),
10392                                                          config_bytes, launch_args)
10393    if "batch_telemetry" in cfg and type(cfg["batch_telemetry"]) is not bool:
10394        ap.error("batch_telemetry must be true or false")
10395    try:
10396        ready_path = ready_file.preflight(a.ready_file) if a.ready_file else None
10397    except ValueError as e:
10398        ap.error(str(e))
10399    max_queue = a.max_queue if a.max_queue is not None else cfg.get("max_queue")
10400    if max_queue is not None and (isinstance(max_queue, bool) or not isinstance(max_queue, int)
10401                                  or not 0 <= max_queue <= 4096):
10402        ap.error("--max-queue / max_queue must be a whole number in 0..4096")
10403    queue_timeout = a.queue_timeout if a.queue_timeout is not None else cfg.get("queue_timeout")
10404    if queue_timeout is not None and (isinstance(queue_timeout, bool) or not isinstance(queue_timeout, (int, float))
10405                                      or not math.isfinite(queue_timeout) or not 0.1 <= queue_timeout <= 600):
10406        ap.error("--queue-timeout / queue_timeout must be finite seconds in 0.1..600")
10407    if queue_timeout is not None and max_queue is None:
10408        ap.error("--queue-timeout requires --max-queue / max_queue to bound pending calls")
10409    if a.parallel is not None:
10410        if a.parallel < 1 or a.parallel > 1024:
10411            ap.error("--parallel must be in 1..1024; the engine may reduce it to the supported count")
10412        if parallel_flag_conflicts(cfg):
10413            ap.error("--parallel conflicts with an explicit --batch/--slots in the saved engine args")
10414        cfg["parallel"] = a.parallel
10415    if a.batch_groups is not None:
10416        if a.batch_groups != "auto" and (not a.batch_groups.isdecimal() or int(a.batch_groups) < 1):
10417            ap.error("--batch-groups must be auto or a positive integer")
10418        if not cfg or "args" not in cfg:
10419            ap.error("--batch-groups needs an engine config")
10420        if "--batch-groups" in cfg["args"]:
10421            ap.error("--batch-groups conflicts with the saved engine args")
10422        cfg["args"] = [*cfg["args"], "--batch-groups", a.batch_groups]
10423    lift_reasoning_effort_arg(cfg)
10424    if a.replicas is not None:
10425        cfg["replicas"] = a.replicas
10426    if a.split_serve is not None:
10427        pair = [x.strip() for x in a.split_serve.split(",")]
10428        if len(pair) != 2 or not all(x.isdecimal() for x in pair):
10429            ap.error("--split-serve takes two card numbers: PREFILL,DECODE (for example 0,1)")
10430        cfg["split_serve"] = {**(cfg.get("split_serve") if isinstance(cfg.get("split_serve"), dict) else {}),
10431                              "prefill_gpu": int(pair[0]), "decode_gpu": int(pair[1])}
10432    if a.gpu is not None:
10433        cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu
10434    a.host = a.host or cfg.get("host") or "127.0.0.1"   # issue #26: the run scripts pass no --host, the config can
10435    supplied_args = argv if argv is not None else sys.argv[1:]
10436    if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or \
10437            any((x == "--api-key" and i + 1 < len(supplied_args) and not supplied_args[i + 1].strip()) or
10438                x.strip() == "--api-key=" for i, x in enumerate(supplied_args)):
10439        print("[strata] an API key was given but it is empty: set a key, or leave it out", file=sys.stderr)
10440        return 2
10441    raw_key = a.api_key or cfg.get("api_key", "")
10442    no_key_chosen = bool(getattr(a, "no_api_key", False)) or explicit_no_key(raw_key)
10443    if explicit_no_key(raw_key):
10444        raw_key = ""
10445    try:
10446        preflight_api_key = api_key_of(raw_key)
10447    except ValueError as e:
10448        print(f"[strata] {e}: set a key, or leave it out", file=sys.stderr)
10449        return 2
10450    # A key is recommended on a network, never required (owner decision 2026-10-20): the banner below warns once.
10451    try:                                                # before the minutes of loading: is the port free?
10452        Server((a.host, a.port), BaseHTTPRequestHandler).server_close()
10453    except OSError as e:
10454        ap.error(listen_problem(a.host, a.port, e))
10455    if cfg.get("tokenizer"):
10456        a.tokenizer = cfg["tokenizer"]
10457    tok = ByteTokenizer()
10458    tcfg = {}
10459    tpath = Path(a.tokenizer)
10460    if a.engine == "strata" and not (tpath / "vocab.json").exists():
10461        ap.error(f"the model's tokenizer is missing ({tpath / 'vocab.json'}); run setup again")
10462    if (tpath / "vocab.json").exists():
10463        import strata_tokenizer as ST
10464        vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8"))
10465        tokens = [None] * len(vocab)
10466        for t, i in vocab.items():
10467            tokens[i] = t
10468        merges = (tpath / "merges.txt").read_text(encoding="utf-8").split("\n")
10469        types = json.loads((tpath / "token_type.json").read_text())
10470        try:                                            # the pack's pre-tokenizer name and special ids (DeepSeek's differ)
10471            tcfg = json.loads((tpath / "tokenizer.json").read_text(encoding="utf-8"))
10472        except (OSError, ValueError):
10473            pass
10474        try:
10475            tok = ST.Tokenizer(tokens, merges, types, tcfg.get("pre") or "qwen35", tcfg.get("special_ids") or None)
10476        except ST.UnknownPreTokenizer as e:             # a model with its own splitting rule: stop here, never split with another's
10477            ap.error(f"the model's tokenizer ({tpath}): {e}")
10478    if a.engine == "strata" and not cfg.get("arch") and arch_from_tokenizer(None, tcfg.get("pre")):
10479        cfg["arch"] = arch_from_tokenizer(None, tcfg.get("pre"))
10480        print(f"[strata] the config names no \"arch\" and this tokenizer is DeepSeek's: serving it as {cfg['arch']} (its end token, DSML tool "
10481              f"calls and effort words); add \"arch\": \"{cfg['arch']}\" to the config to say it outright", flush=True)
10482    hub = hub_from_config(cfg, a.mcp_config)            # before the minutes of loading: a bad entry stops here
10483    if a.offline and (hub is not None or cfg.get("before_load") or a.before_load):
10484        ap.error("--offline requires MCP servers and before_load commands to be disabled in this profile")
10485    if a.offline:
10486        # The same decision, reported through the policy module so the two cannot drift: a profile
10487        # that permits a network source is refused here rather than on its first request.
10488        try:
10489            from strata_control import offline as offline_policy
10490            blocked = offline_policy.ensure_strictly_offline(cfg)
10491        except ImportError:
10492            blocked = []
10493        if blocked:
10494            ap.error("--offline cannot be strict for this profile: " + "; ".join(blocked))
10495    lazy = False
10496    if a.engine == "strata":
10497        if not cfg:
10498            ap.error("--engine strata needs --config")
10499        cfg = apply_vision_defaults(with_component_engine(cfg))
10500        vision = None
10501        # The engine's own environment. It carries the offline policy too: an engine that fetched a
10502        # missing shard or a plugin would break the promise the flag makes.
10503        env = child_env(cfg, offline=a.offline)
10504        configure_batch_telemetry_env(env, cfg, a.batch_telemetry)
10505        sampling_defaults = sampling_defaults_from_config(cfg)
10506        if sampling_defaults:
10507            pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items())
10508            print(f"[strata] sampling defaults from the config: {pretty}", flush=True)
10509        lazy = a.lazy or cfg.get("lazy_load") is True
10510        for line in card_roles_lines(cfg):             # the card roles: said first; every card Off stops here, before anything touches a card
10511            print(line, flush=True)
10512        if cfg.get("vision"):
10513            elastic = cfg["vision"].get("elastic") is True
10514            print("the vision encoder starts with the first picture (elastic) ..." if elastic else
10515                  "loading the vision encoder ..." if not lazy else
10516                  "vision encoder unloaded; it starts with the model ...", flush=True)
10517            # relative paths are the config's cwd's, as for the engine below
10518            vcfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
10519                        if k in ("exe", "mmproj", "model") and isinstance(v, str) and not os.path.isabs(v) else v)
10520                    for k, v in cfg["vision"].items() if not (k == "exe" and engine_component.is_reference(v))}
10521            if engine_component.is_reference(cfg["vision"].get("exe")):     # the engine from the component folder
10522                vcfg["exe"] = _component_exe(cfg["vision"]["exe"], cfg)
10523            if vcfg.get("elastic") is True and layer_split_of(cfg):
10524                # the engine turns --vram-elastic off on a layer split (a cache per GPU): the encoder still starts
10525                # with the first picture and stops when idle, but its VRAM has to be free already
10526                print('[strata] images: on a layer split the expert cache cannot make room for the image encoder (the '
10527                      'engine turns --vram-elastic off); keep its VRAM free with "--vram-reserve-mib" on the '
10528                      "encoder's GPU, or the first picture may not get it", flush=True)
10529            vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None,
10530                            env=vision_env(cfg, env), lazy=lazy)
10531        print("model unloaded; the first request loads it ..." if lazy else
10532              "loading the model (the first start takes a minute or two) ...", flush=True)
10533        warn_budget_over_ram(engine_args(cfg, announce=False) if "args" in cfg else [])      # #1080
10534        note = card_note(cfg, env)
10535        if note:
10536            print(note, flush=True)
10537        arch_line = engine_arch_note(cfg)
10538        if arch_line:
10539            print(arch_line, flush=True)
10540        igpu_line = igpu_split_warning(cfg)
10541        if igpu_line:
10542            print(igpu_line, flush=True)
10543        if layer_split_of(cfg):
10544            try:
10545                split = layer_split_value(cfg)          # #644: before the (minutes-long) start
10546            except ValueError as e:
10547                raise SystemExit(f"[strata] config {e}")
10548            print(f"[strata] layer split across GPUs {gpu_list(cfg)} ({split})", flush=True)
10549        elif len(gpu_list(cfg)) > 1:
10550            print(f"[strata] GPUs {gpu_list(cfg)}: the later card(s) serve as the peer expert tier (--peer-device)",
10551                  flush=True)
10552        # a relative "exe" is the config's cwd's: Windows' CreateProcess resolves "engine/strata.exe" against nothing
10553        # it is told about (WinError 2), so it is made absolute here
10554        if engine_component.is_reference(cfg["exe"]):      # "component:strata-engine": the engine package for this PC
10555            exe = _component_exe(cfg["exe"], cfg)
10556        else:
10557            exe = cfg["exe"] if os.path.isabs(cfg["exe"]) else os.path.abspath(os.path.join(cfg.get("cwd") or ".", cfg["exe"]))
10558        try:
10559            silence = engine_silence_s(cfg)             # #481: checked before the (minutes-long) start
10560            apply_ready_timeout(cfg)
10561        except ValueError as e:
10562            raise SystemExit(f"[strata] config {e}")
10563        try:
10564            effort_end = effort_end_args(cfg, exe, tok)  # #458
10565        except ValueError as e:
10566            raise SystemExit(f"[strata] config {e}")
10567        from serve import replicas as rp
10568        try:
10569            groups = rp.gpu_groups(cfg)
10570        except rp.ReplicaConfigError as e:
10571            raise SystemExit(f"[strata] config {e}")
10572        from serve import split as split_mod
10573        try:
10574            split = split_mod.split_spec(cfg)
10575            if split:
10576                split_mod.check_cfg(cfg, split)
10577        except split_mod.SplitConfigError as e:
10578            raise SystemExit(f"[strata] config {e}")
10579        if groups:
10580            engine = start_replicas(cfg, groups, exe, effort_end or [], lazy, offline=a.offline)
10581        elif split:
10582            engine = start_split(cfg, split, exe, effort_end or [], lazy, offline=a.offline)
10583        else:
10584            engine = start_engine_or_fallback(cfg, exe, effort_end, env, lazy, tok, offline=a.offline, batch_telemetry=a.batch_telemetry)
10585        engine.silence_s = silence                      # an attribute of its own: restart() keeps it
10586        warn_tight_ram(engine.info.get("arena_mib"))
10587        note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1],
10588                                 linux_desktop()) if not groups and not split else None
10589        if note:                                        # #560 #516: before --open starts a browser on that card
10590            print(note, flush=True)
10591    else:
10592        effort_end = None
10593        engine, vision, sampling_defaults = MockEngine(tok, a.script or [
10594            "Thinking about it.</think>\n\nHello from the mock engine."],
10595            cycle=getattr(a, "script_cycle", False),
10596            delay_s=getattr(a, "script_delay", 0.0) or 0.0), None, {}
10597    # the model's own chat template (exported with its tokenizer), else the original model's
10598    tpl = tpath / "chat_template.jinja"
10599    if (cfg.get("arch") or "") == "deepseek41":
10600        from serve import dsml
10601        tpl, swapped = dsml.pick_template(tpl)
10602        if swapped:
10603            print("[strata] this pack's chat template spells the tool-call block differently from the V4.1 model's; "
10604                  "using the V4.1 template so tool calls come back as real calls", flush=True)
10605    if vision is None and a.engine == "strata" and (cfg.get("arch") or "") == "deepseek41":
10606        vision = ds4_engine_vision(cfg, engine)
10607    svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"),
10608                  model_name=default_model_name(cfg), vision=vision,
10609                  sampling_defaults=sampling_defaults,
10610                  fit_max_tokens=a.fit_max_tokens or (not a.no_fit_max_tokens and cfg.get("fit_max_tokens") is not False))
10611    svc.launch_attestation = launch_attestation
10612    if (cfg.get("arch") or "") == "deepseek41" and vision is None and a.engine == "strata":
10613        # DeepSeek-V4.1 reads pictures with the engine's own tower (--vision on, the default): no separate reader process.
10614        # `--vision off` in the config's args, or a pack without a tower, leaves svc.vision None: pictures are refused with the 400 as before.
10615        _dsp = DsPictures.from_config(cfg, tmp_dir=Path(cfg["log"]).parent / "ds-pictures" if cfg.get("log") else None)
10616        if _dsp is not None:
10617            svc.vision = _dsp
10618            print("[strata] pictures: on (DeepSeek-V4.1 reads them with the engine's own vision tower; --vision off turns them off)", flush=True)
10619    svc.offline = a.offline
10620    svc.max_queue = max_queue
10621    svc.queue_timeout_s = float(queue_timeout) if queue_timeout is not None else None
10622    if a.engine == "strata":                            # the model card's sampling when nothing else is said (see MODEL_CARD_SAMPLING)
10623        svc.model_arch = cfg.get("arch") or "qwen4exp"
10624        svc.set_family(svc.model_arch if svc.model_arch == "deepseek41" else None)
10625        requested = cfg.get("parallel")
10626        if requested is None:
10627            args = cfg.get("args", [])
10628            for flag in ("--batch", "--slots"):
10629                if flag in args and args.index(flag) + 1 < len(args):
10630                    try:
10631                        requested = int(args[args.index(flag) + 1])
10632                    except ValueError:
10633                        pass
10634        per_replica = requested if isinstance(requested, int) and not isinstance(requested, bool) and requested > 0 else 1
10635        svc.requested_slots = per_replica * len(groups) if groups else per_replica
10636    svc.answer_room = cfg.get("answer_room") is not False
10637    svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True    # #1053: opt-in, off by default
10638    if cfg.get("images"):                               # image generation (serve/images.py), set up by setup --images
10639        icfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
10640                    if k in ("exe", "diffusion_model", "vae", "llm", "out_dir") and isinstance(v, str)
10641                    and not os.path.isabs(v) else v)
10642                for k, v in cfg["images"].items()}
10643        try:
10644            svc.images = images_api.ImageGen(icfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None)
10645        except ValueError as e:
10646            raise SystemExit(f"[strata] config: {e}")
10647        gone = svc.images.missing()
10648        if gone:
10649            print(f"[strata] image generation: missing {', '.join(gone)} - requests fail until setup --images has run "
10650                  "again", flush=True)
10651        noise_problem = svc.images.noise_problem()
10652        if noise_problem:
10653            print(f"[strata] image generation: {noise_problem}", flush=True)
10654        vae_problem = svc.images.vae_problem()
10655        if vae_problem:
10656            print(f"[strata] image generation: {vae_problem}", flush=True)
10657        print(f"[strata] image generation: {svc.images.model} {icfg.get('quant') or ''} on "
10658              f"{icfg.get('backend') or '?'} (POST /v1/images/generations; GPU policy {svc.images.policy})", flush=True)
10659    if cfg.get("prevent_sleep") is not None and not isinstance(cfg["prevent_sleep"], bool):
10660        raise SystemExit(f"[strata] config \"prevent_sleep\" must be true or false, not {cfg['prevent_sleep']!r}")
10661    from serve.keepawake import KeepAwake
10662    svc.keep_awake = KeepAwake.create(cfg.get("prevent_sleep") is True)      # #1727: opt-in, Windows only
10663    if cfg.get("reasoning_effort") is not None:         # #1641: the thinking level of requests that name none
10664        try:
10665            svc.config_effort = clean_shared_defaults({"reasoning_effort": cfg["reasoning_effort"]}).get("reasoning_effort")
10666        except ValueError as e:
10667            raise SystemExit(f"[strata] config {e}")
10668        if svc.config_effort:
10669            print(f"[strata] thinking level: {svc.config_effort} (reasoning_effort in the config; a request, or the "
10670                  "Chat settings shared with other apps, can set its own)", flush=True)
10671    svc.codex_thread_titles = cfg.get("codex_thread_titles") is True    # #923: opt-in, off by default
10672    svc.codex_compaction_cache = cfg.get("codex_compaction_cache") is True   # #924: opt-in, off by default
10673    try:
10674        svc.set_aliases(cfg.get("aliases"))             # #297: other names the model answers to
10675    except ValueError as e:
10676        raise SystemExit(f"[strata] config {e}")
10677    if svc.aliases:
10678        print(f"[strata] model aliases: {', '.join(svc.aliases)}", flush=True)
10679    svc.api_key = preflight_api_key
10680    try:
10681        svc.telemetry_key = api_key_of(os.environ.get("STRATA_TELEMETRY_KEY") or cfg.get("telemetry_read_key", ""))
10682    except ValueError as e:
10683        print(f"[strata] invalid telemetry_read_key: {e}", file=sys.stderr)
10684        return 2
10685    if set(key_list(svc.api_key)) & set(key_list(svc.telemetry_key)):
10686        print("[strata] telemetry_read_key must differ from every inference API key", file=sys.stderr)
10687        return 2
10688    if not svc.api_key and "api_key" in cfg and not no_key_chosen:             # #569: written, but empty: the server has none (a warning, not a stop)
10689        print("[strata] the api_key in the config is empty: this server has no API key (anyone who can reach it can "
10690              "use it); set one, or leave api_key out", file=sys.stderr, flush=True)
10691    svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True)
10692    svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False)
10693    try:
10694        svc.allowed_hosts = allowed_hosts_of(cfg.get("allowed_hosts"), os.environ.get("STRATA_ALLOWED_HOSTS", ""))
10695    except ValueError as e:
10696        raise SystemExit(f"[strata] config {e}")
10697    if svc.allowed_hosts:
10698        print("[strata] Host check off: any name reaches this server (allowed_hosts \"*\")" if "*" in svc.allowed_hosts
10699              else f"[strata] also answers to the host names {', '.join(svc.allowed_hosts)} (allowed_hosts)", flush=True)
10700    svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True
10701    if svc.api_monitor:
10702        print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in "
10703              "memory" + ("" if svc.api_key else "; anyone who can reach this server can read them (no API key)"),
10704              flush=True)
10705    if svc.cors_origins:
10706        print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}"
10707              + ("" if svc.api_key or "*" not in svc.cors_origins else
10708                 " - WARNING: any web page may use the model (no API key)"), flush=True)
10709    svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0)
10710    svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \
10711        int(cfg.get("min_free_vram_mib") or 0)
10712    svc.before_load = a.before_load or cfg.get("before_load") or None
10713    try:
10714        svc.before_load_timeout_s = float(cfg.get("before_load_timeout_s") or svc.before_load_timeout_s)
10715    except (TypeError, ValueError):
10716        print("[strata] \"before_load_timeout_s\" in the config is not a number; using "
10717              f"{svc.before_load_timeout_s:g} s", flush=True)
10718    svc.before_load_ignore_failure = cfg.get("before_load_ignore_failure") is True
10719    svc.before_load_strict = cfg.get("before_load_strict") is True
10720    # --slot-save-path is relative to the working directory the server was started in; the config's slot_save_path
10721    # to the config's "cwd" (the engine's folder) when it has one.  Either way the engine gets an absolute path.
10722    if a.slot_save_path or cfg.get("slot_save_path"):
10723        try:
10724            svc.slot_save_path = slot_save_dir(a.slot_save_path) if a.slot_save_path else \
10725                slot_save_dir(cfg["slot_save_path"], cfg.get("cwd"))
10726        except (ValueError, OSError) as e:
10727            raise SystemExit(f"[strata] {e}")
10728        print(f"[strata] slot save/restore on: {svc.slot_save_path} (session files are kept until deleted: "
10729              "about 1.2 GB per 63K-token conversation; restore only files this server wrote)", flush=True)
10730    mode = str(cfg.get("anthropic_thinking") or "model")   # #278: "on_request" = only when the request asks
10731    if mode not in ("model", "on_request"):
10732        raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}")
10733    svc.anthropic_think_unasked = mode == "model"
10734    svc.tool_call_recovery = tool_call_recovery_setting(cfg)
10735    svc.undeclared_tool_calls = undeclared_tool_calls_setting(cfg)
10736    etu = cfg.get("env_to_user", False)                # opt-in: see frontend._env_to_user
10737    if not isinstance(etu, bool):
10738        raise SystemExit(f"[strata] config \"env_to_user\" must be true or false, not {etu!r}")
10739    import serve.frontend as _frontend
10740    _frontend.ENV_TO_USER = etu
10741    rs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS)   # #606: opt-out with 0
10742    if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0:
10743        raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}")
10744    svc.repeat_stop_tokens = rs
10745    tl = cfg.get("thinking_loop_tokens", 0)             # opt-in: close the thinking on a repeated token and answer
10746    if isinstance(tl, bool) or not isinstance(tl, int) or tl < 0:
10747        raise SystemExit(f"[strata] config \"thinking_loop_tokens\" must be a whole number >= 0 (0 = off), not {tl!r}")
10748    svc.thinking_loop_tokens = tl
10749    svc.effort_end = bool(effort_end)                   # #458: "effort_position": "end" with an engine that has it
10750    if cfg.get("reasoning_budget_tokens") is not None:  # #123: a default thinking budget for every request
10751        svc.reasoning_budget_configured = True
10752        try:
10753            svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"]
10754            budget = svc.reasoning_budget({})
10755        except ValueError as e:
10756            raise SystemExit(f"[strata] config {e}")
10757        if budget:
10758            print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)",
10759                  flush=True)
10760    recovery = cfg.get("reasoning_loop_recovery", False)   # #728: false (default) | "stop" | "recover" (true)
10761    if recovery is True:
10762        recovery = "recover"
10763    if recovery is not False and recovery not in ("stop", "recover"):
10764        raise SystemExit("[strata] config \"reasoning_loop_recovery\" must be false, \"stop\" or \"recover\", "
10765                         f"not {recovery!r}")
10766    svc.reasoning_loop_recovery = recovery
10767    svc.gpu_index = (gpu_list(cfg) or [0])[0]           # the Monitor reads the card the engine runs on (issue #51)
10768    svc.gpu_indices = gpu_list(cfg)                     # ... or every card of a layer split (issue #112)
10769    if a.engine == "strata" and groups:                 # replicas: every card of every group
10770        svc.gpu_indices = [c for g in groups for c in g]
10771        svc.gpu_index = svc.gpu_indices[0]
10772        svc.replica_gpu_groups = groups
10773    if a.engine == "strata" and split:                  # split serving: the two cards (the prefill card first)
10774        svc.gpu_indices = [split["prefill_gpu"], split["decode_gpu"]]
10775        svc.gpu_index = split["decode_gpu"]
10776    svc.terminal_visibility_order = visible_device_order(env, cfg.get("backend")) if a.engine == "strata" else []
10777    svc.terminal_topology_mode = ("replicas (configured)" if a.engine == "strata" and groups
10778                                  else "split serve (configured)" if a.engine == "strata" and split
10779                                  else "layer split (configured)" if a.engine == "strata" and layer_split_of(cfg)
10780                                  else "single GPU or CPU" if a.engine == "strata" else "mock")
10781    svc.terminal_configured_split = (layer_split_value(cfg) if a.engine == "strata" and layer_split_of(cfg)
10782                                     else None)
10783    svc.backend = cfg.get("backend")                    # "hip": the AMD cards' readings come from sysfs (#301)
10784    if a.config:
10785        svc.config_path = a.config                      # #564: the web page's Settings view
10786    if a.config:                                        # the Chat settings shared with other apps, from last time
10787        svc.shared_path = str(Path(a.config).with_suffix("")) + ".shared-settings.json"
10788        try:
10789            svc.shared = clean_shared_defaults(json.loads(Path(svc.shared_path).read_text(encoding="utf-8")))
10790            if svc.shared:
10791                print("[strata] other apps use the Chat settings: " +
10792                      ", ".join(f"{k}={v}" for k, v in svc.shared.items()), flush=True)
10793        except (OSError, ValueError):
10794            svc.shared = {}
10795    if hub is not None:
10796        import atexit
10797        svc.mcp = hub
10798        if hub.settings["image_results"]:
10799            hub.media_dir = Path(a.config).with_suffix(".tool-media") if a.config else Path.cwd() / ".tool-media"
10800        print(f"[strata] starting {len(hub.servers)} MCP server{'s' * (len(hub.servers) != 1)} for the web app's "
10801              f"chat: {', '.join(hub.servers)}", flush=True)
10802        hub.start()
10803        atexit.register(hub.close)                      # the servers Strata started end with it
10804    httpd = serve(svc, host=a.host, port=a.port)
10805    bound_port = httpd.server_address[1]               # --port 0: report the port the OS actually assigned
10806    svc.start_idle_unload()
10807    svc.start_vision_idle()
10808    here = "[::1]" if a.host == "::" else "127.0.0.1" if a.host in ("0.0.0.0", "") else f"[{a.host}]" if ":" in a.host else a.host
10809    print(f"ready: http://{here}:{bound_port}/v1  (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, "
10810          f"context {engine.max_context} tokens{', images on' if vision else ''}"
10811          f"{', API key required' if svc.api_key else ''})", flush=True)
10812    print(f"       open http://{here}:{bound_port}/ in a browser to chat; close this window to stop the model", flush=True)
10813    if a.host not in ("127.0.0.1", "localhost", "::1"):
10814        # issue #26: reachable from other devices - say at which address, and what can still block it
10815        ips = [f"[{a.host}]"] if ":" in a.host and a.host != "::" else [] if a.host == "::" else lan_addresses()
10816        for ip in ips:
10817            print(f"       from other devices: http://{ip}:{bound_port}/   (API: http://{ip}:{bound_port}/v1)", flush=True)
10818        if not ips:
10819            address = "[<this PC's IPv6 address>]" if a.host == "::" else "<this PC's IP address>"
10820            print(f"       from other devices: http://{address}:{bound_port}/", flush=True)
10821        if not svc.api_key:
10822            print("       WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None),
10823                  flush=True)
10824        if os.name == "nt":
10825            print("       nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run "
10826                  "in an admin PowerShell:\n         New-NetFirewallRule -DisplayName \"Strata " + str(bound_port) + "\" "
10827                  "-Direction Inbound -Protocol TCP -LocalPort " + str(bound_port) + " -Action Allow -Profile Private\n"
10828                  "       (and set this network to Private in Windows' network settings)", flush=True)
10829    if a.open and cfg.get("open_browser") is not False:   # #609: the config's "open_browser": false wins (an older
10830        import webbrowser                                  # run-<model>.bat still passes --open)
10831        # on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as
10832        # the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872)
10833        threading.Thread(target=webbrowser.open, daemon=True, name="strata-open-browser",
10834                         args=(f"http://{here}:{bound_port}/",)).start()
10835    if ready_path is not None or event_sink is not None:
10836        ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here
10837        record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(),
10838                  "api_url": f"http://{ready_host}:{bound_port}", "bound_host": a.host, "bound_port": bound_port,
10839                  "model_id": svc.model, "model_state": "unloaded" if lazy else "ready",
10840                  "api_state": "ready", "created_at": time.time()}
10841    interrupted = False
10842    drained = True
10843    try:
10844        # inside the try: a SIGTERM that arrives the moment the ready file is visible (a supervisor that reads it and
10845        # stops the server at once) takes the clean stop below, not an uncaught KeyboardInterrupt with the file left behind
10846        if ready_path is not None:
10847            try:
10848                ready_file.publish(ready_path, record)
10849            except OSError as e:
10850                print(f"[strata] could not write ready file ({type(e).__name__})", file=sys.stderr)
10851                return 6                                # the finally below closes everything once
10852        if event_sink is not None:
10853            notify_lifecycle("ready", record)
10854        while True:
10855            time.sleep(1)                               # Windows never delivers Ctrl+C to an untimed Event.wait()
10856    except KeyboardInterrupt:
10857        interrupted = True
10858        notify_lifecycle("stopping", {"reason": termination, "instance_id": svc.instance_id})
10859        print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True)
10860    finally:
10861        cancelled = 0
10862        if a.shutdown_timeout is not None:
10863            pending = svc.begin_drain()
10864            notify_lifecycle("draining", {"instance_id": svc.instance_id,
10865                                          "pending_requests": pending,
10866                                          "deadline_s": a.shutdown_timeout})
10867            if pending:
10868                print(f"[strata] draining {pending} inference call(s) for up to {a.shutdown_timeout:g} s ...",
10869                      flush=True)
10870            pending = svc.wait_for_drain(a.shutdown_timeout)
10871            if pending:
10872                cancelled = svc.cancel_owned_requests()
10873                print(f"[strata] drain deadline expired; cancelling {cancelled} owned request(s) ...", flush=True)
10874                svc.wait_for_drain(5)
10875                drained = False
10876        else:
10877            # #6055: without --shutdown-timeout there is no wait, but a request that arrives while the engine closes is
10878            # still refused (503 server_draining, retry elsewhere) instead of being accepted and cut off with 0 tokens
10879            svc.begin_drain()
10880        closers =[httpd.shutdown, getattr(engine, "close", None), vision.shutdown if vision else None,
10881                   hub.close if hub is not None else None]
10882        try:
10883            for close in filter(None, closers):
10884                try:
10885                    close()
10886                except KeyboardInterrupt:               # a second Ctrl+C: don't wait for the engine to free its memory
10887                    if getattr(engine, "proc", None):
10888                        engine.proc.kill()
10889                        try:
10890                            from serve import cache_drop
10891                            cache_drop.drop_after_exit(engine)       # opt-in (STRATA_DROP_CACHE_ON_EXIT=1), default unchanged
10892                        except Exception as e:  # noqa: BLE001 - never block the exit
10893                            print(f"[strata] could not release the model files' cache: {e}", flush=True)
10894        finally:
10895            if ready_path is not None:
10896                ready_file.remove_if_owned(ready_path, svc.instance_id)
10897            finished.set()
10898        if interrupted:
10899            print("[strata] stopped", flush=True)
10900    exit_code = (8 if not drained else
10901                 interrupt_exit_code if interrupted and termination == "sigint" else 0)
10902    notify_lifecycle("stopped", {"instance_id": svc.instance_id, "reason": termination if interrupted else "normal",
10903                                 "drained": drained, "cancelled_requests": cancelled,
10904                                 "exit_code": exit_code})
10905    return exit_code
10906
10907
10908if __name__ == "__main__":
10909    sys.exit(main())