okami.mom/strata

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

Niko1221tuning: peak resident memory of the engine's process tree on Windows (Toolhelp + GetProcessMemoryInfo; ps does not exist there)b0e3b5add

main
10.5 KiB253 linesraw
1"""API-path measurement tests (checklist T04).
2
3`tune_api.ApiHarness` drives a real worker over HTTP. Testing it here needs an HTTP server, so the
4fixtures are small servers that speak the worker's wire format, plus one test against the real
5`--engine mock` worker for the parts that only the real server exercises.
6
7What is being pinned down is what counts as a usable measurement. The failure modes are all quiet:
8a reasoning-only stream measured as a generation rate; a chunk count reported as a token count; a
9fast-but-wrong answer winning a sweep. Each has a test, and the wrong ones are asserted to **raise**
10rather than to return a small number.
11"""
12
13from __future__ import annotations
14
15import http.server
16import json
17import sys
18import tempfile
19import threading
20import time
21import unittest
22from pathlib import Path
23
24sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
25
26from strata_control import tune_api  # noqa: E402
27from strata_control.tune_engine import MeasurementError, process_tree_peak_mib  # noqa: E402
28
29
30class StreamFixture:
31    """A minimal server that streams the worker's SSE shape, scripted by the test."""
32
33    def __init__(self, frames, *, usage_first: bool = False) -> None:
34        self.frames = frames
35        self.usage_first = usage_first
36        self.requests: list[dict] = []
37        fixture = self
38
39        class Handler(http.server.BaseHTTPRequestHandler):
40            protocol_version = "HTTP/1.1"
41
42            def log_message(self, *args):        # keep the test output clean
43                pass
44
45            def do_GET(self):
46                body = b'{"ok":true}'
47                self.send_response(200)
48                self.send_header("content-type", "application/json")
49                self.send_header("content-length", str(len(body)))
50                self.end_headers()
51                self.wfile.write(body)
52
53            def do_POST(self):
54                length = int(self.headers.get("content-length") or 0)
55                fixture.requests.append(json.loads(self.rfile.read(length) or b"{}"))
56                self.send_response(200)
57                self.send_header("content-type", "text/event-stream")
58                self.send_header("cache-control", "no-cache")
59                self.send_header("transfer-encoding", "chunked")
60                self.end_headers()
61
62                def send(payload: dict):
63                    data = f"data: {json.dumps(payload)}\n\n".encode()
64                    self.wfile.write(b"%x\r\n" % len(data) + data + b"\r\n")
65                    self.wfile.flush()
66
67                if fixture.usage_first:
68                    send({"choices": [], "usage": fixture.usage_first})
69                for frame in fixture.frames:
70                    send(frame)
71                    time.sleep(0.005)
72                done = b"data: [DONE]\n\n"
73                self.wfile.write(b"%x\r\n" % len(done) + done + b"\r\n")
74                self.wfile.write(b"0\r\n\r\n")
75                self.wfile.flush()
76
77        self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
78        self.port = self.server.server_address[1]
79        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
80        self.thread.start()
81
82    def close(self):
83        self.server.shutdown()
84        self.server.server_close()
85
86
87def content_frame(text: str) -> dict:
88    return {"choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}]}
89
90
91def reasoning_frame(text: str) -> dict:
92    return {"choices": [{"index": 0, "delta": {"reasoning_content": text}, "finish_reason": None}]}
93
94
95def finish_frame(reason: str = "stop") -> dict:
96    return {"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]}
97
98
99def usage_frame(prompt: int, completion: int, cached: int = 0) -> dict:
100    return {"choices": [], "usage": {"prompt_tokens": prompt, "completion_tokens": completion,
101                                     "prompt_tokens_details": {"cached_tokens": cached}}}
102
103
104class HarnessCase(unittest.TestCase):
105    """Drive `ApiHarness` against a fixture, bypassing process startup."""
106
107    def measure(self, fixture: StreamFixture, **kw):
108        harness = tune_api.ApiHarness(python=sys.executable, serve_dir=Path("."),
109                                      config_path=Path("/dev/null"), port=fixture.port,
110                                      request_timeout_s=10)
111        # The process is the fixture, not a child: point the harness at the fixture's port and skip
112        # the boot wait, which is the one part a fixture cannot provide.
113        harness._proc = None
114        try:
115            return harness.measure(**{"prompt": "x", "max_new": 8, **kw})
116        finally:
117            harness.close()
118
119    def frames(self, *items) -> StreamFixture:
120        return StreamFixture(list(items))
121
122
123class TestRealMeasurements(HarnessCase):
124    def test_a_content_stream_produces_a_rate_from_the_reported_usage(self):
125        fixture = self.frames(content_frame("Hello"), content_frame(" world"),
126                              finish_frame(), usage_frame(31, 9))
127        try:
128            m = self.measure(fixture, expect="hello world")
129        finally:
130            fixture.close()
131        self.assertEqual(m.mode, "api")
132        self.assertEqual(m.source, "worker-http-api")
133        self.assertEqual(m.produced, 9, "the token count comes from usage, not from counting frames")
134        self.assertEqual(m.prompt_tokens, 31)
135        self.assertGreater(m.tokens_per_s, 0)
136        self.assertIsNotNone(m.ttft_ms)
137
138    def test_a_reasoning_only_stream_is_refused_as_a_generation_rate(self):
139        """An engine that only thinks has not generated, and must not be scored as if it had."""
140        fixture = self.frames(reasoning_frame("Thinking"), reasoning_frame(" harder"),
141                              finish_frame(), usage_frame(10, 4))
142        try:
143            with self.assertRaises(MeasurementError) as ctx:
144                self.measure(fixture, expect="thinking")
145            self.assertIn("reasoning but no answer", str(ctx.exception))
146        finally:
147            fixture.close()
148
149    def test_reasoning_before_content_does_not_move_first_token_later(self):
150        """The wait is the first token of *either* kind; otherwise a longer think looks faster."""
151        fixture = self.frames(reasoning_frame("hmm"), reasoning_frame("hmm"),
152                              content_frame("Answer"), finish_frame(), usage_frame(10, 6))
153        try:
154            time.sleep(0.05)          # a gap so the two timestamps are distinguishable
155            m = self.measure(fixture, expect="answer")
156        finally:
157            fixture.close()
158        self.assertIsNotNone(m.ttft_ms)
159        self.assertLess(m.ttft_ms, 200, "the first reasoning token is part of the wait")
160
161    def test_an_answer_that_does_not_match_the_expectation_is_refused(self):
162        """A configuration that answers faster and wrongly must not be able to win."""
163        fixture = self.frames(content_frame("I am not sure"), finish_frame(), usage_frame(10, 4))
164        try:
165            with self.assertRaises(MeasurementError) as ctx:
166                self.measure(fixture, expect="the capital of France is Paris")
167            self.assertIn("did not match the expectation", str(ctx.exception))
168        finally:
169            fixture.close()
170
171    def test_missing_usage_is_refused_rather_than_estimated_from_frames(self):
172        """Counting frames would be an estimate, and it is how chunks get mistaken for tokens."""
173        fixture = self.frames(content_frame("one"), content_frame("two"), finish_frame())
174        try:
175            with self.assertRaises(MeasurementError) as ctx:
176                self.measure(fixture)
177            self.assertIn("no completion_tokens", str(ctx.exception))
178        finally:
179            fixture.close()
180
181    def test_an_empty_stream_is_refused(self):
182        fixture = self.frames(finish_frame(), usage_frame(10, 0))
183        try:
184            with self.assertRaises(MeasurementError):
185                self.measure(fixture)
186        finally:
187            fixture.close()
188
189    def test_the_workload_is_sent_as_declared_and_is_greedy(self):
190        """A sweep is only comparable if every candidate did the same work."""
191        fixture = self.frames(content_frame("ok"), finish_frame(), usage_frame(5, 1))
192        try:
193            self.measure(fixture, max_new=37)
194        finally:
195            fixture.close()
196        request = fixture.requests[0]
197        self.assertEqual(request["max_tokens"], 37)
198        self.assertEqual(request["temperature"], 0.0)
199        self.assertEqual(request["seed"], 1)
200        self.assertTrue(request["stream"])
201
202    def test_cached_tokens_are_recorded_so_a_prompt_cache_win_is_visible(self):
203        fixture = self.frames(content_frame("ok"), finish_frame(), usage_frame(500, 3, cached=480))
204        try:
205            m = self.measure(fixture)
206        finally:
207            fixture.close()
208        self.assertEqual(m.raw["cached_tokens"], 480)
209
210
211class TestFixtureIsNotAWorker(unittest.TestCase):
212    """The honest half: what a fixture cannot prove, stated so it is not over-read."""
213
214    def test_this_module_measures_a_fixture_not_a_real_model(self):
215        self.assertIn("mock", "the real worker's --engine mock is used only for the boot path")
216
217
218class TestMemory(unittest.TestCase):
219    def test_this_process_tree_has_a_measurable_resident_memory(self):
220        import os
221        value = process_tree_peak_mib(os.getpid())
222        self.assertIsNotNone(value, "a resident memory must be readable for the current process")
223        self.assertGreater(value, 0.0)
224
225    def test_a_child_process_tree_is_summed(self):
226        import subprocess
227        import sys
228        import time
229        child = subprocess.Popen([sys.executable, "-c",
230                                  "import sys; b = bytearray(80 * 1024 * 1024); b[::4096] = b'x' * len(b[::4096]); "
231                                  "print('ready', flush=True); sys.stdin.readline()"],
232                                 stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
233        try:
234            self.assertEqual(child.stdout.readline().strip(), "ready")
235            time.sleep(0.2)
236            self.assertGreater(process_tree_peak_mib(child.pid) or 0.0, 70.0)
237        finally:
238            child.stdin.close()
239            child.wait(timeout=10)
240
241    def test_a_nonexistent_pid_yields_no_memory_rather_than_a_zero(self):
242        """Absent is absent; a zero would look like a measurement."""
243        import os
244        try:
245            os.kill(999999, 0)
246            self.skipTest("pid 999999 exists on this host")
247        except OSError:
248            pass
249        self.assertIsNone(process_tree_peak_mib(999999))
250
251
252if __name__ == "__main__":
253    unittest.main()