Files
strata/serve/test_monitor.py
T
Niko1221 272c16c767 #332 follow-up: the API request monitor is opt-in ("api_monitor": true / --api-monitor), off by default
It keeps the last 100 requests' prompts, answers and reasoning in memory. Off (the default): begin_request() keeps
nothing, the streams are not wrapped, GET /api/requests and /api-monitor answer 404. Every record write goes through
_note(), which does nothing without a record (the PR's direct self.record[...] writes in the stream error paths
would have failed with the monitor off). A client disconnect in do_POST is marked and then re-raised, as the server
handled it before. The start line says when it is on (and that anyone can read the history without an API key).
test_monitor: turns it on; MonitorOff checks the default; Anthropic requests ask for thinking with "thinking" (#278).
2026-10-01 08:32:01 +02:00

199 lines
9.6 KiB
Python

"""Request inspection through HTTP; no native model or GPU is required."""
import json
import threading
import time
import unittest
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, EngineDied, MockEngine, Service, serve
class ReloadableEngine(MockEngine):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.running, self.unloaded = True, False
def alive(self):
return self.running
def unload(self):
self.running, self.unloaded = False, True
def restart(self):
self.running, self.unloaded = True, False
class MonitorOff(unittest.TestCase):
"""#332 is opt-in: by default no prompt or answer is kept, and the monitor's endpoints do not exist."""
def test_off_by_default(self):
tok = ByteTokenizer()
svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok,
ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
httpd = serve(svc, port=0)
base = f"http://127.0.0.1:{httpd.server_address[1]}"
try:
req = urllib.request.Request(base + "/v1/chat/completions", headers={"Content-Type": "application/json"},
data=json.dumps({"messages": [{"role": "user", "content": "secret"}]}).encode())
with urllib.request.urlopen(req, timeout=10) as r:
self.assertEqual(r.status, 200)
self.assertEqual(len(svc.api_requests), 0)
for path in ("/api/requests", "/api-monitor"):
with self.assertRaises(urllib.error.HTTPError) as e:
urllib.request.urlopen(base + path, timeout=10)
self.assertEqual(e.exception.code, 404, path)
e.exception.close()
finally:
httpd.shutdown()
httpd.server_close()
class Monitor(unittest.TestCase):
def setUp(self):
self.tok = ByteTokenizer()
self.engine = ReloadableEngine(self.tok, "Thought.</think>\nHello <script>alert(1)</script>.", max_context=16384)
self.svc = Service(self.engine, self.tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
self.svc.api_monitor = True # opt-in ("api_monitor": true / --api-monitor)
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 request(self, path, body=None, headers=None):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode() if body is not None else None,
headers={"Content-Type": "application/json", **(headers or {})})
try:
response = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read().decode()
return response.status, json.loads(raw) if "application/json" in response.headers.get("Content-Type", "") else raw
def chat(self, api="openai", **kwargs):
# Anthropic thinks only when asked (#278): "thinking" there, reasoning_effort for OpenAI
think = {"thinking": {"type": "enabled", "budget_tokens": 1024}} if api == "anthropic" else {"reasoning_effort": "low"}
return self.request("/v1/messages" if api == "anthropic" else "/v1/chat/completions",
{"messages": [{"role": "user", "content": "Say hello."}],
"max_tokens": 256, **think, **kwargs})
def latest(self):
summary = self.request("/api/requests")[1]["requests"][0]
return self.request("/api/requests?id=" + summary["id"])[1]
def test_output_and_reasoning_for_both_dialects_and_stream_modes(self):
for api in ("openai", "anthropic"):
for stream in (False, True):
with self.subTest(api=api, stream=stream):
code, reply = self.chat(api, stream=stream)
self.assertEqual(code, 200)
record = self.latest()
self.assertEqual(record["state"], "completed")
self.assertEqual(record["http_status"], 200)
self.assertIn("Say hello.", record["input"])
self.assertIn("<script>alert(1)</script>", record["output"])
self.assertIn("Thought.", record["reasoning"])
self.assertGreater(record["usage"].get("completion_tokens", record["usage"].get("output_tokens", 0)), 0)
self.assertGreaterEqual(record["wallclock_s"], record["first_token_s"])
self.assertNotIn("_clock", record)
if not stream:
self.assertEqual(json.loads(record["response"]), reply)
else:
self.assertNotIn("response", record)
def test_error_and_engine_death_are_not_successes(self):
self.assertEqual(self.chat(max_tokens=20000)[0], 400)
self.assertEqual(self.latest()["state"], "error")
for api in ("openai", "anthropic"):
for stream in (False, True):
with self.subTest(api=api, stream=stream), mock.patch.object(self.engine, "generate", side_effect=EngineDied("stopped")):
self.chat(api, stream=stream)
record = self.latest()
self.assertEqual(record["state"], "error")
self.assertIn("stopped", record["error"]["message"])
self.assertEqual(record["output"], "")
self.assertNotIn("timings", record)
def test_history_is_authorized_and_does_not_capture_headers(self):
self.svc.api_key = "secret"
auth = {"Authorization": "Bearer secret"}
self.assertEqual(self.request("/api/requests")[0], 401)
self.assertEqual(self.request("/api/requests?id=missing")[0], 401)
self.assertEqual(len(self.svc.api_requests), 0)
self.assertEqual(self.request("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, auth)[0], 200)
summary = self.request("/api/requests", headers=auth)[1]["requests"][0]
self.assertNotIn("input", summary)
self.assertNotIn("output", summary)
self.assertEqual(self.request("/api/requests?id=" + summary["id"])[0], 401)
detail = self.request("/api/requests?id=" + summary["id"], headers=auth)[1]
self.assertNotIn("secret", json.dumps(detail))
def test_capture_is_bounded_and_eviction_returns_404(self):
huge = "x" * 262200
first = self.svc.begin_request("/v1/chat/completions", {"messages": [{"content": huge}]})
self.assertEqual(len(first["input"]), 262144)
self.assertTrue(first["input_truncated"])
for _ in range(100):
self.svc.begin_request("/v1/chat/completions", {"messages": []})
self.assertEqual(len(self.request("/api/requests")[1]["requests"]), 100)
self.assertEqual(self.request("/api/requests?id=" + first["id"])[0], 404)
# Exercise output capture without making a mock engine emit 262K tokens.
handler = object.__new__(self.httpd.RequestHandlerClass)
handler.record = self.svc.api_requests[-1]
chunk = {"choices": [{"delta": {"content": huge, "reasoning_content": huge}}]}
list(handler._capture((item for item in [chunk]), "openai"))
for field in ("output", "reasoning"):
self.assertEqual(len(handler.record[field]), 262144)
self.assertTrue(handler.record[field + "_truncated"])
def test_queue_wait_and_loading_are_attributed_separately(self):
self.engine.unload()
entered, release = threading.Event(), threading.Event()
original = self.engine.restart
def restart():
entered.set()
self.assertTrue(release.wait(5))
original()
with mock.patch.object(self.engine, "restart", side_effect=restart), ThreadPoolExecutor(max_workers=2) as pool:
first = pool.submit(self.chat)
self.assertTrue(entered.wait(5))
second = pool.submit(self.chat)
deadline = time.monotonic() + 5
while len(self.svc.api_requests) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
self.assertEqual(len(self.svc.api_requests), 2)
history = self.request("/api/requests")[1]
self.assertEqual({r["state"] for r in history["requests"]}, {"queued", "loading"})
self.assertFalse(history["loaded"])
self.assertTrue(history["auto_load"])
time.sleep(0.03)
release.set()
self.assertEqual(first.result()[0], 200)
self.assertEqual(second.result()[0], 200)
records = list(self.svc.api_requests)
self.assertGreater(records[0]["load_s"], 0.02)
self.assertGreater(records[1]["queue_s"], 0.02)
self.assertLess(records[1]["load_s"], records[0]["load_s"])
self.assertTrue(all(r["state"] == "completed" for r in records))
def test_page_and_relative_assets_are_served(self):
code, html = self.request("/api-monitor")
self.assertEqual(code, 200)
self.assertIn('src="/web/monitor.js"', html)
code, script = self.request("/web/monitor.js")
self.assertEqual(code, 200)
self.assertIn("textContent", script)
self.assertNotIn("innerHTML", script)
self.assertEqual(self.request("/web/../server.py")[0], 404)
if __name__ == "__main__":
unittest.main()