Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: on Windows the engine, vision encoder and MCP servers end with the server

Apposite2454ff986a0aa27
diff --git a/serve/mcp.py b/serve/mcp.py
index 327216fed..610eac61b 100644
--- a/serve/mcp.py
+++ b/serve/mcp.py
@@ -31,6 +31,8 @@ import time
import urllib.error
import urllib.request
+from serve.winjob import contain
+
PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given
DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0}
@@ -105,6 +107,7 @@ class StdioTransport:
env=env, **extra)
except OSError as e:
raise McpError(f"could not start {command!r}: {e}") from None
+ contain(self.proc) # ends with the server, however it ends (Windows)
threading.Thread(target=self._read, daemon=True).start()
threading.Thread(target=self._read_stderr, daemon=True).start()
diff --git a/serve/server.py b/serve/server.py
index 89b88b59f..fd5ad3ada 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -47,6 +47,7 @@ sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a
from serve.frontend import (ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402
images_of, openai_to_messages)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
+from serve.winjob import contain # noqa: E402
IM_END = "<|im_end|>"
IMAGE_PAD = "<|image_pad|>"
@@ -167,6 +168,7 @@ class StrataEngine:
daemon=True).start()
self.proc = subprocess.Popen([exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env)
+ contain(self.proc) # ends with the server, however it ends (Windows)
self.max_context = 0
self.can_stop = False # the engine honours a STOP line mid-request (READY <ctx> stop)
self.last = {}
@@ -394,6 +396,7 @@ class Vision:
self.dir = Path(tempfile.mkdtemp(prefix="strata-vision-"))
self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL,
text=True, encoding="utf-8", bufsize=1, env=env)
+ contain(self.proc)
line = self.proc.stdout.readline()
if not line.startswith("READY"):
raise RuntimeError("the vision encoder did not start: " + line.strip())
diff --git a/serve/test_winjob.py b/serve/test_winjob.py
new file mode 100644
index 000000000..31b617ab2
--- /dev/null
+++ b/serve/test_winjob.py
@@ -0,0 +1,67 @@
+"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even
+when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own.
+
+ python -m unittest serve.test_winjob (Windows only; skipped elsewhere)
+"""
+import os
+import subprocess
+import sys
+import time
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+
+# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed
+PARENT = f"""
+import subprocess, sys, time
+sys.path.insert(0, {str(ROOT)!r})
+from serve.winjob import contain
+code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); "
+ "print(g.pid, flush=True); time.sleep(120)")
+child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True)
+ok = contain(child)
+print(ok, child.pid, child.stdout.readline().strip(), flush=True)
+time.sleep(120)
+"""
+
+
+def running(pid: int) -> bool:
+ out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output=True, text=True).stdout
+ return str(pid) in out
+
+
[email protected](os.name == "nt", "job objects are Windows-only")
+class TestWinJob(unittest.TestCase):
+ def test_children_end_with_a_killed_server(self):
+ # a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter
+ python = getattr(sys, "_base_executable", None) or sys.executable
+ parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True)
+ child = grandchild = None
+ try:
+ ok, child, grandchild = parent.stdout.readline().split()
+ child, grandchild = int(child), int(grandchild)
+ self.assertEqual(ok, "True")
+ self.assertTrue(running(child) and running(grandchild))
+ parent.kill() # TerminateProcess: no atexit, no finally - like closing the window
+ parent.wait(10)
+ deadline = time.monotonic() + 10
+ while (running(child) or running(grandchild)) and time.monotonic() < deadline:
+ time.sleep(0.2)
+ self.assertFalse(running(child), "the child outlived the server")
+ self.assertFalse(running(grandchild), "the grandchild outlived the server")
+ finally:
+ if parent.poll() is None:
+ parent.kill()
+ for pid in (child, grandchild): # on a failure, don't leave them sleeping
+ if pid and running(pid):
+ subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True)
+
+ def test_elsewhere_or_without_a_process_it_is_a_no_op(self):
+ from serve.winjob import contain
+ self.assertFalse(contain(None))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/winjob.py b/serve/winjob.py
new file mode 100644
index 000000000..008642a09
--- /dev/null
+++ b/serve/winjob.py
@@ -0,0 +1,74 @@
+"""serve/winjob.py - on Windows, tie the processes Strata starts to the server's own lifetime.
+
+Closing the console window, Task Manager or a crash end the server without running its cleanup, and the engine,
+the vision encoder and the MCP servers kept running on their own. `contain(proc)` puts a child in a job object that
+is set to kill everything in it when its last handle closes - and the only handle is this process's, which the OS
+closes however the server ends. Processes the child starts later join the same job. The server itself stays out of
+the job, so a browser that `--open` starts is not tied to it. Elsewhere, and if the job cannot be made, a no-op.
+"""
+from __future__ import annotations
+
+import os
+import threading
+
+_job = None
+_lock = threading.Lock()
+
+if os.name == "nt":
+ import ctypes
+ from ctypes import wintypes
+
+ _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
+
+ class _IoCounters(ctypes.Structure):
+ _fields_ = [(n, ctypes.c_ulonglong) for n in ("ReadOperationCount", "WriteOperationCount",
+ "OtherOperationCount", "ReadTransferCount",
+ "WriteTransferCount", "OtherTransferCount")]
+
+ class _BasicLimits(ctypes.Structure):
+ _fields_ = [("PerProcessUserTimeLimit", ctypes.c_longlong), ("PerJobUserTimeLimit", ctypes.c_longlong),
+ ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
+ ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),
+ ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),
+ ("SchedulingClass", wintypes.DWORD)]
+
+ class _ExtendedLimits(ctypes.Structure):
+ _fields_ = [("BasicLimitInformation", _BasicLimits), ("IoInfo", _IoCounters),
+ ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
+ ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
+
+ _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
+ _JobObjectExtendedLimitInformation = 9
+
+ _k32.CreateJobObjectW.restype = wintypes.HANDLE
+ _k32.CreateJobObjectW.argtypes = (wintypes.LPVOID, wintypes.LPCWSTR)
+ _k32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD)
+ _k32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
+
+ def _make_job():
+ job = _k32.CreateJobObjectW(None, None) # no security attributes: the handle is not inherited
+ if not job:
+ return None
+ info = _ExtendedLimits()
+ info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(info),
+ ctypes.sizeof(info)):
+ _k32.CloseHandle(job)
+ return None
+ return job
+
+
+def contain(proc) -> bool:
+ """Put a started subprocess.Popen in the kill-on-close job. True if it is in; False (harmlessly) otherwise."""
+ global _job
+ if os.name != "nt" or proc is None:
+ return False
+ with _lock:
+ if _job is None:
+ _job = _make_job() or 0
+ if not _job:
+ return False
+ try:
+ return bool(_k32.AssignProcessToJobObject(_job, int(proc._handle)))
+ except (AttributeError, OSError, ValueError):
+ return False