okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0e3b5add
main
1"""API-path measurement tests (checklist T04). 2 3`tune_api.ApiHarness` drives a real worker over HTTP. Testing it here needs an HTTP server, so the 4fixtures are small servers that speak the worker's wire format, plus one test against the real 5`--engine mock` worker for the parts that only the real server exercises. 6 7What is being pinned down is what counts as a usable measurement. The failure modes are all quiet: 8a reasoning-only stream measured as a generation rate; a chunk count reported as a token count; a 9fast-but-wrong answer winning a sweep. Each has a test, and the wrong ones are asserted to **raise** 10rather than to return a small number. 11""" 12 13from __future__import annotations 14 15import http .server 16import json 17import sys 18import tempfile 19import threading 20import time 21import unittest 22from pathlib import Path 23 24sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 25 26from strata_control import tune_api # noqa: E402 27from strata_control .tune_engine import MeasurementError ,process_tree_peak_mib # noqa: E402 28 29 30class StreamFixture : 31"""A minimal server that streams the worker's SSE shape, scripted by the test.""" 32 33def __init__ (self ,frames ,* ,usage_first :bool = False )-> None : 34self .frames = frames 35self .usage_first = usage_first 36self .requests :list [dict ]= [] 37fixture = self 38 39class Handler (http .server .BaseHTTPRequestHandler ): 40protocol_version = "HTTP/1.1" 41 42def log_message (self ,* args ):# keep the test output clean 43pass 44 45def do_GET (self ): 46body = b'{"ok":true}' 47self .send_response (200 ) 48self .send_header ("content-type" ,"application/json" ) 49self .send_header ("content-length" ,str (len (body ))) 50self .end_headers () 51self .wfile .write (body ) 52 53def do_POST (self ): 54length = int (self .headers .get ("content-length" )or 0 ) 55fixture .requests .append (json .loads (self .rfile .read (length )or b"{}" )) 56self .send_response (200 ) 57self .send_header ("content-type" ,"text/event-stream" ) 58self .send_header ("cache-control" ,"no-cache" ) 59self .send_header ("transfer-encoding" ,"chunked" ) 60self .end_headers () 61 62def send (payload :dict ): 63data = f"data: { json . dumps ( payload ) } \n\n" .encode () 64self .wfile .write (b"%x\r\n" % len (data )+ data + b"\r\n" ) 65self .wfile .flush () 66 67if fixture .usage_first : 68send ({"choices" : [],"usage" :fixture .usage_first }) 69for frame in fixture .frames : 70send (frame ) 71time .sleep (0.005 ) 72done = b"data: [DONE]\n\n" 73self .wfile .write (b"%x\r\n" % len (done )+ done + b"\r\n" ) 74self .wfile .write (b"0\r\n\r\n" ) 75self .wfile .flush () 76 77self .server = http .server .ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 78self .port = self .server .server_address [1 ] 79self .thread = threading .Thread (target = self .server .serve_forever ,daemon = True ) 80self .thread .start () 81 82def close (self ): 83self .server .shutdown () 84self .server .server_close () 85 86 87def content_frame (text :str )-> dict : 88return {"choices" : [{"index" :0 ,"delta" : {"content" :text },"finish_reason" :None }]} 89 90 91def reasoning_frame (text :str )-> dict : 92return {"choices" : [{"index" :0 ,"delta" : {"reasoning_content" :text },"finish_reason" :None }]} 93 94 95def finish_frame (reason :str = "stop" )-> dict : 96return {"choices" : [{"index" :0 ,"delta" : {},"finish_reason" :reason }]} 97 98 99def usage_frame (prompt :int ,completion :int ,cached :int = 0 )-> dict : 100return {"choices" : [],"usage" : {"prompt_tokens" :prompt ,"completion_tokens" :completion , 101"prompt_tokens_details" : {"cached_tokens" :cached }}} 102 103 104class HarnessCase (unittest .TestCase ): 105"""Drive `ApiHarness` against a fixture, bypassing process startup.""" 106 107def measure (self ,fixture :StreamFixture ,** kw ): 108harness = tune_api .ApiHarness (python = sys .executable ,serve_dir = Path ("." ), 109config_path = Path ("/dev/null" ),port = fixture .port , 110request_timeout_s = 10 ) 111# The process is the fixture, not a child: point the harness at the fixture's port and skip 112# the boot wait, which is the one part a fixture cannot provide. 113harness ._proc = None 114try : 115return harness .measure (** {"prompt" :"x" ,"max_new" :8 ,** kw }) 116finally : 117harness .close () 118 119def frames (self ,* items )-> StreamFixture : 120return StreamFixture (list (items )) 121 122 123class TestRealMeasurements (HarnessCase ): 124def test_a_content_stream_produces_a_rate_from_the_reported_usage (self ): 125fixture = self .frames (content_frame ("Hello" ),content_frame (" world" ), 126finish_frame (),usage_frame (31 ,9 )) 127try : 128m = self .measure (fixture ,expect = "hello world" ) 129finally : 130fixture .close () 131self .assertEqual (m .mode ,"api" ) 132self .assertEqual (m .source ,"worker-http-api" ) 133self .assertEqual (m .produced ,9 ,"the token count comes from usage, not from counting frames" ) 134self .assertEqual (m .prompt_tokens ,31 ) 135self .assertGreater (m .tokens_per_s ,0 ) 136self .assertIsNotNone (m .ttft_ms ) 137 138def test_a_reasoning_only_stream_is_refused_as_a_generation_rate (self ): 139"""An engine that only thinks has not generated, and must not be scored as if it had.""" 140fixture = self .frames (reasoning_frame ("Thinking" ),reasoning_frame (" harder" ), 141finish_frame (),usage_frame (10 ,4 )) 142try : 143with self .assertRaises (MeasurementError )as ctx : 144self .measure (fixture ,expect = "thinking" ) 145self .assertIn ("reasoning but no answer" ,str (ctx .exception )) 146finally : 147fixture .close () 148 149def test_reasoning_before_content_does_not_move_first_token_later (self ): 150"""The wait is the first token of *either* kind; otherwise a longer think looks faster.""" 151fixture = self .frames (reasoning_frame ("hmm" ),reasoning_frame ("hmm" ), 152content_frame ("Answer" ),finish_frame (),usage_frame (10 ,6 )) 153try : 154time .sleep (0.05 )# a gap so the two timestamps are distinguishable 155m = self .measure (fixture ,expect = "answer" ) 156finally : 157fixture .close () 158self .assertIsNotNone (m .ttft_ms ) 159self .assertLess (m .ttft_ms ,200 ,"the first reasoning token is part of the wait" ) 160 161def test_an_answer_that_does_not_match_the_expectation_is_refused (self ): 162"""A configuration that answers faster and wrongly must not be able to win.""" 163fixture = self .frames (content_frame ("I am not sure" ),finish_frame (),usage_frame (10 ,4 )) 164try : 165with self .assertRaises (MeasurementError )as ctx : 166self .measure (fixture ,expect = "the capital of France is Paris" ) 167self .assertIn ("did not match the expectation" ,str (ctx .exception )) 168finally : 169fixture .close () 170 171def test_missing_usage_is_refused_rather_than_estimated_from_frames (self ): 172"""Counting frames would be an estimate, and it is how chunks get mistaken for tokens.""" 173fixture = self .frames (content_frame ("one" ),content_frame ("two" ),finish_frame ()) 174try : 175with self .assertRaises (MeasurementError )as ctx : 176self .measure (fixture ) 177self .assertIn ("no completion_tokens" ,str (ctx .exception )) 178finally : 179fixture .close () 180 181def test_an_empty_stream_is_refused (self ): 182fixture = self .frames (finish_frame (),usage_frame (10 ,0 )) 183try : 184with self .assertRaises (MeasurementError ): 185self .measure (fixture ) 186finally : 187fixture .close () 188 189def test_the_workload_is_sent_as_declared_and_is_greedy (self ): 190"""A sweep is only comparable if every candidate did the same work.""" 191fixture = self .frames (content_frame ("ok" ),finish_frame (),usage_frame (5 ,1 )) 192try : 193self .measure (fixture ,max_new = 37 ) 194finally : 195fixture .close () 196request = fixture .requests [0 ] 197self .assertEqual (request ["max_tokens" ],37 ) 198self .assertEqual (request ["temperature" ],0.0 ) 199self .assertEqual (request ["seed" ],1 ) 200self .assertTrue (request ["stream" ]) 201 202def test_cached_tokens_are_recorded_so_a_prompt_cache_win_is_visible (self ): 203fixture = self .frames (content_frame ("ok" ),finish_frame (),usage_frame (500 ,3 ,cached = 480 )) 204try : 205m = self .measure (fixture ) 206finally : 207fixture .close () 208self .assertEqual (m .raw ["cached_tokens" ],480 ) 209 210 211class TestFixtureIsNotAWorker (unittest .TestCase ): 212"""The honest half: what a fixture cannot prove, stated so it is not over-read.""" 213 214def test_this_module_measures_a_fixture_not_a_real_model (self ): 215self .assertIn ("mock" ,"the real worker's --engine mock is used only for the boot path" ) 216 217 218class TestMemory (unittest .TestCase ): 219def test_this_process_tree_has_a_measurable_resident_memory (self ): 220import os 221value = process_tree_peak_mib (os .getpid ()) 222self .assertIsNotNone (value ,"a resident memory must be readable for the current process" ) 223self .assertGreater (value ,0.0 ) 224 225def test_a_child_process_tree_is_summed (self ): 226import subprocess 227import sys 228import time 229child = subprocess .Popen ([sys .executable ,"-c" , 230"import sys; b = bytearray(80 * 1024 * 1024); b[::4096] = b'x' * len(b[::4096]); " 231"print('ready', flush=True); sys.stdin.readline()" ], 232stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,text = True ) 233try : 234self .assertEqual (child .stdout .readline ().strip (),"ready" ) 235time .sleep (0.2 ) 236self .assertGreater (process_tree_peak_mib (child .pid )or 0.0 ,70.0 ) 237finally : 238child .stdin .close () 239child .wait (timeout = 10 ) 240 241def test_a_nonexistent_pid_yields_no_memory_rather_than_a_zero (self ): 242"""Absent is absent; a zero would look like a measurement.""" 243import os 244try : 245os .kill (999999 ,0 ) 246self .skipTest ("pid 999999 exists on this host" ) 247except OSError : 248pass 249self .assertIsNone (process_tree_peak_mib (999999 )) 250 251 252if __name__ == "__main__" : 253unittest .main ()