okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""serve/winjob.py + serve/lifeline.py: a process that a contained child starts in its very first moments is in the 2kill-on-close job too. lifeline.popen used to assign the child to the job only after Popen returned, so whatever the 3child started before that (the `npx` / `uvx` wrappers of MCP servers start their real server at once) stayed outside the 4job and survived a hard kill of the server. Now the child is created suspended, assigned, then resumed. 5 6The window is made wide on purpose: the assignment is delayed by 1.5 s (a busy machine can delay it too), during which a 7child that already runs has long started its own child. Then the job is ended (winjob.terminate, what the OS does when 8the server dies) and the processes must be gone. They are held by handle, so a reused PID cannot pass. Beside that: 9the caller's creation flags, pipes, cwd and env pass through; a refused assignment and an error before the resume leave 10no child suspended; and a server that itself runs inside a job (no breakaway) still starts and resumes its child. 11 12Nothing of the real install is touched: the per-user state folders point at a temp folder and no launch record is 13written (isolated()). 14 15python -m unittest serve.test_winjob_early_child (Windows only; skipped elsewhere) 16""" 17import os 18import shutil 19import subprocess 20import sys 21import tempfile 22import time 23import unittest 24from pathlib import Path 25from unittest import mock 26 27ROOT = Path (__file__ ).resolve ().parent .parent 28sys .path .insert (0 ,str (ROOT )) 29 30# the child: starts a grandchild at once, says its pid, then waits 31CHILD = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); " 32"print(g.pid, flush=True); time.sleep(120)" ) 33# the echo child: one stdin line back in capitals, its cwd, one variable of its env, a line on stderr 34ECHO = ("import os, sys; line = sys.stdin.readline().strip(); print(line.upper()); print(os.getcwd()); " 35"print(os.environ.get('STRATA_T_ECHO', '-')); print('to stderr', file=sys.stderr)" ) 36 37_PROCESS_TERMINATE ,_SYNCHRONIZE ,_QUERY = 0x0001 ,0x00100000 ,0x1000 38 39if os .name == "nt" : 40import ctypes 41from ctypes import wintypes 42 43_k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 44_k32 .OpenProcess .restype = wintypes .HANDLE 45_k32 .OpenProcess .argtypes = (wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ) 46_k32 .WaitForSingleObject .restype = wintypes .DWORD 47_k32 .WaitForSingleObject .argtypes = (wintypes .HANDLE ,wintypes .DWORD ) 48_k32 .TerminateProcess .argtypes = (wintypes .HANDLE ,wintypes .UINT ) 49_k32 .CloseHandle .argtypes = (wintypes .HANDLE ,) 50 51 52class Held : 53def __init__ (self ,pid :int ,label :str ): 54self .label = label 55self .handle = _k32 .OpenProcess (_SYNCHRONIZE | _QUERY | _PROCESS_TERMINATE ,False ,pid ) 56if not self .handle : 57raise ctypes .WinError (ctypes .get_last_error ()) 58 59def exited (self ,wait_ms :int = 0 )-> bool : 60return _k32 .WaitForSingleObject (self .handle ,wait_ms )== 0 61 62def end (self ): 63if self .handle : 64if not self .exited (): 65_k32 .TerminateProcess (self .handle ,1 ) 66_k32 .CloseHandle (self .handle ) 67self .handle = None 68 69 70class isolated : 71"""The per-user state folders in a temp folder and no launch record: nothing of the real install is touched.""" 72 73def __enter__ (self ): 74from strata_control import procs 75self .tmp = tempfile .TemporaryDirectory () 76self .patches = [mock .patch .dict (os .environ , {"LOCALAPPDATA" :self .tmp .name ,"APPDATA" :self .tmp .name , 77"XDG_STATE_HOME" :self .tmp .name }), 78mock .patch .object (procs ,"write_record" ,lambda * a ,** k :None )] 79for p in self .patches : 80p .start () 81return self 82 83def __exit__ (self ,* exc ): 84for p in reversed (self .patches ): 85p .stop () 86self .tmp .cleanup () 87return False 88 89 90def late (real_contain ): 91def slow_contain (proc ): 92time .sleep (1.5 )# a late assignment: the child has started its own child by now 93return real_contain (proc ) 94return slow_contain 95 96 97@ unittest . skipUnless ( os . name == "nt" , "job objects are Windows-only" ) 98class EarlyGrandchild (unittest .TestCase ): 99def test_a_process_started_before_the_assignment_would_have_run_is_in_the_job (self ): 100from serve import lifeline ,winjob 101held = [] 102with isolated (),mock .patch .object (winjob ,"contain" ,late (winjob .contain )): 103self .assertEqual (lifeline .mechanism (),"job" ) 104child = lifeline .popen ([sys .executable ,"-c" ,CHILD ],"engine" ,stdout = subprocess .PIPE ,text = True ) 105try : 106gpid = int (child .stdout .readline ().strip ()) 107held = [Held (child .pid ,"the child" ),Held (gpid ,"the grandchild" )] 108self .assertFalse (any (h .exited ()for h in held )) 109self .assertTrue (winjob .terminate (),"no job to end" )# what the OS does when the server dies 110left = [h .label for h in held if not h .exited (10000 )] 111self .assertEqual (left , [],"outside the job, so it survived the end of the job" ) 112finally : 113for h in held : 114h .end () 115if child .poll ()is None : 116child .kill () 117child .wait (10 ) 118 119def test_a_cmd_shim_that_starts_node_is_ended_with_its_node (self ): 120"""Close to the report: an MCP server started through a .cmd wrapper (npx / uvx are such shims) whose real program 121is a long-running node. With the assignment late, node used to be outside the job and survive.""" 122node = shutil .which ("node" ) 123if node is None : 124self .skipTest ("node is not on PATH here" ) 125from serve import lifeline ,winjob 126held = [] 127with isolated ()as iso ,mock .patch .object (winjob ,"contain" ,late (winjob .contain )): 128shim = Path (iso .tmp .name )/ "fake-npx.cmd" 129shim .write_text ('@echo off\r\n"%s" -e "console.log(process.pid); setInterval(function () {}, 1000)"\r\n' % node , 130encoding = "ascii" ) 131child = lifeline .popen ([str (shim )],"mcp" ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 132stderr = subprocess .PIPE ,text = True ,creationflags = subprocess .CREATE_NO_WINDOW ) 133try : 134npid = int (child .stdout .readline ().strip ()) 135held = [Held (child .pid ,"cmd.exe" ),Held (npid ,"node" )] 136self .assertTrue (winjob .terminate (),"no job to end" ) 137self .assertEqual ([h .label for h in held if not h .exited (10000 )], [],"survived the end of the job" ) 138finally : 139for h in held : 140h .end () 141if child .poll ()is None : 142child .kill () 143child .wait (10 ) 144 145 146@ unittest . skipUnless ( os . name == "nt" , "job objects are Windows-only" ) 147class FlagsPipesAndRefusals (unittest .TestCase ): 148def start (self ,role ,** kw ): 149"""lifeline.popen of the echo child; returns (the kwargs that reached subprocess.Popen, stdout lines, stderr, exit 150code, the cwd given, the env given).""" 151from serve import lifeline 152seen = {} 153real_popen = subprocess .Popen 154 155def recording (args ,** k ): 156seen .update (k ) 157return real_popen (args ,** k ) 158with tempfile .TemporaryDirectory ()as tmp : 159env = {** os .environ ,"STRATA_T_ECHO" :"through" } 160with mock .patch .object (subprocess ,"Popen" ,recording ): 161child = lifeline .popen ([sys .executable ,"-c" ,ECHO ],role ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 162stderr = subprocess .PIPE ,text = True ,cwd = tmp ,env = env ,** kw ) 163out ,err = child .communicate ("hello\n" ,timeout = 60 ) 164return seen ,out .splitlines (),err .strip (),child .returncode ,tmp ,env 165 166def test_all_three_pipes_cwd_and_env_pass_through_and_the_child_runs (self ): 167from serve import winjob 168with isolated (): 169seen ,out ,err ,rc ,tmp ,env = self .start ("mcp" ,creationflags = subprocess .CREATE_NO_WINDOW ) 170self .assertEqual (rc ,0 ) 171self .assertEqual (out [0 ],"HELLO" )# resumed, and stdin / stdout work 172self .assertEqual (os .path .normcase (os .path .realpath (out [1 ])),os .path .normcase (os .path .realpath (tmp ))) 173self .assertEqual (out [2 ],"through" ) 174self .assertEqual (err ,"to stderr" ) 175self .assertIs (seen ["env" ],env ) 176self .assertEqual ((seen ["stdin" ],seen ["stdout" ],seen ["stderr" ]), (subprocess .PIPE ,)* 3 ) 177self .assertEqual (seen ["creationflags" ],subprocess .CREATE_NO_WINDOW | winjob .CREATE_SUSPENDED ) 178 179def test_the_callers_flags_are_kept_beside_the_suspended_start (self ): 180from serve import winjob 181with isolated (): 182seen ,out ,_ ,rc ,_ ,_ = self .start ("engine" ,creationflags = subprocess .CREATE_NO_WINDOW ) 183self .assertEqual ((rc ,out [0 ]), (0 ,"HELLO" )) 184self .assertEqual (seen ["creationflags" ],subprocess .CREATE_NO_WINDOW | subprocess .CREATE_NEW_PROCESS_GROUP | 185winjob .CREATE_SUSPENDED )# the engine role's own group flag too 186 187def test_a_refused_assignment_still_starts_and_resumes_the_child (self ): 188from serve import winjob 189with isolated (),mock .patch .object (winjob ._k32 ,"AssignProcessToJobObject" ,lambda * a :0 ): 190_ ,out ,_ ,rc ,_ ,_ = self .start ("mcp" ) 191self .assertEqual ((rc ,out [0 ]), (0 ,"HELLO" )) 192 193def test_an_error_between_the_start_and_the_resume_leaves_no_child (self ): 194from serve import lifeline ,winjob 195made = [] 196real_popen = subprocess .Popen 197 198def recording (args ,** k ): 199made .append (real_popen (args ,** k )) 200return made [- 1 ] 201 202def broken (proc ): 203raise RuntimeError ("assignment exploded" ) 204with isolated (),mock .patch .object (subprocess ,"Popen" ,recording ),mock .patch .object (winjob ,"contain" ,broken ): 205with self .assertRaises (RuntimeError ): 206lifeline .popen ([sys .executable ,"-c" ,"import time; time.sleep(60)" ],"mcp" ) 207self .assertEqual (len (made ),1 ) 208self .assertIsNotNone (made [0 ].poll (),"the child was left behind (suspended or running)" ) 209 210 211# the server itself inside a job of its own (a terminal, a service wrapper, the app, a CI runner): kill-on-close and no 212# breakaway; it starts the echo child through lifeline.popen and reports what came back 213INSIDE_A_JOB = r''' 214import ctypes, os, subprocess, sys 215from ctypes import wintypes 216sys.path.insert(0, ROOT) 217k = ctypes.WinDLL("kernel32", use_last_error=True) 218k.CreateJobObjectW.restype = wintypes.HANDLE 219k.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD) 220k.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE) 221k.GetCurrentProcess.restype = wintypes.HANDLE 222from serve import winjob 223job = k.CreateJobObjectW(None, None) 224info = winjob._ExtendedLimits() 225info.BasicLimitInformation.LimitFlags = 0x2000 # kill on close; no BREAKAWAY_OK, no SILENT_BREAKAWAY_OK 226assert k.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)) 227assert k.AssignProcessToJobObject(job, k.GetCurrentProcess()), ctypes.get_last_error() 228from strata_control import procs 229procs.write_record = lambda *a, **kw: None 230from serve import lifeline 231child = lifeline.popen([sys.executable, "-c", ECHO], "mcp", stdin=subprocess.PIPE, stdout=subprocess.PIPE, 232stderr=subprocess.PIPE, text=True) 233out, err = child.communicate("nested\n", timeout=60) 234print("RESULT", child.returncode, out.splitlines()[0], bool(winjob._job)) 235''' 236 237 238@ unittest . skipUnless ( os . name == "nt" , "job objects are Windows-only" ) 239class ServerInsideAJob (unittest .TestCase ): 240def test_a_server_that_runs_in_a_job_of_its_own_still_starts_and_resumes_its_child (self ): 241with tempfile .TemporaryDirectory ()as tmp : 242env = {** os .environ ,"LOCALAPPDATA" :tmp ,"APPDATA" :tmp ,"XDG_STATE_HOME" :tmp } 243code = "ROOT = %r\nECHO = %r\n" % (str (ROOT ),ECHO )+ INSIDE_A_JOB 244done = subprocess .run ([sys .executable ,"-c" ,code ],env = env ,capture_output = True ,text = True ,timeout = 120 ) 245self .assertEqual (done .returncode ,0 ,done .stderr [- 2000 :]) 246result = [line for line in done .stdout .splitlines ()if line .startswith ("RESULT" )] 247self .assertEqual (result [:1 ], ["RESULT 0 NESTED True" ],done .stdout + done .stderr [- 2000 :]) 248 249 250if __name__ == "__main__" : 251unittest .main ()