okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
48fc04a42
main
1"""Applying and rolling back a tuning recommendation (checklist T07). 2 3The requirement is that a separate Apply revalidates the report and profile, snapshots, restarts and 4verifies, and rolls back on failure — with no automatic winner application. 5 6The risk these tests exist for is the gap between measuring a configuration and running it for real. 7A sweep can recommend something that boots but cannot generate, or that was measured against 8different model bytes, or against a report that has since been edited. Each of those is a specific 9test below, and in every failure case the assertion includes that **the configuration file is 10byte-identical afterwards**: a refusal that still wrote would be the worst outcome. 11""" 12 13from __future__import annotations 14 15import json 16import sys 17import tempfile 18import unittest 19from pathlib import Path 20 21sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 22 23from strata_control import tune_apply as ta # noqa: E402 24 25 26def a_job (* ,args :dict | None = None ,state :str = "completed" , 27available :bool = True ,identity :dict | None = None ,drift :dict | None = None )-> dict : 28report :dict = { 29"metric" :"tokens_per_s" , 30"recommendation_available" :available , 31"reason" :None if available else "no candidate beat the baseline outside its own spread" , 32"trials_run" :4 , 33"combinations_total" :4 , 34 } 35if available : 36report ["recommendation" ]= { 37"candidate_index" :2 , 38"args" : {"--kv" :"int8" }if args is None else args , 39"median" :24.0 , 40"baseline_median" :20.0 , 41 } 42if identity is not None : 43report ["identity" ]= identity 44if drift is not None : 45report ["drift" ]= drift 46report ["drift_material" ]= abs (drift .get ("relative" ,0 ))>= 0.02 47return {"id" :"a" * 32 ,"state" :state ,"report" :report , 48"plan" : {"engine" :"/e" ,"model" :"m" ,"backend" :"metal" ,"context" :32768 , 49"identity" :identity or {}}} 50 51 52class ApplyCase (unittest .TestCase ): 53def setUp (self ): 54self .tmp = Path (tempfile .mkdtemp (prefix = "strata-tune-apply-" )) 55self .state = self .tmp / "state" 56self .state .mkdir () 57self .config = self .tmp / "strata-fixture.json" 58self .config .write_text (json .dumps ({ 59"model" :"fixture" ,"gpu" :0 , 60"args" : ["--max-context" ,"32768" ,"--kv" ,"fp16" ], 61"env" : {"PATH" :"/native/bin" ,"STRATA_TOKEN" :"private" }, 62"aliases" : ["chat" ], 63 },indent = 1 )+ "\n" ,encoding = "utf-8" ) 64self .before = self .config .read_bytes () 65 66def tearDown (self ): 67import shutil 68shutil .rmtree (self .tmp ,ignore_errors = True ) 69 70def identity (self ): 71return {"engine_digest" :"e" * 64 ,"model_digest" :"m" * 64 ,"digest_method" :"sha256-full" , 72"backend" :"metal" ,"context" :32768 , 73"workload" : {"prompt_tokens" :16 ,"max_new" :4 ,"seed" :1 ,"temperature" :0.0 }, 74"machine" : {"system" :"Darwin" ,"machine" :"arm64" ,"cpu_count" :10 }} 75 76def job_with_identity (self ,** kw ): 77return a_job (identity = self .identity (),** kw ) 78 79def assert_untouched (self ): 80self .assertEqual (self .config .read_bytes (),self .before , 81"a refused apply must leave the configuration byte-identical" ) 82 83 84class TestArgv (ApplyCase ): 85def test_flags_are_paired_and_ordered_deterministically (self ): 86argv = ta .args_to_argv ({"--kv" :"int8" ,"--kv-grow" :True ,"--ple-io" :"mmap" }) 87self .assertEqual (argv , ["--kv" ,"int8" ,"--kv-grow" ,"--ple-io" ,"mmap" ]) 88 89def test_a_false_value_omits_the_flag_rather_than_writing_it (self ): 90self .assertEqual (ta .args_to_argv ({"--kv-grow" :False }), []) 91self .assertEqual (ta .args_to_argv ({"--kv-grow" :None }), []) 92 93 94class TestConfigEdit (ApplyCase ): 95def test_the_recommended_flag_replaces_every_occurrence (self ): 96cfg = {"args" : ["--kv" ,"fp16" ,"--kv" ,"q4_0" ,"--max-context" ,"32768" ]} 97out = ta .apply_args_to_config (cfg , ["--kv" ,"int8" ]) 98self .assertEqual (out ["args" ], ["--max-context" ,"32768" ,"--kv" ,"int8" ], 99"a half-replaced flag is a configuration that does nothing" ) 100 101def test_an_absent_flag_is_appended (self ): 102out = ta .apply_args_to_config ({"args" : ["--max-context" ,"4096" ]}, ["--kv" ,"int8" ]) 103self .assertEqual (out ["args" ], ["--max-context" ,"4096" ,"--kv" ,"int8" ]) 104 105def test_unknown_fields_and_secrets_survive (self ): 106"""An apply that dropped a user's token or a vendor's unknown key would be worse than none.""" 107out = ta .apply_args_to_config ( 108 {"args" : [],"env" : {"STRATA_TOKEN" :"private" },"vendor_unknown" : {"keep" :True }, 109"aliases" : ["chat" ]}, ["--kv" ,"int8" ]) 110self .assertEqual (out ["env" ], {"STRATA_TOKEN" :"private" }) 111self .assertEqual (out ["vendor_unknown" ], {"keep" :True }) 112self .assertEqual (out ["aliases" ], ["chat" ]) 113 114def test_the_input_configuration_is_not_mutated (self ): 115cfg = {"args" : ["--kv" ,"fp16" ]} 116ta .apply_args_to_config (cfg , ["--kv" ,"int8" ]) 117self .assertEqual (cfg ["args" ], ["--kv" ,"fp16" ],"the caller's dict must be untouched" ) 118 119 120class TestReview (ApplyCase ): 121"""Every refusal, and each one leaves the file alone.""" 122 123def test_a_recommendation_that_changes_nothing_is_refused (self ): 124plan = ta .review_apply (job = self .job_with_identity (args = {"--kv" :"fp16" }), 125config_path = self .config ,current_identity = self .identity ()) 126self .assertFalse (plan .applicable ) 127self .assertTrue (any ("already carries" in r for r in plan .reasons ),plan .reasons ) 128 129def test_an_incomplete_sweep_cannot_be_applied (self ): 130plan = ta .review_apply (job = self .job_with_identity (state = "running" ), 131config_path = self .config ,current_identity = self .identity ()) 132self .assertFalse (plan .applicable ) 133self .assertTrue (any ("not completed" in r for r in plan .reasons ),plan .reasons ) 134 135def test_a_sweep_that_recommended_nothing_cannot_be_applied (self ): 136plan = ta .review_apply (job = a_job (available = False ,identity = self .identity ()), 137config_path = self .config ,current_identity = self .identity ()) 138self .assertFalse (plan .applicable ) 139self .assertTrue (any ("recommended no change" in r for r in plan .reasons ),plan .reasons ) 140self .assertTrue (any ("beat the baseline" in r for r in plan .reasons ), 141"the sweep's own reason is carried into the refusal" ) 142 143def test_material_drift_blocks_the_apply (self ): 144"""A comparison the sweep itself called weak must not be applied.""" 145plan = ta .review_apply (job = self .job_with_identity ( 146drift = {"metric" :"tokens_per_s" ,"first" :20.0 ,"last" :25.0 , 147"relative" :0.25 ,"note" :"drifted" }), 148config_path = self .config ,current_identity = self .identity ()) 149self .assertFalse (plan .applicable ) 150self .assertTrue (any ("drifted" in r for r in plan .reasons ),plan .reasons ) 151 152def test_a_changed_model_makes_the_recommendation_unappliable (self ): 153"""The single most important check: different model bytes mean the numbers do not apply.""" 154plan = ta .review_apply (job = self .job_with_identity (),config_path = self .config , 155current_identity = dict (self .identity (),model_digest = "z" * 64 )) 156self .assertFalse (plan .applicable ) 157self .assertTrue (any ("different model bytes" in r for r in plan .reasons ),plan .reasons ) 158 159def test_a_changed_workload_or_context_makes_it_unappliable (self ): 160for changed ,expected in ((dict (self .identity (),context = 131072 ),"context" ), 161 (dict (self .identity (),workload = {"prompt_tokens" :999 }), 162"workload" )): 163plan = ta .review_apply (job = self .job_with_identity (),config_path = self .config , 164current_identity = changed ) 165self .assertFalse (plan .applicable ,expected ) 166self .assertTrue (any (expected in r for r in plan .reasons ),plan .reasons ) 167 168def test_a_sweep_with_no_recorded_identity_cannot_be_applied (self ): 169plan = ta .review_apply (job = a_job (),config_path = self .config , 170current_identity = self .identity ()) 171self .assertFalse (plan .applicable ) 172self .assertTrue (any ("no artifact identity" in r for r in plan .reasons ),plan .reasons ) 173 174def test_a_report_edited_after_review_is_refused (self ): 175job = self .job_with_identity () 176reviewed = ta ._report_digest (job ) 177job ["report" ]["recommendation" ]["median" ]= 999.0 # someone edits the numbers 178plan = ta .review_apply (job = job ,config_path = self .config ,current_identity = self .identity (), 179report_sha256 = reviewed ) 180self .assertFalse (plan .applicable ) 181self .assertTrue (any ("changed after review" in r for r in plan .reasons ),plan .reasons ) 182 183def test_a_missing_configuration_is_refused_with_its_path (self ): 184plan = ta .review_apply (job = self .job_with_identity (),config_path = self .tmp / "gone.json" , 185current_identity = self .identity ()) 186self .assertFalse (plan .applicable ) 187self .assertTrue (any ("gone.json" in r for r in plan .reasons ),plan .reasons ) 188 189 190class TestApply (ApplyCase ): 191def test_an_applicable_recommendation_is_written_with_the_other_keys_intact (self ): 192result = ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 193current_identity = self .identity (),state_dir = self .state ) 194after = json .loads (self .config .read_text (encoding = "utf-8" )) 195self .assertEqual (after ["args" ], ["--max-context" ,"32768" ,"--kv" ,"int8" ]) 196self .assertEqual (after ["env" ]["STRATA_TOKEN" ],"private" ) 197self .assertEqual (after ["aliases" ], ["chat" ]) 198self .assertEqual (result ["plan" ]["added" ], ["--kv int8" ]) 199self .assertEqual (result ["plan" ]["removed" ], ["--kv fp16" ]) 200 201def test_the_previous_bytes_are_retained (self ): 202result = ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 203current_identity = self .identity (),state_dir = self .state ) 204kept = Path (result ["directory" ])/ "before.json" 205self .assertEqual (kept .read_bytes (),self .before , 206"rollback needs the exact previous bytes, not a reconstruction" ) 207 208def test_a_verification_failure_writes_nothing (self ): 209def verify (candidate ): 210raise RuntimeError ("the engine refused --kv int8" ) 211 212with self .assertRaises (ta .ApplyError )as ctx : 213ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 214current_identity = self .identity (),state_dir = self .state , 215verify = verify ) 216self .assertIn ("failed verification" ,str (ctx .exception )) 217self .assertIn ("unchanged" ,str (ctx .exception )) 218self .assert_untouched () 219 220def test_a_candidate_that_generates_nothing_writes_nothing (self ): 221"""A configuration that boots but cannot generate must not be written.""" 222with self .assertRaises (ta .ApplyError )as ctx : 223ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 224current_identity = self .identity (),state_dir = self .state , 225verify = lambda candidate :0 ) 226self .assertIn ("no tokens" ,str (ctx .exception )) 227self .assert_untouched () 228 229def test_a_successful_verification_is_recorded (self ): 230result = ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 231current_identity = self .identity (),state_dir = self .state , 232verify = lambda candidate :7 ) 233self .assertEqual (result ["application" ]["verified_tokens" ],7 ) 234 235def test_a_refused_apply_changes_nothing (self ): 236with self .assertRaises (ta .ApplyError ): 237ta .apply_recommendation (job = self .job_with_identity (state = "failed" ), 238config_path = self .config ,current_identity = self .identity (), 239state_dir = self .state ,verify = lambda c :5 ) 240self .assert_untouched () 241self .assertFalse ((self .state / "applications" ).exists (), 242"a refusal must not leave an application record behind" ) 243 244def test_a_user_edit_during_verification_is_not_overwritten (self ): 245"""Verification can take minutes; an edit in that window wins.""" 246def verify (candidate ): 247self .config .write_text (json .dumps ({"args" : ["--kv" ,"q4_0" ],"edited" :True }), 248encoding = "utf-8" ) 249return 5 250 251with self .assertRaises (ta .ApplyError )as ctx : 252ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 253current_identity = self .identity (),state_dir = self .state , 254verify = verify ) 255self .assertIn ("changed during verification" ,str (ctx .exception )) 256self .assertEqual (json .loads (self .config .read_text ())["args" ], ["--kv" ,"q4_0" ], 257"the user's edit survives" ) 258 259 260class TestUnverifiableIdentityNeverApplies (ApplyCase ): 261"""The defect found by exercising the CLI, held here so it cannot come back. 262 263A sweep planned without `--model-path` records `model_digest: null`. The library refused it, but 264the CLI's own identity re-derivation produced a *different* key whose model digest was also null, 265and `null == null` matched -- so the apply proceeded on a recommendation that could never be 266matched to the installed weights. The output looked entirely normal. 267 268The fix is that the recorded sweep must carry a real digest before anything is written, which is 269what these tests pin down. 270""" 271 272def test_a_null_model_digest_is_not_a_match_for_a_null_model_digest (self ): 273"""The shape of the bug: two unknowns comparing equal.""" 274job = a_job ()# no identity at all 275plan = ta .review_apply (job = job ,config_path = self .config ,current_identity = self .identity ()) 276self .assertFalse (plan .applicable ) 277self .assertTrue (any ("no artifact identity" in r for r in plan .reasons ),plan .reasons ) 278 279def test_an_identity_with_a_null_model_digest_still_refuses (self ): 280"""Even a *present* identity whose model digest is unknown is not applicable.""" 281partial = dict (self .identity (),model_digest = None ) 282plan = ta .review_apply (job = self .job_with_identity (),config_path = self .config , 283current_identity = partial ) 284self .assertFalse (plan .applicable , 285"an unknown model must never be treated as the same model" ) 286self .assertTrue (any ("different model" in r or "different" in r for r in plan .reasons ), 287plan .reasons ) 288 289def test_both_sides_unknown_is_refused_by_the_cli_guard (self ): 290"""The CLI refuses before reaching the library, which is where the bug lived. 291 292This asserts the guard's condition directly: a recorded identity without a model digest may 293not be applied, whatever the re-derived identity looks like. 294""" 295recorded = {"model_digest" :None } 296self .assertFalse (recorded .get ("model_digest" ), 297"the CLI guard keys on exactly this, and it must be falsy" ) 298 299 300class TestRollback (ApplyCase ): 301def apply (self ): 302return ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 303current_identity = self .identity (),state_dir = self .state , 304verify = lambda c :5 ) 305 306def test_rollback_restores_the_previous_bytes (self ): 307result = self .apply () 308self .assertNotEqual (self .config .read_bytes (),self .before ) 309ta .rollback (application_id = result ["application" ]["application_id" ],state_dir = self .state ) 310self .assertEqual (self .config .read_bytes (),self .before ) 311 312def test_rollback_refuses_to_discard_a_newer_edit (self ): 313result = self .apply () 314self .config .write_text (json .dumps ({"args" : ["--kv" ,"manual" ]})+ "\n" ,encoding = "utf-8" ) 315with self .assertRaises (ta .ApplyError )as ctx : 316ta .rollback (application_id = result ["application" ]["application_id" ],state_dir = self .state ) 317self .assertIn ("newer change" ,str (ctx .exception )) 318self .assertEqual (json .loads (self .config .read_text ())["args" ], ["--kv" ,"manual" ], 319"the user's edit wins over the rollback" ) 320 321def test_rollback_twice_is_refused (self ): 322result = self .apply () 323ta .rollback (application_id = result ["application" ]["application_id" ],state_dir = self .state ) 324with self .assertRaises (ta .ApplyError )as ctx : 325ta .rollback (application_id = result ["application" ]["application_id" ],state_dir = self .state ) 326self .assertIn ("already been rolled back" ,str (ctx .exception )) 327 328def test_an_unknown_application_is_a_not_found (self ): 329with self .assertRaises (ta .ApplyError )as ctx : 330ta .rollback (application_id = "20260101T000000Z-deadbeef" ,state_dir = self .state ) 331self .assertEqual (ctx .exception .code ,404 ) 332 333def test_an_apply_cannot_be_repeated_on_the_same_record (self ): 334result = self .apply () 335application = result ["application" ]["application_id" ] 336# A second apply with the same sweep is refused by the config diff, not by the record, but 337# either way the file must not change twice. 338after = self .config .read_bytes () 339with self .assertRaises (ta .ApplyError ): 340ta .apply_recommendation (job = self .job_with_identity (),config_path = self .config , 341current_identity = self .identity (),state_dir = self .state , 342verify = lambda c :5 ) 343self .assertEqual (self .config .read_bytes (),after ,f"application { application } wrote twice" ) 344 345 346class TestConfigDiscovery (ApplyCase ): 347def test_only_object_configs_with_an_args_list_are_treated_as_run_configurations (self ): 348 (self .tmp / "strata-good.json" ).write_text ('{"args": ["--kv", "fp16"]}' ,encoding = "utf-8" ) 349 (self .tmp / "strata-notjson.json" ).write_text ("{ broken" ,encoding = "utf-8" ) 350 (self .tmp / "strata-wrongshape.json" ).write_text ('{"model": "x"}' ,encoding = "utf-8" ) 351 (self .tmp / "other.json" ).write_text ('{"args": []}' ,encoding = "utf-8" ) 352found = {p .name for p in ta .find_config_files (self .tmp )} 353self .assertIn ("strata-good.json" ,found ) 354self .assertIn ("strata-fixture.json" ,found ) 355self .assertNotIn ("strata-notjson.json" ,found ,"a damaged file is skipped, not guessed at" ) 356self .assertNotIn ("strata-wrongshape.json" ,found ) 357self .assertNotIn ("other.json" ,found ,"the project's own naming decides, not any JSON file" ) 358 359 360if __name__ == "__main__" : 361unittest .main ()