okami.mom/strata

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

Niko1221Fix answers arriving one request late after an aborted request: no DONE after the NaN-stop ERR, server drops a trailing DONE, abort-sync test9aea047ee

main
4.1 KiB111 linesraw
1"""After an aborted request the engine and the server are back in step: the next requests get their OWN answers.
2
3A request that ends on an engine ERR (the DeepSeek NaN stop printed `ERR ...` and then also `DONE ...`), a client that
4cancels mid-answer, and one that disconnects during the prompt: each is followed by two ordinary requests, and each of those
5must receive the tokens meant for it - never the previous request's DONE or tokens (found on 2 x A4000 at 64K: the needle prompt
6after a NaN-stopped request came back empty at once, and its answer went to the request after it).  No GPU or model is used.
7"""
8import sys
9import tempfile
10import threading
11import unittest
12from pathlib import Path
13from unittest import mock
14
15from serve import server
16
17FAKE = r'''import queue, sys, threading, time
18mode = sys.argv[sys.argv.index('--mode') + 1]
19cmds, stop = queue.Queue(), threading.Event()
20def reader():
21    for line in sys.stdin:
22        line = line.strip()
23        if line == 'STOP':
24            stop.set()
25        else:
26            cmds.put(line)
27    cmds.put('QUIT')
28threading.Thread(target=reader, daemon=True).start()
29print('READY 4096 stop', flush=True)
30n = 0
31while True:
32    line = cmds.get()
33    if line == 'QUIT':
34        break
35    if not line.startswith('GEN '):
36        continue
37    n += 1
38    stop.clear()
39    ids = line.split()[-1]
40    if n == 1 and mode in ('err_done', 'err_only'):
41        print('T 7', flush=True)
42        print("ERR the model's numbers went non-finite (NaN reached the router), so the answer would be nonsense", flush=True)
43        if mode == 'err_done':
44            print('DONE 1 5 1 1 cancel 0 0 0', flush=True)
45    elif n == 1 and mode == 'cancel':
46        print('T 7', flush=True)
47        stop.wait(10)
48        time.sleep(.05)
49        print('DONE 1 5 1 1 cancel 0 0 0', flush=True)
50    else:
51        # the answer of request n: its own marker token (100 + n) twice, so a late or early line is visible
52        print(f'T {100 + n}', flush=True)
53        print(f'T {100 + n}', flush=True)
54        print('DONE 2 5 1 1 stop 0 0 0', flush=True)
55'''
56
57
58class AbortSync(unittest.TestCase):
59    def engine(self, mode):
60        tmp = tempfile.TemporaryDirectory()
61        self.addCleanup(tmp.cleanup)
62        script = Path(tmp.name) / 'engine.py'
63        script.write_text(FAKE, encoding='utf-8')
64        real_popen = server.subprocess.Popen
65        with mock.patch.object(server.subprocess, 'Popen', lambda cmd, **kw:
66                               real_popen([sys.executable, str(script), *cmd[1:]], **kw)):
67            eng = server.StrataEngine('strata', ['--mode', mode])
68        self.addCleanup(eng.close)
69        return eng
70
71    def ask(self, eng, cancel_after=None):
72        cancel = threading.Event()
73        got = []
74        try:
75            for t in eng.generate([1, 2, 3], 8, {}, cancel):
76                got.append(t)
77                if cancel_after is not None and len(got) >= cancel_after:
78                    cancel.set()
79                    break
80        except ValueError as e:
81            return got, str(e)
82        return got, None
83
84    def two_following(self, eng, first_n):
85        a, err_a = self.ask(eng)
86        b, err_b = self.ask(eng)
87        self.assertEqual((a, err_a), ([100 + first_n + 1] * 2, None), "the first request after the abort got someone else's answer")
88        self.assertEqual((b, err_b), ([100 + first_n + 2] * 2, None), "the second request after the abort got someone else's answer")
89
90    def test_err_then_done_does_not_shift_the_next_answers(self):
91        eng = self.engine('err_done')
92        got, err = self.ask(eng)
93        self.assertEqual(got, [7])
94        self.assertIn('non-finite', err)
95        self.two_following(eng, 1)
96
97    def test_err_alone_is_over_with_the_err(self):
98        eng = self.engine('err_only')
99        got, err = self.ask(eng)
100        self.assertIn('non-finite', err)
101        self.two_following(eng, 1)
102
103    def test_a_cancel_mid_answer_leaves_the_engine_in_step(self):
104        eng = self.engine('cancel')
105        got, err = self.ask(eng, cancel_after=1)
106        self.assertEqual((got, err), ([7], None))
107        self.two_following(eng, 1)
108
109
110if __name__ == '__main__':
111    unittest.main()