okami.mom/strata

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

Niko1221serve: a request the engine refuses with ERR answers at once, not after a 300 s wait for a DONE (#1059)ef6c18a14

main
8.6 KiB213 linesraw
1"""#1012 (the old #792): requests waiting for the engine's control lines when the engine is restarted.
2
3restart() runs StrataEngine.__init__ again; it used to make a new condition variable, lock, wait counter and wait
4list while the waiters still held the old ones: they hung for good, or failed with `list.remove(x): x not in
5list`.  The admission state is now kept across a restart.  A waiter either goes on with the new engine or ends
6with a clean 503; never a hang, never a ValueError.  The fake engine of test_parallel runs behind the real
7StrataEngine and Service.
8
9    python -m unittest serve.test_restart_waiters -v
10"""
11import json
12import subprocess
13import sys
14import threading
15import time
16import unittest
17import urllib.error
18import urllib.request
19from pathlib import Path
20from unittest import mock
21
22from serve import test_parallel
23
24REAL_POPEN = subprocess.Popen
25
26class RestartWaiters(unittest.TestCase):
27    # the fake-engine helpers of test_parallel (its module, not its class, is imported: no duplicate tests)
28    chat = test_parallel.ParallelService.chat
29    _start, tearDown = test_parallel.ParallelService.start, test_parallel.ParallelService.tearDown
30
31    def start(self, slots, fit=None):
32        """The fake engine, and it stays the engine for the restarts that follow (Popen is patched for the test)."""
33        import serve.server as server
34        real = REAL_POPEN
35        self._start(slots, fit=fit)
36        script = Path(self.tmp.name) / "fake_strata.py"
37        patch = mock.patch.object(server.subprocess, "Popen",
38                                  lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw))
39        patch.start()
40        self.addCleanup(patch.stop)
41
42    def post(self, text, out, i):
43        try:
44            out[i] = ("ok", self.chat(text)["choices"][0]["message"]["content"])
45        except urllib.error.HTTPError as e:
46            out[i] = ("http", e.code, json.loads(e.read().decode())["error"]["message"])
47        except Exception as e:      # noqa: BLE001 - reported by the assertions
48            out[i] = ("exc", repr(e))
49
50    def waiters(self, n):
51        """n requests that wait for the control lines: the test holds them (as a prompt read would)."""
52        assert self.engine.ctl.acquire(timeout=5)
53        out, threads = {}, []
54        for i in range(n):
55            th = threading.Thread(target=self.post, args=(f"question {i}", out, i))
56            th.start()
57            threads.append(th)
58        deadline = time.time() + 20
59        while self.engine.waiting < n and time.time() < deadline:
60            time.sleep(0.02)
61        self.assertEqual(self.engine.waiting, n)
62        return out, threads
63
64    def joined(self, threads):
65        for th in threads:
66            th.join(60)
67        self.assertFalse([th for th in threads if th.is_alive()], "a waiter hung")
68
69    def clean(self):
70        e = self.engine
71        self.assertEqual((e.waiting, e.wait_lens), (0, []))
72        self.assertFalse(e.ctl.locked())
73
74    def kill(self):
75        self.engine.proc.kill()
76        self.engine.proc.wait(timeout=10)
77
78    def go_on(self, slots):
79        self.start(slots)
80        e = self.engine
81        cv, ctl, old_proc = e.slot_cv, e.ctl, e.proc
82        out, threads = self.waiters(3)
83        self.kill()
84        restarter = threading.Thread(target=e.restart)               # what ensure_loaded does for the next request
85        restarter.start()
86        time.sleep(0.2)
87        e.ctl.release()                                              # the request that held the lines is gone
88        restarter.join(120)
89        self.joined(threads)
90        self.assertEqual(out, {i: ("ok", "ok, done.") for i in range(3)})
91        self.assertIsNot(e.proc, old_proc)
92        self.assertIs(e.slot_cv, cv)                                 # the same condition variable and lock
93        self.assertIs(e.ctl, ctl)
94        self.clean()
95
96    def test_waiters_go_on_with_the_new_engine_2_slots(self):
97        self.go_on(2)
98
99    def test_waiters_go_on_with_the_new_engine_4_slots(self):
100        self.go_on(4)
101
102    def stays_down(self, slots):
103        self.start(slots)
104        out, threads = self.waiters(3)
105        self.kill()
106        self.engine.ctl.release()
107        self.joined(threads)
108        for i in range(3):
109            self.assertEqual(out[i][:2], ("http", 503), out[i])
110            self.assertNotIn("list.remove", out[i][2])
111            self.assertIn("engine", out[i][2])
112        self.clean()
113        # the next request starts the engine again and is served
114        self.assertEqual(self.chat("after")["choices"][0]["message"]["content"], "ok, done.")
115        self.clean()
116
117    def test_waiters_get_a_clean_503_when_the_engine_stays_down_2_slots(self):
118        self.stays_down(2)
119
120    def test_waiters_get_a_clean_503_when_the_engine_stays_down_4_slots(self):
121        self.stays_down(4)
122
123    def test_a_restart_that_fails_wakes_the_waiters(self):
124        self.start(2)
125        e = self.engine
126        out, threads = self.waiters(2)
127        self.kill()
128
129        def refuse(*a, **k):                    # as __init__ when the new engine exits before READY
130            e.proc = REAL_POPEN([sys.executable, "-c", "pass"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
131                                text=True)
132            raise RuntimeError("the engine exited before it was ready")
133        e.__init__ = refuse
134        try:
135            with self.assertRaises(RuntimeError):
136                e.restart(tries=1)
137        finally:
138            del e.__init__
139        e.ctl.release()
140        self.joined(threads)
141        self.assertEqual([out[i][:2] for i in range(2)], [("http", 503)] * 2, out)
142        self.clean()
143
144    def killed_mid_read(self, slots, others):
145        """A long prompt is being read (alone, or with `others` short requests arriving meanwhile: it gives way and is
146        admitted into a slot) when the engine dies: every request ends at once with a 503.  It used to wait out the
147        300 s drain for an end line that had been read already."""
148        self.start(slots)
149        out, threads = {}, []
150        threads.append(threading.Thread(target=self.post, args=("LONGREPLY " + "word " * 740, out, "long")))
151        threads[0].start()
152        time.sleep(0.25)
153        for i in range(others):
154            th = threading.Thread(target=self.post, args=(f"short {i}", out, i))
155            th.start()
156            threads.append(th)
157            time.sleep(0.05)
158        time.sleep(0.1)
159        t0 = time.time()
160        self.kill()
161        self.joined(threads)
162        self.assertLess(time.time() - t0, 20)
163        self.assertTrue(all(v[0] == "ok" or v[:2] == ("http", 503) for v in out.values()), out)
164        self.assertEqual(out["long"][:2], ("http", 503), out)
165        self.clean()
166        self.assertEqual(self.chat("after")["choices"][0]["message"]["content"], "ok, done.")
167
168    def test_killed_while_reading_alone(self):
169        self.killed_mid_read(2, 0)
170
171    def test_killed_while_reading_with_others_arriving(self):
172        self.killed_mid_read(2, 2)
173
174    def test_an_old_request_meets_a_restart_in_progress(self):
175        """A request that learns its engine died while restart() has already taken the process (self.proc is None):
176        its death note and its sends answer with EngineDied, not AttributeError (the client got no reply at all)."""
177        from serve.server import EngineDied
178        self.start(2)
179        self.kill()
180        self.engine.close()                                           # what restart() does first
181        self.assertIsNone(self.engine.proc)
182        self.assertTrue(self.engine.death_note())                    # a sentence, no AttributeError
183        self.assertFalse(self.engine.alive())
184        with self.assertRaises(EngineDied):
185            self.engine._send("STOP")
186
187    def refused(self, slots):
188        """#1059: the engine refuses a request up front (ERR, then idle).  The server answered after a 300 s drain of
189        a DONE that never comes, and held the control lines meanwhile."""
190        self.start(slots)
191        out = {}
192        t0 = time.time()
193        self.post("REFUSEME please", out, 0)
194        self.assertLess(time.time() - t0, 20)
195        self.assertEqual(out[0][0], "http", out)
196        self.assertIn("refused", out[0][2])
197        self.clean()
198        self.assertEqual(self.chat("after")["choices"][0]["message"]["content"], "ok, done.")
199
200    def test_an_engine_err_answers_at_once_solo_loop(self):
201        self.refused(2)
202
203    def test_an_engine_err_answers_at_once_not_batched(self):
204        self.refused(0)
205
206    def test_solo_engine_is_unchanged(self):
207        self.start(4, fit=0)                                          # the engine turns batching off
208        self.kill()
209        self.assertEqual(self.chat("hi")["choices"][0]["message"]["content"], "ok, done.")
210
211
212if __name__ == "__main__":
213    unittest.main()