okami.mom/strata

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

Niko1221Merge f-0213-qatui (final d33d45ade) into f-0213-intb247f4ecd

main
9.0 KiB187 linesraw
1"""Round 0213 QATUI: a profile or run config of the launch itself that cannot be read stops the launch BEFORE anything is written.
2
3Found on l620 (job qatui-s03c / s03d): with `chmod 000` on the launch's own profile, `strata launch --access lan` printed "A new API key was made", rewrote the
4launch's run config with that new key, and only then failed with `profile 'launch-x' already exists` (exit 2): the key every app was set up with was gone.
5With `chmod 000` on the run config the launch went on and replaced it silently, again with a new key. Real files, an isolated home; only the Runner's
6step is called (the rest of a launch needs an engine).
7
8    python -m pytest tests/terminal/test_launch_unreadable_state_0213_qatui.py
9"""
10from __future__ import annotations
11
12import json
13import os
14import sys
15import unittest
16from pathlib import Path
17from unittest import mock
18
19ROOT = Path(__file__).resolve().parents[2]
20sys.path.insert(0, str(ROOT))
21
22from tests.terminal.launch_support import Home  # noqa: E402
23
24POSIX_NOT_ROOT = os.name != "nt" and hasattr(os, "geteuid") and os.geteuid() != 0
25
26
27def _runner():
28    from strata_cli.launch import settings as S
29    from strata_cli.launch.runner import Runner
30    r = Runner(S.LaunchSettings(model="iq3_s", context=32768))
31    assert r.name == "iq3_s-32k" and r.profile == "launch-iq3_s-32k"
32    return r
33
34
35def _write_state(name: str = "iq3_s-32k", key: str = "sk-strata-OLD"):
36    from strata_cli.launch.runner import launch_dir
37    cfg = launch_dir() / f"{name}.json"
38    cfg.write_text(json.dumps({"exe": "x", "args": [], "api_key": key}), encoding="utf-8")
39    pdir = Path(os.environ["STRATA_PROFILE_DIR"])
40    pdir.mkdir(parents=True, exist_ok=True)
41    prof = pdir / f"launch-{name}.json"
42    prof.write_text(json.dumps({"schema_version": 1, "id": f"launch-{name}", "source_config": str(cfg), "overrides": {}}), encoding="utf-8")
43    return cfg, prof
44
45
46class CheckSavedState(unittest.TestCase):
47    def test_nothing_saved_yet_is_fine(self):
48        with Home():
49            _runner().check_saved_state_readable()
50
51    def test_readable_state_is_fine(self):
52        with Home():
53            _write_state()
54            _runner().check_saved_state_readable()
55
56    def test_a_damaged_profile_of_this_launch_stops_it_before_any_write(self):
57        from strata_control import profiles
58        with Home():
59            cfg, prof = _write_state()
60            prof.write_text("{not json", encoding="utf-8")
61            before = cfg.read_bytes()
62            with self.assertRaises(profiles.ProfileError) as ctx:
63                _runner().check_saved_state_readable()
64            text = str(ctx.exception)
65            self.assertTrue(text.startswith(f"The profile of this launch ({prof}) cannot be read ("), text)
66            self.assertTrue(text.endswith("). Fix its permissions or move it away, then run the launch again."), text)
67            self.assertEqual(ctx.exception.exit_code, 2)
68            self.assertEqual(cfg.read_bytes(), before)
69
70    @unittest.skipUnless(POSIX_NOT_ROOT, "needs permissions that deny the owner")
71    def test_an_unreadable_profile_stops_the_launch_and_the_key_stays(self):
72        from strata_control import profiles
73        with Home():
74            cfg, prof = _write_state()
75            os.chmod(prof, 0)
76            try:
77                with self.assertRaises(profiles.ProfileError) as ctx:
78                    _runner().check_saved_state_readable()
79            finally:
80                os.chmod(prof, 0o600)
81            self.assertIn("(Permission denied)", str(ctx.exception))
82            self.assertIn("sk-strata-OLD", cfg.read_text(encoding="utf-8"))
83
84    @unittest.skipUnless(POSIX_NOT_ROOT, "needs permissions that deny the owner")
85    def test_an_unreadable_run_config_stops_the_launch_instead_of_minting_a_key(self):
86        from strata_cli.launch.runner import LaunchError
87        with Home():
88            cfg, prof = _write_state()
89            os.chmod(cfg, 0)
90            try:
91                with self.assertRaises(LaunchError) as ctx:
92                    _runner().check_saved_state_readable()
93            finally:
94                os.chmod(cfg, 0o600)
95            self.assertEqual(str(ctx.exception), f"The saved settings of this launch ({cfg}) cannot be read (Permission denied). Fix its permissions or move it away, "
96                                                 "then run the launch again: writing a new one would drop its API key and your changes.")
97            self.assertEqual(ctx.exception.code, 6)
98            self.assertIn("sk-strata-OLD", cfg.read_text(encoding="utf-8"))
99
100    def test_an_unreadable_run_config_is_refused_on_every_platform(self):
101        """The same, with the read failing the way a locked or permission-denied file fails (also testable on Windows)."""
102        from strata_cli.launch.runner import LaunchError
103        with Home():
104            cfg, prof = _write_state()
105            real = Path.read_bytes
106
107            def denied(self_):
108                if self_ == cfg:
109                    raise PermissionError(13, "Permission denied")
110                return real(self_)
111            with mock.patch.object(Path, "read_bytes", denied):
112                with self.assertRaises(LaunchError) as ctx:
113                    _runner().check_saved_state_readable()
114            self.assertIn("cannot be read (Permission denied)", str(ctx.exception))
115
116
117NEW_KEY = "A new API key was made, because the server is shared beyond this computer. It is saved with the preset; show it with: strata launch --show-key"
118
119
120class NewKeySentenceIsTrue(unittest.TestCase):
121    """The sentence "A new API key was made" is said only after the run config that holds the key has been written: not in the plan, not before a refusal."""
122
123    def _run(self, *, refuse=None, fail_after_write=None):
124        from strata_cli.launch import settings as S
125        from strata_cli.launch.runner import Runner
126        events, order = [], []
127        r = Runner(S.LaunchSettings(model="iq3_s", context=32768), emit=lambda e: events.append(e))
128        r.key_written_notice = NEW_KEY
129        base = Path(os.environ["STRATA_INSTALL_DIR"]) / "base.json"
130
131        def build(self_, base_path):
132            order.append("written")
133            return base
134        patches = [mock.patch.object(Runner, "check_own_files"), mock.patch.object(Runner, "check_serving", return_value=None),
135                   mock.patch.object(Runner, "ensure_engine"), mock.patch.object(Runner, "ensure_model", return_value=base),
136                   mock.patch.object(Runner, "ensure_drafter"), mock.patch.object(Runner, "build_config", build),
137                   mock.patch.object(Runner, "ensure_profile", side_effect=fail_after_write or (lambda *a, **k: None)),
138                   mock.patch.object(Runner, "tune", side_effect=RuntimeError("stop here")),
139                   mock.patch.object(Runner, "check_saved_state_readable", side_effect=refuse or (lambda *a, **k: None))]
140        for p in patches:
141            p.start()
142        self.addCleanup(lambda: [p.stop() for p in patches])
143        try:
144            r.run()
145        except Exception as exc:  # noqa: BLE001
146            return r, events, order, exc
147        return r, events, order, None
148
149    def test_a_refusal_before_the_write_says_nothing_about_a_new_key(self):
150        from strata_cli.launch.runner import LaunchError
151        with Home():
152            r, events, order, exc = self._run(refuse=LaunchError("cannot be read", "fix it"))
153        self.assertIsInstance(exc, LaunchError)
154        self.assertEqual(order, [])                                    # nothing was written
155        self.assertFalse(r.key_written)
156        self.assertNotIn(NEW_KEY, [e.text for e in events])
157
158    def test_the_sentence_comes_once_right_after_the_write(self):
159        with Home():
160            r, events, order, exc = self._run()
161        self.assertEqual(order, ["written"])
162        self.assertTrue(r.key_written)
163        said = [e for e in events if e.text == NEW_KEY]
164        self.assertEqual(len(said), 1)
165        self.assertEqual(said[0].level, "warn")
166        texts = [e.text for e in events]
167        self.assertLess(texts.index(NEW_KEY), texts.index("Settings are saved.") if "Settings are saved." in texts else len(texts))
168
169    def test_it_stays_true_when_something_fails_after_the_write(self):
170        from strata_control import profiles
171        with Home():
172            r, events, order, exc = self._run(fail_after_write=profiles.ProfileError("later problem"))
173        self.assertIsInstance(exc, profiles.ProfileError)
174        self.assertTrue(r.key_written)                                 # the key IS on disk then
175        self.assertIn(NEW_KEY, [e.text for e in events])
176
177    def test_the_plan_never_says_it(self):
178        from tests.terminal.launch_support import run_cli
179        with Home():
180            code, out, err = run_cli(["launch", "--plan", "--family", "qwen", "--model", "q2_0", "--access", "lan", "--yes"])
181        self.assertIn("Plan for", out, out + err)                       # the plan really ran
182        self.assertIn("API key on", out)                                 # and it knows a key is wanted
183        self.assertNotIn("A new API key was made", out + err)
184
185
186if __name__ == "__main__":
187    unittest.main()