okami.mom/strata

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

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

main
6.0 KiB135 linesraw
1"""Round 0213 TUICFG, step 1: profile identity and keys (#4395, #4396).
2
3Real temporary profile files (isolated home); only the runtime status is a double. A damaged profile must neither throw nor lend its
4neighbour's endpoint/config/key, in either order."""
5from __future__ import annotations
6
7import json
8import sys
9import unittest
10from pathlib import Path
11from unittest import mock
12
13ROOT = Path(__file__).resolve().parents[2]
14sys.path.insert(0, str(ROOT))
15
16from tests.terminal.launch_support import Home  # noqa: E402
17
18
19def _cfg(home: Home, name: str, key: str) -> Path:
20    path = home.base / f"{name}.run.json"
21    path.write_text(json.dumps({"exe": str(home.base / "engine.exe"), "tokenizer": str(home.base / "tok.json"), "args": [],
22                                "api_key": key, "model_name": name}), encoding="utf-8")
23    return path
24
25
26def _profile(home: Home, pid: str, cfg: Path | None, port: int | None = None, host: str | None = None) -> None:
27    d = Path(home.env["STRATA_PROFILE_DIR"])
28    d.mkdir(parents=True, exist_ok=True)
29    ov = {}
30    if port is not None:
31        ov["port"] = port
32    if host is not None:
33        ov["host"] = host
34    (d / f"{pid}.json").write_text(json.dumps({"schema_version": 1, "id": pid, "source_config": str(cfg), "overrides": ov}), encoding="utf-8")
35
36
37def _broken(home: Home, pid: str, how: str = "garbage") -> None:
38    d = Path(home.env["STRATA_PROFILE_DIR"])
39    d.mkdir(parents=True, exist_ok=True)
40    (d / f"{pid}.json").write_text("{not json" if how == "garbage" else json.dumps({"schema_version": 1, "id": pid}), encoding="utf-8")
41
42
43class RunningLaunchesBrokenProfile(unittest.TestCase):
44    """#4395: prof was read outside the try that binds it."""
45
46    def _rows(self, first_broken: bool):
47        from strata_cli.launch import cmd
48        with Home() as home:
49            good_cfg = _cfg(home, "good", "sk-strata-GOOD")
50            if first_broken:
51                _broken(home, "launch-a-broken")
52                _profile(home, "launch-b-good", good_cfg, port=18123, host="0.0.0.0")
53            else:
54                _profile(home, "launch-a-good", good_cfg, port=18123, host="0.0.0.0")
55                _broken(home, "launch-b-broken")
56            with mock.patch("strata_control.runtime.status", return_value={"state": "ready"}):
57                return cmd.running_launches()
58
59    def test_broken_first_does_not_throw_and_good_row_is_intact(self):
60        rows = self._rows(first_broken=True)
61        self.assertEqual(len(rows), 2)
62        bad = next(r for r in rows if r["name"].endswith("broken"))
63        good = next(r for r in rows if r["name"].endswith("good"))
64        self.assertIsNone(bad["config"])
65        self.assertEqual(good["port"], 18123)
66        self.assertTrue(good["config"].endswith("good.run.json"))
67
68    def test_broken_after_valid_never_shows_the_previous_rows_endpoint_or_config(self):
69        rows = self._rows(first_broken=False)
70        self.assertEqual(len(rows), 2)
71        bad = next(r for r in rows if r["name"].endswith("broken"))
72        self.assertIsNone(bad["config"])
73        self.assertNotEqual(bad["port"], 18123)
74        self.assertEqual(bad["host"], "127.0.0.1")
75
76    def test_connect_info_never_returns_another_profiles_key(self):
77        from strata_cli.launch import cmd
78        for first_broken in (True, False):
79            with self.subTest(first_broken=first_broken), Home() as home:
80                good_cfg = _cfg(home, "good", "sk-strata-GOOD")
81                bad_id, good_id = ("launch-a-broken", "launch-b-good") if first_broken else ("launch-b-broken", "launch-a-good")
82                _broken(home, bad_id)
83                _profile(home, good_id, good_cfg, port=18123)
84                with mock.patch("strata_control.runtime.status", return_value={"state": "ready"}):
85                    bad = cmd.launch_info(bad_id[7:])
86                    good = cmd.launch_info(good_id[7:])
87                self.assertIsNone(bad["key"])
88                self.assertNotEqual(bad["port"], 18123)
89                self.assertEqual(good["key"], "sk-strata-GOOD")
90                self.assertEqual(good["port"], 18123)
91
92
93class KeptKeyBrokenProfile(unittest.TestCase):
94    """#4396: one unreadable profile must not make kept_key() mint a new key."""
95
96    def test_valid_key_survives_a_damaged_profile_in_either_order(self):
97        from strata_cli.launch import access
98        for order in ("broken-first", "broken-last"):
99            for how in ("garbage", "missing-fields"):
100                with self.subTest(order=order, how=how), Home() as home:
101                    cfg = _cfg(home, "ok", "sk-strata-KEEP")
102                    if order == "broken-first":
103                        _broken(home, "launch-a-bad", how)
104                        _profile(home, "launch-b-ok", cfg)
105                    else:
106                        _profile(home, "launch-a-ok", cfg)
107                        _broken(home, "launch-b-bad", how)
108                    self.assertEqual(access.kept_key(), "sk-strata-KEEP")
109
110    def test_the_named_launch_with_a_damaged_profile_falls_back_to_the_other_valid_key(self):
111        from strata_cli.launch import access
112        with Home() as home:
113            cfg = _cfg(home, "ok", "sk-strata-KEEP")
114            _broken(home, "launch-mine")
115            _profile(home, "launch-other", cfg)
116            self.assertEqual(access.kept_key("mine"), "sk-strata-KEEP")
117
118    def test_a_config_row_without_a_source_is_skipped_not_fatal(self):
119        from strata_cli.launch import access
120        with Home() as home:
121            cfg = _cfg(home, "ok", "sk-strata-KEEP")
122            _profile(home, "launch-ok", cfg)
123            rows = [{"id": "launch-err", "error": "cannot read profile (PermissionError)"}, {"id": "launch-ok", "source_config": str(cfg)}]
124            with mock.patch("strata_control.profiles.list_profiles", return_value=rows):
125                self.assertEqual(access.kept_key(), "sk-strata-KEEP")
126
127    def test_no_valid_profile_still_returns_none(self):
128        from strata_cli.launch import access
129        with Home() as home:
130            _broken(home, "launch-only")
131            self.assertIsNone(access.kept_key())
132
133
134if __name__ == "__main__":
135    unittest.main()