okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
049ae1c67
main
1"""Calibration report binding, review and atomic apply without a GPU.""" 2 3import io 4import json 5import os 6import stat 7import subprocess 8import sys 9import tempfile 10import threading 11import unittest 12import uuid 13from contextlib import redirect_stdout 14from pathlib import Path 15from types import SimpleNamespace 16from unittest import mock 17 18from strata_cli .cli import main 19from strata_control import calibration ,journal ,management ,profiles ,runtime 20import setup 21 22 23class CalibrationFlowTests (unittest .TestCase ): 24def test_mac_ram_identity_is_available_without_proc_meminfo (self ): 25with mock .patch .object (setup ,"WIN" ,False ), \ 26mock .patch .object (setup .sys ,"platform" ,"darwin" ), \ 27mock .patch .object (setup .subprocess ,"run" , 28return_value = SimpleNamespace (stdout = "17179869184\n" )): 29self .assertEqual (setup .ram_gb (),16.0 ) 30 31def setUp (self ): 32self .temp = tempfile .TemporaryDirectory () 33self .addCleanup (self .temp .cleanup ) 34self .root = Path (self .temp .name ) 35patcher = mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" ), 36"STRATA_RUNTIME_DIR" :str (self .root / "runtime" ), 37"XDG_CONFIG_HOME" :str (self .root / "settings" ), 38"APPDATA" :str (self .root / "settings" ), 39"STRATA_API_KEY" :"" }) 40patcher .start () 41self .addCleanup (patcher .stop ) 42# setup's own answer: <XDG_CONFIG_HOME>/strata/settings.json, or %APPDATA%/Strata/settings.json on Windows 43self .settings_file = setup .settings_path () 44self .assertTrue (str (self .settings_file ).startswith (str (self .root )),"settings must stay in the temp tree" ) 45engine = self .root / "strata-engine" 46engine .write_bytes (b"fake engine" ) 47engine .chmod (0o700 ) 48tokenizer = self .root / "tokenizer" 49tokenizer .mkdir () 50for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ): 51 (tokenizer / name ).write_text ("{}" ,encoding = "utf-8" ) 52 (self .root / "pack" ).mkdir () 53 (self .root / "model.gguf" ).write_bytes (b"fake model" ) 54self .config = self .root / "run.json" 55self .config .write_text (json .dumps ({"exe" :str (engine ),"tokenizer" :str (tokenizer ), 56"args" : ["--pack" ,str (self .root / "pack" ), 57"--native" ,str (self .root / "model.gguf" )], 58"cwd" :str (self .root ),"model_name" :"test-model" ,"port" :8095 }), 59encoding = "utf-8" ) 60profiles .create ("local" ,str (self .config )) 61hardware = mock .patch ("strata_control.calibration._hardware_key" ,return_value = "test-gpu|24GB|test-cpu" ) 62hardware .start () 63self .addCleanup (hardware .stop ) 64port = mock .patch ("strata_control.calibration._port_active" ,return_value = False ) 65port .start () 66self .addCleanup (port .stop ) 67 68def fake_result (self ,cfg ,say ,** _ ): 69say ("measured fake decode workload" ) 70return {"settings" : {"--pcie-frac" :"0.20" }, 71"report" : {"default" : {"pcie_frac" :0.55 },"confirm" : {"default" : [10.0 ,10.2 ,10.1 ], 72"candidate" : [12.0 ,12.2 ,12.1 ]}, 73"tok_s" :12.1 ,"seconds" :30 }} 74 75def test_desktop_calibration_receipts_recover_measure_apply_and_rollback (self ): 76def send (action ,params ): 77return management .dispatch ({"schema_version" :1 ,"action" :action , 78"profile" :"local" ,"params" :params }) 79 80path = self .root / "desktop-calibration.json" 81plan = send ("calibration.plan" , {})["plan" ] 82reviewed = {"path" :str (path ),"exclusive_ack" :True , 83"if_profile_revision" :plan ["profile_revision" ], 84"if_source_sha256" :plan ["source_sha256" ]} 85measure_id = uuid .uuid4 ().hex 86created = send ("calibration.job.create" , {"job_id" :measure_id ,"action" :"measure" , 87"if_report_sha256" :None ,** reviewed }) 88self .assertEqual (created ["job_id" ],measure_id ) 89self .assertEqual (send ("calibration.job" , {"job_id" :measure_id })["job" ]["state" ],"launching" ) 90with mock .patch ("tools.calibrate.run" ,side_effect = self .fake_result ), \ 91mock .patch ("strata_control.calibration._smoke" ,return_value = 2 ): 92measured = send ("calibration.measure" , {** reviewed ,"job_id" :measure_id }) 93self .assertEqual (measured ["operation_id" ],measure_id ) 94recovered = send ("calibration.job" , {"job_id" :measure_id })["job" ] 95self .assertEqual (recovered ["state" ],"succeeded" ) 96self .assertEqual (recovered ["result" ]["settings" ], {"--pcie-frac" :"0.20" }) 97 98apply_plan = send ("calibration.apply.plan" , {"path" :str (path )}) 99apply = {** reviewed ,"if_profile_revision" :apply_plan ["profile_revision" ], 100"if_source_sha256" :apply_plan ["source_sha256" ], 101"if_report_sha256" :apply_plan ["report_sha256" ]} 102apply_id = uuid .uuid4 ().hex 103send ("calibration.job.create" , {"job_id" :apply_id ,"action" :"apply" ,** apply }) 104with self .assertRaisesRegex (profiles .ProfileError ,"only calibration measurement" ): 105send ("calibration.cancel" , {"job_id" :apply_id }) 106self .assertEqual (send ("calibration.apply" , {** apply ,"job_id" :apply_id })["operation_id" ],apply_id ) 107self .assertTrue (send ("calibration.job" , {"job_id" :apply_id })["job" ]["result" ]["changed" ]) 108 109rollback_plan = send ("calibration.rollback.plan" , {"path" :str (path )}) 110rollback = {** reviewed ,"if_profile_revision" :rollback_plan ["profile_revision" ], 111"if_source_sha256" :rollback_plan ["source_sha256" ], 112"if_report_sha256" :rollback_plan ["report_sha256" ]} 113rollback_id = uuid .uuid4 ().hex 114send ("calibration.job.create" , {"job_id" :rollback_id ,"action" :"rollback" ,** rollback }) 115self .assertEqual (send ("calibration.rollback" , {** rollback ,"job_id" :rollback_id })["operation_id" ], 116rollback_id ) 117self .assertTrue (send ("calibration.job" , {"job_id" :rollback_id })["job" ]["result" ]["changed" ]) 118 119def test_saved_measurement_reconciles_exact_unfinished_job (self ): 120def send (action ,params ): 121return management .dispatch ({"schema_version" :1 ,"action" :action , 122"profile" :"local" ,"params" :params }) 123 124path = self .root / "recovered-calibration.json" 125plan = send ("calibration.plan" , {})["plan" ] 126job_id = uuid .uuid4 ().hex 127reviewed = {"job_id" :job_id ,"action" :"measure" ,"path" :str (path ), 128"exclusive_ack" :True ,"if_profile_revision" :plan ["profile_revision" ], 129"if_source_sha256" :plan ["source_sha256" ],"if_report_sha256" :None } 130send ("calibration.job.create" ,reviewed ) 131with mock .patch ("tools.calibrate.run" ,side_effect = self .fake_result ): 132calibration .measure ("local" ,path ,exclusive_ack = True ,runner = self .fake_result , 133say = lambda _ :None ,job_id = job_id ) 134recovered = send ("calibration.job" , {"job_id" :job_id })["job" ] 135self .assertEqual (recovered ["state" ],"succeeded" ) 136self .assertEqual (recovered ["outcome" ],"report_recovered" ) 137self .assertEqual (journal .load ("local" ,job_id )["state" ],"succeeded" ) 138result = subprocess .run ([sys .executable ,"-m" ,"strata_control.management" ], 139input = json .dumps ({"schema_version" :1 ,"action" :"calibration.job" ,"profile" :"local" , 140"params" : {"job_id" :job_id }}),text = True ,capture_output = True , 141cwd = Path (__file__ ).resolve ().parents [2 ],env = os .environ .copy (),check = True ) 142self .assertEqual (json .loads (result .stdout )["job" ]["result" ]["report_id" ], 143recovered ["result" ]["report_id" ]) 144with self .assertRaisesRegex (profiles .ProfileError ,"already finished" ): 145journal .finish ("local" ,job_id ,"failed" , {"error_type" :"wrong" }) 146 147def test_failed_desktop_calibration_preflight_finishes_receipt (self ): 148def send (action ,params ): 149return management .dispatch ({"schema_version" :1 ,"action" :action , 150"profile" :"local" ,"params" :params }) 151 152plan = send ("calibration.plan" , {})["plan" ] 153job_id = uuid .uuid4 ().hex 154path = self .root / "failed-calibration.json" 155reviewed = {"path" :str (path ),"exclusive_ack" :True , 156"if_profile_revision" :plan ["profile_revision" ], 157"if_source_sha256" :plan ["source_sha256" ]} 158send ("calibration.job.create" , {"job_id" :job_id ,"action" :"measure" , 159"if_report_sha256" :None ,** reviewed }) 160self .config .write_text (self .config .read_text ().replace ("test-model" ,"changed-model" )) 161with self .assertRaisesRegex (profiles .ProfileError ,"source changed" ): 162send ("calibration.measure" , {** reviewed ,"job_id" :job_id }) 163self .assertEqual (journal .load ("local" ,job_id )["state" ],"failed" ) 164self .assertFalse (path .exists ()) 165 166def test_unrelated_report_cannot_finish_calibration_receipt (self ): 167def send (action ,params ): 168return management .dispatch ({"schema_version" :1 ,"action" :action , 169"profile" :"local" ,"params" :params }) 170 171plan = send ("calibration.plan" , {})["plan" ] 172path = self .root / "unrelated-report.json" 173job_id = uuid .uuid4 ().hex 174send ("calibration.job.create" , {"job_id" :job_id ,"action" :"measure" , 175"path" :str (path ),"exclusive_ack" :True , 176"if_profile_revision" :plan ["profile_revision" ], 177"if_source_sha256" :plan ["source_sha256" ],"if_report_sha256" :None }) 178calibration .measure ("local" ,path ,exclusive_ack = True ,runner = self .fake_result , 179say = lambda _ :None ,job_id = uuid .uuid4 ().hex ) 180self .assertEqual (send ("calibration.job" , {"job_id" :job_id })["job" ]["state" ],"launching" ) 181self .assertEqual (journal .load ("local" ,job_id )["state" ],"running" ) 182 183def test_active_measurement_progress_and_exact_cancel (self ): 184from tools import calibrate as cal 185 186def send (action ,params ): 187return management .dispatch ({"schema_version" :1 ,"action" :action , 188"profile" :"local" ,"params" :params }) 189 190path = self .root / "stopped-calibration.json" 191plan = send ("calibration.plan" , {})["plan" ] 192job_id = uuid .uuid4 ().hex 193reviewed = {"path" :str (path ),"exclusive_ack" :True , 194"if_profile_revision" :plan ["profile_revision" ], 195"if_source_sha256" :plan ["source_sha256" ]} 196send ("calibration.job.create" , {"job_id" :job_id ,"action" :"measure" , 197"if_report_sha256" :None ,** reviewed }) 198started = threading .Event () 199outcome = [] 200original = self .config .read_bytes () 201 202def waiting (cfg ,say ,* ,progress ,cancel_event ): 203progress ("pcie_share" ,2 ,21 ) 204started .set () 205if not cancel_event .wait (4 ): 206raise AssertionError ("operator cancellation did not reach the worker" ) 207raise cal .CalibrationCancelled ("operator requested stop" ) 208 209def worker (): 210try : 211send ("calibration.measure" , {** reviewed ,"job_id" :job_id }) 212except BaseException as exc : 213outcome .append (exc ) 214 215def bridge (action ): 216request = {"schema_version" :1 ,"action" :action ,"profile" :"local" , 217"params" : {"job_id" :job_id }} 218child = subprocess .run ([sys .executable ,"-m" ,"strata_control.management" ], 219input = json .dumps (request ),text = True ,capture_output = True , 220cwd = Path (__file__ ).resolve ().parents [2 ],env = os .environ .copy (),check = True ) 221return json .loads (child .stdout ) 222 223with mock .patch ("tools.calibrate.run" ,side_effect = waiting ): 224thread = threading .Thread (target = worker ) 225thread .start () 226try : 227self .assertTrue (started .wait (4 )) 228active = send ("calibration.job" , {"job_id" :job_id })["job" ] 229self .assertEqual (active ["state" ],"running" ) 230self .assertEqual (active ["activity" ],"active" ) 231self .assertEqual (active ["progress" ]["stage" ],"pcie_share" ) 232self .assertEqual (active ["progress" ]["completed" ],2 ) 233fresh = bridge ("calibration.job" )["job" ] 234self .assertEqual (fresh ["state" ],"running" ) 235self .assertEqual (fresh ["progress" ]["completed" ],2 ) 236with self .assertRaisesRegex (profiles .ProfileError ,"not found" ): 237send ("calibration.cancel" , {"job_id" :uuid .uuid4 ().hex }) 238self .assertEqual (bridge ("calibration.cancel" )["state" ],"cancel_requested" ) 239finally : 240thread .join (timeout = 6 ) 241self .assertFalse (thread .is_alive ()) 242self .assertEqual (len (outcome ),1 ) 243self .assertIsInstance (outcome [0 ],profiles .ProfileError ) 244self .assertEqual (outcome [0 ].exit_code ,130 ) 245finished = send ("calibration.job" , {"job_id" :job_id })["job" ] 246self .assertEqual (finished ["state" ],"cancelled" ) 247self .assertTrue (finished ["cancel_requested" ]) 248self .assertFalse (path .exists ()) 249self .assertEqual (self .config .read_bytes (),original ) 250with self .assertRaisesRegex (profiles .ProfileError ,"not active" ): 251send ("calibration.cancel" , {"job_id" :job_id }) 252 253def test_pruning_finished_receipt_removes_progress_and_cancel_marker (self ): 254from strata_control import calibration_jobs 255 256def send (action ,params ): 257return management .dispatch ({"schema_version" :1 ,"action" :action , 258"profile" :"local" ,"params" :params }) 259 260plan = send ("calibration.plan" , {})["plan" ] 261shared = {"action" :"measure" ,"exclusive_ack" :True , 262"if_profile_revision" :plan ["profile_revision" ], 263"if_source_sha256" :plan ["source_sha256" ],"if_report_sha256" :None } 264first = uuid .uuid4 ().hex 265send ("calibration.job.create" , {** shared ,"job_id" :first , 266"path" :str (self .root / "first.json" )}) 267calibration_jobs ._save_progress ("local" ,first ,"pcie_share" ,2 ,21 ) 268marker = calibration_jobs ._cancel_path ("local" ,first ) 269marker .write_bytes (b"1" ) 270marker .chmod (0o600 ) 271journal .finish ("local" ,first ,"failed" , {"cancelled" :True }) 272with mock .patch .object (journal ,"MAX_RECORDS" ,1 ): 273send ("calibration.job.create" , {** shared ,"job_id" :uuid .uuid4 ().hex , 274"path" :str (self .root / "second.json" )}) 275self .assertFalse (calibration_jobs ._progress_path ("local" ,first ).exists ()) 276self .assertFalse (marker .exists ()) 277 278def test_management_bridge_reviews_and_journals_exclusive_calibration (self ): 279def send (action ,params ): 280return management .dispatch ({"schema_version" :1 ,"action" :action , 281"profile" :"local" ,"params" :params }) 282 283report_path = self .root / "bridge-calibration.json" 284initial = self .config .read_bytes () 285plan = send ("calibration.plan" , {})["plan" ] 286self .assertEqual (plan ["source_config" ],str (self .config .resolve ())) 287self .assertTrue (plan ["component_preflight" ]["ok" ]) 288source = {"if_profile_revision" :plan ["profile_revision" ], 289"if_source_sha256" :plan ["source_sha256" ]} 290measure = {"path" :str (report_path ),"exclusive_ack" :True ,** source } 291with self .assertRaisesRegex (profiles .ProfileError ,"exclusive-access" ): 292send ("calibration.measure" , {** measure ,"exclusive_ack" :False }) 293with self .assertRaisesRegex (profiles .ProfileError ,"source changed" ): 294send ("calibration.measure" , {** measure ,"if_source_sha256" :"0" * 64 }) 295self .assertEqual (journal .list_runs ("local" ), []) 296with mock .patch ("tools.calibrate.run" ,side_effect = self .fake_result ), \ 297mock .patch ("strata_control.calibration._smoke" ,return_value = 3 ): 298measured = send ("calibration.measure" ,measure ) 299self .assertTrue (measured ["ok" ]) 300self .assertTrue (measured ["applicable" ]) 301self .assertEqual (self .config .read_bytes (),initial ) 302self .assertEqual (journal .load ("local" ,measured ["operation_id" ])["state" ],"succeeded" ) 303 304apply_plan = send ("calibration.apply.plan" , {"path" :str (report_path )}) 305self .assertTrue (apply_plan ["plan" ]["applicable" ]) 306apply = {"path" :str (report_path ),"exclusive_ack" :True , 307"if_profile_revision" :apply_plan ["profile_revision" ], 308"if_source_sha256" :apply_plan ["source_sha256" ], 309"if_report_sha256" :apply_plan ["report_sha256" ]} 310with self .assertRaisesRegex (profiles .ProfileError ,"report changed" ): 311send ("calibration.apply" , {** apply ,"if_report_sha256" :"0" * 64 }) 312self .assertEqual (len (journal .list_runs ("local" )),1 ) 313applied = send ("calibration.apply" ,apply ) 314self .assertTrue (applied ["application" ]["changed" ]) 315self .assertTrue (Path (applied ["application" ]["application_record" ]).is_file ()) 316 317rollback_plan = send ("calibration.rollback.plan" , {"path" :str (report_path )}) 318self .assertTrue (rollback_plan ["plan" ]["applicable" ]) 319rolled = send ("calibration.rollback" , {"path" :str (report_path ), 320"exclusive_ack" :True ,"if_profile_revision" :rollback_plan ["profile_revision" ], 321"if_source_sha256" :rollback_plan ["source_sha256" ], 322"if_report_sha256" :rollback_plan ["report_sha256" ]}) 323self .assertTrue (rolled ["rollback" ]["changed" ]) 324self .assertEqual (self .config .read_bytes (),initial ) 325self .assertEqual ([row ["kind" ]for row in journal .list_runs ("local" )], 326 ["engine.calibrate.rollback" ,"engine.calibrate.apply" , 327"engine.calibrate.measure" ]) 328 329def test_missing_report_folder_is_refused_before_the_sweep (self ): 330# #3187: the sweep takes ~19 minutes; the folder check must not wait until after it 331for output in (self .root / "no-such-dir" / "report.json" ,self .config / "report.json" ): 332with self .assertRaisesRegex (profiles .ProfileError ,"report output directory does not exist" ): 333calibration .measure ("local" ,output ,exclusive_ack = True , 334runner = lambda * _a ,** _k :self .fail ("the sweep must not start" )) 335 336def test_calibration_rechecks_reviewed_digests_inside_operation_lock (self ): 337report_path = self .root / "pinned-calibration.json" 338with self .assertRaisesRegex (profiles .ProfileError ,"source changed after review" ): 339calibration .measure ("local" ,report_path ,exclusive_ack = True , 340runner = lambda * _args ,** _kwargs :self .fail ("runner must not start" ), 341expected_source_sha256 = "0" * 64 ) 342self .assertFalse (report_path .exists ()) 343report = calibration .measure ("local" ,report_path ,exclusive_ack = True , 344runner = self .fake_result ,say = lambda _ :None ) 345source = self .config .read_bytes () 346with self .assertRaisesRegex (profiles .ProfileError ,"report changed after review" ): 347calibration .apply_result ("local" ,report_path ,exclusive_ack = True , 348expected_report_sha256 = "0" * 64 , 349smoke = lambda * _args :self .fail ("smoke must not start" )) 350self .assertEqual (self .config .read_bytes (),source ) 351calibration .apply_result ("local" ,report_path ,exclusive_ack = True , 352expected_report_sha256 = report ["body_sha256" ],smoke = lambda * _args :2 ) 353with self .assertRaisesRegex (profiles .ProfileError ,"report changed after review" ): 354calibration .rollback_result ("local" ,report_path ,exclusive_ack = True , 355expected_report_sha256 = "0" * 64 , 356smoke = lambda * _args :self .fail ("smoke must not start" )) 357 358def test_measure_review_apply_and_setup_persistence (self ): 359before = self .config .read_bytes () 360report_path = self .root / "calibration.json" 361report = calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 362self .assertEqual (self .config .read_bytes (),before ) 363self .assertTrue (report ["applicable" ]) 364self .assertEqual (report ["settings" ]["--pcie-frac" ],"0.20" ) 365if os .name != "nt" : 366self .assertEqual (stat .S_IMODE (report_path .stat ().st_mode ),0o600 ) 367preview = calibration .review ("local" ,report_path ) 368self .assertTrue (preview ["applicable" ]) 369self .assertIn ("--pcie-frac" ,preview ["after_args" ]) 370applied = calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :4 ) 371self .assertTrue (applied ["changed" ]) 372self .assertEqual (applied ["smoke_output_tokens" ],4 ) 373self .assertEqual (Path (applied ["backup" ]).read_bytes (),before ) 374self .assertIn ("--pcie-frac" ,json .loads (self .config .read_text ())["args" ]) 375settings = json .loads ((self .settings_file ).read_text ()) 376self .assertEqual (settings ["calibration" ]["test-gpu|24GB|test-cpu" ]["settings" ],report ["settings" ]) 377self .assertFalse (calibration .review ("local" ,report_path )["applicable" ]) 378 379def test_applied_result_survives_the_next_launches_with_its_origin (self ): 380"""#5132: `engine calibrate --apply-result` writes the profile's run config; a launch builds that file again from the installed config and 381used to drop the calibrated values. They come back over Auto, as 'calibrated' (not as the person's overrides), launch after launch.""" 382from strata_cli .launch import settings as S 383from strata_cli .launch .runner import derive_config 384from strata_control import arg_layers ,tune_knobs 385base = json .loads (self .config .read_text ()) 386base ["args" ]+= ["--max-context" ,"65536" ] 387self .config .write_text (json .dumps (base ),encoding = "utf-8" ) 388 389def launch (prev ): 390cfg = derive_config (json .loads (json .dumps (base )),S .LaunchSettings (drafting = "off" ),bool_flags = tune_knobs .BOOL_FLAGS ,prev = prev ) 391arg_layers .stamp (cfg ) 392return json .loads (json .dumps (cfg )) 393 394first = launch (None ) 395self .config .write_text (json .dumps (first ),encoding = "utf-8" )# the profile points at the launch's file 396report_path = self .root / "cal-launch.json" 397calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 398calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 399written = json .loads (self .config .read_text ()) 400self .assertEqual (written ["args" ][written ["args" ].index ("--pcie-frac" )+ 1 ],"0.20" ) 401for prev in (written ,launch (written )): 402nxt = launch (prev ) 403self .assertEqual (nxt ["args" ][nxt ["args" ].index ("--pcie-frac" )+ 1 ],"0.20" ) 404self .assertEqual (nxt ["args" ].count ("--pcie-frac" ),1 ) 405self .assertEqual (nxt ["calibrated" ]["settings" ], {"--pcie-frac" :"0.20" }) 406self .assertNotIn ("--pcie-frac" ,nxt .get ("user_args" )or []) 407 408def test_review_and_rollback_restore_config_and_absent_settings (self ): 409before = self .config .read_bytes () 410report_path = self .root / "calibration.json" 411calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 412applied = calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :3 ) 413self .assertTrue (Path (applied ["application_record" ]).is_file ()) 414if os .name == "posix" : 415self .assertEqual (stat .S_IMODE (Path (applied ["application_record" ]).stat ().st_mode ),0o600 ) 416preview = calibration .review_rollback ("local" ,report_path ) 417self .assertTrue (preview ["applicable" ],preview ["reasons" ]) 418self .assertTrue (preview ["setup_settings_would_be_removed" ]) 419restored = calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 420self .assertTrue (restored ["changed" ]) 421self .assertEqual (restored ["smoke_output_tokens" ],2 ) 422self .assertEqual (self .config .read_bytes (),before ) 423self .assertFalse ((self .settings_file ).exists ()) 424self .assertFalse (calibration .review_rollback ("local" ,report_path )["applicable" ]) 425 426@ unittest . skipUnless ( os . name == "posix" , "managed activity lease is POSIX-only" ) 427def test_managed_activity_lease_blocks_apply_and_rollback_smoke (self ): 428report_path = self .root / "calibration.json" 429 430def assert_exclusive (): 431with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 432runtime .acquire_activity_lease (shared = True ) 433 434def runner (cfg ,say ): 435assert_exclusive () 436return self .fake_result (cfg ,say ) 437 438def smoke (cfg ): 439assert_exclusive () 440return 2 441 442calibration .measure ("local" ,report_path ,exclusive_ack = True , 443runner = runner ,say = lambda _ :None ) 444before = self .config .read_bytes () 445lease = runtime .acquire_activity_lease (shared = True ) 446try : 447with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 448calibration .apply_result ("local" ,report_path ,exclusive_ack = True , 449smoke = lambda cfg :self .fail ("apply smoke ran" )) 450finally : 451os .close (lease ) 452self .assertEqual (self .config .read_bytes (),before ) 453calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = smoke ) 454applied = self .config .read_bytes () 455lease = runtime .acquire_activity_lease (shared = True ) 456try : 457with self .assertRaisesRegex (profiles .ProfileError ,"engine lease" ): 458calibration .rollback_result ("local" ,report_path ,exclusive_ack = True , 459smoke = lambda cfg :self .fail ("rollback smoke ran" )) 460finally : 461os .close (lease ) 462self .assertEqual (self .config .read_bytes (),applied ) 463with mock .patch ("strata_control.calibration._port_active" ,return_value = True ): 464with self .assertRaisesRegex (profiles .ProfileError ,"server is listening" ): 465calibration .rollback_result ("local" ,report_path ,exclusive_ack = True , 466smoke = lambda cfg :self .fail ("rollback smoke ran" )) 467self .assertEqual (self .config .read_bytes (),applied ) 468self .assertTrue (calibration .rollback_result ("local" ,report_path ,exclusive_ack = True , 469smoke = smoke )["changed" ]) 470 471def test_rollback_restores_existing_settings_exactly (self ): 472settings_path = self .settings_file 473settings_path .parent .mkdir (parents = True ) 474original_settings = b'{"unrelated": "keep", "calibration": {"other-device": {"settings": {}}}}\n' 475settings_path .write_bytes (original_settings ) 476original_config = self .config .read_bytes () 477report_path = self .root / "calibration.json" 478calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 479applied = calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 480self .assertEqual (Path (applied ["settings_backup" ]).read_bytes (),original_settings ) 481calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 482self .assertEqual (settings_path .read_bytes (),original_settings ) 483self .assertEqual (self .config .read_bytes (),original_config ) 484 485def test_rollback_refuses_stale_state_and_failed_smoke (self ): 486report_path = self .root / "calibration.json" 487calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 488calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 489applied_config = self .config .read_bytes () 490settings_path = self .settings_file 491applied_settings = settings_path .read_bytes () 492with self .assertRaisesRegex (profiles .ProfileError ,"rollback smoke generation failed" ): 493calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :1 / 0 ) 494self .assertEqual (self .config .read_bytes (),applied_config ) 495settings_path .write_bytes (applied_settings + b" " ) 496preview = calibration .review_rollback ("local" ,report_path ) 497self .assertIn ("setup_settings_changed_after_apply" ,preview ["reasons" ]) 498with self .assertRaisesRegex (profiles .ProfileError ,"rollback is stale" ): 499calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 500self .assertEqual (self .config .read_bytes (),applied_config ) 501settings_path .write_bytes (applied_settings ) 502self .config .write_bytes (applied_config + b" " ) 503preview = calibration .review_rollback ("local" ,report_path ) 504self .assertIn ("run_config_changed_after_apply" ,preview ["reasons" ]) 505with self .assertRaisesRegex (profiles .ProfileError ,"rollback is stale" ): 506calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 507 508def test_rollback_detects_change_during_smoke (self ): 509report_path = self .root / "calibration.json" 510calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 511calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 512applied_config = self .config .read_bytes () 513settings_path = self .settings_file 514applied_settings = settings_path .read_bytes () 515 516def smoke (cfg ): 517settings_path .write_bytes (applied_settings + b" " ) 518return 2 519 520with self .assertRaisesRegex (profiles .ProfileError ,"changed during rollback smoke" ): 521calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = smoke ) 522self .assertEqual (self .config .read_bytes (),applied_config ) 523 524def test_rollback_rejects_modified_backup (self ): 525report_path = self .root / "calibration.json" 526calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 527applied = calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 528Path (applied ["backup" ]).write_bytes (b"{}" ) 529preview = calibration .review_rollback ("local" ,report_path ) 530self .assertIn ("config_backup_changed" ,preview ["reasons" ]) 531with self .assertRaisesRegex (profiles .ProfileError ,"rollback is stale" ): 532calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 533 534def test_rollback_requires_exclusive_acknowledgement (self ): 535report_path = self .root / "calibration.json" 536output = io .StringIO () 537with redirect_stdout (output ): 538code = main (["engine" ,"calibrate" ,"--profile" ,"local" ,"--rollback-result" , 539str (report_path ),"--output" ,"json" ]) 540self .assertEqual (code ,2 ) 541self .assertFalse (json .loads (output .getvalue ())["ok" ]) 542with self .assertRaisesRegex (profiles .ProfileError ,"exclusive-access" ): 543calibration .rollback_result ("local" ,report_path ) 544 545@ unittest . skipUnless ( os . name == "posix" , "symlink test requires POSIX" ) 546def test_apply_refuses_symlinked_backup_directory (self ): 547report_path = self .root / "calibration.json" 548calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 549previous = self .config .read_bytes () 550elsewhere = self .root / "elsewhere" 551elsewhere .mkdir () 552 (self .root / ".strata-calibration-backups" ).symlink_to (elsewhere ,target_is_directory = True ) 553with self .assertRaisesRegex (profiles .ProfileError ,"owner-only and not a symlink" ): 554calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 555self .assertEqual (self .config .read_bytes (),previous ) 556self .assertEqual (list (elsewhere .iterdir ()), []) 557 558def test_rollback_write_failure_restores_applied_state (self ): 559report_path = self .root / "calibration.json" 560calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 561calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 562current_config = self .config .read_bytes () 563settings_path = self .settings_file 564current_settings = settings_path .read_bytes () 565original_replace = calibration ._replace_bytes 566failures = 0 567 568def fail_restore (path ,payload ): 569nonlocal failures 570if path == self .config .resolve ()and failures == 0 : 571failures += 1 572original_replace (path ,payload ) 573raise OSError ("simulated failure after config replacement" ) 574return original_replace (path ,payload ) 575 576with mock .patch ("strata_control.calibration._replace_bytes" ,side_effect = fail_restore ): 577with self .assertRaisesRegex (profiles .ProfileError ,"applied state restored" ): 578calibration .rollback_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 579self .assertEqual (self .config .read_bytes (),current_config ) 580self .assertEqual (settings_path .read_bytes (),current_settings ) 581 582def test_failed_smoke_or_changed_config_never_applies (self ): 583report_path = self .root / "calibration.json" 584calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 585before = self .config .read_bytes () 586with self .assertRaisesRegex (profiles .ProfileError ,"smoke generation failed" ): 587calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :1 / 0 ) 588self .assertEqual (self .config .read_bytes (),before ) 589self .config .write_bytes (before + b" " ) 590with self .assertRaisesRegex (profiles .ProfileError ,"stale" ): 591calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :4 ) 592 593def test_report_id_and_settings_are_validated_before_apply (self ): 594report_path = self .root / "calibration.json" 595calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 596report = json .loads (report_path .read_text ()) 597report ["report_id" ]= "../../outside" 598report_path .write_text (json .dumps (report ),encoding = "utf-8" ) 599with self .assertRaisesRegex (profiles .ProfileError ,"unsupported calibration report" ): 600calibration .review ("local" ,report_path ) 601report ["report_id" ]= "0" * 32 602report ["settings" ]= {"--pool-workers" :"999999" } 603report_path .write_text (json .dumps (report ),encoding = "utf-8" ) 604with self .assertRaisesRegex (profiles .ProfileError ,"positive whole number" ): 605calibration .review ("local" ,report_path ) 606report ["settings" ]= {"--pcie-frac" :"0.75" } 607report_path .write_text (json .dumps (report ),encoding = "utf-8" ) 608with self .assertRaisesRegex (profiles .ProfileError ,"changed after measurement" ): 609calibration .review ("local" ,report_path ) 610 611def test_machine_cli_measure_review_apply_emits_one_json_record (self ): 612report_path = self .root / "calibration.json" 613with mock .patch ("tools.calibrate.run" ,side_effect = self .fake_result ), \ 614mock .patch ("strata_control.calibration._smoke" ,return_value = 3 ): 615for args ,expected_key in ((["--measure" ,"--out" ,str (report_path ),"--exclusive" ],"report" ), 616 (["--review-result" ,str (report_path )],"review" ), 617 (["--apply-result" ,str (report_path ),"--exclusive" ],"application" ), 618 (["--review-rollback" ,str (report_path )],"rollback_review" ), 619 (["--rollback-result" ,str (report_path ),"--exclusive" ],"rollback" )): 620output = io .StringIO () 621with redirect_stdout (output ): 622code = main (["engine" ,"calibrate" ,"--profile" ,"local" ,* args ,"--output" ,"json" ]) 623self .assertEqual (code ,0 ) 624parsed = json .loads (output .getvalue ()) 625self .assertTrue (parsed ["ok" ]) 626self .assertIn (expected_key ,parsed ) 627if expected_key in ("report" ,"application" ,"rollback" ): 628record = journal .load ("local" ,parsed ["operation_id" ]) 629self .assertEqual (record ["schema_version" ],2 ) 630self .assertEqual (record ["origin" ],"direct" ) 631self .assertEqual (record ["state" ],"succeeded" ) 632self .assertNotIn ("candidate" ,json .dumps (record )) 633else : 634self .assertNotIn ("operation_id" ,parsed ) 635self .assertEqual ([row ["kind" ]for row in journal .list_runs ("local" )], 636 ["engine.calibrate.rollback" ,"engine.calibrate.apply" ,"engine.calibrate.measure" ]) 637 638def test_explicit_run_config_path_retains_legacy_nonjournaled_calibration (self ): 639report_path = self .root / "calibration-path.json" 640output = io .StringIO () 641with mock .patch ("tools.calibrate.run" ,side_effect = self .fake_result ): 642with redirect_stdout (output ): 643code = main (["engine" ,"calibrate" ,"--profile" ,str (self .config ),"--measure" , 644"--exclusive" ,"--out" ,str (report_path ),"--output" ,"json" ]) 645self .assertEqual (code ,0 ) 646self .assertNotIn ("operation_id" ,json .loads (output .getvalue ())) 647self .assertEqual (journal .list_runs ("local" ), []) 648 649def test_direct_apply_failure_is_a_compact_failed_operation (self ): 650report_path = self .root / "calibration.json" 651calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 652output = io .StringIO () 653with mock .patch ("strata_control.calibration._smoke" ,side_effect = OSError ("private engine trace" )): 654with redirect_stdout (output ): 655code = main (["engine" ,"calibrate" ,"--profile" ,"local" ,"--apply-result" , 656str (report_path ),"--exclusive" ,"--output" ,"json" ]) 657self .assertEqual (code ,6 ) 658self .assertFalse (json .loads (output .getvalue ())["ok" ]) 659record = journal .load ("local" ,journal .list_runs ("local" )[0 ]["operation_id" ]) 660self .assertEqual ((record ["kind" ],record ["state" ]), ("engine.calibrate.apply" ,"failed" )) 661self .assertNotIn ("private engine trace" ,json .dumps (record )) 662 663def test_measure_requires_exclusive_access_and_rejects_live_profile_port (self ): 664report_path = self .root / "calibration.json" 665with self .assertRaisesRegex (profiles .ProfileError ,"exclusive-access" ): 666calibration .measure ("local" ,report_path ,runner = self .fake_result ) 667with mock .patch ("strata_control.calibration._port_active" ,return_value = True ): 668with self .assertRaisesRegex (profiles .ProfileError ,"server is listening" ): 669calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ) 670profiles .set_values ("local" , ["port=9123" ]) 671with mock .patch ("strata_control.calibration._port_active" , 672side_effect = lambda cfg :cfg .get ("port" )== 9123 )as checked : 673with self .assertRaisesRegex (profiles .ProfileError ,"server is listening" ): 674calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ) 675self .assertEqual ([call .args [0 ]["port" ]for call in checked .call_args_list ], [8095 ,9123 ]) 676self .assertFalse (report_path .exists ()) 677 678def test_measure_and_smoke_use_saved_engine_overrides_without_writing_them (self ): 679profiles .set_values ("local" , ["parallel=8" ,"batch_groups=2" ]) 680source = self .config .read_bytes () 681report_path = self .root / "calibration.json" 682seen = {} 683 684def runner (cfg ,say ): 685seen ["measured" ]= cfg 686return self .fake_result (cfg ,say ) 687 688def smoke (cfg ): 689seen ["smoked" ]= cfg 690return 2 691 692calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = runner ,say = lambda _ :None ) 693self .assertEqual (seen ["measured" ]["parallel" ],8 ) 694self .assertEqual (seen ["measured" ]["args" ][- 2 :], ["--batch-groups" ,"2" ]) 695self .assertEqual (self .config .read_bytes (),source ) 696calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = smoke ) 697self .assertEqual (seen ["smoked" ]["parallel" ],8 ) 698self .assertIn ("--batch-groups" ,seen ["smoked" ]["args" ]) 699saved_args = json .loads (self .config .read_text ())["args" ] 700self .assertNotIn ("--batch-groups" ,saved_args ) 701 702def test_profile_edit_during_measurement_marks_report_stale (self ): 703report_path = self .root / "calibration.json" 704 705def runner (cfg ,say ): 706profiles .set_values ("local" , ["parallel=4" ]) 707return self .fake_result (cfg ,say ) 708 709report = calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = runner ,say = lambda _ :None ) 710self .assertFalse (report ["applicable" ]) 711preview = calibration .review ("local" ,report_path ) 712self .assertFalse (preview ["applicable" ]) 713self .assertIn ("measurement_became_stale" ,preview ["reasons" ]) 714 715def test_profile_edit_during_smoke_prevents_apply (self ): 716report_path = self .root / "calibration.json" 717calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 718source = self .config .read_bytes () 719 720def smoke (cfg ): 721profiles .set_values ("local" , ["parallel=4" ]) 722return 2 723 724with self .assertRaisesRegex (profiles .ProfileError ,"changed during smoke" ): 725calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = smoke ) 726self .assertEqual (self .config .read_bytes (),source ) 727 728def test_settings_write_failure_restores_previous_run_config (self ): 729report_path = self .root / "calibration.json" 730calibration .measure ("local" ,report_path ,exclusive_ack = True ,runner = self .fake_result ,say = lambda _ :None ) 731source = self .config .read_bytes () 732original_replace = calibration ._replace_bytes 733failures = 0 734 735def fail_settings (path ,payload ): 736nonlocal failures 737if path .name == "settings.json" : 738failures += 1 739if failures == 1 : 740original_replace (path ,payload ) 741raise OSError ("simulated failure after settings replacement" ) 742return original_replace (path ,payload ) 743 744with mock .patch ("strata_control.calibration._replace_bytes" ,side_effect = fail_settings ): 745with self .assertRaisesRegex (profiles .ProfileError ,"config restored" ): 746calibration .apply_result ("local" ,report_path ,exclusive_ack = True ,smoke = lambda cfg :2 ) 747self .assertEqual (self .config .read_bytes (),source ) 748self .assertFalse ((self .settings_file ).exists ()) 749 750 751if __name__ == "__main__" : 752unittest .main ()