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
9.3 KiB194 linesraw
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":
22    import ctypes
23    from ctypes import wintypes
24
25    _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
26
27    class _IoCounters(ctypes.Structure):
28        _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount",
29                                                       "OtherOperationCount", "ReadTransferCount",
30                                                       "WriteTransferCount", "OtherTransferCount")]
31
32    class _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
39    class _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
53    def _make_job():
54        job = _k32.CreateJobObjectW(None, None)     # no security attributes: the handle is not inherited
55        if not job:
56            return None
57        info = _ExtendedLimits()
58        info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
59        if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info),
60                                            ctypes.sizeof(info)):
61            _k32.CloseHandle(job)
62            return None
63        return job
64
65    class _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
71    def no_throttle(handle) -> bool:
72        """Opt a process out of Windows power throttling (EcoQoS).  Without it Windows 11 treats a process whose console
73        window is minimized as background work and, on a hybrid CPU, moves its threads to the E-cores: generation
74        slowed by about 20% while the server window was minimized (#691, i9-13980HX: 36.6 -> 43.2 tok/s)."""
75        for mask in (0x1 | 0x4, 0x1):               # EXECUTION_SPEED and IGNORE_TIMER_RESOLUTION, both off (Windows 11);
76            info = _PowerThrottling(1, mask, 0)     # Windows 10 knows the first only: ERROR_INVALID_PARAMETER for both
77            if _k32.SetProcessInformation(handle, 4, ctypes.byref(info), ctypes.sizeof(info)):   # ProcessPowerThrottling
78                return True
79        return False
80
81    no_throttle(_k32.GetCurrentProcess())           # the server itself (tokenizing, streaming) too
82else:
83    def no_throttle(handle) -> bool:
84        return 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
89    there is no job (nothing was contained, or not Windows)."""
90    if os.name != "nt" or not _job:
91        return False
92    return 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.
100    contain() after Popen leaves a window: a child that starts a process in its first milliseconds (the `npx` / `uvx`
101    wrappers of MCP servers, serve/mcp.py) can do so before it is assigned, and that process stays outside the job and
102    survives a hard kill of the server.  So the child is created suspended, assigned, then resumed.  The resume
103    happens whatever the assignment did (a child that is not in the job still runs, as contain() would leave it); a
104    child that cannot be resumed is ended and the start fails, never left hanging.  Elsewhere: plain Popen."""
105    if os.name != "nt":
106        return 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
108    kw["creationflags"] = kw.get("creationflags", 0) | CREATE_SUSPENDED
109    proc = subprocess.Popen(args, **kw)
110    real = isinstance(proc, _REAL_POPEN)              # (a test's stand-in object has no suspended process behind it)
111    try:
112        contain(proc)                                  # False when refused (the server's own job forbids it): it still runs
113    except BaseException:
114        if real:
115            _end(proc)                                 # the caller never gets it: not left suspended, not left running
116        raise
117    pid = getattr(proc, "pid", None)
118    resumed = isinstance(pid, int) and pid > 0 and _resume(pid)   # (a stand-in wrapping a real process is resumed too)
119    if real and not resumed:
120        _end(proc)
121        program = args[0] if args else "?"
122        raise 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.")
124    return proc
125
126
127def _end(proc) -> None:
128    try:
129        proc.kill()
130        proc.wait(10)
131    except (OSError, subprocess.TimeoutExpired):
132        pass
133
134
135if os.name == "nt":
136    class _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
156    one thread was resumed."""
157    if os.name != "nt":
158        return True
159    snap = _k32.CreateToolhelp32Snapshot(_TH32CS_SNAPTHREAD, 0)
160    if not snap or snap == _INVALID_HANDLE:
161        return False
162    resumed = 0
163    try:
164        entry = _ThreadEntry()
165        entry.dwSize = ctypes.sizeof(_ThreadEntry)
166        ok = _k32.Thread32First(snap, ctypes.byref(entry))
167        while ok:
168            if entry.th32OwnerProcessID == pid:
169                th = _k32.OpenThread(_THREAD_SUSPEND_RESUME, False, entry.th32ThreadID)
170                if th:
171                    if _k32.ResumeThread(th) != 0xFFFFFFFF:
172                        resumed += 1
173                    _k32.CloseHandle(th)
174            ok = _k32.Thread32Next(snap, ctypes.byref(entry))
175    finally:
176        _k32.CloseHandle(snap)
177    return 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."""
182    global _job
183    if os.name != "nt" or proc is None:
184        return False
185    with _lock:
186        if _job is None:
187            _job = _make_job() or 0
188        if not _job:
189            return False
190    try:
191        no_throttle(int(proc._handle))
192        return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle)))
193    except (AttributeError, OSError, ValueError):
194        return False