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
18.9 KiB361 linesraw
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",
27          available: bool = True, identity: dict | None = None, drift: dict | None = None) -> dict:
28    report: 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    }
35    if available:
36        report["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        }
42    if identity is not None:
43        report["identity"] = identity
44    if drift is not None:
45        report["drift"] = drift
46        report["drift_material"] = abs(drift.get("relative", 0)) >= 0.02
47    return {"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):
53    def setUp(self):
54        self.tmp = Path(tempfile.mkdtemp(prefix="strata-tune-apply-"))
55        self.state = self.tmp / "state"
56        self.state.mkdir()
57        self.config = self.tmp / "strata-fixture.json"
58        self.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")
64        self.before = self.config.read_bytes()
65
66    def tearDown(self):
67        import shutil
68        shutil.rmtree(self.tmp, ignore_errors=True)
69
70    def identity(self):
71        return {"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
76    def job_with_identity(self, **kw):
77        return a_job(identity=self.identity(), **kw)
78
79    def assert_untouched(self):
80        self.assertEqual(self.config.read_bytes(), self.before,
81                         "a refused apply must leave the configuration byte-identical")
82
83
84class TestArgv(ApplyCase):
85    def test_flags_are_paired_and_ordered_deterministically(self):
86        argv = ta.args_to_argv({"--kv": "int8", "--kv-grow": True, "--ple-io": "mmap"})
87        self.assertEqual(argv, ["--kv", "int8", "--kv-grow", "--ple-io", "mmap"])
88
89    def test_a_false_value_omits_the_flag_rather_than_writing_it(self):
90        self.assertEqual(ta.args_to_argv({"--kv-grow": False}), [])
91        self.assertEqual(ta.args_to_argv({"--kv-grow": None}), [])
92
93
94class TestConfigEdit(ApplyCase):
95    def test_the_recommended_flag_replaces_every_occurrence(self):
96        cfg = {"args": ["--kv", "fp16", "--kv", "q4_0", "--max-context", "32768"]}
97        out = ta.apply_args_to_config(cfg, ["--kv", "int8"])
98        self.assertEqual(out["args"], ["--max-context", "32768", "--kv", "int8"],
99                         "a half-replaced flag is a configuration that does nothing")
100
101    def test_an_absent_flag_is_appended(self):
102        out = ta.apply_args_to_config({"args": ["--max-context", "4096"]}, ["--kv", "int8"])
103        self.assertEqual(out["args"], ["--max-context", "4096", "--kv", "int8"])
104
105    def 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."""
107        out = ta.apply_args_to_config(
108            {"args": [], "env": {"STRATA_TOKEN": "private"}, "vendor_unknown": {"keep": True},
109             "aliases": ["chat"]}, ["--kv", "int8"])
110        self.assertEqual(out["env"], {"STRATA_TOKEN": "private"})
111        self.assertEqual(out["vendor_unknown"], {"keep": True})
112        self.assertEqual(out["aliases"], ["chat"])
113
114    def test_the_input_configuration_is_not_mutated(self):
115        cfg = {"args": ["--kv", "fp16"]}
116        ta.apply_args_to_config(cfg, ["--kv", "int8"])
117        self.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
123    def test_a_recommendation_that_changes_nothing_is_refused(self):
124        plan = ta.review_apply(job=self.job_with_identity(args={"--kv": "fp16"}),
125                               config_path=self.config, current_identity=self.identity())
126        self.assertFalse(plan.applicable)
127        self.assertTrue(any("already carries" in r for r in plan.reasons), plan.reasons)
128
129    def test_an_incomplete_sweep_cannot_be_applied(self):
130        plan = ta.review_apply(job=self.job_with_identity(state="running"),
131                               config_path=self.config, current_identity=self.identity())
132        self.assertFalse(plan.applicable)
133        self.assertTrue(any("not completed" in r for r in plan.reasons), plan.reasons)
134
135    def test_a_sweep_that_recommended_nothing_cannot_be_applied(self):
136        plan = ta.review_apply(job=a_job(available=False, identity=self.identity()),
137                               config_path=self.config, current_identity=self.identity())
138        self.assertFalse(plan.applicable)
139        self.assertTrue(any("recommended no change" in r for r in plan.reasons), plan.reasons)
140        self.assertTrue(any("beat the baseline" in r for r in plan.reasons),
141                        "the sweep's own reason is carried into the refusal")
142
143    def test_material_drift_blocks_the_apply(self):
144        """A comparison the sweep itself called weak must not be applied."""
145        plan = ta.review_apply(job=self.job_with_identity(
146                                   drift={"metric": "tokens_per_s", "first": 20.0, "last": 25.0,
147                                          "relative": 0.25, "note": "drifted"}),
148                               config_path=self.config, current_identity=self.identity())
149        self.assertFalse(plan.applicable)
150        self.assertTrue(any("drifted" in r for r in plan.reasons), plan.reasons)
151
152    def test_a_changed_model_makes_the_recommendation_unappliable(self):
153        """The single most important check: different model bytes mean the numbers do not apply."""
154        plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,
155                               current_identity=dict(self.identity(), model_digest="z" * 64))
156        self.assertFalse(plan.applicable)
157        self.assertTrue(any("different model bytes" in r for r in plan.reasons), plan.reasons)
158
159    def test_a_changed_workload_or_context_makes_it_unappliable(self):
160        for changed, expected in ((dict(self.identity(), context=131072), "context"),
161                                  (dict(self.identity(), workload={"prompt_tokens": 999}),
162                                   "workload")):
163            plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,
164                                   current_identity=changed)
165            self.assertFalse(plan.applicable, expected)
166            self.assertTrue(any(expected in r for r in plan.reasons), plan.reasons)
167
168    def test_a_sweep_with_no_recorded_identity_cannot_be_applied(self):
169        plan = ta.review_apply(job=a_job(), config_path=self.config,
170                               current_identity=self.identity())
171        self.assertFalse(plan.applicable)
172        self.assertTrue(any("no artifact identity" in r for r in plan.reasons), plan.reasons)
173
174    def test_a_report_edited_after_review_is_refused(self):
175        job = self.job_with_identity()
176        reviewed = ta._report_digest(job)
177        job["report"]["recommendation"]["median"] = 999.0        # someone edits the numbers
178        plan = ta.review_apply(job=job, config_path=self.config, current_identity=self.identity(),
179                               report_sha256=reviewed)
180        self.assertFalse(plan.applicable)
181        self.assertTrue(any("changed after review" in r for r in plan.reasons), plan.reasons)
182
183    def test_a_missing_configuration_is_refused_with_its_path(self):
184        plan = ta.review_apply(job=self.job_with_identity(), config_path=self.tmp / "gone.json",
185                               current_identity=self.identity())
186        self.assertFalse(plan.applicable)
187        self.assertTrue(any("gone.json" in r for r in plan.reasons), plan.reasons)
188
189
190class TestApply(ApplyCase):
191    def test_an_applicable_recommendation_is_written_with_the_other_keys_intact(self):
192        result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
193                                        current_identity=self.identity(), state_dir=self.state)
194        after = json.loads(self.config.read_text(encoding="utf-8"))
195        self.assertEqual(after["args"], ["--max-context", "32768", "--kv", "int8"])
196        self.assertEqual(after["env"]["STRATA_TOKEN"], "private")
197        self.assertEqual(after["aliases"], ["chat"])
198        self.assertEqual(result["plan"]["added"], ["--kv int8"])
199        self.assertEqual(result["plan"]["removed"], ["--kv fp16"])
200
201    def test_the_previous_bytes_are_retained(self):
202        result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
203                                        current_identity=self.identity(), state_dir=self.state)
204        kept = Path(result["directory"]) / "before.json"
205        self.assertEqual(kept.read_bytes(), self.before,
206                         "rollback needs the exact previous bytes, not a reconstruction")
207
208    def test_a_verification_failure_writes_nothing(self):
209        def verify(candidate):
210            raise RuntimeError("the engine refused --kv int8")
211
212        with self.assertRaises(ta.ApplyError) as ctx:
213            ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
214                                    current_identity=self.identity(), state_dir=self.state,
215                                    verify=verify)
216        self.assertIn("failed verification", str(ctx.exception))
217        self.assertIn("unchanged", str(ctx.exception))
218        self.assert_untouched()
219
220    def test_a_candidate_that_generates_nothing_writes_nothing(self):
221        """A configuration that boots but cannot generate must not be written."""
222        with self.assertRaises(ta.ApplyError) as ctx:
223            ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
224                                    current_identity=self.identity(), state_dir=self.state,
225                                    verify=lambda candidate: 0)
226        self.assertIn("no tokens", str(ctx.exception))
227        self.assert_untouched()
228
229    def test_a_successful_verification_is_recorded(self):
230        result = ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
231                                        current_identity=self.identity(), state_dir=self.state,
232                                        verify=lambda candidate: 7)
233        self.assertEqual(result["application"]["verified_tokens"], 7)
234
235    def test_a_refused_apply_changes_nothing(self):
236        with self.assertRaises(ta.ApplyError):
237            ta.apply_recommendation(job=self.job_with_identity(state="failed"),
238                                    config_path=self.config, current_identity=self.identity(),
239                                    state_dir=self.state, verify=lambda c: 5)
240        self.assert_untouched()
241        self.assertFalse((self.state / "applications").exists(),
242                         "a refusal must not leave an application record behind")
243
244    def test_a_user_edit_during_verification_is_not_overwritten(self):
245        """Verification can take minutes; an edit in that window wins."""
246        def verify(candidate):
247            self.config.write_text(json.dumps({"args": ["--kv", "q4_0"], "edited": True}),
248                                   encoding="utf-8")
249            return 5
250
251        with self.assertRaises(ta.ApplyError) as ctx:
252            ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
253                                    current_identity=self.identity(), state_dir=self.state,
254                                    verify=verify)
255        self.assertIn("changed during verification", str(ctx.exception))
256        self.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
263    A sweep planned without `--model-path` records `model_digest: null`. The library refused it, but
264    the CLI's own identity re-derivation produced a *different* key whose model digest was also null,
265    and `null == null` matched -- so the apply proceeded on a recommendation that could never be
266    matched to the installed weights. The output looked entirely normal.
267
268    The fix is that the recorded sweep must carry a real digest before anything is written, which is
269    what these tests pin down.
270    """
271
272    def 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."""
274        job = a_job()                                    # no identity at all
275        plan = ta.review_apply(job=job, config_path=self.config, current_identity=self.identity())
276        self.assertFalse(plan.applicable)
277        self.assertTrue(any("no artifact identity" in r for r in plan.reasons), plan.reasons)
278
279    def test_an_identity_with_a_null_model_digest_still_refuses(self):
280        """Even a *present* identity whose model digest is unknown is not applicable."""
281        partial = dict(self.identity(), model_digest=None)
282        plan = ta.review_apply(job=self.job_with_identity(), config_path=self.config,
283                               current_identity=partial)
284        self.assertFalse(plan.applicable,
285                         "an unknown model must never be treated as the same model")
286        self.assertTrue(any("different model" in r or "different" in r for r in plan.reasons),
287                        plan.reasons)
288
289    def 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
292        This asserts the guard's condition directly: a recorded identity without a model digest may
293        not be applied, whatever the re-derived identity looks like.
294        """
295        recorded = {"model_digest": None}
296        self.assertFalse(recorded.get("model_digest"),
297                         "the CLI guard keys on exactly this, and it must be falsy")
298
299
300class TestRollback(ApplyCase):
301    def apply(self):
302        return ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
303                                       current_identity=self.identity(), state_dir=self.state,
304                                       verify=lambda c: 5)
305
306    def test_rollback_restores_the_previous_bytes(self):
307        result = self.apply()
308        self.assertNotEqual(self.config.read_bytes(), self.before)
309        ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)
310        self.assertEqual(self.config.read_bytes(), self.before)
311
312    def test_rollback_refuses_to_discard_a_newer_edit(self):
313        result = self.apply()
314        self.config.write_text(json.dumps({"args": ["--kv", "manual"]}) + "\n", encoding="utf-8")
315        with self.assertRaises(ta.ApplyError) as ctx:
316            ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)
317        self.assertIn("newer change", str(ctx.exception))
318        self.assertEqual(json.loads(self.config.read_text())["args"], ["--kv", "manual"],
319                         "the user's edit wins over the rollback")
320
321    def test_rollback_twice_is_refused(self):
322        result = self.apply()
323        ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)
324        with self.assertRaises(ta.ApplyError) as ctx:
325            ta.rollback(application_id=result["application"]["application_id"], state_dir=self.state)
326        self.assertIn("already been rolled back", str(ctx.exception))
327
328    def test_an_unknown_application_is_a_not_found(self):
329        with self.assertRaises(ta.ApplyError) as ctx:
330            ta.rollback(application_id="20260101T000000Z-deadbeef", state_dir=self.state)
331        self.assertEqual(ctx.exception.code, 404)
332
333    def test_an_apply_cannot_be_repeated_on_the_same_record(self):
334        result = self.apply()
335        application = 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.
338        after = self.config.read_bytes()
339        with self.assertRaises(ta.ApplyError):
340            ta.apply_recommendation(job=self.job_with_identity(), config_path=self.config,
341                                    current_identity=self.identity(), state_dir=self.state,
342                                    verify=lambda c: 5)
343        self.assertEqual(self.config.read_bytes(), after, f"application {application} wrote twice")
344
345
346class TestConfigDiscovery(ApplyCase):
347    def 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")
352        found = {p.name for p in ta.find_config_files(self.tmp)}
353        self.assertIn("strata-good.json", found)
354        self.assertIn("strata-fixture.json", found)
355        self.assertNotIn("strata-notjson.json", found, "a damaged file is skipped, not guessed at")
356        self.assertNotIn("strata-wrongshape.json", found)
357        self.assertNotIn("other.json", found, "the project's own naming decides, not any JSON file")
358
359
360if __name__ == "__main__":
361    unittest.main()