okami.mom/strata

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

Niko1221Terminal Overview: the ASCII look has no U+00B7 (a redirected stdout in cp852, cp874, cp932 or ascii raised UnicodeEncodeError); test_speed_average decodes node's output as UTF-8 instead of the locale code page568127b7a

main
6.8 KiB112 linesraw
1"""The run average of the speed cards (community patch: keinebenutzer/STRATA-average-patch, MIT, made against v0.1.55 c62d5e3a; ported by hand onto rc1).
2
3serve/web/app.js (the Monitor tab's Decode and Prefill cards), serve/web/monitor.js and monitor.html (the API monitor page) and strata_cli/overview.py (the Terminal
4Overview) show, when the server is idle, the token-weighted average of the run instead of the last request's speed. Live values stay live. This file runs the
5browser code the way a page would (a few lines of node, no browser, no network) and checks that what was added is display only."""
6import json
7import re
8import shutil
9import subprocess
10import unittest
11from pathlib import Path
12
13WEB = Path(__file__).resolve().parent / "web"
14NODE = shutil.which("node")
15
16
17def run_node(source: str) -> object:
18    done = subprocess.run([NODE, "-e", source], capture_output=True, text=True, encoding="utf-8", timeout=60, check=True)   # node writes UTF-8; the locale code page (cp1252, cp932 ...) is not what it speaks
19    return json.loads(done.stdout)
20
21
22def function_source(text: str, name: str) -> str:
23    """One top-level function of a browser script, by its opening line to its closing brace in column 0."""
24    start = text.index(f"function {name}(")
25    end = text.index("\n}\n", start) + 3
26    return text[start:end]
27
28
29def cards_block(text: str) -> str:
30    """The lines of renderMonitor that make the Decode and Prefill cards."""
31    start = text.index("  // the eight cards")
32    return text[start:text.index('  spark("sp-speed"', start)]
33
34
35@unittest.skipUnless(NODE, "node is needed to run the page's own code")
36class MonitorTab(unittest.TestCase):
37    """serve/web/app.js: the two cards, run with stand-ins for the page's helpers."""
38
39    def cards(self, live, last, totals):
40        block = cards_block((WEB / "app.js").read_text(encoding="utf-8"))
41        script = ("const calls = []; const setMetric = (...a) => calls.push(a); const fmt = (n, d = 0) => Number(n).toFixed(d);\n"
42                  f"function run(live, last, totals) {{\n{block}\n}}\nrun({json.dumps(live)}, {json.dumps(last)}, {json.dumps(totals)});\nconsole.log(JSON.stringify(calls));")
43        script = script.replace("spark(", "(() => {})(")
44        calls = run_node(script)
45        return {c[0]: (c[1], c[3]) for c in calls}
46
47    TOTALS = {"requests": 12, "prompt_tokens": 90000, "reused": 5000, "output_tokens": 40000, "prompt_ms": 120000.0, "decode_ms": 1000000.0}
48    LAST = {"decode_tok_s": 50.5, "prompt_ms": 2000.0, "prompt_tokens": 1000, "reused": 0}
49
50    def test_idle_shows_the_run_average_for_both_cards(self):
51        cards = self.cards({"state": "idle"}, self.LAST, self.TOTALS)
52        self.assertEqual(cards["speed"], ("40.0", "Decode · run average"))
53        self.assertEqual(cards["prefill"], ("708", "Prefill · run average"), "(90000 - 5000 reused) tokens in 120 s")
54
55    def test_live_values_stay_live(self):
56        self.assertEqual(self.cards({"state": "generating", "tok_s": 31.5, "prefill_tok_s_mean": 600}, self.LAST, self.TOTALS)["speed"], ("31.5", "Decode now"))
57        self.assertEqual(self.cards({"state": "generating", "tok_s": 31.5, "prefill_tok_s_mean": 600}, self.LAST, self.TOTALS)["prefill"], ("600", "Prefill this request"))
58        self.assertEqual(self.cards({"state": "reading", "prefill_tok_s_mean": 820}, self.LAST, self.TOTALS)["prefill"], ("820", "Prefill now"))
59
60    def test_without_totals_it_is_the_last_request_and_never_an_invented_zero(self):
61        for totals in (None, {}, {"output_tokens": 0, "decode_ms": 0, "prompt_tokens": 0, "prompt_ms": 0}):
62            cards = self.cards({"state": "idle"}, self.LAST, totals)
63            self.assertEqual(cards["speed"], ("50.5", "Decode last request"), totals)
64            self.assertEqual(cards["prefill"], ("500", "Prefill last request"), totals)
65        cards = self.cards({"state": "idle"}, None, None)
66        self.assertEqual(cards["speed"], (None, "Decode"))
67        self.assertEqual(cards["prefill"], (None, "Prefill"))
68
69
70@unittest.skipUnless(NODE, "node is needed to run the page's own code")
71class MonitorPage(unittest.TestCase):
72    def average(self, rows):
73        source = function_source((WEB / "monitor.js").read_text(encoding="utf-8"), "averageDecodeSpeed")
74        return run_node(f"{source}\nconsole.log(JSON.stringify(averageDecodeSpeed({json.dumps(rows)})));")
75
76    def test_it_is_token_weighted_over_the_finished_requests(self):
77        long_one = {"timings": {"predicted_n": 19511, "predicted_ms": 386000}}
78        short_one = {"timings": {"predicted_n": 11, "predicted_ms": 410}}
79        self.assertAlmostEqual(self.average([long_one, short_one]), (19511 + 11) / (386410 / 1000), places=6)
80        self.assertGreater(self.average([long_one, short_one]), 50, "a plain mean of the two (about 38) would let the short one count as much as the long one")
81
82    def test_requests_without_timings_or_with_one_token_are_left_out(self):
83        self.assertIsNone(self.average([]))
84        self.assertIsNone(self.average([{}, {"timings": None}, {"timings": {"predicted_n": 1, "predicted_ms": 10}}, {"timings": {"predicted_n": 5, "predicted_ms": 0}},
85                                        {"timings": {"predicted_n": "9", "predicted_ms": 5}}]))
86        self.assertEqual(self.average([{"timings": {"predicted_n": 100, "predicted_ms": 2000}}, {}]), 50)
87
88    def test_the_card_says_what_it_shows(self):
89        html = (WEB / "monitor.html").read_text(encoding="utf-8")
90        self.assertIn("Average decode speed", html)
91        self.assertIn("Run average", html)
92        self.assertNotIn("Last decode speed", html)
93        js = (WEB / "monitor.js").read_text(encoding="utf-8")
94        self.assertIn('text("speed", speed(averageDecodeSpeed(records.filter(r => !active(r)))))', js)
95
96
97class AddedCodeIsDisplayOnly(unittest.TestCase):
98    """What the patch added reads numbers the page already has and writes text with textContent: no request, no eval, no markup, no address."""
99
100    def test_nothing_but_arithmetic_and_text(self):
101        pieces = [cards_block((WEB / "app.js").read_text(encoding="utf-8")), function_source((WEB / "monitor.js").read_text(encoding="utf-8"), "averageDecodeSpeed"),
102                  (Path(__file__).resolve().parents[1] / "strata_cli" / "overview.py").read_text(encoding="utf-8")]
103        pieces[2] = pieces[2][pieces[2].index("def run_average_speed"):pieces[2].index("def _cards")]
104        forbidden = re.compile(r"\b(fetch|XMLHttpRequest|WebSocket|sendBeacon|eval|Function|import|require|innerHTML|insertAdjacentHTML|document\.write|"
105                               r"subprocess|socket|urllib|requests|os\.system|open)\s*\(|https?://|\.src\s*=|new Image")
106        for piece in pieces:
107            self.assertIsNone(forbidden.search(piece), forbidden.search(piece) and forbidden.search(piece).group(0))
108        self.assertIn("textContent", (WEB / "monitor.js").read_text(encoding="utf-8"))
109
110
111if __name__ == "__main__":
112    unittest.main()