okami.mom/strata

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

Niko1221Merge branch 'f-139-ux' into f-139-rel92ca0c7fb

main
8.9 KiB165 linesraw
1"""serve/test_runconfig.py - #564: the web page's Settings view of the run config (GET / POST /config), against the
2mock engine: only the listed keys change, every other key of the file stays, a bad value changes nothing, and only
3Strata's own page may write it (JSON, no foreign Origin, the API key when one is set).
4
5    python -m unittest serve.test_runconfig
6"""
7from __future__ import annotations
8
9import contextlib
10import io
11import json
12import tempfile
13import unittest
14import urllib.error
15import urllib.request
16from pathlib import Path
17
18from serve import runconfig
19from serve.frontend import ChatTemplate
20from serve.server import ByteTokenizer, MockEngine, Service, serve
21
22ROOT = Path(__file__).resolve().parents[1]
23CFG = {"exe": "engine/strata.exe", "args": ["--pack", "data/packs/q2_0", "--kv", "int8", "--spec-min-p", "0.5"],
24       "model_name": "qwen3.8-flash-next-q2_0", "port": 8080, "host": "0.0.0.0", "api_key": "",
25       "sampling": {"temperature": 0.7, "presence_penalty": 1.5},
26       "mcp_servers": {"files": {"command": "npx", "args": ["-y", "server-filesystem", "."]}},
27       "cors_origins": ["http://localhost:3000"]}
28
29
30class Apply(unittest.TestCase):
31    def test_only_the_named_keys_change(self):
32        new, changed = runconfig.apply(CFG, {"sampling.top_p": 0.95, "reasoning_budget_tokens": 4096,
33                                             "vram_reserve_mib": 2048, "aliases": "qwen, local", "lazy_load": True})
34        self.assertEqual(changed, ["sampling.top_p", "reasoning_budget_tokens", "vram_reserve_mib", "aliases",
35                                   "lazy_load"])
36        self.assertEqual(new["sampling"], {"temperature": 0.7, "presence_penalty": 1.5, "top_p": 0.95})
37        self.assertEqual(new["args"][-2:], ["--vram-reserve-mib", "2048"])
38        self.assertEqual(new["aliases"], ["qwen", "local"])
39        for k in ("exe", "model_name", "port", "host", "api_key", "mcp_servers", "cors_origins"):
40            self.assertEqual(new[k], CFG[k], k)
41        self.assertEqual(CFG["sampling"], {"temperature": 0.7, "presence_penalty": 1.5})   # the input is left alone
42
43    def test_null_is_the_default_again(self):
44        cfg, _ = runconfig.apply(CFG, {"vram_reserve_mib": 2048, "fit_max_tokens": True})
45        new, changed = runconfig.apply(cfg, {"vram_reserve_mib": None, "fit_max_tokens": None,
46                                             "sampling.temperature": None, "idle_unload_s": None})
47        self.assertEqual(changed, ["vram_reserve_mib", "fit_max_tokens", "sampling.temperature"])
48        self.assertEqual(new["args"], CFG["args"])
49        self.assertNotIn("fit_max_tokens", new)
50        self.assertEqual(new["sampling"], {"presence_penalty": 1.5})
51        new, _ = runconfig.apply({"sampling": {"top_k": 20}}, {"sampling.top_k": None})
52        self.assertNotIn("sampling", new)                                 # an empty block goes
53
54    def test_refused(self):
55        for changes in ({"api_key": "x"}, {"host": "0.0.0.0"}, {"mcp_servers": {}}, {"before_load": "calc.exe"},
56                        {"args": []}, {"exe": "evil.exe"}, {"trusted_origins": ["*"]}, {"allowed_hosts": ["*"]},
57                        {"sampling.temperature": -1}, {"sampling.top_p": 0}, {"sampling.top_k": 65},
58                        {"sampling.min_p": 2}, {"reasoning_budget_tokens": 1.5}, {"fit_max_tokens": "yes"},
59                        {"effort_position": "middle"}, {"vram_reserve_mib": -5}, {"idle_unload_s": True},
60                        {"aliases": [1]}, {}, None, ["x"]):
61            with self.subTest(changes=changes), self.assertRaises(ValueError):
62                runconfig.apply(CFG, changes)
63        with self.assertRaises(ValueError):                              # one bad value: nothing is applied
64            runconfig.apply(CFG, {"fit_max_tokens": True, "sampling.top_k": 0})
65        with self.assertRaises(ValueError):
66            runconfig.apply({**CFG, "vision": {"gpu": True}}, {"lazy_load": True})
67
68    def test_view(self):
69        v = runconfig.view({**CFG, "args": CFG["args"] + ["--vram-reserve-mib", "1500"]}, "x/strata-q2_0.json")
70        self.assertEqual(v["file"], "strata-q2_0.json")
71        got = {k["key"]: k for k in v["keys"]}
72        self.assertEqual(got["sampling.temperature"]["value"], 0.7)
73        self.assertEqual(got["vram_reserve_mib"]["value"], 1500)
74        self.assertIsNone(got["fit_max_tokens"]["value"])
75        self.assertEqual(got["anthropic_thinking"]["choices"], ["model", "on_request"])
76        self.assertNotIn("api_key", got)
77        self.assertNotIn("mcp_servers", got)
78
79
80class Http(unittest.TestCase):
81    def setUp(self):
82        self.dir = tempfile.TemporaryDirectory()
83        self.path = Path(self.dir.name) / "strata-q2_0.json"
84        self.path.write_text(json.dumps(CFG, indent=1), encoding="utf-8")
85        tok = ByteTokenizer()
86        self.svc = Service(MockEngine(tok, "ok", max_context=4096), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
87        self.svc.config_path = str(self.path)
88        self.httpd = serve(self.svc, port=0)
89        self.host = f"127.0.0.1:{self.httpd.server_address[1]}"
90
91    def tearDown(self):
92        self.httpd.shutdown()
93        self.httpd.server_close()
94        self.dir.cleanup()
95
96    def call(self, method, body=None, headers=None):
97        h = {"Content-Type": "application/json", **(headers or {})}
98        req = urllib.request.Request(f"http://{self.host}/config", method=method, headers=h,
99                                     data=None if body is None else (body if isinstance(body, bytes)
100                                                                     else json.dumps(body).encode()))
101        try:
102            with urllib.request.urlopen(req, timeout=10) as r:
103                return r.status, json.loads(r.read())
104        except urllib.error.HTTPError as e:
105            with e:
106                return e.code, json.loads(e.read())
107
108    def saved(self):
109        return json.loads(self.path.read_text(encoding="utf-8"))
110
111    def test_read_and_write_from_the_page(self):
112        status, v = self.call("GET")
113        self.assertEqual(status, 200, v)
114        self.assertEqual({k["key"]: k["value"] for k in v["keys"]}["sampling.temperature"], 0.7)
115        with contextlib.redirect_stdout(io.StringIO()):
116            status, v = self.call("POST", {"set": {"sampling.temperature": 1.0, "open_browser": False}},
117                                  {"Origin": f"http://{self.host}"})
118        self.assertEqual(status, 200, v)
119        self.assertEqual(v["changed"], ["sampling.temperature", "open_browser"])
120        cfg = self.saved()
121        self.assertEqual(cfg["sampling"]["temperature"], 1.0)
122        self.assertIs(cfg["open_browser"], False)
123        for k in ("mcp_servers", "cors_origins", "host", "args", "exe"):
124            self.assertEqual(cfg[k], CFG[k], k)
125        self.assertEqual(json.loads((self.path.parent / "strata-q2_0.json.bak").read_text(encoding="utf-8")), CFG)
126        status, v = self.call("POST", {"set": {"open_browser": False}})   # no Origin (a script on this PC): allowed
127        self.assertEqual((status, v["changed"]), (200, []))
128
129    def test_only_from_strata_s_own_page(self):
130        before = self.path.read_bytes()
131        status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Origin": "https://evil.example"})
132        self.assertEqual(status, 403)
133        status, _ = self.call("POST", b'{"set": {"fit_max_tokens": true}}', {"Content-Type": "text/plain"})
134        self.assertEqual(status, 415)
135        for body in ({"set": {"api_key": ""}}, {"set": {"mcp_servers": {"x": {"command": "calc"}}}},
136                     {"set": {"sampling.top_k": 0}}, {"nothing": 1}, b"not json"):
137            status, b = self.call("POST", body, {"Origin": f"http://{self.host}"})
138            self.assertEqual(status, 400, (body, b))
139        self.assertEqual(self.path.read_bytes(), before)                 # nothing was written
140        self.assertFalse((self.path.parent / "strata-q2_0.json.bak").exists())
141
142    def test_the_api_key(self):
143        self.svc.api_key = "secret"
144        self.assertEqual(self.call("GET")[0], 401)
145        self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 401)
146        with contextlib.redirect_stdout(io.StringIO()):
147            status, _ = self.call("POST", {"set": {"fit_max_tokens": True}}, {"Authorization": "Bearer secret"})
148        self.assertEqual(status, 200)
149        self.assertIs(self.saved()["fit_max_tokens"], True)
150
151    def test_without_a_run_config(self):
152        self.svc.config_path = None
153        self.assertEqual(self.call("GET")[0], 404)
154        self.assertEqual(self.call("POST", {"set": {"fit_max_tokens": True}})[0], 404)
155
156    def test_the_page_has_the_view(self):
157        web = ROOT / "serve" / "web"
158        html, js = (web / "index.html").read_text(encoding="utf-8"), (web / "app.js").read_text(encoding="utf-8")
159        for el in ("cfg-card", "cfg-form", "cfg-save", "cfg-msg"):
160            self.assertIn(f'id="{el}"', html)
161        self.assertIn('fetch("config", {method: "POST", headers: headers(true)', js)
162
163
164if __name__ == "__main__":
165    unittest.main()