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