okami.mom/strata

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

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
7.6 KiB190 linesraw
1"""The picture reader's READY pipe (serve/server.py Vision._start_reader / _await_ready).
2
3A crashing reader can start a debugger (ggml's abort path forks gdb) and the debugger writes to the reader's stdout, the pipe the server reads the
4READY line from.  The first line of that pipe is then not READY.  The server used to kill the reader on any first line that was not READY, while the
5debugger was still attached to it.  Now: READY and ERR lines are answers; any other line is a stray line, kept and logged, and the wait goes on with
6ONE deadline.  A reader that is only printing is never killed.  A reader whose process has ended counts as ended after READY_GRACE_S even when a
7debugger or a child still holds the pipe open.  The readers here are small Python scripts run as real processes.
8
9    python -m serve.test_vision_ready_pipe
10"""
11import contextlib
12import io
13import subprocess
14import sys
15import tempfile
16import textwrap
17import time
18import unittest
19from pathlib import Path
20from unittest import mock
21
22import serve.server as server
23
24
25def plain_popen(what, args, **kw):                 # the real process, without the lifeline's anchor and watcher
26    kw.pop("role", None)
27    return subprocess.Popen(args, **kw)
28
29
30class ReadyPipe(unittest.TestCase):
31    def setUp(self):
32        self.tmp = tempfile.TemporaryDirectory()
33        self.addCleanup(self.tmp.cleanup)
34        self.procs = []
35        self.addCleanup(self.stop_all)
36
37    def stop_all(self):
38        for p in self.procs:
39            if p.poll() is None:
40                p.kill()
41            p.wait(timeout=10)
42            for stream in (p.stdin, p.stdout):
43                with contextlib.suppress(OSError, ValueError):
44                    stream.close()
45
46    def reader(self, body: str):
47        """A Vision whose reader is a script with `body`; returns it (nothing started yet)."""
48        script = Path(self.tmp.name) / ("reader%d.py" % len(list(Path(self.tmp.name).glob("reader*.py"))))
49        script.write_text("import os, subprocess, sys, time\n" + textwrap.dedent(body), encoding="utf-8")
50        v = server.Vision.__new__(server.Vision)
51        v.spawn = ([sys.executable, "-u", str(script)], None, None)
52        v.dir = Path(self.tmp.name)
53        v.stopped, v.proc = True, None
54        return v
55
56    def start(self, v):
57        """v._start_reader() with the process kept for cleanup; (the error or None, the text it printed, seconds taken)."""
58        out, error, t0 = io.StringIO(), None, time.monotonic()
59        real = plain_popen
60
61        def keep(what, args, **kw):
62            p = real(what, args, **kw)
63            self.procs.append(p)
64            return p
65
66        with mock.patch.object(server, "popen", keep), contextlib.redirect_stdout(out):
67            try:
68                v._start_reader()
69            except RuntimeError as e:
70                error = e
71        return error, out.getvalue(), time.monotonic() - t0
72
73    def test_a_stray_line_before_READY_does_not_kill_the_reader(self):
74        v = self.reader("""
75            print("[New LWP 477206]", flush=True)
76            time.sleep(1.0)
77            print("READY 2560", flush=True)
78            sys.stdin.readline()
79        """)
80        error, said, _ = self.start(v)
81        self.assertIsNone(error)
82        self.assertFalse(v.stopped)
83        self.assertIsNone(v.proc.poll(), "a reader that was only printing is still running")
84        self.assertIn("[New LWP 477206]", said)                      # logged
85        self.assertIn("printed on its output", said)
86
87    def test_the_encode_answers_after_READY_are_not_taken_by_the_start(self):
88        v = self.reader("""
89            print("noise", flush=True)
90            print("READY 2560", flush=True)
91            print("OK 7 1 1 1", flush=True)
92            sys.stdin.readline()
93        """)
94        error, _, _ = self.start(v)
95        self.assertIsNone(error)
96        self.assertEqual(v._readline(5.0, "x"), "OK 7 1 1 1\n")
97
98    def test_many_stray_lines_are_bounded_in_the_log_and_the_message(self):
99        v = self.reader("""
100            for i in range(200):
101                print("stray %d" % i, flush=True)
102            sys.exit(1)
103        """)
104        error, said, _ = self.start(v)
105        self.assertIsNotNone(error)
106        self.assertLessEqual(said.count("printed on its output"), server.Vision.STRAY_KEEP)
107        self.assertIn("stray 199", str(error))                       # the last ones are in the message
108        self.assertNotIn("stray 0 ", str(error) + " ")
109
110    def test_a_stray_line_then_the_end_names_the_exit_and_the_line(self):
111        v = self.reader("""
112            print("[New LWP 5]", flush=True)
113            sys.exit(1)
114        """)
115        error, _, took = self.start(v)
116        self.assertIsNotNone(error)
117        text = str(error)
118        self.assertIn("did not start", text)
119        self.assertIn("exit code 1", text)
120        self.assertIn("[New LWP 5]", text)
121        self.assertLess(took, 10)
122
123    def test_a_stray_line_then_ERR_gives_the_ERR_line(self):
124        v = self.reader("""
125            print("[New LWP 5]", flush=True)
126            print("ERR cannot load the vision encoder x.gguf", flush=True)
127            sys.exit(1)
128        """)
129        error, _, _ = self.start(v)
130        text = str(error)
131        self.assertIn("ERR cannot load the vision encoder", text)
132        self.assertIn("[New LWP 5]", text)
133
134    def test_a_reader_that_only_prints_is_ended_at_the_deadline_with_its_lines_in_the_message(self):
135        v = self.reader("""
136            print("[New LWP 5]", flush=True)
137            time.sleep(60)
138        """)
139        with mock.patch.object(server, "VISION_READY_S", 1.5):
140            error, _, took = self.start(v)
141        self.assertIsNotNone(error)
142        self.assertIn("said nothing for", str(error))
143        self.assertIn("[New LWP 5]", str(error))
144        self.assertGreaterEqual(took, 1.4)
145        self.assertLess(took, 8)
146        self.assertIsNotNone(self.procs[-1].wait(timeout=10), "it was killed at the deadline (not before: the wait above took the whole deadline)")
147        self.assertTrue(v.stopped)
148        self.assertIsNone(v.proc)
149
150    def test_a_reader_that_ended_while_a_child_holds_its_pipe_is_judged_after_the_grace(self):
151        v = self.reader("""
152            subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"], stdout=sys.stdout)     # the "debugger": holds the pipe
153            print("[New LWP 5]", flush=True)
154            os._exit(3)
155        """)
156        with mock.patch.object(server.Vision, "READY_GRACE_S", 0.5):
157            error, _, took = self.start(v)
158        self.assertIsNotNone(error)
159        self.assertIn("exit code 3", str(error))
160        self.assertLess(took, 4.5, "the pipe's end (5 s) is not waited for: the process's end is what counts")
161
162    def test_a_silent_reader_that_dies_is_the_same_as_before(self):
163        v = self.reader("""
164            sys.exit(7)
165        """)
166        error, _, _ = self.start(v)
167        self.assertIn("exit code 7", str(error))
168        self.assertIn("without saying anything", str(error))
169
170    def test_the_cause_in_a_stray_line_is_named(self):
171        v = self.reader("""
172            print("cudaMalloc failed: CUDA-capable device(s) is/are busy or unavailable", flush=True)
173            sys.exit(1)
174        """)
175        error, _, _ = self.start(v)
176        self.assertIn("Exclusive_Process", str(error))
177
178    def test_no_deadline_means_wait_for_ever_not_fail_at_once(self):
179        v = self.reader("""
180            time.sleep(0.6)
181            print("READY 2560", flush=True)
182            sys.stdin.readline()
183        """)
184        with mock.patch.object(server, "VISION_READY_S", None):
185            error, _, _ = self.start(v)
186        self.assertIsNone(error)
187
188
189if __name__ == "__main__":
190    unittest.main()