"""serve/test_server.py - the max tokens budget over both APIs, against the mock engine (no GPU, no pack). python -m unittest serve.test_server -v """ from __future__ import annotations import json import os import sys import threading import time import unittest import urllib.error import urllib.request from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 from serve.server import CTX_SLACK, ByteTokenizer, EngineDied, MockEngine, Service, StrataEngine, request_timings, serve # noqa: E402 ROOT = Path(__file__).resolve().parents[1] CTX = 4096 ANSWER = "x" * 2000 # longer than the old 1024 fallback: one token per byte class RecordingEngine(MockEngine): def generate(self, ids, max_new, sampling, cancel, embeddings=None): self.last_max_new = max_new yield from super().generate(ids, max_new, sampling, cancel, embeddings) class MaxTokens(unittest.TestCase): @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() def post(self, path, body): req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read()) except urllib.error.HTTPError as e: with e: return e.code, json.loads(e.read()) def call(self, api, text="hi", **budget): """-> (status, body, prompt tokens, completion tokens); `budget` is merged into the request as given.""" msgs = [{"role": "user", "content": text}] if api == "openai": s, b = self.post("/v1/chat/completions", {"model": "m", "messages": msgs, **budget}) u = b.get("usage", {}) return s, b, u.get("prompt_tokens"), u.get("completion_tokens") s, b = self.post("/v1/messages", {"model": "m", "messages": msgs, **budget}) u = b.get("usage", {}) return s, b, u.get("input_tokens"), u.get("output_tokens") def test_unset_budget_is_the_rest_of_the_context(self): cases = {"openai": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}, {"max_completion_tokens": -1}, {"max_completion_tokens": None, "max_tokens": None}], "anthropic": [{"max_tokens": -1}, {"max_tokens": 0}, {}, {"max_tokens": None}]} for api, budgets in cases.items(): for budget in budgets: with self.subTest(api=api, budget=budget): s, b, pt, ct = self.call(api, **budget) self.assertEqual(s, 200, b) self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) self.assertGreater(ct, 1024) # the whole answer, not cut at the old 1024 fallback def test_explicit_budget_is_honoured(self): for api, budget in [("openai", {"max_tokens": 50}), ("openai", {"max_completion_tokens": 50}), ("openai", {"max_completion_tokens": 50, "max_tokens": 9}), ("anthropic", {"max_tokens": 50}), ("openai", {"max_tokens": 1500}), ("anthropic", {"max_tokens": 1500})]: with self.subTest(api=api, budget=budget): want = budget.get("max_completion_tokens") or budget["max_tokens"] s, b, _, ct = self.call(api, **budget) self.assertEqual(s, 200, b) self.assertEqual(self.engine.last_max_new, want) self.assertEqual(ct, want) def test_explicit_budget_over_the_context_is_rejected(self): for api in ("openai", "anthropic"): with self.subTest(api=api): s, b, _, _ = self.call(api, max_tokens=CTX) self.assertEqual(s, 400) self.assertIn("exceeds the context", b["error"]["message"]) def test_unset_budget_with_a_near_full_prompt(self): _, _, pt0, _ = self.call("openai", max_tokens=1) overhead = pt0 - len("hi") # the template's tokens around the user text for api in ("openai", "anthropic"): _, _, pa, _ = self.call(api, max_tokens=1) over = pa - pt0 # the Anthropic template may differ slightly with self.subTest(api=api, room=5): # a few tokens left: the budget is exactly those text = "y" * (CTX - CTX_SLACK - overhead - over - 5) s, b, pt, ct = self.call(api, text=text, max_tokens=-1) self.assertEqual(s, 200, b) self.assertEqual(self.engine.last_max_new, 5) self.assertEqual(ct, 5) with self.subTest(api=api, room=0): # nothing left: rejected, not truncated text = "y" * (CTX - CTX_SLACK - overhead - over) s, b, _, _ = self.call(api, text=text) self.assertEqual(s, 400, b) self.assertIn("no room to answer", b["error"]["message"]) def test_debug_log_shows_the_resolved_budget(self): import contextlib import io os.environ["STRATA_DEBUG"] = "1" try: for api in ("openai", "anthropic"): with self.subTest(api=api): out = io.StringIO() with contextlib.redirect_stdout(out): _, _, pt, _ = self.call(api, max_tokens=-1) self.assertIn(f"max_new={CTX - CTX_SLACK - pt} ", out.getvalue()) finally: del os.environ["STRATA_DEBUG"] class FitMaxTokens(unittest.TestCase): """PR #24: --fit-max-tokens clamps an explicit budget that overshoots the context instead of a 400.""" @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = RecordingEngine(tok, "\n\n" + ANSWER, max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), fit_max_tokens=True) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() post = MaxTokens.post call = MaxTokens.call def test_overshoot_is_clamped_to_the_room(self): for api in ("openai", "anthropic"): with self.subTest(api=api): s, b, pt, ct = self.call(api, max_tokens=CTX) self.assertEqual(s, 200, b) self.assertEqual(self.engine.last_max_new, CTX - CTX_SLACK - pt) def test_a_budget_that_fits_is_unchanged(self): s, b, _, ct = self.call("openai", max_tokens=50) self.assertEqual(s, 200, b) self.assertEqual(self.engine.last_max_new, 50) def test_no_room_is_still_a_400(self): _, _, pt0, _ = self.call("openai", max_tokens=1) overhead = pt0 - len("hi") s, b, _, _ = self.call("openai", text="y" * (CTX - CTX_SLACK - overhead), max_tokens=100) self.assertEqual(s, 400, b) self.assertIn("no room to answer", b["error"]["message"]) class ClientShapes(unittest.TestCase): """What real clients send: Claude Code posts /v1/messages?beta=true (issue #55) and puts hook context into the conversation as a mid-conversation system message (issue #56); some OpenAI clients send a late developer message.""" @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = RecordingPrompt(tok, "\n\n2", max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() def post(self, path, body): req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read()) except urllib.error.HTTPError as e: with e: return e.code, json.loads(e.read()) def prompt_text(self): return bytes(i for i in self.engine.last_ids if i < 256).decode("utf-8", "replace") def test_query_string(self): body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]} for path in ("/v1/messages?beta=true", "/v1/chat/completions?api-version=1", "/v1/messages/?beta=true"): status, b = self.post(path, body) self.assertEqual(status, 200, (path, b)) status, _ = self.post("/v1/nothing?beta=true", body) self.assertEqual(status, 404) def test_anthropic_mid_conversation_system(self): status, b = self.post("/v1/messages?beta=true", { "model": "x", "max_tokens": 50, "system": [{"type": "text", "text": "You are terse."}], "messages": [ {"role": "user", "content": [{"type": "text", "text": "1+1? digits only"}]}, {"role": "system", "content": [{"type": "text", "text": "answer in digits"}]}]}) self.assertEqual(status, 200, b) text = self.prompt_text() self.assertIn("You are terse.", text) self.assertIn("answer in digits", text) self.assertLess(text.index("You are terse."), text.index("1+1?")) # the first system stays first self.assertLess(text.index("1+1?"), text.index("answer in digits")) # the late one stays in place def test_openai_late_developer_and_system(self): status, b = self.post("/v1/chat/completions", { "model": "x", "max_tokens": 50, "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi"}, {"role": "developer", "content": "Now use digits."}, {"role": "system", "content": "Also this."}, {"role": "user", "content": "1+1?"}]}) self.assertEqual(status, 200, b) text = self.prompt_text() for part in ("Be brief.", "Now use digits.", "Also this.", "1+1?"): self.assertIn(part, text) def test_leading_system_unchanged(self): from serve.frontend import anthropic_to_messages, openai_to_messages msgs, _, _ = openai_to_messages({"messages": [{"role": "developer", "content": "D"}, {"role": "user", "content": "u"}]}) self.assertEqual([m["role"] for m in msgs], ["system", "user"]) msgs, _, _ = anthropic_to_messages({"system": "S", "messages": [{"role": "user", "content": "u"}]}) self.assertEqual([m["role"] for m in msgs], ["system", "user"]) class SamplingKeys(unittest.TestCase): """The GEN line's sampling keys: top_k 0 ("off") or wider than the engine's 64 get the widest list, 64 (they used to fall back to the engine default 20); a penalty always carries its window.""" def keys(self, **sampling): return StrataEngine.sampling_keys(sampling).split() def test_top_k(self): self.assertIn("top_k=10", self.keys(temperature=0.7, top_k=10)) self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=64)) self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=0)) self.assertIn("top_k=64", self.keys(temperature=0.7, top_k=100)) for bad in (-1, True, 2.5, "20"): self.assertFalse([k for k in self.keys(temperature=0.7, top_k=bad) if k.startswith("top_k=")], bad) def test_tune_keys(self): k = self.keys(temperature=0, strata_tune={"pcie_frac": 0.2, "spec_min_p": 0.7}) self.assertIn("pcie_frac=0.2", k) self.assertIn("spec_min_p=0.7", k) bad = self.keys(strata_tune={"pcie_frac": 3, "spec_min_p": True, "pool_workers": 2}) self.assertFalse([x for x in bad if x.split("=")[0] in ("pcie_frac", "spec_min_p", "pool_workers")]) def test_penalty_window(self): self.assertIn("penalty_last_n=64", self.keys(presence_penalty=1.5)) self.assertIn("penalty_last_n=4096", self.keys(repetition_penalty=1.1, penalty_last_n=4096)) self.assertFalse([k for k in self.keys(temperature=0.7) if k.startswith("penalty")]) class GpuChoice(unittest.TestCase): """Issue #51: the config's \"gpu\" reaches the engine as CUDA_VISIBLE_DEVICES, numbered like nvidia-smi.""" def test_env(self): from serve.server import child_env env = child_env({"gpu": 1}) self.assertEqual(env["CUDA_VISIBLE_DEVICES"], "1") self.assertEqual(env["CUDA_DEVICE_ORDER"], "PCI_BUS_ID") plain = child_env({}) # no choice: the environment as it was (existing installs) self.assertEqual(plain.get("CUDA_VISIBLE_DEVICES"), os.environ.get("CUDA_VISIBLE_DEVICES")) self.assertEqual(plain.get("CUDA_DEVICE_ORDER"), os.environ.get("CUDA_DEVICE_ORDER")) class RecordingPrompt(MockEngine): def generate(self, ids, max_new, sampling, cancel, embeddings=None): self.last_ids = list(ids) yield from super().generate(ids, max_new, sampling, cancel, embeddings) class DyingEngine(MockEngine): """Issue #27: an engine that dies after a few tokens of its first answer, and comes back when restarted.""" def __init__(self, tok, script, max_context): super().__init__(tok, script, max_context=max_context) self.dead, self.restarts, self.die_after = False, 0, 5 def alive(self): return not self.dead def restart(self): self.dead, self.die_after = False, None self.restarts += 1 def generate(self, ids, max_new, sampling, cancel, embeddings=None): for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): if self.die_after is not None and i == self.die_after: self.dead = True raise EngineDied("the engine stopped unexpectedly (exit code -9)") yield t class EngineDeath(unittest.TestCase): """Issue #27: a dead engine is an error (not "length"), and the next request starts it again.""" def test_error_then_restart(self): tok = ByteTokenizer() eng = DyingEngine(tok, "\n\n" + ANSWER, max_context=CTX) svc = Service(eng, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) httpd = serve(svc, port=0) base = f"http://127.0.0.1:{httpd.server_address[1]}" try: def post(body): req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.read().decode() except urllib.error.HTTPError as e: with e: return e.code, e.read().decode() msgs = [{"role": "user", "content": "hi"}] code, text = post({"model": "m", "messages": msgs, "max_tokens": 50, "stream": True}) self.assertEqual(code, 200) self.assertIn('"error"', text) self.assertIn("stopped unexpectedly", text) self.assertTrue(text.rstrip().endswith("data: [DONE]")) self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") code, text = post({"model": "m", "messages": msgs, "max_tokens": 50}) self.assertEqual(code, 200, text) self.assertEqual(eng.restarts, 1) self.assertEqual(json.loads(text)["usage"]["completion_tokens"], 50) finally: httpd.shutdown() httpd.server_close() def test_engine_err_mid_stream(self): """The engine's ERR line after the stream started reaches the client as an error event (it used to be a 400 written into the open stream, which clients read as an empty answer).""" class ErrEngine(MockEngine): def generate(self, ids, max_new, sampling, cancel, embeddings=None): yield None # a prompt-progress heartbeat: the stream has started raise ValueError("verify: layer 31 never rang (an illegal memory access was encountered)") tok = ByteTokenizer() svc = Service(ErrEngine(tok, ANSWER, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) httpd = serve(svc, port=0) base = f"http://127.0.0.1:{httpd.server_address[1]}" try: for path, body in [("/v1/chat/completions", {"model": "m", "stream": True, "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]}), ("/v1/messages", {"model": "m", "stream": True, "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}]})]: req = urllib.request.Request(base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=30) as r: text = r.read().decode() self.assertIn("illegal memory access", text, path) self.assertNotIn("HTTP/1", text, path) self.assertEqual(svc.metrics()["requests"][0]["finish"], "error") finally: httpd.shutdown() httpd.server_close() class LiveRate(unittest.TestCase): """The Monitor's Speed readout: live.tok_s is a rate, and a request that never got a DONE keeps no counters. It used to be `generated / (now - first_token)` - the mean since the first token, whose first sample is 1/elapsed. Against a paced engine that reads five-digit numbers for the first instant of every answer and undershoots for the first second after that. It is now the rate over the last RATE_WINDOW_S, with the mean still available as `live.tok_s_mean` for anyone who wants it.""" PACE_S = 0.02 # 50 tokens/s: a 30-token answer takes about 0.6 s TOKENS = 30 def setUp(self): self.tok = ByteTokenizer() self.engine = MockEngine(self.tok, "x" * self.TOKENS, max_context=CTX, delay_s=self.PACE_S) self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) self.httpd = serve(self.svc, port=0) self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" def tearDown(self): self.httpd.shutdown() self.httpd.server_close() def metrics(self): with urllib.request.urlopen(self.base + "/metrics", timeout=10) as r: return json.loads(r.read()) def test_the_live_number_is_a_rate(self): live_samples, stop = [], threading.Event() def poll(): # what the Monitor polls, at 10 ms while not stop.is_set(): live = self.metrics()["live"] if live["state"] == "generating" and live["tok_s"] is not None: live_samples.append((live["generated"], live["tok_s"], live["tok_s_mean"])) time.sleep(0.01) body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "temperature": 0, "messages": [{"role": "user", "content": "hi"}]}).encode() watcher = threading.Thread(target=poll, daemon=True) watcher.start() t0 = time.time() try: with urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=body, headers={"Content-Type": "application/json"}), timeout=30) as r: usage = json.loads(r.read())["usage"] finally: stop.set() watcher.join(2) true_rate = usage["completion_tokens"] / (time.time() - t0) self.assertGreaterEqual(len(live_samples), 3, "too few live readings to judge the readout") self.assertLess(max(s for _g, s, _m in live_samples), 4 * true_rate, f"live.tok_s peaked at {max(s for _g, s, _m in live_samples):.1f} tok/s " f"for a {true_rate:.1f} tok/s engine") self.assertEqual(self.metrics()["live"]["state"], "idle") self.assertIsNone(self.metrics()["live"]["tok_s"]) def test_a_request_without_a_done_keeps_no_engine_counters(self): """An engine that dies mid-answer: the previous request's `last` must not become this row's decode rate.""" class HalfDead(MockEngine): last = {"generated": 99, "prompt_tokens": 9, "prompt_ms": 10.0, "decode_ms": 100.0, "finish": "stop"} def generate(self, ids, max_new, sampling, cancel, embeddings=None): for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): if i == 3: raise EngineDied("the engine stopped unexpectedly (exit code -9)") yield t tok = ByteTokenizer() svc = Service(HalfDead(tok, "x" * self.TOKENS, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) httpd = serve(svc, port=0) base = f"http://127.0.0.1:{httpd.server_address[1]}" try: body = json.dumps({"model": "m", "max_tokens": self.TOKENS, "stream": True, "messages": [{"role": "user", "content": "hi"}]}).encode() with urllib.request.urlopen(urllib.request.Request(base + "/v1/chat/completions", data=body, headers={"Content-Type": "application/json"}), timeout=30) as r: text = r.read().decode() self.assertIn('"error"', text) row = svc.metrics()["requests"][0] self.assertEqual(row["finish"], "error") self.assertEqual(row["output_tokens"], 3) self.assertIsNone(row["decode_tok_s"], "the previous request's counters were recorded as this one's") self.assertIsNone(row["engine_generated"]) finally: httpd.shutdown() httpd.server_close() class SharedSettings(unittest.TestCase): """The web app's "Use for other apps too": POST /settings makes its Chat settings every client's defaults.""" @classmethod def setUpClass(cls): import tempfile class Sampled(RecordingEngine): def generate(self, ids, max_new, sampling, cancel, embeddings=None): self.last_sampling = dict(sampling or {}) yield from super().generate(ids, max_new, sampling, cancel, embeddings) tok = ByteTokenizer() cls.engine = Sampled(tok, "\n\nhello", max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.tmp = tempfile.TemporaryDirectory() cls.svc.shared_path = os.path.join(cls.tmp.name, "strata-x.shared-settings.json") cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() cls.tmp.cleanup() def req(self, path, body, headers=None, raw=None): h = {"Content-Type": "application/json", **(headers or {})} r = urllib.request.Request(self.base + path, data=raw if raw is not None else json.dumps(body).encode(), headers=h) try: with urllib.request.urlopen(r, timeout=30) as resp: return resp.status, json.loads(resp.read()) except urllib.error.HTTPError as e: with e: return e.code, json.loads(e.read()) def chat(self, **extra): return self.req("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "hi"}], **extra}) def tearDown(self): self.svc.set_shared(None) def test_other_apps_get_the_chat_settings(self): d = {"temperature": 0.3, "top_p": 0.9, "top_k": 10, "seed": 7, "max_tokens": 77, "reasoning_effort": "low", "experimental_speed_projection": False} code, b = self.req("/settings", {"defaults": d}) self.assertEqual(code, 200, b) self.assertTrue(b["shared"]) self.assertTrue(os.path.exists(self.svc.shared_path)) code, _ = self.chat() # a client that sets nothing self.assertEqual(code, 200) got = self.engine.last_sampling for k in ("temperature", "top_p", "top_k", "seed", "experimental_speed_projection"): self.assertEqual(got[k], d[k], k) self.assertEqual(self.engine.last_max_new, 77) code, _ = self.chat(temperature=0.9, max_tokens=5) # its own values win self.assertEqual(self.engine.last_sampling["temperature"], 0.9) self.assertEqual(self.engine.last_max_new, 5) r = self.svc.with_shared({"messages": []}, "openai") self.assertEqual(r["reasoning_effort"], "low") self.assertEqual(self.svc.with_shared({"reasoning_effort": "high"}, "openai")["reasoning_effort"], "high") self.assertEqual(self.svc.with_shared({}, "anthropic")["output_config"], {"effort": "low"}) def test_off_again(self): self.req("/settings", {"defaults": {"temperature": 0.3}}) code, b = self.req("/settings", {"defaults": None}) self.assertEqual((code, b["shared"]), (200, False)) self.assertFalse(os.path.exists(self.svc.shared_path)) self.chat() self.assertNotIn("temperature", self.engine.last_sampling) def test_only_strata_s_own_page_may_set_them(self): code, _ = self.req("/settings", None, {"Content-Type": "text/plain"}, raw=b'{"defaults": {"temperature": 1}}') self.assertEqual(code, 415) code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://evil.example"}) self.assertEqual(code, 403) code, b = self.req("/settings", {"defaults": {"temperature": 9}}) self.assertEqual(code, 400) self.assertIn("temperature", b["error"]["message"]) self.assertEqual(self.svc.shared, {}) host = self.base.split("://", 1)[1] code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://" + host}) self.assertEqual(code, 200) def test_they_need_the_key_when_one_is_set(self): self.svc.api_key = "secret" try: self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}})[0], 401) self.assertEqual(self.req("/settings", {"defaults": {"temperature": 1}}, {"Authorization": "Bearer secret"})[0], 200) finally: self.svc.api_key = "" class WebApp(unittest.TestCase): """The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics.""" @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.svc = Service(RecordingEngine(tok, "\n\nhello", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() def get(self, path, headers=None): req = urllib.request.Request(self.base + path, headers=headers or {}) try: with urllib.request.urlopen(req, timeout=10) as r: return r.status, r.headers.get("Content-Type", ""), r.read() except urllib.error.HTTPError as e: return e.code, e.headers.get("Content-Type", ""), e.read() def test_page_and_files(self): code, ctype, body = self.get("/") self.assertEqual(code, 200) self.assertIn("text/html", ctype) self.assertIn(b"\"web/app.js\"", body) # relative since #82 (works behind a path-prefixed proxy) for path, want in (("/web/app.js", "javascript"), ("/web/app.css", "text/css"), ("/web/tokens.css", "text/css"), ("/web/components.css", "text/css"), ("/web/sprite.svg", "image/svg+xml")): with self.subTest(path=path): code, ctype, _ = self.get(path) self.assertEqual(code, 200) self.assertIn(want, ctype) def test_only_the_app_files_are_served(self): for path in ("/web/..%2Fserver.py", "/web/index.html", "/web/test.py", "/fonts/..%2F..%2Fsetup.py", "/fonts/missing.woff2", "/fonts/x.ttf"): with self.subTest(path=path): self.assertEqual(self.get(path)[0], 404) def test_metrics(self): data = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}).encode() urllib.request.urlopen(urllib.request.Request(self.base + "/v1/chat/completions", data=data, headers={"Content-Type": "application/json"}), timeout=10).read() code, ctype, body = self.get("/metrics") self.assertEqual(code, 200) m = json.loads(body) for key in ("engine", "live", "requests", "hardware", "hardware_static", "history"): self.assertIn(key, m) self.assertEqual(m["engine"]["max_context"], CTX) self.assertEqual(m["live"]["state"], "idle") self.assertEqual(m["requests"][0]["output_tokens"], 5) def test_model_discovery_and_props(self): svc = self.svc previous = svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared try: svc.engine.max_context = 262144 svc.sampling_defaults = {"temperature": 1.0, "repetition_penalty": 1.1} svc.shared = {"temperature": 0.7, "max_tokens": 4096} for vision in (None, object()): svc.vision = vision for path in ("/models", "/v1/models"): code, _, body = self.get(path) self.assertEqual(code, 200) models = json.loads(body)["data"] self.assertEqual(len(models), 1) model = models[0] self.assertEqual(model["id"], svc.model) self.assertEqual(model["status"]["value"], "loaded") self.assertEqual(model["meta"]["n_ctx"], 262144) self.assertEqual(model["architecture"]["input_modalities"], ["text", "image"] if vision else ["text"]) code, _, body = self.get("/props?model=" + svc.model + "&autoload=false") self.assertEqual(code, 200) props = json.loads(body) self.assertEqual(props["default_generation_settings"]["n_ctx"], 262144) self.assertEqual(props["default_generation_settings"]["params"], {"temperature": 0.7, "repeat_penalty": 1.1, "n_predict": 4096}) self.assertEqual(props["chat_template"], (ROOT / "serve/chat_template.jinja").read_text(encoding="utf-8")) self.assertEqual(props["modalities"]["vision"], vision is not None) self.assertEqual(props["total_slots"], 1) self.assertFalse(props["models_autoload"]) svc.shared = {} props = json.loads(self.get("/props")[2]) self.assertEqual(props["default_generation_settings"]["params"]["n_predict"], -1) self.assertEqual(self.get("/props?model=not-loaded&autoload=true")[0], 404) finally: svc.engine.max_context, svc.vision, svc.sampling_defaults, svc.shared = previous def test_discovery_needs_the_api_key(self): self.svc.api_key = "secret" try: for path in ("/models", "/v1/models", "/props", "/slots"): self.assertEqual(self.get(path)[0], 401) self.assertEqual(self.get(path, {"Authorization": "Bearer secret"})[0], 200) finally: self.svc.api_key = "" def test_build_model_path_and_slot_status(self): engine = self.svc.engine engine.model_path = "models/example.gguf" engine.info = {"version": "0.1.21"} try: props = json.loads(self.get("/props")[2]) self.assertEqual(props["model_path"], engine.model_path) self.assertEqual(props["build_info"], "Strata 0.1.21") for busy in (True, False): with self.svc.status_lock: self.svc.status["busy"] = busy code, _, body = self.get("/slots") self.assertEqual(code, 200) self.assertEqual(json.loads(body), [{"id": 0, "n_ctx": CTX, "is_processing": busy}]) finally: with self.svc.status_lock: self.svc.status["busy"] = False del engine.model_path, engine.info props = json.loads(self.get("/props")[2]) self.assertNotIn("build_info", props) self.assertNotIn("model_path", props) def test_discovery_does_not_restart_a_dead_engine(self): self.svc.engine.alive = lambda: False try: for path in ("/models", "/v1/models"): code, _, body = self.get(path) self.assertEqual(code, 200) self.assertEqual(json.loads(body)["data"], []) self.assertEqual(self.get("/props")[0], 503) self.assertEqual(json.loads(self.get("/slots")[2]), []) finally: del self.svc.engine.alive def test_metrics_need_the_key_when_one_is_set(self): self.svc.api_key = "secret" try: self.assertEqual(self.get("/metrics")[0], 401) self.assertEqual(self.get("/metrics", {"Authorization": "Bearer secret"})[0], 200) self.assertEqual(self.get("/")[0], 200) # the page itself asks for the key finally: self.svc.api_key = "" class ClockedEngine(MockEngine): """The mock engine with StrataEngine's clock: `last` as the engine's DONE line gives it, the conversation cache holding the first REUSED tokens of every prompt.""" REUSED = 5 def generate(self, ids, max_new, sampling, cancel, embeddings=None): n = 0 try: for t in super().generate(ids, max_new, sampling, cancel, embeddings): n += 1 yield t finally: # as StrataEngine reads its DONE line: also when the server closes the request at a stop token self.last = {"generated": n, "prompt_tokens": len(ids), "prompt_ms": 40.0, "decode_ms": 20.0 * n, "finish": "stop", "reused": min(self.REUSED, len(ids)), "hits": 9, "lookups": 10} class UsageAndStatus(unittest.TestCase): """What clients read besides the text: the part of the prompt the conversation cache held (OpenAI's prompt_tokens_details.cached_tokens, Anthropic's cache_read_input_tokens), llama.cpp's timings, GET /v1/status.""" @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = ClockedEngine(tok, "\n\nok", max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @classmethod def tearDownClass(cls): cls.httpd.shutdown() cls.httpd.server_close() def request(self, path, body=None): req = urllib.request.Request(self.base + path, data=None if body is None else json.dumps(body).encode(), headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"}) with urllib.request.urlopen(req, timeout=30) as r: return r.status, r.read() def chat(self, path, stream=False): body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} status, raw = self.request(path, body) self.assertEqual(status, 200) if not stream: return json.loads(raw) return [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")] def test_openai(self): b = self.chat("/v1/chat/completions") u, t = b["usage"], b["timings"] self.assertEqual(u["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) self.assertEqual(t["cache_n"], ClockedEngine.REUSED) self.assertEqual(t["prompt_n"] + t["cache_n"], u["prompt_tokens"]) self.assertEqual(t["predicted_n"], u["completion_tokens"]) self.assertAlmostEqual(t["prompt_per_second"], t["prompt_n"] / 0.040, delta=0.1) self.assertAlmostEqual(t["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token def test_openai_stream(self): last = self.chat("/v1/chat/completions", stream=True)[-1] self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], len(self.engine.last_prompt)) self.assertGreater(u["output_tokens"], 0) def test_v1_status(self): self.chat("/v1/chat/completions") status, raw = self.request("/v1/status") self.assertEqual(status, 200) s = json.loads(raw) self.assertEqual(s["model"], self.svc.model) self.assertEqual(s["context"]["max_positions"], CTX) self.assertEqual(s["concurrency"]["serving"], 1) self.assertFalse(s["vision"]["available"]) self.assertEqual(s["activity"]["in_flight"], 0) self.assertGreaterEqual(s["activity"]["requests"], 1) self.assertEqual(s["last_timings"]["cache_n"], ClockedEngine.REUSED) self.assertIn("at", s["last_timings"]) def test_no_clock(self): """An engine without a clock (MockEngine): no timings, nothing cached.""" tok = ByteTokenizer() svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) httpd = serve(svc, port=0) try: data = json.dumps({"model": "x", "max_tokens": 5, "messages": [{"role": "user", "content": "hi"}]}).encode() req = urllib.request.Request(f"http://127.0.0.1:{httpd.server_address[1]}/v1/chat/completions", data=data, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=30) as r: b = json.loads(r.read()) self.assertNotIn("timings", b) self.assertEqual(b["usage"]["prompt_tokens_details"]["cached_tokens"], 0) self.assertIsNone(svc.v1_status()["last_timings"]) finally: httpd.shutdown() httpd.server_close() class TimingsDrafts(unittest.TestCase): """`timings` carries the speculative draft counts (PR #83's fields) only when the engine reported them.""" def test_draft_fields(self): base = {"prompt_ms": 100.0, "decode_ms": 200.0, "generated": 20, "reused": 4} t = request_timings(24, 20, dict(base, drafts_offered=15, drafts_accepted=11)) self.assertEqual((t["draft_n"], t["draft_n_accepted"]), (15, 11)) self.assertEqual((t["prompt_n"], t["cache_n"]), (20, 4)) self.assertNotIn("draft_n", request_timings(24, 20, base)) self.assertIsNone(request_timings(24, 20, {})) if __name__ == "__main__": unittest.main()