okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
3.1 KiB84 linesraw
1"""A request whose consumer stops early sends the engine STOP from Engine.generate's `finally`.  When the engine is being
2ended or restarted on another thread at that moment, its stdin can already be closed (Engine.close() closes it before it
3clears `proc`) or `proc` can already be None.  The stop path must not raise in any of these states: the exception would
4replace the request's own outcome and leave the generator's close() with an error (serve/replicas.py's gen.close(); seen
5as the "'NoneType' object has no attribute 'stdin'" warning in serve/test_stream_ownership.py)."""
6
7from __future__ import annotations
8
9import io
10import queue
11import sys
12import threading
13import unittest
14from pathlib import Path
15from unittest import mock
16
17sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18
19from serve import server  # noqa: E402
20from serve.server import StrataEngine  # noqa: E402
21
22
23class FakeProc:
24    def __init__(self):
25        self.stdin = io.StringIO()
26
27    def poll(self):
28        return None
29
30
31def engine() -> StrataEngine:
32    e = StrataEngine.__new__(StrataEngine)
33    e.alive = lambda: True
34    e.batch, e.multi, e.silence_s, e.can_stop = 0, 0, 0, True
35    e.lines = queue.Queue()
36    e.proc = FakeProc()
37    e.sampling_keys = lambda sampling: ""
38    e.exit_code = lambda: 1
39    return e
40
41
42class StopOnAClosedPipe(unittest.TestCase):
43    def run_case(self, break_pipe):
44        e = engine()
45        e.lines.put("T 7")
46        with mock.patch.object(server.bias_api, "validate_request", lambda *a, **k: None), \
47                mock.patch.object(server, "refuse_for_split", lambda *a, **k: None), \
48                mock.patch.object(server, "ENGINE_STALL_S", 0):
49            gen = e.generate([1, 2, 3], 8, {}, threading.Event())
50            self.assertEqual(next(gen), 7)
51            break_pipe(e)
52            e.lines.put(None)                    # the engine's output ended (its reader thread's end mark)
53            gen.close()                          # must not raise, whatever state the pipe is in
54
55    def test_stdin_closed(self):
56        self.run_case(lambda e: e.proc.stdin.close())          # ValueError: I/O operation on closed file
57
58    def test_proc_gone(self):
59        def gone(e):
60            e.proc = None                                        # AttributeError: 'NoneType' ... 'stdin'
61        self.run_case(gone)
62
63    def test_broken_pipe_still_quiet(self):
64        def broken(e):
65            def write(_):
66                raise BrokenPipeError(32, "Broken pipe")
67            e.proc.stdin.write = write
68        self.run_case(broken)
69
70    def test_open_pipe_gets_the_stop(self):
71        e = engine()
72        e.lines.put("T 7")
73        with mock.patch.object(server.bias_api, "validate_request", lambda *a, **k: None), \
74                mock.patch.object(server, "refuse_for_split", lambda *a, **k: None), \
75                mock.patch.object(server, "ENGINE_STALL_S", 0):
76            gen = e.generate([1, 2, 3], 8, {}, threading.Event())
77            self.assertEqual(next(gen), 7)
78            e.lines.put("DONE 1 3 1.0 1.0 stop")
79            gen.close()
80        self.assertTrue(e.proc.stdin.getvalue().endswith("STOP\n"))
81
82
83if __name__ == "__main__":
84    unittest.main()