okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""Owner-editable typed operations; previews never run or write an operation.""" 2 3import io 4import json 5import os 6import stat 7import subprocess 8import sys 9import tempfile 10import unittest 11from contextlib import redirect_stdout 12from pathlib import Path 13from unittest import mock 14 15from strata_cli .cli import main 16from strata_control import journal ,profiles ,recipes 17 18 19class RecipeTests (unittest .TestCase ): 20def setUp (self ): 21self .temp = tempfile .TemporaryDirectory () 22self .addCleanup (self .temp .cleanup ) 23self .root = Path (self .temp .name ) 24environment = mock .patch .dict (os .environ , {"STRATA_PROFILE_DIR" :str (self .root / "profiles" ), 25"XDG_CONFIG_HOME" :str (self .root / "settings" )}) 26environment .start () 27self .addCleanup (environment .stop ) 28engine = self .root / "engine" 29engine .write_bytes (b"fake engine" ) 30engine .chmod (0o700 ) 31tokenizer = self .root / "tokenizer" 32tokenizer .mkdir () 33for name in ("vocab.json" ,"merges.txt" ,"token_type.json" ): 34 (tokenizer / name ).write_text ("{}" ,encoding = "utf-8" ) 35self .config = self .root / "run.json" 36self .config .write_text (json .dumps ({"exe" :str (engine ),"tokenizer" :str (tokenizer ), 37"args" : [],"cwd" :str (self .root ),"model_name" :"fake" , 38"host" :"127.0.0.1" ,"port" :0 }),encoding = "utf-8" ) 39profiles .create ("local" ,str (self .config )) 40 41def _cli (self ,* args ): 42output = io .StringIO () 43with redirect_stdout (output ): 44code = main (["ops" ,* args ,"--profile" ,"local" ,"--output" ,"json" ]) 45return code ,json .loads (output .getvalue ()) 46 47def test_benchmark_job_receipt_is_readable_by_new_owner_bridge_process (self ): 48_ ,revision = profiles .load ("local" ) 49job_id = "a" * 32 50intent = {"path" :str (self .root / "future-benchmark" ),"suite" :"serving-smoke" , 51"concurrency" :2 ,"repeat" :1 ,"request_timeout" :30 , 52"condition" :"baseline" ,"if_profile_revision" :revision , 53"if_source_sha256" :"b" * 64 , 54"if_owner_id" :"c" * 32 ,"if_instance_id" :"d" * 32 } 55journal .begin_direct ("local" ,"bench.run" ,revision ,intent ,operation_id = job_id ) 56request = {"schema_version" :1 ,"action" :"bench.job" ,"profile" :"local" , 57"params" : {"job_id" :job_id }} 58process = subprocess .run ([sys .executable ,"-m" ,"strata_control.management" ], 59input = json .dumps (request ),text = True ,capture_output = True , 60cwd = Path (__file__ ).resolve ().parents [2 ],timeout = 10 ,check = True ) 61response = json .loads (process .stdout ) 62self .assertTrue (response ["ok" ]) 63self .assertEqual (response ["job" ]["job_id" ],job_id ) 64self .assertEqual (response ["job" ]["state" ],"launching" ) 65self .assertIsNone (response ["job" ]["result" ]) 66 67def test_init_set_plan_and_run_are_typed_and_machine_clean (self ): 68self .assertEqual (self ._cli ("list" )[1 ]["recipes" ], []) 69self .assertFalse ((profiles .profile_dir ()/ ".ops" ).exists ()) 70code ,initialized = self ._cli ("init" ) 71self .assertEqual (code ,0 ) 72self .assertEqual (initialized ["created" ], ["restart" ,"calibrate" ,"check" ]) 73self .assertEqual (self ._cli ("init" )[1 ]["created" ], []) 74self .assertEqual (len (self ._cli ("list" )[1 ]["recipes" ]),3 ) 75before ,revision = recipes .load ("local" ,"restart" ) 76code ,preview = self ._cli ("set" ,"restart" ,"startup_wait_s=45" ,"--plan" ) 77self .assertEqual (code ,0 ) 78self .assertTrue (preview ["would_save" ]) 79self .assertEqual (recipes .load ("local" ,"restart" ), (before ,revision )) 80self .assertEqual (self ._cli ("set" ,"restart" ,"startup_wait_s=45" )[0 ],0 ) 81self .assertFalse (self ._cli ("set" ,"restart" ,"startup_wait_s=45" ,"--plan" )[1 ]["would_save" ]) 82with mock .patch ("strata_control.runtime.plan_restart" ,return_value = {"ok" :True , 83"state" :"ready" ,"would_drain" :False }), \ 84mock .patch ("strata_control.runtime.restart" ,return_value = {"ok" :True , 85"state" :"ready" ,"instance_id" :"next" })as restart : 86code ,planned = self ._cli ("plan" ,"restart" ) 87self .assertEqual (code ,0 ) 88self .assertFalse (planned ["plan" ]["would_execute" ]) 89self .assertEqual (planned ["plan" ]["operation" ]["startup_wait_s" ],45 ) 90self .assertTrue (planned ["plan" ]["operation" ]["run_effects" ]["drain_current_instance" ]) 91restart .assert_not_called () 92code ,ran = self ._cli ("run" ,"restart" ) 93self .assertEqual (code ,0 ) 94self .assertEqual (ran ["operation" ]["result" ]["instance_id" ],"next" ) 95restart .assert_called_once_with ("local" ,startup_wait = 45 ) 96self .assertEqual (self ._cli ("run" ,"check" )[0 ],0 ) 97with mock .patch ("strata_control.runtime.restart" )as restart : 98code ,invalid = self ._cli ("run" ,"restart" ,"--exclusive" ) 99self .assertEqual (code ,2 ) 100self .assertFalse (invalid ["ok" ]) 101restart .assert_not_called () 102 103def test_calibration_requires_fresh_exclusivity_and_uses_new_report_path (self ): 104recipes .initialize ("local" ) 105source = self .config .read_bytes () 106report_dir = self .root / "reports" 107self .assertEqual (self ._cli ("set" ,"calibrate" ,f"report_dir= { report_dir } " )[0 ],0 ) 108code ,result = self ._cli ("plan" ,"calibrate" ) 109self .assertEqual (code ,0 ) 110self .assertFalse (result ["plan" ]["would_execute" ]) 111self .assertTrue (result ["plan" ]["operation" ]["run_effects" ]["start_engine_for_decode_sweep" ]) 112self .assertFalse (result ["plan" ]["operation" ]["run_effects" ]["change_run_config" ]) 113self .assertFalse (report_dir .exists ()) 114code ,denied = self ._cli ("run" ,"calibrate" ) 115self .assertEqual (code ,2 ) 116self .assertFalse (denied ["ok" ]) 117 118def fake_runner (cfg ,say ): 119return {"settings" : {"--pcie-frac" :"0.20" }, 120"report" : {"default" : {"pcie_frac" :0.55 }, 121"confirm" : {"default" : [10.0 ,10.2 ,10.1 ], 122"candidate" : [12.0 ,12.2 ,12.1 ]}, 123"tok_s" :12.1 ,"seconds" :30 }} 124 125with mock .patch ("tools.calibrate.run" ,side_effect = fake_runner ), \ 126mock .patch ("strata_control.calibration._hardware_key" ,return_value = "fake-gpu" ), \ 127mock .patch ("strata_control.calibration._port_active" ,return_value = False ): 128first = self ._cli ("run" ,"calibrate" ,"--exclusive" ) 129second = self ._cli ("run" ,"calibrate" ,"--exclusive" ) 130self .assertEqual (first [0 ],0 ) 131self .assertEqual (second [0 ],0 ) 132first_path = Path (first [1 ]["operation" ]["result" ]["report_path" ]) 133second_path = Path (second [1 ]["operation" ]["result" ]["report_path" ]) 134self .assertNotEqual (first_path ,second_path ) 135self .assertTrue (first_path .is_file ()) 136self .assertTrue (second_path .is_file ()) 137self .assertEqual (self .config .read_bytes (),source ) 138if os .name == "posix" : 139self .assertEqual (stat .S_IMODE (first_path .stat ().st_mode ),0o600 ) 140 141def test_component_recipe_can_enable_a_typed_live_card_check (self ): 142cfg = json .loads (self .config .read_text (encoding = "utf-8" )) 143cfg ["gpu" ]= [0 ,1 ,2 ,3 ] 144cfg ["backend" ]= "cuda" 145self .config .write_text (json .dumps (cfg ),encoding = "utf-8" ) 146recipes .initialize ("local" ) 147code ,proposed = self ._cli ("set" ,"check" ,"live=true" ,"--plan" ) 148self .assertEqual (code ,0 ) 149self .assertTrue (proposed ["would_save" ]) 150self .assertEqual (recipes .load ("local" ,"check" )[0 ]["params" ], {}) 151self .assertEqual (self ._cli ("set" ,"check" ,"live=true" )[0 ],0 ) 152cards = "\n" .join (f" { i } , RTX 6000 test, GPU-test- { i } , 49140, 580.95" for i in range (4 )) 153with mock .patch ("strata_control.doctor.shutil.which" ,return_value = "/fake/nvidia-smi" ), \ 154mock .patch ("strata_control.doctor.subprocess.run" , 155return_value = mock .Mock (returncode = 0 ,stdout = cards ))as probe : 156code ,preview = self ._cli ("plan" ,"check" ) 157self .assertEqual (code ,0 ) 158self .assertTrue (preview ["plan" ]["operation" ]["run_effects" ]["query_host_gpus" ]) 159self .assertEqual (preview ["plan" ]["operation" ]["preflight" ]["live_gpu_probe" ]["status" ],"ok" ) 160code ,executed = self ._cli ("run" ,"check" ,"--if-revision" ,preview ["plan" ]["recipe_revision" ]) 161self .assertEqual (code ,0 ) 162self .assertEqual (executed ["operation" ]["result" ]["report" ]["live_gpu_probe" ]["status" ],"ok" ) 163self .assertEqual (probe .call_count ,2 ) 164record = journal .load ("local" ,executed ["operation" ]["operation_id" ]) 165self .assertEqual (record ["intent" ], {"live" :True }) 166with self .assertRaisesRegex (profiles .ProfileError ,"parameter is not supported" ): 167recipes .propose_value ("local" ,"check" ,"live=maybe" ) 168 169def test_invalid_edit_keeps_draft_and_saved_recipe (self ): 170recipes .initialize ("local" ) 171before = recipes .load ("local" ,"check" ) 172editor = self .root / "bad_editor.py" 173editor .write_text ("import pathlib, sys\npathlib.Path(sys.argv[1]).write_text('{}')\n" ) 174with mock .patch .dict (os .environ , {"VISUAL" :f" { sys . executable } { editor } " }): 175code ,result = self ._cli ("edit" ,"check" ) 176self .assertEqual (code ,2 ) 177self .assertFalse (result ["ok" ]) 178self .assertEqual (recipes .load ("local" ,"check" ),before ) 179self .assertEqual (len (list ((profiles .profile_dir ()/ ".ops" / "local" ).glob (".check-edit-*.json" ))),1 ) 180 181def test_history_rollback_and_stale_edit (self ): 182recipes .initialize ("local" ) 183original ,first = recipes .load ("local" ,"restart" ) 184proposed ,revision = recipes .propose_value ("local" ,"restart" ,"startup_wait_s=60" ) 185recipes .save ("local" ,"restart" ,proposed ,revision ) 186with mock .patch ("strata_control.runtime.restart" )as restart : 187code ,stale = self ._cli ("run" ,"restart" ,"--if-revision" ,first ) 188self .assertEqual (code ,6 ) 189self .assertFalse (stale ["ok" ]) 190restart .assert_not_called () 191with self .assertRaisesRegex (profiles .ProfileError ,"changed during edit" ): 192recipes .save ("local" ,"restart" ,original ,first ) 193entries = recipes .history ("local" ,"restart" ) 194self .assertEqual (entries [1 ]["revision" ],first ) 195code ,restored = self ._cli ("rollback" ,"restart" ,"--to" ,first ) 196self .assertEqual (code ,0 ) 197self .assertEqual (restored ["recipe" ]["params" ]["startup_wait_s" ],300 ) 198self .assertEqual (recipes .load ("local" ,"restart" )[0 ],original ) 199 200def test_recipe_file_cannot_inject_shell_kind_or_symlink (self ): 201recipes .initialize ("local" ) 202path = profiles .profile_dir ()/ ".ops" / "local" / "restart.json" 203original = path .read_bytes () 204path .write_text (json .dumps ({"schema_version" :1 ,"profile" :"local" ,"id" :"restart" , 205"kind" :"shell.exec" ,"params" : {"command" :"rm -rf /" }})) 206with self .assertRaisesRegex (profiles .ProfileError ,"unsupported" ): 207recipes .load ("local" ,"restart" ) 208path .unlink () 209outside = self .root / "outside.json" 210outside .write_bytes (original ) 211path .symlink_to (outside ) 212with self .assertRaisesRegex (profiles .ProfileError ,"regular file" ): 213recipes .load ("local" ,"restart" ) 214 215def test_init_rejects_conflicting_default_name_before_other_writes (self ): 216recipes .create ("local" ,"check" ,"runtime.restart" ) 217with self .assertRaisesRegex (profiles .ProfileError ,"different kind" ): 218recipes .initialize ("local" ) 219self .assertEqual ([item ["id" ]for item in recipes .list_recipes ("local" )], ["check" ]) 220 221def test_operation_journal_records_compact_success_and_is_read_only_to_list (self ): 222recipes .initialize ("local" ) 223self .assertEqual (self ._cli ("runs" )[1 ]["runs" ], []) 224self .assertFalse ((profiles .profile_dir ()/ ".ops" / "local" / ".runs" ).exists ()) 225code ,executed = self ._cli ("run" ,"check" ) 226self .assertEqual (code ,0 ) 227operation_id = executed ["operation" ]["operation_id" ] 228code ,listed = self ._cli ("runs" ) 229self .assertEqual (code ,0 ) 230self .assertEqual (listed ["runs" ][0 ]["operation_id" ],operation_id ) 231code ,shown = self ._cli ("result" ,operation_id ) 232self .assertEqual (code ,0 ) 233record = shown ["record" ] 234self .assertEqual (record ["state" ],"succeeded" ) 235self .assertEqual (record ["intent" ], {}) 236self .assertEqual ([event ["state" ]for event in record ["events" ]], ["running" ,"succeeded" ]) 237self .assertEqual (set (record ["result" ]), {"ok" ,"issue_codes" }) 238path = profiles .profile_dir ()/ ".ops" / "local" / ".runs" / f" { operation_id } .json" 239if os .name == "posix" : 240self .assertEqual (stat .S_IMODE (path .stat ().st_mode ),0o600 ) 241 242def test_failed_and_uncertain_runs_keep_distinct_journal_states_without_raw_result (self ): 243recipes .initialize ("local" ) 244with mock .patch ("strata_control.runtime.restart" ,return_value = {"ok" :False , 245"state" :"ready" ,"error" :"new_instance_failed" ,"exit_code" :6 , 246"private_trace" :"TOPSECRET" }): 247code ,executed = self ._cli ("run" ,"restart" ) 248self .assertEqual (code ,6 ) 249failed = journal .load ("local" ,executed ["operation" ]["operation_id" ]) 250self .assertEqual (failed ["state" ],"failed" ) 251self .assertNotIn ("TOPSECRET" ,json .dumps (failed )) 252with mock .patch ("strata_control.runtime.restart" , 253side_effect = profiles .ProfileError ("runtime operation wait expired" ,8 )): 254code ,timed_out = self ._cli ("run" ,"restart" ) 255self .assertEqual (code ,8 ) 256self .assertFalse (timed_out ["ok" ]) 257newest = journal .list_runs ("local" )[0 ] 258uncertain = journal .load ("local" ,newest ["operation_id" ]) 259self .assertEqual (uncertain ["state" ],"completion_unknown" ) 260self .assertEqual (uncertain ["result" ]["exit_code" ],8 ) 261with mock .patch ("strata_control.runtime.restart" ,side_effect = KeyboardInterrupt ): 262code ,interrupted = self ._cli ("run" ,"restart" ) 263self .assertEqual (code ,130 ) 264self .assertFalse (interrupted ["ok" ]) 265newest = journal .list_runs ("local" )[0 ] 266self .assertEqual (journal .load ("local" ,newest ["operation_id" ])["state" ],"completion_unknown" ) 267 268def test_broken_machine_output_detaches_without_reporting_local_file_failure (self ): 269recipes .initialize ("local" ) 270 271class ClosedPipe (io .StringIO ): 272def write (self ,text ): 273raise BrokenPipeError ("consumer closed" ) 274 275with redirect_stdout (ClosedPipe ()): 276self .assertEqual (main (["ops" ,"list" ,"--profile" ,"local" ,"--output" ,"json" ]),0 ) 277 278def test_journal_prunes_old_terminal_records_but_not_running_work (self ): 279recipes .initialize ("local" ) 280with mock .patch .object (journal ,"MAX_RECORDS" ,2 ): 281ids = [] 282for _ in range (3 ): 283code ,executed = self ._cli ("run" ,"check" ) 284self .assertEqual (code ,0 ) 285ids .append (executed ["operation" ]["operation_id" ]) 286self .assertEqual (len (journal .list_runs ("local" )),2 ) 287with self .assertRaisesRegex (profiles .ProfileError ,"not found" ): 288journal .load ("local" ,ids [0 ]) 289# Two unfinished records exhaust the cap; neither may be discarded. 290directory = profiles .profile_dir ()/ ".ops" / "local" / ".runs" 291for path in directory .glob ("*.json" ): 292path .unlink () 293first = journal .begin ("local" ,"check" ,"components.verify" ,"0" * 16 ,"0" * 16 ) 294second = journal .begin ("local" ,"check" ,"components.verify" ,"0" * 16 ,"0" * 16 ) 295with self .assertRaisesRegex (profiles .ProfileError ,"journal is full" ): 296journal .begin ("local" ,"check" ,"components.verify" ,"0" * 16 ,"0" * 16 ) 297self .assertEqual (journal .load ("local" ,first ["operation_id" ])["state" ],"running" ) 298self .assertTrue (journal .load ("local" ,first ["operation_id" ])["completion_unverified" ]) 299self .assertEqual (journal .load ("local" ,second ["operation_id" ])["state" ],"running" ) 300 301def test_invalid_journal_event_is_reported_without_rendering_record_content (self ): 302recipes .initialize ("local" ) 303operation_id = self ._cli ("run" ,"check" )[1 ]["operation" ]["operation_id" ] 304path = profiles .profile_dir ()/ ".ops" / "local" / ".runs" / f" { operation_id } .json" 305record = json .loads (path .read_text ()) 306record ["events" ][- 1 ]["state" ]= "\x1b[31mforged\x1b[0m" 307path .write_text (json .dumps (record )) 308with self .assertRaisesRegex (profiles .ProfileError ,"invalid events" ): 309journal .load ("local" ,operation_id ) 310code ,listed = self ._cli ("runs" ) 311self .assertEqual (code ,0 ) 312self .assertIn ("error" ,listed ["runs" ][0 ]) 313self .assertNotIn ("forged" ,json .dumps (listed )) 314 315def test_direct_journal_is_typed_compact_and_keeps_uncertain_interruptions (self ): 316revision = profiles .load ("local" )[1 ] 317operation_id ,result = journal .run_direct ("local" ,"runtime.restart" ,revision , 318 {"wait_s" :20 ,"startup_wait_s" :10 ,"expected_profile_revision" :revision }, 319lambda : {"ok" :False ,"state" :"ready" ,"error" :"activation_failed" ,"exit_code" :6 , 320"private_trace" :"TOPSECRET" }) 321self .assertFalse (result ["ok" ]) 322record = journal .load ("local" ,operation_id ) 323self .assertEqual (record ["schema_version" ],2 ) 324self .assertEqual (record ["origin" ],"direct" ) 325self .assertEqual (record ["state" ],"failed" ) 326self .assertNotIn ("TOPSECRET" ,json .dumps (record )) 327deadline_id ,_ = journal .run_direct ("local" ,"runtime.stop" ,revision , {"wait_s" :12 }, 328lambda : {"ok" :False ,"state" :"stopping" ,"exit_code" :8 }) 329self .assertEqual (journal .load ("local" ,deadline_id )["state" ],"completion_unknown" ) 330with self .assertRaises (KeyboardInterrupt ): 331journal .run_direct ("local" ,"runtime.stop" ,revision , {"wait_s" :12 }, 332lambda : (_ for _ in ()).throw (KeyboardInterrupt ())) 333# the interrupted run is the one that is neither of the two above (list_runs orders by file time, and three runs written 334# within one tick of a coarse Windows clock come back in any order) 335latest = next (r for r in journal .list_runs ("local" )if r ["operation_id" ]not in (operation_id ,deadline_id )) 336uncertain = journal .load ("local" ,latest ["operation_id" ]) 337self .assertEqual (uncertain ["state" ],"completion_unknown" ) 338with self .assertRaisesRegex (profiles .ProfileError ,"unsupported fields" ): 339journal .begin_direct ("local" ,"runtime.stop" ,revision , 340 {"wait_s" :12 ,"shell" :"rm -rf /" }) 341self .assertEqual (len (journal .list_runs ("local" )),3 ) 342 343def test_direct_journal_rejects_tampered_origin (self ): 344revision = profiles .load ("local" )[1 ] 345record = journal .begin_direct ("local" ,"runtime.stop" ,revision , {"wait_s" :12 }) 346path = profiles .profile_dir ()/ ".ops" / "local" / ".runs" / f" { record [ 'operation_id' ] } .json" 347forged = json .loads (path .read_text ()) 348forged ["origin" ]= "remote" 349path .write_text (json .dumps (forged )) 350with self .assertRaisesRegex (profiles .ProfileError ,"unsupported intent" ): 351journal .load ("local" ,record ["operation_id" ]) 352 353 354if __name__ == "__main__" : 355unittest .main ()