okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ffb3d9b31
main
1"""The standard benchmark (docs/BENCHMARK_PROTOCOL.md) against a scripted mock server: no engine, no model weights.""" 2 3from __future__import annotations 4 5import contextlib 6import copy 7import http .client 8import io 9import json 10import os 11import re 12import shutil 13import tempfile 14import threading 15import time 16import unittest 17from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 18from pathlib import Path 19from unittest import mock 20 21from strata_cli import bench ,bench_facts ,bench_standard as bs 22from strata_cli .cli import main 23from strata_control .profiles import ProfileError 24 25COMMIT = "a" * 40 26TEMPLATE = "{{ messages }} mock chat template" 27 28 29def corpus_specs ()-> dict [str ,dict ]: 30return {spec ["id" ]:spec for spec in bs .load_corpus ().specs } 31 32 33class MockStrata : 34"""A server that speaks enough of Strata's API: /health, /props, /v1/status, /metrics and streamed chat completions.""" 35 36def __init__ (self ,model_file :Path ): 37self .specs = corpus_specs () 38self .model_file = model_file 39self .script :dict [str ,dict ]= {} 40self .bodies :list [dict ]= [] 41self .order :list [str ]= [] 42self .arrivals :list [float ]= [] 43self .active = 0 44self .max_active = 0 45self .dead = False 46self .lock = threading .Lock () 47self .requests_before = 0 48self .gpu_name = "Mock GPU 12 GB" 49owner = self 50 51class Handler (BaseHTTPRequestHandler ): 52def log_message (self ,* args ): 53pass 54 55def _json (self ,code ,value ): 56data = json .dumps (value ).encode () 57self .send_response (code ) 58self .send_header ("Content-Type" ,"application/json" ) 59self .send_header ("Content-Length" ,str (len (data ))) 60self .end_headers () 61self .wfile .write (data ) 62 63def do_GET (self ): 64if owner .dead and self .path == "/health" : 65return self ._json (503 , {"error" :"down" }) 66if self .path == "/health" : 67return self ._json (200 , {"service" :"strata" ,"loaded" :True }) 68if self .path == "/props" : 69return self ._json (200 , {"model_alias" :"qwen3.8-flash-next" ,"chat_template" :TEMPLATE , 70"default_generation_settings" : {"n_ctx" :131072 ,"params" : {"temperature" :0.7 }}, 71"total_slots" :1 ,"build_info" :"Strata 0.1.45.3" , 72"model_path" :str (owner .model_file ),"is_sleeping" :False }) 73if self .path == "/v1/status" : 74return self ._json (200 , {"service" :"strata" ,"model" :"qwen3.8-flash-next" ,"engine" :"0.1.45.3" , 75"machine" : {"gpu" : {"name" :owner .gpu_name }}, 76"activity" : {"requests" :owner .requests_before }}) 77if self .path == "/metrics" : 78return self ._json (200 , {"engine" : {"version" :"0.1.45.3" },"hardware_static" : {"gpu_name" :owner .gpu_name }}) 79self ._json (404 , {}) 80 81def do_POST (self ): 82body = json .loads (self .rfile .read (int (self .headers .get ("Content-Length" ,"0" )))) 83rid = re .match (r"\[case ([^\]]+)\]" ,body ["messages" ][0 ]["content" ]).group (1 ) 84with owner .lock : 85owner .bodies .append (body ) 86owner .order .append (rid ) 87owner .arrivals .append (time .monotonic ()) 88owner .active += 1 89owner .max_active = max (owner .max_active ,owner .active ) 90try : 91self .respond (rid ,body ) 92finally : 93with owner .lock : 94owner .active -= 1 95 96def respond (self ,rid ,body ): 97spec = owner .specs [rid ] 98plan = owner .script .get (rid , {}) 99if plan .get ("hold_for_arrivals" ): 100deadline = time .monotonic ()+ 3 101while time .monotonic ()< deadline and owner .active < plan ["hold_for_arrivals" ]: 102time .sleep (0.01 ) 103if plan .get ("die" ): 104owner .dead = True 105self .connection .close () 106return 107if plan .get ("http" ): 108return self ._json (plan ["http" ], {"error" : {"message" :"refused" }}) 109self .send_response (200 ) 110self .send_header ("Content-Type" ,"text/event-stream" ) 111self .end_headers () 112 113def send (event ): 114self .wfile .write (b"data: " + json .dumps (event ).encode ()+ b"\n\n" ) 115self .wfile .flush () 116chunk = lambda delta ,finish = None : {"choices" : [{"index" :0 ,"delta" :delta ,"finish_reason" :finish }]}# noqa: E731 117send (chunk ({"role" :"assistant" ,"content" :"" })) 118self .wfile .write (b": keep-alive\n\n" ) 119send (chunk ({"content" :"" })) 120if plan .get ("hang" ): 121time .sleep (plan ["hang" ]) 122return 123time .sleep (plan .get ("first_delay" ,0 )) 124send (chunk ({"reasoning_content" :"Thinking about it. " })) 125expected = spec .get ("expected" )or {} 126finish = plan .get ("finish" ,"stop" ) 127if "tool_calls" in plan : 128calls = plan ["tool_calls" ] 129finish = plan .get ("finish" ,"tool_calls" if calls else "stop" ) 130elif expected .get ("kind" )== "tool_call" : 131calls = [{"name" :expected ["name" ],"arguments" :json .dumps (expected ["arguments" ])}] 132finish = plan .get ("finish" ,"tool_calls" ) 133else : 134calls = [] 135if "content" in plan : 136text = plan ["content" ] 137elif expected .get ("kind" )== "text" : 138text = expected ["value" ] 139elif expected .get ("kind" )== "json" : 140text = json .dumps (expected ["value" ],separators = ("," ,":" )) 141elif expected .get ("kind" )== "tool_call" : 142text = "" 143else : 144text = "A hash table hashes the key." 145if text : 146send (chunk ({"content" :text })) 147for index ,call in enumerate (calls ): 148send (chunk ({"tool_calls" : [{"index" :index ,"id" :f"call_ { index } " ,"type" :"function" , 149"function" : {"name" :call ["name" ],"arguments" :"" }}]})) 150send (chunk ({"tool_calls" : [{"index" :index ,"function" : {"arguments" :call ["arguments" ]}}]})) 151final = chunk ({},finish ) 152prompt = spec ["input_tokens_frozen" ] 153output = plan .get ("completion_tokens" ,50 ) 154if plan .get ("usage" ,True ): 155final ["usage" ]= {"prompt_tokens" :prompt ,"completion_tokens" :output ,"total_tokens" :prompt + output , 156"prompt_tokens_details" : {"cached_tokens" :plan .get ("cached" ,0 )}} 157if plan .get ("timings" ,True ): 158cached = plan .get ("cached" ,0 ) 159read = prompt - cached 160final ["timings" ]= {"cache_n" :cached ,"prompt_n" :read ,"prompt_ms" :float (read ),"prompt_per_second" :1000.0 , 161"predicted_n" :plan .get ("predicted_n" ,output ),"predicted_ms" :500.0 , 162"predicted_per_second" :plan .get ("rate" ,100.0 )} 163send (final ) 164if not plan .get ("no_done" ): 165self .wfile .write (b"data: [DONE]\n\n" ) 166self .wfile .flush () 167 168self .httpd = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 169self .httpd .daemon_threads = True 170self .thread = threading .Thread (target = self .httpd .serve_forever ,daemon = True ) 171self .thread .start () 172self .url = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 173 174def close (self ): 175self .httpd .shutdown () 176self .httpd .server_close () 177 178 179class StandardBase (unittest .TestCase ): 180def setUp (self ): 181self .temp = tempfile .TemporaryDirectory () 182self .addCleanup (self .temp .cleanup ) 183self .root = Path (self .temp .name ) 184self .model = self .root / "Qwen3.8-Flash-Next-IQ2_XS-00001-of-00001.gguf" 185self .model .write_bytes (b"model bytes" ) 186self .server = MockStrata (self .model ) 187self .addCleanup (self .server .close ) 188for name ,value in (("nvidia_gpus" , ([],None ,None )), ("other_gpus" , ([],None )), ("cpu_name" ,lambda :"Mock CPU" ), 189 ("ram_bytes" ,lambda :64 * 2 ** 30 ), ("storage_of" ,lambda path : [{"kind" :"nvme" ,"model" :"Mock SSD" ,"bus" :"nvme" }]), 190 ("git_commit" ,lambda folder = None :COMMIT )): 191patcher = mock .patch .object (bench_facts ,name ,** ({"return_value" :value }if isinstance (value ,tuple )else {"side_effect" :value })) 192patcher .start () 193self .addCleanup (patcher .stop ) 194self .target = bs .Target (self .server .url ,None ) 195 196def run_standard (self ,name = "out" ,** kwargs ): 197kwargs .setdefault ("hash_model" ,True ) 198doc ,out = bs .run (self .target ,self .root / name ,** kwargs ) 199return doc ,out 200 201def record (self ,doc ,rid ): 202return next (r for r in doc ["requests" ]if r ["id" ]== rid ) 203 204def summary (self ,doc ,case ,metric ,phase = "performance" ): 205return next (s for s in doc ["summaries" ]if s ["phase" ]== phase and s ["case_id" ]== case and s ["metric" ]== metric ) 206 207 208class FixtureTests (unittest .TestCase ): 209def test_bundle_follows_the_protocol_tables (self ): 210corpus = bs .load_corpus () 211specs = {s ["id" ]:s for s in corpus .specs } 212self .assertEqual ([s ["id" ]for s in corpus .specs ][:10 ], 213 ["warmup" ,"performance-short-r1" ,"performance-prompt-4k-r1" ,"performance-prompt-16k-r1" , 214"performance-short-r2" ,"performance-prompt-4k-r2" ,"performance-prompt-16k-r2" , 215"performance-short-r3" ,"performance-prompt-4k-r3" ,"performance-prompt-16k-r3" ]) 216self .assertEqual ([s ["id" ]for s in corpus .specs if s ["phase" ]== "sanity" ], 217 [f"sanity- { n } " for n in ("I1" ,"I2" ,"I3" ,"I4" ,"R1" ,"R2" ,"R3" ,"R4" ,"T1" ,"T2" ,"T3" ,"T4" )]) 218self .assertEqual (len (corpus .specs ),34 ) 219self .assertEqual ((specs ["warmup" ]["seed" ],specs ["warmup" ]["max_output_tokens" ]), (1 ,128 )) 220for repetition in (1 ,2 ,3 ): 221for case in ("short" ,"prompt-4k" ,"prompt-16k" ): 222spec = specs [f"performance- { case } -r { repetition } " ] 223self .assertEqual ((spec ["seed" ],spec ["max_output_tokens" ],spec ["concurrency" ]), (repetition ,512 ,1 )) 224for spec in corpus .specs : 225if spec ["phase" ]== "sanity" : 226self .assertEqual ((spec ["seed" ],spec ["max_output_tokens" ]), (1 ,2048 )) 227if spec ["phase" ]== "concurrency" : 228self .assertEqual (spec ["seed" ],4 * (spec ["round" ]- 1 )+ int (spec ["id" ][- 1 ])) 229self .assertEqual ((spec ["max_output_tokens" ],spec ["concurrency" ]), (512 ,4 )) 230self .assertTrue (spec ["messages" ][0 ]["content" ].startswith (f"[case { spec [ 'id' ] } ]\n" )) 231self .assertEqual (len (spec ["messages" ]),1 ) 232self .assertEqual (specs ["performance-short-r1" ]["messages" ][0 ]["content" ].split ("\n" ,1 )[1 ], 233"Explain how a hash table finds a value, including collisions and one small example." ) 234 235def test_records_and_retrieval_placement (self ): 236specs = corpus_specs () 237body = specs ["performance-prompt-4k-r1" ]["messages" ][0 ]["content" ].split ("\n" ,1 )[1 ] 238lines = body .split ("\n" ) 239self .assertEqual (lines [0 ],"record000001: alpha beta gamma delta epsilon zeta eta theta." ) 240self .assertEqual (lines [- 1 ],"Summarize the structure of these records and explain how to look up a record by its ID." ) 241count = len (lines )- 1 242for rid ,key ,fraction in (("sanity-R1" ,"access_code = ORBIT-731" ,0.10 ), ("sanity-R2" ,"storage_label = CEDAR-284" ,0.50 )): 243rows = specs [rid ]["messages" ][0 ]["content" ].split ("\n" ,1 )[1 ].split ("\n" ) 244self .assertEqual (rows .index (key ),int (fraction * count ))# inserted before record index floor(f * count) 245self .assertEqual (sum ("record" not in r for r in rows ),2 )# the inserted line and the question 246long_count = len (specs ["performance-prompt-16k-r1" ]["messages" ][0 ]["content" ].split ("\n" ))- 2 247rows = specs ["sanity-R4" ]["messages" ][0 ]["content" ].split ("\n" ,1 )[1 ].split ("\n" ) 248self .assertEqual (rows .index ("north = N-124" ),int (0.10 * long_count )) 249self .assertEqual (rows .index ("south = S-875" )- 1 ,int (0.90 * long_count ))# one earlier insert shifts it by one line 250self .assertEqual (specs ["sanity-R4" ]["expected" ]["value" ], {"north" :"N-124" ,"south" :"S-875" }) 251for rid ,name ,props in (("sanity-T1" ,"lookup_record" , {"id" :"string" }), 252 ("sanity-T3" ,"convert_units" , {"value" :"number" ,"from_unit" :"string" ,"to_unit" :"string" }), 253 ("sanity-T4" ,"get_build_status" , {"project" :"string" ,"build" :"integer" })): 254function = specs [rid ]["tools" ][0 ]["function" ] 255self .assertEqual (function ["name" ],name ) 256self .assertEqual ({k :v ["type" ]for k ,v in function ["parameters" ]["properties" ].items ()},props ) 257self .assertEqual (function ["parameters" ]["required" ],list (props )) 258self .assertIs (function ["parameters" ]["additionalProperties" ],False ) 259self .assertEqual (function ["description" ],"Synthetic benchmark lookup; no external action is performed." ) 260self .assertEqual (specs [rid ]["tool_choice" ],"auto" ) 261self .assertIsNone (specs ["sanity-I1" ]["tools" ]) 262 263def test_prompt_lengths_are_within_two_percent_of_their_targets (self ): 264for spec in bs .load_corpus ().specs : 265if spec ["target_input_tokens" ]: 266self .assertLessEqual (abs (spec ["input_tokens_frozen" ]- spec ["target_input_tokens" ])/ spec ["target_input_tokens" ],0.02 ) 267 268def test_a_changed_or_converted_file_is_refused (self ): 269with tempfile .TemporaryDirectory ()as temp : 270copy_of = Path (temp )/ "bundle" 271shutil .copytree (bs .corpus_dir (),copy_of ) 272self .assertEqual (bs .load_corpus (copy_of ).sha256 ,bs .load_corpus ().sha256 ) 273target = copy_of / "requests" / "warmup.json" 274target .write_bytes (target .read_bytes ().replace (b"\n" ,b"\r\n" )) 275with self .assertRaisesRegex (ProfileError ,"fixture file changed: requests/warmup.json" ): 276bs .load_corpus (copy_of ) 277target .write_bytes (bs .load_corpus ().manifest [:0 ]+ (bs .corpus_dir ()/ "requests" / "warmup.json" ).read_bytes ()) 278 (copy_of / "requests" / "extra.json" ).write_text ("{}" ,encoding = "utf-8" ) 279with self .assertRaisesRegex (ProfileError ,"not in the manifest" ): 280bs .load_corpus (copy_of ) 281 282def test_gitattributes_keeps_fixture_bytes (self ): 283text = (Path (__file__ ).resolve ().parents [2 ]/ ".gitattributes" ).read_text (encoding = "utf-8" ) 284self .assertIn ("bench/prompts/** -text" ,text ) 285 286 287class DocsAndPackagingTests (unittest .TestCase ): 288ROOT = Path (__file__ ).resolve ().parents [2 ] 289 290def test_the_protocol_names_the_frozen_bundle (self ): 291text = (self .ROOT / "docs" / "BENCHMARK_PROTOCOL.md" ).read_text (encoding = "utf-8" ) 292self .assertIn (bs .load_corpus ().sha256 ,text ) 293self .assertIn (bs .PROTOCOL_ID ,text ) 294for heading in ("## Run it" ,"## Submit and review" ,"## Activation checklist" ,"### Where the numbers come from" ): 295self .assertIn (heading ,text ) 296self .assertNotIn ("do not implement this protocol" ,text ) 297 298def test_the_terminal_archive_carries_the_fixtures (self ): 299import sys 300sys .path .insert (0 ,str (self .ROOT / "packaging" )) 301import package_terminal 302self .assertIn ("bench/prompts/standard-v1" ,package_terminal .PAYLOAD ) 303 304def test_the_launchers_point_at_the_standard_benchmark (self ): 305for name in ("BENCH.bat" ,"bench.sh" ): 306self .assertIn ("strata.py bench run" , (self .ROOT / name ).read_text (encoding = "utf-8" )) 307 308 309class ScoringTests (unittest .TestCase ): 310def test_strict_json (self ): 311self .assertEqual (bs .strict_json (' {"a": 1}\n' ), {"a" :1 }) 312for bad in ('{"a":1,"a":2}' ,"```json\n{}\n```" ,'{"a":1} extra' ,"NaN" ,"Infinity" ,"" ,'{"a":1}{"b":2}' ): 313with self .assertRaises (ValueError ,msg = bad ): 314bs .strict_json (bad ) 315 316def test_json_equality_checks_types (self ): 317self .assertTrue (bs .same_json ({"a" : [1 ,2 ],"b" :True }, {"b" :True ,"a" : [1 ,2 ]})) 318self .assertFalse (bs .same_json ({"ok" :True }, {"ok" :1 })) 319self .assertFalse (bs .same_json (3 ,3.0 )) 320self .assertFalse (bs .same_json ([1 ,2 ], [2 ,1 ])) 321self .assertFalse (bs .same_json ({"a" :1 }, {"a" :1 ,"b" :2 })) 322 323def test_text_check_strips_only_ascii_whitespace (self ): 324spec = {"expected" : {"kind" :"text" ,"value" :"READY" },"category" :"instruction" } 325self .assertTrue (bs .evaluate (spec ,"completed" ," \nREADY\t" , [])["passed" ]) 326self .assertFalse (bs .evaluate (spec ,"completed" ,"READY." , [])["passed" ]) 327self .assertFalse (bs .evaluate (spec ,"completed" ,"ready" , [])["passed" ]) 328self .assertFalse (bs .evaluate (spec ,"truncated" ,"READY" , [])["passed" ]) 329 330def test_tool_call_needs_one_exact_structured_call (self ): 331spec = {"expected" : {"kind" :"tool_call" ,"name" :"get_weather" ,"arguments" : {"city" :"Zagreb" ,"unit" :"celsius" }}, 332"category" :"tool_call" } 333good = {"name" :"get_weather" ,"arguments" :'{"unit":"celsius","city":"Zagreb"}' } 334self .assertTrue (bs .evaluate (spec ,"completed" ,"" , [good ])["passed" ]) 335self .assertFalse (bs .evaluate (spec ,"completed" ,"get_weather(...)" , [])["passed" ]) 336self .assertFalse (bs .evaluate (spec ,"completed" ,"" , [good ,good ])["passed" ]) 337self .assertFalse (bs .evaluate (spec ,"completed" ,"" , [{** good ,"name" :"other" }])["passed" ]) 338self .assertFalse (bs .evaluate (spec ,"completed" ,"" , [{** good ,"arguments" :'{"city":"Zagreb"}' }])["passed" ]) 339self .assertFalse (bs .evaluate (spec ,"completed" ,"" , [{** good ,"arguments" :'{"city":"Zagreb","unit":"celsius","x":1}' }])["passed" ]) 340self .assertFalse (bs .evaluate (spec ,"completed" ,"" , [{** good ,"arguments" :'{"city":"a","city":"Zagreb","unit":"celsius"}' }])["passed" ]) 341 342 343class RunTests (StandardBase ): 344def test_a_full_run_follows_the_protocol (self ): 345doc ,out = self .run_standard () 346self .assertEqual (bs .validate (doc ), []) 347run = doc ["run" ] 348self .assertEqual ((doc ["format" ],doc ["schema_version" ],run ["status" ]), ("strata-standard-benchmark" ,1 ,"complete" )) 349self .assertEqual (doc ["protocol" ]["id" ],"strata-qwen38-thinking-v1-draft.1" ) 350self .assertEqual (doc ["protocol" ]["corpus_sha256" ],bs .load_corpus ().sha256 ) 351self .assertEqual (doc ["protocol" ]["git_commit" ],COMMIT ) 352self .assertEqual (len (doc ["requests" ]),22 ) 353self .assertEqual (self .server .order , [r ["id" ]for r in doc ["requests" ]]) 354self .assertEqual (doc ["request_counts" ]["warmup" ], {"planned" :1 ,"attempted" :1 ,"completed" :1 ,"truncated" :0 ,"failed" :0 ,"skipped" :0 }) 355self .assertEqual (doc ["request_counts" ]["performance" ]["completed" ],9 ) 356self .assertEqual (doc ["request_counts" ]["concurrency" ]["planned" ],0 ) 357self .assertEqual (doc ["quality" ], {"passed" :12 ,"total" :12 ,"categories" : { 358"instruction" : {"passed" :4 ,"total" :4 },"retrieval" : {"passed" :4 ,"total" :4 },"tool_call" : {"passed" :4 ,"total" :4 }}}) 359self .assertEqual (len (doc ["summaries" ]),15 ) 360self .assertEqual (doc ["concurrency_rounds" ], []) 361self .assertEqual (self .summary (doc ,"prompt-4k" ,"prompt_tps" )["median" ],1000.0 ) 362self .assertEqual (self .summary (doc ,"short" ,"decode_tps" )["median" ],100.0 ) 363for case in ("short" ,"prompt-4k" ,"prompt-16k" ): 364for metric in ("prompt_tps" ,"decode_tps" ,"ttft_s" ,"first_answer_s" ,"total_s" ): 365row = self .summary (doc ,case ,metric ) 366self .assertEqual (row ["n" ],3 ) 367self .assertLessEqual (row ["min" ],row ["median" ]) 368self .assertLessEqual (row ["median" ],row ["max" ]) 369# the warm-up and the sanity cases do not enter the speed summaries 370self .assertNotIn ("warmup" , {i for s in doc ["summaries" ]for i in s ["included_request_ids" ]}) 371self .assertFalse (any (i .startswith ("sanity" )for s in doc ["summaries" ]for i in s ["included_request_ids" ])) 372self .assertTrue (run ["required_duration_s" ]> 0 ) 373self .assertIsNone (run ["optional_duration_s" ]) 374self .assertIn ("optional_duration_s" ,"" .join (doc ["missing" ])) 375 376def test_every_request_carries_the_required_settings (self ): 377self .run_standard () 378self .assertEqual (len (self .server .bodies ),22 ) 379specs = corpus_specs () 380for body ,rid in zip (self .server .bodies ,self .server .order ): 381spec = specs [rid ] 382self .assertIs (body ["stream" ],True ) 383self .assertEqual (body ["stream_options" ], {"include_usage" :True }) 384self .assertEqual ((body ["temperature" ],body ["top_p" ],body ["top_k" ],body ["min_p" ]), (1.0 ,0.95 ,20 ,0.0 )) 385self .assertEqual ((body ["presence_penalty" ],body ["repetition_penalty" ]), (0.0 ,1.0 )) 386self .assertEqual (body ["reasoning_effort" ],"xhigh" ) 387self .assertEqual (body ["chat_template_kwargs" ], {"enable_thinking" :True ,"preserve_thinking" :True }) 388self .assertEqual (body ["reasoning_budget_tokens" ],0 ) 389self .assertEqual ((body ["seed" ],body ["max_tokens" ]), (spec ["seed" ],spec ["max_output_tokens" ])) 390self .assertNotIn ("stop" ,body ) 391self .assertEqual (body ["messages" ],spec ["messages" ]) 392self .assertEqual (body .get ("tools" ),spec ["tools" ]) 393if spec ["tools" ]: 394self .assertEqual (body ["tool_choice" ],"auto" ) 395 396def test_the_report_files_and_their_hashes (self ): 397doc ,out = self .run_standard () 398for name in ("results.json" ,"README.md" ,"outputs.jsonl" ,"config.json" ,"provenance/chat_template.jinja" , 399"provenance/corpus-manifest.sha256" ,"provenance/corpus-build.json" ): 400self .assertTrue ((out / name ).is_file (),name ) 401saved = json .loads ((out / "results.json" ).read_text (encoding = "utf-8" )) 402self .assertEqual (saved ,doc ) 403for artifact in doc ["artifacts" ]: 404self .assertEqual (bench_facts .sha256_file (out / artifact ["path" ]),artifact ["sha256" ]) 405self .assertNotIn (".." ,artifact ["path" ]) 406self .assertEqual ({a ["kind" ]for a in doc ["artifacts" ]}, {"outputs" ,"config" ,"provenance" }) 407lines = (out / "outputs.jsonl" ).read_text (encoding = "utf-8" ).splitlines () 408self .assertEqual ([json .loads (line )["request_id" ]for line in lines ], [r ["id" ]for r in doc ["requests" ]]) 409first = json .loads (lines [0 ]) 410self .assertEqual (first ["dispatch_offset_s" ],0.0 ) 411self .assertEqual (first ["first_delta" ]["kind" ],"reasoning" ) 412self .assertEqual (doc ["configuration" ]["template" ], {"path" :"provenance/chat_template.jinja" , 413"sha256" :bench_facts .sha256_text (TEMPLATE )}) 414self .assertEqual (doc ["model" ]["files" ], [{"path" :self .model .name ,"sha256" :bench_facts .sha256_file (self .model )}]) 415self .assertEqual (doc ["model" ]["quantization" ],"IQ2_XS" ) 416readme = (out / "README.md" ).read_text (encoding = "utf-8" ) 417self .assertIn ("Status: complete" ,readme ) 418self .assertIn ("12 of 12" ,readme ) 419self .assertNotIn (str (self .root ),readme ) 420 421def test_every_null_has_a_reason_and_the_request_shape_is_complete (self ): 422doc ,_ = self .run_standard () 423self .assertEqual (set (doc ["missing" ]),set (bs .scan_nulls (doc ))) 424self .assertIn ("/hardware/gpus/0/power_limit_w" ,doc ["missing" ]) 425self .assertIn ("/protocol/model_card_revision" ,doc ["missing" ]) 426self .assertIn ("/requests/0/round" ,doc ["missing" ]) 427record = self .record (doc ,"performance-short-r1" ) 428self .assertEqual (set (record ), {"id" ,"phase" ,"case_id" ,"repetition" ,"seed" ,"max_output_tokens" ,"concurrency" ,"round" , 429"status" ,"finish_reason" ,"error" ,"tokens" ,"timings" ,"metrics" ,"sources" , 430"first_delta_kind" ,"token_accounting_note" ,"evaluation" }) 431self .assertEqual (record ["tokens" ], {"input_tokens" :record ["tokens" ]["input_tokens" ],"cached_tokens" :0 , 432"read_tokens" :record ["tokens" ]["input_tokens" ],"output_tokens" :50 ,"decode_tokens" :50 }) 433self .assertEqual (record ["timings" ]["decode_s" ],0.5 ) 434self .assertEqual (record ["first_delta_kind" ],"reasoning" ) 435self .assertIsNone (record ["token_accounting_note" ]) 436 437def test_the_run_names_its_default_folder_after_the_gpu (self ): 438self .server .gpu_name = "NVIDIA GeForce RTX 3060" 439with mock .patch .object (bench_facts ,"nvidia_gpus" ,return_value = ([{ 440"device_index" :0 ,"name" :"NVIDIA GeForce RTX 3060" ,"memory_bytes" :12 * 2 ** 30 ,"memory_kind" :"dedicated" , 441"power_limit_w" :170.0 ,"driver" :"560.1" }],"560.1" ,"12.6" )): 442doc ,out = bs .run (self .target ,None ,out_root = self .root / "results" ,hash_model = True ) 443self .assertRegex (out .name ,r"^\d{4}-\d\d-\d\d-standard-rtx-3060-[0-9a-f]{8}$" ) 444self .assertEqual (doc ["hardware" ]["gpus" ][0 ]["power_limit_w" ],170.0 ) 445self .assertEqual (doc ["software" ]["runtime" ], [{"name" :"cuda" ,"version" :"12.6" }]) 446 447def test_early_eos_and_a_reached_cap_stay_in_the_speed_summaries (self ): 448self .server .script ["performance-short-r1" ]= {"completion_tokens" :5 ,"predicted_n" :5 ,"rate" :10.0 } 449self .server .script ["performance-short-r2" ]= {"finish" :"length" ,"completion_tokens" :512 ,"predicted_n" :512 ,"rate" :1024.0 } 450doc ,_ = self .run_standard () 451self .assertEqual (self .record (doc ,"performance-short-r2" )["status" ],"truncated" ) 452self .assertEqual (self .record (doc ,"performance-short-r2" )["finish_reason" ],"length" ) 453row = self .summary (doc ,"short" ,"decode_tps" ) 454self .assertEqual ((row ["n" ],row ["min" ],row ["max" ]), (3 ,10.0 ,1024.0 )) 455self .assertEqual (doc ["request_counts" ]["performance" ]["truncated" ],1 ) 456 457def test_a_failed_request_is_excluded_and_listed_but_the_run_goes_on (self ): 458self .server .script ["performance-prompt-4k-r2" ]= {"http" :500 } 459doc ,out = self .run_standard () 460self .assertEqual (doc ["run" ]["status" ],"complete" ) 461record = self .record (doc ,"performance-prompt-4k-r2" ) 462self .assertEqual ((record ["status" ],record ["error" ]["kind" ]), ("failed" ,"http_500" )) 463row = self .summary (doc ,"prompt-4k" ,"decode_tps" ) 464self .assertEqual (row ["n" ],2 ) 465self .assertEqual (row ["excluded" ], [{"request_id" :"performance-prompt-4k-r2" ,"reason" :"failed: http_500" }]) 466self .assertEqual (doc ["request_counts" ]["performance" ]["failed" ],1 ) 467self .assertEqual (len (self .server .order ),22 ) 468self .assertIn ("performance-prompt-4k-r2 failed" , (out / "README.md" ).read_text (encoding = "utf-8" )) 469self .assertEqual (bs .validate (doc ), []) 470 471def test_a_failed_warmup_skips_everything_else (self ): 472self .server .script ["warmup" ]= {"http" :500 } 473doc ,_ = self .run_standard () 474self .assertEqual (doc ["run" ]["status" ],"partial" ) 475self .assertEqual (len (self .server .order ),1 ) 476self .assertEqual (len (doc ["requests" ]),22 ) 477self .assertEqual (doc ["request_counts" ]["performance" ]["skipped" ],9 ) 478self .assertEqual (doc ["request_counts" ]["sanity" ], {"planned" :12 ,"attempted" :0 ,"completed" :0 ,"truncated" :0 ,"failed" :0 ,"skipped" :12 }) 479self .assertEqual (doc ["quality" ]["passed" ],0 ) 480skipped = self .record (doc ,"sanity-T4" ) 481self .assertEqual ((skipped ["status" ],skipped ["error" ]["kind" ]), ("skipped" ,"skipped" )) 482self .assertFalse (skipped ["evaluation" ]["passed" ]) 483self .assertTrue (all (s ["n" ]== 0 and s ["median" ]is None for s in doc ["summaries" ])) 484self .assertEqual (bs .validate (doc ), []) 485 486def test_a_dead_server_marks_the_rest_skipped (self ): 487self .server .script ["performance-prompt-4k-r1" ]= {"die" :True } 488doc ,_ = self .run_standard () 489self .assertEqual (doc ["run" ]["status" ],"partial" ) 490self .assertEqual (self .record (doc ,"performance-prompt-4k-r1" )["status" ],"failed" ) 491self .assertEqual (self .record (doc ,"performance-prompt-16k-r1" )["status" ],"skipped" ) 492self .assertIn ("server stopped answering" ,self .record (doc ,"sanity-I1" )["error" ]["message" ]) 493self .assertEqual (len (doc ["requests" ]),22 ) 494self .assertEqual (bs .validate (doc ), []) 495 496def test_a_request_that_never_finishes_times_out (self ): 497self .server .script ["performance-short-r1" ]= {"hang" :3 } 498started = time .monotonic () 499doc ,_ = self .run_standard (timeout_s = 0.6 ) 500record = self .record (doc ,"performance-short-r1" ) 501self .assertEqual ((record ["status" ],record ["error" ]["kind" ]), ("failed" ,"timeout" )) 502self .assertLess (record ["timings" ]["total_s" ],2.0 ) 503self .assertGreaterEqual (record ["timings" ]["total_s" ],0.5 ) 504self .assertEqual (doc ["run" ]["status" ],"complete" ) 505self .assertLess (time .monotonic ()- started ,30 ) 506 507def test_a_stream_without_done_or_finish_reason_is_a_failure (self ): 508self .server .script ["performance-short-r1" ]= {"no_done" :True } 509self .server .script ["performance-short-r2" ]= {"finish" :None } 510doc ,_ = self .run_standard () 511self .assertEqual (self .record (doc ,"performance-short-r1" )["error" ]["kind" ],"malformed_stream" ) 512self .assertEqual (self .record (doc ,"performance-short-r2" )["error" ]["kind" ],"malformed_stream" ) 513self .assertEqual (self .summary (doc ,"short" ,"decode_tps" )["n" ],1 ) 514 515def test_empty_deltas_and_keepalives_do_not_count_as_the_first_token (self ): 516self .server .script ["performance-short-r1" ]= {"first_delay" :0.4 } 517doc ,out = self .run_standard () 518record = self .record (doc ,"performance-short-r1" ) 519self .assertGreaterEqual (record ["timings" ]["ttft_s" ],0.35 ) 520self .assertEqual (record ["first_delta_kind" ],"reasoning" ) 521self .assertGreaterEqual (record ["timings" ]["first_answer_s" ],record ["timings" ]["ttft_s" ]) 522tool = self .record (doc ,"sanity-T1" ) 523self .assertIsNotNone (tool ["timings" ]["first_answer_s" ])# a tool-call delta is an answer 524self .assertIsNone (self .record (doc ,"sanity-T1" )["error" ]) 525 526def test_missing_usage_and_timings_leave_the_rates_null_with_reasons (self ): 527self .server .script ["performance-short-r1" ]= {"usage" :False ,"timings" :False } 528doc ,_ = self .run_standard () 529record = self .record (doc ,"performance-short-r1" ) 530self .assertEqual (record ["status" ],"completed" ) 531self .assertIsNone (record ["metrics" ]["prompt_tps" ]) 532self .assertIsNone (record ["metrics" ]["decode_tps" ]) 533self .assertIsNone (record ["tokens" ]["output_tokens" ]) 534self .assertIsNotNone (record ["timings" ]["ttft_s" ]) 535index = doc ["requests" ].index (record ) 536self .assertIn (f"/requests/ { index } /metrics/decode_tps" ,doc ["missing" ]) 537row = self .summary (doc ,"short" ,"decode_tps" ) 538self .assertEqual (row ["n" ],2 ) 539self .assertIn ("decode_tps is not available" ,row ["excluded" ][0 ]["reason" ]) 540self .assertEqual (bs .validate (doc ), []) 541 542def test_a_decode_count_that_disagrees_with_the_rate_is_explained (self ): 543# the engine's rate and time imply 50 tokens (100/s over 0.5 s) while predicted_n says 60 and the API says 61 544self .server .script ["performance-short-r1" ]= {"predicted_n" :60 ,"completion_tokens" :61 } 545doc ,_ = self .run_standard () 546record = self .record (doc ,"performance-short-r1" ) 547self .assertEqual (record ["tokens" ]["decode_tokens" ],50 ) 548self .assertEqual (record ["tokens" ]["output_tokens" ],61 ) 549self .assertIn ("implied" ,record ["token_accounting_note" ]) 550self .assertEqual (record ["metrics" ]["decode_tps" ],100.0 ) 551self .assertIn ("derived" ,record ["sources" ]["decode_tokens" ]) 552 553def test_wrong_answers_are_kept_and_scored_without_changing_the_run_status (self ): 554specs = corpus_specs () 555script = self .server .script 556script ["sanity-I1" ]= {"content" :'```json\n{"ok":true,"count":3}\n```' } 557script ["sanity-I2" ]= {"content" :"Here you go: [-4,1,2,9]" } 558script ["sanity-I3" ]= {"content" :'{"project":"Orion","project":"Orion","build":17}' } 559script ["sanity-R1" ]= {"finish" :"length" ,"content" :"ORB" ,"completion_tokens" :2048 ,"predicted_n" :2048 } 560script ["sanity-R2" ]= {"content" :"cedar-284" } 561script ["sanity-T1" ]= {"tool_calls" : [],"content" :"lookup_record({\"id\":\"A-17\"})" } 562script ["sanity-T2" ]= {"tool_calls" : [{"name" :"get_weather" ,"arguments" :'{"city":"Zagreb","unit":"celsius"}' }]* 2 } 563script ["sanity-T3" ]= {"tool_calls" : [{"name" :"convert_units" ,"arguments" :'{"value":3.0,"from_unit":"km","to_unit":"m"}' }]} 564doc ,_ = self .run_standard () 565verdicts = {r ["case_id" ]:r ["evaluation" ]["passed" ]for r in doc ["requests" ]if r ["phase" ]== "sanity" } 566self .assertEqual (verdicts , {"I1" :False ,"I2" :False ,"I3" :False ,"I4" :True ,"R1" :False ,"R2" :False ,"R3" :True ,"R4" :True , 567"T1" :False ,"T2" :False ,"T3" :False ,"T4" :True }) 568self .assertEqual (doc ["quality" ]["passed" ],4 ) 569self .assertEqual (doc ["quality" ]["categories" ]["instruction" ]["passed" ],1 ) 570self .assertEqual (self .record (doc ,"sanity-R1" )["status" ],"truncated" ) 571self .assertIn ("output cap" ,self .record (doc ,"sanity-R1" )["evaluation" ]["reason" ]) 572self .assertEqual (doc ["run" ]["status" ],"complete" ) 573self .assertEqual (specs ["sanity-I1" ]["expected" ]["value" ], {"ok" :True ,"count" :3 }) 574text = bs .format_plain (doc ) 575self .assertIn ("Sanity checks: 4 of 12 passed" ,text ) 576self .assertIn ("I1:" ,text ) 577 578def test_unexpected_reuse_of_the_user_payload_is_excluded_and_nonconforming (self ): 579spec = corpus_specs ()["performance-prompt-4k-r2" ] 580self .server .script ["performance-prompt-4k-r2" ]= {"cached" :spec ["input_tokens_frozen" ]- 10 } 581# the shared template prefix alone is allowed 582self .server .script ["performance-prompt-4k-r1" ]= {"cached" :40 } 583# whatever the login of the machine running the test is: "user" is an ordinary word of the report, not a name here 584with mock .patch .object (bench_facts .getpass ,"getuser" ,return_value = "no-such-login" ): 585doc ,_ = self .run_standard () 586self .assertEqual (doc ["run" ]["status" ],"nonconforming" ) 587row = self .summary (doc ,"prompt-4k" ,"prompt_tps" ) 588self .assertEqual (row ["n" ],2 ) 589self .assertIn ("unexpected cache reuse" ,row ["excluded" ][0 ]["reason" ]) 590self .assertTrue (any ("unexpected reuse of the user payload in performance-prompt-4k-r2" in r 591for r in doc ["extensions" ]["status_reasons" ])) 592self .assertEqual (self .record (doc ,"performance-prompt-4k-r1" )["tokens" ]["cached_tokens" ],40 ) 593self .assertEqual (bs .validate (doc ), []) 594 595def test_a_prompt_length_off_its_target_is_nonconforming (self ): 596original = bs .load_corpus () 597specs = copy .deepcopy (original .specs ) 598for spec in specs : 599if spec ["id" ]== "performance-prompt-4k-r1" : 600spec ["target_input_tokens" ]= 3000 601patched = bs .Corpus (original .sha256 ,specs ,original .build ,original .manifest ,original .directory ) 602doc ,_ = self .run_standard (corpus = patched ) 603self .assertEqual (doc ["run" ]["status" ],"nonconforming" ) 604self .assertTrue (any ("outside 2%" in r for r in doc ["extensions" ]["status_reasons" ])) 605 606def test_a_refused_setting_is_nonconforming (self ): 607self .server .script ["warmup" ]= {"http" :400 } 608doc ,_ = self .run_standard () 609self .assertEqual (doc ["run" ]["status" ],"nonconforming" ) 610self .assertTrue (any ("refused the protocol's required settings" in r for r in doc ["extensions" ]["status_reasons" ])) 611self .assertEqual (self .record (doc ,"sanity-I1" )["status" ],"skipped" ) 612 613def test_missing_identity_makes_the_run_nonconforming (self ): 614with mock .patch .object (bench_facts ,"git_commit" ,return_value = None ): 615doc ,_ = self .run_standard ("nocommit" ) 616self .assertEqual (doc ["run" ]["status" ],"nonconforming" ) 617self .assertIn ("/software/strata_commit" ,doc ["missing" ]) 618self .assertIsNone (doc ["protocol" ]["git_commit" ]) 619doc2 ,_ = self .run_standard ("nohash" ,hash_model = False ) 620self .assertEqual (doc2 ["run" ]["status" ],"nonconforming" ) 621self .assertIsNone (doc2 ["model" ]["files" ]) 622self .assertIn ("/model/files" ,doc2 ["missing" ]) 623 624def test_a_remote_server_is_nonconforming (self ): 625with mock .patch .object (bs .Target ,"loopback" ,new_callable = mock .PropertyMock ,return_value = False ): 626doc ,_ = self .run_standard () 627self .assertEqual (doc ["run" ]["status" ],"nonconforming" ) 628self .assertTrue (any ("not on loopback" in r for r in doc ["extensions" ]["status_reasons" ])) 629 630def test_cancelling_keeps_the_finished_requests_and_skips_the_rest (self ): 631real = bs .stream_chat 632calls = [] 633 634def interrupted (target ,spec ,model ,** kwargs ): 635calls .append (spec ["id" ]) 636if len (calls )== 6 : 637class Boom : 638sock = None 639 640def request (self ,* args ,** kw ): 641raise KeyboardInterrupt 642 643def close (self ): 644pass 645with mock .patch .object (bs .Target ,"connection" ,return_value = Boom ()): 646return real (target ,spec ,model ,** kwargs ) 647return real (target ,spec ,model ,** kwargs ) 648with mock .patch .object (bs ,"stream_chat" ,interrupted ): 649doc ,_ = self .run_standard () 650self .assertEqual (doc ["run" ]["status" ],"partial" ) 651self .assertEqual (self .record (doc ,"performance-prompt-4k-r2" )["error" ]["kind" ],"cancelled" ) 652self .assertEqual (self .record (doc ,"performance-prompt-4k-r2" )["status" ],"failed" ) 653self .assertEqual (self .record (doc ,"performance-prompt-16k-r3" )["status" ],"skipped" ) 654self .assertEqual (self .record (doc ,"sanity-T4" )["error" ]["message" ],"the operator cancelled the run" ) 655self .assertEqual (self .summary (doc ,"short" ,"decode_tps" )["n" ],3 - 1 ) 656self .assertEqual (bs .validate (doc ), []) 657 658def test_the_optional_concurrency_stage_releases_four_together (self ): 659for r in (1 ,2 ,3 ): 660for c in (1 ,2 ,3 ,4 ): 661self .server .script [f"concurrency-r { r } -c { c } " ]= {"hold_for_arrivals" :4 } 662doc ,_ = self .run_standard (optional_concurrency = True ) 663self .assertEqual (doc ["run" ]["status" ],"complete" ) 664self .assertEqual (len (doc ["requests" ]),34 ) 665self .assertEqual (self .server .max_active ,4 ) 666self .assertEqual (doc ["request_counts" ]["concurrency" ]["planned" ],12 ) 667self .assertEqual (len (doc ["concurrency_rounds" ]),3 ) 668for round_ in doc ["concurrency_rounds" ]: 669self .assertEqual (round_ ["output_tokens" ],200 ) 670self .assertEqual (round_ ["failed" ],0 ) 671self .assertAlmostEqual (round_ ["aggregate_tps" ],200 / round_ ["wall_s" ],places = 3 ) 672self .assertEqual (len (round_ ["request_ids" ]),4 ) 673rows = [s for s in doc ["summaries" ]if s ["phase" ]== "concurrency" ] 674self .assertEqual (len (rows ),5 ) 675self .assertEqual ({(s ["case_id" ],s ["concurrency" ])for s in rows }, {("short-burst" ,4 )}) 676self .assertEqual (rows [0 ]["n" ],12 ) 677self .assertIsNotNone (doc ["run" ]["optional_duration_s" ]) 678for round_no in (1 ,2 ,3 ):# a round finishes before the next one is released 679 680self .assertEqual ({n for n in self .server .order [22 + 4 * (round_no - 1 ):22 + 4 * round_no ]}, 681 {f"concurrency-r { round_no } -c { c } " for c in (1 ,2 ,3 ,4 )}) 682self .assertEqual (bs .validate (doc ), []) 683 684def test_a_failed_concurrent_request_keeps_its_time_in_the_round (self ): 685self .server .script ["concurrency-r1-c2" ]= {"http" :500 } 686doc ,_ = self .run_standard (optional_concurrency = True ) 687first = doc ["concurrency_rounds" ][0 ] 688self .assertEqual ((first ["failed" ],first ["output_tokens" ]), (1 ,150 )) 689self .assertEqual (doc ["concurrency_rounds" ][1 ]["failed" ],0 ) 690self .assertEqual (doc ["request_counts" ]["concurrency" ]["failed" ],1 ) 691 692def test_a_round_total_is_null_when_a_counted_request_has_no_token_count (self ): 693self .server .script ["concurrency-r2-c3" ]= {"usage" :False } 694# the first round must last a measurable time: Windows' monotonic clock moves in ~15.6 ms ticks, and a fast PC (a CI runner) can finish 695# the stub round inside one tick (wall 0 s, so no rate) 696self .server .script ["concurrency-r1-c1" ]= {"first_delay" :0.05 } 697doc ,_ = self .run_standard (optional_concurrency = True ) 698second = doc ["concurrency_rounds" ][1 ] 699self .assertIsNone (second ["output_tokens" ]) 700self .assertIsNone (second ["aggregate_tps" ]) 701self .assertIsNotNone (doc ["concurrency_rounds" ][0 ]["aggregate_tps" ]) 702self .assertEqual (bs .validate (doc ), []) 703 704def test_the_plain_summary (self ): 705doc ,_ = self .run_standard () 706text = bs .format_plain (doc ) 707self .assertIn ("Status: complete. 21 of 21 required requests finished, 0 failed, 0 skipped." ,text ) 708self .assertIn ("prompt-16k" ,text ) 709self .assertIn ("Sanity checks: 12 of 12 passed" ,text ) 710self .assertIn ("Prompt tok/s" ,text ) 711self .assertIn ("1000.0 (1000.0-1000.0) n=3" ,text ) 712 713def test_the_summary_says_what_the_short_prompt_and_the_cap_mean (self ): 714doc ,_ = self .run_standard () 715for text in (bs .format_plain (doc ),bs .report_markdown (doc )): 716self .assertIn ("Capped" ,text ) 717self .assertIn ("not shown; read prompt speed from prompt-4k and prompt-16k" ,text ) 718self .assertIn ("time to the cap, not to an answer" ,text ) 719short_row = next (line for line in bs .format_plain (doc ).splitlines ()if line .strip ().startswith ("short " )) 720self .assertIn ("n/a" ,short_row ) 721self .assertNotIn ("1000.0" ,short_row ) 722self .assertIn ("0/3" ,short_row ) 723# the data keeps the short case's prompt rate: only the readable summaries leave it out 724self .assertIsNotNone (self .summary (doc ,"short" ,"prompt_tps" )) 725# a request that stopped at the cap is counted 726record = next (r for r in doc ["requests" ]if r ["id" ]== "performance-prompt-4k-r1" ) 727record ["status" ]= "truncated" 728row = next (line for line in bs .format_plain (doc ).splitlines ()if line .strip ().startswith ("prompt-4k " )) 729self .assertTrue (row .rstrip ().endswith ("1/3" )) 730 731def test_the_server_is_not_asked_for_anything_outside_the_protocol (self ): 732self .run_standard () 733self .assertTrue (all (body ["messages" ]== corpus_specs ()[rid ]["messages" ]for body ,rid in zip (self .server .bodies ,self .server .order ))) 734 735 736class ValidatorTests (StandardBase ): 737def test_the_validator_refuses_broken_results (self ): 738doc ,_ = self .run_standard () 739self .assertEqual (bs .validate (doc ), []) 740broken = copy .deepcopy (doc ) 741broken ["schema_version" ]= 2 742self .assertTrue (bs .validate (broken )) 743broken = copy .deepcopy (doc ) 744broken ["request_counts" ]["performance" ]["completed" ]= 8 745self .assertTrue (any ("identity" in p for p in bs .validate (broken ))) 746broken = copy .deepcopy (doc ) 747broken ["missing" ].pop (next (iter (broken ["missing" ]))) 748self .assertTrue (any ("missing must list" in p for p in bs .validate (broken ))) 749broken = copy .deepcopy (doc ) 750broken ["summaries" ][0 ]["median" ]= 12345.0 751self .assertTrue (any ("rebuilt" in p for p in bs .validate (broken ))) 752broken = copy .deepcopy (doc ) 753broken ["requests" ][1 ]["timings" ]["ttft_s" ]= float ("nan" ) 754self .assertTrue (bs .validate (broken )) 755broken = copy .deepcopy (doc ) 756broken ["surprise" ]= 1 757self .assertTrue (any ("extensions" in p for p in bs .validate (broken ))) 758broken = copy .deepcopy (doc ) 759broken ["artifacts" ][0 ]["path" ]= "../escape" 760self .assertTrue (any ("artifact" in p for p in bs .validate (broken ))) 761 762def test_load_reads_a_saved_result_and_refuses_other_files (self ): 763doc ,out = self .run_standard () 764self .assertEqual (bs .load (out )["run" ]["id" ],doc ["run" ]["id" ]) 765self .assertIsNone (bs .load_if_standard (self .root / "nothing" )) 766other = self .root / "other.json" 767other .write_text (json .dumps ({"kind" :"strata.serving.benchmark" }),encoding = "utf-8" ) 768self .assertIsNone (bs .load_if_standard (other )) 769bad = json .loads ((out / "results.json" ).read_text (encoding = "utf-8" )) 770bad ["schema_version" ]= 9 771 (self .root / "bad.json" ).write_text (json .dumps (bad ),encoding = "utf-8" ) 772with self .assertRaises (ProfileError ): 773bs .load_if_standard (self .root / "bad.json" ) 774 775 776class CommandLineTests (StandardBase ): 777def invoke (self ,* args ,env = None ): 778output ,errors = io .StringIO (),io .StringIO () 779with mock .patch .dict (os .environ ,env or {}),contextlib .redirect_stdout (output ),contextlib .redirect_stderr (errors ): 780code = main (["bench" ,"run" ,* args ]) 781return code ,output .getvalue (),errors .getvalue () 782 783def test_the_standard_suite_is_the_default_and_prints_a_plain_summary (self ): 784out = self .root / "cli" 785code ,text ,errors = self .invoke ("--url" ,self .server .url ,"--out" ,str (out )) 786self .assertEqual (code ,0 ,errors ) 787self .assertIn ("Strata standard benchmark (strata-qwen38-thinking-v1-draft.1)" ,text ) 788self .assertIn ("Sanity checks: 12 of 12 passed" ,text ) 789self .assertIn ("Report:" ,text ) 790self .assertEqual (bs .load (out )["run" ]["status" ],"complete" ) 791self .assertIn ("[1/22] warmup" ,errors ) 792 793def test_json_output (self ): 794code ,text ,_ = self .invoke ("--url" ,self .server .url ,"--out" ,str (self .root / "j" ),"--output" ,"json" ) 795self .assertEqual (code ,0 ) 796value = json .loads (text ) 797self .assertTrue (value ["ok" ]) 798self .assertEqual (value ["quality" ]["passed" ],12 ) 799self .assertEqual (len (value ["summaries" ]),15 ) 800 801def test_a_partial_run_exits_with_6 (self ): 802self .server .script ["warmup" ]= {"http" :500 } 803code ,text ,_ = self .invoke ("--url" ,self .server .url ,"--out" ,str (self .root / "p" )) 804self .assertEqual (code ,6 ) 805self .assertIn ("Status: partial" ,text ) 806self .assertIn ("Why this is not a complete standard result" ,text ) 807 808def test_serving_options_do_not_apply (self ): 809for option in (("--concurrency" ,"2" ), ("--repeat" ,"2" ), ("--request-timeout" ,"30" ), ("--condition" ,"baseline" )): 810code ,text ,_ = self .invoke ("--url" ,self .server .url ,"--out" ,str (self .root / "x" ),"--output" ,"json" ,* option ) 811self .assertEqual (code ,2 ,option ) 812self .assertIn ("do not apply to the standard suite" ,text ) 813self .assertFalse ((self .root / "x" ).exists ()) 814 815def test_the_out_folder_must_be_new_and_the_default_goes_under_bench_results (self ): 816 (self .root / "taken" ).mkdir () 817code ,text ,_ = self .invoke ("--url" ,self .server .url ,"--out" ,str (self .root / "taken" ),"--output" ,"json" ) 818self .assertEqual (code ,2 ) 819previous = Path .cwd () 820os .chdir (self .root ) 821try : 822code ,text ,_ = self .invoke ("--url" ,self .server .url ) 823finally : 824os .chdir (previous ) 825self .assertEqual (code ,0 ) 826self .assertTrue (any ((self .root / "bench-results" ).glob ("*-standard-*/results.json" ))) 827 828def test_the_serving_suites_still_need_out_and_keep_their_defaults (self ): 829code ,text ,_ = self .invoke ("--url" ,self .server .url ,"--suite" ,"serving-smoke" ,"--output" ,"json" ) 830self .assertEqual (code ,2 ) 831self .assertIn ("--out is required for the serving suites" ,text ) 832 833def test_the_options_reach_the_report (self ): 834out = self .root / "opts" 835code ,_ ,errors = self .invoke ("--url" ,self .server .url ,"--out" ,str (out ),"--track" ,"default" ,"--track-notes" , 836"0.2.0 release, setup choices" ,"--model-revision" ,"r1" ,"--source-revision" ,"r2" , 837"--tokenizer-revision" ,"r3" ,"--custom-pack" ,"none" ,"--background" ,"browser open" , 838"--build-options" ,"cuda,sm86" ,"--optional-concurrency" ) 839self .assertEqual (code ,0 ,errors ) 840doc = bs .load (out ) 841self .assertEqual ((doc ["configuration" ]["track" ],doc ["configuration" ]["track_notes" ]), ("default" ,"0.2.0 release, setup choices" )) 842self .assertEqual ((doc ["model" ]["revision" ],doc ["model" ]["source_revision" ],doc ["model" ]["tokenizer_revision" ]), ("r1" ,"r2" ,"r3" )) 843self .assertEqual (doc ["hardware" ]["background_workloads" ], ["browser open" ]) 844self .assertEqual (doc ["software" ]["build_options" ], ["cuda" ,"sm86" ]) 845self .assertTrue (doc ["run" ]["optional_concurrency" ]) 846self .assertIn ("--track default" ,doc ["run" ]["command" ]) 847self .assertTrue (doc ["run" ]["command" ].startswith ("strata bench run" )) 848 849def test_results_json_is_redacted_like_the_other_files (self ): 850"""#4484: free text from the operator reached results.json as typed while the README and the other files were redacted.""" 851out = self .root / "redacted" 852home = str (Path .home ()) 853notes = f"models in { home } /m, server 192.168.7.9" 854code ,_ ,errors = self .invoke ("--url" ,self .server .url ,"--out" ,str (out ),"--track" ,"custom" ,"--track-notes" ,notes , 855"--background" ,f"indexer in { home } /idx" ) 856self .assertEqual (code ,0 ,errors ) 857for name in ("results.json" ,"README.md" ,"config.json" ,"outputs.jsonl" ): 858text = (out / name ).read_text (encoding = "utf-8" ) 859self .assertNotIn (home ,text ,name ) 860self .assertNotIn (home .replace ("\\" ,"\\\\" ),text ,name )# the way JSON spells a Windows path 861self .assertNotIn ("192.168.7.9" ,text ,name ) 862doc = bs .load (out ) 863self .assertRegex (doc ["configuration" ]["track_notes" ],"<home>|<user>" ) 864self .assertIn ("<ip>" ,doc ["configuration" ]["track_notes" ]) 865self .assertEqual (doc ["request_counts" ]["performance" ]["planned" ]> 0 ,True )# counters are untouched 866 867def test_a_login_that_is_an_ordinary_word_does_not_rewrite_the_reports_own_words (self ): 868"""INT3 on l620, where the login is exactly "user": the report's fixed text (status reasons, enum values, field names) came out as 869"<user>", while the operator's own text still loses the name.""" 870spec = corpus_specs ()["performance-prompt-4k-r2" ] 871out = self .root / "wordlogin" 872with mock .patch .object (bench_facts .getpass ,"getuser" ,return_value = "user" ), \ 873mock .patch .object (bench_facts .socket ,"gethostname" ,return_value = "summaries" ), \ 874mock .patch .object (bench_facts .platform ,"node" ,return_value = "summaries" ): 875self .server .script ["performance-prompt-4k-r2" ]= {"cached" :spec ["input_tokens_frozen" ]- 10 } 876code ,_ ,errors = self .invoke ("--url" ,self .server .url ,"--out" ,str (out ),"--track" ,"custom" , 877"--track-notes" ,"ask the user at summaries time" ) 878self .assertEqual (code ,6 ,errors ) 879doc = bs .load (out ) 880self .assertEqual (bs .validate (doc ), []) 881self .assertTrue (any ("unexpected reuse of the user payload in performance-prompt-4k-r2" in r 882for r in doc ["extensions" ]["status_reasons" ]),doc ["extensions" ]["status_reasons" ]) 883self .assertEqual (doc ["configuration" ]["track_notes" ],"ask the <user> at <host> time" ) 884text = (out / "results.json" ).read_text (encoding = "utf-8" ) 885self .assertIn ('"summaries"' ,text )# a field name that equals the host name stays a field name 886 887def test_a_credential_of_none_is_no_key_and_the_word_is_left_alone (self ): 888"""#4483: STRATA_KEY=none was sent as "Bearer none" and the word was replaced wherever it occurred.""" 889out = self .root / "nonekey" 890code ,_ ,errors = self .invoke ("--url" ,self .server .url ,"--out" ,str (out ),"--credential-env" ,"STRATA_TEST_KEY" , 891"--track-notes" ,"nonempty reasoning, none of the nodes" ,env = {"STRATA_TEST_KEY" :" None " }) 892self .assertEqual (code ,0 ,errors ) 893doc = bs .load (out ) 894self .assertFalse (doc ["extensions" ]["api_key_sent" ]) 895self .assertEqual (doc ["configuration" ]["track_notes" ],"nonempty reasoning, none of the nodes" ) 896self .assertNotIn ("<key>" , (out / "README.md" ).read_text (encoding = "utf-8" )) 897 898def test_report_reads_a_standard_result_in_three_forms (self ): 899out = self .root / "rep" 900self .assertEqual (self .invoke ("--url" ,self .server .url ,"--out" ,str (out ))[0 ],0 ) 901output = io .StringIO () 902with contextlib .redirect_stdout (output ): 903self .assertEqual (main (["bench" ,"report" ,str (out )]),0 ) 904self .assertIn ("Sanity checks: 12 of 12 passed" ,output .getvalue ()) 905output = io .StringIO () 906with contextlib .redirect_stdout (output ): 907self .assertEqual (main (["bench" ,"report" ,str (out ),"--output" ,"markdown" ]),0 ) 908self .assertIn ("# Strata standard benchmark" ,output .getvalue ()) 909output = io .StringIO () 910with contextlib .redirect_stdout (output ): 911self .assertEqual (main (["bench" ,"report" ,str (out ),"--output" ,"json" ]),0 ) 912self .assertEqual (json .loads (output .getvalue ())["summary" ]["status" ],"complete" ) 913 914def test_a_profile_that_is_not_running_is_started_and_stopped (self ): 915out = self .root / "prof" 916cfg = {"api_key" :"" ,"model_name" :"mock" } 917plan = {"effective" : {"host" :"127.0.0.1" ,"port" :int (self .server .url .rsplit (":" ,1 )[1 ])},"engine_argv" : ["--kv" ,"int8" ,"--expert-cache" ,"1500" ]} 918health = {"calls" :0 } 919real_get = bs .Target .get 920 921def get (target ,path ,timeout = 10 ): 922if path == "/health" and health ["calls" ]< 1 : 923health ["calls" ]+= 1 924return None # nothing answers before the engine is started 925return real_get (target ,path ,timeout ) 926started = [] 927with mock .patch ("strata_cli.cli._source" ,return_value = (Path ("p.json" ),None ,None ,cfg )), \ 928mock .patch ("strata_cli.cli._launch_plan" ,return_value = (plan , [])), \ 929mock .patch .object (bs .Target ,"get" ,get ), \ 930mock .patch .object (bs ,"start_engine" ,side_effect = lambda ref ,target ,log ,say ,wait :started .append (ref )or "proc" )as start , \ 931mock .patch .object (bs ,"stop_engine" )as stop : 932code ,text ,errors = self .invoke ("--profile" ,"p.json" ,"--out" ,str (out )) 933self .assertEqual (code ,0 ,errors ) 934self .assertEqual (started , ["p.json" ]) 935stop .assert_called_once_with ("proc" ) 936doc = bs .load (out ) 937self .assertTrue (doc ["extensions" ]["started_engine" ]) 938self .assertEqual (doc ["configuration" ]["kv_cache" ], {"--kv" :"int8" }) 939self .assertEqual (doc ["configuration" ]["expert_cache" ], {"--expert-cache" :"1500" }) 940self .assertNotIn ("/configuration/kv_cache" ,doc ["missing" ]) 941 942def test_a_running_profile_is_used_and_left_running (self ): 943plan = {"effective" : {"host" :"127.0.0.1" ,"port" :int (self .server .url .rsplit (":" ,1 )[1 ])},"engine_argv" : []} 944with mock .patch ("strata_cli.cli._source" ,return_value = (Path ("p.json" ),None ,None , {})), \ 945mock .patch ("strata_cli.cli._launch_plan" ,return_value = (plan , [])), \ 946mock .patch .object (bs ,"start_engine" )as start ,mock .patch .object (bs ,"stop_engine" )as stop : 947code ,text ,errors = self .invoke ("--profile" ,"p.json" ,"--out" ,str (self .root / "run" )) 948self .assertEqual (code ,0 ,errors ) 949start .assert_not_called () 950stop .assert_called_once_with (None ) 951self .assertIn ("already running" ,errors ) 952self .assertFalse (bs .load (self .root / "run" )["extensions" ]["started_engine" ]) 953 954def test_no_start_refuses_to_launch (self ): 955self .server .close () 956plan = {"effective" : {"host" :"127.0.0.1" ,"port" :int (self .server .url .rsplit (":" ,1 )[1 ])},"engine_argv" : []} 957with mock .patch ("strata_cli.cli._source" ,return_value = (Path ("p.json" ),None ,None , {})), \ 958mock .patch ("strata_cli.cli._launch_plan" ,return_value = (plan , [])), \ 959mock .patch .object (bs ,"start_engine" )as start : 960code ,text ,_ = self .invoke ("--profile" ,"p.json" ,"--out" ,str (self .root / "ns" ),"--no-start" ,"--output" ,"json" ) 961self .assertEqual (code ,5 ) 962start .assert_not_called () 963 964 965class EngineProcessTests (unittest .TestCase ): 966def test_start_engine_runs_serve_with_the_profile_and_stop_ends_only_that_process (self ): 967class Fake : 968pid = 4242 969 970def poll (self ): 971return None 972 973def wait (self ,timeout = None ): 974return 0 975 976def kill (self ):# stop_engine's last step on Windows, when taskkill (mocked below) left the process running 977pass 978seen = {} 979 980def popen (command ,** kwargs ): 981seen ["command" ]= command 982return Fake () 983target = mock .Mock () 984target .get .return_value = {"service" :"strata" ,"loaded" :True } 985with tempfile .TemporaryDirectory ()as temp ,mock .patch ("subprocess.Popen" ,popen ): 986proc = bs .start_engine ("run.json" ,target ,Path (temp )/ "engine.log" ,lambda m :None ,5 ) 987self .assertEqual (seen ["command" ][1 ].replace ("\\" ,"/" ).rsplit ("/" ,1 )[- 1 ],"strata.py" ) 988self .assertEqual (seen ["command" ][2 :5 ], ["serve" ,"--profile" ,"run.json" ]) 989with mock .patch ("subprocess.run" )as run ,mock .patch ("os.killpg" ,create = True )as killpg : 990bs .stop_engine (proc ) 991if os .name == "nt" : 992self .assertEqual (run .call_args [0 ][0 ][:4 ], ["taskkill" ,"/PID" ,"4242" ,"/T" ]) 993else : 994killpg .assert_called () 995 996# #3438: the stop used to ignore taskkill's result and the wait timeout, so a stop that failed still ended as a normal finish 997def _stuck_proc (self ): 998class Stuck : 999pid = 777 1000 1001def poll (self ): 1002return None # never exits 1003 1004def wait (self ,timeout = None ): 1005raise bs .subprocess .TimeoutExpired ("x" ,timeout ) 1006 1007def terminate (self ): 1008pass 1009 1010def kill (self ): 1011pass 1012return Stuck () 1013 1014def test_stop_engine_says_so_when_the_process_survives (self ): 1015proc = self ._stuck_proc () 1016done = bs .subprocess .CompletedProcess ([],1 ,b"" ,b"ERROR: Access is denied." ) 1017with mock .patch ("subprocess.run" ,return_value = done ),mock .patch ("os.killpg" ,create = True ): 1018problem = bs .stop_engine (proc ) 1019self .assertIsNotNone (problem ) 1020self .assertIn ("777" ,problem ) 1021self .assertIn ("still running" ,problem ) 1022if os .name == "nt" : 1023self .assertIn ("taskkill" ,problem ) 1024self .assertIn ("Access is denied" ,problem ) 1025 1026@ unittest . skipUnless ( os . name == "nt" , "taskkill is the Windows stop" ) 1027def test_stop_engine_reports_a_taskkill_that_times_out (self ): 1028proc = self ._stuck_proc () 1029with mock .patch ("subprocess.run" ,side_effect = bs .subprocess .TimeoutExpired ("taskkill" ,60 )): 1030problem = bs .stop_engine (proc ) 1031self .assertIn ("did not finish in 60 s" ,problem ) 1032 1033def test_stop_engine_is_quiet_when_the_process_ends (self ): 1034class Ends : 1035pid = 5 1036alive = True 1037 1038def poll (self ): 1039return None if self .alive else 0 1040 1041def wait (self ,timeout = None ): 1042self .alive = False 1043return 0 1044 1045def terminate (self ): 1046self .alive = False 1047proc = Ends () 1048done = bs .subprocess .CompletedProcess ([],0 ,b"" ,b"" ) 1049 1050def kill (* args ,** kwargs ): 1051proc .alive = False 1052return done 1053with mock .patch ("subprocess.run" ,side_effect = kill ),mock .patch ("os.killpg" ,create = True ,side_effect = lambda * a :setattr (proc ,"alive" ,False )): 1054self .assertIsNone (bs .stop_engine (proc )) 1055self .assertIsNone (bs .stop_engine (None )) 1056# a process that exited by itself needs no kill at all 1057gone = mock .Mock () 1058gone .poll .return_value = 0 1059self .assertIsNone (bs .stop_engine (gone )) 1060 1061def test_a_run_whose_engine_cannot_be_stopped_is_marked_failed_and_loud (self ): 1062# cli: the run finished, the stop failed -> exit code 6, an ERROR line on stderr, a note in the folder, ok false in the json 1063plan = {"effective" : {"host" :"127.0.0.1" ,"port" :1 },"engine_argv" : [],"config" : {}} 1064fake_doc = {"run" : {"status" :"complete" },"quality" : {},"summaries" : []} 1065out_dir = Path (tempfile .mkdtemp ()) 1066self .addCleanup (shutil .rmtree ,out_dir ,True ) 1067 (out_dir / "results.json" ).write_text ("{}" ,encoding = "utf-8" ) 1068 (out_dir / "README.md" ).write_text ("x" ,encoding = "utf-8" ) 1069with mock .patch ("strata_cli.cli._source" ,return_value = (Path ("p.json" ),None ,None , {})), \ 1070mock .patch ("strata_cli.cli._launch_plan" ,return_value = (plan , [])), \ 1071mock .patch .object (bs ,"start_engine" ,return_value = object ()), \ 1072mock .patch .object (bs ,"run" ,return_value = (fake_doc ,out_dir )), \ 1073mock .patch .object (bs ,"stop_engine" ,return_value = "process 9 is still running 30 s after it was told to stop" ), \ 1074mock .patch ("strata_cli.client.server_url" ,side_effect = lambda u :u ): 1075err = io .StringIO () 1076out = io .StringIO () 1077with contextlib .redirect_stderr (err ),contextlib .redirect_stdout (out ): 1078try : 1079code = main (["bench" ,"run" ,"--suite" ,"standard-v1" ,"--profile" ,"p.json" ,"--out" ,str (out_dir ),"--output" ,"json" ]) 1080except SystemExit as stop : 1081code = stop .code 1082self .assertEqual (code ,6 ) 1083self .assertIn ("could not be stopped" ,err .getvalue ()) 1084self .assertIn ("FAILED" ,err .getvalue ()) 1085self .assertTrue ((out_dir / "ENGINE-NOT-STOPPED.txt" ).is_file ()) 1086 1087def test_an_engine_that_exits_before_it_is_ready_is_an_error (self ): 1088class Dead : 1089pid = 1 1090 1091def poll (self ): 1092return 3 1093 1094def wait (self ,timeout = None ): 1095return 3 1096target = mock .Mock () 1097target .get .return_value = None 1098with tempfile .TemporaryDirectory ()as temp ,mock .patch ("subprocess.Popen" ,lambda * a ,** k :Dead ()): 1099with self .assertRaisesRegex (ProfileError ,"did not become ready" ): 1100bs .start_engine ("run.json" ,target ,Path (temp )/ "engine.log" ,lambda m :None ,5 ) 1101 1102 1103class RealServerTests (unittest .TestCase ): 1104"""The same request bodies against the real API server with its mock engine: every protocol setting is accepted.""" 1105 1106def test_the_real_server_accepts_the_protocol_requests (self ): 1107from serve .frontend import ChatTemplate 1108from serve .server import ByteTokenizer ,MockEngine ,Service ,serve 1109with tempfile .TemporaryDirectory ()as temp : 1110tok = ByteTokenizer () 1111template = ChatTemplate (Path (__file__ ).resolve ().parents [2 ]/ "serve/chat_template.jinja" ) 1112service = Service (MockEngine (tok ,"A hash table hashes the key." ,max_context = 400000 ),tok ,template ) 1113service .api_key = "inference-test-secret" 1114httpd = serve (service ,port = 0 ) 1115self .addCleanup (httpd .server_close ) 1116self .addCleanup (httpd .shutdown ) 1117target = bs .Target (f"http://127.0.0.1: { httpd . server_address [ 1 ] } " ,"inference-test-secret" ) 1118patches = [mock .patch .object (bench_facts ,"git_commit" ,return_value = COMMIT )] 1119for patch in patches : 1120patch .start () 1121self .addCleanup (patch .stop ) 1122doc ,out = bs .run (target ,Path (temp )/ "real" ,hash_model = True ) 1123self .assertEqual (bs .validate (doc ), []) 1124failed = [(r ["id" ],r ["error" ])for r in doc ["requests" ]if r ["status" ]== "failed" ] 1125self .assertEqual (failed , []) 1126self .assertTrue (all (r ["status" ]== "completed" for r in doc ["requests" ])) 1127self .assertEqual (doc ["configuration" ]["template" ]["sha256" ],bench_facts .sha256_text (template .source )) 1128self .assertIsNotNone (doc ["configuration" ]["context_tokens" ]) 1129# the mock engine has no clock: the rates stay null and say why instead of being estimated 1130record = next (r for r in doc ["requests" ]if r ["id" ]== "performance-short-r1" ) 1131self .assertIsNone (record ["metrics" ]["decode_tps" ]) 1132self .assertIsNotNone (record ["tokens" ]["input_tokens" ]) 1133self .assertIsNotNone (record ["timings" ]["ttft_s" ]) 1134self .assertEqual (doc ["run" ]["status" ],"nonconforming" )# no model file to hash, so the identity is incomplete 1135 1136 1137class RealRunFindingsTests (StandardBase ): 1138"""What the first run on release engines (RTX 3060, 2x RTX A4000, 0.1.46) got wrong.""" 1139 1140LVM = {"blockdevices" : [{"name" :"ubuntu--vg-data" ,"type" :"lvm" ,"rota" :False ,"model" :None ,"tran" :None ,"children" : [ 1141 {"name" :"nvme0n1p3" ,"type" :"part" ,"rota" :False ,"model" :None ,"tran" :"nvme" ,"children" : [ 1142 {"name" :"nvme0n1" ,"type" :"disk" ,"rota" :False ,"model" :"Lexar SSD NM620 512GB" ,"tran" :"nvme" }]}]}]} 1143 1144def test_the_drive_under_an_lvm_volume_is_found (self ): 1145self .assertEqual (bench_facts .lsblk_disk (self .LVM ), [{"kind" :"nvme" ,"model" :"Lexar SSD NM620 512GB" ,"bus" :"nvme" }]) 1146 1147def test_a_partition_on_a_disk_and_a_missing_disk (self ): 1148plain = {"blockdevices" : [{"name" :"sda1" ,"type" :"part" ,"children" : [ 1149 {"name" :"sda" ,"type" :"disk" ,"rota" :True ,"model" :"Spinner" ,"tran" :"sata" }]}]} 1150self .assertEqual (bench_facts .lsblk_disk (plain ), [{"kind" :"hdd" ,"model" :"Spinner" ,"bus" :"sata" }]) 1151self .assertIsNone (bench_facts .lsblk_disk ({"blockdevices" : [{"name" :"loop0" ,"type" :"loop" }]})) 1152 1153def test_the_runtime_is_the_one_the_engine_was_built_with (self ): 1154engine = self .root / "engine" 1155engine .mkdir () 1156exe = engine / "strata" 1157exe .write_bytes (b"" ) 1158self .assertIsNone (bench_facts .engine_build_runtime (str (exe ))) 1159 (engine / "engine-component.json" ).write_text (json .dumps ({"build_id" :"a7bdbfdabc9a+cuda12.9" }),encoding = "utf-8" ) 1160self .assertEqual (bench_facts .engine_build_runtime (str (exe )), {"name" :"cuda" ,"version" :"12.9" }) 1161 (engine / "engine-component.json" ).write_text (json .dumps ({"build_id" :"abc+hip6.4" }),encoding = "utf-8" ) 1162self .assertEqual (bench_facts .engine_build_runtime (str (exe )), {"name" :"rocm" ,"version" :"6.4" }) 1163why = bench_facts .Why () 1164block = bench_facts .software (why , {"driver" :"580.1" ,"cuda" :"13.0" },engine_version = "0.1.46" ,build_options = None , 1165engine_build = {"name" :"cuda" ,"version" :"12.9" }) 1166self .assertEqual (block ["runtime" ], [{"name" :"cuda" ,"version" :"12.9" }, {"name" :"cuda-driver-supports" ,"version" :"13.0" }]) 1167 1168def test_the_engine_log_comes_from_the_run_configs_log_file (self ): 1169console = self .root / "engine.log" 1170console .write_bytes (b"" ) 1171run_log = self .root / "strata-model.log" 1172run_log .write_bytes (b"old line from an earlier start\n" ) 1173offset = run_log .stat ().st_size 1174with run_log .open ("ab" )as stream : 1175stream .write (b"strata serve: expert cache 1500 slots\n" ) 1176kept = bs .engine_log_since (console ,run_log ,offset ) 1177self .assertEqual (kept .read_bytes (),b"strata serve: expert cache 1500 slots\n" ) 1178self .assertEqual (bs .engine_log_since (console ,None ,0 ),console ) 1179self .assertEqual (bs .engine_log_since (console ,self .root / "missing.log" ,0 ),console ) 1180self .assertEqual (bs .engine_log_since (console ,run_log ,run_log .stat ().st_size ),console ) 1181 1182def test_a_freshly_loaded_server_is_reported_as_fresh (self ): 1183doc ,out = self .run_standard () 1184doc ["extensions" ]["server_requests_before_run" ]= 0 1185self .assertIn ("freshly loaded engine" ,bs .report_markdown (doc )) 1186self .assertNotIn ("could not tell" ,bs .report_markdown (doc )) 1187doc ["extensions" ]["server_requests_before_run" ]= None 1188self .assertIn ("could not tell" ,bs .report_markdown (doc )) 1189doc ["extensions" ]["server_requests_before_run" ]= 3 1190self .assertIn ("answered 3 request(s)" ,bs .report_markdown (doc )) 1191 1192 1193class NvidiaBannerTests (unittest .TestCase ): 1194def test_the_cuda_version_is_read_from_old_and_new_driver_banners (self ): 1195query = "0, NVIDIA GeForce RTX 3060, 12288, 170.00, 615.71.09" 1196for banner ,version in (("| NVIDIA-SMI 580.1 Driver Version: 580.1 CUDA Version: 13.0 |" ,"13.0" ), 1197 ("| NVIDIA-SMI 615.71 KMD Version: 615.71.09 CUDA UMD Version: 13.4 |" ,"13.4" )): 1198def fake (cmd ,banner = banner ): 1199return query if any (a .startswith ("--query-gpu" )for a in cmd )else banner 1200with mock .patch .object (bench_facts ,"run_cmd" ,side_effect = fake ): 1201cards ,driver ,cuda = bench_facts .nvidia_gpus () 1202self .assertEqual ((driver ,cuda ), ("615.71.09" ,version )) 1203 1204 1205class ArchiveCommitTests (unittest .TestCase ): 1206"""The release archive carried no COMMIT file, so every run on it was nonconforming.""" 1207 1208ROOT = Path (__file__ ).resolve ().parents [2 ] 1209 1210def setUp (self ): 1211import sys 1212sys .path .insert (0 ,str (self .ROOT / "packaging" )) 1213import package_terminal 1214self .pt = package_terminal 1215 1216def test_an_explicit_commit_or_the_variable_wins_over_git (self ): 1217sha = "ab" * 20 1218self .assertEqual (self .pt .build_commit (sha .upper ()),sha ) 1219with mock .patch .dict (os .environ , {"STRATA_COMMIT" :"cd" * 20 }): 1220self .assertEqual (self .pt .build_commit (None ),"cd" * 20 ) 1221 1222def test_a_tree_copy_without_git_has_no_commit (self ): 1223with mock .patch .dict (os .environ , {},clear = False ),mock .patch .object (self .pt .subprocess ,"run" )as run : 1224os .environ .pop ("STRATA_COMMIT" ,None ) 1225run .return_value = mock .Mock (stdout = "fatal: not a git repository\n" ) 1226self .assertIsNone (self .pt .build_commit ("not a sha" )) 1227 1228def test_a_distributable_build_refuses_to_run_without_a_commit (self ): 1229with tempfile .TemporaryDirectory ()as out ,mock .patch .object (self .pt ,"build_commit" ,return_value = None ),mock .patch ("sys.argv" , ["package_terminal.py" ,"--out" ,out ]): 1230with self .assertRaises (SystemExit )as raised : 1231self .pt .main () 1232self .assertIn ("COMMIT" ,str (raised .exception )) 1233 1234 1235class RedactorKeyTests (unittest .TestCase ): 1236"""#4483: the API key is replaced as a whole word in its own case; "none" is no key.""" 1237 1238def test_none_is_not_a_key (self ): 1239for value in ("none" ,"None" ," NONE " ,"" ,None ," " ): 1240self .assertIsNone (bench_facts .usable_key (value ),value ) 1241self .assertEqual (bench_facts .usable_key (" sk-realkey " ),"sk-realkey" ) 1242clean = bench_facts .redactor ("none" ) 1243self .assertEqual (clean ("nonempty, none, None" ),"nonempty, none, None" ) 1244 1245def test_the_key_is_replaced_as_a_word_in_its_case (self ): 1246key = "a1b2c3d4" 1247clean = bench_facts .redactor (key ) 1248self .assertEqual (clean (f"token= { key } and { key } " ),"token=<key> and <key>" ) 1249self .assertEqual (clean (f"sha { key } ff and { key . upper () } " ),f"sha { key } ff and { key . upper () } " ) 1250self .assertEqual (clean ("Authorization: Bearer abcdefgh12345" ),"Authorization: Bearer <key>" ) 1251 1252def test_a_short_key_is_still_removed_where_it_stands_alone (self ): 1253self .assertEqual (bench_facts .redactor ("pw12" )("the password is pw12." ),"the password is <key>." ) 1254 1255 1256if __name__ == "__main__" : 1257unittest .main ()