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
12.4 KiB251 linesraw
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
15    python -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":
40    import ctypes
41    from 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:
53    def __init__(self, pid: int, label: str):
54        self.label = label
55        self.handle = _k32.OpenProcess(_SYNCHRONIZE | _QUERY | _PROCESS_TERMINATE, False, pid)
56        if not self.handle:
57            raise ctypes.WinError(ctypes.get_last_error())
58
59    def exited(self, wait_ms: int = 0) -> bool:
60        return _k32.WaitForSingleObject(self.handle, wait_ms) == 0
61
62    def end(self):
63        if self.handle:
64            if not self.exited():
65                _k32.TerminateProcess(self.handle, 1)
66            _k32.CloseHandle(self.handle)
67            self.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
73    def __enter__(self):
74        from strata_control import procs
75        self.tmp = tempfile.TemporaryDirectory()
76        self.patches = [mock.patch.dict(os.environ, {"LOCALAPPDATA": self.tmp.name, "APPDATA": self.tmp.name,
77                                                    "XDG_STATE_HOME": self.tmp.name}),
78                        mock.patch.object(procs, "write_record", lambda *a, **k: None)]
79        for p in self.patches:
80            p.start()
81        return self
82
83    def __exit__(self, *exc):
84        for p in reversed(self.patches):
85            p.stop()
86        self.tmp.cleanup()
87        return False
88
89
90def late(real_contain):
91    def slow_contain(proc):
92        time.sleep(1.5)                           # a late assignment: the child has started its own child by now
93        return real_contain(proc)
94    return slow_contain
95
96
97@unittest.skipUnless(os.name == "nt", "job objects are Windows-only")
98class EarlyGrandchild(unittest.TestCase):
99    def test_a_process_started_before_the_assignment_would_have_run_is_in_the_job(self):
100        from serve import lifeline, winjob
101        held = []
102        with isolated(), mock.patch.object(winjob, "contain", late(winjob.contain)):
103            self.assertEqual(lifeline.mechanism(), "job")
104            child = lifeline.popen([sys.executable, "-c", CHILD], "engine", stdout=subprocess.PIPE, text=True)
105            try:
106                gpid = int(child.stdout.readline().strip())
107                held = [Held(child.pid, "the child"), Held(gpid, "the grandchild")]
108                self.assertFalse(any(h.exited() for h in held))
109                self.assertTrue(winjob.terminate(), "no job to end")   # what the OS does when the server dies
110                left = [h.label for h in held if not h.exited(10000)]
111                self.assertEqual(left, [], "outside the job, so it survived the end of the job")
112            finally:
113                for h in held:
114                    h.end()
115                if child.poll() is None:
116                    child.kill()
117                child.wait(10)
118
119    def 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
121        is a long-running node.  With the assignment late, node used to be outside the job and survive."""
122        node = shutil.which("node")
123        if node is None:
124            self.skipTest("node is not on PATH here")
125        from serve import lifeline, winjob
126        held = []
127        with isolated() as iso, mock.patch.object(winjob, "contain", late(winjob.contain)):
128            shim = Path(iso.tmp.name) / "fake-npx.cmd"
129            shim.write_text('@echo off\r\n"%s" -e "console.log(process.pid); setInterval(function () {}, 1000)"\r\n' % node,
130                            encoding="ascii")
131            child = lifeline.popen([str(shim)], "mcp", stdin=subprocess.PIPE, stdout=subprocess.PIPE,
132                                   stderr=subprocess.PIPE, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
133            try:
134                npid = int(child.stdout.readline().strip())
135                held = [Held(child.pid, "cmd.exe"), Held(npid, "node")]
136                self.assertTrue(winjob.terminate(), "no job to end")
137                self.assertEqual([h.label for h in held if not h.exited(10000)], [], "survived the end of the job")
138            finally:
139                for h in held:
140                    h.end()
141                if child.poll() is None:
142                    child.kill()
143                child.wait(10)
144
145
146@unittest.skipUnless(os.name == "nt", "job objects are Windows-only")
147class FlagsPipesAndRefusals(unittest.TestCase):
148    def start(self, role, **kw):
149        """lifeline.popen of the echo child; returns (the kwargs that reached subprocess.Popen, stdout lines, stderr, exit
150        code, the cwd given, the env given)."""
151        from serve import lifeline
152        seen = {}
153        real_popen = subprocess.Popen
154
155        def recording(args, **k):
156            seen.update(k)
157            return real_popen(args, **k)
158        with tempfile.TemporaryDirectory() as tmp:
159            env = {**os.environ, "STRATA_T_ECHO": "through"}
160            with mock.patch.object(subprocess, "Popen", recording):
161                child = lifeline.popen([sys.executable, "-c", ECHO], role, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
162                                       stderr=subprocess.PIPE, text=True, cwd=tmp, env=env, **kw)
163            out, err = child.communicate("hello\n", timeout=60)
164            return seen, out.splitlines(), err.strip(), child.returncode, tmp, env
165
166    def test_all_three_pipes_cwd_and_env_pass_through_and_the_child_runs(self):
167        from serve import winjob
168        with isolated():
169            seen, out, err, rc, tmp, env = self.start("mcp", creationflags=subprocess.CREATE_NO_WINDOW)
170        self.assertEqual(rc, 0)
171        self.assertEqual(out[0], "HELLO")                         # resumed, and stdin / stdout work
172        self.assertEqual(os.path.normcase(os.path.realpath(out[1])), os.path.normcase(os.path.realpath(tmp)))
173        self.assertEqual(out[2], "through")
174        self.assertEqual(err, "to stderr")
175        self.assertIs(seen["env"], env)
176        self.assertEqual((seen["stdin"], seen["stdout"], seen["stderr"]), (subprocess.PIPE,) * 3)
177        self.assertEqual(seen["creationflags"], subprocess.CREATE_NO_WINDOW | winjob.CREATE_SUSPENDED)
178
179    def test_the_callers_flags_are_kept_beside_the_suspended_start(self):
180        from serve import winjob
181        with isolated():
182            seen, out, _, rc, _, _ = self.start("engine", creationflags=subprocess.CREATE_NO_WINDOW)
183        self.assertEqual((rc, out[0]), (0, "HELLO"))
184        self.assertEqual(seen["creationflags"], subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP |
185                         winjob.CREATE_SUSPENDED)                  # the engine role's own group flag too
186
187    def test_a_refused_assignment_still_starts_and_resumes_the_child(self):
188        from serve import winjob
189        with isolated(), mock.patch.object(winjob._k32, "AssignProcessToJobObject", lambda *a: 0):
190            _, out, _, rc, _, _ = self.start("mcp")
191        self.assertEqual((rc, out[0]), (0, "HELLO"))
192
193    def test_an_error_between_the_start_and_the_resume_leaves_no_child(self):
194        from serve import lifeline, winjob
195        made = []
196        real_popen = subprocess.Popen
197
198        def recording(args, **k):
199            made.append(real_popen(args, **k))
200            return made[-1]
201
202        def broken(proc):
203            raise RuntimeError("assignment exploded")
204        with isolated(), mock.patch.object(subprocess, "Popen", recording), mock.patch.object(winjob, "contain", broken):
205            with self.assertRaises(RuntimeError):
206                lifeline.popen([sys.executable, "-c", "import time; time.sleep(60)"], "mcp")
207        self.assertEqual(len(made), 1)
208        self.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,
232                       stderr=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):
240    def test_a_server_that_runs_in_a_job_of_its_own_still_starts_and_resumes_its_child(self):
241        with tempfile.TemporaryDirectory() as tmp:
242            env = {**os.environ, "LOCALAPPDATA": tmp, "APPDATA": tmp, "XDG_STATE_HOME": tmp}
243            code = "ROOT = %r\nECHO = %r\n" % (str(ROOT), ECHO) + INSIDE_A_JOB
244            done = subprocess.run([sys.executable, "-c", code], env=env, capture_output=True, text=True, timeout=120)
245        self.assertEqual(done.returncode, 0, done.stderr[-2000:])
246        result = [line for line in done.stdout.splitlines() if line.startswith("RESULT")]
247        self.assertEqual(result[:1], ["RESULT 0 NESTED True"], done.stdout + done.stderr[-2000:])
248
249
250if __name__ == "__main__":
251    unittest.main()