okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf67d177
main
1"""Serving benchmark evidence with a live mock HTTP server, no model weights.""" 2 3import io 4import json 5import os 6import stat 7import subprocess 8import sys 9import tempfile 10import threading 11import time 12import unittest 13from concurrent .futures import ThreadPoolExecutor 14from contextlib import redirect_stdout 15from pathlib import Path 16from unittest import mock 17 18from serve .frontend import ChatTemplate 19from serve .server import ByteTokenizer ,IM_END ,MockEngine ,Service ,serve 20from strata_cli import bench 21from strata_cli .cli import main 22from strata_cli .client import Endpoint 23from strata_control import benchmarking ,journal ,management 24from strata_control .private_files import is_unshared 25from strata_control .profiles import ProfileError 26 27 28class _NoGpu : 29note = None 30 31def ok (self ): 32return False 33 34def name (self ): 35return None 36 37def read (self ): 38return {} 39 40 41class BenchTests (unittest .TestCase ): 42def setUp (self ): 43self .temp = tempfile .TemporaryDirectory () 44self .addCleanup (self .temp .cleanup ) 45self .root = Path (self .temp .name ) 46# The telemetry sampler reads the machine's real GPU on a timer; a card's first reading lands 47# between two benchmark runs and makes their reported environments differ. Use no GPU. 48patcher = mock .patch ("serve.telemetry.gpu_reader" ,lambda index = 0 ,amd = False :_NoGpu ()) 49patcher .start () 50self .addCleanup (patcher .stop ) 51tok = ByteTokenizer () 52service = Service (MockEngine (tok ,"Benchmark mock answer." ,max_context = 4096 ),tok , 53ChatTemplate (Path (__file__ ).resolve ().parents [2 ]/ "serve/chat_template.jinja" )) 54service .api_key = "inference-test-secret" 55service .telemetry_key = "monitor-test-secret" 56self .service = service 57self .httpd = serve (service ,port = 0 ) 58self .addCleanup (self .httpd .server_close ) 59self .addCleanup (self .httpd .shutdown ) 60self .url = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 61self .inference = Endpoint (self .url ,service .api_key ) 62self .telemetry = Endpoint (self .url ,service .telemetry_key ) 63 64def test_live_benchmark_writes_private_report_without_prompt_or_answer (self ): 65out = self .root / "smoke" 66with redirect_stdout (io .StringIO ()): 67report = bench .run (self .inference ,self .telemetry ,out ,concurrency = 2 ) 68self .assertTrue (report ["successful" ]) 69self .assertEqual ([p ["kind" ]for p in report ["phases" ]], ["warmup" ,"serial" ,"mixed" ]) 70self .assertEqual (report ["phases" ][2 ]["requested" ],2 ) 71self .assertEqual (report ["phases" ][2 ]["client_workers" ],2 ) 72self .assertEqual (report ["instance_id" ],report ["after" ]["instance_id" ]) 73self .assertTrue (all (r ["ttft_s" ]is not None and r ["completion_tokens" ]is not None 74for p in report ["phases" ]for r in p ["requests" ])) 75contents = (out / "results.json" ).read_text (encoding = "utf-8" ) 76for secret in ("inference-test-secret" ,"monitor-test-secret" ,"Benchmark mock answer." , 77"Answer in one sentence" ): 78self .assertNotIn (secret ,contents ) 79self .assertIn ("prompt_sha256" ,contents ) 80if os .name != "nt" : 81self .assertEqual (stat .S_IMODE (out .stat ().st_mode ),0o700 ) 82self .assertEqual (stat .S_IMODE ((out / "results.json" ).stat ().st_mode ),0o600 ) 83self .assertEqual (bench .summary (bench .load (out ))["successful" ],True ) 84self .assertEqual (self .telemetry .snapshot ()["work" ]["client_disconnect_cancels" ],0 ) 85 86def test_phase_progress_is_private_and_recovers_from_saved_report (self ): 87output = self .root / "progress" 88reached = threading .Event () 89release = threading .Event () 90original = bench ._phase 91 92def held_phase (* args ,** kwargs ): 93if kwargs ["kind" ]== "mixed" : 94reached .set () 95if not release .wait (10 ): 96raise AssertionError ("progress test did not release the mixed phase" ) 97return original (* args ,** kwargs ) 98 99with mock .patch .object (bench ,"_phase" ,side_effect = held_phase ), \ 100ThreadPoolExecutor (max_workers = 1 )as pool : 101future = pool .submit (bench .run ,self .inference ,self .telemetry ,output ,concurrency = 2 ) 102try : 103self .assertTrue (reached .wait (10 )) 104active = bench .progress (output ) 105self .assertEqual (active ["state" ],"running" ) 106self .assertEqual (active ["completed_phases" ],2 ) 107self .assertEqual (active ["current_phase" ],"mixed" ) 108finally : 109release .set () 110self .assertTrue (future .result (timeout = 10 )["successful" ]) 111saved = bench .progress (output / "results.json" ) 112self .assertEqual (saved ["state" ],"report_saved" ) 113self .assertEqual (saved ["completed_phases" ],3 ) 114self .assertTrue (saved ["successful" ]) 115raw = (output / "progress.json" ).read_text () 116self .assertNotIn ("inference-test-secret" ,raw ) 117self .assertNotIn ("Benchmark mock answer" ,raw ) 118if os .name == "posix" : 119self .assertEqual (stat .S_IMODE ((output / "progress.json" ).stat ().st_mode ),0o600 ) 120 121def test_saved_profile_benchmark_lease_refuses_overlap (self ): 122with mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" )}): 123output = self .root / "leased-run" 124self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"untracked" ) 125with benchmarking .benchmark_lease ("local" ,output ): 126self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"active" ) 127self .assertEqual (benchmarking .benchmark_activity ("local" ,self .root / "other-run" ), 128"other_active" ) 129raw = (self .root / "profiles" / ".bench-local.lock" ).read_bytes () 130self .assertNotIn (os .fsencode (str (output )),raw ) 131with self .assertRaisesRegex (ProfileError ,"another benchmark is running" ): 132with benchmarking .benchmark_lease ("local" ): 133self .fail ("overlapping benchmark lease was accepted" ) 134self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"ended" ) 135self .assertEqual (benchmarking .benchmark_activity ("local" ,self .root / "raw-run" ), 136"untracked" ) 137with benchmarking .benchmark_lease ("local" ): 138self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"untracked" ) 139 140def test_operator_cancel_stops_live_stream_and_saves_distinct_evidence (self ): 141output = self .root / "operator-stopped" 142self .service .engine .delay = 0.15 143with mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" )}), \ 144ThreadPoolExecutor (max_workers = 1 )as pool : 145def execute (): 146with benchmarking .benchmark_lease ("local" ,output ): 147return bench .run (self .inference ,self .telemetry ,output , 148concurrency = 2 ,request_timeout = 30 ) 149started = time .monotonic () 150future = pool .submit (execute ) 151deadline = started + 10 152while time .monotonic ()< deadline : 153if output .exists ()and self .telemetry .snapshot ()["work" ]["active" ]> 0 : 154break 155time .sleep (0.05 ) 156else : 157self .fail ("benchmark did not enter an active request" ) 158wrong = self .root / "another-run" 159wrong .mkdir (mode = 0o700 ) 160with self .assertRaisesRegex (ProfileError ,"exact benchmark run is not active" ): 161benchmarking .request_cancel ("local" ,wrong ) 162linked = self .root / "linked-run" 163linked .symlink_to (output ,target_is_directory = True ) 164with self .assertRaisesRegex (ProfileError ,"owner-only" ): 165benchmarking .request_cancel ("local" ,linked ) 166with mock .patch ("strata_control.profiles.load" ,return_value = ({"id" :"local" },"a" * 16 )): 167request = management .dispatch ({"schema_version" :1 ,"action" :"bench.cancel" , 168"profile" :"local" , 169"params" : {"path" :str (output / "results.json" )}}) 170self .assertEqual (request ["state" ],"cancel_requested" ) 171report = future .result (timeout = 10 ) 172self .assertLess (time .monotonic ()- started ,10 ) 173self .assertTrue (report ["cancelled" ]) 174self .assertFalse (report ["successful" ]) 175self .assertEqual (bench .progress (output )["state" ],"cancelled" ) 176self .assertTrue (benchmarking .cancel_requested (output )) 177self .assertTrue (bench .load (output )["cancelled" ]) 178self .assertIn ("| Result | Cancelled |" ,bench .markdown_report (report )) 179self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"ended" ) 180with self .assertRaisesRegex (ProfileError ,"not active" ): 181benchmarking .request_cancel ("local" ,output ) 182 183def test_progress_bridge_reports_exact_run_lease (self ): 184output = self .root / "bridge-progress" 185with redirect_stdout (io .StringIO ()): 186bench .run (self .inference ,self .telemetry ,output ,concurrency = 1 ) 187request = {"schema_version" :1 ,"action" :"bench.progress" ,"profile" :"local" , 188"params" : {"path" :str (output / "results.json" )}} 189with mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" )}), \ 190mock .patch ("strata_control.profiles.load" ,return_value = ({"id" :"local" },"a" * 16 )): 191with benchmarking .benchmark_lease ("local" ,output ): 192active = management .dispatch (request ) 193self .assertEqual (active ["activity" ],"active" ) 194self .assertEqual (active ["progress" ]["state" ],"report_saved" ) 195self .assertEqual (management .dispatch (request )["activity" ],"ended" ) 196 197def test_durable_benchmark_job_receipt_survives_host_state_loss (self ): 198output = self .root / "durable-job" 199instance = self .telemetry .snapshot ()["instance" ]["id" ] 200revision ,source = "a" * 16 ,"b" * 64 201job_id = "c" * 32 202params = {"path" :str (output ),"suite" :"serving-smoke" ,"concurrency" :2 , 203"repeat" :1 ,"request_timeout" :30 ,"condition" :"baseline" , 204"if_profile_revision" :revision ,"if_source_sha256" :source , 205"if_owner_id" :"d" * 32 ,"if_instance_id" :instance } 206identity = {"profile" :"local" ,"revision" :revision ,"source_sha256" :source } 207settings = (None ,identity ,self .inference ,self .telemetry ,output ) 208planned = {"profile_revision" :revision ,"source_sha256" :source , 209"owner_id" :"d" * 32 ,"instance_id" :instance } 210 (self .root / "profiles" ).mkdir (mode = 0o700 ) 211with mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" )}), \ 212mock .patch ("strata_control.profiles.load" ,return_value = ({"id" :"local" },revision )), \ 213mock .patch .object (benchmarking ,"_settings" ,return_value = settings ), \ 214mock .patch .object (benchmarking ,"plan" ,return_value = planned ), \ 215mock .patch .object (bench ,"_managed_match" ,return_value = {"matched" :True , 216"instance_id" :instance }): 217created = management .dispatch ({"schema_version" :1 ,"action" :"bench.job.create" , 218"profile" :"local" ,"params" : {** params ,"job_id" :job_id }}) 219self .assertEqual (created ["job_id" ],job_id ) 220self .assertEqual (benchmarking .job_status ("local" ,job_id )["job" ]["state" ], 221"launching" ) 222real_run = bench .run 223 224def report_before_worker_receipt (* args ,** kwargs ): 225report = real_run (* args ,** kwargs ) 226self .assertEqual (benchmarking .job_status ("local" ,job_id )["job" ]["state" ], 227"completed" ) 228return report 229 230with mock .patch .object (bench ,"run" ,side_effect = report_before_worker_receipt ), \ 231redirect_stdout (io .StringIO ()): 232result = management .dispatch ({"schema_version" :1 ,"action" :"bench.run" , 233"profile" :"local" ,"params" : {** params ,"job_id" :job_id }}) 234self .assertTrue (result ["successful" ]) 235recovered = management .dispatch ({"schema_version" :1 ,"action" :"bench.job" , 236"profile" :"local" ,"params" : {"job_id" :job_id }})["job" ] 237self .assertEqual (recovered ["state" ],"completed" ) 238self .assertTrue (recovered ["result" ]["successful" ]) 239self .assertEqual (recovered ["result" ]["run_id" ],bench .load (output )["run_id" ]) 240self .assertEqual (recovered ["progress" ]["state" ],"report_saved" ) 241self .assertEqual (journal .load ("local" ,job_id )["state" ],"succeeded" ) 242receipt = self .root / "profiles" / ".ops" / "local" / ".runs" / f" { job_id } .json" 243if os .name == "nt" : 244self .assertTrue (is_unshared (receipt ))# NTFS has no mode bits: assert the effective ACL 245else : 246self .assertEqual (stat .S_IMODE (receipt .stat ().st_mode ),0o600 ) 247 248failed_path = self .root / "failed-job" 249failed_params = {** params ,"path" :str (failed_path )} 250failed_id = "e" * 32 251management .dispatch ({"schema_version" :1 ,"action" :"bench.job.create" , 252"profile" :"local" ,"params" : {** failed_params ,"job_id" :failed_id }}) 253with mock .patch .object (benchmarking ,"plan" ,side_effect = ProfileError ("stale benchmark" ,6 )): 254with self .assertRaisesRegex (ProfileError ,"stale benchmark" ): 255management .dispatch ({"schema_version" :1 ,"action" :"bench.run" , 256"profile" :"local" ,"params" : {** failed_params ,"job_id" :failed_id }}) 257self .assertEqual (benchmarking .job_status ("local" ,failed_id )["job" ]["state" ],"failed" ) 258 259recovered_path = self .root / "report-before-receipt" 260recovered_params = {** params ,"path" :str (recovered_path )} 261recovered_id = "f" * 32 262management .dispatch ({"schema_version" :1 ,"action" :"bench.job.create" , 263"profile" :"local" ,"params" : {** recovered_params ,"job_id" :recovered_id }}) 264with redirect_stdout (io .StringIO ()): 265bench .run (self .inference ,self .telemetry ,recovered_path ,concurrency = 2 , 266request_timeout = 30 ,condition = "baseline" ,profile_identity = identity , 267require_managed_match = True ) 268self .assertEqual (journal .load ("local" ,recovered_id )["state" ],"running" ) 269self .assertEqual (benchmarking .job_status ("local" ,recovered_id )["job" ]["state" ], 270"completed" ) 271self .assertEqual (journal .load ("local" ,recovered_id )["state" ],"succeeded" ) 272 273def test_process_death_releases_exact_run_lease (self ): 274output = self .root / "child-run" 275ready = self .root / "child-ready" 276environment = {** os .environ ,"STRATA_PROFILE_DIR" :str (self .root / "profiles" )} 277code = ("from pathlib import Path\n" 278"from strata_control.benchmarking import benchmark_lease\n" 279"from time import sleep\n" 280f"with benchmark_lease('local', Path( { str ( output )!r } )):\n" 281f" Path( { str ( ready )!r } ).write_text('ready')\n" 282" sleep(30)\n" ) 283process = subprocess .Popen ([sys .executable ,"-c" ,code ], 284cwd = Path (__file__ ).resolve ().parents [2 ],env = environment , 285stdout = subprocess .DEVNULL ,stderr = subprocess .PIPE ) 286try : 287deadline = time .monotonic ()+ 10 288while not ready .exists ()and process .poll ()is None and time .monotonic ()< deadline : 289time .sleep (0.05 ) 290if not ready .exists (): 291self .fail ("benchmark lease child did not become ready: " + 292 (process .stderr .read ().decode ("utf-8" ,"replace" )if process .poll ()is not None else 293"timed out" )) 294with mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :environment ["STRATA_PROFILE_DIR" ]}): 295self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"active" ) 296if os .name == "nt" : 297# a venv's python.exe is a launcher that runs the real interpreter as its child 298subprocess .run (["taskkill" ,"/F" ,"/T" ,"/PID" ,str (process .pid )],capture_output = True ) 299else : 300process .kill () 301process .wait (timeout = 5 ) 302self .assertEqual (benchmarking .benchmark_activity ("local" ,output ),"ended" ) 303finally : 304if process .poll ()is None : 305process .kill () 306process .wait (timeout = 5 ) 307process .stderr .close () 308 309def test_interrupted_phase_cannot_produce_successful_report (self ): 310output = self .root / "interrupted" 311original = bench ._phase 312 313def interrupted_phase (* args ,** kwargs ): 314if kwargs ["kind" ]== "serial" : 315raise RuntimeError ("synthetic benchmark interruption" ) 316return original (* args ,** kwargs ) 317 318with mock .patch .object (bench ,"_phase" ,side_effect = interrupted_phase ), \ 319redirect_stdout (io .StringIO ()): 320with self .assertRaisesRegex (RuntimeError ,"synthetic benchmark interruption" ): 321bench .run (self .inference ,self .telemetry ,output ,concurrency = 2 ) 322report = bench .load (output ) 323self .assertEqual ([p ["kind" ]for p in report ["phases" ]], ["warmup" ]) 324self .assertEqual (report ["planned_phases" ], ["warmup" ,"serial" ,"mixed" ]) 325self .assertFalse (report ["successful" ]) 326self .assertEqual (bench .summary (report )["completed_phase_count" ],1 ) 327self .assertEqual (bench .summary (report )["planned_phase_count" ],3 ) 328self .assertIn ("| Result | Incomplete |" ,bench .markdown_report (report )) 329record = bench .progress (output ) 330self .assertEqual (record ["state" ],"report_saved" ) 331self .assertEqual (record ["completed_phases" ],1 ) 332self .assertEqual (record ["current_phase" ],None ) 333self .assertFalse (record ["successful" ]) 334report ["successful" ]= True 335 (output / "results.json" ).write_text (json .dumps (report ),encoding = "utf-8" ) 336with self .assertRaisesRegex (ProfileError ,"unsupported benchmark report" ): 337bench .load (output ) 338del report ["planned_phases" ]# Old reports must not claim success for a partial suite either. 339 (output / "results.json" ).write_text (json .dumps (report ),encoding = "utf-8" ) 340with self .assertRaisesRegex (ProfileError ,"unsupported benchmark report" ): 341bench .load (output ) 342 343def test_postflight_telemetry_parse_failure_keeps_failed_evidence (self ): 344output = self .root / "postflight" 345original = bench ._phase 346postflight = False 347 348def phase (* args ,** kwargs ): 349nonlocal postflight 350result = original (* args ,** kwargs ) 351if kwargs ["kind" ]== "mixed" : 352postflight = True 353return result 354 355def snapshot (): 356if postflight : 357raise ValueError ("malformed postflight telemetry" ) 358return self .telemetry .snapshot () 359 360telemetry = mock .Mock (timeout = self .telemetry .timeout ) 361telemetry .snapshot .side_effect = snapshot 362with mock .patch .object (bench ,"_phase" ,side_effect = phase ),redirect_stdout (io .StringIO ()): 363report = bench .run (self .inference ,telemetry ,output ,concurrency = 2 ) 364self .assertFalse (report ["successful" ]) 365self .assertEqual (len (report ["phases" ]),3 ) 366self .assertEqual (report ["after" ]["instance_id" ],None ) 367self .assertFalse (bench .load (output )["successful" ]) 368self .assertEqual (bench .progress (output )["state" ],"report_saved" ) 369 370def test_auth_failure_is_recorded_and_does_not_claim_success (self ): 371out = self .root / "failed" 372with redirect_stdout (io .StringIO ()): 373report = bench .run (Endpoint (self .url ,"wrong-key" ),self .telemetry ,out ,concurrency = 2 ) 374self .assertFalse (report ["successful" ]) 375self .assertTrue ((out / "results.json" ).exists ()) 376self .assertTrue (all (r ["error_code" ]== "authentication_failed" 377for p in report ["phases" ]for r in p ["requests" ])) 378 379def test_unloaded_model_is_rejected_before_creating_output (self ): 380out = self .root / "unloaded" 381unloaded = mock .Mock () 382unloaded .snapshot .return_value = {"instance" : {"id" :"one" },"model" : {"loaded" :False }} 383with self .assertRaisesRegex (ProfileError ,"loaded Strata instance" ): 384bench .run (self .inference ,unloaded ,out ) 385self .assertFalse (out .exists ()) 386 387def test_invalid_condition_is_rejected_before_creating_output (self ): 388out = self .root / "invalid-label" 389with self .assertRaisesRegex (ProfileError ,"condition must be a lowercase name" ): 390bench .run (self .inference ,self .telemetry ,out ,condition = "monitor\x1b[31m" ) 391self .assertFalse (out .exists ()) 392 393def test_run_cli_records_an_operator_condition (self ): 394out = self .root / "cli-baseline" 395output = io .StringIO () 396with mock .patch .dict (os .environ , {"STRATA_API_KEY" :self .service .api_key }),redirect_stdout (output ): 397code = main (["bench" ,"run" ,"--suite" ,"serving-smoke" ,"--url" ,self .url ,"--condition" ,"baseline" , 398"--concurrency" ,"1" ,"--out" ,str (out ),"--output" ,"json" ]) 399self .assertEqual (code ,0 ) 400self .assertEqual (json .loads (output .getvalue ())["summary" ]["condition" ],"baseline" ) 401report = bench .load (out ) 402self .assertEqual (report ["condition" ],"baseline" ) 403self .assertTrue (any ("monitor attachment is not verified" in note for note in report ["limitations" ])) 404 405def test_managed_benchmark_checks_owned_instance_before_and_after (self ): 406identity = {"profile" :"local" ,"revision" :"a" * 16 , 407"source_sha256" :"b" * 64 } 408instance = self .telemetry .snapshot ()["instance" ]["id" ] 409owner = {"ok" :True ,"state" :"ready" ,"launch_attested" :True , 410"api_identity_verified" :True ,"generation_ready" :True , 411"instance_id" :instance ,"profile_revision" :identity ["revision" ],"api_url" :self .url } 412plan = {"ok" :True ,"changed" :False ,"current_instance_id" :instance , 413"current_profile_revision" :identity ["revision" ], 414"candidate_profile_revision" :identity ["revision" ]} 415out = self .root / "managed" 416with mock .patch ("strata_control.runtime.status" ,return_value = owner )as status , \ 417mock .patch ("strata_control.runtime.plan_restart" ,return_value = plan )as preview , \ 418redirect_stdout (io .StringIO ()): 419report = bench .run (self .inference ,self .telemetry ,out ,concurrency = 1 , 420profile_identity = identity ,require_managed_match = True ) 421self .assertTrue (report ["successful" ]) 422self .assertEqual (report ["profile_running_match" ],"managed_launch_checked" ) 423self .assertTrue (report ["profile_running_check" ]["before" ]["matched" ]) 424self .assertTrue (report ["profile_running_check" ]["after" ]["matched" ]) 425self .assertEqual (bench .summary (report )["profile_running_match" ],"managed_launch_checked" ) 426self .assertEqual (status .call_count ,2 ) 427self .assertEqual (preview .call_count ,2 ) 428 429with mock .patch ("strata_control.runtime.status" ,return_value = {** owner ,"instance_id" :"wrong" }), \ 430mock .patch ("strata_control.runtime.plan_restart" ,return_value = plan ): 431rejected = self .root / "rejected" 432with self .assertRaisesRegex (ProfileError ,"managed benchmark preflight failed: instance_mismatch" ): 433bench .run (self .inference ,self .telemetry ,rejected ,concurrency = 1 , 434profile_identity = identity ,require_managed_match = True ) 435self .assertFalse (rejected .exists ()) 436 437with mock .patch ("strata_control.runtime.status" ,return_value = owner ), \ 438mock .patch ("strata_control.runtime.plan_restart" ,return_value = {** plan ,"changed" :True }): 439stale = self .root / "stale" 440with self .assertRaisesRegex (ProfileError ,"managed benchmark preflight failed: profile_or_source_changed" ): 441bench .run (self .inference ,self .telemetry ,stale ,concurrency = 1 , 442profile_identity = identity ,require_managed_match = True ) 443self .assertFalse (stale .exists ()) 444 445with mock .patch ("strata_control.runtime.status" ,side_effect = [owner , {** owner ,"instance_id" :"wrong" }]), \ 446mock .patch ("strata_control.runtime.plan_restart" ,return_value = plan ), \ 447redirect_stdout (io .StringIO ()): 448changed = bench .run (self .inference ,self .telemetry ,self .root / "changed" ,concurrency = 1 , 449profile_identity = identity ,require_managed_match = True ) 450self .assertFalse (changed ["successful" ]) 451self .assertEqual (changed ["profile_running_check" ]["after" ]["reason" ],"instance_mismatch" ) 452self .assertTrue ((self .root / "changed" / "results.json" ).is_file ()) 453 454def test_managed_match_flag_requires_a_saved_profile (self ): 455output = io .StringIO () 456with redirect_stdout (output ): 457code = main (["bench" ,"run" ,"--suite" ,"serving-smoke" ,"--url" ,self .url ,"--require-managed-match" , 458"--out" ,str (self .root / "unused" ),"--output" ,"json" ]) 459self .assertEqual (code ,2 ) 460self .assertFalse (json .loads (output .getvalue ())["ok" ]) 461self .assertFalse ((self .root / "unused" ).exists ()) 462 463def test_desktop_review_runs_shared_benchmark_and_rejects_changed_owner (self ): 464source = self .root / "run.json" 465source .write_text ("{}" ,encoding = "utf-8" ) 466instance = self .telemetry .snapshot ()["instance" ]["id" ] 467revision = "a" * 16 468owner_id = ["b" * 32 ] 469owner = {"ok" :True ,"state" :"ready" ,"launch_attested" :True , 470"api_identity_verified" :True ,"generation_ready" :True , 471"instance_id" :instance ,"profile_revision" :revision ,"api_url" :self .url } 472restart = {"ok" :True ,"changed" :False ,"current_instance_id" :instance , 473"current_profile_revision" :revision ,"candidate_profile_revision" :revision } 474launch = {"effective" : {"host" :"127.0.0.1" ,"port" :self .httpd .server_address [1 ]}} 475settings = {"path" :str (self .root / "desktop-run" ),"suite" :"serving-smoke" , 476"concurrency" :2 ,"repeat" :1 ,"request_timeout" :120 , 477"condition" :"baseline" } 478def send (action ,params ): 479return management .dispatch ({"schema_version" :1 ,"action" :action , 480"profile" :"local" ,"params" :params }) 481with mock .patch ("strata_control.benchmarking._source" ,return_value = ( 482source , {"id" :"local" },revision , {"model_name" :"test" ,"gpu" :"cpu" })), \ 483mock .patch ("strata_control.benchmarking._launch_plan" ,return_value = (launch , [])), \ 484mock .patch ("strata_control.runtime.status" ,side_effect = lambda _ : { 485** owner ,"owner_id" :owner_id [0 ]}), \ 486mock .patch ("strata_control.runtime.plan_restart" ,return_value = restart ), \ 487mock .patch .dict (os .environ , {"STRATA_API_KEY" :self .service .api_key , 488"STRATA_TELEMETRY_KEY" :self .service .telemetry_key }): 489reviewed = send ("bench.run.plan" ,settings )["plan" ] 490self .assertEqual (reviewed ["planned_requests" ],5 ) 491self .assertEqual (reviewed ["instance_id" ],instance ) 492pinned = {"if_profile_revision" :reviewed ["profile_revision" ], 493"if_source_sha256" :reviewed ["source_sha256" ], 494"if_owner_id" :reviewed ["owner_id" ], 495"if_instance_id" :reviewed ["instance_id" ]} 496owner_id [0 ]= "c" * 32 497with self .assertRaisesRegex (ProfileError ,"target changed after review" ): 498send ("bench.run" , {** settings ,** pinned }) 499self .assertFalse (Path (settings ["path" ]).exists ()) 500owner_id [0 ]= "b" * 32 501with redirect_stdout (io .StringIO ()): 502result = send ("bench.run" , {** settings ,** pinned }) 503self .assertTrue (result ["successful" ]) 504self .assertTrue (Path (result ["path" ]).is_file ()) 505self .assertEqual (bench .load (Path (settings ["path" ]))["profile_running_match" ], 506"managed_launch_checked" ) 507 508def test_report_cli_json_and_malformed_report (self ): 509out = self .root / "smoke" 510with redirect_stdout (io .StringIO ()): 511bench .run (self .inference ,self .telemetry ,out ,concurrency = 1 ) 512stdout = io .StringIO () 513with redirect_stdout (stdout ): 514self .assertEqual (main (["bench" ,"report" ,str (out ),"--output" ,"json" ]),0 ) 515value = json .loads (stdout .getvalue ()) 516self .assertTrue (value ["ok" ]) 517self .assertEqual (value ["summary" ]["suite" ],"serving-smoke" ) 518report_file = out / "results.json" 519data = json .loads (report_file .read_text ()) 520for phase in data ["phases" ]: 521phase .pop ("passed" )# reports written before the overload suite remain readable 522report_file .write_text (json .dumps (data ),encoding = "utf-8" ) 523self .assertTrue (all (phase ["passed" ]for phase in bench .summary (bench .load (out ))["phases" ])) 524data ["phases" ]= [{"kind" :"mixed" }] 525report_file .write_text (json .dumps (data ),encoding = "utf-8" ) 526with self .assertRaisesRegex (ProfileError ,"unsupported benchmark report" ): 527bench .load (out ) 528 529def test_markdown_export_is_local_private_and_keeps_measurement_limits (self ): 530first = self .root / "baseline" 531second = self .root / "candidate" 532with redirect_stdout (io .StringIO ()): 533report = bench .run (self .inference ,self .telemetry ,first ,concurrency = 1 ) 534report ["model_id" ]= "model | <untrusted>" 535 (first / "results.json" ).write_text (json .dumps (report ),encoding = "utf-8" ) 536other = json .loads (json .dumps (report )) 537other ["run_id" ]= "f" * 32 538second .mkdir () 539 (second / "results.json" ).write_text (json .dumps (other ),encoding = "utf-8" ) 540share = self .root / "share.md" 541with mock .patch .object (Endpoint ,"snapshot" ,side_effect = AssertionError ("export must stay offline" )): 542with redirect_stdout (io .StringIO ()): 543self .assertEqual (main (["bench" ,"report" ,str (first ),"--output" ,"markdown" , 544"--out" ,str (share )]),0 ) 545comparison = io .StringIO () 546with redirect_stdout (comparison ): 547self .assertEqual (main (["bench" ,"compare" ,str (first ),str (second ), 548"--output" ,"markdown" ]),0 ) 549exported = share .read_text (encoding = "utf-8" ) 550self .assertIn ("model \\| \\<untrusted\\>" ,exported ) 551self .assertIn ("Peak slots" ,exported ) 552self .assertIn ("Missing readings appear as `unavailable`" ,exported ) 553self .assertNotIn (self .url ,exported ) 554for secret in ("inference-test-secret" ,"monitor-test-secret" ,"Benchmark mock answer." , 555"Answer in one sentence" ): 556self .assertNotIn (secret ,exported ) 557self .assertNotIn (secret ,comparison .getvalue ()) 558self .assertIn ("Provisional comparison" ,comparison .getvalue ()) 559self .assertIn ("monitor attachment" ,comparison .getvalue ()) 560original = share .read_bytes () 561with redirect_stdout (io .StringIO ()): 562self .assertEqual (main (["bench" ,"report" ,str (first ),"--output" ,"markdown" , 563"--out" ,str (share )]),2 ) 564self .assertEqual (share .read_bytes (),original ) 565if os .name != "nt" : 566self .assertEqual (stat .S_IMODE (share .stat ().st_mode ),0o600 ) 567 568def test_saved_run_comparison_is_read_only_and_provisional (self ): 569baseline_path ,candidate_path = self .root / "baseline" ,self .root / "monitored" 570with redirect_stdout (io .StringIO ()): 571baseline = bench .run (self .inference ,self .telemetry ,baseline_path ,concurrency = 2 ,repeat = 3 , 572condition = "baseline" ) 573candidate = bench .run (self .inference ,self .telemetry ,candidate_path ,concurrency = 2 ,repeat = 3 , 574condition = "monitor-default" ) 575self .assertTrue (baseline ["successful" ]and candidate ["successful" ]) 576before = [(path / "results.json" ).read_bytes ()for path in (baseline_path ,candidate_path )] 577with mock .patch .object (Endpoint ,"snapshot" ,side_effect = AssertionError ("compare must not contact server" )): 578output = io .StringIO () 579with redirect_stdout (output ): 580code = main (["bench" ,"compare" ,str (baseline_path ),str (candidate_path ), 581"--output" ,"json" ]) 582self .assertEqual (code ,0 ) 583comparison = json .loads (output .getvalue ())["comparison" ] 584self .assertEqual (comparison ["qualification" ],"provisional" ) 585self .assertTrue (comparison ["workload_match" ]) 586self .assertEqual (comparison ["primary_phases" ],3 ) 587self .assertIsNotNone (comparison ["median_primary_metrics" ]["p95_ttft_s" ]["baseline" ]) 588self .assertEqual (comparison ["baseline" ]["condition" ],"baseline" ) 589self .assertEqual (comparison ["candidate" ]["condition" ],"monitor-default" ) 590self .assertTrue (any ("monitor attachment" in note for note in comparison ["warnings" ])) 591self .assertEqual (before , [(path / "results.json" ).read_bytes () 592for path in (baseline_path ,candidate_path )]) 593self .assertIn ("provisional comparison" ,bench .format_comparison (comparison )) 594missing = json .loads (json .dumps (candidate )) 595next (phase for phase in missing ["phases" ]if phase ["kind" ]== "mixed" )["summary" ]["p95_ttft_s" ]= None 596self .assertIsNone (bench .compare (baseline ,missing )["median_primary_metrics" ]["p95_ttft_s" ]["candidate" ]) 597next (phase for phase in missing ["phases" ]if phase ["kind" ]== "mixed" )["summary" ]["p95_ttft_s" ]= 10 ** 400 598self .assertIsNone (bench .compare (baseline ,missing )["median_primary_metrics" ]["p95_ttft_s" ]["candidate" ]) 599 600def test_comparison_rejects_workload_and_identity_mismatch (self ): 601first_path ,second_path = self .root / "one" ,self .root / "two" 602with redirect_stdout (io .StringIO ()): 603first = bench .run (self .inference ,self .telemetry ,first_path ,concurrency = 1 ) 604second = bench .run (self .inference ,self .telemetry ,second_path ,concurrency = 2 ) 605with self .assertRaisesRegex (ProfileError ,"workload or concurrency differs" ): 606bench .compare (first ,second ) 607second ["phases" ][2 ]["requested" ]= first ["phases" ][2 ]["requested" ] 608second ["phases" ][2 ]["client_workers" ]= first ["phases" ][2 ]["client_workers" ] 609second ["phases" ][2 ]["requests" ]= first ["phases" ][2 ]["requests" ] 610second ["environment" ]["slots_effective" ]= 999 611with self .assertRaisesRegex (ProfileError ,"reported environment differs: slots_effective" ): 612bench .compare (first ,second ) 613second ["environment" ]["slots_effective" ]= first ["environment" ]["slots_effective" ] 614first ["profile_identity" ]= {"source_sha256" :"0" * 64 } 615second ["profile_identity" ]= {"source_sha256" :"1" * 64 } 616with self .assertRaisesRegex (ProfileError ,"source config digests differ" ): 617bench .compare (first ,second ) 618 619def test_overload_suite_requires_bounded_admission_before_creating_output (self ): 620out = self .root / "overload" 621with self .assertRaisesRegex (ProfileError ,"max_queue and queue_timeout" ): 622bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-overload-v1" ,concurrency = 4 ) 623self .assertFalse (out .exists ()) 624self .service .max_queue = 1 625self .service .queue_timeout_s = 0.1 626with self .assertRaisesRegex (ProfileError ,"must exceed the admission limit" ): 627bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-overload-v1" ,concurrency = 2 ) 628self .assertFalse (out .exists ()) 629 630def test_cancel_suite_requires_queue_capacity_and_disconnect_telemetry (self ): 631out = self .root / "cancel" 632with self .assertRaisesRegex (ProfileError ,"cancellation suite requires" ): 633bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-cancel-v1" ,concurrency = 1 ) 634self .assertFalse (out .exists ()) 635self .service .max_queue = 1 636self .service .queue_timeout_s = 0.1 637with self .assertRaisesRegex (ProfileError ,"queue_timeout >= 2" ): 638bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-cancel-v1" ,concurrency = 1 ) 639self .assertFalse (out .exists ()) 640 641def test_prefill_cancel_requires_parallel_engine (self ): 642out = self .root / "prefill" 643with self .assertRaisesRegex (ProfileError ,"at least two effective slots" ): 644bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-prefill-cancel-v1" ,concurrency = 2 ) 645self .assertFalse (out .exists ()) 646 647def test_overload_suite_records_rejections_and_recovery_without_content (self ): 648self .service .max_queue = 1 649self .service .queue_timeout_s = 0.1 650self .service .engine .delay = 0.02 651out = self .root / "overload" 652with redirect_stdout (io .StringIO ()): 653report = bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-overload-v1" , 654concurrency = 6 ) 655self .assertTrue (report ["successful" ]) 656self .assertEqual ([phase ["kind" ]for phase in report ["phases" ]], ["warmup" ,"overload" ,"recovery" ]) 657overload = report ["phases" ][1 ] 658self .assertTrue (overload ["passed" ]) 659self .assertEqual (overload ["requested" ],6 ) 660self .assertGreaterEqual (overload ["summary" ]["expected_overload" ],1 ) 661self .assertEqual (overload ["summary" ]["expected_overload" ], 662overload ["summary" ]["admission_full" ]+ overload ["summary" ]["queue_wait_timeout" ]) 663self .assertEqual (overload ["summary" ]["failed" ],0 ) 664self .assertIsNotNone (overload ["summary" ]["launch_spread_s" ]) 665self .assertEqual (len ([row ["launch_offset_s" ]for row in overload ["requests" ]]),6 ) 666self .assertTrue (all (row ["error_code" ]in (None ,"admission_full" ,"queue_wait_timeout" ) 667for row in overload ["requests" ])) 668self .assertTrue (report ["phases" ][2 ]["passed" ]) 669data = (out / "results.json" ).read_text (encoding = "utf-8" ) 670for secret in ("inference-test-secret" ,"monitor-test-secret" ,"Benchmark mock answer." , 671"Answer in one sentence" ): 672self .assertNotIn (secret ,data ) 673loaded = bench .load (out ) 674self .assertEqual (bench .summary (loaded )["phases" ][1 ]["expected_overload" ], 675overload ["summary" ]["expected_overload" ]) 676comparison_shape = json .loads (json .dumps (loaded )) 677comparison_shape ["run_id" ]= "f" * 32 678same = bench .compare (loaded ,comparison_shape ) 679self .assertEqual (same ["primary_kind" ],"overload" ) 680self .assertIn ("admission full" ,bench .format_comparison (same )) 681human = bench .format_summary (bench .summary (loaded )) 682self .assertIn ("rejected" ,human ) 683self .assertIn ("timed out" ,human ) 684self .assertIn ("launch spread" ,human ) 685self .assertNotIn ("Benchmark mock answer" ,human ) 686 687def test_cancel_suite_observes_active_and_queued_disconnect_and_recovery (self ): 688self .service .max_queue = 1 689self .service .queue_timeout_s = 5 690engine = self .service .engine 691engine .script = engine .tok .encode ("A" * 200 ,parse_special = True )+ \ 692engine .tok .encode (IM_END ,parse_special = True ) 693engine .delay = 0.01 694out = self .root / "cancel" 695with redirect_stdout (io .StringIO ()): 696report = bench .run (self .inference ,self .telemetry ,out ,suite = "parallel-cancel-v1" , 697concurrency = 1 ,request_timeout = 10 ) 698self .assertTrue (report ["successful" ],bench .format_summary (bench .summary (report ))) 699self .assertEqual ([phase ["kind" ]for phase in report ["phases" ]], 700 ["warmup" ,"cancel_active" ,"cancel_queued" ,"recovery" ]) 701for phase in report ["phases" ][1 :3 ]: 702self .assertTrue (phase ["passed" ]) 703self .assertEqual (phase ["summary" ]["client_disconnect_delta" ],1 ) 704self .assertTrue (phase ["summary" ]["settled" ]) 705self .assertEqual (phase ["summary" ]["queue_timeouts_delta" ],0 ) 706self .assertEqual (report ["phases" ][2 ]["summary" ]["companion_successful" ],1 ) 707data = (out / "results.json" ).read_text () 708self .assertNotIn ("A" * 50 ,data ) 709self .assertTrue (bench .load (out )["successful" ]) 710comparison_shape = json .loads (json .dumps (report )) 711comparison_shape ["run_id" ]= "f" * 32 712comparison = bench .compare (report ,comparison_shape ) 713self .assertTrue (comparison ["workload_match" ]) 714self .assertEqual (comparison ["primary_kind" ],"cancel_active" ) 715self .assertEqual (comparison ["phases" ][1 ]["metrics" ]["client_disconnect_delta" ]["baseline" ],1.0 ) 716self .assertIn ("disconnects" ,bench .format_comparison (comparison )) 717corrupt = json .loads (data ) 718corrupt ["phases" ][1 ]["summary" ].pop ("client_disconnect_delta" ) 719 (out / "results.json" ).write_text (json .dumps (corrupt )) 720with self .assertRaisesRegex (ProfileError ,"unsupported benchmark report" ): 721bench .load (out ) 722 723 724if __name__ == "__main__" : 725unittest .main ()