Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: owned-server contract for the terminal (ready file, owner guard, launch identity, queue deadline, stage telemetry)

Niko1221c968d37a48f9
diff --git a/serve/launch_identity.py b/serve/launch_identity.py
new file mode 100644
index 000000000..f405d8ed6
--- /dev/null
+++ b/serve/launch_identity.py
@@ -0,0 +1,22 @@
+"""Private proof of the configuration and arguments read by an owned server.
+
+The owner passes a fresh secret through the child environment, then compares
+this MAC with the value on the authenticated telemetry endpoint. The digest
+does not expose a reusable hash of the run config's credentials.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+
+
+def attestation(key: bytes, config_bytes: bytes, argv: list[str]) -> str:
+ if len(key) != 32 or not isinstance(config_bytes, bytes) or \
+ not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv):
+ raise ValueError("invalid launch attestation inputs")
+ args = json.dumps(argv, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+ message = b"strata-owned-launch-v1\0" + len(config_bytes).to_bytes(8, "big") + config_bytes + \
+ len(args).to_bytes(8, "big") + args
+ return hmac.new(key, message, hashlib.sha256).hexdigest()
diff --git a/serve/owner_guard.py b/serve/owner_guard.py
new file mode 100644
index 000000000..26bb64221
--- /dev/null
+++ b/serve/owner_guard.py
@@ -0,0 +1,35 @@
+"""Emergency parent-loss guard for a server launched by the local runtime host.
+
+The inherited pipe has exactly one writer, held by the host. EOF therefore
+means the host exited, including after SIGKILL. The server has its own process
+group so its engine subprocesses receive the emergency stop as well.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import stat
+import threading
+
+
+def start(fd: int) -> None:
+ if os.name != "posix" or fd < 0 or os.getpgrp() != os.getpid():
+ raise ValueError("--owner-fd requires a dedicated POSIX server process group")
+ if not stat.S_ISFIFO(os.fstat(fd).st_mode):
+ raise ValueError("--owner-fd must be an inherited pipe")
+
+ def watch() -> None:
+ try:
+ while os.read(fd, 1):
+ pass
+ # This is an emergency path. Signal the whole dedicated group so
+ # an engine already spawned during model loading cannot be orphaned.
+ os.killpg(os.getpgrp(), signal.SIGTERM)
+ except OSError:
+ # A broken guard must never authorize another process to manage us.
+ os.killpg(os.getpgrp(), signal.SIGTERM)
+ finally:
+ os.close(fd)
+
+ threading.Thread(target=watch, name="strata-owner-guard", daemon=True).start()
diff --git a/serve/ready.py b/serve/ready.py
new file mode 100644
index 000000000..1d8c440c9
--- /dev/null
+++ b/serve/ready.py
@@ -0,0 +1,46 @@
+"""Ready file for a foreground Strata server instance.
+
+A consumer must still compare the instance ID with live telemetry before acting.
+An abruptly killed process can leave this file behind; a stale file is never
+accepted as proof of a running model by this module.
+POSIX files use mode 0600; Windows access follows the parent directory ACL.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+
+def preflight(path: str) -> Path:
+ target = Path(path)
+ if not target.is_absolute():
+ raise ValueError("--ready-file must be an absolute path")
+ if not target.parent.is_dir():
+ raise ValueError("--ready-file parent directory must exist")
+ if target.exists() or target.is_symlink():
+ raise ValueError("--ready-file already exists; verify and remove a stale file before reuse")
+ return target
+
+
+def publish(path: Path, payload: dict) -> None:
+ data = (json.dumps(payload, ensure_ascii=False, allow_nan=False, sort_keys=True) + "\n").encode("utf-8")
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+
+
+def remove_if_owned(path: Path, instance_id: str) -> None:
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if isinstance(data, dict) and data.get("instance_id") == instance_id and data.get("pid") == os.getpid():
+ path.unlink(missing_ok=True)
+ except (OSError, ValueError):
+ pass
diff --git a/serve/replicas.py b/serve/replicas.py
index f788dea33..5a139efa8 100644
--- a/serve/replicas.py
+++ b/serve/replicas.py
@@ -392,6 +392,9 @@ class ReplicaEngine:
held = False
nonfinite = False
try:
+ selected = getattr(cancel, "_strata_replica_selected", None)
+ if selected is not None:
+ selected(k)
self.router.note(k, ids)
if not int(getattr(e, "batch", 0) or 0): # no slots: this replica takes one request at a time
lock = self.run_locks[k]
diff --git a/serve/server.py b/serve/server.py
index 3ca03b03b..901ea7147 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -62,6 +62,9 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro
tool_choice_of, unmark_think_literals)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve import runconfig # noqa: E402
+from serve import ready as ready_file # noqa: E402
+from serve import owner_guard # noqa: E402
+from serve import launch_identity # noqa: E402
from serve import logit_bias as bias_api # noqa: E402
from serve.winjob import contain # noqa: E402
from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402
@@ -287,19 +290,28 @@ class MockEngine:
"""Replays a scripted completion (text) as token ids, one per step, then the end-of-turn token. Given a list of
scripts, each request gets the next one and the last one repeats (a tool call, then the answer after it)."""
- def __init__(self, tokenizer, script: str | list[str], max_context: int = 32768, delay_s: float = 0.0):
+ def __init__(self, tokenizer, script: str | list[str], max_context: int = 32768, delay_s: float = 0.0,
+ cycle: bool = False):
self.tok, self.max_context, self.delay = tokenizer, max_context, delay_s
end = tokenizer.encode(IM_END, parse_special=True)
self.scripts = [tokenizer.encode(x, parse_special=True) + end for x in ([script] if isinstance(script, str)
else script)]
self.script, self.turns = self.scripts[0], 0
+ # `cycle` picks the script by request position instead of advancing to the last one and staying
+ # there. A harness adds requests the script author did not plan for -- a session title, a re-ask
+ # after a tool result -- and with the default behaviour one extra request shifts every later
+ # reply, so a run looks like a model that simply chose differently.
+ self.cycle = bool(cycle)
self.last_prompt: list[int] = []
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
self.last_prompt = list(ids)
self.last_embeddings = embeddings
if len(self.scripts) > 1:
- self.script = self.scripts[min(self.turns, len(self.scripts) - 1)]
+ if self.cycle:
+ self.script = self.scripts[self.turns % len(self.scripts)]
+ else:
+ self.script = self.scripts[min(self.turns, len(self.scripts) - 1)]
self.turns += 1
for t in self.script[:max_new]:
if cancel.is_set():
@@ -327,6 +339,14 @@ class ModelBusy(RuntimeError):
"""Explicit model controls must not interrupt active or queued requests."""
+class QueueWaitExpired(RuntimeError):
+ """An inference call waited too long for its first engine turn."""
+
+
+class QueueCancelled(RuntimeError):
+ """The client left before its first serial engine turn."""
+
+
class EngineSilent(EngineDied):
"""#481: the engine said nothing for too long during a request (or never acknowledged a STOP): the two sides lost
step - the engine waiting for its next command, the server for this request's end - and the server ended it. An
@@ -744,6 +764,101 @@ FATAL_PREFIXES = ("ERR verify: timed out at layer ", "ERR verify batch: timed ou
"ERR verify: an earlier window never finished", "ERR verify batch: an earlier window never finished")
+def parse_engine_stage_line(line: str) -> list[dict] | None:
+ """Accept only the engine's final, contiguous stage plan (inclusive layer ends)."""
+ prefix = "strata serve: layer split: layers "
+ suffix = ", one hand-off per window"
+ if not line.startswith(prefix) or not line.rstrip("\r\n").endswith(suffix):
+ return None
+ body = line.rstrip("\r\n")[len(prefix):-len(suffix)]
+ parts = body.split(", ")
+ if not 2 <= len(parts) <= 16:
+ return None
+ stages, next_layer = [], 0
+ for i, part in enumerate(parts):
+ match = re.fullmatch(r"([0-9]{1,5})-([0-9]{1,5}) \(CUDA([0-9]{1,2})\)", part)
+ if match is None:
+ return None
+ first, last, ordinal = map(int, match.groups())
+ if first != next_layer or last < first or last > 65535 or ordinal > 15:
+ return None
+ stages.append({"stage": i, "layer_start": first, "layer_end": last,
+ "engine_ordinal": ordinal})
+ next_layer = last + 1
+ return stages
+
+
+def read_engine_stage_log(path: str | None, start: int, limit: int = 2 << 20) -> list[dict]:
+ """Read this engine start only; oversized/unavailable logs leave placement unknown."""
+ if not path or start < 0:
+ return []
+ try:
+ with open(path, "rb") as source:
+ source.seek(start)
+ data = source.read(limit + 1)
+ except OSError:
+ return []
+ if len(data) > limit:
+ return []
+ for line in reversed(data.decode("utf-8", errors="replace").splitlines()):
+ stages = parse_engine_stage_line(line)
+ if stages is not None:
+ return stages
+ return []
+
+
+def visible_device_order(env: dict | None, backend: str | None) -> list[int]:
+ """Map engine ordinals to OS GPU indices only when the visibility list is unambiguous."""
+ if backend not in (None, "cuda", "hip"):
+ return []
+ if backend != "hip" and (env or {}).get("CUDA_DEVICE_ORDER") != "PCI_BUS_ID":
+ return []
+ name = "HIP_VISIBLE_DEVICES" if backend == "hip" else "CUDA_VISIBLE_DEVICES"
+ value = (env or {}).get(name)
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,5}(?:,[0-9]{1,5}){0,15}", value):
+ return []
+ devices = [int(part) for part in value.split(",")]
+ return devices if all(0 <= device <= 65535 for device in devices) and len(set(devices)) == len(devices) else []
+
+
+def configure_batch_telemetry_env(env: dict, cfg: dict, override: bool | None) -> None:
+ """Only an explicit setting changes the inherited opt-in engine environment."""
+ choice = override if override is not None else cfg.get("batch_telemetry")
+ if choice is True:
+ env["STRATA_BATCH_TELEMETRY"] = "1"
+ elif choice is False:
+ env.pop("STRATA_BATCH_TELEMETRY", None)
+
+
+def parse_batch_window_sample(line: str) -> dict | None:
+ """Read an opt-in engine BSTAT sample; rows are verifier work, not emitted tokens."""
+ if len(line) > 80:
+ return None
+ match = re.fullmatch(r"BSTAT ([1-9][0-9]{0,8}) ([1-9][0-9]{0,9}) "
+ r"([1-9][0-9]{0,9}) ([1-9][0-9]{0,9})\r?\n?", line)
+ if match is None:
+ return None
+ windows, rows, active, elapsed_ms = map(int, match.groups())
+ if rows > windows * 8 or active > rows or elapsed_ms > 86_400_000:
+ return None
+ return {"windows": windows, "processed_rows": rows, "active_rows": active,
+ "elapsed_ms": elapsed_ms}
+
+
+def parse_stage_in_flight_sample(line: str) -> dict | None:
+ """Read bounded PSTAT host scheduling spans; these are not GPU utilization."""
+ if len(line) > 256 or re.fullmatch(
+ 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:
+ return None
+ parts = line.strip().split(" ")
+ stages, elapsed_us = int(parts[1]), int(parts[2])
+ in_flight_us = [int(value) for value in parts[3:]]
+ if len(in_flight_us) != stages or elapsed_us > 86_400_000_000 or \
+ any(value > elapsed_us for value in in_flight_us):
+ return None
+ return {"elapsed_us": elapsed_us, "in_flight_us": in_flight_us}
+
+
class StrataEngine:
"""The resident engine: `strata --serve` reads `GEN <max_new> <ids>` lines and streams `T <id>` lines, then
`DONE ...`. Requests are serialized by the service's FIFO, so one pipe is enough.
@@ -789,6 +904,9 @@ class StrataEngine:
self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)
self.last = {}
self.info = {} # INFO key=value facts (engine 0.1.8+): kv, expert slots, ... (Monitor tab)
+ self.terminal_stages: list[dict] = [] # final layer ranges from this engine start's bounded stderr log
+ self.terminal_batch_sample: dict | None = None
+ self.terminal_stage_sample: dict | None = None
self.prefill_tok_s_mean = None
self.progress = None # (read, total) prompt tokens while a prompt is read, from PP lines
self.progress_ms = 0 # PP's own milliseconds since the prompt started (its third field)
@@ -902,6 +1020,7 @@ class StrataEngine:
# report their own version (INFO engine=, 0.1.8+) win, the manifest stays the fallback for older ones
if self.info.get("engine"):
self.info["version"] = str(self.info["engine"])
+ self.terminal_stages = read_engine_stage_log(log, log_start) if log else []
self.ended = False # READY: alive from here (restart() set it True, #344)
# the engine's stdout on a thread, so a request can wait with a timeout (heartbeats, cancel checks)
self.lines: queue.Queue = queue.Queue()
@@ -975,6 +1094,16 @@ class StrataEngine:
except OSError:
pass
break # publish EOF, never the trailing DONE
+ if line.startswith("BSTAT"):
+ sample = parse_batch_window_sample(line)
+ if sample is not None and self.proc is proc:
+ self.terminal_batch_sample = {**sample, "observed_monotonic": time.monotonic()}
+ continue # control telemetry never enters a request's token stream
+ if line.startswith("PSTAT"):
+ sample = parse_stage_in_flight_sample(line)
+ if sample is not None and self.proc is proc:
+ self.terminal_stage_sample = {**sample, "observed_monotonic": time.monotonic()}
+ continue
if line.startswith(("BT ", "BDONE ")) and slot_q: # --batch: a batch slot's own lines
try:
slot_q[int(line.split()[1])].put(line)
@@ -1436,6 +1565,9 @@ class StrataEngine:
beat = time.monotonic()
try:
while True:
+ deadline = getattr(cancel, "_strata_queue_deadline", None)
+ if deadline is not None and time.monotonic() >= deadline:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
if not self.alive() and not getattr(self, "starting", False):
# #1012: the engine is gone and nobody is starting it again: this request was not sent, so it
# ends now (a clean 503) instead of waiting for control lines nothing will answer on. While a
@@ -1445,7 +1577,8 @@ class StrataEngine:
turn = after_epoch is None or self.ctl_epoch > after_epoch or self.waiting <= 1
if turn and new and ADMIT_SHORT_FIRST > 0:
turn = self._admit_next() is entry
- if turn and self.ctl.acquire(timeout=0.5):
+ left = deadline - time.monotonic() if deadline is not None else 0.5
+ if turn and left > 0 and self.ctl.acquire(timeout=min(0.5, left)):
if new and ADMIT_SHORT_FIRST > 0:
with self.slot_cv: # a shorter one came while this one waited in acquire()
first = self._admit_next() is entry
@@ -1455,12 +1588,15 @@ class StrataEngine:
self.slot_cv.notify_all()
continue
if self.alive():
+ if deadline is not None and time.monotonic() >= deadline:
+ self.ctl.release()
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
break
self.ctl.release() # it died (or is being restarted) while this one was getting
turn = False # the lines: not the engine this request was meant for
if not turn:
with self.slot_cv:
- self.slot_cv.wait(timeout=0.5)
+ self.slot_cv.wait(timeout=min(0.5, max(0, left)))
if cancel.is_set():
return False
if time.monotonic() - beat >= 10.0: # a heartbeat every 10 s, as the engine's own wait
@@ -1547,7 +1683,15 @@ class StrataEngine:
if alone and left > 1:
head = f"GENI {left}{keys} {embeddings}" if embeddings else f"GEN {left}{keys}"
self._last_done = None # (#879: this request's DONE decides below)
+ deadline = getattr(cancel, "_strata_queue_deadline", None)
+ if deadline is not None and time.monotonic() >= deadline:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
+ if deadline is not None:
+ cancel._strata_queue_deadline = None
+ started = getattr(cancel, "_strata_queue_started", None)
+ if started is not None:
+ started()
phase = "solo"
self._ctl_mode, self._ctl_result, self._yielded = "solo", None, None
self._ctl_erred = False
@@ -1607,6 +1751,9 @@ class StrataEngine:
# that gave way (BYIELD) and needs them to go on, so waiting with them is a deadlock - long,
# long, short at 0.25 s steps under parallel: 2 (ENGINE_REVIEW finding 1, reproduced in 0.1.41).
while True:
+ deadline = getattr(cancel, "_strata_queue_deadline", None)
+ if deadline is not None and time.monotonic() >= deadline:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
with self.slot_cv:
slot = self.pick_slot(prompt)
if slot is not None:
@@ -1635,7 +1782,8 @@ class StrataEngine:
f"ending: {sorted(self.slot_releasing)}) (issue #1603)", flush=True)
self._reap_orphan_slots()
if self.pick_slot(prompt) is None:
- self.slot_cv.wait(timeout=1.0)
+ wait_remaining = deadline - time.monotonic() if deadline is not None else 1.0
+ self.slot_cv.wait(timeout=min(1.0, max(0, wait_remaining)))
if cancel.is_set():
return
if not holding:
@@ -1658,11 +1806,20 @@ class StrataEngine:
while not self.slot_q[slot].empty():
self.slot_q[slot].get_nowait()
head = f"BGENI {slot} {left}{keys} {embeddings}" if embeddings else f"BGEN {slot} {left}{keys}"
- live = {"slot": slot, "state": "reading", "prompt_tokens": len(prompt), "generated": 0,
+ live = {"slot": slot, "request_id": getattr(cancel, "_strata_request_id", None),
+ "state": "reading", "prompt_tokens": len(prompt), "prompt_read": 0, "generated": 0,
"started": time.time(), "first_token": None}
+ deadline = getattr(cancel, "_strata_queue_deadline", None)
+ if deadline is not None and time.monotonic() >= deadline:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
self.slot_live[slot] = live
self._last_done = None # (#879: this admission's DONE decides below)
self._send(f"{head} {','.join(str(int(t)) for t in prompt)}")
+ if deadline is not None:
+ cancel._strata_queue_deadline = None
+ started = getattr(cancel, "_strata_queue_started", None)
+ if started is not None:
+ started()
self.slot_held[slot] = [] # the admission overwrites what the slot held
phase = "admit"
self._ctl_mode, self._ctl_result, self._yielded = "batch", None, None
@@ -1675,14 +1832,20 @@ class StrataEngine:
self._shorter_waiting(len(prompt))):
self._send(f"BYIELD {slot}")
asked = True
+
+ def note_progress():
+ # the terminal layer's live prompt counter (the batch admission path)
+ if self.progress and live["state"] == "reading":
+ live["prompt_read"] = self.progress[0]
try:
- for x in self._control(cancel, pending.append, on_quiet=ask):
+ for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress())):
while pending:
t = pending.pop(0)
out.append(t)
yield t
if x is None:
ask()
+ note_progress()
yield None
except ValueError as e:
# #1994: the engine says this slot is not free (its view and ours differ for a moment, or a
@@ -1892,6 +2055,7 @@ class StrataEngine:
continue
ft = r.get("first_token")
view.append({"slot": b, "state": r["state"], "prompt_tokens": r["prompt_tokens"],
+ "prompt_read": r.get("prompt_read") if r["state"] == "reading" else None,
"generated": r["generated"], "elapsed_s": round(now - r["started"], 1),
"tok_s": round(r["generated"] / max(1e-6, now - ft), 1) if ft else None})
return view
@@ -2830,7 +2994,7 @@ def ordered_gpus(cfg: dict, scores=None, vrams=None) -> list[int]:
return out
-def child_env(cfg: dict) -> dict:
+def child_env(cfg: dict, *, offline: bool = False) -> dict:
"""The engine's environment: the CUDA libraries setup installed (pip's nvidia packages, or the toolkit that
compiled it) first on the library search path."""
env = dict(os.environ)
@@ -2841,6 +3005,19 @@ def child_env(cfg: dict) -> dict:
env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in ordered_gpus(cfg))
for k, v in (cfg.get("env") or {}).items(): # engine settings the config carries (AMD: the GEMM tuning table)
env[str(k)] = str(v)
+ # Strict offline reaches children through the environment, because a tool subprocess or a model
+ # loader is code this server does not own. Applied last so a profile's own `env` cannot remove
+ # the policy by naming the same variable.
+ if offline:
+ try:
+ from strata_control import offline as offline_policy
+ env.update(offline_policy.OFFLINE_ENV)
+ except ImportError:
+ # The policy module is part of the application; without it, refuse rather than silently
+ # running a child with network access under a flag that promised otherwise.
+ env["STRATA_OFFLINE"] = "1"
+ env["HF_HUB_OFFLINE"] = "1"
+ env["TRANSFORMERS_OFFLINE"] = "1"
dirs = [d for d in cfg.get("lib_dirs") or [] if Path(d).is_dir()]
if dirs:
var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
@@ -3109,6 +3286,20 @@ class Service:
# "parallel" (the engine's batch slots): every running request's own status and rate window; self.status
# then says busy while any runs and shows the newest one
self.live_reqs: dict[int, tuple[dict, collections.deque]] = {}
+ # Privacy-safe correlation for terminal telemetry. No prompts, client identity or tool text is stored.
+ self.terminal_requests: dict[str, dict] = {}
+ self.terminal_events = collections.deque(maxlen=128) # fixed-shape request transitions only
+ self.terminal_event_seq = 0
+ # HTTP admission is reserved before generation or SSE headers. This bounds pending inference calls even
+ # while a model is loading or a request is between MCP rounds; the engine's own slots remain unchanged.
+ self.max_queue: int | None = None
+ self.queue_timeout_s: float | None = None
+ self.admission_reserved = 0
+ self.admission_rejected = 0
+ self.queue_timeouts = 0
+ self.client_disconnect_cancels = 0
+ self.draining = False
+ self.active_cancels: set[threading.Event] = set()
# #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory,
# so it is off unless the config's "api_monitor" (or --api-monitor) turns it on
self.api_monitor = False
@@ -3127,8 +3318,12 @@ class Service:
self.latencies = Latencies() # GET /metrics in Prometheus text: the latency histograms
self.last_request_at = None # when a request last started or finished
self.started_at = time.time()
+ self.instance_id = uuid.uuid4().hex
self.status_lock = threading.Lock()
+ self.admission_changed = threading.Condition(self.status_lock)
self.mcp = None # serve/mcp.py's McpHub when MCP servers are configured
+ self.offline = False # no image URL fetch or MCP subprocess in strict local mode
+ self.telemetry_key = "" # optional read-only key, valid only on /v1/telemetry
# sharing the GPU with other programs (all off by default): unload the engine after this many idle seconds,
# only start it again when this much VRAM is free, and run this command first (e.g. to unload another
# server's model); the next request after an unload starts the engine again
@@ -3156,6 +3351,101 @@ class Service:
def loaded(self) -> bool:
return not hasattr(self.engine, "alive") or self.engine.alive()
+ def admission_limit(self) -> int | None:
+ if self.max_queue is None:
+ return None
+ return max(1, int(getattr(self.engine, "batch", 0) or 0)) + self.max_queue
+
+ def _terminal_event_locked(self, request_id: str, event: str, outcome: str | None = None) -> None:
+ """Append one redacted transition while holding status_lock; never include request content."""
+ if event not in ("queued", "admitted", "reading", "first_token", "finished", "cancelled",
+ "disconnected", "timeout", "error"):
+ return
+ if outcome is not None and outcome not in ("stop", "length", "cancel", "disconnect", "timeout", "error"):
+ outcome = "error"
+ self.terminal_event_seq += 1
+ row = {"seq": self.terminal_event_seq, "at": time.time(),
+ "request_id": request_id, "event": event}
+ if outcome is not None:
+ row["outcome"] = outcome
+ self.terminal_events.append(row)
+
+ def reserve_inference(self) -> bool | None:
+ """Reserve one bounded HTTP inference call before response headers are written."""
+ with self.status_lock:
+ if self.draining:
+ return None
+ limit = self.admission_limit()
+ if limit is not None and self.admission_reserved >= limit:
+ self.admission_rejected += 1
+ return False
+ self.admission_reserved += 1
+ return True
+
+ def release_inference(self) -> None:
+ with self.admission_changed:
+ self.admission_reserved -= 1
+ self.admission_changed.notify_all()
+
+ def note_client_disconnect(self, cancel: threading.Event) -> None:
+ """Cancel once; count only work that was still queued or active when the client left."""
+ with self.status_lock:
+ if not cancel.is_set():
+ request_id = getattr(cancel, "_strata_request_id", None)
+ active = request_id in self.terminal_requests
+ cancel.set()
+ if active:
+ self.client_disconnect_cancels += 1
+
+ @contextlib.contextmanager
+ def _inference_fifo(self, deadline: float | None, cancel: threading.Event | None = None):
+ if deadline is None:
+ with self.fifo:
+ yield
+ return
+ while True:
+ if cancel is not None and cancel.is_set():
+ raise QueueCancelled("the client disconnected while waiting for the engine")
+ left = deadline - time.monotonic()
+ if left <= 0:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
+ if self.fifo.acquire(timeout=min(0.1, left)):
+ break
+ try:
+ if cancel is not None and cancel.is_set():
+ raise QueueCancelled("the client disconnected while waiting for the engine")
+ if time.monotonic() >= deadline:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
+ yield
+ finally:
+ self.fifo.release()
+
+ def begin_drain(self) -> int:
+ """Stop new inference admission and return the number of owned calls to drain."""
+ with self.admission_changed:
+ self.draining = True
+ self.admission_changed.notify_all()
+ return self.admission_reserved
+
+ def wait_for_drain(self, timeout: float) -> int:
+ """Wait for reserved inference calls; return the number still in flight."""
+ deadline = time.monotonic() + max(0.0, timeout)
+ with self.admission_changed:
+ while self.admission_reserved:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ break
+ self.admission_changed.wait(left)
+ return self.admission_reserved
+
+ def cancel_owned_requests(self) -> int:
+ """Cancel only requests admitted by this Service, never unrelated GPU work."""
+ with self.status_lock:
+ active = list(self.active_cancels)
+ for cancel in active:
+ cancel.set()
+ return len(active)
+
def slot_action(self, slot: str, action: str, filename) -> tuple[int, dict]:
"""llama-server's POST /slots/{id}?action=save|restore {"filename": ...}: the conversation the engine holds,
to or from a file in slot_save_path. -> (HTTP status, body)."""
@@ -3785,6 +4075,7 @@ class Service:
with self.status_lock:
s, totals = dict(self.status), dict(self.totals)
last_t, last_at = (dict(self.last_timings) if self.last_timings else None), self.last_request_at
+ running = len(self.live_reqs) if self.live_reqs else int(bool(s.get("busy")))
tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "static": {}}
hw, static = tel.get("now") or {}, tel.get("static") or {}
@@ -3804,11 +4095,12 @@ class Service:
"context": {"native": ctx, "max_positions": ctx},
# one request at a time (more wait their turn), or "parallel": N batch slots (#465)
"concurrency": {"serving": max(1, int(getattr(self.engine, "batch", 0) or 0)),
- "requested": max(1, int(getattr(self.engine, "batch", 0) or 0))},
+ "requested": getattr(self, "requested_slots", max(1, int(getattr(self.engine, "batch", 0) or 0)))},
"dialects": ["/v1/chat/completions", "/v1/messages", "/v1/responses"],
"vision": {"enabled": images, "available": images, "error": None},
"image_generation": self.images.status() if self.images is not None else {"enabled": False},
- "activity": {"requests": totals["requests"] + int(busy), "in_flight": int(busy) + int(s.get("queued") or 0),
+ "activity": {"requests": totals["requests"] + running,
+ "in_flight": running + int(s.get("queued") or 0),
"last_request_at": int(last_at) if last_at else None},
"last_timings": last_t,
"vram": dict((getattr(self.engine, "info", {}) or {}).get("vram") or {},
@@ -3886,6 +4178,8 @@ class Service:
try:
if cancel is not None and cancel.is_set():
raise ClientGone()
+ if self.offline and src.startswith(("http://", "https://")):
+ raise ValueError("offline mode cannot download an image URL")
if src.startswith(("http://", "https://")):
src = fetched[item["source"]] = Vision.download(src) # outside the FIFO, as in prepare()
with self._turn(cancel): # the encoder takes its turn with the requests (see below)
@@ -3911,6 +4205,8 @@ class Service:
self.embeddings.keys = None
images = images_of(messages)
if images:
+ if self.offline and any(src.startswith(("http://", "https://")) for src in images):
+ raise ValueError("offline mode cannot download an image URL; send a data: image instead")
if self.vision is None:
raise ValueError("this server was started without the vision encoder (run setup again and choose "
"'vision'), so it cannot read images")
@@ -4186,42 +4482,65 @@ class Service:
# one arrived. A reasoning-budget continuation is another native generation, not another API request,
# so the generated reasoning must not become this request's cached input (#615).
segments = []
+ timed_out = False
trace = getattr(self.request_trace, "record", None)
waiting = time.perf_counter()
+ first_engine_token_s = None # this request, from entering the engine queue; includes queue/prefill
# #465: with "parallel" (the engine's batch slots) requests run at once: each keeps its own status and rate
# window (self.status says busy while any runs); one at a time they are self.status / self.rate, as before
par = bool(getattr(self.engine, "batch", 0))
st = {} if par else self.status
rate = collections.deque(maxlen=32) if par else self.rate
+ request_id = uuid.uuid4().hex[:12]
+ setattr(cancel, "_strata_request_id", request_id)
+ deadline = time.monotonic() + self.queue_timeout_s if self.queue_timeout_s is not None else None
+ if deadline is not None:
+ setattr(cancel, "_strata_queue_deadline", deadline)
+ def queue_started():
+ with self.status_lock:
+ row = self.terminal_requests.get(request_id)
+ if row is not None and row["state"] != "reading":
+ row["state"] = "reading"
+ self._terminal_event_locked(request_id, "reading")
+ setattr(cancel, "_strata_queue_started", queue_started)
+ def replica_selected(index: int) -> None:
+ with self.status_lock:
+ row = self.terminal_requests.get(request_id)
+ if row is not None:
+ row["replica"] = index
+ setattr(cancel, "_strata_replica_selected", replica_selected)
with self.status_lock:
self.status["queued"] += 1
+ self.terminal_requests[request_id] = {"id": request_id, "state": "queued",
+ "queued_at": time.time(), "admitted_at": None,
+ "prompt_tokens": len(ids)}
+ self._terminal_event_locked(request_id, "queued")
+ queued_counted = True
try:
# --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them)
turn = contextlib.ExitStack()
- if not getattr(self.engine, "batch", 0):
+ if not par:
# #1619: a request waiting for the single turn sends a keep-alive every QUEUE_BEAT_S, so a client with
# a stream idle timeout does not abort a healthy queued request (and its retry read the prompt again);
# a client that left while queued gives its place up instead of taking the turn only to cancel there
got = False
- try:
- while not got:
- got = self.fifo.acquire(timeout=QUEUE_BEAT_S)
- if got:
- turn.callback(self.fifo.release)
- elif cancel.is_set():
- break
- else:
- yield "ping", None
- except BaseException: # the consumer closed us at a ping: no longer queued
- with self.status_lock:
- self.status["queued"] -= 1
- raise
- if not got: # cancelled while queued
- with self.status_lock:
- self.status["queued"] -= 1
- yield "done", {"finish": "cancel", "completion_tokens": 0, "reused": 0, "timings": None,
- "reasoning_tokens": 0, "reasoning_recoveries": 0}
- return
+ while not got:
+ if cancel.is_set():
+ raise QueueCancelled("the client disconnected while waiting for the engine")
+ left = deadline - time.monotonic() if deadline is not None else QUEUE_BEAT_S
+ if left <= 0:
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
+ got = self.fifo.acquire(timeout=min(QUEUE_BEAT_S, left))
+ if got:
+ if cancel.is_set():
+ self.fifo.release()
+ raise QueueCancelled("the client disconnected while waiting for the engine")
+ if deadline is not None and time.monotonic() >= deadline:
+ self.fifo.release()
+ raise QueueWaitExpired("the inference queue wait deadline expired; retry later")
+ turn.callback(self.fifo.release)
+ else:
+ yield "ping", None
with turn:
try:
with self.status_lock:
@@ -4230,25 +4549,25 @@ class Service:
trace["state"] = "generating"
if not par:
self.status["queued"] -= 1
+ queued_counted = False
+ self.terminal_requests[request_id].update(state="admitted", admitted_at=time.time())
+ self._terminal_event_locked(request_id, "admitted")
# issue #27: it died in an earlier request (or was unloaded) - start it again instead of failing
# (parallel requests do not hold the fifo: one of them starts it, the others wait for that).
# #1603: a parallel request stays counted as queued until it is registered as running below -
# waiting here for the fifo (an image encode, a /v1/vram resize) left it neither - and one on a
# loaded engine has nothing to start, so it does not wait for the fifo at all
- try:
- if not par:
+ if not par:
+ self.ensure_loaded()
+ elif not (self.loaded() and not self._vision_down()):
+ with self._inference_fifo(deadline, cancel):
self.ensure_loaded()
- elif not (self.loaded() and not self._vision_down()):
- with self.fifo:
- self.ensure_loaded()
- except BaseException:
- if par:
- with self.status_lock:
- self.status["queued"] -= 1
- raise
with self.status_lock:
if par:
self.status["queued"] -= 1
+ queued_counted = False
+ self.terminal_requests[request_id].update(state="waiting", admitted_at=time.time())
+ self._terminal_event_locked(request_id, "admitted")
st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids),
generated=0, started=time.time(), first_token=None, tool=None, tail="",
max_tokens=max_new, reasoning_recoveries=0, thinking_budget=budget)
@@ -4284,6 +4603,13 @@ class Service:
yield "ping", None
continue
n += 1
+ if first_engine_token_s is None:
+ first_engine_token_s = round(time.perf_counter() - waiting, 3)
+ with self.status_lock:
+ row = self.terminal_requests.get(request_id)
+ if row is not None:
+ row["first_engine_token_s"] = first_engine_token_s
+ self._terminal_event_locked(request_id, "first_token")
if trace is not None and trace["first_token_s"] is None:
with self.status_lock:
trace["first_token_s"] = round(time.perf_counter() - trace["_clock"], 3)
@@ -4352,6 +4678,10 @@ class Service:
finish = "error"
self._say_died(e)
raise
+ except QueueWaitExpired:
+ finish = "error"
+ timed_out = True
+ raise
except ValueError as e: # the engine's ERR line (it may have ended after it)
finish = "error"
print(f"[strata] the engine reported an error: {e}", flush=True)
@@ -4485,7 +4815,7 @@ class Service:
# #266: settle this request's status, history and totals while still holding the fifo: once
# it is released the next request sets its own status, which this must not record or clear
with self.status_lock:
- if st.get("busy"):
+ if st.get("busy") and not timed_out:
last = request_stats(segments) # only this request's own DONEs count
started = st.get("started", time.time())
cvec = (getattr(self.engine, "info", {}) or {}).get("cvec", 0)
@@ -4498,10 +4828,12 @@ class Service:
if last.get("offloaded") is not None and routed else None
seen = prompt_tokens_seen(len(ids), last) # #471: < len(ids) when cancelled mid-read
self.history.append({
+ "id": request_id,
"projection": (sampling or {}).get("experimental_speed_projection") is not False
if loaded else None,
"time": started, "duration_s": round(time.time() - started, 1), "finish": finish,
"prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n,
+ "first_engine_token_s": first_engine_token_s,
# the request's whole prompt, and the tokens read of it (None: an older engine)
"prompt_total": len(ids), "prompt_read": last.get("prompt_read"),
"reasoning_recoveries": recovery_count,
@@ -4558,7 +4890,27 @@ class Service:
self.status.update(busy=False)
self.status.pop("tail", None)
self.status.pop("tool", None)
+ except QueueCancelled:
+ finish = "cancel"
+ yield "done", {"finish": "cancel", "completion_tokens": 0, "reused": 0, "timings": None,
+ "reasoning_tokens": 0, "reasoning_recoveries": 0}
+ return
+ except QueueWaitExpired:
+ finish = "timeout"
+ with self.status_lock:
+ self.queue_timeouts += 1
+ raise
+ except Exception:
+ finish = "error"
+ raise
finally:
+ with self.status_lock:
+ if queued_counted:
+ self.status["queued"] -= 1
+ self.terminal_requests.pop(request_id, None)
+ event = {"stop": "finished", "length": "finished", "cancel": "cancelled",
+ "disconnect": "disconnected", "timeout": "timeout", "error": "error"}.get(finish, "error")
+ self._terminal_event_locked(request_id, event, finish)
if emb:
Path(emb).unlink(missing_ok=True)
for ev in cut(parser.finish(finish)):
@@ -5048,6 +5400,7 @@ def make_handler(svc: Service):
record = None # #332: this request's monitor record, if kept
watch_done = None # #430 #431: stops this request's disconnect watcher
+ cancel_event = None # active generation owned by this handler
body_read = False # whether a handler took this request's body
DRAIN_SECONDS = 5 # the longest an unread body is read and dropped
@@ -5217,6 +5570,9 @@ def make_handler(svc: Service):
was done. Every 0.5 s: the socket readable with nothing to read (EOF) means the client closed it. A
request is HTTP/1.0 and fully read here, so no later bytes are expected - data is not a hang-up."""
done = self.watch_done = threading.Event()
+ self.cancel_event = cancel
+ with svc.status_lock:
+ svc.active_cancels.add(cancel)
sock = self.connection
def watch():
@@ -5228,9 +5584,9 @@ def make_handler(svc: Service):
gone = True
except (OSError, ValueError): # the socket was closed here: the request has ended
return
- if gone:
+ if gone and not done.is_set():
self._note(outcome="disconnected")
- cancel.set()
+ svc.note_client_disconnect(cancel)
return
threading.Thread(target=watch, daemon=True, name="strata-client-watch").start()
@@ -5269,7 +5625,7 @@ def make_handler(svc: Service):
self.send_header("Content-Length", "0")
self.end_headers()
- def _json(self, code, obj, headers=None):
+ def _json(self, code, obj, headers=None, retry_after=None):
if self.record is not None:
with svc.status_lock:
self.record["http_status"] = code
@@ -5283,6 +5639,8 @@ def make_handler(svc: Service):
self.send_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
self.send_header(k, str(v))
+ if retry_after is not None:
+ self.send_header("Retry-After", str(retry_after))
self._cors()
self.send_header("Content-Length", str(len(body)))
self.end_headers()
@@ -5298,6 +5656,17 @@ def make_handler(svc: Service):
self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}})
return False
+ def _authorized_telemetry(self) -> bool:
+ if not svc.api_key and not svc.telemetry_key:
+ return True
+ auth = self.headers.get("Authorization", "")
+ given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")
+ if (svc.api_key and key_matches(given, svc.api_key)) or \
+ (svc.telemetry_key and key_matches(given, svc.telemetry_key)):
+ return True
+ self._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong telemetry key"}})
+ return False
+
def do_GET(self):
path = self.path.split("?")[0].rstrip("/")
if path.startswith("/fonts/"):
@@ -5357,6 +5726,181 @@ def make_handler(svc: Service):
# the last 12 requests; `?requests=all` every one kept (the Monitor's "Show all", issue #35)
self._json(200, svc.metrics(all_requests="requests=all" in self.path))
return
+ if path == "/v1/telemetry":
+ if self._authorized_telemetry():
+ from strata_cli.client import normalize_legacy
+ snapshot = normalize_legacy(svc.metrics(), svc.v1_status())
+ snapshot["source"] = "server-v1"
+ snapshot["work"]["slots_requested"] = getattr(svc, "requested_slots", None)
+ # Keep /metrics' established slot shape intact; enrich only this versioned contract.
+ replica_engines = (getattr(svc.engine, "engines", None)
+ if hasattr(svc.engine, "replica_view") else None)
+ if replica_engines:
+ groups, live_slots, replica_by_slot = [], [], []
+ group_base = 0
+ all_batched = True
+ for replica, child in enumerate(replica_engines):
+ count = int(getattr(child, "batch", 0) or 0)
+ all_batched = all_batched and count > 0
+ count = max(1, count)
+ child_groups = getattr(child, "slot_group", [])
+ child_live = getattr(child, "slot_live", [])
+ for local in range(count):
+ group = child_groups[local] if local < len(child_groups) else None
+ groups.append(group_base + group if type(group) is int and group >= 0 else None)
+ live_slots.append(child_live[local] if local < len(child_live) else None)
+ replica_by_slot.append(replica)
+ group_base += int(getattr(child, "slot_groups", 0) or 0)
+ snapshot["work"]["groups"] = group_base if all_batched and group_base > 0 else None
+ else:
+ groups = getattr(svc.engine, "slot_group", [])
+ live_slots = getattr(svc.engine, "slot_live", [])
+ replica_by_slot = []
+ for slot in snapshot["work"]["slots"]:
+ i = slot.get("slot")
+ if type(i) is int and 0 <= i < len(groups):
+ slot["group"] = groups[i]
+ if type(i) is int and 0 <= i < len(replica_by_slot):
+ slot["replica"] = replica_by_slot[i]
+ if type(i) is int and 0 <= i < len(live_slots) and live_slots[i]:
+ slot["request_id"] = live_slots[i].get("request_id")
+ slot_by_id = {slot.get("request_id"): slot for slot in snapshot["work"]["slots"]
+ if slot.get("request_id")}
+ with svc.status_lock:
+ active = list(svc.terminal_requests.values())
+ snapshot["activity"] = {"last_seq": svc.terminal_event_seq,
+ "events": list(svc.terminal_events)[-32:]}
+ draining = svc.draining
+ admission_reserved = svc.admission_reserved
+ admission_rejected = svc.admission_rejected
+ queue_timeouts = svc.queue_timeouts
+ client_disconnect_cancels = svc.client_disconnect_cancels
+ in_flight_tokens = (sum(max(0, int(st.get("generated") or 0))
+ for st, _ in svc.live_reqs.values())
+ if svc.live_reqs else
+ max(0, int(svc.status.get("generated") or 0))
+ if svc.status.get("busy") else 0)
+ output_counter = int(svc.totals.get("output_tokens") or 0) + in_flight_tokens
+ snapshot["instance"]["id"] = svc.instance_id
+ snapshot["instance"]["state"] = "draining" if draining else "ready"
+ if getattr(svc, "launch_attestation", None) is not None:
+ snapshot["instance"]["launch_attestation"] = svc.launch_attestation
+ snapshot["rates"]["output_tokens_server_counter"] = output_counter
+ snapshot["work"]["requests_omitted"] = max(0, len(active) - 50)
+ snapshot["work"].update(max_queue=svc.max_queue, queue_timeout_s=svc.queue_timeout_s,
+ queue_timeouts=queue_timeouts,
+ client_disconnect_cancels=client_disconnect_cancels,
+ admission_limit=svc.admission_limit(),
+ admission_reserved=admission_reserved,
+ admission_rejected=admission_rejected,
+ oldest_queue_s=max((max(0, time.time() - row["queued_at"])
+ for row in active if row["state"] in ("queued", "waiting")),
+ default=0))
+ snapshot["work"]["requests"] = [
+ {**row, "state": slot_by_id[row["id"]]["state"] if row["id"] in slot_by_id else row["state"],
+ "slot": slot_by_id[row["id"]]["slot"] if row["id"] in slot_by_id else None,
+ "group": slot_by_id[row["id"]]["group"] if row["id"] in slot_by_id else None,
+ "replica": slot_by_id[row["id"]]["replica"] if row["id"] in slot_by_id else row.get("replica"),
+ "generated": slot_by_id[row["id"]].get("generated") if row["id"] in slot_by_id else None,
+ "prompt_read": slot_by_id[row["id"]].get("prompt_read") if row["id"] in slot_by_id else None}
+ for row in active[:50]]
+ snapshot["quality"]["request_correlation"] = "reported"
+ batch_sample = (getattr(svc.engine, "terminal_batch_sample", None)
+ if svc.loaded() and not replica_engines else None)
+ if replica_engines:
+ replica_batches = []
+ for replica, child in enumerate(replica_engines[:16]):
+ row = {"replica": replica}
+ sample = (getattr(child, "terminal_batch_sample", None)
+ if child.alive() else None)
+ if sample:
+ row.update(batch_sample_windows=sample["windows"],
+ batch_sample_rows=sample["processed_rows"],
+ batch_sample_active_rows=sample["active_rows"],
+ batch_sample_span_s=sample["elapsed_ms"] / 1000.0,
+ batch_sample_age_s=max(0.0, time.monotonic() -
+ sample["observed_monotonic"]))
+ replica_batches.append(row)
+ snapshot["work"]["replica_batches"] = replica_batches
+ if batch_sample:
+ windows = batch_sample["windows"]
+ snapshot["work"].update(effective_rows_window=batch_sample["processed_rows"] / windows,
+ batch_active_rows_window=batch_sample["active_rows"] / windows,
+ batch_sample_windows=windows,
+ batch_sample_rows=batch_sample["processed_rows"],
+ batch_sample_active_rows=batch_sample["active_rows"],
+ batch_sample_span_s=batch_sample["elapsed_ms"] / 1000.0,
+ batch_sample_age_s=max(0.0, time.monotonic() -
+ batch_sample["observed_monotonic"]))
+ snapshot["quality"]["batch_window_rows"] = "measured"
+ snapshot["quality"]["batch_window_source"] = "engine_bstat"
+ stage_sample = (getattr(svc.engine, "terminal_stage_sample", None)
+ if svc.loaded() and not replica_engines else None)
+ if replica_engines:
+ replica_stage_samples = []
+ for replica, child in enumerate(replica_engines[:16]):
+ row = {"replica": replica}
+ sample = (getattr(child, "terminal_stage_sample", None)
+ if child.alive() else None)
+ if sample:
+ row.update(stage_sample_elapsed_us=sample["elapsed_us"],
+ stage_in_flight_us=sample["in_flight_us"],
+ stage_sample_age_s=max(0.0, time.monotonic() -
+ sample["observed_monotonic"]))
+ replica_stage_samples.append(row)
+ snapshot["work"]["replica_stage_samples"] = replica_stage_samples
+ if stage_sample:
+ snapshot["work"].update(stage_sample_elapsed_us=stage_sample["elapsed_us"],
+ stage_in_flight_us=stage_sample["in_flight_us"],
+ stage_sample_age_s=max(0.0, time.monotonic() -
+ stage_sample["observed_monotonic"]))
+ snapshot["quality"]["stage_in_flight_source"] = "engine_pstat_host_span"
+ indices = list(getattr(svc, "gpu_indices", []) or [])
+ visibility = list(getattr(svc, "terminal_visibility_order", []) or [])
+ reported = (list(getattr(svc.engine, "terminal_stages", []) or [])
+ if svc.loaded() and not replica_engines else [])
+ stages = [{**stage, "device_index":
+ visibility[stage["engine_ordinal"]]
+ if stage["engine_ordinal"] < len(visibility) else None}
+ for stage in reported]
+ snapshot["topology"]["selected_devices"] = indices if replica_engines else visibility or indices
+ replica_devices = getattr(svc, "replica_gpu_groups", []) if replica_engines else []
+ snapshot["topology"]["replica_devices"] = [
+ {"replica": i, "devices": list(devices)}
+ for i, devices in enumerate(replica_devices[:16])]
+ replica_stages = []
+ for replica, child in enumerate((replica_engines or [])[:16]):
+ child_reported = (list(getattr(child, "terminal_stages", []) or [])
+ if child.alive() else [])
+ spawn = getattr(child, "spawn", None)
+ child_env = spawn[4] if isinstance(spawn, tuple) and len(spawn) > 4 else None
+ child_visibility = visible_device_order(child_env, getattr(svc, "backend", None))
+ configured_cards = (set(replica_devices[replica])
+ if replica < len(replica_devices) else set())
+ child_stages = []
+ for stage in child_reported:
+ ordinal = stage["engine_ordinal"]
+ card = (child_visibility[ordinal]
+ if type(ordinal) is int and 0 <= ordinal < len(child_visibility) else None)
+ child_stages.append({**stage, "device_index": card if card in configured_cards else None})
+ replica_stages.append({"replica": replica, "stages": child_stages})
+ snapshot["topology"]["replica_stages"] = replica_stages
+ snapshot["topology"]["mode"] = ("layer split (engine reported)" if stages else
+ getattr(svc, "terminal_topology_mode", None))
+ snapshot["topology"]["configured_split"] = getattr(svc, "terminal_configured_split", None)
+ snapshot["topology"]["stages"] = stages
+ snapshot["topology"]["resolved"] = bool(stages) and all(
+ stage["device_index"] is not None for stage in stages)
+ snapshot["topology"]["source"] = "engine_start_log" if stages else None
+ snapshot["quality"]["placement"] = ("reported" if snapshot["topology"]["resolved"] else
+ "partial" if stages else "unavailable")
+ present = {d.get("index") for d in snapshot["devices"]}
+ for index in indices:
+ if index not in present:
+ snapshot["devices"].append({"index": index, "name": None, "mem_used": None,
+ "mem_total": None, "util": None, "temp": None, "power": None})
+ self._json(200, snapshot)
+ return
if path == "/api/requests" and svc.api_monitor:
if self._authorized():
request_id = parse_qs(urlsplit(self.path).query).get("id", [None])[0]
@@ -5509,7 +6053,24 @@ def make_handler(svc: Service):
self._json(503, {"error": {"type": "server_error", "message": str(e)}},
headers={"Retry-After": int(ra)} if ra else None)
return
+ reserved = False
try:
+ if path in ("/v1/chat/completions", "/v1/messages", "/v1/responses"):
+ reserved = svc.reserve_inference()
+ if reserved is None:
+ error = {"type": "server_error", "code": "server_draining",
+ "message": "this instance is draining; retry against the next instance"}
+ body = responses_error_body(error["message"], "server_error", code=error["code"]) \
+ if path == "/v1/responses" else {"error": error}
+ self._json(503, body, retry_after=1)
+ return
+ if not reserved:
+ error = {"type": "rate_limit_error", "code": "admission_full",
+ "message": "the inference admission limit is full; retry later"}
+ body = responses_error_body(error["message"], "server_error", code=error["code"]) \
+ if path == "/v1/responses" else {"error": error}
+ self._json(429, body, retry_after=1)
+ return
req = json.loads(self._body() or b"{}")
if not isinstance(req, dict):
raise ValueError("send a JSON object")
@@ -5589,6 +6150,12 @@ def make_handler(svc: Service):
self._json(400, {"error": {"type": "invalid_request_error", "message": str(e)}})
except ModelBusy as e:
self._json(409, {"error": {"type": "model_busy", "message": str(e)}})
+ except QueueWaitExpired as e:
+ error = {"type": "rate_limit_error", "code": "queue_wait_timeout", "message": str(e)}
+ self._note(error=error)
+ body = responses_error_body(str(e), "server_error", code="queue_wait_timeout") \
+ if path == "/v1/responses" else {"error": error}
+ self._json(429, body, retry_after=1)
except StructuredOutputError as e:
self._json(502, {"error": {"type": "structured_output_failed", "code": "structured_output_failed",
"message": str(e)}})
@@ -5618,9 +6185,14 @@ def make_handler(svc: Service):
self._note(outcome="disconnected")
raise # as before #332: the server's own handling
finally:
+ if reserved:
+ svc.release_inference()
svc.drop_embeddings() # the images' file of a request that never got to run()
if self.watch_done is not None:
self.watch_done.set()
+ if self.cancel_event is not None:
+ with svc.status_lock:
+ svc.active_cancels.discard(self.cancel_event)
record = self.record
if record is not None:
with svc.status_lock:
@@ -5907,12 +6479,16 @@ def make_handler(svc: Service):
self.wfile.write(b"data: [DONE]\n\n")
except OSError:
self._note(outcome="disconnected")
- cancel.set() # client went away: stop the engine
+ svc.note_client_disconnect(cancel) # client went away: stop the engine
chunks.close()
except EngineDied as e: # mid-stream: say so, then end the stream properly
err = {"error": {"type": "server_error", "message": f"{e}; the next request restarts it"}}
self._note(error=err["error"])
self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
+ except QueueWaitExpired as e:
+ err = {"error": {"type": "rate_limit_error", "code": "queue_wait_timeout", "message": str(e)}}
+ self._note(error=err["error"])
+ self.wfile.write(b"data: " + json.dumps(err).encode() + b"\n\ndata: [DONE]\n\n")
except StructuredOutputError as e:
err = {"error": {"type": "structured_output_failed", "code": "structured_output_failed", "message": str(e)}}
self._note(error=err["error"])
@@ -5981,6 +6557,9 @@ def make_handler(svc: Service):
except StructuredOutputError as e:
return self._json(502, responses_error_body(str(e), "server_error",
code="structured_output_failed"))
+ except QueueWaitExpired as e:
+ return self._json(429, responses_error_body(str(e), "server_error",
+ code="queue_wait_timeout"), retry_after=1)
except EngineDied as e:
return self._json(503, responses_error_body(f"{e}; the next request restarts it", "server_error",
code="server_error"))
@@ -6012,10 +6591,12 @@ def make_handler(svc: Service):
self.wfile.flush()
except OSError:
self._note(outcome="disconnected")
- cancel.set() # client went away: stop the engine
+ svc.note_client_disconnect(cancel) # client went away: stop the engine
items.close()
except EngineDied as e: # mid-stream: response.failed, then the stream ends
self._responses_failed(asm, f"{e}; the next request restarts it", "server_error", send)
+ except QueueWaitExpired as e:
+ self._responses_failed(asm, str(e), "queue_wait_timeout", send)
except StructuredOutputError as e:
self._responses_failed(asm, str(e), "structured_output_failed", send)
except ValueError as e: # the engine's ERR after the stream started
@@ -6131,12 +6712,17 @@ def make_handler(svc: Service):
self.wfile.flush()
except OSError:
self._note(outcome="disconnected")
- cancel.set()
+ svc.note_client_disconnect(cancel)
events.close()
except EngineDied as e: # mid-stream: Anthropic's error event
err = {"type": "error", "error": {"type": "api_error", "message": f"{e}; the next request restarts it"}}
self._note(error=err["error"])
self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
+ except QueueWaitExpired as e:
+ err = {"type": "error", "error": {"type": "rate_limit_error", "code": "queue_wait_timeout",
+ "message": str(e)}}
+ self._note(error=err["error"])
+ self.wfile.write(b"event: error\ndata: " + json.dumps(err).encode() + b"\n\n")
except ValueError as e: # the engine's ERR after the stream started
err = {"type": "error", "error": {"type": "api_error", "message": str(e)}}
self._note(error=err["error"])
@@ -6584,7 +7170,8 @@ def sampling_defaults_from_config(cfg: dict) -> dict:
return out
-def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: list[str], lazy: bool):
+def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: list[str], lazy: bool,
+ *, offline: bool = False):
"""Opt-in data-parallel replicas (serve/replicas.py): one StrataEngine per card group, each with its own cards, log
and CPU cores, started together; the ReplicaEngine in front spreads the requests."""
from serve import replicas as rp
@@ -6600,7 +7187,7 @@ def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: lis
rc = rp.replica_cfg(cfg, i, groups[i])
try:
engines[i] = StrataEngine(exe, engine_args(rc) + effort_end, cwd=rc.get("cwd"), log=rc.get("log"),
- env=child_env(rc), lazy=lazy, cpus=cpus[i] if cpus else None)
+ env=child_env(rc, offline=offline), lazy=lazy, cpus=cpus[i] if cpus else None)
except BaseException as e: # noqa: BLE001
errors.append((i, e))
rc0 = rp.replica_cfg(cfg, 0, groups[0])
@@ -6672,7 +7259,19 @@ def default_model_name(cfg: dict) -> str:
return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
-def main() -> int:
+def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> int:
+ event_sink = lifecycle_event
+
+ def notify_lifecycle(kind: str, payload: dict) -> None:
+ nonlocal event_sink
+ if event_sink is None:
+ return
+ try:
+ event_sink(kind, payload)
+ except (OSError, ValueError):
+ # A closed event consumer must not strand the owned engine or API.
+ event_sink = None
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--engine", choices=["mock", "strata"], default="mock")
ap.add_argument("--config", help="strata engine config (JSON: exe, args, cwd, tokenizer, model_name), "
@@ -6680,10 +7279,33 @@ def main() -> int:
ap.add_argument("--host", default=None,
help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices "
"on your network (set an API key); also \"host\" in the config")
+ ap.add_argument("--script-cycle", action="store_true",
+ help="with --script given more than once: repeat the scripts by position instead of advancing "
+ "to the last one and staying there, so extra requests a harness makes (a session title, "
+ "a re-ask after a tool result) cannot shift the sequence")
+ ap.add_argument("--script-delay", type=float, default=0.0,
+ help="seconds to wait between the mock engine's tokens, so a turn stays live long enough for a "
+ "client to cancel it; the mock honours cancellation between tokens")
ap.add_argument("--script", action="append",
help="the mock engine's answer (default: a short greeting); given more than once, requests get "
"them in turn and the last one repeats")
ap.add_argument("--port", type=int, default=8095)
+ ap.add_argument("--ready-file", help="write a JSON instance record once the API is bound and model state is known")
+ ap.add_argument("--owner-fd", type=int, help=argparse.SUPPRESS)
+ ap.add_argument("--shutdown-timeout", type=float, default=None,
+ help="opt-in graceful drain deadline in seconds (0..300) before owned requests are cancelled")
+ ap.add_argument("--parallel", type=int, default=None,
+ help="request this many simultaneous engine slots without changing the saved config")
+ ap.add_argument("--batch-groups", default=None,
+ help="pipeline groups: auto or a positive integer, without changing the saved config")
+ ap.add_argument("--max-queue", type=int, default=None,
+ help="maximum inference calls waiting beyond effective engine slots; 0 refuses overload")
+ ap.add_argument("--queue-timeout", type=float, default=None,
+ help="maximum seconds waiting for the first engine turn (0.1..600; off by default)")
+ ap.add_argument("--batch-telemetry", action=argparse.BooleanOptionalAction, default=None,
+ help="opt in to low-rate engine decode-window samples for /v1/telemetry")
+ ap.add_argument("--offline", action="store_true",
+ help="do not fetch remote image URLs or start MCP/tool subprocesses")
ap.add_argument("--gpu", help="the GPU to run on, as nvidia-smi numbers them, or several for a layer split "
"(\"0,2\"; also \"gpu\" in the config)")
ap.add_argument("--tokenizer", default=str(ROOT / "pack/full/tokenizer"),
@@ -6718,14 +7340,74 @@ def main() -> int:
help="data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on "
"each, requests spread over them (also \"replicas\" in the config: a number, or "
"[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])")
- a = ap.parse_args()
- cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {} # Notepad adds a BOM
+ launch_args = list(sys.argv[1:] if argv is None else argv)
+ a = ap.parse_args(launch_args)
+ if a.owner_fd is not None:
+ try:
+ owner_guard.start(a.owner_fd)
+ except (OSError, ValueError) as exc:
+ ap.error(str(exc))
+ if a.shutdown_timeout is not None and not 0 <= a.shutdown_timeout <= 300:
+ ap.error("--shutdown-timeout must be in 0..300 seconds")
+ config_bytes = Path(a.config).read_bytes() if a.config else b""
+ cfg = json.loads(config_bytes.decode("utf-8-sig")) if a.config else {} # Notepad adds a BOM
+ attestation_key = os.environ.pop("STRATA_OWNER_ATTEST_KEY", None)
+ launch_attestation = None
+ if a.owner_fd is not None:
+ if attestation_key is None or not re.fullmatch(r"[0-9a-f]{64}", attestation_key):
+ ap.error("owned server needs a private launch attestation key")
+ launch_attestation = launch_identity.attestation(bytes.fromhex(attestation_key),
+ config_bytes, launch_args)
+ if "batch_telemetry" in cfg and type(cfg["batch_telemetry"]) is not bool:
+ ap.error("batch_telemetry must be true or false")
+ try:
+ ready_path = ready_file.preflight(a.ready_file) if a.ready_file else None
+ except ValueError as e:
+ ap.error(str(e))
+ max_queue = a.max_queue if a.max_queue is not None else cfg.get("max_queue")
+ if max_queue is not None and (isinstance(max_queue, bool) or not isinstance(max_queue, int)
+ or not 0 <= max_queue <= 4096):
+ ap.error("--max-queue / max_queue must be a whole number in 0..4096")
+ queue_timeout = a.queue_timeout if a.queue_timeout is not None else cfg.get("queue_timeout")
+ if queue_timeout is not None and (isinstance(queue_timeout, bool) or not isinstance(queue_timeout, (int, float))
+ or not math.isfinite(queue_timeout) or not 0.1 <= queue_timeout <= 600):
+ ap.error("--queue-timeout / queue_timeout must be finite seconds in 0.1..600")
+ if queue_timeout is not None and max_queue is None:
+ ap.error("--queue-timeout requires --max-queue / max_queue to bound pending calls")
+ if a.parallel is not None:
+ if a.parallel < 1 or a.parallel > 1024:
+ ap.error("--parallel must be in 1..1024; the engine may reduce it to the supported count")
+ if "--batch" in cfg.get("args", []) or "--slots" in cfg.get("args", []):
+ ap.error("--parallel conflicts with an explicit --batch/--slots in the saved engine args")
+ cfg["parallel"] = a.parallel
+ if a.batch_groups is not None:
+ if a.batch_groups != "auto" and (not a.batch_groups.isdecimal() or int(a.batch_groups) < 1):
+ ap.error("--batch-groups must be auto or a positive integer")
+ if not cfg or "args" not in cfg:
+ ap.error("--batch-groups needs an engine config")
+ if "--batch-groups" in cfg["args"]:
+ ap.error("--batch-groups conflicts with the saved engine args")
+ cfg["args"] = [*cfg["args"], "--batch-groups", a.batch_groups]
lift_reasoning_effort_arg(cfg)
if a.replicas is not None:
cfg["replicas"] = a.replicas
if a.gpu is not None:
cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu
a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can
+ supplied_args = argv if argv is not None else sys.argv[1:]
+ if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or \
+ any((x == "--api-key" and i + 1 < len(supplied_args) and not supplied_args[i + 1].strip()) or
+ x.strip() == "--api-key=" for i, x in enumerate(supplied_args)):
+ print("[strata] an API key was given but it is empty: set a key, or leave it out", file=sys.stderr)
+ return 2
+ try:
+ preflight_api_key = api_key_of(a.api_key or cfg.get("api_key", ""))
+ except ValueError as e:
+ print(f"[strata] {e}: set a key, or leave it out", file=sys.stderr)
+ return 2
+ if a.host not in ("127.0.0.1", "localhost", "::1") and not preflight_api_key:
+ print("[strata] a non-loopback bind requires an inference API key", file=sys.stderr, flush=True)
+ return 2
try: # before the minutes of loading: is the port free?
Server((a.host, a.port), BaseHTTPRequestHandler).server_close()
except OSError as e:
@@ -6746,11 +7428,27 @@ def main() -> int:
types = json.loads((tpath / "token_type.json").read_text())
tok = ST.Tokenizer(tokens, merges, types)
hub = hub_from_config(cfg, a.mcp_config) # before the minutes of loading: a bad entry stops here
+ if a.offline and (hub is not None or cfg.get("before_load") or a.before_load):
+ ap.error("--offline requires MCP servers and before_load commands to be disabled in this profile")
+ if a.offline:
+ # The same decision, reported through the policy module so the two cannot drift: a profile
+ # that permits a network source is refused here rather than on its first request.
+ try:
+ from strata_control import offline as offline_policy
+ blocked = offline_policy.ensure_strictly_offline(cfg)
+ except ImportError:
+ blocked = []
+ if blocked:
+ ap.error("--offline cannot be strict for this profile: " + "; ".join(blocked))
+ lazy = False
if a.engine == "strata":
if not cfg:
ap.error("--engine strata needs --config")
vision = None
- env = child_env(cfg)
+ # The engine's own environment. It carries the offline policy too: an engine that fetched a
+ # missing shard or a plugin would break the promise the flag makes.
+ env = child_env(cfg, offline=a.offline)
+ configure_batch_telemetry_env(env, cfg, a.batch_telemetry)
sampling_defaults = sampling_defaults_from_config(cfg)
if sampling_defaults:
pretty = ", ".join(f"{k}={v}" for k, v in sampling_defaults.items())
@@ -6800,7 +7498,7 @@ def main() -> int:
except rp.ReplicaConfigError as e:
raise SystemExit(f"[strata] config {e}")
if groups:
- engine = start_replicas(cfg, groups, exe, effort_end or [], lazy)
+ engine = start_replicas(cfg, groups, exe, effort_end or [], lazy, offline=a.offline)
else:
engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"),
env=env, lazy=lazy)
@@ -6813,13 +7511,31 @@ def main() -> int:
else:
effort_end = None
engine, vision, sampling_defaults = MockEngine(tok, a.script or [
- "Thinking about it.</think>\n\nHello from the mock engine."]), None, {}
+ "Thinking about it.</think>\n\nHello from the mock engine."],
+ cycle=getattr(a, "script_cycle", False),
+ delay_s=getattr(a, "script_delay", 0.0) or 0.0), None, {}
# the model's own chat template (exported with its tokenizer), else the original model's
tpl = tpath / "chat_template.jinja"
svc = Service(engine, tok, ChatTemplate(tpl if tpl.exists() else ROOT / "serve/chat_template.jinja"),
model_name=default_model_name(cfg), vision=vision,
sampling_defaults=sampling_defaults,
fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True)
+ svc.launch_attestation = launch_attestation
+ svc.offline = a.offline
+ svc.max_queue = max_queue
+ svc.queue_timeout_s = float(queue_timeout) if queue_timeout is not None else None
+ if a.engine == "strata":
+ requested = cfg.get("parallel")
+ if requested is None:
+ args = cfg.get("args", [])
+ for flag in ("--batch", "--slots"):
+ if flag in args and args.index(flag) + 1 < len(args):
+ try:
+ requested = int(args[args.index(flag) + 1])
+ except ValueError:
+ pass
+ per_replica = requested if isinstance(requested, int) and not isinstance(requested, bool) and requested > 0 else 1
+ svc.requested_slots = per_replica * len(groups) if groups else per_replica
svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True # #1053: opt-in, off by default
if cfg.get("images"): # image generation (serve/images.py), set up by setup --images
icfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
@@ -6856,16 +7572,14 @@ def main() -> int:
raise SystemExit(f"[strata] config {e}")
if svc.aliases:
print(f"[strata] model aliases: {', '.join(svc.aliases)}", flush=True)
- if ("STRATA_API_KEY" in os.environ and not os.environ["STRATA_API_KEY"].strip()) or any(x == "--api-key" and i + 1 < len(sys.argv) and not sys.argv[i + 1].strip() or x.strip() == "--api-key="
- for i, x in enumerate(sys.argv)):
- # #213: an empty key would switch authentication off without a word
- print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out",
- file=sys.stderr)
- return 2
+ svc.api_key = preflight_api_key
try:
- svc.api_key = api_key_of(a.api_key or cfg.get("api_key", ""))
+ svc.telemetry_key = api_key_of(os.environ.get("STRATA_TELEMETRY_KEY") or cfg.get("telemetry_read_key", ""))
except ValueError as e:
- print(f'[strata] {e}: set a key, or leave --api-key / STRATA_API_KEY / "api_key" out', file=sys.stderr)
+ print(f"[strata] invalid telemetry_read_key: {e}", file=sys.stderr)
+ return 2
+ if set(key_list(svc.api_key)) & set(key_list(svc.telemetry_key)):
+ print("[strata] telemetry_read_key must differ from every inference API key", file=sys.stderr)
return 2
if not svc.api_key and "api_key" in cfg: # #569: written, but empty: the server has none (a warning, not a stop)
print("[strata] the api_key in the config is empty: this server has no API key (anyone who can reach it can "
@@ -6948,6 +7662,13 @@ def main() -> int:
if a.engine == "strata" and groups: # replicas: every card of every group
svc.gpu_indices = [c for g in groups for c in g]
svc.gpu_index = svc.gpu_indices[0]
+ svc.replica_gpu_groups = groups
+ svc.terminal_visibility_order = visible_device_order(env, cfg.get("backend")) if a.engine == "strata" else []
+ svc.terminal_topology_mode = ("replicas (configured)" if a.engine == "strata" and groups
+ else "layer split (configured)" if a.engine == "strata" and layer_split_of(cfg)
+ else "single GPU or CPU" if a.engine == "strata" else "mock")
+ svc.terminal_configured_split = (layer_split_value(cfg) if a.engine == "strata" and layer_split_of(cfg)
+ else None)
svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301)
if a.config:
svc.config_path = a.config # #564: the web page's Settings view
@@ -6968,60 +7689,113 @@ def main() -> int:
hub.start()
atexit.register(hub.close) # the servers Strata started end with it
httpd = serve(svc, host=a.host, port=a.port)
+ bound_port = httpd.server_address[1] # --port 0: report the port the OS actually assigned
svc.start_idle_unload()
svc.start_vision_idle()
here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host
- print(f"ready: http://{here}:{a.port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, "
+ print(f"ready: http://{here}:{bound_port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, "
f"context {engine.max_context} tokens{', images on' if vision else ''}"
f"{', API key required' if svc.api_key else ''})", flush=True)
- print(f" open http://{here}:{a.port}/ in a browser to chat; close this window to stop the model", flush=True)
+ print(f" open http://{here}:{bound_port}/ in a browser to chat; close this window to stop the model", flush=True)
if a.host not in ("127.0.0.1", "localhost", "::1"):
# issue #26: reachable from other devices - say at which address, and what can still block it
ips = lan_addresses()
for ip in ips:
- print(f" from other devices: http://{ip}:{a.port}/ (API: http://{ip}:{a.port}/v1)", flush=True)
+ print(f" from other devices: http://{ip}:{bound_port}/ (API: http://{ip}:{bound_port}/v1)", flush=True)
if not ips:
- print(" from other devices: http://<this PC's IP address>:" + str(a.port) + "/", flush=True)
+ print(" from other devices: http://<this PC's IP address>:" + str(bound_port) + "/", flush=True)
if not svc.api_key:
print(" WARNING: no API key - anyone on your network can use this model. Add \"api_key\": \"...\" "
"to the config (clients send it as their API key; the web page asks for it)", flush=True)
if os.name == "nt":
print(" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run "
- "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(a.port) + "\" "
- "-Direction Inbound -Protocol TCP -LocalPort " + str(a.port) + " -Action Allow -Profile Private\n"
+ "in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(bound_port) + "\" "
+ "-Direction Inbound -Protocol TCP -LocalPort " + str(bound_port) + " -Action Allow -Profile Private\n"
" (and set this network to Private in Windows' network settings)", flush=True)
if a.open and cfg.get("open_browser") is not False: # #609: the config's "open_browser": false wins (an older
import webbrowser # run-<model>.bat still passes --open)
- webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{a.port}/")
+ webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/")
# #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after
# the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine).
# SIGINT keeps Python's own handler, so Ctrl+C and a second Ctrl+C work as before.
+ termination = "sigint"
+
def on_sigterm(signum, frame):
+ nonlocal termination
+ termination = "sigterm"
raise KeyboardInterrupt
try:
signal.signal(signal.SIGTERM, on_sigterm)
except (ValueError, OSError, AttributeError): # not the main thread
pass
+ if ready_path is not None or event_sink is not None:
+ ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here
+ record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(),
+ "api_url": f"http://{ready_host}:{bound_port}", "bound_host": a.host, "bound_port": bound_port,
+ "model_id": svc.model, "model_state": "unloaded" if lazy else "ready",
+ "api_state": "ready", "created_at": time.time()}
+ if ready_path is not None:
+ try:
+ ready_file.publish(ready_path, record)
+ except OSError as e:
+ print(f"[strata] could not write ready file ({type(e).__name__})", file=sys.stderr)
+ for close in (httpd.shutdown, getattr(engine, "close", None), vision.shutdown if vision else None,
+ hub.close if hub is not None else None):
+ if close:
+ close()
+ return 6
+ if event_sink is not None:
+ notify_lifecycle("ready", record)
+ interrupted = False
+ drained = True
try:
while True:
time.sleep(1) # Windows never delivers Ctrl+C to an untimed Event.wait()
except KeyboardInterrupt:
+ interrupted = True
+ notify_lifecycle("stopping", {"reason": termination, "instance_id": svc.instance_id})
print("\n[strata] stopping (Ctrl+C again to end the engine at once) ...", flush=True)
+ finally:
+ cancelled = 0
+ if a.shutdown_timeout is not None:
+ pending = svc.begin_drain()
+ notify_lifecycle("draining", {"instance_id": svc.instance_id,
+ "pending_requests": pending,
+ "deadline_s": a.shutdown_timeout})
+ if pending:
+ print(f"[strata] draining {pending} inference call(s) for up to {a.shutdown_timeout:g} s ...",
+ flush=True)
+ pending = svc.wait_for_drain(a.shutdown_timeout)
+ if pending:
+ cancelled = svc.cancel_owned_requests()
+ print(f"[strata] drain deadline expired; cancelling {cancelled} owned request(s) ...", flush=True)
+ svc.wait_for_drain(5)
+ drained = False
closers = [httpd.shutdown, getattr(engine, "close", None), vision.shutdown if vision else None,
hub.close if hub is not None else None]
- for close in filter(None, closers):
- try:
- close()
- except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory
- if getattr(engine, "proc", None):
- engine.proc.kill()
try:
- from serve import cache_drop
- cache_drop.drop_after_exit(engine) # opt-in (STRATA_DROP_CACHE_ON_EXIT=1), default unchanged
- except Exception as e: # noqa: BLE001 - never block the exit
- print(f"[strata] could not release the model files' cache: {e}", flush=True)
- print("[strata] stopped", flush=True)
- return 0
+ for close in filter(None, closers):
+ try:
+ close()
+ except KeyboardInterrupt: # a second Ctrl+C: don't wait for the engine to free its memory
+ if getattr(engine, "proc", None):
+ engine.proc.kill()
+ try:
+ from serve import cache_drop
+ cache_drop.drop_after_exit(engine) # opt-in (STRATA_DROP_CACHE_ON_EXIT=1), default unchanged
+ except Exception as e: # noqa: BLE001 - never block the exit
+ print(f"[strata] could not release the model files' cache: {e}", flush=True)
+ finally:
+ if ready_path is not None:
+ ready_file.remove_if_owned(ready_path, svc.instance_id)
+ if interrupted:
+ print("[strata] stopped", flush=True)
+ exit_code = (8 if not drained else
+ interrupt_exit_code if interrupted and termination == "sigint" else 0)
+ notify_lifecycle("stopped", {"instance_id": svc.instance_id, "reason": termination if interrupted else "normal",
+ "drained": drained, "cancelled_requests": cancelled,
+ "exit_code": exit_code})
+ return exit_code
if __name__ == "__main__":
diff --git a/serve/telemetry.py b/serve/telemetry.py
index 2e2a28ad7..b1054759f 100644
--- a/serve/telemetry.py
+++ b/serve/telemetry.py
@@ -571,9 +571,9 @@ class Telemetry:
g["util"] = sum(u) / len(u) if u else None
t = vals("temp")
g["temp"] = max(t) if t else None
- s["gpus"] = [{"index": i, "util": r.get("util"), "mem_used": r.get("mem_used"),
+ s["gpus"] = [{"index": i, "name": reader.name(), "util": r.get("util"), "mem_used": r.get("mem_used"),
"mem_total": r.get("mem_total"), "temp": r.get("temp"), "power": r.get("power")}
- for i, r in reads]
+ for (i, r), (_, reader) in zip(reads, self.gpus)]
s.update({f"gpu_{k}": v for k, v in g.items()})
if self.ps:
try:
diff --git a/serve/test_parallel.py b/serve/test_parallel.py
index bde520845..3e8d7940d 100644
--- a/serve/test_parallel.py
+++ b/serve/test_parallel.py
@@ -17,6 +17,8 @@ from unittest import mock
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, Service, StrataEngine, engine_args, parallel_args, serve
+from strata_cli import bench
+from strata_cli.client import Endpoint
# The fake engine: one token every STEP seconds per active slot (a "window" serves every active slot at once);
# GEN (solo) streams T lines; BGEN reads the prompt (one T line, DONE), answers BADM and continues in the slot.
@@ -41,11 +43,15 @@ def reader():
threading.Thread(target=reader, daemon=True).start()
print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") +
(" slot_cache=1" if "--slotcache" in args else "") + (f" batch_groups={groups}" if groups > 1 else ""), flush=True)
+if "--fake-stage-plan" in args:
+ print("strata serve: layer split: layers 0-11 (CUDA0), 12-23 (CUDA1), 24-35 (CUDA2), "
+ "36-47 (CUDA3), one hand-off per window", file=sys.stderr, flush=True)
print("READY 4096 stop", flush=True)
LONG = list(b"LONGREPLY")
def continued(ids): # (the whole reply, how much of it the prompt already ends with: a request continued)
ids = [int(x) for x in ids]
- long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids)))
+ long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids))) or \
+ b"Cancellation benchmark:" in bytes(int(x) & 255 for x in ids)
R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257]
return R, max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k])
def reply(ids): # the rest of the reply after what the prompt already ends with
@@ -60,6 +66,7 @@ def window(): # one batch window: every active slot one token
if fail and len(active) >= 2: # as the engine: the reason on stdout, then exit code 1
print("ERR verify batch: layer 34 never rang (graph finished)", flush=True)
sys.exit(1)
+ processed = len(active)
for b in sorted(active):
left, max_new, produced = active[b]
if b in nf_slots and produced >= 2:
@@ -77,6 +84,10 @@ def window(): # one batch window: every active slot one token
del active[b]
else:
active[b] = [left, max_new, produced]
+ if "--fake-batch-sample" in args and processed and not active:
+ print(f"BSTAT 1 {processed} {processed} 20", flush=True)
+ if "--fake-stage-sample" in args and processed and not active:
+ print("PSTAT 4 20000 16000 14000 12000 10000", flush=True)
log = open(args[args.index("--log") + 1], "a") if "--log" in args else None
PPK = int(args[args.index("--pp-every") + 1]) if "--pp-every" in args else 1
READF = "--readfield" in args # DONE's 15th field: the prompt tokens the engine read (a continued prompt: the 1 it copies)
@@ -145,12 +156,16 @@ while True:
ys = int(l2.split()[1])
if len(ids) - 1 - q > CH and (slot is None or ys == slot) and given is None:
given = (ys, q)
+ elif l2 == "STOP":
+ stop.set()
else:
held.append(l2)
for l2 in held:
lines.put(l2)
if given:
break
+ if stop.is_set():
+ break
if active and (q // CH) % 4 == 0: # the slots decode between the prompt's chunks (as the engine)
window()
if given:
@@ -305,7 +320,8 @@ class PickSlot(unittest.TestCase):
class ParallelService(unittest.TestCase):
"""The real StrataEngine and Service over HTTP, the fake engine behind them."""
- def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False, says_groups=0, more=()):
+ def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False, says_groups=0,
+ more=(), stage_plan=False, batch_sample=False, stage_sample=False):
import serve.server as server
self.tmp = tempfile.TemporaryDirectory()
script = Path(self.tmp.name) / "fake_strata.py"
@@ -317,10 +333,13 @@ class ParallelService(unittest.TestCase):
extra += ["--fail-window"] if fail else []
extra += ["--reuse"] if reuse else []
extra += ["--says-groups", str(says_groups)] if says_groups else []
+ extra += ["--fake-stage-plan"] if stage_plan else []
+ extra += ["--fake-batch-sample"] if batch_sample else []
+ extra += ["--fake-stage-sample"] if stage_sample else []
extra += list(more)
with mock.patch.object(server.subprocess, "Popen",
lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
- self.engine = StrataEngine("strata", extra)
+ self.engine = StrataEngine("strata", extra, log=str(Path(self.tmp.name) / "engine.log") if stage_plan else None)
tok = ByteTokenizer()
self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
@@ -398,6 +417,186 @@ class ParallelService(unittest.TestCase):
self.assertEqual(self.engine.batch, 2)
self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2)
+ def test_admission_cap_uses_effective_slots_and_rejects_before_stream(self):
+ self.start(4, fit=2)
+ self.svc.max_queue = 1
+ self.assertEqual(self.svc.admission_limit(), 3)
+ self.assertTrue(all(self.svc.reserve_inference() for _ in range(3)))
+ cases = (
+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "stream": True}),
+ ("/v1/messages", {"model": "m", "max_tokens": 8,
+ "messages": [{"role": "user", "content": "hi"}], "stream": True}),
+ ("/v1/responses", {"model": "m", "input": "hi", "stream": True}),
+ )
+ try:
+ for path, body in cases:
+ req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"})
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ urllib.request.urlopen(req, timeout=10)
+ err = caught.exception
+ self.assertEqual(err.code, 429)
+ self.assertEqual(err.headers.get("Retry-After"), "1")
+ self.assertIn("admission_full", err.read().decode())
+ snapshot = self.get("/v1/telemetry")["work"]
+ self.assertEqual((snapshot["admission_reserved"], snapshot["admission_limit"],
+ snapshot["max_queue"], snapshot["admission_rejected"]), (3, 3, 1, 3))
+ finally:
+ for _ in range(3):
+ self.svc.release_inference()
+ self.assertEqual(self.chat("capacity freed")["choices"][0]["message"]["content"], "ok, done.")
+ self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
+
+ def test_queue_timeout_serial_fifo_returns_429_and_recovers(self):
+ self.start(1)
+ self.svc.queue_timeout_s = 0.12
+ self.svc.max_queue = 1
+ self.svc.fifo.acquire()
+ try:
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ self.chat("waiting for serial turn")
+ self.assertEqual(caught.exception.code, 429)
+ self.assertEqual(caught.exception.headers.get("Retry-After"), "1")
+ self.assertEqual(json.loads(caught.exception.read())["error"]["code"], "queue_wait_timeout")
+ work = self.get("/v1/telemetry")["work"]
+ self.assertEqual((work["queue_timeout_s"], work["queue_timeouts"], work["queued"]),
+ (0.12, 1, 0))
+ finally:
+ self.svc.fifo.release()
+ self.assertEqual(self.chat("next turn")["choices"][0]["message"]["content"], "ok, done.")
+ self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
+
+ def test_queue_timeout_parallel_control_and_stream_formats(self):
+ self.start(2)
+ self.svc.queue_timeout_s = 0.12
+ self.svc.max_queue = 1
+ self.engine.ctl.acquire()
+ cases = (
+ ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, "data: "),
+ ("/v1/messages", {"model": "m", "max_tokens": 8,
+ "messages": [{"role": "user", "content": "hi"}]}, "event: error"),
+ ("/v1/responses", {"model": "m", "input": "hi"}, "event: response.failed"),
+ )
+ try:
+ for path, body, marker in cases:
+ for stream in (False, True):
+ req = urllib.request.Request(self.base + path,
+ data=json.dumps({**body, "stream": stream}).encode(),
+ headers={"Content-Type": "application/json"})
+ if stream:
+ with urllib.request.urlopen(req, timeout=10) as response:
+ data = response.read().decode()
+ self.assertIn(marker, data)
+ self.assertIn("queue_wait_timeout", data)
+ else:
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ urllib.request.urlopen(req, timeout=10)
+ self.assertEqual(caught.exception.code, 429)
+ self.assertIn("queue_wait_timeout", caught.exception.read().decode())
+ work = self.get("/v1/telemetry")["work"]
+ self.assertEqual(work["queue_timeouts"], 6)
+ self.assertEqual((work["admission_reserved"], work["waiting"]), (0, 0))
+ finally:
+ self.engine.ctl.release()
+ self.assertEqual(self.chat("healthy")["choices"][0]["message"]["content"], "ok, done.")
+
+ def test_queue_timeout_parallel_slot_wait_releases_control(self):
+ self.start(2)
+ self.svc.queue_timeout_s = 0.12
+ with self.engine.slot_cv:
+ self.engine.slot_busy[:] = [True, True]
+ try:
+ with self.assertRaises(urllib.error.HTTPError) as caught:
+ self.chat("waiting for a batch slot")
+ self.assertEqual(caught.exception.code, 429)
+ self.assertIn("queue_wait_timeout", caught.exception.read().decode())
+ self.assertFalse(self.engine.ctl.locked())
+ self.assertEqual(self.engine.waiting, 0)
+ finally:
+ with self.engine.slot_cv:
+ self.engine.slot_busy[:] = [False, False]
+ self.engine.slot_cv.notify_all()
+ self.assertEqual(self.chat("slot freed")["choices"][0]["message"]["content"], "ok, done.")
+
+ def test_benchmark_overload_suite_preserves_batch_recovery(self):
+ self.start(2)
+ self.svc.max_queue = 0
+ self.svc.queue_timeout_s = 0.15
+ out = Path(self.tmp.name) / "overload"
+ report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
+ suite="parallel-overload-v1", concurrency=6)
+ self.assertTrue(report["successful"])
+ overload = report["phases"][1]
+ self.assertEqual(overload["kind"], "overload")
+ self.assertGreater(overload["summary"]["expected_overload"], 0)
+ self.assertEqual(overload["summary"]["failed"], 0)
+ self.assertTrue(report["phases"][2]["passed"])
+ self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
+
+ def test_benchmark_cancel_suite_releases_batch_queue_and_slots(self):
+ self.start(2)
+ self.svc.max_queue = 1
+ self.svc.queue_timeout_s = 5
+ out = Path(self.tmp.name) / "cancel"
+ report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
+ suite="parallel-cancel-v1", concurrency=2, request_timeout=15)
+ self.assertTrue(report["successful"], bench.format_summary(bench.summary(report)))
+ self.assertEqual([row["kind"] for row in report["phases"]],
+ ["warmup", "cancel_active", "cancel_queued", "recovery"])
+ self.assertEqual(report["phases"][2]["summary"]["companion_successful"], 2)
+ self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
+
+ def test_benchmark_prefill_cancel_observes_progress_and_companion_completion(self):
+ self.start(2)
+ out = Path(self.tmp.name) / "prefill-cancel"
+ report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
+ suite="parallel-prefill-cancel-v1", concurrency=2, request_timeout=15)
+ self.assertTrue(report["successful"], bench.format_summary(bench.summary(report)))
+ self.assertEqual([row["kind"] for row in report["phases"]],
+ ["warmup", "cancel_prefill", "recovery"])
+ phase = report["phases"][1]
+ self.assertTrue(phase["summary"]["prompt_read_seen"])
+ self.assertGreater(phase["requests"][0]["prompt_read_at_close"], 0)
+ self.assertLess(phase["requests"][0]["prompt_read_at_close"],
+ phase["requests"][0]["prompt_tokens_at_close"])
+ self.assertEqual(phase["summary"]["client_disconnect_delta"], 1)
+ self.assertEqual(phase["summary"]["companion_successful"], 1)
+ self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
+ data = (out / "results.json").read_text()
+ self.assertNotIn("Explain how a serving system", data)
+
+ def test_telemetry_keeps_engine_waiting_age_visible(self):
+ self.start(2)
+ self.svc.max_queue = 1
+ self.svc.queue_timeout_s = 0.5
+ self.engine.ctl.acquire()
+ outcome = []
+ def request():
+ try:
+ self.chat("waiting")
+ except urllib.error.HTTPError as error:
+ outcome.append(error.code)
+ error.read()
+ worker = threading.Thread(target=request)
+ try:
+ worker.start()
+ cutoff = time.monotonic() + 2
+ while time.monotonic() < cutoff:
+ work = self.get("/v1/telemetry")["work"]
+ if any(row["state"] == "waiting" for row in work["requests"]):
+ break
+ time.sleep(0.01)
+ else:
+ self.fail("engine wait was not visible in telemetry")
+ time.sleep(0.04)
+ work = self.get("/v1/telemetry")["work"]
+ self.assertGreater(work["oldest_queue_s"], 0.03)
+ self.assertTrue(any(row["state"] == "waiting" for row in work["requests"]))
+ finally:
+ self.engine.ctl.release()
+ worker.join(timeout=3)
+ self.assertEqual(outcome, [])
+
def test_batch_groups_auto_follows_the_engine(self):
"""--batch-groups auto: the engine picks the groups and says so (INFO batch_groups=G); the server spreads the
requests over those groups, and a plain number is read as before."""
@@ -406,6 +605,8 @@ class ParallelService(unittest.TestCase):
self.assertEqual((e.batch, e.slot_groups), (8, 4))
self.assertEqual(e.slot_group, [0, 0, 1, 1, 2, 2, 3, 3])
self.assertEqual(e.slot_order[:4], [0, 2, 4, 6])
+ telemetry = self.get("/v1/telemetry")
+ self.assertEqual([s["group"] for s in telemetry["work"]["slots"]], [0, 0, 1, 1, 2, 2, 3, 3])
self.tearDown(); self.httpd = self.engine = self.tmp = None
self.start(8, more=["--batch-groups", "auto"]) # an engine that reports none: one group
self.assertEqual(self.engine.slot_groups, 1)
@@ -419,6 +620,80 @@ class ParallelService(unittest.TestCase):
self.start(8, says_groups=4, more=["--batch-groups", "1"]) # the opt-out
self.assertEqual(self.engine.slot_groups, 1)
+ def test_engine_log_resolves_four_stage_layer_and_device_mapping(self):
+ self.start(8, says_groups=4, stage_plan=True)
+ self.svc.terminal_visibility_order = [2, 0, 3, 1]
+ self.svc.gpu_indices = [2, 0, 3, 1]
+ telemetry = self.get("/v1/telemetry")
+ topology = telemetry["topology"]
+ self.assertEqual(topology["source"], "engine_start_log")
+ self.assertTrue(topology["resolved"])
+ self.assertEqual(telemetry["quality"]["placement"], "reported")
+ self.assertEqual([(row["stage"], row["device_index"], row["layer_start"], row["layer_end"])
+ for row in topology["stages"]],
+ [(0, 2, 0, 11), (1, 0, 12, 23), (2, 3, 24, 35), (3, 1, 36, 47)])
+ clean = Endpoint(self.base).snapshot()
+ self.assertEqual(clean["topology"]["stages"], topology["stages"])
+ self.svc.terminal_visibility_order = []
+ partial = self.get("/v1/telemetry")
+ self.assertFalse(partial["topology"]["resolved"])
+ self.assertEqual(len(partial["topology"]["stages"]), 4)
+ self.assertIsNone(partial["topology"]["stages"][0]["device_index"])
+ self.assertEqual(partial["quality"]["placement"], "partial")
+ self.engine.unload()
+ unloaded = self.get("/v1/telemetry")["topology"]
+ self.assertFalse(unloaded["resolved"])
+ self.assertEqual(unloaded["stages"], [])
+
+ def test_engine_batch_window_sample_reaches_telemetry_without_entering_reply(self):
+ self.start(2, batch_sample=True)
+ replies = self.race("first LONGREPLY", "second LONGREPLY", delay=0.05, max_tokens=64)
+ self.assertTrue(all("ok, " in reply for reply, _ in replies.values()))
+ self.assertTrue(any(line.startswith("BGEN") for line in self.log.read_text().splitlines()))
+ deadline = time.monotonic() + 2
+ while True:
+ telemetry = self.get("/v1/telemetry")
+ if telemetry["quality"]["batch_window_rows"] == "measured":
+ break
+ if time.monotonic() >= deadline:
+ self.fail("fake engine's BSTAT sample did not reach telemetry")
+ time.sleep(0.02)
+ work = telemetry["work"]
+ self.assertGreaterEqual(work["effective_rows_window"], 1.0)
+ self.assertLessEqual(work["effective_rows_window"], 2.0)
+ self.assertEqual(work["batch_active_rows_window"], work["effective_rows_window"])
+ self.assertEqual(work["batch_sample_windows"], 1)
+ self.assertEqual(work["batch_sample_span_s"], 0.02)
+ self.assertGreaterEqual(work["batch_sample_age_s"], 0)
+ clean = Endpoint(self.base).snapshot()
+ self.assertEqual(clean["quality"]["batch_window_rows"], "measured")
+ self.assertGreaterEqual(clean["work"]["batch_sample_rows"], 1)
+ self.engine.unload()
+ unloaded = self.get("/v1/telemetry")
+ self.assertIsNone(unloaded["work"]["effective_rows_window"])
+ self.assertEqual(unloaded["quality"]["batch_window_rows"], "unavailable")
+
+ def test_pipeline_stage_host_spans_reach_telemetry_without_entering_reply(self):
+ self.start(2, says_groups=2, stage_plan=True, stage_sample=True)
+ replies = self.race("first LONGREPLY", "second LONGREPLY", delay=0.05, max_tokens=64)
+ self.assertTrue(all("ok, " in reply for reply, _ in replies.values()))
+ deadline = time.monotonic() + 2
+ while True:
+ telemetry = self.get("/v1/telemetry")
+ if telemetry["quality"].get("stage_in_flight_source") == "engine_pstat_host_span":
+ break
+ if time.monotonic() >= deadline:
+ self.fail("fake engine's PSTAT sample did not reach telemetry")
+ time.sleep(0.02)
+ self.assertEqual(telemetry["work"]["stage_in_flight_us"], [16000, 14000, 12000, 10000])
+ clean = Endpoint(self.base).snapshot()
+ self.assertEqual(clean["quality"]["stage_in_flight"], "measured_host_span")
+ self.assertEqual([row["percent"] for row in clean["work"]["stage_in_flight"]],
+ [80.0, 70.0, 60.0, 50.0])
+ self.engine.unload()
+ unloaded = self.get("/v1/telemetry")
+ self.assertNotIn("stage_in_flight_us", unloaded["work"])
+
def test_a_burst_of_connections_is_not_reset(self):
"""30-40 clients at once got "connection reset by peer" with the listen backlog of 5 (4 x R9700 burst): the
server listens with a deep backlog (STRATA_HTTP_BACKLOG, 256), so 60 simultaneous requests all get answers."""
@@ -459,7 +734,7 @@ class ParallelService(unittest.TestCase):
# the first one decodes long enough for the others to arrive while it runs (also on a busy PC)
texts = ["first question LONGREPLY", "second question, longer", "a third one waits for a slot"]
reply = {t: "ok, " + "la " * 15 + "done." if "LONGREPLY" in t else "ok, done." for t in texts}
- out, errors, seen = {}, [], []
+ out, errors, seen, terminal_seen = {}, [], [], []
def go(t):
try:
@@ -475,6 +750,7 @@ class ParallelService(unittest.TestCase):
while any(th.is_alive() for th in threads) and time.time() < deadline:
m = self.get("/metrics")["live"]
seen.append(m)
+ terminal_seen.append(self.get("/v1/telemetry"))
time.sleep(0.01)
for th in threads:
th.join(30)
@@ -484,6 +760,15 @@ class ParallelService(unittest.TestCase):
# the slots were reported, and a request was admitted while another decoded in a slot (the fake logs how many
# slots were active at each admission)
self.assertTrue(any(m.get("parallel") == 2 and len(m.get("slots", [])) == 2 for m in seen))
+ self.assertTrue(any(t["work"]["requests"] for t in terminal_seen))
+ self.assertTrue(any(s.get("request_id") for t in terminal_seen for s in t["work"]["slots"]))
+ self.assertTrue(any(isinstance(r.get("first_engine_token_s"), (int, float)) and
+ r["first_engine_token_s"] > 0
+ for t in terminal_seen for r in t["work"]["requests"]
+ if r["state"] == "decoding"), "live per-request first engine token was not observed")
+ for t in terminal_seen:
+ self.assertEqual(t["quality"]["request_correlation"], "reported")
+ self.assertNotIn("input", json.dumps(t))
admitted = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")]
self.assertIn(1, admitted)
# every request recorded its own row; nothing is left running
@@ -493,6 +778,11 @@ class ParallelService(unittest.TestCase):
self.assertFalse(self.svc.status["busy"])
self.assertEqual(sorted(r["output_tokens"] for r in self.svc.history),
sorted(len(reply[t]) + 1 for t in texts))
+ self.assertTrue(all(isinstance(r.get("first_engine_token_s"), (int, float)) and
+ r["first_engine_token_s"] > 0 for r in self.svc.history))
+ clean = Endpoint(self.base).snapshot()
+ self.assertTrue(all(isinstance(r.get("first_engine_token_s"), (int, float))
+ for r in clean["recent"][:3]))
# never more than two in the slots at once (the fake logs how many were active at each admission)
active = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")]
self.assertTrue(all(a <= 1 for a in active), active)
diff --git a/serve/test_replicas.py b/serve/test_replicas.py
index f8d018671..95f1a12e6 100644
--- a/serve/test_replicas.py
+++ b/serve/test_replicas.py
@@ -4,6 +4,7 @@ import json
import sys
import tempfile
import threading
+import time
import unittest
import urllib.request
from pathlib import Path
@@ -80,6 +81,9 @@ class FakeEngine:
def alive(self):
return self.up
+ def generate(self, ids, max_new, sampling, cancel, embeddings=None):
+ yield 7
+
class RouteChoice(unittest.TestCase):
def test_least_loaded_then_affinity(self):
@@ -143,6 +147,15 @@ class RouteChoice(unittest.TestCase):
self.assertEqual(ReplicaEngine([FakeEngine(4), FakeEngine(4)]).batch, 8)
self.assertEqual(ReplicaEngine([FakeEngine(0), FakeEngine(0)]).batch, 2)
+ def test_selected_replica_is_reported_for_solo_requests_too(self):
+ engine = ReplicaEngine([FakeEngine(), FakeEngine()])
+ engine.inflight[0] = 1
+ cancel = threading.Event()
+ selected = []
+ cancel._strata_replica_selected = selected.append
+ self.assertEqual(list(engine.generate([1, 2], 1, {}, cancel)), [7])
+ self.assertEqual(selected, [1])
+
class ReplicaService(unittest.TestCase):
def start(self, slots=4, n=2):
@@ -215,6 +228,61 @@ class ReplicaService(unittest.TestCase):
self.assertEqual([r["replica"] for r in m["live"]["replicas"]], [0, 1])
self.assertEqual(m["engine"]["replicas"], 2)
+ def test_terminal_telemetry_correlates_second_replica_without_global_sample_claim(self):
+ self.start()
+ self.svc.replica_gpu_groups = [[0, 1], [2, 3]]
+ second = self.engine.engines[1]
+ request_id = "abcdef012345"
+ second.slot_live[1] = {"request_id": request_id, "state": "reading", "prompt_tokens": 100,
+ "prompt_read": 12, "generated": 0, "started": time.time(), "first_token": None}
+ first = self.engine.engines[0]
+ first.terminal_batch_sample = {"windows": 2, "processed_rows": 8, "active_rows": 4,
+ "elapsed_ms": 1000, "observed_monotonic": time.monotonic()}
+ second.terminal_batch_sample = {"windows": 2, "processed_rows": 6, "active_rows": 4,
+ "elapsed_ms": 1000, "observed_monotonic": time.monotonic()}
+ first.terminal_stage_sample = {"elapsed_us": 1_000_000, "in_flight_us": [800_000, 600_000],
+ "observed_monotonic": time.monotonic()}
+ second.terminal_stage_sample = {"elapsed_us": 1_000_000, "in_flight_us": [700_000, 500_000],
+ "observed_monotonic": time.monotonic()}
+ self.svc.backend = "cuda"
+ for child, cards in ((first, [0, 1]), (second, [2, 3])):
+ child.spawn = (*child.spawn[:4], {"CUDA_DEVICE_ORDER": "PCI_BUS_ID",
+ "CUDA_VISIBLE_DEVICES": ",".join(map(str, cards))},
+ *child.spawn[5:])
+ child.terminal_stages = [
+ {"stage": 0, "layer_start": 0, "layer_end": 19, "engine_ordinal": 0},
+ {"stage": 1, "layer_start": 20, "layer_end": 39, "engine_ordinal": 1}]
+ with self.svc.status_lock:
+ self.svc.terminal_requests[request_id] = {"id": request_id, "state": "waiting",
+ "queued_at": time.time(), "admitted_at": time.time(),
+ "prompt_tokens": 100}
+ with urllib.request.urlopen(self.base + "/v1/telemetry", timeout=10) as response:
+ snapshot = json.load(response)
+ slot = snapshot["work"]["slots"][5]
+ self.assertEqual((slot["slot"], slot["replica"], slot["group"], slot["request_id"]),
+ (5, 1, 1, request_id))
+ request = snapshot["work"]["requests"][0]
+ self.assertEqual((request["slot"], request["replica"], request["group"], request["state"]),
+ (5, 1, 1, "reading"))
+ self.assertEqual(snapshot["work"]["groups"], 2)
+ self.assertIsNone(snapshot["work"]["effective_rows_window"])
+ self.assertEqual([(row["replica"], row["batch_sample_rows"], row["batch_sample_active_rows"])
+ for row in snapshot["work"]["replica_batches"]], [(0, 8, 4), (1, 6, 4)])
+ self.assertEqual([(row["replica"], row["stage_in_flight_us"])
+ for row in snapshot["work"]["replica_stage_samples"]],
+ [(0, [800_000, 600_000]), (1, [700_000, 500_000])])
+ self.assertNotIn("stage_in_flight_us", snapshot["work"])
+ self.assertEqual(snapshot["topology"]["stages"], [])
+ self.assertEqual(snapshot["topology"]["replica_stages"][1]["stages"][1]["device_index"], 3)
+ self.assertEqual(snapshot["topology"]["replica_devices"],
+ [{"replica": 0, "devices": [0, 1]}, {"replica": 1, "devices": [2, 3]}])
+ second.spawn = (*second.spawn[:4], {"CUDA_DEVICE_ORDER": "PCI_BUS_ID",
+ "CUDA_VISIBLE_DEVICES": "9,3"}, *second.spawn[5:])
+ with urllib.request.urlopen(self.base + "/v1/telemetry", timeout=10) as response:
+ mismatch = json.load(response)
+ self.assertIsNone(mismatch["topology"]["replica_stages"][1]["stages"][0]["device_index"])
+ self.assertEqual(mismatch["topology"]["replica_stages"][1]["stages"][1]["device_index"], 3)
+
def test_engines_without_slots_run_one_each_at_once(self):
self.start(slots=0)
out = self.burst(["a" * 40, "b" * 40])
diff --git a/serve/test_security.py b/serve/test_security.py
index 0e8f260be..c50ee69ab 100644
--- a/serve/test_security.py
+++ b/serve/test_security.py
@@ -237,6 +237,55 @@ class OverHttp(unittest.TestCase):
self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
{**headers, "Authorization": "Bearer s3cret"})[0], 200)
+ def test_terminal_telemetry_requires_the_existing_key(self):
+ self.start(api_key="s3cret")
+ self.assertEqual(self.req("GET", "/v1/telemetry")[0], 401)
+ code, body, _ = self.req("GET", "/v1/telemetry", headers={"Authorization": "Bearer s3cret"})
+ self.assertEqual(code, 200)
+ self.assertEqual(body["schema_version"], 1)
+ self.assertNotIn("input", json.dumps(body))
+
+ def test_read_only_telemetry_key_does_not_authorize_inference_or_management(self):
+ self.start(api_key="inference-secret", telemetry_key="read-secret")
+ header = {"Authorization": "Bearer read-secret"}
+ self.assertEqual(self.req("GET", "/v1/telemetry", headers=header)[0], 200)
+ self.assertEqual(self.req("GET", "/metrics", headers=header)[0], 401)
+ self.assertEqual(self.req("GET", "/v1/models", headers=header)[0], 401)
+ self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
+ {**header, "Content-Type": "application/json"})[0], 401)
+ self.assertEqual(self.req("POST", "/unload", {},
+ {**header, "Content-Type": "application/json"})[0], 401)
+
+ def test_read_only_key_gets_bounded_redacted_request_activity(self):
+ self.start(api_key="inference-secret", telemetry_key="read-secret")
+ prompt = "DO_NOT_LEAK_PROMPT_ACTIVITY"
+ request = {**self.chat_body(), "messages": [{"role": "user", "content": prompt}]}
+ self.assertEqual(self.req("POST", "/v1/chat/completions", request,
+ {"Authorization": "Bearer inference-secret",
+ "Content-Type": "application/json"})[0], 200)
+ code, body, _ = self.req("GET", "/v1/telemetry",
+ headers={"Authorization": "Bearer read-secret"})
+ self.assertEqual(code, 200)
+ activity = body["activity"]
+ self.assertEqual(activity["last_seq"], len(activity["events"]))
+ self.assertLessEqual(len(activity["events"]), 32)
+ self.assertEqual(activity["events"][0]["event"], "queued")
+ self.assertEqual(activity["events"][-1]["event"], "finished")
+ self.assertEqual([e["seq"] for e in activity["events"]],
+ list(range(1, activity["last_seq"] + 1)))
+ self.assertEqual(len({e["request_id"] for e in activity["events"]}), 1)
+ serialized = json.dumps(activity)
+ for secret in (prompt, "inference-secret", "read-secret", "</think>"):
+ self.assertNotIn(secret, serialized)
+ with self.svc.status_lock:
+ for i in range(140):
+ self.svc._terminal_event_locked(f"{i:012x}", "queued")
+ bounded = self.req("GET", "/v1/telemetry",
+ headers={"Authorization": "Bearer read-secret"})[1]["activity"]
+ self.assertEqual(len(self.svc.terminal_events), 128)
+ self.assertEqual(len(bounded["events"]), 32)
+ self.assertEqual(bounded["events"][-1]["seq"], bounded["last_seq"])
+
# --- /unload and /load
def test_control_body_arrives_before_the_operation_and_reply(self):
self.start()