okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b247f4ecd
main
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 7python -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): 39return kid 40 41def fake_run(*a, **k): # the benchmark itself: still running when the signal comes 42Path(ready).write_text("x") 43time.sleep(120) 44 45def slow_wait(*a, **k): # the model is still loading when the signal comes 46Path(ready).write_text("x") 47time.sleep(120) 48 49patches = [mock.patch("strata_cli.cli._source", return_value=(Path("p.json"), None, None, {})), 50mock.patch("strata_cli.cli._launch_plan", return_value=(plan, [])), 51mock.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 53patches += [mock.patch.object(bs.subprocess, "Popen", lambda *a, **k: kid), mock.patch.object(bs, "_start_wait", slow_wait)] 54else: 55patches += [mock.patch.object(bs, "start_engine", fake_start), mock.patch.object(bs, "run", fake_run)] 56for p in patches: 57p.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 : 63try : 64os .kill (pid ,0 ) 65except ProcessLookupError : 66return False 67except PermissionError : 68return True 69try : 70return Path (f"/proc/ { pid } /stat" ).read_text ().rsplit (")" ,1 )[1 ].split ()[0 ]!= "Z" 71except OSError : 72return 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 ): 77def setUp (self ): 78self .temp = tempfile .TemporaryDirectory (prefix = "strata-benchterm-" ) 79self .addCleanup (self .temp .cleanup ) 80self .pidfile = Path (self .temp .name )/ "kid.pid" 81self .ready = Path (self .temp .name )/ "ready" 82self .driver = Path (self .temp .name )/ "driver.py" 83self .driver .write_text (DRIVER ,encoding = "utf-8" ) 84self .addCleanup (self ._reap ) 85 86def _reap (self ): 87try : 88pid = int (self .pidfile .read_text ()) 89if alive (pid ): 90os .kill (pid ,signal .SIGKILL ) 91except (OSError ,ValueError ): 92pass 93 94def _run (self ,mode :str ,sig = signal .SIGTERM ): 95proc = subprocess .Popen ([sys .executable ,str (self .driver ),str (ROOT ),mode ,str (self .pidfile ),str (self .ready )], 96stdout = subprocess .PIPE ,stderr = subprocess .PIPE ,text = True ) 97self .addCleanup (lambda :proc .poll ()is None and proc .kill ()) 98deadline = time .time ()+ 60 99while time .time ()< deadline and not self .ready .exists (): 100time .sleep (0.1 ) 101self .assertTrue (self .ready .exists (),"the driver never got to the benchmark: " + (proc .stderr .read ()if proc .poll ()is not None else "" )) 102kid = int (self .pidfile .read_text ()) 103self .assertTrue (alive (kid )) 104proc .send_signal (sig ) 105try : 106code = proc .wait (timeout = 60 ) 107except subprocess .TimeoutExpired : 108proc .kill () 109self .fail ("the runner did not end after the signal" ) 110end = time .time ()+ 30 111while time .time ()< end and alive (kid ): 112time .sleep (0.2 ) 113return code ,kid ,proc 114 115def test_sigterm_while_the_benchmark_runs_stops_the_engine (self ): 116code ,kid ,proc = self ._run ("running" ) 117self .assertFalse (alive (kid ),"the engine this run started is still running after SIGTERM" ) 118self .assertEqual (code ,130 ,proc .stderr .read ()) 119 120def test_sigint_while_the_benchmark_runs_stops_the_engine (self ): 121code ,kid ,proc = self ._run ("running" ,signal .SIGINT ) 122self .assertFalse (alive (kid ),"the engine this run started is still running after SIGINT" ) 123 124def 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.""" 126code ,kid ,proc = self ._run ("loading" ) 127self .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" ) 132def test_the_handler_is_installed_only_inside_and_put_back (self ): 133before = signal .getsignal (signal .SIGTERM ) 134with bench_standard .term_is_interrupt (): 135self .assertIsNot (signal .getsignal (signal .SIGTERM ),before ) 136with self .assertRaises (KeyboardInterrupt ): 137signal .raise_signal (signal .SIGTERM ) 138self .assertIs (signal .getsignal (signal .SIGTERM ),before ) 139 140def test_a_thread_other_than_the_main_one_is_left_alone (self ): 141import threading 142seen = [] 143 144def work (): 145with bench_standard .term_is_interrupt (): 146seen .append (True ) 147t = threading .Thread (target = work ) 148t .start () 149t .join () 150self .assertEqual (seen , [True ]) 151 152 153if __name__ == "__main__" : 154unittest .main ()