okami.mom/strata

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

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
19.6 KiB355 linesraw
1"""Owner-editable typed operations; previews never run or write an operation."""
2
3import io
4import json
5import os
6import stat
7import subprocess
8import sys
9import tempfile
10import unittest
11from contextlib import redirect_stdout
12from pathlib import Path
13from unittest import mock
14
15from strata_cli.cli import main
16from strata_control import journal, profiles, recipes
17
18
19class RecipeTests(unittest.TestCase):
20    def setUp(self):
21        self.temp = tempfile.TemporaryDirectory()
22        self.addCleanup(self.temp.cleanup)
23        self.root = Path(self.temp.name)
24        environment = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
25                                                "XDG_CONFIG_HOME": str(self.root / "settings")})
26        environment.start()
27        self.addCleanup(environment.stop)
28        engine = self.root / "engine"
29        engine.write_bytes(b"fake engine")
30        engine.chmod(0o700)
31        tokenizer = self.root / "tokenizer"
32        tokenizer.mkdir()
33        for name in ("vocab.json", "merges.txt", "token_type.json"):
34            (tokenizer / name).write_text("{}", encoding="utf-8")
35        self.config = self.root / "run.json"
36        self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
37                                           "args": [], "cwd": str(self.root), "model_name": "fake",
38                                           "host": "127.0.0.1", "port": 0}), encoding="utf-8")
39        profiles.create("local", str(self.config))
40
41    def _cli(self, *args):
42        output = io.StringIO()
43        with redirect_stdout(output):
44            code = main(["ops", *args, "--profile", "local", "--output", "json"])
45        return code, json.loads(output.getvalue())
46
47    def test_benchmark_job_receipt_is_readable_by_new_owner_bridge_process(self):
48        _, revision = profiles.load("local")
49        job_id = "a" * 32
50        intent = {"path": str(self.root / "future-benchmark"), "suite": "serving-smoke",
51                  "concurrency": 2, "repeat": 1, "request_timeout": 30,
52                  "condition": "baseline", "if_profile_revision": revision,
53                  "if_source_sha256": "b" * 64,
54                  "if_owner_id": "c" * 32, "if_instance_id": "d" * 32}
55        journal.begin_direct("local", "bench.run", revision, intent, operation_id=job_id)
56        request = {"schema_version": 1, "action": "bench.job", "profile": "local",
57                   "params": {"job_id": job_id}}
58        process = subprocess.run([sys.executable, "-m", "strata_control.management"],
59                                 input=json.dumps(request), text=True, capture_output=True,
60                                 cwd=Path(__file__).resolve().parents[2], timeout=10, check=True)
61        response = json.loads(process.stdout)
62        self.assertTrue(response["ok"])
63        self.assertEqual(response["job"]["job_id"], job_id)
64        self.assertEqual(response["job"]["state"], "launching")
65        self.assertIsNone(response["job"]["result"])
66
67    def test_init_set_plan_and_run_are_typed_and_machine_clean(self):
68        self.assertEqual(self._cli("list")[1]["recipes"], [])
69        self.assertFalse((profiles.profile_dir() / ".ops").exists())
70        code, initialized = self._cli("init")
71        self.assertEqual(code, 0)
72        self.assertEqual(initialized["created"], ["restart", "calibrate", "check"])
73        self.assertEqual(self._cli("init")[1]["created"], [])
74        self.assertEqual(len(self._cli("list")[1]["recipes"]), 3)
75        before, revision = recipes.load("local", "restart")
76        code, preview = self._cli("set", "restart", "startup_wait_s=45", "--plan")
77        self.assertEqual(code, 0)
78        self.assertTrue(preview["would_save"])
79        self.assertEqual(recipes.load("local", "restart"), (before, revision))
80        self.assertEqual(self._cli("set", "restart", "startup_wait_s=45")[0], 0)
81        self.assertFalse(self._cli("set", "restart", "startup_wait_s=45", "--plan")[1]["would_save"])
82        with mock.patch("strata_control.runtime.plan_restart", return_value={"ok": True,
83                         "state": "ready", "would_drain": False}), \
84                mock.patch("strata_control.runtime.restart", return_value={"ok": True,
85                           "state": "ready", "instance_id": "next"}) as restart:
86            code, planned = self._cli("plan", "restart")
87            self.assertEqual(code, 0)
88            self.assertFalse(planned["plan"]["would_execute"])
89            self.assertEqual(planned["plan"]["operation"]["startup_wait_s"], 45)
90            self.assertTrue(planned["plan"]["operation"]["run_effects"]["drain_current_instance"])
91            restart.assert_not_called()
92            code, ran = self._cli("run", "restart")
93            self.assertEqual(code, 0)
94            self.assertEqual(ran["operation"]["result"]["instance_id"], "next")
95            restart.assert_called_once_with("local", startup_wait=45)
96        self.assertEqual(self._cli("run", "check")[0], 0)
97        with mock.patch("strata_control.runtime.restart") as restart:
98            code, invalid = self._cli("run", "restart", "--exclusive")
99            self.assertEqual(code, 2)
100            self.assertFalse(invalid["ok"])
101            restart.assert_not_called()
102
103    def test_calibration_requires_fresh_exclusivity_and_uses_new_report_path(self):
104        recipes.initialize("local")
105        source = self.config.read_bytes()
106        report_dir = self.root / "reports"
107        self.assertEqual(self._cli("set", "calibrate", f"report_dir={report_dir}")[0], 0)
108        code, result = self._cli("plan", "calibrate")
109        self.assertEqual(code, 0)
110        self.assertFalse(result["plan"]["would_execute"])
111        self.assertTrue(result["plan"]["operation"]["run_effects"]["start_engine_for_decode_sweep"])
112        self.assertFalse(result["plan"]["operation"]["run_effects"]["change_run_config"])
113        self.assertFalse(report_dir.exists())
114        code, denied = self._cli("run", "calibrate")
115        self.assertEqual(code, 2)
116        self.assertFalse(denied["ok"])
117
118        def fake_runner(cfg, say):
119            return {"settings": {"--pcie-frac": "0.20"},
120                    "report": {"default": {"pcie_frac": 0.55},
121                               "confirm": {"default": [10.0, 10.2, 10.1],
122                                           "candidate": [12.0, 12.2, 12.1]},
123                               "tok_s": 12.1, "seconds": 30}}
124
125        with mock.patch("tools.calibrate.run", side_effect=fake_runner), \
126                mock.patch("strata_control.calibration._hardware_key", return_value="fake-gpu"), \
127                mock.patch("strata_control.calibration._port_active", return_value=False):
128            first = self._cli("run", "calibrate", "--exclusive")
129            second = self._cli("run", "calibrate", "--exclusive")
130        self.assertEqual(first[0], 0)
131        self.assertEqual(second[0], 0)
132        first_path = Path(first[1]["operation"]["result"]["report_path"])
133        second_path = Path(second[1]["operation"]["result"]["report_path"])
134        self.assertNotEqual(first_path, second_path)
135        self.assertTrue(first_path.is_file())
136        self.assertTrue(second_path.is_file())
137        self.assertEqual(self.config.read_bytes(), source)
138        if os.name == "posix":
139            self.assertEqual(stat.S_IMODE(first_path.stat().st_mode), 0o600)
140
141    def test_component_recipe_can_enable_a_typed_live_card_check(self):
142        cfg = json.loads(self.config.read_text(encoding="utf-8"))
143        cfg["gpu"] = [0, 1, 2, 3]
144        cfg["backend"] = "cuda"
145        self.config.write_text(json.dumps(cfg), encoding="utf-8")
146        recipes.initialize("local")
147        code, proposed = self._cli("set", "check", "live=true", "--plan")
148        self.assertEqual(code, 0)
149        self.assertTrue(proposed["would_save"])
150        self.assertEqual(recipes.load("local", "check")[0]["params"], {})
151        self.assertEqual(self._cli("set", "check", "live=true")[0], 0)
152        cards = "\n".join(f"{i}, RTX 6000 test, GPU-test-{i}, 49140, 580.95" for i in range(4))
153        with mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
154                mock.patch("strata_control.doctor.subprocess.run",
155                           return_value=mock.Mock(returncode=0, stdout=cards)) as probe:
156            code, preview = self._cli("plan", "check")
157            self.assertEqual(code, 0)
158            self.assertTrue(preview["plan"]["operation"]["run_effects"]["query_host_gpus"])
159            self.assertEqual(preview["plan"]["operation"]["preflight"]["live_gpu_probe"]["status"], "ok")
160            code, executed = self._cli("run", "check", "--if-revision", preview["plan"]["recipe_revision"])
161        self.assertEqual(code, 0)
162        self.assertEqual(executed["operation"]["result"]["report"]["live_gpu_probe"]["status"], "ok")
163        self.assertEqual(probe.call_count, 2)
164        record = journal.load("local", executed["operation"]["operation_id"])
165        self.assertEqual(record["intent"], {"live": True})
166        with self.assertRaisesRegex(profiles.ProfileError, "parameter is not supported"):
167            recipes.propose_value("local", "check", "live=maybe")
168
169    def test_invalid_edit_keeps_draft_and_saved_recipe(self):
170        recipes.initialize("local")
171        before = recipes.load("local", "check")
172        editor = self.root / "bad_editor.py"
173        editor.write_text("import pathlib, sys\npathlib.Path(sys.argv[1]).write_text('{}')\n")
174        with mock.patch.dict(os.environ, {"VISUAL": f"{sys.executable} {editor}"}):
175            code, result = self._cli("edit", "check")
176        self.assertEqual(code, 2)
177        self.assertFalse(result["ok"])
178        self.assertEqual(recipes.load("local", "check"), before)
179        self.assertEqual(len(list((profiles.profile_dir() / ".ops" / "local").glob(".check-edit-*.json"))), 1)
180
181    def test_history_rollback_and_stale_edit(self):
182        recipes.initialize("local")
183        original, first = recipes.load("local", "restart")
184        proposed, revision = recipes.propose_value("local", "restart", "startup_wait_s=60")
185        recipes.save("local", "restart", proposed, revision)
186        with mock.patch("strata_control.runtime.restart") as restart:
187            code, stale = self._cli("run", "restart", "--if-revision", first)
188            self.assertEqual(code, 6)
189            self.assertFalse(stale["ok"])
190            restart.assert_not_called()
191        with self.assertRaisesRegex(profiles.ProfileError, "changed during edit"):
192            recipes.save("local", "restart", original, first)
193        entries = recipes.history("local", "restart")
194        self.assertEqual(entries[1]["revision"], first)
195        code, restored = self._cli("rollback", "restart", "--to", first)
196        self.assertEqual(code, 0)
197        self.assertEqual(restored["recipe"]["params"]["startup_wait_s"], 300)
198        self.assertEqual(recipes.load("local", "restart")[0], original)
199
200    def test_recipe_file_cannot_inject_shell_kind_or_symlink(self):
201        recipes.initialize("local")
202        path = profiles.profile_dir() / ".ops" / "local" / "restart.json"
203        original = path.read_bytes()
204        path.write_text(json.dumps({"schema_version": 1, "profile": "local", "id": "restart",
205                                    "kind": "shell.exec", "params": {"command": "rm -rf /"}}))
206        with self.assertRaisesRegex(profiles.ProfileError, "unsupported"):
207            recipes.load("local", "restart")
208        path.unlink()
209        outside = self.root / "outside.json"
210        outside.write_bytes(original)
211        path.symlink_to(outside)
212        with self.assertRaisesRegex(profiles.ProfileError, "regular file"):
213            recipes.load("local", "restart")
214
215    def test_init_rejects_conflicting_default_name_before_other_writes(self):
216        recipes.create("local", "check", "runtime.restart")
217        with self.assertRaisesRegex(profiles.ProfileError, "different kind"):
218            recipes.initialize("local")
219        self.assertEqual([item["id"] for item in recipes.list_recipes("local")], ["check"])
220
221    def test_operation_journal_records_compact_success_and_is_read_only_to_list(self):
222        recipes.initialize("local")
223        self.assertEqual(self._cli("runs")[1]["runs"], [])
224        self.assertFalse((profiles.profile_dir() / ".ops" / "local" / ".runs").exists())
225        code, executed = self._cli("run", "check")
226        self.assertEqual(code, 0)
227        operation_id = executed["operation"]["operation_id"]
228        code, listed = self._cli("runs")
229        self.assertEqual(code, 0)
230        self.assertEqual(listed["runs"][0]["operation_id"], operation_id)
231        code, shown = self._cli("result", operation_id)
232        self.assertEqual(code, 0)
233        record = shown["record"]
234        self.assertEqual(record["state"], "succeeded")
235        self.assertEqual(record["intent"], {})
236        self.assertEqual([event["state"] for event in record["events"]], ["running", "succeeded"])
237        self.assertEqual(set(record["result"]), {"ok", "issue_codes"})
238        path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{operation_id}.json"
239        if os.name == "posix":
240            self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
241
242    def test_failed_and_uncertain_runs_keep_distinct_journal_states_without_raw_result(self):
243        recipes.initialize("local")
244        with mock.patch("strata_control.runtime.restart", return_value={"ok": False,
245                         "state": "ready", "error": "new_instance_failed", "exit_code": 6,
246                         "private_trace": "TOPSECRET"}):
247            code, executed = self._cli("run", "restart")
248        self.assertEqual(code, 6)
249        failed = journal.load("local", executed["operation"]["operation_id"])
250        self.assertEqual(failed["state"], "failed")
251        self.assertNotIn("TOPSECRET", json.dumps(failed))
252        with mock.patch("strata_control.runtime.restart",
253                        side_effect=profiles.ProfileError("runtime operation wait expired", 8)):
254            code, timed_out = self._cli("run", "restart")
255        self.assertEqual(code, 8)
256        self.assertFalse(timed_out["ok"])
257        newest = journal.list_runs("local")[0]
258        uncertain = journal.load("local", newest["operation_id"])
259        self.assertEqual(uncertain["state"], "completion_unknown")
260        self.assertEqual(uncertain["result"]["exit_code"], 8)
261        with mock.patch("strata_control.runtime.restart", side_effect=KeyboardInterrupt):
262            code, interrupted = self._cli("run", "restart")
263        self.assertEqual(code, 130)
264        self.assertFalse(interrupted["ok"])
265        newest = journal.list_runs("local")[0]
266        self.assertEqual(journal.load("local", newest["operation_id"])["state"], "completion_unknown")
267
268    def test_broken_machine_output_detaches_without_reporting_local_file_failure(self):
269        recipes.initialize("local")
270
271        class ClosedPipe(io.StringIO):
272            def write(self, text):
273                raise BrokenPipeError("consumer closed")
274
275        with redirect_stdout(ClosedPipe()):
276            self.assertEqual(main(["ops", "list", "--profile", "local", "--output", "json"]), 0)
277
278    def test_journal_prunes_old_terminal_records_but_not_running_work(self):
279        recipes.initialize("local")
280        with mock.patch.object(journal, "MAX_RECORDS", 2):
281            ids = []
282            for _ in range(3):
283                code, executed = self._cli("run", "check")
284                self.assertEqual(code, 0)
285                ids.append(executed["operation"]["operation_id"])
286            self.assertEqual(len(journal.list_runs("local")), 2)
287            with self.assertRaisesRegex(profiles.ProfileError, "not found"):
288                journal.load("local", ids[0])
289            # Two unfinished records exhaust the cap; neither may be discarded.
290            directory = profiles.profile_dir() / ".ops" / "local" / ".runs"
291            for path in directory.glob("*.json"):
292                path.unlink()
293            first = journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
294            second = journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
295            with self.assertRaisesRegex(profiles.ProfileError, "journal is full"):
296                journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
297            self.assertEqual(journal.load("local", first["operation_id"])["state"], "running")
298            self.assertTrue(journal.load("local", first["operation_id"])["completion_unverified"])
299            self.assertEqual(journal.load("local", second["operation_id"])["state"], "running")
300
301    def test_invalid_journal_event_is_reported_without_rendering_record_content(self):
302        recipes.initialize("local")
303        operation_id = self._cli("run", "check")[1]["operation"]["operation_id"]
304        path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{operation_id}.json"
305        record = json.loads(path.read_text())
306        record["events"][-1]["state"] = "\x1b[31mforged\x1b[0m"
307        path.write_text(json.dumps(record))
308        with self.assertRaisesRegex(profiles.ProfileError, "invalid events"):
309            journal.load("local", operation_id)
310        code, listed = self._cli("runs")
311        self.assertEqual(code, 0)
312        self.assertIn("error", listed["runs"][0])
313        self.assertNotIn("forged", json.dumps(listed))
314
315    def test_direct_journal_is_typed_compact_and_keeps_uncertain_interruptions(self):
316        revision = profiles.load("local")[1]
317        operation_id, result = journal.run_direct("local", "runtime.restart", revision,
318            {"wait_s": 20, "startup_wait_s": 10, "expected_profile_revision": revision},
319            lambda: {"ok": False, "state": "ready", "error": "activation_failed", "exit_code": 6,
320                     "private_trace": "TOPSECRET"})
321        self.assertFalse(result["ok"])
322        record = journal.load("local", operation_id)
323        self.assertEqual(record["schema_version"], 2)
324        self.assertEqual(record["origin"], "direct")
325        self.assertEqual(record["state"], "failed")
326        self.assertNotIn("TOPSECRET", json.dumps(record))
327        deadline_id, _ = journal.run_direct("local", "runtime.stop", revision, {"wait_s": 12},
328                                            lambda: {"ok": False, "state": "stopping", "exit_code": 8})
329        self.assertEqual(journal.load("local", deadline_id)["state"], "completion_unknown")
330        with self.assertRaises(KeyboardInterrupt):
331            journal.run_direct("local", "runtime.stop", revision, {"wait_s": 12},
332                               lambda: (_ for _ in ()).throw(KeyboardInterrupt()))
333        # the interrupted run is the one that is neither of the two above (list_runs orders by file time, and three runs written
334        # within one tick of a coarse Windows clock come back in any order)
335        latest = next(r for r in journal.list_runs("local") if r["operation_id"] not in (operation_id, deadline_id))
336        uncertain = journal.load("local", latest["operation_id"])
337        self.assertEqual(uncertain["state"], "completion_unknown")
338        with self.assertRaisesRegex(profiles.ProfileError, "unsupported fields"):
339            journal.begin_direct("local", "runtime.stop", revision,
340                                 {"wait_s": 12, "shell": "rm -rf /"})
341        self.assertEqual(len(journal.list_runs("local")), 3)
342
343    def test_direct_journal_rejects_tampered_origin(self):
344        revision = profiles.load("local")[1]
345        record = journal.begin_direct("local", "runtime.stop", revision, {"wait_s": 12})
346        path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{record['operation_id']}.json"
347        forged = json.loads(path.read_text())
348        forged["origin"] = "remote"
349        path.write_text(json.dumps(forged))
350        with self.assertRaisesRegex(profiles.ProfileError, "unsupported intent"):
351            journal.load("local", record["operation_id"])
352
353
354if __name__ == "__main__":
355    unittest.main()