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

New serve/ready.py, serve/owner_guard.py and serve/launch_identity.py; server.py
gains the queue wait deadline (QueueWaitExpired/QueueCancelled), the opt-in
STRATA_BATCH_TELEMETRY plumbing (BSTAT/PSTAT parsed off the engine's token stream,
dropped from request output), the engine stage-plan reader, a main(argv, ...)
entry the terminal can call, and per-replica selection hooks; telemetry.py reports
GPU names; the tests for all of it.

server.py merged by hand onto 0.1.45: one conflict, in StrataEngine._take_control, where
0.1.45's STRATA_ADMIT_SHORT_FIRST ordering and the rebuild's queue deadline both edit the
acquire step; both are kept (ordering check first, then the deadline-bounded acquire).
Every line 0.1.45 added to server.py (the #2518 pick_slot fix, the havok multi-user
switches, the Qwen3.6 parallel/vision work) is still present.

From the owner's rebuild branch strata/rebuild-2026-10.
This commit is contained in:
Niko1221 committed 2026-10-15 10:23:23 +02:00
1 parent 79d8ea066a
commit c968d37a48
9 files changed
+1375 -88

No files matched your search

+22
View File
@@ -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()
+35
View File
@@ -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()
+46
View File
@@ -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
+3
View File
@@ -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]
+856 -82
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -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:
+294 -4
View File
@@ -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)
+68
View File
@@ -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])
+49
View File
@@ -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()