okami.mom/strata

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

Niko1221Merge f-027-gh-ctl: GitHub setup, Docker, docs and bench items for 0.2.7538acd098

main
6.8 KiB140 linesraw
1"""Elastic encoder failures reach clients, can be retried, and do not prevent recovery."""
2import json
3from pathlib import Path
4import sys
5import tempfile
6import unittest
7import urllib.error
8import urllib.request
9
10from serve.frontend import ChatTemplate
11from serve.server import ByteTokenizer, Service, Vision, serve
12from serve.test_vision_elastic import ElasticVision
13from serve.test_vram import VramEngine
14
15
16class EncoderFailureHTTP(unittest.TestCase):
17    def setUp(self):
18        tmp = tempfile.TemporaryDirectory()
19        self.addCleanup(tmp.cleanup)
20        tok = ByteTokenizer()
21        self.engine = VramEngine(tok)
22        self.engine.loaded = True
23        self.engine.elastic = False  # as on a layer split: the cache cannot make room
24        self.vision = ElasticVision(tmp.name)
25        self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'),
26                           vision=self.vision)
27        httpd = serve(self.svc, port=0)
28        self.addCleanup(httpd.server_close)
29        self.addCleanup(httpd.shutdown)
30        self.addCleanup(self.drop_embeddings)
31        self.base = f'http://127.0.0.1:{httpd.server_address[1]}'
32        self.attempts = 0
33        self.original_restart = self.vision.restart
34
35    def drop_embeddings(self):
36        path = getattr(getattr(self.svc, 'embeddings', None), 'path', None)
37        if path is not None:
38            path.unlink(missing_ok=True)
39
40    def post(self, path, body):
41        req = urllib.request.Request(self.base + path, json.dumps(body).encode(),
42                                     {'Content-Type': 'application/json'})
43        return urllib.request.urlopen(req, timeout=10)
44
45    @staticmethod
46    def chat_picture():
47        return {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [
48            {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,eA=='}}]}]}
49
50    def fail_with(self, error_type):
51        def fail():
52            self.attempts += 1
53            raise error_type('synthetic encoder startup failure')
54        self.vision.restart = fail
55
56    def assert_503(self, path, body):
57        with self.assertRaises(urllib.error.HTTPError) as got:
58            self.post(path, body)
59        with got.exception as response:
60            self.assertEqual(response.code, 503)
61            payload = json.load(response)
62            self.assertIn('synthetic encoder startup failure', payload['error']['message'])
63
64    def test_start_failure_and_retry_on_all_three_apis(self):
65        cases = [
66            ('/v1/chat/completions', self.chat_picture()),
67            ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [
68                {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}),
69            ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [
70                {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}),
71        ]
72        for error_type in (RuntimeError, OSError):
73            self.fail_with(error_type)
74            for path, body in cases:
75                for stream in (False, True):
76                    for retry in range(2):
77                        with self.subTest(error=error_type.__name__, path=path, stream=stream, retry=retry):
78                            before = self.attempts
79                            self.assert_503(path, {**body, 'stream': stream})
80                            self.assertEqual(self.attempts, before + 1)
81
82    def test_text_requests_and_image_recovery_after_a_failed_start(self):
83        self.fail_with(RuntimeError)
84        text = {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]}
85        with self.post('/v1/chat/completions', text) as response:
86            self.assertEqual(response.status, 200)
87            response.read()
88        self.assertEqual(self.attempts, 0)
89        self.assert_503('/v1/chat/completions', self.chat_picture())
90        self.assertEqual(self.attempts, 1)
91        self.vision.restart = self.original_restart
92        with self.post('/v1/chat/completions', self.chat_picture()) as response:
93            self.assertEqual(response.status, 200)
94            response.read()
95        self.assertEqual(self.vision.starts, 1)
96        with self.post('/v1/chat/completions', text) as response:
97            self.assertEqual(response.status, 200)
98            response.read()
99        self.assertEqual(self.vision.starts, 1)
100
101    @unittest.skipUnless(sys.platform.startswith('linux'), 'child reaping is checked through /proc')
102    def test_real_encoder_failure_retries_and_reaps_each_child(self):
103        with tempfile.TemporaryDirectory() as directory:
104            started = Path(directory) / 'started-pids'
105            executable = Path(directory) / 'encoder-exits'
106            executable.write_text(
107                '#!' + sys.executable + '\nimport os\n'
108                'with open(' + repr(str(started)) + ', "a") as output:\n'
109                '    output.write(str(os.getpid()) + "\\n")\n'
110                'raise SystemExit(71)\n')
111            executable.chmod(0o700)
112            vision = Vision({'exe': str(executable), 'mmproj': 'unused', 'model': 'unused',
113                             'elastic': True}, lazy=True)
114            self.addCleanup(vision.unload)
115            self.svc.vision = vision
116            cases = [
117                ('/v1/chat/completions', self.chat_picture()),
118                ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [
119                    {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}),
120                ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [
121                    {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}),
122            ]
123            for path, body in cases:
124                for stream in (False, True):
125                    for retry in range(2):
126                        with self.subTest(path=path, stream=stream, retry=retry):
127                            previous = started.read_text().splitlines() if started.exists() else []
128                            with self.assertRaises(urllib.error.HTTPError) as got:
129                                self.post(path, {**body, 'stream': stream})
130                            with got.exception as response:
131                                self.assertEqual(response.code, 503)
132                                self.assertIn('the image encoder failed to start', json.load(response)['error']['message'])
133                            children = started.read_text().splitlines()
134                            self.assertEqual(len(children), len(previous) + 1)
135                            self.assertFalse(vision.alive())
136                            self.assertFalse(Path('/proc', children[-1]).exists())
137
138
139if __name__ == '__main__':
140    unittest.main()