okami.mom/strata

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

Niko1221Merge commit 'e0a932a32' into f-split-launchda4a3a476

main
13.7 KiB265 linesraw
1"""Request inspection through HTTP; no native model or GPU is required."""
2import json
3import threading
4import time
5import unittest
6import urllib.error
7import urllib.request
8from concurrent.futures import ThreadPoolExecutor
9from pathlib import Path
10from unittest import mock
11
12from serve.frontend import ChatTemplate
13from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve
14
15
16class ReloadableEngine(MockEngine):
17    def __init__(self, *args, **kwargs):
18        super().__init__(*args, **kwargs)
19        self.running, self.unloaded = True, False
20
21    def alive(self):
22        return self.running
23
24    def unload(self):
25        self.running, self.unloaded = False, True
26
27    def restart(self):
28        self.running, self.unloaded = True, False
29
30
31class MonitorOff(unittest.TestCase):
32    """#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist."""
33
34    def test_off_by_default(self):
35        tok = ByteTokenizer()
36        svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok,
37                      ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
38        httpd = serve(svc, port=0)
39        base = f"http://127.0.0.1:{httpd.server_address[1]}"
40        try:
41            req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"},
42                                         data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode())
43            with urllib.request.urlopen(req, timeout=10) as r:
44                self.assertEqual(r.status, 200)
45            self.assertEqual(len(svc.api_requests), 0)
46            for path in ("/api/requests", "/api-monitor"):
47                with self.assertRaises(urllib.error.HTTPError) as e:
48                    urllib.request.urlopen(base + path, timeout=10)
49                self.assertEqual(e.exception.code, 404, path)
50                e.exception.close()
51        finally:
52            httpd.shutdown()
53            httpd.server_close()
54
55
56class Monitor(unittest.TestCase):
57    def setUp(self):
58        self.tok = ByteTokenizer()
59        self.engine = ReloadableEngine(self.tok, "Thought.</think>\nHello <script>alert(1)</script>.", max_context=16384)
60        self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
61        self.svc.api_monitor = True                       # opt-in ("api_monitor": true / --api-monitor)
62        self.httpd = serve(self.svc, port=0)
63        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
64
65    def tearDown(self):
66        self.httpd.shutdown()
67        self.httpd.server_close()
68
69    def request(self, path, body=None, headers=None):
70        req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,
71                                     headers={"Content-Type": "application/json", **(headers or {})})
72        try:
73            response = urllib.request.urlopen(req, timeout=10)
74        except urllib.error.HTTPError as error:
75            response = error
76        with response:
77            raw = response.read().decode()
78            return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw
79
80    def chat(self, api="openai", **kwargs):
81        # Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI
82        think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else             {"reasoning_effort": "low"}
83        return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions",
84                            {"messages": [{"role": "user", "content": "Say hello."}],
85                             "max_tokens": 256, **think, **kwargs})
86
87    def latest(self):
88        summary = self.request("/api/requests")[1]["requests"][0]
89        return self.request("/api/requests?id=" + summary["id"])[1]
90
91    def test_output_and_reasoning_for_both_dialects_and_stream_modes(self):
92        for api in ("openai", "anthropic"):
93            for stream in (False, True):
94                with self.subTest(api=api, stream=stream):
95                    code, reply = self.chat(api, stream=stream)
96                    self.assertEqual(code, 200)
97                    record = self.latest()
98                    self.assertEqual(record["state"], "completed")
99                    self.assertEqual(record["http_status"], 200)
100                    self.assertIn("Say hello.", record["input"])
101                    self.assertIn("<script>alert(1)</script>", record["output"])
102                    self.assertIn("Thought.", record["reasoning"])
103                    self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0)
104                    self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"])
105                    self.assertNotIn("_clock", record)
106                    if not stream:
107                        self.assertEqual(json.loads(record["response"]), reply)
108                    else:
109                        self.assertNotIn("response", record)
110
111    def test_error_and_engine_death_are_not_successes(self):
112        # a request the server refuses is an error record: the strict mode (fit_max_tokens off) refuses a max_tokens
113        # that overshoots the context, the default shortens it (serve/test_server.py MaxTokens)
114        self.svc.fit_max_tokens = False
115        self.assertEqual(self.chat(max_tokens=20000)[0], 400)
116        self.svc.fit_max_tokens = True
117        self.assertEqual(self.latest()["state"], "error")
118        for api in ("openai", "anthropic"):
119            for stream in (False, True):
120                with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")):
121                    self.chat(api, stream=stream)
122                    record = self.latest()
123                    self.assertEqual(record["state"], "error")
124                    self.assertIn("stopped", record["error"]["message"])
125                    self.assertEqual(record["output"], "")
126                    self.assertNotIn("timings", record)
127
128    def test_history_is_authorized_and_does_not_capture_headers(self):
129        self.svc.api_key = "secret"
130        auth = {"Authorization": "Bearer secret"}
131        self.assertEqual(self.request("/api/requests")[0], 401)
132        self.assertEqual(self.request("/api/requests?id=missing")[0], 401)
133        self.assertEqual(len(self.svc.api_requests), 0)
134        self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200)
135        summary = self.request("/api/requests", headers=auth)[1]["requests"][0]
136        self.assertNotIn("input", summary)
137        self.assertNotIn("output", summary)
138        self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401)
139        detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1]
140        self.assertNotIn("secret", json.dumps(detail))
141
142    def test_capture_is_bounded_and_eviction_returns_404(self):
143        huge = "x" * 262200
144        first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]})
145        self.assertEqual(len(first["input"]), 262144)
146        self.assertTrue(first["input_truncated"])
147        for _ in range(100):
148            self.svc.begin_request("/v1/chat/completions", {"messages": []})
149        self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100)
150        self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404)
151        # Exercise output capture without making a mock engine emit 262K tokens.
152        handler = object.__new__(self.httpd.RequestHandlerClass)
153        handler.record = self.svc.api_requests[-1]
154        chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]}
155        list(handler._capture((item for item in [chunk]), "openai"))
156        for field in ("output", "reasoning"):
157            self.assertEqual(len(handler.record[field]), 262144)
158            self.assertTrue(handler.record[field + "_truncated"])
159
160    def test_queue_wait_and_loading_are_attributed_separately(self):
161        self.engine.unload()
162        entered, release = threading.Event(), threading.Event()
163        original = self.engine.restart
164        def restart():
165            entered.set()
166            self.assertTrue(release.wait(5))
167            original()
168        with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool:
169            first = pool.submit(self.chat)
170            self.assertTrue(entered.wait(5))
171            second = pool.submit(self.chat)
172            deadline = time.monotonic() + 5
173            while len(self.svc.api_requests) < 2 and time.monotonic() < deadline:
174                time.sleep(0.01)
175            self.assertEqual(len(self.svc.api_requests), 2)
176            history = self.request("/api/requests")[1]
177            self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"})
178            self.assertFalse(history["loaded"])
179            self.assertTrue(history["auto_load"])
180            time.sleep(0.03)
181            release.set()
182            self.assertEqual(first.result()[0], 200)
183            self.assertEqual(second.result()[0], 200)
184        records = list(self.svc.api_requests)
185        self.assertGreater(records[0]["load_s"], 0.02)
186        self.assertGreater(records[1]["queue_s"], 0.02)
187        self.assertLess(records[1]["load_s"], records[0]["load_s"])
188        self.assertTrue(all(r["state"] == "completed" for r in records))
189
190    def test_page_and_relative_assets_are_served(self):
191        code, html = self.request("/api-monitor")
192        self.assertEqual(code, 200)
193        self.assertIn('src="/web/monitor.js"', html)
194        code, script = self.request("/web/monitor.js")
195        self.assertEqual(code, 200)
196        self.assertIn("textContent", script)
197        self.assertNotIn("innerHTML", script)
198        self.assertEqual(self.request("/web/../server.py")[0], 404)
199
200
201class ConversationCacheCard(unittest.TestCase):
202    """#596: /metrics' "conversation_cache": the parked conversations from the engine's log lines, the budget and
203    slots from its INFO line, and how much of the prompts the cache gave back."""
204
205    PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 "
206            "snapshot_bytes=104857600 reused_kv_bytes=0\n")
207    RESTORE = "strata serve: conversation cache: restored 4000 tokens (exact) in 30.0 ms; parked=2 bytes=209715200\n"
208
209    def test_the_log(self):
210        from serve.server import ConvCacheLog
211        import tempfile
212        with tempfile.TemporaryDirectory() as d:
213            log = Path(d) / "strata.log"
214            log.write_text("an earlier run\n" + self.PARK, encoding="utf-8")
215            start = log.stat().st_size                 # this run starts here: the earlier run's park is not counted
216            c = ConvCacheLog()
217            self.assertEqual(c.poll(str(log), start)["parked"], 0)
218            with open(log, "a", encoding="utf-8") as f:
219                f.write("strata serve: something else\n" + self.PARK + self.RESTORE + "strata serve: conversation ca")
220            st = c.poll(str(log), start)
221            self.assertEqual((st["parked"], st["bytes"], st["parks"], st["restores"]), (2, 209715200, 1, 1))
222            self.assertEqual((st["last_event"], st["last_tokens"]), ("restored", 4000))
223            with open(log, "a", encoding="utf-8") as f:   # the cut line is read once it is whole
224                f.write("che: dropped 1 superseded copy of this conversation; parked=1\n")
225            self.assertEqual(c.poll(str(log), start)["parked"], 1)
226            self.assertEqual(c.poll(str(log), log.stat().st_size)["parked"], 0)   # the engine started again
227            self.assertEqual(c.poll(None, None)["parked"], 0)
228
229    def test_metrics(self):
230        tok = ByteTokenizer()
231        engine = MockEngine(tok, "Thought.</think>\nHello.", max_context=4096)
232        engine.info = {"conversation_cache_mib": 8192, "conversation_cache_slots": 4}
233        svc = Service(engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
234        httpd = serve(svc, port=0)
235        base = f"http://127.0.0.1:{httpd.server_address[1]}"
236        try:
237            with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
238                c = json.loads(r.read())["conversation_cache"]
239            self.assertEqual((c["enabled"], c["budget_mib"], c["slots"], c["parked"], c["requests"]),
240                             (True, 8192, 4, 0, 0))
241            req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"},
242                                         data=json.dumps({"messages": [{"role": "user", "content": "hi"}]}).encode())
243            with urllib.request.urlopen(req, timeout=10) as r:
244                r.read()
245            with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
246                c = json.loads(r.read())["conversation_cache"]
247            self.assertEqual(c["requests"], 1)
248            self.assertGreater(c["last_prompt"], 0)
249            engine.info = {}
250            with urllib.request.urlopen(base + "/metrics", timeout=10) as r:
251                self.assertFalse(json.loads(r.read())["conversation_cache"]["enabled"])   # off: the reuse lines only
252        finally:
253            httpd.shutdown()
254            httpd.server_close()
255
256    def test_the_card_is_on_the_page(self):
257        web = Path(__file__).parent / "web"
258        html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8")
259        for el in ("cc-card", "cc-slots-text", "cc-mem-text", "cc-facts", "cc-note"):
260            self.assertIn(f'id="{el}"', html)
261            self.assertIn(f'"{el}"', js)
262
263
264if __name__ == "__main__":
265    unittest.main()