okami.mom/strata

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

Niko1221Merge f-0213-qatui (final d33d45ade) into f-0213-intb247f4ecd

main
6.3 KiB154 linesraw
1"""Round 0213 QATUI: `strata bench run --profile` ended with SIGTERM must end the engine it started, like Ctrl+C does.
2
3Found on l620 (Linux, CUDA) and m1001 (macOS): after `kill -TERM <bench pid>` the runner was gone and its server and engine kept the port and the GPU
4(only KeyboardInterrupt was handled, so the `finally` that stops the engine never ran). The driver below runs the real `bench run` command line in a
5child process with a stand-in engine (a sleeping process in its own session, as `start_engine` makes it) and the real `stop_engine`.
6
7    python -m pytest tests/terminal/test_bench_term_0213_qatui.py
8"""
9from __future__ import annotations
10
11import os
12import signal
13import subprocess
14import sys
15import tempfile
16import time
17import unittest
18from pathlib import Path
19
20ROOT = Path(__file__).resolve().parents[2]
21sys.path.insert(0, str(ROOT))
22
23from strata_cli import bench_standard  # noqa: E402
24
25POSIX = os.name != "nt"
26
27DRIVER = r'''
28import os, subprocess, sys, time
29from pathlib import Path
30from unittest import mock
31sys.path.insert(0, sys.argv[1])
32from strata_cli import bench_standard as bs, cli
33mode, pidfile, ready = sys.argv[2], sys.argv[3], sys.argv[4]
34kid = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"], start_new_session=True)
35Path(pidfile).write_text(str(kid.pid))
36plan = {"effective": {"host": "127.0.0.1", "port": 9}, "engine_argv": []}
37
38def fake_start(ref, target, log_path, log, timeout_s):
39    return kid
40
41def fake_run(*a, **k):                         # the benchmark itself: still running when the signal comes
42    Path(ready).write_text("x")
43    time.sleep(120)
44
45def slow_wait(*a, **k):                        # the model is still loading when the signal comes
46    Path(ready).write_text("x")
47    time.sleep(120)
48
49patches = [mock.patch("strata_cli.cli._source", return_value=(Path("p.json"), None, None, {})),
50           mock.patch("strata_cli.cli._launch_plan", return_value=(plan, [])),
51           mock.patch.object(bs.Target, "get", lambda self, path, timeout=10: None)]
52if mode == "loading":                          # the REAL start_engine, with the child it would start and a wait that never ends
53    patches += [mock.patch.object(bs.subprocess, "Popen", lambda *a, **k: kid), mock.patch.object(bs, "_start_wait", slow_wait)]
54else:
55    patches += [mock.patch.object(bs, "start_engine", fake_start), mock.patch.object(bs, "run", fake_run)]
56for p in patches:
57    p.start()
58raise SystemExit(cli.main(["bench", "run", "--profile", "p.json", "--out", os.path.join(os.path.dirname(pidfile), "out"), "--skip-model-hash"]))
59'''
60
61
62def alive(pid: int) -> bool:
63    try:
64        os.kill(pid, 0)
65    except ProcessLookupError:
66        return False
67    except PermissionError:
68        return True
69    try:
70        return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
71    except OSError:
72        return True
73
74
75@unittest.skipUnless(POSIX, "SIGTERM is a POSIX signal; Windows ends the tree through a job object (test_bench_stop.py)")
76class TermEndsTheEngine(unittest.TestCase):
77    def setUp(self):
78        self.temp = tempfile.TemporaryDirectory(prefix="strata-benchterm-")
79        self.addCleanup(self.temp.cleanup)
80        self.pidfile = Path(self.temp.name) / "kid.pid"
81        self.ready = Path(self.temp.name) / "ready"
82        self.driver = Path(self.temp.name) / "driver.py"
83        self.driver.write_text(DRIVER, encoding="utf-8")
84        self.addCleanup(self._reap)
85
86    def _reap(self):
87        try:
88            pid = int(self.pidfile.read_text())
89            if alive(pid):
90                os.kill(pid, signal.SIGKILL)
91        except (OSError, ValueError):
92            pass
93
94    def _run(self, mode: str, sig=signal.SIGTERM):
95        proc = subprocess.Popen([sys.executable, str(self.driver), str(ROOT), mode, str(self.pidfile), str(self.ready)],
96                                stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
97        self.addCleanup(lambda: proc.poll() is None and proc.kill())
98        deadline = time.time() + 60
99        while time.time() < deadline and not self.ready.exists():
100            time.sleep(0.1)
101        self.assertTrue(self.ready.exists(), "the driver never got to the benchmark: " + (proc.stderr.read() if proc.poll() is not None else ""))
102        kid = int(self.pidfile.read_text())
103        self.assertTrue(alive(kid))
104        proc.send_signal(sig)
105        try:
106            code = proc.wait(timeout=60)
107        except subprocess.TimeoutExpired:
108            proc.kill()
109            self.fail("the runner did not end after the signal")
110        end = time.time() + 30
111        while time.time() < end and alive(kid):
112            time.sleep(0.2)
113        return code, kid, proc
114
115    def test_sigterm_while_the_benchmark_runs_stops_the_engine(self):
116        code, kid, proc = self._run("running")
117        self.assertFalse(alive(kid), "the engine this run started is still running after SIGTERM")
118        self.assertEqual(code, 130, proc.stderr.read())
119
120    def test_sigint_while_the_benchmark_runs_stops_the_engine(self):
121        code, kid, proc = self._run("running", signal.SIGINT)
122        self.assertFalse(alive(kid), "the engine this run started is still running after SIGINT")
123
124    def test_sigterm_while_the_model_loads_stops_the_engine(self):
125        """The engine is started but not ready: start_engine owns it then, the caller never receives it."""
126        code, kid, proc = self._run("loading")
127        self.assertFalse(alive(kid), "the engine is still running after SIGTERM during the load")
128
129
130class Handler(unittest.TestCase):
131    @unittest.skipUnless(POSIX, "POSIX signal")
132    def test_the_handler_is_installed_only_inside_and_put_back(self):
133        before = signal.getsignal(signal.SIGTERM)
134        with bench_standard.term_is_interrupt():
135            self.assertIsNot(signal.getsignal(signal.SIGTERM), before)
136            with self.assertRaises(KeyboardInterrupt):
137                signal.raise_signal(signal.SIGTERM)
138        self.assertIs(signal.getsignal(signal.SIGTERM), before)
139
140    def test_a_thread_other_than_the_main_one_is_left_alone(self):
141        import threading
142        seen = []
143
144        def work():
145            with bench_standard.term_is_interrupt():
146                seen.append(True)
147        t = threading.Thread(target=work)
148        t.start()
149        t.join()
150        self.assertEqual(seen, [True])
151
152
153if __name__ == "__main__":
154    unittest.main()