okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime. 2 3Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine, 4the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that 5is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS 6closes however the server ends. Processes the child starts later join the same job. The server itself stays out of 7the job, so a browser that `--open` starts is not tied to it. Each child (and the server) is also opted out of Windows 8power throttling, see `no_throttle` (#691). Elsewhere, and if the job cannot be made, a no-op. 9""" 10from __future__import annotations 11 12import os 13import subprocess 14import threading 15 16_REAL_POPEN = subprocess .Popen # the class itself, before any test replaces the name 17 18_job = None 19_lock = threading .Lock () 20 21if os .name == "nt" : 22import ctypes 23from ctypes import wintypes 24 25_k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 26 27class _IoCounters (ctypes .Structure ): 28_fields_ = [(n ,ctypes .c_ulonglong )for n in ("ReadOperationCount" ,"WriteOperationCount" , 29"OtherOperationCount" ,"ReadTransferCount" , 30"WriteTransferCount" ,"OtherTransferCount" )] 31 32class _BasicLimits (ctypes .Structure ): 33_fields_ = [("PerProcessUserTimeLimit" ,ctypes .c_longlong ), ("PerJobUserTimeLimit" ,ctypes .c_longlong ), 34 ("LimitFlags" ,wintypes .DWORD ), ("MinimumWorkingSetSize" ,ctypes .c_size_t ), 35 ("MaximumWorkingSetSize" ,ctypes .c_size_t ), ("ActiveProcessLimit" ,wintypes .DWORD ), 36 ("Affinity" ,ctypes .c_size_t ), ("PriorityClass" ,wintypes .DWORD ), 37 ("SchedulingClass" ,wintypes .DWORD )] 38 39class _ExtendedLimits (ctypes .Structure ): 40_fields_ = [("BasicLimitInformation" ,_BasicLimits ), ("IoInfo" ,_IoCounters ), 41 ("ProcessMemoryLimit" ,ctypes .c_size_t ), ("JobMemoryLimit" ,ctypes .c_size_t ), 42 ("PeakProcessMemoryUsed" ,ctypes .c_size_t ), ("PeakJobMemoryUsed" ,ctypes .c_size_t )] 43 44_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 45_JobObjectExtendedLimitInformation = 9 46 47_k32 .CreateJobObjectW .restype = wintypes .HANDLE 48_k32 .CreateJobObjectW .argtypes = (wintypes .LPVOID ,wintypes .LPCWSTR ) 49_k32 .SetInformationJobObject .argtypes = (wintypes .HANDLE ,ctypes .c_int ,wintypes .LPVOID ,wintypes .DWORD ) 50_k32 .AssignProcessToJobObject .argtypes = (wintypes .HANDLE ,wintypes .HANDLE ) 51_k32 .TerminateJobObject .argtypes = (wintypes .HANDLE ,wintypes .UINT ) 52 53def _make_job (): 54job = _k32 .CreateJobObjectW (None ,None )# no security attributes: the handle is not inherited 55if not job : 56return None 57info = _ExtendedLimits () 58info .BasicLimitInformation .LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE 59if not _k32 .SetInformationJobObject (job ,_JobObjectExtendedLimitInformation ,ctypes .byref (info ), 60ctypes .sizeof (info )): 61_k32 .CloseHandle (job ) 62return None 63return job 64 65class _PowerThrottling (ctypes .Structure ): 66_fields_ = [("Version" ,wintypes .ULONG ), ("ControlMask" ,wintypes .ULONG ), ("StateMask" ,wintypes .ULONG )] 67 68_k32 .SetProcessInformation .argtypes = (wintypes .HANDLE ,ctypes .c_int ,wintypes .LPVOID ,wintypes .DWORD ) 69_k32 .GetCurrentProcess .restype = wintypes .HANDLE 70 71def no_throttle (handle )-> bool : 72"""Opt a process out of Windows power throttling (EcoQoS). Without it Windows 11 treats a process whose console 73window is minimized as background work and, on a hybrid CPU, moves its threads to the E-cores: generation 74slowed by about 20% while the server window was minimized (#691, i9-13980HX: 36.6 -> 43.2 tok/s).""" 75for mask in (0x1 | 0x4 ,0x1 ):# EXECUTION_SPEED and IGNORE_TIMER_RESOLUTION, both off (Windows 11); 76info = _PowerThrottling (1 ,mask ,0 )# Windows 10 knows the first only: ERROR_INVALID_PARAMETER for both 77if _k32 .SetProcessInformation (handle ,4 ,ctypes .byref (info ),ctypes .sizeof (info )):# ProcessPowerThrottling 78return True 79return False 80 81no_throttle (_k32 .GetCurrentProcess ())# the server itself (tokenizing, streaming) too 82else : 83def no_throttle (handle )-> bool : 84return False 85 86 87def terminate ()-> bool : 88"""End every process in the job now (the deadline kill of an owner that must not leave a tree behind). False when 89there is no job (nothing was contained, or not Windows).""" 90if os .name != "nt" or not _job : 91return False 92return bool (_k32 .TerminateJobObject (_job ,1 )) 93 94 95CREATE_SUSPENDED = 0x00000004 96 97 98def start_contained (args ,** kw ): 99"""``subprocess.Popen(args, **kw)`` with the child in the kill-on-close job before it runs a single instruction. 100contain() after Popen leaves a window: a child that starts a process in its first milliseconds (the `npx` / `uvx` 101wrappers of MCP servers, serve/mcp.py) can do so before it is assigned, and that process stays outside the job and 102survives a hard kill of the server. So the child is created suspended, assigned, then resumed. The resume 103happens whatever the assignment did (a child that is not in the job still runs, as contain() would leave it); a 104child that cannot be resumed is ended and the start fails, never left hanging. Elsewhere: plain Popen.""" 105if os .name != "nt" : 106return subprocess .Popen (args ,** kw ) 107# the caller's own flags (CREATE_NO_WINDOW, CREATE_NEW_PROCESS_GROUP, ...) are kept; every other argument passes as is 108kw ["creationflags" ]= kw .get ("creationflags" ,0 )| CREATE_SUSPENDED 109proc = subprocess .Popen (args ,** kw ) 110real = isinstance (proc ,_REAL_POPEN )# (a test's stand-in object has no suspended process behind it) 111try : 112contain (proc )# False when refused (the server's own job forbids it): it still runs 113except BaseException : 114if real : 115_end (proc )# the caller never gets it: not left suspended, not left running 116raise 117pid = getattr (proc ,"pid" ,None ) 118resumed = isinstance (pid ,int )and pid > 0 and _resume (pid )# (a stand-in wrapping a real process is resumed too) 119if real and not resumed : 120_end (proc ) 121program = args [0 ]if args else "?" 122raise OSError (f"Windows started { program } but did not let it run, so Strata stopped it. " 123"Start it again; if this keeps happening, restart the computer." ) 124return proc 125 126 127def _end (proc )-> None : 128try : 129proc .kill () 130proc .wait (10 ) 131except (OSError ,subprocess .TimeoutExpired ): 132pass 133 134 135if os .name == "nt" : 136class _ThreadEntry (ctypes .Structure ): 137_fields_ = [("dwSize" ,wintypes .DWORD ), ("cntUsage" ,wintypes .DWORD ), ("th32ThreadID" ,wintypes .DWORD ), 138 ("th32OwnerProcessID" ,wintypes .DWORD ), ("tpBasePri" ,wintypes .LONG ), ("tpDeltaPri" ,wintypes .LONG ), 139 ("dwFlags" ,wintypes .DWORD )] 140 141_TH32CS_SNAPTHREAD ,_THREAD_SUSPEND_RESUME = 0x00000004 ,0x0002 142_INVALID_HANDLE = wintypes .HANDLE (- 1 ).value 143_k32 .CreateToolhelp32Snapshot .restype = wintypes .HANDLE 144_k32 .CreateToolhelp32Snapshot .argtypes = (wintypes .DWORD ,wintypes .DWORD ) 145_k32 .Thread32First .argtypes = (wintypes .HANDLE ,ctypes .POINTER (_ThreadEntry )) 146_k32 .Thread32Next .argtypes = (wintypes .HANDLE ,ctypes .POINTER (_ThreadEntry )) 147_k32 .OpenThread .restype = wintypes .HANDLE 148_k32 .OpenThread .argtypes = (wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ) 149_k32 .ResumeThread .restype = wintypes .DWORD 150_k32 .ResumeThread .argtypes = (wintypes .HANDLE ,) 151_k32 .CloseHandle .argtypes = (wintypes .HANDLE ,) 152 153 154def _resume (pid :int )-> bool : 155"""Resume every thread of a process created suspended (a new process has one, its main thread). True if at least 156one thread was resumed.""" 157if os .name != "nt" : 158return True 159snap = _k32 .CreateToolhelp32Snapshot (_TH32CS_SNAPTHREAD ,0 ) 160if not snap or snap == _INVALID_HANDLE : 161return False 162resumed = 0 163try : 164entry = _ThreadEntry () 165entry .dwSize = ctypes .sizeof (_ThreadEntry ) 166ok = _k32 .Thread32First (snap ,ctypes .byref (entry )) 167while ok : 168if entry .th32OwnerProcessID == pid : 169th = _k32 .OpenThread (_THREAD_SUSPEND_RESUME ,False ,entry .th32ThreadID ) 170if th : 171if _k32 .ResumeThread (th )!= 0xFFFFFFFF : 172resumed += 1 173_k32 .CloseHandle (th ) 174ok = _k32 .Thread32Next (snap ,ctypes .byref (entry )) 175finally : 176_k32 .CloseHandle (snap ) 177return resumed > 0 178 179 180def contain (proc )-> bool : 181"""Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise.""" 182global _job 183if os .name != "nt" or proc is None : 184return False 185with _lock : 186if _job is None : 187_job = _make_job ()or 0 188if not _job : 189return False 190try : 191no_throttle (int (proc ._handle )) 192return bool (_k32 .AssignProcessToJobObject (_job ,int (proc ._handle ))) 193except (AttributeError ,OSError ,ValueError ): 194return False