okami.mom/strata

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

Niko1221Merge f-022-issues: 14 small issue fixes + Windows runtime folder repairb111d1e83

main
7.0 KiB143 linesraw
1"""#1527: the READY-read timeout (#1317) ends the engine, and the request that was loading it must end too -
2a 503 with the reason, not a connection that never answers (or a misleading 400)."""
3import os
4from pathlib import Path
5import sys
6import tempfile
7import threading
8import time
9import unittest
10import json
11import urllib.request
12from unittest import mock
13sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14import serve.server as server                                            # noqa: E402
15from serve.server import StrataEngine, Service, ChatTemplate, ByteTokenizer, serve  # noqa: E402
16
17# never prints READY: the READY read times out and the process is killed
18SILENT = r'''
19import time
20time.sleep(3600)
21'''
22
23# first run answers READY + one request; after --hang is touched a restart stays silent forever
24HANG_ON_RESTART = r'''
25import sys, time
26from pathlib import Path
27hang = Path(sys.argv[sys.argv.index('--hang') + 1])
28if hang.exists():
29    time.sleep(3600)
30print('READY 4096 stop', flush=True)
31for line in sys.stdin:
32    if line.startswith('QUIT'):
33        break
34    if line.startswith(('GEN', 'BGEN')):
35        print('T 90\nDONE 1 1 0 1 stop', flush=True)
36'''
37
38
39@unittest.skipIf(os.name == "nt", "the .cmd wrapper keeps the pipe open after the kill (only the wrapper dies), so the "
40                                  "close of its stdout waits for the sleeping child; a real engine is one process")
41class ReadyTimeout(unittest.TestCase):
42    def setUp(self):
43        self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
44        self.root = Path(self.tmp.name)
45        self._patchers = [mock.patch.object(server, 'ENGINE_READY_S', 0.5),
46                          mock.patch.object(StrataEngine, 'RESTART_RETRY_S', 0.0)]
47        for p in self._patchers:
48            p.start(); self.addCleanup(p.stop)
49
50    def make_script(self, name, code):
51        py = self.root / (name + '.py')
52        if os.name == 'nt':
53            py.write_text(code); script = self.root / (name + '.cmd')
54            script.write_text(f'@"{sys.executable}" "{py}" %*\r\n')
55        else:
56            script = py; py.write_text('#!' + sys.executable + '\n' + code); py.chmod(0o700)
57        return str(script)
58
59    def service(self, script, extra_args=()):
60        eng = StrataEngine(script, list(extra_args), lazy=True)
61        self.addCleanup(eng.close)
62        return Service(eng, ByteTokenizer(), ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
63
64    def post(self, base):
65        body = {'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 8}
66        req = urllib.request.Request(base + '/v1/chat/completions', data=json.dumps(body).encode(),
67                                     headers={'Content-Type': 'application/json'})
68        with urllib.request.urlopen(req, timeout=30) as r:
69            return r.status, r.read()
70
71    def assert503(self, base):
72        t0 = time.monotonic()
73        try:
74            self.post(base)
75            self.fail('a request on an engine that never reports READY must not succeed')
76        except urllib.error.HTTPError as e:
77            self.assertEqual(e.code, 503)
78            body = e.read().decode()
79            self.assertIn('did not report READY', body)
80            self.assertIn('next request restarts it', body)
81        self.assertLess(time.monotonic() - t0, 60)
82
83    def test_ready_timeout_on_lazy_load_answers_the_request(self):
84        # lazy start: restart()'s own bookkeeping must not crash on the missing slot_cv either (#1527)
85        svc = self.service(self.make_script('silent', SILENT))
86        httpd = serve(svc, port=0)
87        self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close)
88        base = f'http://127.0.0.1:{httpd.server_address[1]}'
89        self.assert503(base)
90        self.assertFalse(svc.engine.starting)
91
92    def test_ready_timeout_on_restart_answers_the_request(self):
93        # the reporter's case: the engine had answered once, then a restart hangs on the READY read
94        hang = self.root / 'hang'
95        svc = self.service(self.make_script('hang_on_restart', HANG_ON_RESTART), ('--hang', str(hang)))
96        httpd = serve(svc, port=0)
97        self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close)
98        base = f'http://127.0.0.1:{httpd.server_address[1]}'
99        status, _ = self.post(base)                              # first request: the engine works
100        self.assertEqual(status, 200)
101        svc.engine.proc.kill(); svc.engine.proc.wait(10)         # it dies between requests
102        hang.touch()                                             # and its restart never reports READY
103        self.assert503(base)
104        self.assertFalse(svc.engine.starting)
105
106
107class SpawnFailure(unittest.TestCase):
108    """The engine program cannot be started at all (missing, not executable, or blocked by Windows - #735): the
109    request that was loading it gets a 503 with the reason, not a dropped connection."""
110    BODIES = {'/v1/chat/completions': {'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 8},
111              '/v1/messages': {'model': 'strata', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]},
112              '/v1/responses': {'input': 'hi', 'max_output_tokens': 8}}
113
114    def test_missing_engine_answers_503_and_leaves_nothing_running(self):
115        tmp = tempfile.TemporaryDirectory(); self.addCleanup(tmp.cleanup)
116        root = Path(tmp.name)
117        eng = StrataEngine(str(root / 'no-such-engine'), [], log=str(root / 'engine.log'), lazy=True)
118        svc = Service(eng, ByteTokenizer(), ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
119        httpd = serve(svc, port=0)
120        self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close)
121        base = f'http://127.0.0.1:{httpd.server_address[1]}'
122        before = set(threading.enumerate())
123        cases = list(self.BODIES.items()) + [('/v1/chat/completions',
124                                              {**self.BODIES['/v1/chat/completions'], 'stream': True})]
125        for path, body in cases:
126            with self.subTest(path=path, stream=body.get('stream', False)):
127                req = urllib.request.Request(base + path, data=json.dumps(body).encode(),
128                                             headers={'Content-Type': 'application/json'})
129                with self.assertRaises(urllib.error.HTTPError) as cm:
130                    urllib.request.urlopen(req, timeout=30)
131                self.assertEqual(cm.exception.code, 503)
132                self.assertIn('the engine could not be started', cm.exception.read().decode())
133                self.assertTrue(eng.log.closed)                 # our handle on the engine log is given back
134        # the start narrator ("still starting ... please wait") ends with the failed start
135        deadline = time.monotonic() + 5
136        while (narrators := [t for t in set(threading.enumerate()) - before if '(narrate_start)' in t.name]) \
137                and time.monotonic() < deadline:
138            time.sleep(0.1)
139        self.assertEqual(narrators, [])
140
141
142if __name__ == '__main__':
143    unittest.main()