okami.mom/strata

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

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
9.9 KiB226 linesraw
1"""A disconnect reaches the real engine pipe during a quiet prompt read, before its first PP or token.
2
3The native stand-in deliberately says nothing until STOP. This covers the boundary that a MockEngine watching
4the cancel Event itself cannot test: HTTP disconnect -> Event -> STOP -> DONE/BADM -> the next request.
5No GPU or model is used.
6"""
7import json
8import io
9from pathlib import Path
10import queue
11import socket
12import sys
13import tempfile
14import threading
15import time
16import unittest
17from unittest import mock
18import urllib.request
19
20from serve import server
21
22
23FAKE = r'''import json, queue, sys, threading, time
24from pathlib import Path
25log = Path(sys.argv[sys.argv.index('--events') + 1])
26batch = int(sys.argv[sys.argv.index('--batch') + 1])
27commands, stop = queue.Queue(), threading.Event()
28def note(event):
29    with log.open('a') as f:
30        f.write(json.dumps({'event': event, 'at': time.monotonic()}) + '\n')
31def reader():
32    for line in sys.stdin:
33        line = line.strip()
34        if line == 'STOP':
35            note('stop')
36            stop.set()
37        else:
38            commands.put(line)
39    commands.put('QUIT')
40threading.Thread(target=reader, daemon=True).start()
41if batch:
42    print(f'INFO batch_slots={batch}', flush=True)
43print('READY 4096 stop', flush=True)
44count = 0
45while True:
46    line = commands.get()
47    if line == 'QUIT':
48        break
49    if not line.startswith(('GEN ', 'BGEN ')):
50        continue
51    count += 1
52    stop.clear()
53    note('request_' + str(count))
54    fields = line.split()
55    slot = int(fields[1]) if fields[0] == 'BGEN' else None
56    if count == 1:
57        # The test's cleanup also sends STOP, so even a failed assertion leaves no long-lived child.
58        stop.wait(15)
59        time.sleep(.15)  # STOP was received, but the current chunk has not finished yet: it must drain.
60        print('DONE 0 128 1 0 cancel 0 0 0', flush=True)
61    else:
62        print('T 90\nDONE 1 20 1 1 stop', flush=True)
63    if slot is not None:
64        print(f'BADM {slot} 0', flush=True)
65'''
66
67
68class QuietPromptCancel(unittest.TestCase):
69    def check_hangup(self, api, stream, batch, max_new=1):
70        with tempfile.TemporaryDirectory() as directory:
71            root = Path(directory)
72            script, events = root / 'engine.py', root / 'events.jsonl'
73            script.write_text(FAKE, encoding='utf-8')
74            real_popen = server.subprocess.Popen
75            with mock.patch.object(server.subprocess, 'Popen', lambda cmd, **kw:
76                                   real_popen([sys.executable, str(script), *cmd[1:]], **kw)):
77                engine = server.StrataEngine('strata', ['--batch', str(batch), '--events', str(events)])
78            service = server.Service(engine, server.ByteTokenizer(),
79                                     server.ChatTemplate(Path(__file__).parent / 'chat_template.jinja'))
80            http = server.serve(service, port=0)
81            port = http.server_address[1]
82            sock = None
83            reply, errors = [], []
84            follower = None
85            try:
86                body = {'model': 'm', 'stream': stream, 'max_tokens': max_new,
87                        'messages': [{'role': 'user', 'content': 'a long prompt'}],
88                        'reasoning_effort': 'none'}
89                if api == 'responses':
90                    body = {'model': 'm', 'stream': stream, 'max_output_tokens': max_new,
91                            'input': 'a long prompt', 'reasoning': {'effort': 'none'}}
92                data = json.dumps(body).encode()
93                path = {'openai': '/v1/chat/completions', 'anthropic': '/v1/messages',
94                        'responses': '/v1/responses'}[api]
95                sock = socket.create_connection(('127.0.0.1', port), timeout=5)
96                sock.sendall(f'POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n'
97                             f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
98
99                def has(event):
100                    return events.exists() and any(json.loads(row)['event'] == event
101                                                   for row in events.read_text().splitlines())
102
103                deadline = time.monotonic() + 3
104                while not has('request_1') and time.monotonic() < deadline:
105                    time.sleep(.01)
106                self.assertTrue(has('request_1'), 'the first request did not reach the native pipe')
107                closed = time.monotonic()
108                sock.close()
109                sock = None
110
111                def follow():
112                    data = json.dumps({'messages': [{'role': 'user', 'content': 'hi'}],
113                                       'max_tokens': 1, 'reasoning_effort': 'none'}).encode()
114                    req = urllib.request.Request(f'http://127.0.0.1:{port}/v1/chat/completions', data=data,
115                                                 headers={'Content-Type': 'application/json'})
116                    try:
117                        with urllib.request.urlopen(req, timeout=15) as response:
118                            reply.append(json.load(response))
119                    except Exception as exc:
120                        errors.append(exc)
121
122                follower = threading.Thread(target=follow)
123                follower.start()
124                deadline = closed + 2.5
125                while not has('stop') and time.monotonic() < deadline:
126                    time.sleep(.01)
127                self.assertTrue(has('stop'), 'disconnect must send STOP before a PP line or 10 s heartbeat')
128                follower.join(timeout=2.5)
129                self.assertFalse(follower.is_alive(), 'the cancelled request did not release the next request')
130                self.assertEqual(errors, [])
131                self.assertEqual(reply[0]['choices'][0]['message']['content'], 'Z')
132                self.assertTrue(engine.alive(), 'cancellation must preserve the resident engine')
133                self.assertEqual(reply[0]['usage']['completion_tokens'], 1)
134                self.assertEqual(service.history[-1]['engine_generated'], 1,
135                                 'the next request must record its own DONE, not the cancelled request')
136                if batch:
137                    self.assertFalse(any(engine.slot_busy), 'the cancelled admission must release its slot')
138                else:
139                    self.assertEqual(engine.last['finish'], 'stop', 'the next request must read its own DONE')
140            finally:
141                if sock is not None:
142                    sock.close()
143                engine._send('STOP')
144                if follower is not None:
145                    follower.join(timeout=3)
146                http.shutdown()
147                http.server_close()
148                engine.close()
149
150    def test_anthropic_stream(self):
151        self.check_hangup('anthropic', True, 0)
152
153    def test_batch_solo_stream(self):
154        # A batch-enabled engine runs an isolated request with more than one output token through GEN first.
155        self.check_hangup('anthropic', True, 2, max_new=2)
156
157    def test_other_http_modes(self):
158        for api in ('openai', 'anthropic', 'responses'):
159            for stream in (False, True):
160                for batch in (0, 2):
161                    if (api, stream, batch) == ('anthropic', True, 0):
162                        continue
163                    with self.subTest(api=api, stream=stream, batch=batch):
164                        self.check_hangup(api, stream, batch)
165
166
167class QuietWaitPolicy(unittest.TestCase):
168    def test_expired_silence_is_not_a_heartbeat(self):
169        engine = object.__new__(server.StrataEngine)
170        engine.proc = mock.Mock()
171        engine.proc.poll.return_value = None
172        engine.proc.stdin = io.StringIO()
173        engine.lines = mock.Mock()
174        engine.can_stop, engine.silence_s, engine.log_path = True, 10, None
175        now = [0.0]
176
177        def clock():
178            now[0] += .001                 # time also passes between calculating a wait and starting it
179            return now[0]
180
181        def get(timeout):
182            now[0] += timeout
183            raise queue.Empty
184
185        engine.lines.get.side_effect = get
186        with mock.patch.object(server.time, 'monotonic', clock):
187            gen = engine.generate([], 10, {}, threading.Event())
188            with self.assertRaises(server.EngineSilent):
189                next(gen)                  # must fail before yielding an overdue heartbeat to a slow consumer
190        engine.proc.kill.assert_called_once()
191        self.assertNotIn('STOP', engine.proc.stdin.getvalue())
192
193    def test_polling_keeps_ten_second_heartbeats(self):
194        for control in (False, True):
195            with self.subTest(control=control):
196                engine = object.__new__(server.StrataEngine)
197                engine.proc = mock.Mock()
198                engine.proc.poll.return_value = None
199                engine.proc.stdin = io.StringIO()
200                engine.lines = mock.Mock()
201                engine.can_stop, engine.silence_s = True, 0
202                engine._ctl_mode = 'solo'
203                engine._send = mock.Mock()
204                now = [0.0]
205                waits = []
206
207                def get(timeout):
208                    waits.append(timeout)
209                    if now[0] >= 21.0:
210                        return 'DONE 0 1 1 0 length'
211                    now[0] += timeout
212                    raise queue.Empty
213
214                engine.lines.get.side_effect = get
215                cancel = threading.Event()
216                with mock.patch.object(server.time, 'monotonic', lambda: now[0]):
217                    gen = engine._control(cancel, lambda t: None) if control else engine.generate([1], 1, {}, cancel)
218                    heartbeats = list(gen)
219                self.assertEqual(heartbeats, [None, None], 'a quiet 21 seconds emits two heartbeats, not 42')
220                self.assertTrue(all(0 < wait <= .5 for wait in waits), 'cancellation uses bounded blocking waits')
221                engine._send.assert_not_called()
222                self.assertNotIn('STOP', engine.proc.stdin.getvalue())
223
224
225if __name__ == '__main__':
226    unittest.main()