okami.mom/strata

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

Niko1221Merge f-0213-own (final daf4ac087) into f-0213-int4d482e627

main
14.9 KiB328 linesraw
1"""Smaller serve-side robustness fixes of round 0213 (each test fails on the base a3a10b90a):
2
3#3443 ConvCacheLog.poll without a lock, #4792 a failed engine start when another thread closed the process,
4#4738 lost wake-ups of the control-line queue, #5044 a byte that is not UTF-8 on the engine's stdout.
5The fake engine and helpers are those of test_stream_ownership.py.
6"""
7import sys
8import tempfile
9import threading
10import unittest
11from pathlib import Path
12from unittest import mock
13
14from serve.server import StrataEngine
15from serve.test_stream_ownership import FakeEngines, canary_script, collect, expected_reply, prompt_ids
16
17
18class ConvCachePoll(unittest.TestCase):
19    """ConvCacheLog.poll ran outside any lock: a second poll that moved `pos` between the first one's size check and
20    its read left a negative read length (ValueError).  Found by HWSTALL while triaging #3443."""
21    PARK = ("strata serve: conversation cache: parked 5000 tokens in 12.0 ms; parked=1 bytes=104857600 evictions=0 "
22            "snapshot_bytes=104857600 reused_kv_bytes=0\n")
23
24    def test_a_poll_that_overlaps_another_one_does_not_raise(self):
25        import os
26        from serve.server import ConvCacheLog
27        with tempfile.TemporaryDirectory() as d:
28            log = Path(d) / "strata.log"
29            log.write_text(self.PARK, encoding="utf-8")
30            c = ConvCacheLog()
31            c.poll(str(log), 0)
32            with open(log, "a", encoding="utf-8") as f:
33                f.write(self.PARK)
34            first_sized, first_may_go = threading.Event(), threading.Event()
35            real_size = os.path.getsize
36            calls = []
37
38            def slow_first(path):
39                size = real_size(path)
40                if not calls and path == str(log):
41                    calls.append(1)
42                    first_sized.set()
43                    first_may_go.wait(2.0)             # the first poll has its size; a second poll runs meanwhile
44                return size
45            errors = []
46
47            def first():
48                try:
49                    c.poll(str(log), 0)
50                except BaseException as e:             # noqa: BLE001
51                    errors.append(e)
52            with mock.patch("serve.server.os.path.getsize", slow_first):
53                t = threading.Thread(target=first, daemon=True)
54                t.start()
55                self.assertTrue(first_sized.wait(5))
56                with open(log, "a", encoding="utf-8") as f:
57                    f.write(self.PARK * 2)
58                second = threading.Thread(target=lambda: c.poll(str(log), 0), daemon=True)
59                second.start()
60                second.join(0.5)                       # (with the lock it waits for the first one)
61                first_may_go.set()
62                t.join(5)
63                second.join(5)
64            self.assertEqual(errors, [])
65            self.assertEqual(c.poll(str(log), 0)["parks"], 4, "every parked line counted once")
66
67
68class FailedStart(unittest.TestCase):
69    """#4792 (PR by a community author; the fix is written in our tree): a start that ends before READY must not crash
70    when another thread closed the process (set self.proc to None) while the failed start cleaned up."""
71
72    def test_close_from_another_thread_during_a_failed_start(self):
73        import serve.server as server
74        holder = {}
75
76        class Pipe:
77            def close(self):
78                pass
79
80            def __iter__(self):
81                return iter(())                      # the engine's output ends: no READY
82
83        class Proc:
84            returncode = 1
85            stdin, stdout = Pipe(), Pipe()
86            pid = 0
87
88            def wait(self, timeout=None):
89                holder["engine"].proc = None         # restart()'s close() on another thread
90                return 1
91
92            def poll(self):
93                return 1
94
95            def kill(self):
96                pass
97
98        engine = StrataEngine.__new__(StrataEngine)
99        holder["engine"] = engine
100        with mock.patch.object(server, "popen", lambda *a, **k: Proc()), \
101                mock.patch.object(server, "end_leftover_engines", lambda exe: None), \
102                mock.patch.object(server, "transient_start_failure", lambda *a, **k: False):
103            with self.assertRaises(server.EngineDied):
104                engine.__init__("strata", [], retry_args=None)
105
106
107class ControlNotify(unittest.TestCase):
108    """#4738 (the PR's approach, written in our tree): a request that waits for the control lines must not miss a
109    notification sent between its check of the turn and its wait, and a waiter that leaves tells the others."""
110
111    class Cond(threading.Condition):
112        def __init__(self):
113            super().__init__()
114            self.exits, self.after_check, self.waits, self.notifications = 0, None, [], 0
115
116        def __exit__(self, *args):
117            result = super().__exit__(*args)
118            self.exits += 1
119            if self.exits == 2 and self.after_check is not None:     # registered (1), turn read (2): now the producer
120                hook, self.after_check = self.after_check, None
121                hook()
122            return result
123
124        def wait(self, timeout=None):
125            self.waits.append(timeout)
126            return True                                              # (never blocks: the test is the schedule)
127
128        def notify_all(self):
129            self.notifications += 1
130            return super().notify_all()
131
132    def engine(self):
133        e = StrataEngine.__new__(StrataEngine)
134        e.slot_cv, e.waiting, e.admitting = self.Cond(), 1, 0        # one other request is waiting
135        e.wait_lens, e.arrivals, e.ctl_epoch, e.ctl = [], __import__("collections").deque(maxlen=64), 0, threading.Lock()
136        e.proc, e.ended, e.starting = mock.Mock(**{"poll.return_value": None}), False, False
137        return e
138
139    def test_a_notification_between_the_check_and_the_wait_is_not_lost(self):
140        e = self.engine()
141
142        def producer():                                              # another request took the lines and gave them back
143            with e.slot_cv:
144                e.ctl_epoch += 1
145                e.slot_cv.notify_all()
146        e.slot_cv.after_check = producer
147        gen = e._take_control(threading.Event(), 10, after_epoch=0)
148        with self.assertRaises(StopIteration) as done:
149            for _ in range(5):
150                next(gen)
151        self.assertTrue(done.exception.value)
152        self.assertEqual(e.slot_cv.waits, [], "it waited although its turn had come in the meantime")
153
154    def test_a_waiter_that_leaves_notifies_the_others(self):
155        e = self.engine()
156        e.ctl.acquire()                                              # the lines are taken: this one cannot have them
157        cancel = threading.Event()
158        cancel.set()
159        gen = e._take_control(cancel, 10)
160        with self.assertRaises(StopIteration) as done:
161            for _ in range(3):
162                next(gen)
163        self.assertFalse(done.exception.value)
164        self.assertGreaterEqual(e.slot_cv.notifications, 1)
165        self.assertEqual(e.waiting, 1)
166
167
168class StalledClient(unittest.TestCase):
169    """#4271: a streaming client that stops reading, without closing its connection, must not hold the engine's turn
170    for ever: the write that makes no progress ends the request as a disconnect and the next request is served."""
171
172    def test_a_client_that_stops_reading_gives_the_turn_back(self):
173        import json
174        import socket
175        import time
176        import urllib.request
177        import serve.server as server
178        from serve.frontend import ChatTemplate
179        from serve.server import ByteTokenizer, MockEngine, Service, serve
180        tok = ByteTokenizer()
181        engine = MockEngine(tok, " ".join(str(i) for i in range(80000)), max_context=2_000_000)   # (not one repeated token)
182        svc = Service(engine, tok, ChatTemplate(Path(server.__file__).parent / "chat_template.jinja"))
183        httpd = serve(svc, port=0)
184        port = httpd.server_address[1]
185        stuck = socket.socket()
186        try:
187            with mock.patch.object(server, "STREAM_WRITE_TIMEOUT_S", 0.5, create=True):
188                stuck.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
189                stuck.connect(("127.0.0.1", port))
190                body = json.dumps({"messages": [{"role": "user", "content": "go"}], "stream": True,
191                                   "max_tokens": 400000, "reasoning_effort": "none"}).encode()
192                stuck.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n"
193                              b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body)
194                # ... and it never reads.  Wait until the server is writing into a full buffer, then until it lets go.
195                end = time.monotonic() + 3
196                while time.monotonic() < end and not svc.fifo.locked():
197                    time.sleep(0.01)
198                self.assertTrue(svc.fifo.locked(), "the stuck client's request holds the engine's turn")
199                end = time.monotonic() + 20
200                while time.monotonic() < end and svc.fifo.locked():
201                    time.sleep(0.05)
202                self.assertFalse(svc.fifo.locked(), "the turn is still held by a client that does not read")
203        finally:
204            stuck.close()
205            httpd.shutdown()
206            httpd.server_close()
207
208
209    def test_a_client_that_reads_but_waits_for_a_slow_engine_is_not_cut_off(self):
210        """The write limit is for a write that makes no progress (the client stopped reading), not for a client that is
211        idle while the engine thinks: 0.3 s between tokens, a 0.1 s write limit, the whole reply arrives."""
212        import http.client
213        import json
214        import serve.server as server
215        from serve.frontend import ChatTemplate
216        from serve.server import ByteTokenizer, MockEngine, Service, serve
217        tok = ByteTokenizer()
218        svc = Service(MockEngine(tok, "abcdef", delay_s=0.3), tok,
219                      ChatTemplate(Path(server.__file__).parent / "chat_template.jinja"))
220        httpd = serve(svc, port=0)
221        try:
222            with mock.patch.object(server, "STREAM_WRITE_TIMEOUT_S", 0.1, create=True):
223                conn = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=30)
224                conn.request("POST", "/v1/chat/completions", json.dumps(
225                    {"messages": [{"role": "user", "content": "go"}], "stream": True, "max_tokens": 50,
226                     "reasoning_effort": "none"}), {"Content-Type": "application/json"})
227                body = conn.getresponse().read().decode()
228                conn.close()
229            text = "".join(json.loads(l[5:])["choices"][0]["delta"].get("content") or ""
230                           for l in body.splitlines() if l.startswith("data:") and "[DONE]" not in l
231                           and json.loads(l[5:]).get("choices"))
232            self.assertEqual(text, "abcdef")
233            self.assertIn("data: [DONE]", body)
234        finally:
235            httpd.shutdown()
236            httpd.server_close()
237
238
239class BlockedConsole(unittest.TestCase):
240    """#4479 / #2481: a console that stops taking output must not hold the thread that prints."""
241
242    def pipe(self):
243        import os
244        r, w = os.pipe()
245        self.addCleanup(lambda: [os.close(x) for x in (r,) if True])
246        return r, os.fdopen(w, "w", encoding="utf-8", buffering=1)
247
248    def test_a_print_to_a_full_pipe_blocks_without_the_wrapper(self):
249        """The control: this is the dependency the request lifecycle had on the console."""
250        r, w = self.pipe()
251        done = threading.Event()
252
253        def spam():
254            for i in range(20000):
255                w.write(f"[strata] progress line {i} " + "x" * 40 + "\n")
256                w.flush()
257            done.set()
258        threading.Thread(target=spam, daemon=True).start()
259        self.assertFalse(done.wait(1.0), "a pipe nobody reads must block a plain print")
260
261    def test_the_wrapper_never_blocks_and_keeps_the_newest_lines(self):
262        import os
263        from serve.nonblocking_out import NonBlockingOut
264        r, w = self.pipe()
265        out = NonBlockingOut(w, max_bytes=64 * 1024, max_chunks=500)
266        done = threading.Event()
267
268        def spam():
269            for i in range(20000):
270                print(f"[strata] progress line {i} " + "x" * 40, file=out, flush=True)
271            done.set()
272        threading.Thread(target=spam, daemon=True).start()
273        self.assertTrue(done.wait(5.0), "printing into a console nobody reads must not block")
274        self.assertGreater(out.dropped_chunks, 0)
275        self.assertLessEqual(len(out._q), 500)
276        # the console wakes up: everything that was kept arrives, in order, ending with the newest line
277        data = b""
278        end = __import__("time").monotonic() + 10
279        while __import__("time").monotonic() < end and b"progress line 19999" not in data:
280            data += os.read(r, 65536)
281        text = data.decode()
282        self.assertIn("progress line 19999 ", text)
283        seen = [int(l.split()[3]) for l in text.splitlines() if l.startswith("[strata] progress line")]
284        self.assertEqual(seen, sorted(seen), "order is kept")
285        out.close(1.0)
286
287    def test_the_console_is_restored_and_drained(self):
288        import io
289        from serve.nonblocking_out import NonBlockingOut
290        real = io.StringIO()
291        out = NonBlockingOut(real)
292        out.write("hello\n")
293        out.write("world\n")
294        self.assertTrue(out.drain(2.0))
295        self.assertEqual(real.getvalue(), "hello\nworld\n")
296        out.close()
297        self.assertEqual(out.write("late\n"), 5)                     # a late write after close is not an error
298
299
300class EngineOutputDecoding(FakeEngines, unittest.TestCase):
301    """#5044: a byte that is not UTF-8 on the engine's stdout (Windows can print one) must not end the reader."""
302
303    def tearDown(self):
304        self.cleanup_engines()
305
306    def test_a_non_utf8_byte_before_ready_and_in_a_reply(self):
307        import serve.server as server
308        self.tmp = tempfile.TemporaryDirectory()
309        text = canary_script()
310        bad = 'sys.stdout.buffer.write(b"INFO note=\\x8e\\n"); sys.stdout.flush()\nprint("READY 4096 stop", flush=True)'
311        self.assertIn('print("READY 4096 stop", flush=True)', text)
312        text = text.replace('print("READY 4096 stop", flush=True)', bad, 1)
313        script = Path(self.tmp.name) / "fake_strata.py"
314        script.write_text(text, encoding="utf-8")
315        real = server.subprocess.Popen
316        self.popen_patch = mock.patch.object(server.subprocess, "Popen",
317                                             lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw))
318        self.popen_patch.start()
319        engine = StrataEngine("strata", [])
320        self.engines = [engine]
321        self.assertTrue(engine.alive())
322        got = []
323        collect(engine.generate(prompt_ids("KA0001"), 500, {}, threading.Event()), got)
324        self.assertEqual(got, expected_reply("KA0001"))
325
326
327if __name__ == "__main__":
328    unittest.main()