okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221tuning: job contract, history, apply/rollback and the real-API measurement harness48fc04a42

main
11.7 KiB255 linesraw
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):
26    def setUp(self):
27        self.tmp = Path(tempfile.mkdtemp(prefix="strata-history-"))
28
29    def tearDown(self):
30        import shutil
31        shutil.rmtree(self.tmp, ignore_errors=True)
32
33    def store(self) -> th.HistoryStore:
34        return th.HistoryStore(self.tmp / "history")
35
36    def file(self, name: str, content: bytes) -> Path:
37        p = self.tmp / name
38        p.write_bytes(content)
39        return p
40
41    def key(self, **over):
42        base = th.comparison_key(
43            engine={"digest": "e" * 64, "bytes": 100, "exists": True, "method": th.FULL, "path": "/e"},
44            model={"digest": "m" * 64, "bytes": 200, "exists": True, "method": th.SAMPLED, "path": "/m"},
45            backend="metal",
46            workload={"prompt_tokens": 512, "max_new": 128, "seed": 1, "temperature": 0.0},
47            context=32768,
48            machine={"system": "Darwin", "machine": "arm64", "cpu_count": 10},
49        )
50        base.update(over)
51        return base
52
53
54class TestFileIdentity(HistoryCase):
55    """Identity is a content hash, not a label."""
56
57    def 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."""
59        a = self.file("model.gguf", b"x" * 5000)
60        first = th.file_identity(a)["digest"]
61        a.write_bytes(b"y" * 5000)          # same path, same size, different bytes
62        self.assertNotEqual(th.file_identity(a)["digest"], first)
63
64    def test_a_truncated_file_is_a_different_identity(self):
65        a = self.file("model.gguf", b"x" * 5000)
66        full = th.file_identity(a, full=True)["digest"]
67        a.write_bytes(b"x" * 4000)
68        self.assertNotEqual(th.file_identity(a, full=True)["digest"], full)
69
70    def test_the_identity_method_travels_with_the_digest(self):
71        a = self.file("model.gguf", b"x" * 5000)
72        self.assertEqual(th.file_identity(a)["method"], th.SAMPLED)
73        self.assertEqual(th.file_identity(a, full=True)["method"], th.FULL)
74
75    def 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.
78        big = self.tmp / "big.gguf"
79        with big.open("wb") as fh:
80            fh.write(b"a" * th.SAMPLE_BYTES)
81            fh.write(b"b" * (4 * th.SAMPLE_BYTES))   # middle lands here
82            fh.write(b"c" * th.SAMPLE_BYTES)
83        first = th.file_identity(big)
84        self.assertEqual(first["bytes"], 6 * th.SAMPLE_BYTES)
85        self.assertIsNotNone(first["digest"])
86
87    def test_a_missing_file_is_explicitly_absent_rather_than_hashed_as_empty(self):
88        ident = th.file_identity(self.tmp / "nope")
89        self.assertFalse(ident["exists"])
90        self.assertIsNone(ident["digest"])
91        self.assertIsNone(ident["method"])
92
93
94class TestComparisonKey(HistoryCase):
95    """Every element that makes two measurements incomparable is in the key."""
96
97    def test_each_element_produces_its_own_reason(self):
98        base = self.key()
99        cases = {
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        }
107        for field, expected in cases.items():
108            other = dict(base)
109            other[field] = "changed" if not isinstance(base[field], (dict, int)) else 1
110            reasons = th.incomparable_reasons(base, other)
111            self.assertTrue(reasons, f"{field} must make the records incomparable")
112            self.assertTrue(any(expected in r for r in reasons),
113                            f"{field}: expected a reason mentioning {expected!r}, got {reasons}")
114
115    def test_a_different_digest_method_is_incomparable(self):
116        """Two records hashed differently cannot be compared as though they were the same."""
117        base = self.key()
118        other = dict(base, digest_method=th.FULL)
119        reasons = th.incomparable_reasons(base, other)
120        self.assertTrue(any("computed differently" in r for r in reasons), reasons)
121
122    def test_an_unknown_identity_is_not_treated_as_equal(self):
123        """An unknown is not evidence of sameness."""
124        known = self.key()
125        unknown = self.key(model_digest=None)
126        self.assertTrue(th.incomparable_reasons(known, unknown))
127
128    def test_identical_keys_are_comparable(self):
129        self.assertEqual(th.incomparable_reasons(self.key(), self.key()), [])
130
131    def 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."""
133        self.assertNotIn("node", th.machine_identity())
134        self.assertNotIn("hostname", th.machine_identity())
135
136
137class TestHistoryStore(HistoryCase):
138    def test_a_recorded_sweep_is_comparable_to_itself(self):
139        store = self.store()
140        store.record(key=self.key(), outcome="accepted", recommendation_args={"--kv": "int8"},
141                     median=24.0, baseline_median=20.0, trials_run=4, combinations_total=4)
142        usable, unusable = store.comparable(self.key())
143        self.assertEqual(len(usable), 1)
144        self.assertEqual(usable[0].recommendation_args, {"--kv": "int8"})
145        self.assertEqual(unusable, [])
146
147    def test_a_changed_model_makes_the_history_incomparable_with_a_reason(self):
148        store = self.store()
149        store.record(key=self.key(), outcome="accepted")
150        changed = self.key(model_digest="z" * 64)
151        usable, unusable = store.comparable(changed)
152        self.assertEqual(usable, [], "a different model's numbers must not be reused")
153        self.assertEqual(len(unusable), 1)
154        self.assertIn("different model bytes", unusable[0]["reasons"])
155
156    def test_a_changed_engine_makes_the_history_incomparable(self):
157        store = self.store()
158        store.record(key=self.key(), outcome="accepted")
159        usable, unusable = store.comparable(self.key(engine_digest="d" * 64))
160        self.assertEqual(usable, [])
161        self.assertIn("a different engine build", unusable[0]["reasons"])
162
163    def test_a_changed_context_makes_the_history_incomparable(self):
164        store = self.store()
165        store.record(key=self.key(), outcome="accepted")
166        usable, _ = store.comparable(self.key(context=131072))
167        self.assertEqual(usable, [], "a different context is a different measurement")
168
169    def test_a_changed_workload_makes_the_history_incomparable(self):
170        store = self.store()
171        store.record(key=self.key(), outcome="accepted")
172        usable, _ = store.comparable(self.key(
173            workload={"prompt_tokens": 1024, "max_new": 128, "seed": 1, "temperature": 0.0}))
174        self.assertEqual(usable, [])
175
176    def test_incomparable_history_is_retained_not_deleted(self):
177        """A previous sweep may still answer a question, so the store does not discard it."""
178        store = self.store()
179        store.record(key=self.key(), outcome="accepted")
180        store.record(key=self.key(model_digest="z" * 64), outcome="accepted")
181        usable, unusable = store.comparable(self.key())
182        self.assertEqual(len(usable), 1)
183        self.assertEqual(len(unusable), 1)
184        self.assertEqual(len(store.records()), 2, "both records are still there")
185
186    def 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."""
188        store = self.store()
189        store.record(key=self.key(), outcome="accepted")
190        with store.index.open("a", encoding="utf-8") as fh:
191            fh.write("{ this is not json\n")
192        store.record(key=self.key(), outcome="inconclusive")
193        records = store.records()
194        self.assertEqual(len(records), 2)
195        self.assertEqual([r.outcome for r in records], ["accepted", "inconclusive"])
196
197    def test_a_record_from_another_schema_version_is_ignored(self):
198        store = self.store()
199        store.root.mkdir(parents=True, exist_ok=True)
200        store.index.write_text('{"schema_version": 99, "id": "old", "recorded_at": 1, "key": {}}\n',
201                               encoding="utf-8")
202        self.assertEqual(store.records(), [])
203
204    def test_the_summary_says_what_the_numbers_sit_next_to(self):
205        store = self.store()
206        empty = th.summarise_history(store, self.key())
207        self.assertEqual(empty["comparable_records"], 0)
208        self.assertIn("no earlier sweep", empty["note"])
209
210        store.record(key=self.key(), outcome="accepted")
211        store.record(key=self.key(model_digest="z" * 64), outcome="accepted")
212        summary = th.summarise_history(store, self.key())
213        self.assertEqual(summary["comparable_records"], 1)
214        self.assertEqual(summary["incomparable_records"], 1)
215        self.assertTrue(summary["incomparable"][0]["reasons"])
216        self.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
222    def test_plan_tuning_records_a_content_identity(self):
223        from strata_control import tuning
224        engine = self.file("strata", b"#!/bin/sh\necho 'x' >&2\n")
225        model = self.file("model.gguf", b"weights" * 1000)
226        plan = tuning.plan_tuning(
227            engine, "metal", "fixture", "generation",
228            {"prompt_tokens": 16, "max_new": 4, "seed": 1, "temperature": 0.0},
229            hold=("ple_io", "kv", "kv_grow", "spec_min_p"), model_path=model, context=32768)
230        ident = plan.identity
231        self.assertEqual(ident["backend"], "metal")
232        self.assertEqual(ident["context"], 32768)
233        self.assertIsNotNone(ident["engine_digest"])
234        self.assertIsNotNone(ident["model_digest"])
235        self.assertEqual(ident["model_bytes"], len(b"weights" * 1000))
236
237    def 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."""
239        from strata_control import tuning
240        engine = self.file("strata", b"#!/bin/sh\necho 'x' >&2\n")
241        plan = tuning.plan_tuning(
242            engine, "metal", "fixture", "generation",
243            {"prompt_tokens": 16, "max_new": 4, "seed": 1, "temperature": 0.0},
244            hold=("ple_io", "kv", "kv_grow", "spec_min_p"))
245        self.assertIsNone(plan.identity["model_digest"])
246        # And such a key matches nothing, including another key with the same unknown model.
247        other = dict(plan.identity)
248        self.assertTrue(th.incomparable_reasons(plan.identity, other) == [],
249                        "two records with the same unknowns are consistently comparable to each other")
250        self.assertTrue(th.incomparable_reasons(
251            plan.identity, dict(plan.identity, model_digest="m" * 64)))
252
253
254if __name__ == "__main__":
255    unittest.main()