okami.mom/strata

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

Niko1221Merge f-0213-tuicfg (final c6dda74bf) into f-0213-int049ae1c67

main
43.4 KiB752 linesraw
1"""Calibration report binding, review and atomic apply without a GPU."""
2
3import io
4import json
5import os
6import stat
7import subprocess
8import sys
9import tempfile
10import threading
11import unittest
12import uuid
13from contextlib import redirect_stdout
14from pathlib import Path
15from types import SimpleNamespace
16from unittest import mock
17
18from strata_cli.cli import main
19from strata_control import calibration, journal, management, profiles, runtime
20import setup
21
22
23class CalibrationFlowTests(unittest.TestCase):
24    def test_mac_ram_identity_is_available_without_proc_meminfo(self):
25        with mock.patch.object(setup, "WIN", False), \
26                mock.patch.object(setup.sys, "platform", "darwin"), \
27                mock.patch.object(setup.subprocess, "run",
28                                  return_value=SimpleNamespace(stdout="17179869184\n")):
29            self.assertEqual(setup.ram_gb(), 16.0)
30
31    def setUp(self):
32        self.temp = tempfile.TemporaryDirectory()
33        self.addCleanup(self.temp.cleanup)
34        self.root = Path(self.temp.name)
35        patcher = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
36                                           "STRATA_RUNTIME_DIR": str(self.root / "runtime"),
37                                           "XDG_CONFIG_HOME": str(self.root / "settings"),
38                                           "APPDATA": str(self.root / "settings"),
39                                           "STRATA_API_KEY": ""})
40        patcher.start()
41        self.addCleanup(patcher.stop)
42        # setup's own answer: <XDG_CONFIG_HOME>/strata/settings.json, or %APPDATA%/Strata/settings.json on Windows
43        self.settings_file = setup.settings_path()
44        self.assertTrue(str(self.settings_file).startswith(str(self.root)), "settings must stay in the temp tree")
45        engine = self.root / "strata-engine"
46        engine.write_bytes(b"fake engine")
47        engine.chmod(0o700)
48        tokenizer = self.root / "tokenizer"
49        tokenizer.mkdir()
50        for name in ("vocab.json", "merges.txt", "token_type.json"):
51            (tokenizer / name).write_text("{}", encoding="utf-8")
52        (self.root / "pack").mkdir()
53        (self.root / "model.gguf").write_bytes(b"fake model")
54        self.config = self.root / "run.json"
55        self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
56                                           "args": ["--pack", str(self.root / "pack"),
57                                                    "--native", str(self.root / "model.gguf")],
58                                           "cwd": str(self.root), "model_name": "test-model", "port": 8095}),
59                               encoding="utf-8")
60        profiles.create("local", str(self.config))
61        hardware = mock.patch("strata_control.calibration._hardware_key", return_value="test-gpu|24GB|test-cpu")
62        hardware.start()
63        self.addCleanup(hardware.stop)
64        port = mock.patch("strata_control.calibration._port_active", return_value=False)
65        port.start()
66        self.addCleanup(port.stop)
67
68    def fake_result(self, cfg, say, **_):
69        say("measured fake decode workload")
70        return {"settings": {"--pcie-frac": "0.20"},
71                "report": {"default": {"pcie_frac": 0.55}, "confirm": {"default": [10.0, 10.2, 10.1],
72                                                                  "candidate": [12.0, 12.2, 12.1]},
73                           "tok_s": 12.1, "seconds": 30}}
74
75    def test_desktop_calibration_receipts_recover_measure_apply_and_rollback(self):
76        def send(action, params):
77            return management.dispatch({"schema_version": 1, "action": action,
78                                        "profile": "local", "params": params})
79
80        path = self.root / "desktop-calibration.json"
81        plan = send("calibration.plan", {})["plan"]
82        reviewed = {"path": str(path), "exclusive_ack": True,
83                    "if_profile_revision": plan["profile_revision"],
84                    "if_source_sha256": plan["source_sha256"]}
85        measure_id = uuid.uuid4().hex
86        created = send("calibration.job.create", {"job_id": measure_id, "action": "measure",
87                                                  "if_report_sha256": None, **reviewed})
88        self.assertEqual(created["job_id"], measure_id)
89        self.assertEqual(send("calibration.job", {"job_id": measure_id})["job"]["state"], "launching")
90        with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
91                mock.patch("strata_control.calibration._smoke", return_value=2):
92            measured = send("calibration.measure", {**reviewed, "job_id": measure_id})
93            self.assertEqual(measured["operation_id"], measure_id)
94            recovered = send("calibration.job", {"job_id": measure_id})["job"]
95            self.assertEqual(recovered["state"], "succeeded")
96            self.assertEqual(recovered["result"]["settings"], {"--pcie-frac": "0.20"})
97
98            apply_plan = send("calibration.apply.plan", {"path": str(path)})
99            apply = {**reviewed, "if_profile_revision": apply_plan["profile_revision"],
100                     "if_source_sha256": apply_plan["source_sha256"],
101                     "if_report_sha256": apply_plan["report_sha256"]}
102            apply_id = uuid.uuid4().hex
103            send("calibration.job.create", {"job_id": apply_id, "action": "apply", **apply})
104            with self.assertRaisesRegex(profiles.ProfileError, "only calibration measurement"):
105                send("calibration.cancel", {"job_id": apply_id})
106            self.assertEqual(send("calibration.apply", {**apply, "job_id": apply_id})["operation_id"], apply_id)
107            self.assertTrue(send("calibration.job", {"job_id": apply_id})["job"]["result"]["changed"])
108
109            rollback_plan = send("calibration.rollback.plan", {"path": str(path)})
110            rollback = {**reviewed, "if_profile_revision": rollback_plan["profile_revision"],
111                        "if_source_sha256": rollback_plan["source_sha256"],
112                        "if_report_sha256": rollback_plan["report_sha256"]}
113            rollback_id = uuid.uuid4().hex
114            send("calibration.job.create", {"job_id": rollback_id, "action": "rollback", **rollback})
115            self.assertEqual(send("calibration.rollback", {**rollback, "job_id": rollback_id})["operation_id"],
116                             rollback_id)
117            self.assertTrue(send("calibration.job", {"job_id": rollback_id})["job"]["result"]["changed"])
118
119    def test_saved_measurement_reconciles_exact_unfinished_job(self):
120        def send(action, params):
121            return management.dispatch({"schema_version": 1, "action": action,
122                                        "profile": "local", "params": params})
123
124        path = self.root / "recovered-calibration.json"
125        plan = send("calibration.plan", {})["plan"]
126        job_id = uuid.uuid4().hex
127        reviewed = {"job_id": job_id, "action": "measure", "path": str(path),
128                    "exclusive_ack": True, "if_profile_revision": plan["profile_revision"],
129                    "if_source_sha256": plan["source_sha256"], "if_report_sha256": None}
130        send("calibration.job.create", reviewed)
131        with mock.patch("tools.calibrate.run", side_effect=self.fake_result):
132            calibration.measure("local", path, exclusive_ack=True, runner=self.fake_result,
133                                say=lambda _: None, job_id=job_id)
134        recovered = send("calibration.job", {"job_id": job_id})["job"]
135        self.assertEqual(recovered["state"], "succeeded")
136        self.assertEqual(recovered["outcome"], "report_recovered")
137        self.assertEqual(journal.load("local", job_id)["state"], "succeeded")
138        result = subprocess.run([sys.executable, "-m", "strata_control.management"],
139            input=json.dumps({"schema_version": 1, "action": "calibration.job", "profile": "local",
140                              "params": {"job_id": job_id}}), text=True, capture_output=True,
141            cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(), check=True)
142        self.assertEqual(json.loads(result.stdout)["job"]["result"]["report_id"],
143                         recovered["result"]["report_id"])
144        with self.assertRaisesRegex(profiles.ProfileError, "already finished"):
145            journal.finish("local", job_id, "failed", {"error_type": "wrong"})
146
147    def test_failed_desktop_calibration_preflight_finishes_receipt(self):
148        def send(action, params):
149            return management.dispatch({"schema_version": 1, "action": action,
150                                        "profile": "local", "params": params})
151
152        plan = send("calibration.plan", {})["plan"]
153        job_id = uuid.uuid4().hex
154        path = self.root / "failed-calibration.json"
155        reviewed = {"path": str(path), "exclusive_ack": True,
156                    "if_profile_revision": plan["profile_revision"],
157                    "if_source_sha256": plan["source_sha256"]}
158        send("calibration.job.create", {"job_id": job_id, "action": "measure",
159                                        "if_report_sha256": None, **reviewed})
160        self.config.write_text(self.config.read_text().replace("test-model", "changed-model"))
161        with self.assertRaisesRegex(profiles.ProfileError, "source changed"):
162            send("calibration.measure", {**reviewed, "job_id": job_id})
163        self.assertEqual(journal.load("local", job_id)["state"], "failed")
164        self.assertFalse(path.exists())
165
166    def test_unrelated_report_cannot_finish_calibration_receipt(self):
167        def send(action, params):
168            return management.dispatch({"schema_version": 1, "action": action,
169                                        "profile": "local", "params": params})
170
171        plan = send("calibration.plan", {})["plan"]
172        path = self.root / "unrelated-report.json"
173        job_id = uuid.uuid4().hex
174        send("calibration.job.create", {"job_id": job_id, "action": "measure",
175            "path": str(path), "exclusive_ack": True,
176            "if_profile_revision": plan["profile_revision"],
177            "if_source_sha256": plan["source_sha256"], "if_report_sha256": None})
178        calibration.measure("local", path, exclusive_ack=True, runner=self.fake_result,
179                            say=lambda _: None, job_id=uuid.uuid4().hex)
180        self.assertEqual(send("calibration.job", {"job_id": job_id})["job"]["state"], "launching")
181        self.assertEqual(journal.load("local", job_id)["state"], "running")
182
183    def test_active_measurement_progress_and_exact_cancel(self):
184        from tools import calibrate as cal
185
186        def send(action, params):
187            return management.dispatch({"schema_version": 1, "action": action,
188                                        "profile": "local", "params": params})
189
190        path = self.root / "stopped-calibration.json"
191        plan = send("calibration.plan", {})["plan"]
192        job_id = uuid.uuid4().hex
193        reviewed = {"path": str(path), "exclusive_ack": True,
194                    "if_profile_revision": plan["profile_revision"],
195                    "if_source_sha256": plan["source_sha256"]}
196        send("calibration.job.create", {"job_id": job_id, "action": "measure",
197                                        "if_report_sha256": None, **reviewed})
198        started = threading.Event()
199        outcome = []
200        original = self.config.read_bytes()
201
202        def waiting(cfg, say, *, progress, cancel_event):
203            progress("pcie_share", 2, 21)
204            started.set()
205            if not cancel_event.wait(4):
206                raise AssertionError("operator cancellation did not reach the worker")
207            raise cal.CalibrationCancelled("operator requested stop")
208
209        def worker():
210            try:
211                send("calibration.measure", {**reviewed, "job_id": job_id})
212            except BaseException as exc:
213                outcome.append(exc)
214
215        def bridge(action):
216            request = {"schema_version": 1, "action": action, "profile": "local",
217                       "params": {"job_id": job_id}}
218            child = subprocess.run([sys.executable, "-m", "strata_control.management"],
219                input=json.dumps(request), text=True, capture_output=True,
220                cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(), check=True)
221            return json.loads(child.stdout)
222
223        with mock.patch("tools.calibrate.run", side_effect=waiting):
224            thread = threading.Thread(target=worker)
225            thread.start()
226            try:
227                self.assertTrue(started.wait(4))
228                active = send("calibration.job", {"job_id": job_id})["job"]
229                self.assertEqual(active["state"], "running")
230                self.assertEqual(active["activity"], "active")
231                self.assertEqual(active["progress"]["stage"], "pcie_share")
232                self.assertEqual(active["progress"]["completed"], 2)
233                fresh = bridge("calibration.job")["job"]
234                self.assertEqual(fresh["state"], "running")
235                self.assertEqual(fresh["progress"]["completed"], 2)
236                with self.assertRaisesRegex(profiles.ProfileError, "not found"):
237                    send("calibration.cancel", {"job_id": uuid.uuid4().hex})
238                self.assertEqual(bridge("calibration.cancel")["state"], "cancel_requested")
239            finally:
240                thread.join(timeout=6)
241        self.assertFalse(thread.is_alive())
242        self.assertEqual(len(outcome), 1)
243        self.assertIsInstance(outcome[0], profiles.ProfileError)
244        self.assertEqual(outcome[0].exit_code, 130)
245        finished = send("calibration.job", {"job_id": job_id})["job"]
246        self.assertEqual(finished["state"], "cancelled")
247        self.assertTrue(finished["cancel_requested"])
248        self.assertFalse(path.exists())
249        self.assertEqual(self.config.read_bytes(), original)
250        with self.assertRaisesRegex(profiles.ProfileError, "not active"):
251            send("calibration.cancel", {"job_id": job_id})
252
253    def test_pruning_finished_receipt_removes_progress_and_cancel_marker(self):
254        from strata_control import calibration_jobs
255
256        def send(action, params):
257            return management.dispatch({"schema_version": 1, "action": action,
258                                        "profile": "local", "params": params})
259
260        plan = send("calibration.plan", {})["plan"]
261        shared = {"action": "measure", "exclusive_ack": True,
262                  "if_profile_revision": plan["profile_revision"],
263                  "if_source_sha256": plan["source_sha256"], "if_report_sha256": None}
264        first = uuid.uuid4().hex
265        send("calibration.job.create", {**shared, "job_id": first,
266                                        "path": str(self.root / "first.json")})
267        calibration_jobs._save_progress("local", first, "pcie_share", 2, 21)
268        marker = calibration_jobs._cancel_path("local", first)
269        marker.write_bytes(b"1")
270        marker.chmod(0o600)
271        journal.finish("local", first, "failed", {"cancelled": True})
272        with mock.patch.object(journal, "MAX_RECORDS", 1):
273            send("calibration.job.create", {**shared, "job_id": uuid.uuid4().hex,
274                                            "path": str(self.root / "second.json")})
275        self.assertFalse(calibration_jobs._progress_path("local", first).exists())
276        self.assertFalse(marker.exists())
277
278    def test_management_bridge_reviews_and_journals_exclusive_calibration(self):
279        def send(action, params):
280            return management.dispatch({"schema_version": 1, "action": action,
281                                        "profile": "local", "params": params})
282
283        report_path = self.root / "bridge-calibration.json"
284        initial = self.config.read_bytes()
285        plan = send("calibration.plan", {})["plan"]
286        self.assertEqual(plan["source_config"], str(self.config.resolve()))
287        self.assertTrue(plan["component_preflight"]["ok"])
288        source = {"if_profile_revision": plan["profile_revision"],
289                  "if_source_sha256": plan["source_sha256"]}
290        measure = {"path": str(report_path), "exclusive_ack": True, **source}
291        with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
292            send("calibration.measure", {**measure, "exclusive_ack": False})
293        with self.assertRaisesRegex(profiles.ProfileError, "source changed"):
294            send("calibration.measure", {**measure, "if_source_sha256": "0" * 64})
295        self.assertEqual(journal.list_runs("local"), [])
296        with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
297                mock.patch("strata_control.calibration._smoke", return_value=3):
298            measured = send("calibration.measure", measure)
299            self.assertTrue(measured["ok"])
300            self.assertTrue(measured["applicable"])
301            self.assertEqual(self.config.read_bytes(), initial)
302            self.assertEqual(journal.load("local", measured["operation_id"])["state"], "succeeded")
303
304            apply_plan = send("calibration.apply.plan", {"path": str(report_path)})
305            self.assertTrue(apply_plan["plan"]["applicable"])
306            apply = {"path": str(report_path), "exclusive_ack": True,
307                     "if_profile_revision": apply_plan["profile_revision"],
308                     "if_source_sha256": apply_plan["source_sha256"],
309                     "if_report_sha256": apply_plan["report_sha256"]}
310            with self.assertRaisesRegex(profiles.ProfileError, "report changed"):
311                send("calibration.apply", {**apply, "if_report_sha256": "0" * 64})
312            self.assertEqual(len(journal.list_runs("local")), 1)
313            applied = send("calibration.apply", apply)
314            self.assertTrue(applied["application"]["changed"])
315            self.assertTrue(Path(applied["application"]["application_record"]).is_file())
316
317            rollback_plan = send("calibration.rollback.plan", {"path": str(report_path)})
318            self.assertTrue(rollback_plan["plan"]["applicable"])
319            rolled = send("calibration.rollback", {"path": str(report_path),
320                "exclusive_ack": True, "if_profile_revision": rollback_plan["profile_revision"],
321                "if_source_sha256": rollback_plan["source_sha256"],
322                "if_report_sha256": rollback_plan["report_sha256"]})
323            self.assertTrue(rolled["rollback"]["changed"])
324        self.assertEqual(self.config.read_bytes(), initial)
325        self.assertEqual([row["kind"] for row in journal.list_runs("local")],
326                         ["engine.calibrate.rollback", "engine.calibrate.apply",
327                          "engine.calibrate.measure"])
328
329    def test_missing_report_folder_is_refused_before_the_sweep(self):
330        # #3187: the sweep takes ~19 minutes; the folder check must not wait until after it
331        for output in (self.root / "no-such-dir" / "report.json", self.config / "report.json"):
332            with self.assertRaisesRegex(profiles.ProfileError, "report output directory does not exist"):
333                calibration.measure("local", output, exclusive_ack=True,
334                                    runner=lambda *_a, **_k: self.fail("the sweep must not start"))
335
336    def test_calibration_rechecks_reviewed_digests_inside_operation_lock(self):
337        report_path = self.root / "pinned-calibration.json"
338        with self.assertRaisesRegex(profiles.ProfileError, "source changed after review"):
339            calibration.measure("local", report_path, exclusive_ack=True,
340                runner=lambda *_args, **_kwargs: self.fail("runner must not start"),
341                expected_source_sha256="0" * 64)
342        self.assertFalse(report_path.exists())
343        report = calibration.measure("local", report_path, exclusive_ack=True,
344                                     runner=self.fake_result, say=lambda _: None)
345        source = self.config.read_bytes()
346        with self.assertRaisesRegex(profiles.ProfileError, "report changed after review"):
347            calibration.apply_result("local", report_path, exclusive_ack=True,
348                expected_report_sha256="0" * 64,
349                smoke=lambda *_args: self.fail("smoke must not start"))
350        self.assertEqual(self.config.read_bytes(), source)
351        calibration.apply_result("local", report_path, exclusive_ack=True,
352                                 expected_report_sha256=report["body_sha256"], smoke=lambda *_args: 2)
353        with self.assertRaisesRegex(profiles.ProfileError, "report changed after review"):
354            calibration.rollback_result("local", report_path, exclusive_ack=True,
355                expected_report_sha256="0" * 64,
356                smoke=lambda *_args: self.fail("smoke must not start"))
357
358    def test_measure_review_apply_and_setup_persistence(self):
359        before = self.config.read_bytes()
360        report_path = self.root / "calibration.json"
361        report = calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
362        self.assertEqual(self.config.read_bytes(), before)
363        self.assertTrue(report["applicable"])
364        self.assertEqual(report["settings"]["--pcie-frac"], "0.20")
365        if os.name != "nt":
366            self.assertEqual(stat.S_IMODE(report_path.stat().st_mode), 0o600)
367        preview = calibration.review("local", report_path)
368        self.assertTrue(preview["applicable"])
369        self.assertIn("--pcie-frac", preview["after_args"])
370        applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 4)
371        self.assertTrue(applied["changed"])
372        self.assertEqual(applied["smoke_output_tokens"], 4)
373        self.assertEqual(Path(applied["backup"]).read_bytes(), before)
374        self.assertIn("--pcie-frac", json.loads(self.config.read_text())["args"])
375        settings = json.loads((self.settings_file).read_text())
376        self.assertEqual(settings["calibration"]["test-gpu|24GB|test-cpu"]["settings"], report["settings"])
377        self.assertFalse(calibration.review("local", report_path)["applicable"])
378
379    def test_applied_result_survives_the_next_launches_with_its_origin(self):
380        """#5132: `engine calibrate --apply-result` writes the profile's run config; a launch builds that file again from the installed config and
381        used to drop the calibrated values. They come back over Auto, as 'calibrated' (not as the person's overrides), launch after launch."""
382        from strata_cli.launch import settings as S
383        from strata_cli.launch.runner import derive_config
384        from strata_control import arg_layers, tune_knobs
385        base = json.loads(self.config.read_text())
386        base["args"] += ["--max-context", "65536"]
387        self.config.write_text(json.dumps(base), encoding="utf-8")
388
389        def launch(prev):
390            cfg = derive_config(json.loads(json.dumps(base)), S.LaunchSettings(drafting="off"), bool_flags=tune_knobs.BOOL_FLAGS, prev=prev)
391            arg_layers.stamp(cfg)
392            return json.loads(json.dumps(cfg))
393
394        first = launch(None)
395        self.config.write_text(json.dumps(first), encoding="utf-8")            # the profile points at the launch's file
396        report_path = self.root / "cal-launch.json"
397        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
398        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
399        written = json.loads(self.config.read_text())
400        self.assertEqual(written["args"][written["args"].index("--pcie-frac") + 1], "0.20")
401        for prev in (written, launch(written)):
402            nxt = launch(prev)
403            self.assertEqual(nxt["args"][nxt["args"].index("--pcie-frac") + 1], "0.20")
404            self.assertEqual(nxt["args"].count("--pcie-frac"), 1)
405            self.assertEqual(nxt["calibrated"]["settings"], {"--pcie-frac": "0.20"})
406            self.assertNotIn("--pcie-frac", nxt.get("user_args") or [])
407
408    def test_review_and_rollback_restore_config_and_absent_settings(self):
409        before = self.config.read_bytes()
410        report_path = self.root / "calibration.json"
411        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
412        applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 3)
413        self.assertTrue(Path(applied["application_record"]).is_file())
414        if os.name == "posix":
415            self.assertEqual(stat.S_IMODE(Path(applied["application_record"]).stat().st_mode), 0o600)
416        preview = calibration.review_rollback("local", report_path)
417        self.assertTrue(preview["applicable"], preview["reasons"])
418        self.assertTrue(preview["setup_settings_would_be_removed"])
419        restored = calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
420        self.assertTrue(restored["changed"])
421        self.assertEqual(restored["smoke_output_tokens"], 2)
422        self.assertEqual(self.config.read_bytes(), before)
423        self.assertFalse((self.settings_file).exists())
424        self.assertFalse(calibration.review_rollback("local", report_path)["applicable"])
425
426    @unittest.skipUnless(os.name == "posix", "managed activity lease is POSIX-only")
427    def test_managed_activity_lease_blocks_apply_and_rollback_smoke(self):
428        report_path = self.root / "calibration.json"
429
430        def assert_exclusive():
431            with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
432                runtime.acquire_activity_lease(shared=True)
433
434        def runner(cfg, say):
435            assert_exclusive()
436            return self.fake_result(cfg, say)
437
438        def smoke(cfg):
439            assert_exclusive()
440            return 2
441
442        calibration.measure("local", report_path, exclusive_ack=True,
443                            runner=runner, say=lambda _: None)
444        before = self.config.read_bytes()
445        lease = runtime.acquire_activity_lease(shared=True)
446        try:
447            with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
448                calibration.apply_result("local", report_path, exclusive_ack=True,
449                                         smoke=lambda cfg: self.fail("apply smoke ran"))
450        finally:
451            os.close(lease)
452        self.assertEqual(self.config.read_bytes(), before)
453        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
454        applied = self.config.read_bytes()
455        lease = runtime.acquire_activity_lease(shared=True)
456        try:
457            with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
458                calibration.rollback_result("local", report_path, exclusive_ack=True,
459                                            smoke=lambda cfg: self.fail("rollback smoke ran"))
460        finally:
461            os.close(lease)
462        self.assertEqual(self.config.read_bytes(), applied)
463        with mock.patch("strata_control.calibration._port_active", return_value=True):
464            with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
465                calibration.rollback_result("local", report_path, exclusive_ack=True,
466                                            smoke=lambda cfg: self.fail("rollback smoke ran"))
467        self.assertEqual(self.config.read_bytes(), applied)
468        self.assertTrue(calibration.rollback_result("local", report_path, exclusive_ack=True,
469                                                    smoke=smoke)["changed"])
470
471    def test_rollback_restores_existing_settings_exactly(self):
472        settings_path = self.settings_file
473        settings_path.parent.mkdir(parents=True)
474        original_settings = b'{"unrelated": "keep", "calibration": {"other-device": {"settings": {}}}}\n'
475        settings_path.write_bytes(original_settings)
476        original_config = self.config.read_bytes()
477        report_path = self.root / "calibration.json"
478        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
479        applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
480        self.assertEqual(Path(applied["settings_backup"]).read_bytes(), original_settings)
481        calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
482        self.assertEqual(settings_path.read_bytes(), original_settings)
483        self.assertEqual(self.config.read_bytes(), original_config)
484
485    def test_rollback_refuses_stale_state_and_failed_smoke(self):
486        report_path = self.root / "calibration.json"
487        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
488        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
489        applied_config = self.config.read_bytes()
490        settings_path = self.settings_file
491        applied_settings = settings_path.read_bytes()
492        with self.assertRaisesRegex(profiles.ProfileError, "rollback smoke generation failed"):
493            calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 1 / 0)
494        self.assertEqual(self.config.read_bytes(), applied_config)
495        settings_path.write_bytes(applied_settings + b" ")
496        preview = calibration.review_rollback("local", report_path)
497        self.assertIn("setup_settings_changed_after_apply", preview["reasons"])
498        with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
499            calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
500        self.assertEqual(self.config.read_bytes(), applied_config)
501        settings_path.write_bytes(applied_settings)
502        self.config.write_bytes(applied_config + b" ")
503        preview = calibration.review_rollback("local", report_path)
504        self.assertIn("run_config_changed_after_apply", preview["reasons"])
505        with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
506            calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
507
508    def test_rollback_detects_change_during_smoke(self):
509        report_path = self.root / "calibration.json"
510        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
511        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
512        applied_config = self.config.read_bytes()
513        settings_path = self.settings_file
514        applied_settings = settings_path.read_bytes()
515
516        def smoke(cfg):
517            settings_path.write_bytes(applied_settings + b" ")
518            return 2
519
520        with self.assertRaisesRegex(profiles.ProfileError, "changed during rollback smoke"):
521            calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=smoke)
522        self.assertEqual(self.config.read_bytes(), applied_config)
523
524    def test_rollback_rejects_modified_backup(self):
525        report_path = self.root / "calibration.json"
526        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
527        applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
528        Path(applied["backup"]).write_bytes(b"{}")
529        preview = calibration.review_rollback("local", report_path)
530        self.assertIn("config_backup_changed", preview["reasons"])
531        with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
532            calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
533
534    def test_rollback_requires_exclusive_acknowledgement(self):
535        report_path = self.root / "calibration.json"
536        output = io.StringIO()
537        with redirect_stdout(output):
538            code = main(["engine", "calibrate", "--profile", "local", "--rollback-result",
539                         str(report_path), "--output", "json"])
540        self.assertEqual(code, 2)
541        self.assertFalse(json.loads(output.getvalue())["ok"])
542        with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
543            calibration.rollback_result("local", report_path)
544
545    @unittest.skipUnless(os.name == "posix", "symlink test requires POSIX")
546    def test_apply_refuses_symlinked_backup_directory(self):
547        report_path = self.root / "calibration.json"
548        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
549        previous = self.config.read_bytes()
550        elsewhere = self.root / "elsewhere"
551        elsewhere.mkdir()
552        (self.root / ".strata-calibration-backups").symlink_to(elsewhere, target_is_directory=True)
553        with self.assertRaisesRegex(profiles.ProfileError, "owner-only and not a symlink"):
554            calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
555        self.assertEqual(self.config.read_bytes(), previous)
556        self.assertEqual(list(elsewhere.iterdir()), [])
557
558    def test_rollback_write_failure_restores_applied_state(self):
559        report_path = self.root / "calibration.json"
560        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
561        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
562        current_config = self.config.read_bytes()
563        settings_path = self.settings_file
564        current_settings = settings_path.read_bytes()
565        original_replace = calibration._replace_bytes
566        failures = 0
567
568        def fail_restore(path, payload):
569            nonlocal failures
570            if path == self.config.resolve() and failures == 0:
571                failures += 1
572                original_replace(path, payload)
573                raise OSError("simulated failure after config replacement")
574            return original_replace(path, payload)
575
576        with mock.patch("strata_control.calibration._replace_bytes", side_effect=fail_restore):
577            with self.assertRaisesRegex(profiles.ProfileError, "applied state restored"):
578                calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
579        self.assertEqual(self.config.read_bytes(), current_config)
580        self.assertEqual(settings_path.read_bytes(), current_settings)
581
582    def test_failed_smoke_or_changed_config_never_applies(self):
583        report_path = self.root / "calibration.json"
584        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
585        before = self.config.read_bytes()
586        with self.assertRaisesRegex(profiles.ProfileError, "smoke generation failed"):
587            calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 1 / 0)
588        self.assertEqual(self.config.read_bytes(), before)
589        self.config.write_bytes(before + b" ")
590        with self.assertRaisesRegex(profiles.ProfileError, "stale"):
591            calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 4)
592
593    def test_report_id_and_settings_are_validated_before_apply(self):
594        report_path = self.root / "calibration.json"
595        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
596        report = json.loads(report_path.read_text())
597        report["report_id"] = "../../outside"
598        report_path.write_text(json.dumps(report), encoding="utf-8")
599        with self.assertRaisesRegex(profiles.ProfileError, "unsupported calibration report"):
600            calibration.review("local", report_path)
601        report["report_id"] = "0" * 32
602        report["settings"] = {"--pool-workers": "999999"}
603        report_path.write_text(json.dumps(report), encoding="utf-8")
604        with self.assertRaisesRegex(profiles.ProfileError, "positive whole number"):
605            calibration.review("local", report_path)
606        report["settings"] = {"--pcie-frac": "0.75"}
607        report_path.write_text(json.dumps(report), encoding="utf-8")
608        with self.assertRaisesRegex(profiles.ProfileError, "changed after measurement"):
609            calibration.review("local", report_path)
610
611    def test_machine_cli_measure_review_apply_emits_one_json_record(self):
612        report_path = self.root / "calibration.json"
613        with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
614                mock.patch("strata_control.calibration._smoke", return_value=3):
615            for args, expected_key in ((["--measure", "--out", str(report_path), "--exclusive"], "report"),
616                                       (["--review-result", str(report_path)], "review"),
617                                       (["--apply-result", str(report_path), "--exclusive"], "application"),
618                                       (["--review-rollback", str(report_path)], "rollback_review"),
619                                       (["--rollback-result", str(report_path), "--exclusive"], "rollback")):
620                output = io.StringIO()
621                with redirect_stdout(output):
622                    code = main(["engine", "calibrate", "--profile", "local", *args, "--output", "json"])
623                self.assertEqual(code, 0)
624                parsed = json.loads(output.getvalue())
625                self.assertTrue(parsed["ok"])
626                self.assertIn(expected_key, parsed)
627                if expected_key in ("report", "application", "rollback"):
628                    record = journal.load("local", parsed["operation_id"])
629                    self.assertEqual(record["schema_version"], 2)
630                    self.assertEqual(record["origin"], "direct")
631                    self.assertEqual(record["state"], "succeeded")
632                    self.assertNotIn("candidate", json.dumps(record))
633                else:
634                    self.assertNotIn("operation_id", parsed)
635        self.assertEqual([row["kind"] for row in journal.list_runs("local")],
636                         ["engine.calibrate.rollback", "engine.calibrate.apply", "engine.calibrate.measure"])
637
638    def test_explicit_run_config_path_retains_legacy_nonjournaled_calibration(self):
639        report_path = self.root / "calibration-path.json"
640        output = io.StringIO()
641        with mock.patch("tools.calibrate.run", side_effect=self.fake_result):
642            with redirect_stdout(output):
643                code = main(["engine", "calibrate", "--profile", str(self.config), "--measure",
644                             "--exclusive", "--out", str(report_path), "--output", "json"])
645        self.assertEqual(code, 0)
646        self.assertNotIn("operation_id", json.loads(output.getvalue()))
647        self.assertEqual(journal.list_runs("local"), [])
648
649    def test_direct_apply_failure_is_a_compact_failed_operation(self):
650        report_path = self.root / "calibration.json"
651        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
652        output = io.StringIO()
653        with mock.patch("strata_control.calibration._smoke", side_effect=OSError("private engine trace")):
654            with redirect_stdout(output):
655                code = main(["engine", "calibrate", "--profile", "local", "--apply-result",
656                             str(report_path), "--exclusive", "--output", "json"])
657        self.assertEqual(code, 6)
658        self.assertFalse(json.loads(output.getvalue())["ok"])
659        record = journal.load("local", journal.list_runs("local")[0]["operation_id"])
660        self.assertEqual((record["kind"], record["state"]), ("engine.calibrate.apply", "failed"))
661        self.assertNotIn("private engine trace", json.dumps(record))
662
663    def test_measure_requires_exclusive_access_and_rejects_live_profile_port(self):
664        report_path = self.root / "calibration.json"
665        with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
666            calibration.measure("local", report_path, runner=self.fake_result)
667        with mock.patch("strata_control.calibration._port_active", return_value=True):
668            with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
669                calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result)
670        profiles.set_values("local", ["port=9123"])
671        with mock.patch("strata_control.calibration._port_active",
672                        side_effect=lambda cfg: cfg.get("port") == 9123) as checked:
673            with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
674                calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result)
675        self.assertEqual([call.args[0]["port"] for call in checked.call_args_list], [8095, 9123])
676        self.assertFalse(report_path.exists())
677
678    def test_measure_and_smoke_use_saved_engine_overrides_without_writing_them(self):
679        profiles.set_values("local", ["parallel=8", "batch_groups=2"])
680        source = self.config.read_bytes()
681        report_path = self.root / "calibration.json"
682        seen = {}
683
684        def runner(cfg, say):
685            seen["measured"] = cfg
686            return self.fake_result(cfg, say)
687
688        def smoke(cfg):
689            seen["smoked"] = cfg
690            return 2
691
692        calibration.measure("local", report_path, exclusive_ack=True, runner=runner, say=lambda _: None)
693        self.assertEqual(seen["measured"]["parallel"], 8)
694        self.assertEqual(seen["measured"]["args"][-2:], ["--batch-groups", "2"])
695        self.assertEqual(self.config.read_bytes(), source)
696        calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
697        self.assertEqual(seen["smoked"]["parallel"], 8)
698        self.assertIn("--batch-groups", seen["smoked"]["args"])
699        saved_args = json.loads(self.config.read_text())["args"]
700        self.assertNotIn("--batch-groups", saved_args)
701
702    def test_profile_edit_during_measurement_marks_report_stale(self):
703        report_path = self.root / "calibration.json"
704
705        def runner(cfg, say):
706            profiles.set_values("local", ["parallel=4"])
707            return self.fake_result(cfg, say)
708
709        report = calibration.measure("local", report_path, exclusive_ack=True, runner=runner, say=lambda _: None)
710        self.assertFalse(report["applicable"])
711        preview = calibration.review("local", report_path)
712        self.assertFalse(preview["applicable"])
713        self.assertIn("measurement_became_stale", preview["reasons"])
714
715    def test_profile_edit_during_smoke_prevents_apply(self):
716        report_path = self.root / "calibration.json"
717        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
718        source = self.config.read_bytes()
719
720        def smoke(cfg):
721            profiles.set_values("local", ["parallel=4"])
722            return 2
723
724        with self.assertRaisesRegex(profiles.ProfileError, "changed during smoke"):
725            calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
726        self.assertEqual(self.config.read_bytes(), source)
727
728    def test_settings_write_failure_restores_previous_run_config(self):
729        report_path = self.root / "calibration.json"
730        calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
731        source = self.config.read_bytes()
732        original_replace = calibration._replace_bytes
733        failures = 0
734
735        def fail_settings(path, payload):
736            nonlocal failures
737            if path.name == "settings.json":
738                failures += 1
739                if failures == 1:
740                    original_replace(path, payload)
741                    raise OSError("simulated failure after settings replacement")
742            return original_replace(path, payload)
743
744        with mock.patch("strata_control.calibration._replace_bytes", side_effect=fail_settings):
745            with self.assertRaisesRegex(profiles.ProfileError, "config restored"):
746                calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
747        self.assertEqual(self.config.read_bytes(), source)
748        self.assertFalse((self.settings_file).exists())
749
750
751if __name__ == "__main__":
752    unittest.main()