okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1"""Tiny stdlib loopback fixtures; these never contact an inference server.""" 2import gzip 3import hashlib 4import http .server 5import json 6import os 7from pathlib import Path 8import shutil 9import subprocess 10import sys 11import tempfile 12import threading 13import time 14import unittest 15 16HELPER = Path (__file__ ).with_name ("replay.py" ) 17 18 19class ReplayTests (unittest .TestCase ): 20def setUp (self ): 21self .temp = tempfile .TemporaryDirectory (prefix = "strata-replay-fixture-" ) 22self .root = Path (self .temp .name ) 23shutil .copyfile (HELPER ,self .root / "replay.py" ) 24 (self .root / "requests" ).mkdir () 25self .received = [] 26self .headers = [] 27self .behavior = "success" 28owner = self 29 30class Handler (http .server .BaseHTTPRequestHandler ): 31def log_message (self ,* args ): 32pass 33 34def do_GET (self ): 35body = json .dumps ({"loaded" :True ,"model" :"fixture-only" }).encode () 36self .send_response (200 ) 37self .send_header ("Content-Type" ,"application/json" ) 38self .send_header ("Content-Length" ,str (len (body ))) 39self .end_headers () 40self .wfile .write (body ) 41 42def do_POST (self ): 43body = self .rfile .read (int (self .headers ["Content-Length" ])) 44behavior = owner .behavior 45owner .received .append ((self .path ,body )) 46owner .headers .append (dict (self .headers )) 47if self .path .startswith ("/slots/0?" ): 48payload = b'{"n_saved":1000,"n_restored":1000}' 49self .send_response (200 ) 50self .send_header ("Content-Type" ,"application/json" ) 51self .send_header ("Content-Length" ,str (len (payload ))) 52self .end_headers () 53self .wfile .write (payload ) 54return 55request = json .loads (body ) 56if behavior == "timeout" : 57time .sleep (1.2 ) 58if behavior == "http-error" : 59payload = b'{"error":{"message":"HTTP fixture error"}}' 60self .send_response (503 ) 61self .send_header ("Content-Length" ,str (len (payload ))) 62self .end_headers () 63self .wfile .write (payload ) 64return 65self .send_response (200 ) 66self .send_header ("Content-Type" ,"text/event-stream" ) 67self .end_headers () 68if behavior == "malformed" : 69chunks = [b"data: not-json\n\n" ] 70elif behavior == "error" : 71chunks = [b'data: {"error":{"message":"fixture API error"}}\n\n' ] 72else : 73prompt = 1001 if behavior == "wrong-prompt" else 1000 74reuse = 900 if request ["messages" ][0 ]["content" ]== "disk-continuation" else 0 75if request ["messages" ][0 ]["content" ].startswith ("decode" ): 76reuse = 999 77if behavior == "reused" : 78reuse = 1 79generated = request ["max_tokens" ] 80if behavior == "short" : 81generated -= 1 82finish = "stop" if request ["messages" ][0 ]["content" ].startswith ("disk" )else "length" 83values = [ 84 {"choices" : [{"delta" : {"role" :"assistant" }}]}, 85 {"choices" : [{"delta" : {"reasoning_content" :"actual reasoning" }}]}, 86 {"choices" : [{"delta" : {"content" :"2 + 2 = 5" }}]}, 87 {"choices" : [{"delta" : {"tool_calls" : [{"index" :0 ,"id" :"call1" ,"type" :"function" ,"function" : {"name" :"calculate" ,"arguments" :"{\"x\":" }}]}}]}, 88 {"choices" : [{"delta" : {"tool_calls" : [{"index" :0 ,"function" : {"arguments" :"5}" }}]},"finish_reason" :finish }], 89"usage" : {"prompt_tokens" :prompt ,"completion_tokens" :generated }, 90"timings" : {"cache_n" :reuse ,"prompt_n" :prompt - reuse ,"prompt_ms" :200 ,"predicted_n" :generated ,"predicted_ms" :400 }}, 91 ] 92chunks = [("data: " + json .dumps (value )+ "\r\n\r\n" ).encode ()for value in values ] 93if behavior != "missing-done" : 94chunks .append (b"data: [DONE]\n\n" ) 95try : 96for chunk in chunks : 97self .wfile .write (chunk ) 98self .wfile .flush () 99except (BrokenPipeError ,ConnectionResetError ): 100pass 101 102self .server = http .server .ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 103self .thread = threading .Thread (target = self .server .serve_forever ,daemon = True ) 104self .thread .start () 105self .url = "http://127.0.0.1:" + str (self .server .server_port ) 106 107def tearDown (self ): 108self .server .shutdown () 109self .server .server_close () 110self .thread .join () 111self .temp .cleanup () 112 113def entry (self ,ident ,role = "measured" ,suite = "confirmation" ,round = 0 ): 114request = {"model" :"unchanged-fixture-name" ,"stream" :True , 115"max_tokens" :64 if role == "warmup" else 512 , 116"messages" : [{"role" :"user" ,"content" :ident }]} 117if suite == "disk" : 118request ["max_tokens" ]= 256 119body = json .dumps (request ,separators = ("," ,":" )).encode () 120path = "requests/" + ident + ".json.gz" 121 (self .root / path ).write_bytes (gzip .compress (body ,mtime = 0 )) 122return {"id" :ident ,"suite" :suite ,"role" :role ,"depth" :1000 ,"round" :round , 123"path" :path ,"request_sha256" :hashlib .sha256 (body ).hexdigest (), 124"expected_prompt_tokens" :1000 },body 125 126def run_helper (self ,entries ,* args ): 127 (self .root / "requests/index.json" ).write_text (json .dumps ({"requests" :entries })) 128out = self .root / ("out-" + str (len (list (self .root .glob ("out-*" ))))) 129env = dict (os .environ ,STRATA_BENCHMARK_API_KEY = "fixture-secret-do-not-record" ) 130proc = subprocess .run ([sys .executable ,str (self .root / "replay.py" ),"--url" ,self .url , 131"--suite" ,"confirmation" ,"--out" ,str (out ),* args ], 132capture_output = True ,text = True ,env = env ,timeout = 15 ) 133self .assertTrue ((out / "run.json" ).exists (),"Replay must record run.json: " + proc .stderr ) 134return proc ,out ,json .loads ((out / "run.json" ).read_text ()) 135 136def test_frozen_order_and_actual_output (self ): 137measured ,measured_body = self .entry ("measured" ) 138warm ,warm_body = self .entry ("warm" ,role = "warmup" ) 139ignored ,_ = self .entry ("other-round" ,round = 1 ) 140proc ,out ,run = self .run_helper ([measured ,ignored ,warm ],"--round" ,"0" ) 141self .assertEqual (proc .returncode ,0 ,proc .stderr + proc .stdout ) 142self .assertEqual ([body for _ ,body in self .received ], [warm_body ,measured_body ]) 143row = run ["results" ][1 ] 144self .assertEqual (row ["content" ],"2 + 2 = 5" ) 145self .assertEqual (row ["reasoning_content" ],"actual reasoning" ) 146self .assertEqual (row ["tool_calls" ][0 ]["function" ]["arguments" ],'{"x":5}' ) 147self .assertEqual (row ["engine_prefill_tok_s" ],5000 ) 148self .assertEqual (row ["engine_decode_tok_s" ],1280 ) 149self .assertIsNotNone (row ["client_ttft_s" ]) 150self .assertEqual (len (row ["harness_sha256" ]),64 ) 151self .assertTrue (row ["eligible" ]) 152self .assertTrue (any (b"[DONE]" in path .read_bytes ()for path in out .rglob ("*.sse" ))) 153self .assertEqual (self .headers [0 ]["Authorization" ],"Bearer fixture-secret-do-not-record" ) 154self .assertNotIn ("fixture-secret-do-not-record" , (out / "run.json" ).read_text ()) 155 156def test_stream_failures_recorded (self ): 157for behavior in ("missing-done" ,"error" ,"malformed" ,"timeout" ,"http-error" ): 158with self .subTest (behavior = behavior ): 159self .behavior = behavior 160entry ,_ = self .entry (behavior ) 161proc ,_ ,run = self .run_helper ([entry ],"--timeout" ,"1" ) 162self .assertEqual (proc .returncode ,1 ,proc .stderr + proc .stdout ) 163self .assertFalse (run ["results" ][0 ]["eligible" ]) 164self .assertEqual (run ["results" ][0 ]["status" ],"failed" ) 165self .assertTrue (run ["results" ][0 ]["error" ]) 166if behavior == "timeout" : 167self .assertIn ("timeout" ,run ["results" ][0 ]["error" ].lower ()) 168 169def test_ineligible_counts_are_failures (self ): 170for behavior in ("wrong-prompt" ,"reused" ,"short" ): 171with self .subTest (behavior = behavior ): 172self .behavior = behavior 173entry ,_ = self .entry (behavior ) 174proc ,_ ,run = self .run_helper ([entry ]) 175self .assertEqual (proc .returncode ,1 ) 176self .assertFalse (run ["results" ][0 ]["eligible" ]) 177self .assertEqual (run ["results" ][0 ]["content" ],"2 + 2 = 5" ) 178 179def test_sha_mismatch_never_sends (self ): 180entry ,_ = self .entry ("bad-sha" ) 181entry ["request_sha256" ]= "0" * 64 182proc ,_ ,run = self .run_helper ([entry ]) 183self .assertEqual (proc .returncode ,1 ) 184self .assertEqual (self .received , []) 185self .assertIn ("SHA" ,run ["error" ]) 186 187def test_disk_phase_and_native_slot_actions (self ): 188initial ,_ = self .entry ("disk-initial" ,role = "initial" ,suite = "disk" ) 189continuation ,body = self .entry ("disk-continuation" ,role = "continuation" ,suite = "disk" ) 190continuation ["previous_prefix_tokens" ]= 900 191proc ,_ ,run = self .run_helper ([initial ,continuation ],"--suite" ,"disk" ,"--disk-phase" ,"continuation" ,"--depth" ,"1000" ) 192self .assertEqual (proc .returncode ,0 ,proc .stderr + proc .stdout ) 193self .assertEqual (self .received [0 ][1 ],body ) 194self .assertEqual (run ["results" ][0 ]["previous_prefix_reuse_fraction" ],1 ) 195for action in ("save" ,"restore" ): 196proc ,_ ,run = self .run_helper ([],"--slot-action" ,action ,"--slot-filename" ,"orchestrator.bin" ) 197self .assertEqual (proc .returncode ,0 ,proc .stderr + proc .stdout ) 198self .assertEqual (self .received [- 1 ][0 ],"/slots/0?action=" + action ) 199self .assertEqual (json .loads (self .received [- 1 ][1 ]), {"filename" :"orchestrator.bin" }) 200self .assertEqual (run ["slot_action" ]["response" ]["n_saved" ],1000 ) 201self .assertGreaterEqual (run ["slot_action" ]["client_total_s" ],0 ) 202 203def test_unsafe_slot_basename_never_sends (self ): 204proc ,_ ,run = self .run_helper ([],"--slot-action" ,"save" ,"--slot-filename" ,"../oops.bin" ) 205self .assertEqual (proc .returncode ,1 ) 206self .assertEqual (self .received , []) 207self .assertIn ("basename" ,run ["error" ]) 208 209def test_decode_preserves_sequence_and_cache_eligibility (self ): 210warm0 ,body0 = self .entry ("decode-warm0" ,role = "warmup" ,suite = "decode" ) 211measured0 ,body1 = self .entry ("decode-measured0" ,suite = "decode" ) 212warm1 ,_ = self .entry ("decode-warm1" ,role = "warmup" ,suite = "decode" ,round = 1 ) 213measured1 ,_ = self .entry ("decode-measured1" ,suite = "decode" ,round = 1 ) 214proc ,_ ,run = self .run_helper ([warm0 ,measured0 ,warm1 ,measured1 ],"--suite" ,"decode" ,"--round" ,"0" ) 215self .assertEqual (proc .returncode ,0 ,proc .stderr + proc .stdout ) 216self .assertEqual ([body for _ ,body in self .received ], [body0 ,body1 ]) 217self .assertTrue (run ["results" ][1 ]["eligible" ]) 218self .behavior = "reused" 219proc ,_ ,run = self .run_helper ([measured0 ],"--suite" ,"decode" ) 220self .assertEqual (proc .returncode ,1 ) 221self .assertIn ("99.9%" ,run ["results" ][0 ]["ineligible_reasons" ][0 ]) 222 223def test_disk_wrong_needles_remain_actual (self ): 224entry ,_ = self .entry ("disk-initial" ,role = "initial" ,suite = "disk" ) 225entry ["expected_needles" ]= {"AUDIT_ROUTE_1" :"fixture expected value" } 226proc ,_ ,run = self .run_helper ([entry ],"--suite" ,"disk" ) 227self .assertEqual (proc .returncode ,1 ) 228self .assertFalse (run ["results" ][0 ]["needle_grade" ]["passed" ]) 229self .assertEqual (run ["results" ][0 ]["content" ],"2 + 2 = 5" ) 230 231 232if __name__ == "__main__" : 233unittest .main (verbosity = 2 )