okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
48fc04a42
main
1"""Tuning history tests (checklist T06). 2 3The requirement is that an engine, model, driver, workload or context change invalidates incompatible 4history, and that model identity is more than a name. The risk being tested is specific and quiet: a 5report that mixes two configurations' numbers produces a confident recommendation from incomparable 6measurements, and nothing about the output looks wrong. 7 8So each element of the comparison key gets its own test, and the *reason* is asserted, not just the 9boolean — a report has to be able to say "the model changed", not merely "no". 10""" 11 12from __future__import annotations 13 14import sys 15import tempfile 16import textwrap 17import unittest 18from pathlib import Path 19 20sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 21 22from strata_control import tune_history as th # noqa: E402 23 24 25class HistoryCase (unittest .TestCase ): 26def setUp (self ): 27self .tmp = Path (tempfile .mkdtemp (prefix = "strata-history-" )) 28 29def tearDown (self ): 30import shutil 31shutil .rmtree (self .tmp ,ignore_errors = True ) 32 33def store (self )-> th .HistoryStore : 34return th .HistoryStore (self .tmp / "history" ) 35 36def file (self ,name :str ,content :bytes )-> Path : 37p = self .tmp / name 38p .write_bytes (content ) 39return p 40 41def key (self ,** over ): 42base = th .comparison_key ( 43engine = {"digest" :"e" * 64 ,"bytes" :100 ,"exists" :True ,"method" :th .FULL ,"path" :"/e" }, 44model = {"digest" :"m" * 64 ,"bytes" :200 ,"exists" :True ,"method" :th .SAMPLED ,"path" :"/m" }, 45backend = "metal" , 46workload = {"prompt_tokens" :512 ,"max_new" :128 ,"seed" :1 ,"temperature" :0.0 }, 47context = 32768 , 48machine = {"system" :"Darwin" ,"machine" :"arm64" ,"cpu_count" :10 }, 49 ) 50base .update (over ) 51return base 52 53 54class TestFileIdentity (HistoryCase ): 55"""Identity is a content hash, not a label.""" 56 57def test_a_different_file_with_the_same_name_is_a_different_identity (self ): 58"""The whole point: a re-quantised model keeps its name and changes its behaviour.""" 59a = self .file ("model.gguf" ,b"x" * 5000 ) 60first = th .file_identity (a )["digest" ] 61a .write_bytes (b"y" * 5000 )# same path, same size, different bytes 62self .assertNotEqual (th .file_identity (a )["digest" ],first ) 63 64def test_a_truncated_file_is_a_different_identity (self ): 65a = self .file ("model.gguf" ,b"x" * 5000 ) 66full = th .file_identity (a ,full = True )["digest" ] 67a .write_bytes (b"x" * 4000 ) 68self .assertNotEqual (th .file_identity (a ,full = True )["digest" ],full ) 69 70def test_the_identity_method_travels_with_the_digest (self ): 71a = self .file ("model.gguf" ,b"x" * 5000 ) 72self .assertEqual (th .file_identity (a )["method" ],th .SAMPLED ) 73self .assertEqual (th .file_identity (a ,full = True )["method" ],th .FULL ) 74 75def test_a_large_file_is_sampled_without_reading_all_of_it (self ): 76# The point of sampling is cost. This asserts the digest does not depend on every byte, so a 77# change strictly between the sampled regions is (correctly) not claimed as detection. 78big = self .tmp / "big.gguf" 79with big .open ("wb" )as fh : 80fh .write (b"a" * th .SAMPLE_BYTES ) 81fh .write (b"b" * (4 * th .SAMPLE_BYTES ))# middle lands here 82fh .write (b"c" * th .SAMPLE_BYTES ) 83first = th .file_identity (big ) 84self .assertEqual (first ["bytes" ],6 * th .SAMPLE_BYTES ) 85self .assertIsNotNone (first ["digest" ]) 86 87def test_a_missing_file_is_explicitly_absent_rather_than_hashed_as_empty (self ): 88ident = th .file_identity (self .tmp / "nope" ) 89self .assertFalse (ident ["exists" ]) 90self .assertIsNone (ident ["digest" ]) 91self .assertIsNone (ident ["method" ]) 92 93 94class TestComparisonKey (HistoryCase ): 95"""Every element that makes two measurements incomparable is in the key.""" 96 97def test_each_element_produces_its_own_reason (self ): 98base = self .key () 99cases = { 100"engine_digest" :"a different engine build" , 101"model_digest" :"different model bytes" , 102"backend" :"a different backend" , 103"workload" :"a different workload" , 104"context" :"a different context" , 105"machine" :"a different machine or driver" , 106 } 107for field ,expected in cases .items (): 108other = dict (base ) 109other [field ]= "changed" if not isinstance (base [field ], (dict ,int ))else 1 110reasons = th .incomparable_reasons (base ,other ) 111self .assertTrue (reasons ,f" { field } must make the records incomparable" ) 112self .assertTrue (any (expected in r for r in reasons ), 113f" { field } : expected a reason mentioning { expected !r } , got { reasons } " ) 114 115def test_a_different_digest_method_is_incomparable (self ): 116"""Two records hashed differently cannot be compared as though they were the same.""" 117base = self .key () 118other = dict (base ,digest_method = th .FULL ) 119reasons = th .incomparable_reasons (base ,other ) 120self .assertTrue (any ("computed differently" in r for r in reasons ),reasons ) 121 122def test_an_unknown_identity_is_not_treated_as_equal (self ): 123"""An unknown is not evidence of sameness.""" 124known = self .key () 125unknown = self .key (model_digest = None ) 126self .assertTrue (th .incomparable_reasons (known ,unknown )) 127 128def test_identical_keys_are_comparable (self ): 129self .assertEqual (th .incomparable_reasons (self .key (),self .key ()), []) 130 131def test_a_different_hostname_is_the_same_machine (self ): 132"""A renamed machine is the same machine; the hostname is deliberately not in the key.""" 133self .assertNotIn ("node" ,th .machine_identity ()) 134self .assertNotIn ("hostname" ,th .machine_identity ()) 135 136 137class TestHistoryStore (HistoryCase ): 138def test_a_recorded_sweep_is_comparable_to_itself (self ): 139store = self .store () 140store .record (key = self .key (),outcome = "accepted" ,recommendation_args = {"--kv" :"int8" }, 141median = 24.0 ,baseline_median = 20.0 ,trials_run = 4 ,combinations_total = 4 ) 142usable ,unusable = store .comparable (self .key ()) 143self .assertEqual (len (usable ),1 ) 144self .assertEqual (usable [0 ].recommendation_args , {"--kv" :"int8" }) 145self .assertEqual (unusable , []) 146 147def test_a_changed_model_makes_the_history_incomparable_with_a_reason (self ): 148store = self .store () 149store .record (key = self .key (),outcome = "accepted" ) 150changed = self .key (model_digest = "z" * 64 ) 151usable ,unusable = store .comparable (changed ) 152self .assertEqual (usable , [],"a different model's numbers must not be reused" ) 153self .assertEqual (len (unusable ),1 ) 154self .assertIn ("different model bytes" ,unusable [0 ]["reasons" ]) 155 156def test_a_changed_engine_makes_the_history_incomparable (self ): 157store = self .store () 158store .record (key = self .key (),outcome = "accepted" ) 159usable ,unusable = store .comparable (self .key (engine_digest = "d" * 64 )) 160self .assertEqual (usable , []) 161self .assertIn ("a different engine build" ,unusable [0 ]["reasons" ]) 162 163def test_a_changed_context_makes_the_history_incomparable (self ): 164store = self .store () 165store .record (key = self .key (),outcome = "accepted" ) 166usable ,_ = store .comparable (self .key (context = 131072 )) 167self .assertEqual (usable , [],"a different context is a different measurement" ) 168 169def test_a_changed_workload_makes_the_history_incomparable (self ): 170store = self .store () 171store .record (key = self .key (),outcome = "accepted" ) 172usable ,_ = store .comparable (self .key ( 173workload = {"prompt_tokens" :1024 ,"max_new" :128 ,"seed" :1 ,"temperature" :0.0 })) 174self .assertEqual (usable , []) 175 176def test_incomparable_history_is_retained_not_deleted (self ): 177"""A previous sweep may still answer a question, so the store does not discard it.""" 178store = self .store () 179store .record (key = self .key (),outcome = "accepted" ) 180store .record (key = self .key (model_digest = "z" * 64 ),outcome = "accepted" ) 181usable ,unusable = store .comparable (self .key ()) 182self .assertEqual (len (usable ),1 ) 183self .assertEqual (len (unusable ),1 ) 184self .assertEqual (len (store .records ()),2 ,"both records are still there" ) 185 186def test_a_damaged_line_is_skipped_rather_than_fatal (self ): 187"""The store is a text file a human may have edited; one bad line must not lose the rest.""" 188store = self .store () 189store .record (key = self .key (),outcome = "accepted" ) 190with store .index .open ("a" ,encoding = "utf-8" )as fh : 191fh .write ("{ this is not json\n" ) 192store .record (key = self .key (),outcome = "inconclusive" ) 193records = store .records () 194self .assertEqual (len (records ),2 ) 195self .assertEqual ([r .outcome for r in records ], ["accepted" ,"inconclusive" ]) 196 197def test_a_record_from_another_schema_version_is_ignored (self ): 198store = self .store () 199store .root .mkdir (parents = True ,exist_ok = True ) 200store .index .write_text ('{"schema_version": 99, "id": "old", "recorded_at": 1, "key": {}}\n' , 201encoding = "utf-8" ) 202self .assertEqual (store .records (), []) 203 204def test_the_summary_says_what_the_numbers_sit_next_to (self ): 205store = self .store () 206empty = th .summarise_history (store ,self .key ()) 207self .assertEqual (empty ["comparable_records" ],0 ) 208self .assertIn ("no earlier sweep" ,empty ["note" ]) 209 210store .record (key = self .key (),outcome = "accepted" ) 211store .record (key = self .key (model_digest = "z" * 64 ),outcome = "accepted" ) 212summary = th .summarise_history (store ,self .key ()) 213self .assertEqual (summary ["comparable_records" ],1 ) 214self .assertEqual (summary ["incomparable_records" ],1 ) 215self .assertTrue (summary ["incomparable" ][0 ]["reasons" ]) 216self .assertIn ("this exact engine" ,summary ["note" ]) 217 218 219class TestPlanCarriesIdentity (HistoryCase ): 220"""The plan records what it measured, so a later sweep can compare without re-deriving it.""" 221 222def test_plan_tuning_records_a_content_identity (self ): 223from strata_control import tuning 224engine = self .file ("strata" ,b"#!/bin/sh\necho 'x' >&2\n" ) 225model = self .file ("model.gguf" ,b"weights" * 1000 ) 226plan = tuning .plan_tuning ( 227engine ,"metal" ,"fixture" ,"generation" , 228 {"prompt_tokens" :16 ,"max_new" :4 ,"seed" :1 ,"temperature" :0.0 }, 229hold = ("ple_io" ,"kv" ,"kv_grow" ,"spec_min_p" ),model_path = model ,context = 32768 ) 230ident = plan .identity 231self .assertEqual (ident ["backend" ],"metal" ) 232self .assertEqual (ident ["context" ],32768 ) 233self .assertIsNotNone (ident ["engine_digest" ]) 234self .assertIsNotNone (ident ["model_digest" ]) 235self .assertEqual (ident ["model_bytes" ],len (b"weights" * 1000 )) 236 237def test_a_plan_without_a_model_path_is_incomparable_rather_than_falsely_comparable (self ): 238"""Not knowing the weights must be recorded as unknown, not as a match.""" 239from strata_control import tuning 240engine = self .file ("strata" ,b"#!/bin/sh\necho 'x' >&2\n" ) 241plan = tuning .plan_tuning ( 242engine ,"metal" ,"fixture" ,"generation" , 243 {"prompt_tokens" :16 ,"max_new" :4 ,"seed" :1 ,"temperature" :0.0 }, 244hold = ("ple_io" ,"kv" ,"kv_grow" ,"spec_min_p" )) 245self .assertIsNone (plan .identity ["model_digest" ]) 246# And such a key matches nothing, including another key with the same unknown model. 247other = dict (plan .identity ) 248self .assertTrue (th .incomparable_reasons (plan .identity ,other )== [], 249"two records with the same unknowns are consistently comparable to each other" ) 250self .assertTrue (th .incomparable_reasons ( 251plan .identity ,dict (plan .identity ,model_digest = "m" * 64 ))) 252 253 254if __name__ == "__main__" : 255unittest .main ()