Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: reap the llama-server tree on Windows unload, and unblock a dead spawned backend (#11022)
Daniel Hanbe395e811559
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 3eda91ae8ce..126f6922c7b 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -30684,23 +30684,129 @@ class LlamaCppBackend:@staticmethoddef _collect_descendants(pid):- """The server's own children, for the kill below. Empty when unreadable."""+ """`(children, known)` for the kill below.++ `known` is False when the walk could not be made at all: no Toolhelp snapshot, or+ a root whose own identity cannot be read. An empty list then means "not+ enumerable", not "none", and the difference decides whether this unload may drop+ the record and the pidfile. Treating it as "none" terminates the leader, finds no+ survivors and deletes the only handles on whatever the failed walk did not list.+ """try:- from utils.process_lifetime import collect_descendants- return collect_descendants(pid)+ from utils.process_lifetime import collect_descendants_known+ return collect_descendants_known(pid)except Exception:- return []+ # The import or the walk itself failed, which says nothing about the tree.+ return [], False++ @staticmethod+ def _tree_kill_surviving_process(pid) -> bool:+ """Last resort for a server still alive after terminate. True when it is gone.++ ``owner_verified``: this is reached holding the Popen that spawned the pid, so+ ownership is not in question even when the start time behind the lifetime+ record can no longer be read.+ """+ if not _is_signalable_pid(pid):+ return False+ try:+ from utils.process_lifetime import confirm_pid_exited, terminate_pid+ except Exception:+ return False+ try:+ terminate_pid(pid, timeout = 5.0, owner_verified = True)+ except Exception as e:+ logger.warning(f"Could not terminate surviving llama-server {pid}: {e}")+ try:+ # Not a bare `pid_is_running` read: every kill terminate_pid just made is+ # asynchronous, and asking on the line after one answers its own latency. The+ # two arms below it settle internally now, so this is belt and braces, but a+ # read that decides whether to delete the last handle on a live server is worth+ # spelling the same way everywhere.+ gone = confirm_pid_exited(pid)+ except Exception:+ return False+ if not gone:+ logger.warning(+ f"llama-server {pid} is still running after a tree kill; "+ "keeping its record so the next launch can reap it"+ )+ return gone++ @staticmethod+ def _confirm_group_kill_landed(pid) -> bool:+ """Did the killpg above actually take the leader with it. True when it is gone.++ The cheap half of `_tree_kill_surviving_process`, for the POSIX case where the+ expensive half is a second killpg over a group this teardown has already SIGKILLed.+ No signal is sent from here: the only open question is whether the one already sent+ has finished landing, and kills are asynchronous, so it is answered with a bounded+ poll rather than a single read taken microseconds after the signal.++ False keeps the lifetime record and the pidfile, exactly as a failed tree kill does,+ so a server the group kill could not reach is still reapable by the next launch.+ """+ if not _is_signalable_pid(pid):+ return False+ try:+ from utils.process_lifetime import confirm_pid_exited+ except Exception:+ return False+ try:+ gone = confirm_pid_exited(pid)+ except Exception:+ return False+ if not gone:+ logger.warning(+ f"llama-server {pid} is still running after its process group was killed; "+ "keeping its record so the next launch can reap it"+ )+ return gone@staticmethoddef _terminate_descendants(collected):- """The diffusion shim's visual server, and anything else it started."""+ """The diffusion shim's visual server, and anything else it started.++ Returns the survivors as `(pid, identity)`: the ones still running when the sweep+ gave up, each with the creation-time identity the sweep verified. A forced kill can+ simply fail (access denied, a protected process, an uninterruptible driver ioctl),+ and reading the attempt as the outcome is what lets the caller delete the record+ and the pidfile out from under a worker that is still holding the GPU.+ Each survivor is adopted WITH that identity, so it gets a lifetime record of its+ own rather than depending on the leader's: the leader is usually gone by now, and+ on Windows there is no process group standing in for it. The identity travels+ because a survivor can exit between the sweep's last liveness check and the adopt,+ and adopting the bare number would then record a stranger and, where a job object+ is active, put it in a job that kills its members when the app closes.+ """if not collected:- return+ return []try:- from utils.process_lifetime import terminate_descendants- terminate_descendants(collected, timeout = 5.0)+ from utils.process_lifetime import adopt_pid, terminate_descendants+ survivors = terminate_descendants(collected, timeout = 5.0)except Exception as e:logger.debug(f"Could not terminate server descendants: {e}")+ # Unknown, not none. The pids were collected, so they can still be named, and+ # naming them is the whole point of this return value.+ return list(collected)+ for pid, identity in survivors:+ try:+ # from_snapshot: these pids came out of a walk, so a None identity here means+ # the collector could not READ one, not that this process has just spawned+ # the child. Capturing one now would record whatever holds the number at this+ # moment, which is the recycled stranger the identity check exists to keep+ # out -- and where a job object is active, put it in a job that kills its+ # members when the app closes.+ adopt_pid(pid, identity, from_snapshot = True)+ except Exception:+ pass+ if survivors:+ logger.warning(+ f"llama-server descendants still running after the sweep: "+ f"{[pid for pid, _ in survivors]}; "+ "recorded so the next launch can reap them"+ )+ return survivorsdef _publish_healthy(self) -> bool:"""Commit _healthy under the spawn lock, or refuse if this load is stale.@@ -30819,7 +30925,7 @@ class LlamaCppBackend:# so the visual server has to be named while that link still exists._pid = getattr(self._process, "pid", None)_pgid = self._leading_process_group(_pid)- _descendants = self._collect_descendants(_pid)+ _descendants, _descendants_known = self._collect_descendants(_pid)if teardown:# Before the signal, and as the process itself: the reference stays set# across the waits below, and only identity says which child a teardown@@ -30846,7 +30952,7 @@ class LlamaCppBackend:logger.warning(f"Error killing llama-server process: {e}")finally:self._kill_process_group(_pgid)- self._terminate_descendants(_descendants)+ _surviving_descendants = self._terminate_descendants(_descendants)# getattr: teardown must tolerate a partially-built backend (failed# __init__ or a __new__-built instance), as with _llama_log_fh below.if getattr(self, "_stats_logger", None) is not None:@@ -30858,6 +30964,59 @@ class LlamaCppBackend:# identity, so a recycled pid is never signalled either way._killed_pid = getattr(self._process, "pid", None)_exited = getattr(self._process, "poll", lambda: None)() is not None+ # The tree kill below tells the reaper the owner is known, which waives the+ # "cannot prove this pid is still our child" refusal. That waiver is only+ # true while we hold the handle that spawned the pid, so it is spent on a+ # real child and nothing else: a stand-in _process carrying a pid and no+ # poll() (tests use one to mean "a server is loaded", and one of them holds+ # this process's own pid) reads as "still running" through no fault of its+ # own, and signalling that number would take down whoever holds it now.+ _owns_child = terminable and callable(getattr(self._process, "poll", None))+ if _owns_child and _killed_pid is not None and not _exited:+ if _pgid is not None and hasattr(os, "killpg"):+ # A real process group that `_kill_process_group` could actually+ # signal, which only POSIX ever reports here (_leading_process_group+ # answers None everywhere else, and that function's own no-op+ # condition is repeated so this cannot skip a kill that never+ # happened). killpg+ # SIGKILL went to this exact group eleven lines above, and the tree+ # kill's POSIX arm is killpg SIGTERM, a poll loop, then killpg+ # SIGKILL over the same group: no reach this teardown does not+ # already have, for a full /proc walk and up to five seconds more+ # with _teardown_lock held. Measured at +560 ms of lock hold on the+ # survivor path, which is time a lifecycle reopening behind the lock+ # spends blocked.+ #+ # What the call did buy is the read-back, and that is kept. killpg is+ # asynchronous like every other kill here, so asking on the next line+ # answers "not finished yet" and keeps the record and the pidfile for+ # a server that is already gone.+ _exited = self._confirm_group_kill_landed(_killed_pid)+ else:+ # The terminate above is all Popen offers, and on Windows that is+ # TerminateProcess on the leader alone: a server that ignored it, or+ # that the escalation could not reach, is still holding the model's+ # mapping. taskkill /T /F is the only handle left on it there, and+ # nothing on this path used to reach for it (#9790).+ _exited = self._tree_kill_surviving_process(_killed_pid)+ # A descendant the sweep could not kill keeps the leader's record too. It was+ # adopted under its own pid above, but the record here is what the pidfile and+ # the next launch's reap are keyed on, and dropping it while something of this+ # server is still running is the state that leaves a worker on the GPU with+ # nothing naming it.+ if _surviving_descendants:+ _exited = False+ # And a tree that could not be enumerated is not a tree with nothing in it.+ # The sweep above ran over whatever the failed walk returned, so "no survivors"+ # here is a statement about a list that was never built. Keep the record: a+ # leaked worker the next launch can reap costs a stale pidfile, and dropping it+ # costs the only name anything has for a process still holding the GPU.+ if not _descendants_known and _pid is not None:+ logger.warning(+ "llama-server descendants could not be enumerated before the kill; "+ "keeping its record so the next launch can reap anything left"+ )+ _exited = Falseif _killed_pid is not None and _exited:try:from utils.process_lifetime import forget_pid@@ -30865,7 +31024,13 @@ class LlamaCppBackend:except Exception:passself._process = None- self._clear_server_pid()+ # Same rule as the lifetime record above: the pidfile is the next launch's+ # only handle on a server that outlived this kill, so it is removed once the+ # exit is confirmed and not merely attempted. Without a child handle there is+ # no exit to confirm and nothing was signalled, so the pidfile is dropped as+ # it always was rather than kept forever by a stand-in that cannot answer.+ if _killed_pid is None or _exited or not _owns_child:+ self._clear_server_pid()# Clear healthy so a /load during the replacement's warm-up can't# short-circuit against the previous server's health (#5401).self._healthy = Falsediff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.pyindex e3ae0562586..e45972d1962 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py@@ -233,7 +233,7 @@ class TestWaitForHealthResilience:b._stop_mtp_crash_watchdog = lambda *a, **kw: Noneb._reset_effective_parallel_slots = lambda *a, **kw: Noneb._leading_process_group = lambda *a, **kw: None- b._collect_descendants = lambda *a, **kw: []+ b._collect_descendants = lambda *a, **kw: ([], True)b._kill_process_group = lambda *a, **kw: Noneb._terminate_descendants = lambda *a, **kw: Noneb._process.poll.return_value = 0@@ -377,7 +377,7 @@ class TestWaitForHealthResilience:b._stop_mtp_crash_watchdog = lambda *a, **kw: Noneb._reset_effective_parallel_slots = lambda *a, **kw: Noneb._leading_process_group = lambda *a, **kw: None- b._collect_descendants = lambda *a, **kw: []+ b._collect_descendants = lambda *a, **kw: ([], True)b._kill_process_group = lambda *a, **kw: Noneb._terminate_descendants = lambda *a, **kw: Noneseen = {}@@ -1314,7 +1314,7 @@ class TestHealthPublicationIsAtomicWithTeardown:b._process = object()b._reset_effective_parallel_slots = lambda: Noneb._leading_process_group = lambda _pid: None- b._collect_descendants = lambda _pid: []+ b._collect_descendants = lambda _pid: ([], True)b._diffusion_requested_ngl = Nonepublished = b._publish_healthy()@@ -1411,7 +1411,7 @@ def test_a_lifecycle_cannot_reopen_while_a_teardown_is_still_killing():b._reset_effective_parallel_slots = lambda: Noneb._diffusion_requested_ngl = Noneb._leading_process_group = lambda _pid: None- b._collect_descendants = lambda _pid: []+ b._collect_descendants = lambda _pid: ([], True)b._spawn_lock = threading.RLock() # so the probe below can observe, not deadlockreopened_during_kill = []@@ -1489,7 +1489,7 @@ class TestATeardownDoesNotBlockASpawnItWillRefuse:b._reset_effective_parallel_slots = lambda: Noneb._diffusion_requested_ngl = Noneb._leading_process_group = lambda _p: None- b._collect_descendants = lambda _p: []+ b._collect_descendants = lambda _p: ([], True)class _Stubborn:pid = 4242@@ -1588,6 +1588,31 @@ def test_the_lock_order_is_teardown_then_spawn():assert not inversions, f"_teardown_lock taken inside _spawn_lock at {inversions}"+def test_no_kill_double_still_returns_the_legacy_shape():+ """`_collect_descendants` answers `(descendants, known)`, and the teardown unpacks it.++ Five doubles in this file still returned a bare list, so every kill path here raised+ `ValueError: not enough values to unpack` and the teardown cases were exercising nothing.+ A grep is the cheapest guard against the same drift: a double that returns a list is a+ test that cannot reach the code it names.+ """+ import ast+ import inspect+ import sys++ module = sys.modules[__name__]+ tree = ast.parse(inspect.getsource(module))+ for node in ast.walk(tree):+ if not isinstance(node, ast.Assign):+ continue+ target = node.targets[0]+ if not isinstance(target, ast.Attribute) or target.attr != "_collect_descendants":+ continue+ assert isinstance(node.value, ast.Lambda), ast.unparse(node)+ body = node.value.body+ assert isinstance(body, ast.Tuple) and len(body.elts) == 2, ast.unparse(node)++class TestHealthWaitMeasuresStalls:# Grow RSS, then idle._WORKER = (diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.pyindex 6fb0bace602..17d1476c0f3 100644--- a/studio/backend/tests/test_orphaned_children.py+++ b/studio/backend/tests/test_orphaned_children.py@@ -478,6 +478,15 @@ def test_a_survivor_keeps_its_record_through_a_clean_shutdown(tmp_path, monkeypa# Signalling silently does nothing, as an unkillable child would.monkeypatch.setattr(pl, "_posix_terminate", lambda pid, timeout = 5.0: None)monkeypatch.setattr(pl.os, "kill", lambda pid, sig: None)+ # Both spellings, not just the POSIX one. `terminate_all` routes through the+ # validated tree kill on Windows, and that goes to TerminateProcess through a+ # handle rather than to `os.kill`, so on a Windows runner this child really was+ # killed and the test was passing on the read-back being taken before the kill had+ # landed. False is the Windows spelling of what the line above says: the signal did+ # nothing and the tree still stands.+ monkeypatch.setattr(+ pl, "_windows_terminate_validated_tree", lambda pid, identity = None: False+ )survivors = pl.terminate_all()assert survivors == [stubborn.pid]@@ -697,7 +706,11 @@ def test_the_windows_breadcrumb_fallback_takes_the_whole_tree(tmp_path, monkeypamonkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == 4242)monkeypatch.setattr(pl, "_identity_or_none", lambda pid: "same" if pid == 4242 else None)trees = []- monkeypatch.setattr(pl, "_windows_terminate_tree", trees.append)+ monkeypatch.setattr(+ pl,+ "_windows_terminate_validated_tree",+ lambda pid, identity = None: trees.append(pid),+ )record = tmp_path / "999.json"record.write_text(@@ -843,7 +856,11 @@ def test_the_windows_backstop_takes_the_whole_tree(tmp_path, monkeypatch):monkeypatch.setattr(pl, "_pid_identity", lambda pid: "same")monkeypatch.setattr(pl, "_identity_or_none", lambda pid: "same")trees = []- monkeypatch.setattr(pl, "_windows_terminate_tree", trees.append)+ monkeypatch.setattr(+ pl,+ "_windows_terminate_validated_tree",+ lambda pid, identity = None: trees.append(pid),+ )killed_singly = []monkeypatch.setattr(pl.os, "kill", lambda pid, sig: killed_singly.append(pid))@@ -899,7 +916,7 @@ def test_a_retained_child_keeps_its_group(tmp_path, monkeypatch):monkeypatch.setattr(pl, "_pid_identity", lambda pid: "recorded")monkeypatch.setattr(pl, "_identity_or_none", lambda pid: "recorded")monkeypatch.setattr(pl, "_posix_terminate", lambda pid, timeout = 5.0: None)- monkeypatch.setattr(pl, "_windows_terminate_tree", lambda pid: None)+ monkeypatch.setattr(pl, "_windows_terminate_validated_tree", lambda pid, identity = None: None)assert pl.terminate_all(timeout = 1.0) == [4242]assert pl._tracked_pgids.get(4242) == 4242@@ -1871,11 +1888,11 @@ def test_a_tree_taskkill_could_not_take_keeps_its_record(tmp_path, monkeypatch):state = {"leader": True, "tree": False}monkeypatch.setattr(lifetime, "_pid_alive", lambda pid: state["leader"])- def fake_tree(pid):+ def fake_tree(pid, identity = None):state["leader"] = Falsereturn state["tree"]- monkeypatch.setattr(lifetime, "_windows_terminate_tree", fake_tree)+ monkeypatch.setattr(lifetime, "_windows_terminate_validated_tree", fake_tree)def write_record():(tmp_path / "previous.json").write_text(@@ -1916,11 +1933,11 @@ def test_a_failed_tree_kill_keeps_the_pid_in_the_shutdown_record(monkeypatch):state = {"leader": True, "tree": False}monkeypatch.setattr(lifetime, "_pid_alive", lambda pid: state["leader"])- def fake_tree(pid):+ def fake_tree(pid, identity = None):state["leader"] = Falsereturn state["tree"]- monkeypatch.setattr(lifetime, "_windows_terminate_tree", fake_tree)+ monkeypatch.setattr(lifetime, "_windows_terminate_validated_tree", fake_tree)def track():with lifetime._record_lock:@@ -2198,7 +2215,14 @@ def test_terminate_pid_keeps_a_record_taskkill_could_not_confirm(monkeypatch):monkeypatch.setattr(lifetime, "_write_breadcrumb", lambda: None)state = {"tree": False}- monkeypatch.setattr(lifetime, "_windows_terminate_tree", lambda pid: state["tree"])+ # The validated sweep, not `taskkill /T`: the Windows tree kill is enumerated by+ # `_windows_collect_descendants` so it cannot re-expand through a recycled pid. The+ # contract under test is unchanged -- a tree that did not go down keeps its record.+ monkeypatch.setattr(+ lifetime,+ "_windows_terminate_validated_tree",+ lambda pid, identity = None: state["tree"],+ )def track():with lifetime._record_lock:diff --git a/studio/backend/tests/test_windows_unload_tree_kill.py b/studio/backend/tests/test_windows_unload_tree_kill.pynew file mode 100644index 00000000000..153e81ae930--- /dev/null+++ b/studio/backend/tests/test_windows_unload_tree_kill.py@@ -0,0 +1,2408 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An unload has to reap the whole server tree on Windows, not just its leader (#9790).++`collect_descendants` and `terminate_descendants` returned early and did nothing at all+on Windows, so an unload terminated llama-server and left whatever it had started+holding the model's mapping, and the pidfile was dropped either way so the next launch+could not reap it. The platform arms are covered twice: once against a real process+tree on this host, with only the one seam that cannot exist here faked, and once for+real on a Windows runner with nothing faked at all.+"""++from __future__ import annotations++import contextlib+import os+import signal+import subprocess+import sys+import textwrap+import time+import types as _types+from pathlib import Path+from unittest import mock++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++# Mirror the sibling llama_cpp tests so the module imports without fastapi/structlog.+_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)+sys.modules.setdefault("structlog", _types.ModuleType("structlog"))++import utils.process_lifetime as pl # noqa: E402++IS_WINDOWS = sys.platform == "win32"+IS_LINUX = sys.platform.startswith("linux")++[email protected](autouse = True)+def _warm_the_owner_identity():+ """Read this process's own identity before anything here fakes `_pid_identity`.++ `_own_identity` caches into a module global on first call and keeps it for the life+ of the interpreter, deliberately, since it cannot change. A test that fakes+ `_pid_identity` and then reaches any code path writing a breadcrumb would cache the+ fake, and every later test in the session would read this process as a dead owner+ and reap its children.+ """+ pl._own_identity()+++# ── a real two-level process tree ──++_TREE = textwrap.dedent(+ """+ import pathlib, subprocess, sys, time+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"])+ pathlib.Path(sys.argv[1]).write_text(str(child.pid))+ time.sleep(300)+ """+)+++def _alive(pid: int) -> bool:+ if IS_WINDOWS:+ out = subprocess.run(+ ["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output = True, text = True+ ).stdout+ return str(pid) in out+ try:+ os.kill(pid, 0)+ except OSError:+ return False+ # A child nobody has waited on answers signal 0 exactly like a live one.+ return not pl._pid_is_zombie(pid)+++def _wait_dead(pid: int, timeout: float = 10.0) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not _alive(pid):+ return True+ time.sleep(0.05)+ return not _alive(pid)+++def _signals_that_never_land(pids):+ """`os.kill` swallows the stop signals aimed at *pids*, and only for this block.++ SIGKILL cannot be caught, so the way a process survives one is that the signal never+ lands: denied, or the target is wedged in an uninterruptible driver ioctl. Faking that+ is the only way to reach the state deterministically.++ Deliberately NOT `monkeypatch.setattr`. A fixture's finalizer runs BEFORE monkeypatch+ undoes anything, so a test that fakes `os.kill` for the whole test hands the fake to+ its own tree fixture's cleanup: `_hard_kill` becomes a no-op and the processes are+ still sleeping when the run ends, one set per run. The block has to end before the+ fixture tears down, and `finally` is what guarantees it even when an assert fails.++ Signal 0 passes straight through, so the liveness probe stays real.+ """+ blocked = set(pids)+ real_kill = os.kill++ def _kill(pid, sig, *rest):+ if pid in blocked and sig in (signal.SIGTERM, signal.SIGKILL):+ return None+ return real_kill(pid, sig, *rest)++ os.kill = _kill+ try:+ yield+ finally:+ os.kill = real_kill+++def _hard_kill(pid: int) -> None:+ try:+ if IS_WINDOWS:+ subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output = True)+ else:+ os.kill(pid, signal.SIGKILL)+ except Exception:+ pass+++def tree(tmp_path):+ """(leader Popen, child pid) for a leader that spawned one child and sleeps."""+ marker = tmp_path / "child.pid"+ leader = subprocess.Popen([sys.executable, "-c", _TREE, str(marker)])+ child_pid = None+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ try:+ child_pid = int(marker.read_text())+ break+ except (OSError, ValueError):+ time.sleep(0.05)+ if child_pid is None:+ leader.kill()+ pytest.fail("the spawned child never recorded its pid")+ assert _alive(child_pid)+ try:+ yield leader, child_pid+ finally:+ _hard_kill(child_pid)+ try:+ leader.kill()+ leader.wait(timeout = 10)+ except Exception:+ pass+++# ── the collect side ──+++def _windows_shaped_identity(pid: int):+ """A real Linux start time dressed as a Windows creation FILETIME.++ Windows identities are `high:low` of a 64-bit FILETIME and the walk ORDERS two of+ them to reject a stranger, so a constant would not exercise the floor. Splitting the+ real start time the same way keeps the real ordering between leader and child.+ """+ try:+ with open(f"/proc/{pid}/stat", encoding = "utf-8") as fh:+ stat = fh.read()+ ticks = int(stat[stat.rfind(")") + 2 :].split()[19])+ except Exception:+ return None+ return f"{ticks >> 32}:{ticks & 0xFFFF_FFFF}"++[email protected](not IS_LINUX, reason = "reads real start times out of /proc")+def test_the_windows_walk_claims_a_real_child(monkeypatch, tree):+ """The guard this replaces returned [] for every Windows caller, which is the+ whole of #9790: the unload had nothing to terminate but the leader."""+ leader, child_pid = tree+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", _windows_shaped_identity)+ collected = pl.collect_descendants(leader.pid)+ assert child_pid in [+ pid for pid, _ in collected+ ], f"collect_descendants({leader.pid}) -> {collected}, missing the spawned child"++[email protected](not IS_LINUX, reason = "reads real start times out of /proc")+def test_the_windows_walk_claims_nothing_without_a_readable_root(monkeypatch, tree):+ """Windows keeps a creating pid on a process forever, so with no creation time for+ the root there is no way to tell its children from a stranger left behind by an+ earlier holder of that number. Claiming nothing is the only safe answer."""+ leader, _child_pid = tree+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ assert pl.collect_descendants(leader.pid) == []+++def test_the_windows_walk_rejects_a_stranger_that_predates_the_root(monkeypatch):+ """A recycled pid whose old holder created this process. Its recorded parent is our+ root's number, it is not our child, and taskkilling it would take down an unrelated+ tree, which is worse than the leak being fixed."""+ root, real_child, stranger, grandchild = 500, 600, 700, 800+ created = {root: 1_000, real_child: 2_000, stranger: 10, grandchild: 20}+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{created[pid]}")+ monkeypatch.setattr(+ pl, "_child_pid_map", lambda: {root: [real_child, stranger], stranger: [grandchild]}+ )+ assert [pid for pid, _ in pl.collect_descendants(root)] == [real_child]+++def test_the_windows_walk_rejects_a_stranger_under_a_reused_intermediate_pid(monkeypatch):+ """The root's own creation time is NOT a sufficient floor.++ The machine this is about, with times as Windows would report them:++ * the Unsloth root starts at t=100;+ * an unrelated process U starts at t=200, created by some pid P;+ * that original P exits;+ * at t=300 Windows hands P's number to a genuine Unsloth child;+ * U still records P as its creator and nothing ever clears that.++ U is later than the ROOT, so a root-only floor admits it, and the survivor sweep+ then passes it to `taskkill /PID <U> /T /F`, which takes down U and everything+ under it: someone's training run, editor or server. Ordering U against its own+ parent's CURRENT creation time rejects it, because a process cannot predate the+ process that created it. Nothing real is signalled here: the table, the identities+ and the kill are all fabricated.+ """+ root, reused_parent, stranger, stranger_child, real_grandchild = 500, 600, 700, 701, 601+ created = {+ root: 100,+ reused_parent: 300, # P after the reuse: a genuine Unsloth child+ stranger: 200, # U, created by the OLD holder of P+ stranger_child: 250, # U's own work, hanging off a link we do not have+ real_grandchild: 400, # a true descendant of the reused pid+ }+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{created[pid]}")+ monkeypatch.setattr(+ pl,+ "_child_pid_map",+ lambda: {+ root: [reused_parent],+ reused_parent: [stranger, real_grandchild],+ stranger: [stranger_child],+ },+ )+ found = [pid for pid, _ in pl.collect_descendants(root)]+ assert stranger not in found, "a stranger predating its own parent was claimed"+ assert stranger_child not in found, "the stranger's subtree was walked"+ assert sorted(found) == [reused_parent, real_grandchild]+++def test_the_kill_does_not_re_expand_a_rejected_stranger(monkeypatch):+ """The collector's filter must survive the kill that acts on it.++ `taskkill /T` terminates the named process AND its child processes, and it finds+ them by walking the live parent-pid links -- exactly the links the collector above+ refuses to trust. So U is correctly kept OUT of the collected list, but U still+ records the reused number P as its creator, and a `/T` on P, which IS collected and+ IS identity-verified, rediscovers U through Windows' own walk. The filter is defeated+ by the kill it protects, and someone's training run dies anyway.++ Same fixture as the collector test above, driven one step further.+ """+ root, reused_parent, stranger, stranger_child, real_grandchild = 500, 600, 700, 701, 601+ created = {+ root: 100,+ reused_parent: 300,+ stranger: 200,+ stranger_child: 250,+ real_grandchild: 400,+ }+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{created[pid]}")+ monkeypatch.setattr(+ pl,+ "_child_pid_map",+ lambda: {+ root: [reused_parent],+ reused_parent: [stranger, real_grandchild],+ stranger: [stranger_child],+ },+ )+ killed = []+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: killed.append(pid))++ # Reaching for /T at all is the regression: the expansion happens inside Windows, so+ # no assertion on the resulting pid set can see it once the call has been made.+ def _no_tree_kill(pid):+ raise AssertionError(f"taskkill /T was used on {pid}; it re-expands rejected pids")++ monkeypatch.setattr(pl, "_windows_terminate_tree", _no_tree_kill)++ collected = pl.collect_descendants(root)+ pl._windows_terminate_collected(collected)++ assert stranger not in killed, "the rejected stranger was killed by tree expansion"+ assert stranger_child not in killed, "the stranger's own work was killed with it"+ # Everything the collector DID claim still dies, deepest first.+ assert set(killed) == {reused_parent, real_grandchild}+ assert killed.index(real_grandchild) < killed.index(reused_parent)+++def test_the_windows_walk_skips_a_candidate_whose_identity_cannot_be_read(monkeypatch):+ """An unreadable creation time proves nothing, and the action taken on the result+ is a forced tree kill, so the candidate and its subtree are dropped."""+ root, child, grandchild = 500, 600, 700+ created = {root: 100, child: None, grandchild: 900}+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(+ pl,+ "_pid_identity",+ lambda pid: None if created[pid] is None else f"0:{created[pid]}",+ )+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {root: [child], child: [grandchild]})+ assert pl.collect_descendants(root) == []+++# ── the terminate side ──++[email protected](IS_WINDOWS, reason = "the real taskkill is covered below")+def test_the_windows_terminate_reaps_every_survivor(monkeypatch, tree):+ """`_windows_terminate_collected` is the whole Windows arm of terminate_descendants.+ Only `taskkill`, which does not exist here, is stood in for; the pids, the liveness+ probe and the identity check are all real, and so is the process that has to die."""+ leader, child_pid = tree+ asked = []++ def fake_taskkill(pid, identity = None):+ asked.append(pid)+ _hard_kill(pid)+ return True++ monkeypatch.setattr(pl, "_windows_terminate_pid", fake_taskkill)+ collected = [(child_pid, pl._pid_identity(child_pid))]+ leader.terminate()+ leader.wait(timeout = 10)+ pl._windows_terminate_collected(collected)+ assert asked == [child_pid]+ assert _wait_dead(child_pid), "the spawned child outlived the unload"+++def test_the_windows_terminate_skips_a_recycled_pid(monkeypatch):+ """The leader's terminate runs between the snapshot and this call, so a number here+ can already belong to something else by now."""+ # `_same_identity` compares the start time alone on Linux, for records written before+ # it carried a comm, and a whole Windows FILETIME pair on Windows. Both halves of the+ # synthetic identities here have to count, so this reads as the Windows host it is about.+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:999")+ asked = []+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: asked.append(pid))+ pl._windows_terminate_collected([(4242, "0:1")])+ assert asked == []+++def test_the_windows_terminate_works_deepest_first(monkeypatch):+ """A child has to go before the parent whose link named it, or the link is gone."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ identities = {10: "0:10", 11: "0:11", 12: "0:12"}+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: identities[pid])+ order = []+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: order.append(pid))+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ # collect_descendants emits breadth first, so the parent comes before its child.+ pl._windows_terminate_collected([(10, "0:10"), (11, "0:11"), (12, "0:12")])+ assert order == [12, 11, 10]+++def test_the_windows_terminate_leaves_an_unreadable_identity_alone(monkeypatch):+ """Fail closed, not open.++ `_still_the_same` answers "is this provably somebody else", which is right for a+ SIGTERM at a pid we still hold a record for. It is wrong here: this runs AFTER the+ leader's terminate, an unreadable identity is exactly what a recycled pid looks+ like, and the action is `taskkill /T /F`, which reaches everything the number now+ owns. So a pid whose identity cannot be read on either side is skipped.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ asked = []+ monkeypatch.setattr(pl, "_windows_terminate_tree", lambda pid: asked.append(pid))++ # the identity cannot be read NOW+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ pl._windows_terminate_collected([(4242, "0:1")])+ assert asked == [], "an unreadable current identity must not be tree killed"++ # the identity was not readable AT COLLECTION either+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:1")+ pl._windows_terminate_collected([(4242, None)])+ assert asked == [], "a survivor collected without an identity must not be tree killed"+++# ── the real thing, on a real Windows runner ──++[email protected](not IS_WINDOWS, reason = "the Windows arms, unfaked")+def test_windows_unload_reaps_the_spawned_child_for_real(tree):+ """The round-2 repro, as a test: snapshot the tree, terminate the leader the way+ Popen does, then sweep. On the guarded code the sweep had nothing to sweep and the+ child was still alive here."""+ leader, child_pid = tree+ collected = pl.collect_descendants(leader.pid)+ assert child_pid in [+ pid for pid, _ in collected+ ], f"collect_descendants({leader.pid}) -> {collected}"+ leader.terminate()+ leader.wait(timeout = 10)+ pl.terminate_descendants(collected, timeout = 10.0)+ assert _wait_dead(child_pid), "the spawned child outlived the unload"++[email protected](not IS_WINDOWS, reason = "Toolhelp snapshot")+def test_the_toolhelp_snapshot_reads_this_process_as_its_parent(tree):+ """The table itself, before any filtering: a real Popen child has to be listed+ under this interpreter's pid."""+ leader, _child_pid = tree+ table = pl._windows_child_pid_map()+ assert table is not None, "the Toolhelp snapshot could not be read"+ assert leader.pid in table.get(+ os.getpid(), []+ ), f"pid {leader.pid} is not listed under its own parent {os.getpid()}"+++def test_a_windows_identity_orders_by_creation_time():+ assert pl._windows_creation_time("2:1") == (2 << 32) | 1+ assert pl._windows_creation_time("1:4294967295") < pl._windows_creation_time("2:0")+ for bad in (None, 5, "", "12345", "a:b", "1:2:3"):+ assert pl._windows_creation_time(bad) is None+++# ── the unload path in the backend ──+++def _make_backend():+ from core.inference.llama_cpp import LlamaCppBackend++ b = LlamaCppBackend.__new__(LlamaCppBackend)+ b._port = 12345+ b._stdout_thread = None+ b._stdout_lines = []+ b._process = mock.Mock()+ b._stats_logger = None+ b._llama_log_fh = None+ b._stop_mtp_crash_watchdog = lambda *a, **kw: None+ b._reset_effective_parallel_slots = lambda *a, **kw: None+ b._leading_process_group = lambda *a, **kw: None+ b._collect_descendants = lambda *a, **kw: ([], True)+ b._kill_process_group = lambda *a, **kw: None+ b._terminate_descendants = lambda *a, **kw: []+ return b+++def _instrument(monkeypatch, *, gone: bool):+ from core.inference.llama_cpp import LlamaCppBackend++ cleared, killed = [], []+ monkeypatch.setattr(+ LlamaCppBackend, "_clear_server_pid", classmethod(lambda cls: cleared.append(1))+ )++ def tree_kill(pid):+ killed.append(pid)+ return gone++ monkeypatch.setattr(LlamaCppBackend, "_tree_kill_surviving_process", staticmethod(tree_kill))+ return cleared, killed+++def test_an_unload_tree_kills_a_server_that_ignored_the_terminate(monkeypatch):+ """Popen.terminate is TerminateProcess on the leader alone on Windows. Nothing on+ this path used to reach for taskkill, and the pidfile went either way, so the next+ launch could not reap what was left."""+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = None # still running after terminate and kill+ cleared, killed = _instrument(monkeypatch, gone = False)+ b._kill_process()+ assert killed == [4242]+ assert cleared == [], "dropped the pidfile while the server was still running"+++def test_an_unload_clears_the_pidfile_once_the_tree_kill_worked(monkeypatch):+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = None+ cleared, killed = _instrument(monkeypatch, gone = True)+ b._kill_process()+ assert killed == [4242]+ assert cleared == [1]+++def test_an_unload_that_already_worked_does_not_tree_kill(monkeypatch):+ """The common path. A server that exited on the terminate must not pay for a+ taskkill, and must still have its pidfile removed."""+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = 0+ cleared, killed = _instrument(monkeypatch, gone = False)+ b._kill_process()+ assert killed == []+ assert cleared == [1]+++def test_an_unload_with_nothing_to_kill_still_clears_the_pidfile(monkeypatch):+ """A stand-in _process with no pid, as the tests that mean "a server is loaded"+ without spawning one use. There is nothing to prove gone, so a stale pidfile from a+ previous run must not be kept forever."""+ b = _make_backend()+ b._process = mock.Mock(spec = []) # no pid, no terminate, no poll+ cleared, killed = _instrument(monkeypatch, gone = False)+ b._kill_process()+ assert killed == []+ assert cleared == [1]+++def test_the_tree_kill_tells_the_reaper_the_owner_is_known(monkeypatch):+ """The unload holds the Popen that spawned the pid, so terminate_pid must not refuse+ on "cannot prove this is still our child" when the start time behind the lifetime+ record can no longer be read."""+ from core.inference.llama_cpp import LlamaCppBackend++ calls = []+ monkeypatch.setattr(pl, "terminate_pid", lambda pid, **kw: calls.append((pid, kw)))+ monkeypatch.setattr(pl, "pid_is_running", lambda pid: False)+ assert LlamaCppBackend._tree_kill_surviving_process(4242) is True+ assert calls == [(4242, {"timeout": 5.0, "owner_verified": True})]+++def test_the_tree_kill_reports_a_server_it_could_not_stop(monkeypatch):+ from core.inference.llama_cpp import LlamaCppBackend++ monkeypatch.setattr(pl, "terminate_pid", lambda pid, **kw: None)+ monkeypatch.setattr(pl, "pid_is_running", lambda pid: True)+ assert LlamaCppBackend._tree_kill_surviving_process(4242) is False++[email protected]("pid", [None, 0, 1])+def test_the_tree_kill_never_signals_a_reserved_pid(monkeypatch, pid):+ from core.inference.llama_cpp import LlamaCppBackend++ calls = []+ monkeypatch.setattr(pl, "terminate_pid", lambda p, **kw: calls.append(p))+ assert LlamaCppBackend._tree_kill_surviving_process(pid) is False+ assert calls == []+++def test_owner_verified_still_leaves_a_recycled_pid_alone(monkeypatch):+ """The waiver is for "cannot prove it is ours", not for "it provably is not"."""+ monkeypatch.setattr(pl, "_pid_alive", lambda p: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda p: "NOW-SOMEONE-ELSE")+ signalled = []+ monkeypatch.setattr(pl, "_windows_terminate_tree", lambda p: signalled.append(p))+ monkeypatch.setattr(pl, "_posix_terminate", lambda p, t: signalled.append(p))+ # A registry of its own, and no breadcrumb: the real ones belong to the process+ # running the suite, and `forget_pid` on the mismatch path writes one out.+ monkeypatch.setattr(pl, "_tracked_pids", {4242: "WHEN-WE-SPAWNED-IT"})+ monkeypatch.setattr(pl, "_tracked_pgids", {})+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ pl.terminate_pid(4242, timeout = 0.01, owner_verified = True)+ assert signalled == []+ assert 4242 not in pl._tracked_pids, "a provably recycled pid must not stay recorded"+++def test_a_stand_in_process_with_a_pid_is_never_signalled(monkeypatch):+ """The waiver is spent only on a pid we hold the spawning handle for.++ `_process` is a real Popen in the server, but several sibling tests stand in a plain+ object carrying a pid to mean "a server is loaded", and one of them uses this very+ process's pid. Such an object has no `poll`, so the unload reads it as "still+ running" and used to hand the number to a reaper that had been told the owner was+ verified, which waives the "cannot prove this is ours" refusal: the number's current+ holder was terminated. Nothing is signalled here, and the pidfile still goes, which+ is what the unload did before the tree kill existed.+ """+ b = _make_backend()+ b._process = type("P", (), {"pid": 4242})()+ cleared, killed = _instrument(monkeypatch, gone = False)+ b._kill_process()+ assert killed == [], "signalled a pid this backend never spawned"+ assert cleared == [1], "kept the pidfile for a stand-in that can never confirm an exit"+++def test_a_stand_in_with_a_pid_leaves_a_real_bystander_running():+ """The same rule against a live process, with nothing about the kill faked.++ A stand-in's pid belongs to whoever holds the number now. Terminating it is the+ failure, so the assertion is on a process that has to survive the unload.+ """+ from core.inference.llama_cpp import LlamaCppBackend++ bystander = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])+ try:+ for _ in range(50):+ if bystander.poll() is None:+ break+ time.sleep(0.05)+ assert bystander.poll() is None, "the bystander never started"+ b = _make_backend()+ b._process = type("P", (), {"pid": bystander.pid})()+ b._clear_server_pid = lambda: None+ b._kill_process()+ time.sleep(1.0)+ assert (+ bystander.poll() is None+ ), f"the unload terminated an unrelated process (rc {bystander.poll()})"+ finally:+ bystander.kill()+ bystander.wait(timeout = 10)+++# ── the surviving-root fallback, and what it leaves behind ──+++def test_the_surviving_root_fallback_does_not_re_expand_the_tree(monkeypatch):+ """`terminate_pid` is where the unload's last resort lands, and it used to mean `/T`.++ The collector refuses to trust the live parent-pid links, and `taskkill /T` finds its+ children by walking exactly those links, so routing the fallback through it hands the+ rejected stranger straight back to the kill. Windows does the expansion, so no+ assertion on the resulting pid set can observe it: the tree call is made to raise+ instead, which fails this test the moment anything reaches for it.+ """+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ identities = {500: "0:500", 600: "0:600"}+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: identities.get(pid))+ monkeypatch.setattr(pl, "_tracked_pids", {500: "0:500"})+ monkeypatch.setattr(pl, "_tracked_pgids", {})+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_group_has_members", lambda pgid: False)++ def _no_tree(pid):+ raise AssertionError("taskkill /T re-expands through the links the filter rejects")++ monkeypatch.setattr(pl, "_windows_terminate_tree", _no_tree)+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(600, "0:600")], True) if pid == 500 else ([], True),+ )+ dead: "set[int]" = set()+ killed = []++ def _kill(pid, identity = None):+ killed.append(pid)+ dead.add(pid)+ return True++ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)++ pl.terminate_pid(500, timeout = 0.01, owner_verified = True)+ # Root first, then the snapshot deepest-first. The root is stopped the moment the+ # snapshot exists, because working through the snapshot spends one `taskkill` per+ # descendant and a root that is still running can spawn into a window that nothing+ # afterwards examines. Its descendants are already named, with their identities, so+ # stopping it cannot lose them.+ assert killed == [500, 600], "the root is stopped first, then the validated set only"+ assert 500 not in pl._tracked_pids, "a tree that went down releases its record"+++def test_the_surviving_root_fallback_keeps_the_record_when_something_lives(monkeypatch):+ """The other half of the contract the `/T` call carried: False means the record stays.++ Reading it back from the pids matters more here than it did with `/T`, because the+ exit status of one `taskkill /F` says nothing about the descendant killed before it.+ """+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ # The root dies, the descendant does not: exactly the shape a per-pid kill can produce+ # and a single /T status could never report.+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == 600)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ identities = {500: "0:500", 600: "0:600"}+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: identities.get(pid))+ monkeypatch.setattr(pl, "_tracked_pids", {500: "0:500"})+ monkeypatch.setattr(pl, "_tracked_pgids", {})+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_group_has_members", lambda pgid: False)+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(600, "0:600")], True) if pid == 500 else ([], True),+ )+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)++ pl.terminate_pid(500, timeout = 0.01, owner_verified = True)+ assert 500 in pl._tracked_pids, "dropped the only handle on a worker that is still up"+++def test_a_descendant_that_would_not_die_is_reported(monkeypatch):+ """`taskkill /F` can fail, and can report success on a process that has not gone.++ Discarding that answer is what lets the unload delete the record and the pidfile with a+ worker still holding the GPU: nothing else names it after the leader is reaped.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ # Returns True, and the process is still there. The read-back is the only thing that+ # can tell the difference.+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ assert pl._windows_terminate_collected([(10, "0:10"), (11, "0:11")]) == [+ (11, "0:11"),+ (10, "0:10"),+ ]+++def test_a_descendant_that_did_die_is_not_reported(monkeypatch):+ """The ordinary path reports nothing, or every unload would keep its record forever."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ assert pl._windows_terminate_collected([(10, "0:10")]) == []++[email protected](IS_WINDOWS, reason = "the POSIX arm")+def test_the_posix_sweep_reports_a_child_the_signals_did_not_reach(tree):+ """Same contract on POSIX, with the real child and the real liveness probe.++ SIGKILL cannot be caught, but it is not instantaneous either, and a worker asleep in a+ driver ioctl outlives it. The signals are stubbed out rather than the process being+ made unkillable, which is the only way to reach that state deterministically.+ """+ leader, child_pid = tree+ collected = pl.collect_descendants(leader.pid)+ assert child_pid in [pid for pid, _ in collected]+ with _signals_that_never_land([child_pid]):+ survivors = pl.terminate_descendants(collected, timeout = 0.2)+ assert child_pid in [+ pid for pid, _ in survivors+ ], "a child that is plainly still running was reported dead"+ assert _alive(child_pid)+++def test_an_unload_keeps_the_pidfile_when_a_descendant_survives(monkeypatch):+ """The leader exited cleanly, so the unload would have dropped the record and the+ pidfile. Its worker is still up, and after the leader is reaped those are the only+ things that name anything about this server to the next launch."""+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = 0 # the leader itself went down on the terminate+ b._terminate_descendants = lambda *a, **kw: [(777, "0:777")]+ cleared, killed = _instrument(monkeypatch, gone = True)+ b._kill_process()+ assert killed == [], "the leader exited, so there is nothing to tree kill"+ assert cleared == [], "dropped the pidfile with a worker of this server still running"+++def test_an_unload_clears_the_pidfile_when_every_descendant_died(monkeypatch):+ """The common path, unchanged: nothing survived, so nothing is kept."""+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = 0+ b._terminate_descendants = lambda *a, **kw: []+ cleared, killed = _instrument(monkeypatch, gone = True)+ b._kill_process()+ assert cleared == [1]+++def test_a_surviving_descendant_is_adopted_so_a_later_sweep_can_reach_it(monkeypatch):+ """The leader's record is keyed on the leader. Once it is gone the survivor needs a+ record of its own, and on Windows there is no process group to stand in for one."""+ from core.inference.llama_cpp import LlamaCppBackend++ adopted = []+ monkeypatch.setattr(+ pl,+ "terminate_descendants",+ lambda collected, timeout: [(777, "0:777")],+ )+ monkeypatch.setattr(+ pl,+ "adopt_pid",+ lambda pid, identity = None, from_snapshot = False: adopted.append(+ (pid, identity, from_snapshot)+ ),+ )+ assert LlamaCppBackend._terminate_descendants([(777, "0:777")]) == [(777, "0:777")]+ # The identity the sweep verified travels with the pid, so the adopt cannot record a+ # process that took the number over in between -- and it is flagged as coming from a+ # snapshot, so a survivor whose identity could NOT be read is refused rather than having+ # one captured for it now, which would record whoever holds the number at this moment.+ assert adopted == [(777, "0:777", True)]+++def test_a_sweep_that_raised_names_every_pid_it_had(monkeypatch):+ """An exception is "unknown", not "none". The pids were collected, so they can still+ be named, and naming them is the whole point of the return value."""+ from core.inference.llama_cpp import LlamaCppBackend++ def _raises(collected, timeout):+ raise RuntimeError("Toolhelp snapshot unavailable")++ monkeypatch.setattr(pl, "terminate_descendants", _raises)+ assert LlamaCppBackend._terminate_descendants([(777, "0:777"), (778, None)]) == [+ (777, "0:777"),+ (778, None),+ ]+++# ── an answer that could not be obtained is not an answer of "none" ──+++def test_an_unreadable_process_table_is_indeterminate_not_empty(monkeypatch):+ """`[]` has two meanings and only one of them is safe to act on.++ The Toolhelp snapshot can fail outright, and the walk can fail partway. Reported as an+ empty tree, the unload terminates the leader, finds no survivors, and deletes the+ record and the pidfile -- so the workers the failed snapshot never listed are left+ running with nothing naming them, which is the leak this collector was added to close,+ reached through a failed snapshot instead of through a reparent.+ """+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:500")+ monkeypatch.setattr(pl, "_child_pid_map", lambda: None)+ assert pl.collect_descendants_known(500) == ([], False)+ # The old spelling still answers with the list alone, so callers that only want+ # something to signal are unaffected.+ assert pl.collect_descendants(500) == []++ # A readable table with no children is the other meaning, and it must stay knowable.+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {999: [1000]})+ assert pl.collect_descendants_known(500) == ([], True)+++def test_a_root_with_no_readable_identity_is_indeterminate(monkeypatch):+ """The root's creation time is the ancestry floor, so without it the walk can prove+ nothing about anything -- which is not the same as proving there is nothing."""+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {500: [600]})+ assert pl.collect_descendants_known(500) == ([], False)+++def test_an_unenumerable_tree_keeps_the_pidfile(monkeypatch):+ """The leader exited cleanly and the sweep found nothing, but the sweep ran over a list+ that was never built. Keeping the record costs a stale pidfile; dropping it costs the+ only name anything has for a process that may still hold the GPU."""+ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = 0+ b._collect_descendants = lambda *a, **kw: ([], False)+ b._terminate_descendants = lambda *a, **kw: []+ cleared, _killed = _instrument(monkeypatch, gone = True)+ b._kill_process()+ assert cleared == [], "dropped the pidfile after a walk that could not be made"+++def test_a_live_but_unverifiable_descendant_is_reported_not_signalled(monkeypatch):+ """Refusing to kill it is right. Saying nothing about it is not.++ An identity that cannot be read on either side is exactly what a recycled pid looks+ like, so it must not be signalled. It is also what a live worker under momentary+ handle pressure looks like, and omitting it from the survivor list told the caller the+ sweep was complete.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None) # unreadable NOW+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ killed = []+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: killed.append(pid))+ assert pl._windows_terminate_collected([(11, "0:11")]) == [(11, "0:11")]+ assert killed == [], "an unverifiable pid must never be signalled"+++def test_a_pid_that_provably_moved_on_is_neither_killed_nor_adopted(monkeypatch):+ """The boundary. A number that now belongs to a stranger is not our leaked worker, so+ adopting it would put someone else's process into our lifetime record."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:999") # somebody else+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ killed = []+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: killed.append(pid))+ assert pl._windows_terminate_collected([(11, "0:11")]) == []+ assert killed == []+++def test_the_two_provable_questions_are_asked_separately(monkeypatch):+ """`_provably_the_same` folds "somebody else" and "cannot tell" into one False, which+ is right for deciding whether to signal and wrong for deciding whether to report."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:11")+ assert pl._provably_the_same(11, "0:11") is True+ assert pl._provably_different(11, "0:11") is False+ assert pl._provably_the_same(11, "0:99") is False+ assert pl._provably_different(11, "0:99") is True++ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ # Unknown on one side: neither question can be answered yes.+ assert pl._provably_the_same(11, "0:11") is False+ assert pl._provably_different(11, "0:11") is False+ assert pl._provably_the_same(11, None) is False+ assert pl._provably_different(11, None) is False+++# ── an enumeration that failed is not an enumeration that ended ──+++def test_a_walk_that_failed_partway_is_not_a_table(monkeypatch):+ """`Process32NextW` returning FALSE is not "that was the last one".++ It is also every way the walk can fail partway, and only ERROR_NO_MORE_FILES says the+ list ended. Reading a termination error as the end returns a table missing whatever+ came after it, and a table is read as an ANSWER: the unload then finds no survivors and+ deletes the record and the pidfile for workers the walk never reached. The Windows+ scanner in studio/src-tauri/src/process.rs already makes this distinction.+ """+ source = Path(pl.__file__).read_text(encoding = "utf-8")+ start = source.index("def _windows_child_pid_map")+ body = source[start : source.index("\ndef ", start + 10)]+ assert "ERROR_NO_MORE_FILES = 18" in body+ assert "ctypes.get_last_error() != ERROR_NO_MORE_FILES" in body+ # And the branch returns None, which is what `known` is derived from, rather than the+ # partial table.+ error_branch = body[body.index("ctypes.get_last_error()") :]+ assert error_branch.split("\n")[1].strip() == "return None", error_branch.split("\n")[1]+++def test_a_failed_late_walk_kills_the_survivor_and_reports_it(monkeypatch):+ """The second walk covers whatever the survivor started AFTER the snapshot.++ Failing it and carrying on killed the survivor and then reported nothing, so a+ grandchild only that walk could have named was left running with the record and the+ pidfile deleted. The survivor itself is still killed -- it is collected and+ identity-verified, and refusing on a walk BELOW it would leave the process this sweep+ exists for running -- but the tree is reported unresolved so the record stays.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], False)+ )+ killed = []+ dead: "set[int]" = set()++ # The kill WORKS here, so the survivor read-back finds nothing and the unresolved+ # report is the only thing that can name this tree. Without that, a pid that merely+ # outlived its own kill would satisfy the assertion for the wrong reason.+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ def _kill(pid, identity = None):+ killed.append(pid)+ dead.add(pid)+ return True++ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)+ assert pl._windows_terminate_collected([(11, "0:11")]) == [(11, "0:11")]+ assert killed == [11], "the collected, verified survivor must still be killed"+++def test_a_successful_late_walk_still_reports_nothing(monkeypatch):+ """The ordinary path is unchanged, or every unload would keep its record."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ assert pl._windows_terminate_collected([(11, "0:11")]) == []+++def test_an_unenumerable_tree_is_not_a_completed_tree_kill(monkeypatch):+ """`terminate_pid` forgets the record on True, so an unenumerable tree cannot answer+ True after a root-only kill: the workers the walk never named would be left with+ nothing pointing at them."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: False) # the root itself went down+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)++ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], False)+ )+ assert pl._windows_terminate_validated_tree(500) is False++ # And a walk that DID run, with nothing under the root, is still a completed kill.+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ assert pl._windows_terminate_validated_tree(500) is True+++def test_a_live_unverifiable_descendant_is_an_incomplete_tree_kill(monkeypatch):+ """`terminate_pid` forgets the record on True, so this read-back has to fail closed.++ A descendant that is still alive and whose creation time cannot be read right now is+ not proof of a recycled pid: handle pressure and access denial look exactly the same as+ a number that has moved on. Ignoring it dropped the last persistent handle on a worker+ that was neither confirmed dead nor shown to be somebody else.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(600, "0:600")], True) if pid == 500 else ([], True),+ )+ # The root dies, the descendant survives, and its identity is unreadable NOW.+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == 600)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ assert pl._windows_terminate_validated_tree(500) is False++ # And a descendant that PROVABLY belongs to someone else is not ours to wait for, so+ # the kill is still complete: this must not turn every recycled number into a kept+ # record, which would be the leak in the other direction.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:999")+ assert pl._windows_terminate_validated_tree(500) is True+++def test_a_recycled_survivor_is_not_adopted(monkeypatch):+ """A survivor can exit between the sweep's last liveness check and the adopt.++ The number is then free, and adopting it records a stranger as this process's child --+ and where a job object is active, puts it in a job that kills its members when the app+ closes. The identity the sweep verified travels with the pid so the adopt can tell.+ """+ recorded = {}+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_adopt_fork_reset", lambda: None)+ monkeypatch.setattr(pl, "_own_process_group", lambda pid: None)+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_tracked_pids", recorded)+ # The number now belongs to something that started later.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "9:9999")++ pl.adopt_pid(4242, "0:4242")+ assert recorded == {}, "adopted a pid that is provably somebody else"++ # Unknown adopts nobody either: an identity that cannot be read is not a match.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: None)+ pl.adopt_pid(4242, "0:4242")+ assert recorded == {}, "adopted a pid whose identity could not be confirmed"++ # And the pid that IS still the same is adopted, with the identity that was verified.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:4242")+ pl.adopt_pid(4242, "0:4242")+ assert recorded == {4242: "0:4242"}++ # A caller with no identity to offer is unchanged: this is the spawn path.+ recorded.clear()+ monkeypatch.setattr(pl, "_identity_for_record", lambda pid: "read-now")+ pl.adopt_pid(4343)+ assert recorded == {4343: "read-now"}+++class _FakeKernel32:+ """Enough of kernel32 for the adopt path: every name is a settable stub.++ `_win_signatures` assigns argtypes and restype onto each entry point, so the attributes+ have to exist and carry assignment, and the three the adopt path actually calls are+ overridden by the test.+ """++ def __init__(self, **calls):+ self._stubs = {}+ for name, fn in calls.items():+ self._stubs[name] = fn++ def __getattr__(self, name):+ if name.startswith("_"):+ raise AttributeError(name)+ stub = self._stubs.get(name)+ if stub is None:++ def stub(*args, **kwargs): # noqa: ANN001,ANN202 -- a no-op entry point+ return 1++ self._stubs[name] = stub+ return stub+++def test_the_handle_identity_is_read_through_the_handle(monkeypatch):+ """The creation time has to come from the handle, not from the number again.++ A handle pins the process it was opened on, so what it reports is what the later call on+ that same handle will act upon. Unreadable times are None, which the caller treats as+ "not proven" rather than as a match.+ """+ import ctypes++ def _times(handle, created_ptr, *rest):+ if handle != 77:+ return 0+ created_ptr._obj.dwHighDateTime = 7+ created_ptr._obj.dwLowDateTime = 4242+ return 1++ kernel32 = _FakeKernel32(GetProcessTimes = _times)+ assert pl._windows_identity_of_handle(kernel32, 77) == "7:4242"+ # A failed read is None, never a fabricated match.+ assert pl._windows_identity_of_handle(kernel32, 78) is None+ del ctypes+++def test_a_pid_recycled_before_the_job_assignment_is_not_assigned(monkeypatch):+ """The pid check happens before the record write and the breadcrumb flush.++ The process can exit anywhere in that interval, its number be taken by a stranger, and+ the `OpenProcess` that follows then lands on the stranger. Assigning that handle to a+ job whose limit is kill-on-close means closing Unsloth kills an unrelated process, so+ the creation time is re-read THROUGH the handle that is about to be assigned.+ """+ import ctypes++ assigned: "list[int]" = []+ opened_rights: "list[int]" = []+ closed: "list[int]" = []+ handle_identity = {"value": "0:4242"}++ def _open(rights, inherit, pid):+ opened_rights.append(rights)+ return 77++ def _times(handle, created_ptr, *rest):+ spelling = handle_identity["value"]+ if spelling is None:+ return 0+ high, low = spelling.split(":")+ created_ptr._obj.dwHighDateTime = int(high)+ created_ptr._obj.dwLowDateTime = int(low)+ return 1++ kernel32 = _FakeKernel32(+ OpenProcess = _open,+ GetProcessTimes = _times,+ AssignProcessToJobObject = lambda job, handle: assigned.append(handle) or 1,+ CloseHandle = lambda handle: closed.append(handle) or 1,+ )+ # ctypes has no WinDLL off Windows, so it is created rather than replaced.+ monkeypatch.setattr(ctypes, "WinDLL", lambda *a, **k: kernel32, raising = False)+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_win_job_handle", 4321)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_adopt_fork_reset", lambda: None)+ monkeypatch.setattr(pl, "_own_process_group", lambda pid: None)+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_tracked_pids", {})+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:4242")++ # The number was taken by something that started later, in the window the pid check+ # cannot cover.+ handle_identity["value"] = "9:9999"+ pl.adopt_pid(4242, "0:4242")+ assert assigned == [], "a stranger was assigned to the kill-on-close job"+ assert closed == [77], "the handle was leaked"++ # Unreadable times are not a match either.+ handle_identity["value"] = None+ pl.adopt_pid(4242, "0:4242")+ assert assigned == [], "assigned a handle whose process could not be identified"++ # The process that is still the same one is assigned, which is the whole point of the+ # belt-and-suspenders pass.+ handle_identity["value"] = "0:4242"+ pl.adopt_pid(4242, "0:4242")+ assert assigned == [77], assigned+ # And the read right is requested, or GetProcessTimes could never succeed on the handle.+ assert all(rights & 0x1000 for rights in opened_rights), opened_rights+++def test_the_forced_kill_goes_through_the_handle_it_verified(monkeypatch):+ """A pid is a NAME, and `taskkill /PID` resolves it inside itself.++ That lookup happens after the caller's identity check and after this process has spent+ time getting to the call, so a number freed in between carries the kill onto whatever+ inherited it. A handle is the process rather than its name: the creation time is read+ from the same object TerminateProcess then ends.+ """+ import ctypes+ import subprocess++ terminated: "list[int]" = []+ closed: "list[int]" = []+ handle_identity = {"value": "0:4242"}+ spawned: "list[list]" = []++ def _times(handle, created_ptr, *rest):+ spelling = handle_identity["value"]+ if spelling is None:+ return 0+ high, low = spelling.split(":")+ created_ptr._obj.dwHighDateTime = int(high)+ created_ptr._obj.dwLowDateTime = int(low)+ return 1++ kernel32 = _FakeKernel32(+ OpenProcess = lambda rights, inherit, pid: 91,+ GetProcessTimes = _times,+ TerminateProcess = lambda handle, code: terminated.append(handle) or 1,+ CloseHandle = lambda handle: closed.append(handle) or 1,+ )+ monkeypatch.setattr(ctypes, "WinDLL", lambda *a, **k: kernel32, raising = False)+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: spawned.append(a)+ or (_ for _ in ()).throw(+ AssertionError("taskkill was spawned for a pid a handle could answer for")+ ),+ )++ assert pl._windows_terminate_pid(4242, "0:4242") is True+ assert terminated == [91], terminated+ assert closed == [91], "the handle was leaked"++ # The number now belongs to something that started later: refused, and nothing is+ # signalled by any route.+ terminated.clear()+ handle_identity["value"] = "9:9999"+ assert pl._windows_terminate_pid(4242, "0:4242") is False+ assert terminated == []++ # Unreadable is not a match either.+ handle_identity["value"] = None+ assert pl._windows_terminate_pid(4242, "0:4242") is False+ assert terminated == []++ # A handle that cannot be opened at all is "cannot answer", not "wrong process", so the+ # old ladder still runs -- but only once ownership has been re-established on the number,+ # immediately before the spawn. `taskkill /PID` resolves that number itself, which is the+ # race the handle route exists to close.+ kernel32._stubs["OpenProcess"] = lambda rights, inherit, pid: 0+ monkeypatch.setattr(+ subprocess,+ "run",+ lambda *a, **k: spawned.append(a[0]) or _types.SimpleNamespace(returncode = 0),+ )+ monkeypatch.setattr(pl, "_provably_the_same", lambda pid, identity: True)+ assert pl._windows_terminate_pid(4242, "0:4242") is True+ assert spawned and spawned[-1][0] == "taskkill", spawned++ # And when it cannot be established, nothing is spawned at all: the old code ran taskkill+ # first and only checked afterwards, so the one signal that could hit a stranger was the+ # one nothing had vouched for.+ spawned.clear()+ monkeypatch.setattr(pl, "_provably_the_same", lambda pid, identity: False)+ assert pl._windows_terminate_pid(4242, "0:4242") is False+ assert spawned == [], spawned+ # With no identity there is nothing to establish, so the same refusal applies.+ monkeypatch.setattr(pl, "_provably_the_same", lambda pid, identity: identity is not None)+ assert pl._windows_terminate_pid(4242) is False+ assert spawned == [], spawned+++def test_no_windows_kill_path_calls_taskkill_slash_t_any_more():+ """The validated collector is only a filter while every forced kill goes through it.++ `taskkill /T` re-walks the live parent-pid links, so any call site that keeps it hands+ the rejected stranger back to the kill -- including the deferred one, where a record is+ reaped at the next application start.+ """+ import ast+ from pathlib import Path++ tree = ast.parse(Path(pl.__file__).read_text(encoding = "utf-8"))+ callers = [+ node.func.id+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_windows_terminate_tree"+ ]+ assert callers == [], "a kill path still expands the tree through taskkill /T"+++def test_an_unreadable_child_identity_makes_the_walk_incomplete(monkeypatch):+ """Toolhelp listed it and this cannot classify it: that is a candidate, not an absence.++ Reported complete, the unload terminated the leader, saw no survivors and deleted the+ record and the pidfile while the child was still running. It is still never signalled --+ unknown is not a licence to kill -- only never silently dropped.+ """+ root, child = 5000, 5001+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {root: [child]})+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(+ pl,+ "_pid_identity",+ lambda pid: "0:100" if pid == root else None,+ )+ found, known = pl.collect_descendants_known(root)+ assert found == []+ assert known is False, "a live child this walk could not classify was reported as absent"++ # A pid that has GONE says nothing about completeness: there is nothing left to name.+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == root)+ found, known = pl.collect_descendants_known(root)+ assert (found, known) == ([], True)+++def test_an_unverifiable_late_descendant_is_reported_not_dropped(monkeypatch):+ """The second walk, under a survivor, had two outcomes where the first has three.++ An identity that becomes unreadable between the late walk and the revalidation is not a+ recycled pid, and dropping it let `attempted` come back empty while the descendant was+ still running, so the caller deleted the only records naming it.+ """+ survivor, late_pid = 6000, 6001+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: None)+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(late_pid, "0:6001")], True),+ )+ # The survivor still reads as itself; the late descendant has become unreadable.+ monkeypatch.setattr(+ pl,+ "_pid_identity",+ lambda pid: "0:6000" if pid == survivor else None,+ )+ reported = pl._windows_terminate_collected([(survivor, "0:6000")])+ assert late_pid in [pid for pid, _ in reported], reported++ # A late descendant that is PROVABLY somebody else is still ignored.+ monkeypatch.setattr(+ pl,+ "_pid_identity",+ lambda pid: "0:6000" if pid == survivor else "9:9999",+ )+ reported = pl._windows_terminate_collected([(survivor, "0:6000")])+ assert late_pid not in [pid for pid, _ in reported], reported+++def test_the_root_is_stopped_before_its_snapshot_is_worked_through(monkeypatch):+ """Each `taskkill` has a 15 second ceiling, so working through a snapshot of N+ descendants leaves a root that is still running for as long as N of those.++ Anything it starts in that window is in no snapshot, the read-back examines only what+ WAS snapshotted, and the caller is told the tree is gone. The root therefore goes first,+ the moment the snapshot exists.+ """+ root, child = 700, 701+ spawned_during_teardown = []+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(+ pl,+ "_pid_identity",+ lambda pid: {root: "0:700", child: "0:701"}.get(pid),+ )+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(child, "0:701")], True) if pid == root else ([], True),+ )+ dead: "set[int]" = set()+ order = []++ def _kill(pid, identity = None):+ order.append(pid)+ dead.add(pid)+ # A root that is still alive keeps spawning. This is what the old order allowed.+ if root not in dead:+ spawned_during_teardown.append(len(order))+ return True++ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ assert pl._windows_terminate_validated_tree(root) is True+ assert order[0] == root, order+ assert (+ spawned_during_teardown == []+ ), "the root was still running while its snapshot was being killed"+++def test_a_child_started_after_the_snapshot_is_still_reached(monkeypatch):+ """The snapshot is taken once, and each `taskkill` after it can take 15 seconds.++ A descendant therefore has a long window in which to start a child of its own before+ its own turn comes. That child is in no snapshot, so a read-back over the snapshot+ alone reports the tree gone, `terminate_pid` drops the record and the pidfile, and the+ late child keeps its GPU memory and its port with nothing left naming it. Each+ descendant is re-collected immediately before it is killed, through the same+ creation-time validation, so the late child is reached instead.+ """+ root, child, late = 800, 801, 802+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ identities = {root: "0:800", child: "0:801", late: "0:802"}+ monkeypatch.setattr(pl, "_pid_identity", identities.get)+ snapshot_taken: "list[int]" = []++ def _collect(pid, identity = None):+ if pid == root:+ snapshot_taken.append(pid)+ # The late child does not exist yet: it is started while the root is being+ # killed, which is after this walk has already returned.+ return [(child, "0:801")], True+ if pid == child:+ # The re-collect at kill time, which is the only walk that can see it.+ return [(late, "0:802")], True+ return [], True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ dead: "set[int]" = set()+ order: "list[int]" = []++ def _kill(pid, identity = None):+ order.append(pid)+ dead.add(pid)+ return True++ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ assert pl._windows_terminate_validated_tree(root) is True+ assert late in order, "a child started after the snapshot was never signalled"+ assert order.index(late) < order.index(child), order+ assert order[0] == root, order+++def test_an_unaccounted_late_child_keeps_the_record(monkeypatch):+ """And when that re-collect cannot be done, the answer is not "the tree is gone".++ True here is what makes `terminate_pid` call `forget_pid`. A walk that failed below a+ descendant has not shown there is nothing under it, so the tree stands and the record+ that names it outlives the call.+ """+ root, child = 900, 901+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", {root: "0:900", child: "0:901"}.get)+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(child, "0:901")], True) if pid == root else ([], False),+ )+ dead: "set[int]" = set()+ monkeypatch.setattr(+ pl, "_windows_terminate_pid", lambda pid, identity = None: dead.add(pid) or True+ )+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ assert pl._windows_terminate_validated_tree(root) is False+++def test_the_fallback_signal_revalidates_the_pid(monkeypatch):+ """`taskkill` has a fifteen second ceiling, and the fallback runs when it failed.++ The caller's identity check happened before that call. The process can exit inside it --+ which is the case the fallback exists for -- and Windows hands the number on, so the+ bare `os.kill` there killed whoever holds it now. An identity that cannot be proven the+ same means no signal at all.+ """+ import subprocess as real_subprocess++ signalled: "list[int]" = []++ def _taskkill_fails(*args, **kwargs):+ raise OSError("taskkill is not on PATH")++ monkeypatch.setattr(real_subprocess, "run", _taskkill_fails)+ monkeypatch.setattr(pl.os, "kill", lambda pid, sig: signalled.append(pid))++ # Recycled while taskkill ran: the number now reads as a different process. No colon in+ # either, since on Linux `_same_identity` compares only what precedes the first one.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "999")+ assert pl._windows_terminate_pid(4242, "111") is False+ assert signalled == [], "a recycled pid was signalled by the fallback"++ # Still ours: the fallback is exactly what it was.+ assert pl._windows_terminate_pid(4242, "999") is False+ assert signalled == [4242]++ # And with nothing to check against, the fallback stands down rather than guessing.+ signalled.clear()+ assert pl._windows_terminate_pid(4242) is False+ assert signalled == []+++def test_a_number_recycled_between_the_snapshot_and_the_identity_read_is_rejected(monkeypatch):+ """The snapshot lists pids; the identity of each is read after it.++ A child that exits in between frees its number at once, and the identity then describes+ whatever took it. That replacement is newer than the parent floor, so the ancestry test+ admits it, and every later check re-verifies the stranger right up to the forced kill.+ A process created after the snapshot was taken cannot be one the snapshot listed.+ """+ root, child = 300, 301+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {root: [child]})+ # The snapshot was taken at 1000; the number was reused by a process that started at+ # 2000, which is after the reading below and therefore after the snapshot.+ monkeypatch.setattr(pl, "_windows_filetime_now", lambda: 1000)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: {root: "0:500", child: "0:2000"}.get(pid))+ monkeypatch.setattr(+ pl,+ "_windows_creation_time",+ lambda identity: (None if identity is None else int(identity.split(":")[1])),+ )++ found, known = pl._windows_collect_descendants_known(root)+ assert found == [], found+ # The entry's own process is gone, so nothing of this tree is unaccounted for.+ assert known is True++ # A child that predates the snapshot is still collected, which is every real one.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: {root: "0:500", child: "0:600"}.get(pid))+ found, known = pl._windows_collect_descendants_known(root)+ assert found == [(child, "0:600")], found+ assert known is True+++def test_a_child_of_a_late_child_is_reached_too(monkeypatch):+ """The late walk has the same problem the first snapshot had.++ Every taskkill in the loop below it spends up to fifteen seconds, so a late descendant+ has its own window in which to start a child, and that grandchild was in neither walk:+ the sweep reported nothing about it and the caller deleted the record and the pidfile+ while it held a GPU.+ """+ survivor, late, later = 400, 401, 402+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ identities = {survivor: "0:400", late: "0:401", later: "0:402"}+ monkeypatch.setattr(pl, "_pid_identity", identities.get)+ dead: "set[int]" = set()+ killed: "list[int]" = []+ walks = {"n": 0}++ def _collect(pid, identity = None):+ if pid != survivor:+ return [], True+ walks["n"] += 1+ # The grandchild only exists from the second walk on: `late` started it while the+ # first round was spending its taskkill budget.+ if walks["n"] == 1:+ return [(late, "0:401")], True+ return [(late, "0:401"), (later, "0:402")], True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ monkeypatch.setattr(+ pl,+ "_windows_terminate_pid",+ lambda pid, identity = None: (killed.append(pid), dead.add(pid), True)[-1],+ )+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ survivors = pl._windows_terminate_collected([(survivor, "0:400")])+ assert later in killed, killed+ assert killed[-1] == survivor, "the survivor must go after what is under it"+ assert survivors == [], survivors+++def test_a_subtree_that_keeps_growing_is_reported_rather_than_looped_on(monkeypatch):+ """A process that respawns faster than it can be killed is not something a loop wins.++ The rounds are bounded, and when they run out the honest answer is that whatever is+ under this survivor has not been accounted for -- which keeps the record for the next+ sweep instead of reporting the tree gone.+ """+ survivor = 500+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ spawned = {"n": 0}++ def _collect(pid, identity = None):+ if pid != survivor:+ return [], True+ spawned["n"] += 1+ fresh = 600 + spawned["n"]+ return [(fresh, f"0:{fresh}")], True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)++ survivors = pl._windows_terminate_collected([(survivor, "0:500")])+ assert spawned["n"] == pl._LATE_WALK_ROUNDS, spawned+ assert (survivor, "0:500") in survivors, survivors+++def test_a_grandchild_is_captured_before_its_parent_is_removed(monkeypatch):+ """Killing the intermediate first severs the only link to what it started.++ Windows' parent-pid field still names it, but a walk from the root has to pass THROUGH+ it, and it no longer exists -- so the grandchild is in no later snapshot either, the+ sweep reports no survivors, and the caller discards the record and the pidfile while it+ holds a GPU. The children of a process are therefore read immediately before that+ process is signalled, never after.+ """+ survivor, middle, grandchild = 1100, 1101, 1102+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"{pid}")+ dead: "set[int]" = set()+ killed: "list[int]" = []++ def _collect(pid, identity = None):+ # The root's walk names the intermediate only: the grandchild does not exist yet.+ if pid == survivor:+ return [(middle, f"{middle}")], True+ # The intermediate's own walk, taken right before it is killed, is the ONLY place+ # the grandchild can be seen -- and once the intermediate is dead the root's walk+ # cannot reach it at all.+ if pid == middle and middle not in dead:+ return [(grandchild, f"{grandchild}")], True+ return [], True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ monkeypatch.setattr(+ pl,+ "_windows_terminate_pid",+ lambda pid, identity = None: (killed.append(pid), dead.add(pid), True)[-1],+ )+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ survivors = pl._windows_terminate_collected([(survivor, f"{survivor}")])+ assert grandchild in killed, killed+ assert killed.index(grandchild) < killed.index(middle), killed+ assert killed[-1] == survivor, killed+ assert survivors == [], survivors+++def test_a_walk_that_fails_below_an_intermediate_keeps_the_record(monkeypatch):+ """The intermediate is still killed -- refusing would leave the process the sweep exists+ for running -- but a walk that could not say what is under it has not shown there is+ nothing, so the pid is reported rather than dropped."""+ survivor, middle = 1200, 1201+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"{pid}")+ dead: "set[int]" = set()+ killed: "list[int]" = []++ def _collect(pid, identity = None):+ if pid == survivor:+ return [(middle, f"{middle}")], True+ if pid == middle:+ return [], False # handle pressure, access denied: cannot tell+ return [], True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ monkeypatch.setattr(+ pl,+ "_windows_terminate_pid",+ lambda pid, identity = None: (killed.append(pid), dead.add(pid), True)[-1],+ )+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid not in dead)++ survivors = pl._windows_terminate_collected([(survivor, f"{survivor}")])+ assert middle in killed, killed+ assert (middle, f"{middle}") in survivors, survivors+++def test_a_child_born_while_the_snapshot_was_taken_is_reported_not_signalled(monkeypatch):+ """A pid created inside the snapshot window is unprovable in both directions.++ It is either a genuine child started while the table was being read, or the replacement+ for a number the table listed for a process that exited in the same window; the ceiling+ cannot separate them, because the replacement predates it too. Signalling it can hand a+ stranger to a forced tree kill. Dropping it silently reports a tree as fully enumerated+ when it may not be, which is the leak this function exists to prevent. So neither: the+ pid is skipped and the walk says it is incomplete, and the late rounds re-snapshot.+ """+ root, child = 1300, 1301+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ clock = {"now": 1000}++ def _table():+ # The child is created while the snapshot is being taken, so it is in the table and+ # its creation time is after the moment the walk started.+ clock["now"] = 2000+ return {root: [child]}++ monkeypatch.setattr(pl, "_child_pid_map", _table)+ monkeypatch.setattr(pl, "_windows_filetime_now", lambda: clock["now"])+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: {root: "0:500", child: "0:1500"}.get(pid))+ monkeypatch.setattr(+ pl,+ "_windows_creation_time",+ lambda identity: (None if identity is None else int(identity.split(":")[1])),+ )++ found, known = pl._windows_collect_descendants_known(root)+ assert found == [], found+ assert known is False++ # And a child that predates the floor is provably one the table listed, so it is+ # collected and the walk is complete: the bound narrows to the window, not to everything.+ clock["now"] = 1000+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: {root: "0:500", child: "0:900"}.get(pid))+ found, known = pl._windows_collect_descendants_known(root)+ assert found == [(child, "0:900")], found+ assert known is True+++def test_a_survivor_whose_identity_cannot_be_read_is_still_reported(monkeypatch):+ """The final pass is accounting, not a decision to signal.++ A pid that is plainly still running and whose identity cannot be read right now is proof+ of nothing, and requiring proof there dropped it from the report, so the caller deleted+ the record and the pidfile that were the only handles on a process the kill had failed to+ stop.+ """+ survivor = 1400+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ reads = {"n": 0}++ def _identity(pid):+ reads["n"] += 1+ # Readable for the check before the kill, unreadable at the final accounting.+ return "1400" if reads["n"] == 1 else None++ monkeypatch.setattr(pl, "_pid_identity", _identity)+ survivors = pl._windows_terminate_collected([(survivor, "1400")])+ assert survivors == [(survivor, "1400")], survivors+++def test_a_tree_kill_does_not_follow_the_number_to_a_stranger(monkeypatch):+ """The leader can exit, and its number be taken, after the caller validated it.++ Re-reading the identity inside the helper blesses whatever holds the number now: the+ descendant collection walks the STRANGER's tree with the stranger as its ancestry+ floor, and the root terminate confirms a handle whose identity it derived from the+ same reading. The caller's identity has to travel in, so the mismatch is visible.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ # The number now belongs to a process created later.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "900:500")+ killed: "list[int]" = []+ walked: "list[int]" = []+ alive = {500, 600}++ def _collect(pid, identity = None):+ walked.append(pid)+ return ([(600, "0:600")], True) if pid == 500 else ([], True)++ def _kill(pid, identity = None):+ killed.append(pid)+ alive.discard(pid)+ return True++ monkeypatch.setattr(pl, "_windows_collect_descendants_known", _collect)+ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)+ # False, because nothing was signalled and the record is the only handle left on+ # whatever our leader started before it exited.+ assert pl._windows_terminate_validated_tree(500, "0:500") is False+ assert killed == [], "a stranger holding a recycled number must not be signalled"+ assert walked == [], "nor may its tree be enumerated as if it were ours"++ # The same call for the process the caller actually validated still kills the tree.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid in alive)+ assert pl._windows_terminate_validated_tree(500, "0:500") is True+ assert killed == [500, 600]+++def test_the_root_is_killed_through_the_identity_the_caller_validated(monkeypatch):+ """Not one derived from the pid being acted on, which is the thing in question."""+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "0:500")+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ seen: "list[tuple[int, object]]" = []+ alive = {500}++ def _kill(pid, identity = None):+ seen.append((pid, identity))+ alive.discard(pid)+ return True++ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid in alive)+ monkeypatch.setattr(pl, "_windows_terminate_pid", _kill)+ assert pl._windows_terminate_validated_tree(500, "0:500") is True+ assert seen == [(500, "0:500")]+++def test_a_subtree_deeper_than_the_capture_depth_is_unresolved(monkeypatch):+ """Exhausting the depth is an unperformed walk, not an empty one.++ A process that starts another child after each preceding snapshot produces a chain+ longer than the recursion goes. Answering False there told the caller the anchor had+ nothing below it, so the anchor was killed -- severing the only traversable link to+ the child no walk had seen -- and the sweep went on to report success, taking the+ lifetime record and the pidfile with it.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ # Every process has exactly one child, one number higher, forever.+ monkeypatch.setattr(+ pl,+ "_windows_collect_descendants_known",+ lambda pid, identity = None: ([(pid + 1, f"0:{pid + 1}")], True),+ )+ attempted: "list[tuple[int, object]]" = []+ unresolved: "list[tuple[int, object]]" = []+ result = pl._windows_kill_below(500, attempted, unresolved, set(), 3)+ assert result is True, "the levels it did reach were killed"+ # The deepest anchor it could not walk below is carried out, not reported gone.+ assert (503, "0:503") in unresolved, unresolved++ # The depth limit itself answers None rather than "nothing below".+ assert pl._windows_kill_below(500, [], [], set(), 0) is None+++def test_the_snapshot_is_rooted_at_the_identity_the_caller_validated(monkeypatch):+ """The other half of the recycled-root guard.++ The root kill refuses a number that has moved on, but the walk below it used to read its+ own floor off the pid: rooted at the replacement, every one of the STRANGER's children is+ later than it, passes the ancestry test with a perfectly valid identity, and is handed to+ the sweep as one of ours. Nothing about the root kill's refusal reaches them.+ """+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ # The number now belongs to a process created later than ours.+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: "900:500")+ monkeypatch.setattr(+ pl, "_windows_creation_time", lambda ident: int((ident or "0:0").split(":")[0])+ )+ monkeypatch.setattr(pl, "_child_pid_map", lambda: {500: [600]})+ monkeypatch.setattr(pl, "_windows_filetime_now", lambda: 10_000)++ assert pl._windows_collect_descendants_known(500, "0:500") == ([], False)+ # And with no identity to check against, the old reading stands: this is the argument-less+ # call every other caller still makes.+ found, known = pl._windows_collect_descendants_known(500)+ assert known is True+ assert [pid for pid, _ in found] == [600]+++def test_a_survivor_with_no_readable_identity_is_not_adopted(monkeypatch):+ """`(pid, None)` out of a walk is "could not be read", not "newly spawned".++ The POSIX collector returns it for a survivor it could not classify, and capturing an+ identity at the adopt records whatever holds the number at THAT moment -- the recycled+ stranger the check exists to keep out, put into a job that kills its members when the app+ closes.+ """+ recorded = {}+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_is_windows", lambda: False)+ monkeypatch.setattr(pl, "_identity_for_record", lambda pid: "999:whoever")+ monkeypatch.setattr(pl, "_own_process_group", lambda pid: None)+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_tracked_pids", recorded)++ pl.adopt_pid(777, None, from_snapshot = True)+ assert recorded == {}, recorded++ # A child this process has just spawned is the other case, and it still captures one.+ pl.adopt_pid(777, None)+ assert recorded == {777: "999:whoever"}+++# ── the survivor read-back needs a grace period ──+#+# Every kill in this module is asynchronous. `SIGKILL` returns once the signal is queued+# and the kernel tears the process down afterwards; `TerminateProcess` is documented as+# initiating termination and returning immediately. Re-reading liveness on the line after+# either one therefore measures the read's own latency, and a process that died on the+# spot is reported as a survivor -- which keeps the lifetime record and the pidfile, so the+# next launch sweeps records naming processes that died during the previous unload.+++_SIGTERM_PROOF_TREE = textwrap.dedent(+ """+ import pathlib, subprocess, sys, time+ kid = (+ "import signal, time;"+ "signal.signal(signal.SIGTERM, signal.SIG_IGN);"+ "time.sleep(300)"+ )+ kids = [subprocess.Popen([sys.executable, "-c", kid]) for _ in range(int(sys.argv[2]))]+ pathlib.Path(sys.argv[1]).write_text(",".join(str(k.pid) for k in kids))+ time.sleep(300)+ """+)+++def stubborn_tree(tmp_path):+ """(leader, [child pids]) where every child ignores SIGTERM and dies on SIGKILL.++ The shape the sweep is written for: the escalation is what kills these, so the+ read-back runs immediately after a SIGKILL rather than after a polite exit.+ """+ marker = tmp_path / "kids.pid"+ leader = subprocess.Popen([sys.executable, "-c", _SIGTERM_PROOF_TREE, str(marker), "4"])+ kids: "list[int]" = []+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ try:+ kids = [int(x) for x in marker.read_text().split(",") if x]+ except (OSError, ValueError):+ kids = []+ if len(kids) == 4:+ break+ time.sleep(0.05)+ if len(kids) != 4:+ leader.kill()+ pytest.fail("the spawned children never recorded their pids")+ try:+ yield leader, kids+ finally:+ for pid in kids:+ _hard_kill(pid)+ try:+ leader.kill()+ leader.wait(timeout = 10)+ except Exception:+ pass++[email protected](IS_WINDOWS, reason = "POSIX signals; the Windows arm is faked below")+def test_a_descendant_that_died_on_the_kill_is_not_reported_as_a_survivor(stubborn_tree):+ """The read-back used to answer "still there" for four processes it had just killed.++ Measured on this host with eight of them: eight reported, none alive half a second+ later. The cost is not the wasted adopt; it is that a reported survivor KEEPS the+ record and the pidfile, so the next launch runs a reap sweep over ghosts.+ """+ leader, kids = stubborn_tree+ collected, known = pl.collect_descendants_known(leader.pid)+ assert known, "the walk itself failed, so this test proves nothing"+ assert sorted(pid for pid, _ in collected) == sorted(kids)++ survivors = pl.terminate_descendants(collected, timeout = 1.0)++ assert survivors == [], f"reported {survivors} as still running"+ for pid in kids:+ assert not _alive(pid), f"{pid} was reported gone and is not"++[email protected](IS_WINDOWS, reason = "POSIX signals; the Windows arm is faked below")+def test_a_descendant_that_refuses_to_die_is_still_reported(stubborn_tree):+ """The other half. A grace period that swallowed a real survivor would be worse than+ the immediate read it replaces: the record and the pidfile are the only handles left on+ a worker still holding a GPU, and this return value is what keeps them.++ Only the one pid's signals are blocked; the other three are killed for real, so this+ also pins that the sweep separates the two in one pass.+ """+ leader, kids = stubborn_tree+ victim = kids[0]++ collected, known = pl.collect_descendants_known(leader.pid)+ assert known+ with _signals_that_never_land([victim]):+ started = time.monotonic()+ survivors = pl.terminate_descendants(collected, timeout = 1.0)+ elapsed = time.monotonic() - started++ assert [pid for pid, _ in survivors] == [victim], survivors+ assert _alive(victim), "the fake did not hold; the victim really died"+ # Bounded, not waited out: the SIGTERM timeout plus one grace period, not a loop+ # that runs until the process gives up. This sits on the teardown path.+ assert elapsed < 1.0 + pl._KILL_SETTLE_SECONDS + 3.0, elapsed++[email protected](IS_WINDOWS, reason = "kills a real process and reads it back")+def test_confirming_an_exit_waits_for_the_kill_to_land():+ victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"])+ try:+ os.kill(victim.pid, signal.SIGKILL)+ # On the next line, which is the whole point: the process is still signalable for+ # as long as the kernel takes to tear it down.+ assert pl.confirm_pid_exited(victim.pid) is True+ finally:+ _hard_kill(victim.pid)+ try:+ victim.wait(timeout = 10)+ except Exception:+ pass+++def test_confirming_an_exit_gives_up_on_a_process_that_stays(monkeypatch):+ monkeypatch.setattr(pl, "pid_is_running", lambda pid: True)+ started = time.monotonic()+ assert pl.confirm_pid_exited(4242) is False+ elapsed = time.monotonic() - started+ assert pl._KILL_SETTLE_SECONDS <= elapsed < pl._KILL_SETTLE_SECONDS + 3.0, elapsed+++def test_confirming_an_exit_polls_rather_than_reading_once(monkeypatch):+ """The deterministic half of the test above it. A single read, at any point inside the+ window the kill takes to land, answers "still running"."""+ reads = {"n": 0}++ def _running(pid):+ reads["n"] += 1+ return reads["n"] <= 3++ monkeypatch.setattr(pl, "pid_is_running", _running)+ assert pl.confirm_pid_exited(4242) is True+ assert reads["n"] > 1, "read once, which is the defect"++[email protected]("pid", [None, 0, 1])+def test_confirming_an_exit_never_probes_a_reserved_pid(monkeypatch, pid):+ """And answers False, not True. This return value authorises deleting the record and+ the pidfile, so "this module will not touch that pid" must not read as "it is gone"."""+ probed = []+ monkeypatch.setattr(pl, "pid_is_running", lambda p: probed.append(p) or True)+ assert pl.confirm_pid_exited(pid) is False+ assert probed == []+++def test_a_probe_that_lies_once_does_not_lose_a_live_worker(monkeypatch):+ """`_pid_alive` fails OPEN on Windows: out of handles, out of memory, or any ctypes+ failure all read as "gone". Polling a fail-open probe fifty times and dropping a pid on+ the first "gone" would multiply the chance of deleting the record and the pidfile for a+ process the kill did not stop, which is the one direction this module refuses to fail+ in. Agreements have to be consecutive for that reason.+ """+ reads = {"n": 0}++ def _alive_except_once(pid, identity):+ reads["n"] += 1+ return reads["n"] != 2 # the second read lies++ survivors = pl._survivors_after_settling([(700, "0:700")], _alive_except_once)+ assert survivors == [(700, "0:700")], "a live worker was dropped on one bad read"+++def test_the_settled_report_keeps_the_callers_order(monkeypatch):+ """Deepest first, which is what the Windows sweep hands out and what the caller adopts+ in turn. The middle one goes; the two around it must not swap."""+ gone = {601}+ survivors = pl._survivors_after_settling(+ [(602, "0:602"), (601, "0:601"), (600, "0:600")],+ lambda pid, _identity: pid not in gone,+ )+ assert survivors == [(602, "0:602"), (600, "0:600")]+++def _terminate_then_linger(monkeypatch, reads_after_the_kill = 3):+ """Fake Windows where `TerminateProcess` returns before the process is gone.++ Returns the list the kills are recorded in. Everything stays visible until the kill,+ then for `reads_after_the_kill` more liveness reads, then goes.+ """+ killed: "list[int]" = []+ reads: "dict[int, int]" = {}++ def _pid_alive(pid):+ if pid not in killed:+ return True+ reads[pid] = reads.get(pid, 0) + 1+ return reads[pid] <= reads_after_the_kill++ def _terminate(pid, identity = None):+ killed.append(pid)+ return True++ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_pid_alive", _pid_alive)+ monkeypatch.setattr(pl, "_windows_terminate_pid", _terminate)+ return killed+++def test_the_validated_tree_kill_gives_the_terminate_time_to_land(monkeypatch):+ """The ordinary Windows unload: a leader with nothing under it.++ `_windows_terminate_pid` is `TerminateProcess` through a handle, which returns in+ microseconds, so the read-back on the next line saw the leader still open and answered+ "the tree stands". False here keeps the record and the pidfile for a process that was+ already dying.+ """+ killed = _terminate_then_linger(monkeypatch)+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ assert pl._windows_terminate_validated_tree(500, "0:500") is True+ assert killed == [500]+++def test_the_validated_tree_kill_still_reports_a_root_it_could_not_stop(monkeypatch):+ """A leader that is genuinely stuck is still a survivor, and the wait is bounded."""+ monkeypatch.setattr(pl, "_is_windows", lambda: True)+ monkeypatch.setattr(pl, "_is_linux", lambda: False)+ monkeypatch.setattr(pl, "_signalable", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True)+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)+ monkeypatch.setattr(pl, "_pid_identity", lambda pid: f"0:{pid}")+ monkeypatch.setattr(pl, "_windows_terminate_pid", lambda pid, identity = None: True)+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ started = time.monotonic()+ assert pl._windows_terminate_validated_tree(500, "0:500") is False+ assert time.monotonic() - started < pl._KILL_SETTLE_SECONDS + 3.0+++def test_the_windows_sweep_separates_a_dying_descendant_from_a_stuck_one(monkeypatch):+ """Same read-back, the descendant side of it. One of these died on the kill and the+ other did not, and an immediate read cannot tell them apart."""+ killed = _terminate_then_linger(monkeypatch)+ real_alive = pl._pid_alive+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: True if pid == 601 else real_alive(pid))+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ survivors = pl._windows_terminate_collected([(600, "0:600"), (601, "0:601")])+ assert sorted(killed) == [600, 601]+ assert survivors == [(601, "0:601")], survivors+++def test_a_windows_shutdown_does_not_report_a_leader_that_is_merely_dying(monkeypatch):+ """The windows-latest staging failure this read-back caused, reproduced.++ `test_a_confirmed_shutdown_still_clears_the_record` failed there with+ `assert [8792] == []`: `terminate_all` terminated a child that exited on the spot and+ then read the pid back one line later, so `_windows_terminate_validated_tree` answered+ False, the pid came out as a survivor and the record it names was written straight back.+ `main` cannot fail that way because `_windows_terminate_tree` there reports the tree+ gone on taskkill's exit code alone and never re-reads anything.+ """+ _terminate_then_linger(monkeypatch)+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ monkeypatch.setattr(pl, "_group_has_members", lambda pgid: False)+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)+ monkeypatch.setattr(pl, "_tracked_pids", {500: "0:500"})+ monkeypatch.setattr(pl, "_tracked_pgids", {})++ assert pl.terminate_all(timeout = 3.0) == []+ assert pl._tracked_pids == {}, "the record was written back for a process that is gone"++[email protected](IS_WINDOWS, reason = "POSIX signals; the Windows arm is above")+def test_a_posix_shutdown_does_not_report_a_child_that_is_merely_dying(monkeypatch, tmp_path):+ """The same defect on the POSIX shutdown path, with a real process.++ `_posix_terminate_one` ends on killpg(SIGKILL) and returns, and `terminate_all` reads+ liveness on the line after it: measured here, it reported a survivor and wrote the+ record straight back for a child that was gone half a second later. Settling inside+ `_posix_terminate_one` covers `terminate_all`, `terminate_pid` and `_reap_one_record`+ at once, since all three read back immediately after it.++ A child that ignores SIGTERM is the point: one that exits politely returns from the+ poll loop above the SIGKILL and never reaches the line this is about.+ """+ monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(tmp_path / "children"))+ monkeypatch.setattr(pl, "_tracked_pids", {})+ monkeypatch.setattr(pl, "_tracked_pgids", {})+ child = subprocess.Popen(+ [+ sys.executable,+ "-c",+ "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(300)",+ ],+ start_new_session = True,+ )+ try:+ pl.adopt_pid(child.pid)+ assert pl._tracked_pids.get(child.pid) is not None++ survivors = pl.terminate_all(timeout = 1.0)++ assert survivors == [], f"reported {survivors} as still running"+ assert pl._tracked_pids == {}, "the record was written back for a process that is gone"+ assert child.wait(timeout = 10) is not None+ finally:+ _hard_kill(child.pid)+ try:+ child.wait(timeout = 10)+ except Exception:+ pass+++def test_a_windows_startup_sweep_consumes_the_record_it_has_emptied(monkeypatch, tmp_path):+ """The second windows-latest staging failure, reproduced.++ `test_macos_style_orphans_are_recorded_and_reaped` failed there on "the record should+ be consumed". `_reap_one_record` kills a recorded child and then asks whether it is+ still there, and the answer it got was the terminate's latency rather than the+ outcome: the record was marked unresolved and left on disk, so every later launch+ re-reads it and re-sweeps a process that died during the first one.+ """+ import json++ _terminate_then_linger(monkeypatch)+ monkeypatch.setattr(+ pl, "_windows_collect_descendants_known", lambda pid, identity = None: ([], True)+ )+ monkeypatch.setattr(pl, "_group_has_members", lambda pgid: False)+ record = tmp_path / "4321.json"+ record.write_text(+ json.dumps(+ {+ "owner_pid": 4321,+ "owner_identity": "a-previous-studio-that-is-gone",+ "children": [{"pid": 500, "identity": "0:500"}],+ }+ )+ )++ killed, deferred = pl._reap_one_record(record, timeout = 3.0)++ assert killed == [500]+ assert deferred is False+ assert not record.exists(), "the record should be consumed"+++# ── the teardown lock is not held across a kill killpg already did ──++[email protected](IS_WINDOWS, reason = "no killpg here, so the branch below is POSIX-only")+def test_a_killed_process_group_makes_the_tree_kill_unnecessary(monkeypatch):+ """`_kill_process_group` sends killpg SIGKILL to this exact tree eleven lines earlier.++ `terminate_pid`'s POSIX arm is killpg SIGTERM, a poll loop and killpg SIGKILL over the+ same group, so on POSIX with a real group it buys no reach and costs a /proc walk plus+ up to five more seconds with `_teardown_lock` held.+ """+ from core.inference.llama_cpp import LlamaCppBackend++ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = None+ b._leading_process_group = lambda pid: pid # POSIX, and the server leads its own group+ cleared, killed = _instrument(monkeypatch, gone = False)+ confirmed = []+ monkeypatch.setattr(+ LlamaCppBackend,+ "_confirm_group_kill_landed",+ staticmethod(lambda pid: bool(confirmed.append(pid)) or True),+ )++ b._kill_process()++ assert killed == [], "killpg already covered this tree"+ assert confirmed == [4242], "the exit still has to be confirmed, just not re-killed"+ assert cleared == [1]+++def test_without_a_process_group_the_tree_kill_still_runs(monkeypatch):+ """Windows, where `_leading_process_group` always answers None. taskkill is the only+ reach left there and this PR exists to use it, so nothing about that path moves."""+ from core.inference.llama_cpp import LlamaCppBackend++ b = _make_backend() # _leading_process_group already answers None+ b._process.pid = 4242+ b._process.poll.return_value = None+ cleared, killed = _instrument(monkeypatch, gone = False)+ confirmed = []+ monkeypatch.setattr(+ LlamaCppBackend,+ "_confirm_group_kill_landed",+ staticmethod(lambda pid: bool(confirmed.append(pid)) or True),+ )++ b._kill_process()++ assert killed == [4242]+ assert confirmed == []+ assert cleared == [], "dropped the pidfile while the server was still running"++[email protected](IS_WINDOWS, reason = "deletes os.killpg, which is not here to delete")+def test_a_process_group_with_no_killpg_still_tree_kills(monkeypatch):+ """The second half of the condition. `_kill_process_group` is a no-op when `os.killpg`+ is missing, so a pgid on its own is not evidence that anything was signalled, and+ skipping the tree kill on it would skip a kill that never happened."""+ import core.inference.llama_cpp as lc+ from core.inference.llama_cpp import LlamaCppBackend++ b = _make_backend()+ b._process.pid = 4242+ b._process.poll.return_value = None+ b._leading_process_group = lambda pid: pid+ monkeypatch.delattr(lc.os, "killpg", raising = False)+ cleared, killed = _instrument(monkeypatch, gone = True)+ confirmed = []+ monkeypatch.setattr(+ LlamaCppBackend,+ "_confirm_group_kill_landed",+ staticmethod(lambda pid: bool(confirmed.append(pid)) or True),+ )++ b._kill_process()++ assert killed == [4242]+ assert confirmed == []+++def test_confirming_a_group_kill_signals_nothing(monkeypatch):+ """It answers a question. The kill already happened, and sending another one from here+ is the cost this replaced.++ Against the signal calls themselves, not just against `terminate_pid`: asserting that+ one helper is not called proves nothing about a helper that never referenced it.+ """+ from core.inference.llama_cpp import LlamaCppBackend++ signalled: "list[tuple[str, int, int]]" = []+ monkeypatch.setattr(pl.os, "kill", lambda pid, sig, *a: signalled.append(("kill", pid, sig)))+ if hasattr(pl.os, "killpg"):+ monkeypatch.setattr(+ pl.os, "killpg", lambda pgid, sig: signalled.append(("killpg", pgid, sig))+ )+ monkeypatch.setattr(+ pl, "terminate_pid", lambda pid, **kw: signalled.append(("terminate_pid", pid, 0))+ )+ monkeypatch.setattr(+ pl,+ "_windows_terminate_pid",+ lambda pid, identity = None: signalled.append(("taskkill", pid, 0)),+ )++ monkeypatch.setattr(pl, "pid_is_running", lambda pid: False)+ assert LlamaCppBackend._confirm_group_kill_landed(4242) is True+ assert signalled == []++ monkeypatch.setattr(pl, "pid_is_running", lambda pid: True)+ assert LlamaCppBackend._confirm_group_kill_landed(4242) is False+ assert signalled == []++[email protected]("pid", [None, 0, 1])+def test_confirming_a_group_kill_never_probes_a_reserved_pid(monkeypatch, pid):+ from core.inference.llama_cpp import LlamaCppBackend++ probed = []+ monkeypatch.setattr(pl, "pid_is_running", lambda p: probed.append(p) or True)+ assert LlamaCppBackend._confirm_group_kill_landed(pid) is False+ assert probed == []diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.pyindex 7aaf9071125..13af06ddfa2 100644--- a/studio/backend/utils/process_lifetime.py+++ b/studio/backend/utils/process_lifetime.py@@ -607,6 +607,209 @@ def _group_has_members(pgid: object) -> bool:return any(not _pid_is_zombie(pid) for pid in members)+def _windows_creation_time(identity: "Optional[str]") -> "Optional[int]":+ """A Windows identity string read back as one 64-bit FILETIME, or None.++ `_pid_identity` writes the creation time as ``high:low`` there, and the+ descendant walk has to order two of them, not just compare them for equality.+ """+ if not isinstance(identity, str):+ return None+ parts = identity.split(":")+ if len(parts) != 2:+ return None+ try:+ return (int(parts[0]) << 32) | int(parts[1])+ except ValueError:+ return None+++def _windows_identity_of_handle(kernel32, handle) -> "Optional[str]":+ """The creation-time identity of the process an OPEN HANDLE refers to, or None.++ A handle pins the process it was opened on: the kernel keeps the object alive while the+ handle is held, and the pid can be recycled without the handle ever following it. So a+ check made through the handle answers about the same process every later call on that+ handle acts upon, which a check made on the pid does not -- between a pid-based check+ and the `OpenProcess` that follows it, the process can exit and its number be taken by+ a stranger, and the handle then refers to the stranger.++ Written in the same ``high:low`` spelling as `_pid_identity`, so the two are directly+ comparable. None when the times cannot be read, which the caller must treat as "not+ proven", never as a match.+ """+ try:+ import ctypes+ from ctypes import wintypes++ kernel32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [+ ctypes.POINTER(wintypes.FILETIME)+ ] * 4+ kernel32.GetProcessTimes.restype = wintypes.BOOL+ created = wintypes.FILETIME()+ other = [wintypes.FILETIME() for _ in range(3)]+ if not kernel32.GetProcessTimes(+ handle, ctypes.byref(created), *[ctypes.byref(x) for x in other]+ ):+ return None+ return f"{created.dwHighDateTime}:{created.dwLowDateTime}"+ except Exception: # noqa: BLE001 -- unreadable is "not proven", handled by the caller+ return None+++def _windows_terminate_through_a_handle(pid: int, identity: "Optional[str]") -> "Optional[bool]":+ """Kill *pid* through a handle that was proved to be the right process, or say why not.++ ``True`` the process was signalled, ``False`` the handle is provably somebody else (or+ cannot be identified while an identity was supplied), ``None`` no handle could be had at+ all and the caller has to fall back.++ A pid is a NAME, and Windows frees it the moment the process exits; ``taskkill /PID`` and+ ``os.kill`` both resolve that name inside themselves, so anything they are told is+ re-looked-up after the caller's check and can land on a replacement. A handle is the+ process, not its name: once opened it refers to the same object until it is closed, so a+ creation time read through it describes exactly what ``TerminateProcess`` on it will end.++ Nothing is killed without proof. No identity to compare against means this stands down+ and lets the caller decide, because the alternative is signalling a number.+ """+ if identity is None:+ return None+ try:+ import ctypes+ from ctypes import wintypes++ PROCESS_TERMINATE = 0x0001+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]+ kernel32.TerminateProcess.restype = wintypes.BOOL+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ handle = kernel32.OpenProcess(+ PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, False, pid+ )+ if not handle:+ # Gone, protected, or denied. All three are "this cannot answer", not "this is+ # the wrong process", so the caller keeps its own ladder.+ return None+ try:+ opened = _windows_identity_of_handle(kernel32, handle)+ if opened is None or opened != identity:+ # Either the number now belongs to something else, or it cannot be shown to+ # belong to the recorded process. Neither is a licence to kill.+ return False+ return bool(kernel32.TerminateProcess(handle, 1))+ finally:+ kernel32.CloseHandle(handle)+ except Exception: # noqa: BLE001 -- no ctypes, no kernel32: the caller falls back+ return None+++def _windows_filetime_now() -> "Optional[int]":+ """The wall clock as one 64-bit FILETIME, comparable with a process creation time.++ `GetProcessTimes` reports creation as a UTC FILETIME and `GetSystemTimeAsFileTime`+ reads the same clock, so a candidate whose creation time is LATER than a reading taken+ before a snapshot cannot be a process that snapshot listed. That is the only way to+ reject a number recycled between the snapshot and the identity read, where the identity+ describes the replacement rather than the entry. None when it cannot be read, which+ leaves the walk exactly as it was.+ """+ if not _is_windows():+ return None+ try:+ import ctypes+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.GetSystemTimeAsFileTime.argtypes = [ctypes.POINTER(wintypes.FILETIME)]+ kernel32.GetSystemTimeAsFileTime.restype = None+ stamp = wintypes.FILETIME()+ kernel32.GetSystemTimeAsFileTime(ctypes.byref(stamp))+ return (int(stamp.dwHighDateTime) << 32) | int(stamp.dwLowDateTime)+ except Exception: # noqa: BLE001 -- cannot tell; the walk keeps its old behaviour+ return None+++def _windows_child_pid_map() -> "Optional[dict[int, list[int]]]":+ """Parent pid -> its children, from a Toolhelp snapshot. None when unreadable.++ ctypes rather than psutil, and a snapshot rather than a `wmic` or PowerShell+ child, for the same reason as the rest of this module: this runs on the unload+ and shutdown paths, psutil is an optional extra here, and spawning a helper is+ the thing being cleaned up after.+ """+ try:+ import ctypes+ from ctypes import wintypes++ TH32CS_SNAPPROCESS = 0x0000_0002+ MAX_PATH = 260++ class PROCESSENTRY32W(ctypes.Structure):+ _fields_ = [+ ("dwSize", wintypes.DWORD),+ ("cntUsage", wintypes.DWORD),+ ("th32ProcessID", wintypes.DWORD),+ ("th32DefaultHeapID", ctypes.c_size_t),+ ("th32ModuleID", wintypes.DWORD),+ ("cntThreads", wintypes.DWORD),+ ("th32ParentProcessID", wintypes.DWORD),+ ("pcPriClassBase", ctypes.c_long),+ ("dwFlags", wintypes.DWORD),+ ("szExeFile", wintypes.WCHAR * MAX_PATH),+ ]++ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)+ kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]+ kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE+ kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]+ kernel32.Process32FirstW.restype = wintypes.BOOL+ kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]+ kernel32.Process32NextW.restype = wintypes.BOOL+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL++ snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)+ # INVALID_HANDLE_VALUE is -1, which arrives here as a large unsigned HANDLE, so+ # falsiness alone does not catch a snapshot that could not be taken.+ if not snapshot or snapshot == ctypes.c_void_p(-1).value:+ return None+ try:+ entry = PROCESSENTRY32W()+ entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)+ if not kernel32.Process32FirstW(snapshot, ctypes.byref(entry)):+ # An empty walk is a failed read, not a machine with no processes, and+ # reporting it as a table would read as "this child has none".+ return None+ ERROR_NO_MORE_FILES = 18+ table: "dict[int, list[int]]" = {}+ while True:+ child = int(entry.th32ProcessID)+ parent = int(entry.th32ParentProcessID)+ if child:+ table.setdefault(parent, []).append(child)+ if not kernel32.Process32NextW(snapshot, ctypes.byref(entry)):+ # FALSE is not "that was the last one". It is also every way the walk+ # can fail partway, and only ERROR_NO_MORE_FILES says the list ended.+ # Treating a termination error as the end returns a table missing+ # whatever came after it, and a table is read as an ANSWER: the unload+ # then finds no survivors and deletes the record and the pidfile for+ # workers the walk never reached. The Windows scanner in+ # studio/src-tauri/src/process.rs already makes this distinction.+ if ctypes.get_last_error() != ERROR_NO_MORE_FILES:+ return None+ break+ return table+ finally:+ kernel32.CloseHandle(snapshot)+ except Exception:+ return None++def _child_pid_map() -> "Optional[dict[int, list[int]]]":"""Parent pid -> its children, or None when the table cannot be read."""if _is_linux():@@ -654,45 +857,364 @@ def _child_pid_map() -> "Optional[dict[int, list[int]]]":return tableexcept Exception:return None+ if _is_windows():+ return _windows_child_pid_map()return None+def collect_descendants_known(+ pid: "Optional[int]",+) -> "tuple[list[tuple[int, Optional[str]]], bool]":+ """`(descendants, known)`, where `known` is False when the walk could not be made.++ An empty list has two very different meanings and collapsing them is a leak.+ `_windows_child_pid_map` returns None when the Toolhelp snapshot cannot be taken or+ the walk fails partway, and the root's own identity can be unreadable too; either way+ the answer is "this process's children are not enumerable right now", not "it has+ none". Read as "none", the unload terminates the leader, sees no survivors, and+ deletes the record and the pidfile -- which is the exact leak this collector exists to+ prevent, arrived at through a failed snapshot instead of through a reparent.++ `collect_descendants` keeps returning the list alone, because the callers that only+ want something to signal are right not to care. The unload does care: it is about to+ drop the last handle on whatever it did not see.+ """+ if not pid:+ # Not a question about a process, so there is nothing indeterminate about it.+ return [], True+ # Windows records the creating pid on a process and never clears it, not even when+ # that parent exits and its number is handed to something else, so the raw table+ # lists strangers created by an earlier holder of this pid as children of it. A real+ # descendant cannot predate the process that created it, so each candidate is+ # ordered against ITS OWN immediate parent, not only against the root.+ #+ # The root floor alone is not enough, and the difference is a real machine:+ # the root starts at t=100, a stranger U starts at t=200 under some unrelated+ # pid P, P exits, at t=300 P's number is reused for a genuine Unsloth child, and+ # U still records P as its creator. U is later than the root, so a root-only floor+ # admits it and taskkill /T /F reaches U and everything under it. Ordering U+ # against P's CURRENT creation time (300) rejects it, because a child cannot+ # predate its parent. Each step of the walk carries the parent's own creation+ # time down, so the check holds at every depth rather than only at the first.+ #+ # Without a readable floor this claims nothing at all, and an unreadable candidate+ # is skipped rather than assumed to be ours: a tree kill is not a place to guess.+ if _is_windows():+ return _windows_collect_descendants_known(pid)+ # The POSIX walk, unchanged: /proc and the BSD table record a parent link the kernel+ # rewrites on reparent, so there is no stale creator to order against and no floor to+ # carry. Kept as its own loop rather than a flag inside the Windows one so this path+ # allocates exactly what it allocated before; a queue of tuples measured 57 us -> 112 us+ # per unload on a 200 process table for a check POSIX does not use.+ table = _child_pid_map()+ if not table:+ return [], False+ found: "list[tuple[int, Optional[str]]]" = []+ seen = {pid}+ queue = list(table.get(pid, ()))+ while queue:+ child = queue.pop(0)+ if child in seen:+ continue+ seen.add(child)+ found.append((child, _pid_identity(child)))+ queue.extend(table.get(child, ()))+ return found, True++def collect_descendants(pid: "Optional[int]") -> "list[tuple[int, Optional[str]]]":"""A pid's descendants and their start-time identities.Read this BEFORE signalling the parent: its children are reparented themoment it exits, and nothing then ties them back to it. The identities letthe kill below skip a number that has since moved on to something else.++ See `collect_descendants_known` for the caller that also needs to know whether the+ walk could be made at all."""- if not pid or _is_windows():- return []+ return collect_descendants_known(pid)[0]+++def _windows_collect_descendants(pid: int) -> "list[tuple[int, Optional[str]]]":+ """The list alone. See `_windows_collect_descendants_known`."""+ return _windows_collect_descendants_known(pid)[0]+++def _windows_collect_descendants_known(+ pid: int, identity: "Optional[str]" = None+) -> "tuple[list[tuple[int, Optional[str]]], bool]":+ """`collect_descendants` for the Toolhelp table, which needs an ancestry proof.++ Each candidate is ordered against ITS OWN immediate parent's creation time, carried+ down the walk, not only against the root's. The root floor alone is not enough and the+ difference is a real machine: the root starts at t=100, a stranger U starts at t=200+ under some unrelated pid P, P exits, at t=300 P's number is reused for a genuine+ Unsloth child, and U still records P as its creator because Windows never clears that+ field. U is later than the root, so a root-only floor admits it, and the survivor sweep+ then hands it to ``taskkill /PID <U> /T /F``, which takes down U and everything under+ it. Ordering U against P's CURRENT creation time rejects it: a process cannot predate+ the process that created it.++ Without a readable floor this claims nothing at all, and a candidate whose own identity+ cannot be read is skipped along with its subtree: a forced tree kill is not a place to+ guess. Skipping it also makes the walk INCOMPLETE, and says so. A live pid the table+ listed and this could not classify is a candidate, not an absence: reporting the walk as+ complete without it let the caller terminate the leader, see no survivors and delete the+ record and the pidfile while that child was still running. Not signalled either way --+ unknown is not a licence to kill -- but never silently dropped.+ """+ # The caller's identity when it has one, never a fresh read of the number. The root can+ # exit and its pid be reused between the caller's own check and this line, and reading the+ # floor off the replacement roots the whole walk at a STRANGER: its children are all later+ # than it, they pass the ancestry test with identities that are perfectly valid, and the+ # sweep goes on to terminate them as if they were ours. The root kill itself is protected+ # by the identity it was given; this is the other half of the same guard.+ if identity is not None and not _provably_the_same(pid, identity):+ return [], False+ root_floor = _windows_creation_time(identity if identity is not None else _pid_identity(pid))+ if root_floor is None:+ # No floor means no ancestry proof for anything, so this claims nothing at all --+ # and "nothing" here is indeterminate, not empty.+ return [], False+ # Read BEFORE the snapshot, and used as a floor on the snapshot itself. Anything the+ # table lists whose creation time is past this moment came into existence while the+ # table was being read, and there is no way to tell which one it is: a genuine child+ # started in that window, or a number the snapshot listed for a process that exited+ # inside the same window and had its number reused. The ceiling below cannot separate+ # them either, because the replacement is created before it. So the pid is not admitted+ # -- a forced sweep is not a place to guess about a number that may belong to a stranger+ # -- and it is not silently dropped either: the walk says it is INCOMPLETE, which is the+ # signal the caller already has for "there may be more than this", and the late-walk+ # rounds re-snapshot with a fresh window and pick up a genuine child then.+ snapshot_floor = _windows_filetime_now()table = _child_pid_map()+ # Read AFTER the snapshot, and used as a ceiling. The identity of each candidate is read+ # after the table, and a child that exits in between frees its number immediately: the+ # identity then describes whatever took it, which -- being newer than the parent floor --+ # the ancestry test admits, and every later check happily re-verifies that stranger right+ # up to the forced kill. A process created after the snapshot cannot be one the snapshot+ # listed, so that is the test.+ #+ # After, not before. A ceiling taken first is earlier than the snapshot, and a genuine+ # child born in the gap is then IN the table with a creation time past the ceiling: it+ # would be rejected as a recycled number while the walk still reported itself complete,+ # which is the leak this whole function exists to prevent. Taken afterwards the ceiling+ # can only be later than the snapshot, so it never rejects anything the snapshot really+ # held; it merely admits a replacement that appeared inside that same gap, which is the+ # old behaviour and not a regression.+ snapshot_ceiling = _windows_filetime_now()if not table:- return []+ return [], Falsefound: "list[tuple[int, Optional[str]]]" = []+ complete = Trueseen = {pid}- queue = list(table.get(pid, ()))+ # (candidate pid, creation time of the parent that listed it)+ queue: "list[tuple[int, int]]" = [(child, root_floor) for child in table.get(pid, ())]while queue:- child = queue.pop(0)+ child, parent_created = queue.pop(0)if child in seen:continueseen.add(child)- found.append((child, _pid_identity(child)))- queue.extend(table.get(child, ()))- return found+ identity = _pid_identity(child)+ created = _windows_creation_time(identity)+ if created is None:+ # Unreadable, not absent. A pid that is plainly still running and cannot be+ # classified leaves this walk unable to say the tree is fully enumerated; one+ # that has already gone says nothing about completeness.+ if _pid_alive(child) and not _pid_is_zombie(child):+ complete = False+ continue+ if created < parent_created:+ # Provably not a descendant: it predates the process that lists it as its+ # creator, which is the recycled-number case this floor exists for. Rejecting+ # it is an ANSWER, so the walk stays complete.+ continue+ if snapshot_ceiling is not None and created > snapshot_ceiling:+ # Provably not the process the snapshot listed: it did not exist when the+ # snapshot was taken. The entry's own process has therefore exited and its+ # number been reused, so nothing of this tree is lost and the walk stays+ # complete -- the subtree under a stranger is the stranger's, not ours.+ continue+ if snapshot_floor is not None and created > snapshot_floor:+ # Created while the table was being read, so it is either a genuine child born+ # in that window or the replacement for a number the table listed. Unprovable+ # either way, so it is skipped and the walk reports itself incomplete rather+ # than handing a possible stranger to `taskkill /T /F`.+ complete = False+ continue+ found.append((child, identity))+ queue.extend((grandchild, created) for grandchild in table.get(child, ()))+ return found, complete+++# How long a read-back gives a kill to actually land before it calls a pid a survivor, and+# how often it looks while it waits.+#+# Neither kill on either platform is synchronous. `SIGKILL` returns as soon as the signal+# is queued, and the process is torn down afterwards -- it stays visible to `kill(pid, 0)`+# until the kernel finishes, and then keeps its number as a zombie until its parent reaps+# it. `TerminateProcess` is documented as asynchronous in exactly the same way: it+# initiates termination and returns immediately, and the process object stays signalable+# until the last thread is gone. A liveness read on the line after the kill therefore+# measures the read's own latency, not the outcome.+#+# Measured here with eight descendants that ignore SIGTERM and die instantly on SIGKILL:+# every one of the eight came back as a survivor, and none of the eight was still alive+# half a second later. What that costs is not the wasted `adopt_pid` calls. A reported+# survivor KEEPS the lifetime record and the pidfile, so the next launch runs a reap sweep+# over records naming processes that died during the previous unload -- on Windows, one+# Toolhelp snapshot per record plus a taskkill each, at startup, forever.+#+# Short on purpose: this sits on the teardown path, and the loop leaves the moment the+# list empties, so a tree that is genuinely gone pays two reads and a tree that is+# genuinely stuck pays the half second once.+_KILL_SETTLE_SECONDS = 0.5+_KILL_SETTLE_POLL_SECONDS = 0.01++# How many passes in a row have to agree a pid is gone before it is dropped from the+# report, and how fast the wait between passes grows.+#+# Two, not one, because the liveness probe FAILS OPEN on Windows: `_pid_alive` reads any+# `OpenProcess` failure other than ACCESS_DENIED -- out of handles, out of memory -- and+# any ctypes failure as "gone". A single read has always been able to lie in that+# direction; polling would multiply the chance of it by the number of passes, and one lie+# drops a pid that a kill did NOT stop, which is the direction the rest of this module+# refuses to fail in (it costs the record and the pidfile that are the only handles on a+# worker still holding the GPU). Requiring two consecutive agreements makes a wrong drop+# need two consecutive lies, so the polling is strictly SAFER here than the single read it+# replaces, not just faster to be right.+#+# The backoff is for the same predicate's cost rather than its truthfulness: off Linux and+# Windows `_pid_is_zombie` and `_pid_identity` each fork `ps`, so a flat 10 ms tick would+# spend the grace forking a hundred times for one stuck pid. Doubling reaches the deadline+# in about six passes while still taking the second read 10 ms in, which is what the+# already-dead path actually waits for.+_KILL_SETTLE_CONFIRMATIONS = 2+_KILL_SETTLE_POLL_CEILING_SECONDS = 0.1+++def _survivors_after_settling(+ candidates: "list[tuple[int, Optional[str]]]",+ still_a_survivor: "Callable[[int, Optional[str]], bool]",+ grace: float = _KILL_SETTLE_SECONDS,+) -> "list[tuple[int, Optional[str]]]":+ """Which of *candidates* are still survivors once the kills have had *grace* to land.++ Polled rather than read once, and bounded rather than waited out: a pid drops out once+ `_KILL_SETTLE_CONFIRMATIONS` passes in a row agree it has gone, and a pid that is+ genuinely stuck is still reported, which is the property the callers depend on. Order+ is the callers' (deepest first) and is preserved.++ The predicate is re-evaluated only for pids still in the list, so the expensive half of+ it -- reading an identity to prove the number has not been recycled -- runs only for+ the ones that look alive, which after a successful kill is none of them. A pid that+ reads as gone and then as alive again starts its count over: agreements have to be+ consecutive, because the point of the count is to survive a probe that lied once.+ """+ if not candidates:+ return []+ agreed: "dict[int, int]" = {}++ def _pass() -> "list[tuple[int, Optional[str]]]":+ still: "list[tuple[int, Optional[str]]]" = []+ for pid, identity in candidates:+ if agreed.get(pid, 0) >= _KILL_SETTLE_CONFIRMATIONS:+ continue+ if still_a_survivor(pid, identity):+ agreed[pid] = 0+ still.append((pid, identity))+ else:+ agreed[pid] = agreed.get(pid, 0) + 1+ if agreed[pid] < _KILL_SETTLE_CONFIRMATIONS:+ still.append((pid, identity))+ return still++ remaining = _pass()+ deadline = time.monotonic() + max(0.0, grace)+ wait = _KILL_SETTLE_POLL_SECONDS+ while remaining and time.monotonic() < deadline:+ time.sleep(wait)+ wait = min(wait * 2, _KILL_SETTLE_POLL_CEILING_SECONDS)+ remaining = _pass()+ return remaining+++def confirm_pid_exited(pid: "Optional[int]", grace: float = _KILL_SETTLE_SECONDS) -> bool:+ """Whether *pid* can be SHOWN to have exited, with the grace the read-backs use.++ For an owner that has just signalled a pid (or the process group it leads) and has to+ decide whether the record and the pidfile naming it may be dropped. Asking on the next+ line answers "the kill has not finished yet" and keeps a record for a process that is+ already gone.++ False for anything this module will not signal, including a pid it cannot read. Not+ True: this answer is what authorises deleting the only handles on a process, so+ "cannot tell" has to come out on the side that keeps them, the same way every other+ unprovable case in this module does.+ """+ if not _signalable(pid):+ return False+ return not _survivors_after_settling(+ [(int(pid), None)], lambda candidate, _identity: pid_is_running(candidate), grace+ )+++def _settle_after_the_kill(+ pid: int,+ group_leader: bool,+ grace: float = _KILL_SETTLE_SECONDS,+) -> None:+ """Wait, briefly, for a SIGKILL that has just been sent to actually land.++ `_posix_terminate_one` ends on `killpg`/`kill` with SIGKILL and returns, and every one+ of its callers reads liveness on the next line: `terminate_all` decides whether to+ write the record straight back, `_reap_one_record` decides whether the file on disk may+ be deleted, `terminate_pid` decides whether the pid may be forgotten. Measured here,+ all three answered "still running" for a child that was gone half a second later, and+ the record survived the process by a launch. Settling once HERE fixes every one of+ them, and is the POSIX counterpart of the read-back grace on the Windows tree kill.++ Only reached when the SIGTERM timeout was exhausted -- a child that exits politely+ returns from the poll loop above and never gets here -- so this costs nothing on the+ ordinary teardown.+ """++ def _still_there(candidate: int, _identity: "Optional[str]") -> bool:+ # The group as well as the leader, because that is what the callers go on to ask:+ # a leader can be gone while the session it started is not.+ if group_leader and _group_has_members(candidate):+ return True+ return _pid_alive(candidate) and not _pid_is_zombie(candidate)++ _survivors_after_settling([(pid, None)], _still_there, grace)def terminate_descendants(collected: "list[tuple[int, Optional[str]]]", timeout: float = 5.0-) -> None:+) -> "list[tuple[int, Optional[str]]]":"""SIGTERM then SIGKILL what `collect_descendants` found, still alive.The POSIX counterpart of the Windows ``taskkill /T``: a child that sharesthis process's group cannot be reached with killpg, so its own children aresignalled by pid instead.++ Returns the survivors as ``(pid, identity)``, with the identity this sweep COLLECTED+ rather than whatever the number reads as afterwards. The pair is what the caller needs:+ a pid it is about to record can have exited and been recycled since, and a bare number+ would then name a stranger. Still running when it gives up is not the same as the+ empty list. A kill can fail (the process is protected, the handle is denied, the+ exit is simply slow), and reporting the attempt as the outcome is what lets the+ caller delete the record and the pidfile out from under a worker that is still+ holding GPU memory or a port, leaving nothing that names it.++ Reporting only: adopting the survivors here would put a global record write on the+ POSIX teardown path, where the group reaper already covers them and nothing asked for+ it. The caller that is about to drop the last handle on them is the one that adopts."""- if not collected or _is_windows():- return+ if not collected:+ return []+ if _is_windows():+ return _windows_terminate_collected(collected)live: "list[tuple[int, Optional[str]]]" = []for pid, identity in collected:if not _signalable(pid) or not _still_the_same(pid, identity):@@ -715,6 +1237,313 @@ def terminate_descendants(os.kill(pid, signal.SIGKILL)except OSError:pass+ # Re-read rather than trusting the signal: SIGKILL is not instantaneous, and an+ # uninterruptible sleep in a driver ioctl outlives it entirely, which is the state a+ # worker holding a GPU is most likely to be in.+ #+ # And re-read with a grace period rather than on the next line. SIGKILL is not+ # instantaneous in the other direction either: a process that dies the moment it is+ # signalled is still visible for the microseconds the kernel spends tearing it down,+ # so an immediate read reported every one of eight descendants as a survivor when none+ # of them was alive half a second later. That answer keeps the record and the pidfile,+ # and the next launch then reaps ghosts. The stuck worker this read-back exists for is+ # unaffected: it is still there at the end of the grace, and is still reported.+ return _survivors_after_settling(+ live,+ lambda pid, identity: (+ _pid_alive(pid) and not _pid_is_zombie(pid) and _still_the_same(pid, identity)+ ),+ )+++# How deep the capture-before-kill recursion goes. Each level is one more Toolhelp snapshot+# taken immediately before a kill, which is the only moment at which a process's children+# can still be read: killing an intermediate first removes it from the next snapshot, and a+# grandchild that still records it as its creator can then no longer be reached by a walk+# that starts at the root, because the walk has to pass THROUGH a process that is gone. A+# tree deeper than this is not dropped silently: exhausting the depth answers None, the+# same answer an unperformed walk gives, so the anchor above it is carried out as+# unresolved and the record naming it survives the sweep.+_SUBTREE_CAPTURE_DEPTH = 8+++def _windows_kill_below(+ anchor: int,+ attempted: "list[tuple[int, Optional[str]]]",+ unresolved: "list[tuple[int, Optional[str]]]",+ killed: "set[int]",+ depth: int,+ anchor_identity: "Optional[str]" = None,+) -> "Optional[bool]":+ """Kill everything under *anchor*, capturing each subtree before removing its root.++ True when something was signalled, False when there was nothing left to signal, and+ None when the walk could not be done at all -- which is not the same as an empty tree+ and must not be reported as one.++ The capture is repeated at every level rather than taken once at the top, and that is+ the whole point: between the snapshot and the kill there is a fifteen second taskkill+ budget per process, and a child started in it is in no snapshot. Killing its parent+ first severs the only link a later walk could follow to it, since Windows' parent-pid+ field still names a process that no longer exists. So the children of a process are+ read immediately before that process is signalled, never after.+ """+ if depth <= 0:+ # Not False. False is "there was nothing left to signal", and the caller acts on+ # that by killing the anchor and reporting the subtree accounted for. A chain that+ # outran the depth (one more child started after each preceding snapshot) is the+ # opposite case: the walk was never performed at this level, killing the anchor+ # severs the only traversable link to whatever is below it, and the sweep would go+ # on to delete the lifetime record and the pidfile while that descendant runs.+ return None+ # With the anchor's own identity, so a number that moved on between the caller's check+ # and this walk cannot root the snapshot at a stranger's tree.+ found, known = _windows_collect_descendants_known(anchor, anchor_identity)+ if not known:+ return None+ progressed = False+ for child_pid, child_identity in reversed(found):+ if child_pid in killed:+ continue+ if not _signalable(child_pid) or not _pid_alive(child_pid):+ killed.add(child_pid)+ continue+ if not _provably_the_same(child_pid, child_identity):+ # The same three outcomes as the caller, which this used to collapse into two.+ # Provably somebody else is dropped; unreadable is a live pid this sweep cannot+ # account for, so it is reported rather than silently discarded, and the record+ # that names it outlives the call.+ if (+ _pid_alive(child_pid)+ and not _pid_is_zombie(child_pid)+ and not _provably_different(child_pid, child_identity)+ ):+ unresolved.append((child_pid, child_identity))+ killed.add(child_pid)+ continue+ # Below it first. It is about to stop existing, and with it every way of finding+ # what it started since the walk above returned.+ below = _windows_kill_below(+ child_pid, attempted, unresolved, killed, depth - 1, child_identity+ )+ if below is None:+ unresolved.append((child_pid, child_identity))+ try:+ _windows_terminate_pid(child_pid, child_identity)+ except Exception: # noqa: BLE001 - best effort, like the rest of this+ pass+ killed.add(child_pid)+ attempted.append((child_pid, child_identity))+ progressed = True+ return progressed+++# How many times a survivor's subtree is re-walked before the sweep gives up and says so.+# Each pass is one Toolhelp snapshot plus one identity read per candidate, so a handful is+# cheap; what it buys is the child a late descendant starts while the taskkill before it+# spends its fifteen seconds.+_LATE_WALK_ROUNDS = 4+++def _windows_terminate_collected(+ collected: "list[tuple[int, Optional[str]]]",+) -> "list[tuple[int, Optional[str]]]":+ """``taskkill /F`` each survivor individually, deepest first. Never ``/T``.++ Windows has no process group, so once the leader has been terminated nothing+ names its workers but this list. Identity is re-read per pid: the leader's+ terminate ran in between, so a number here may already belong to someone else.++ ``/T`` is deliberately NOT used, and that is the whole point of this function.+ ``taskkill /T`` terminates the named process AND its child processes, and it finds+ those children by walking the live parent-pid links -- the very links+ ``_windows_collect_descendants`` refuses to trust. In the reused-pid case that+ collector exists for, the stranger U is correctly kept OUT of `collected`, but U+ still records the reused number P as its creator, so ``/T`` on P, which IS in the+ list and IS identity-verified, rediscovers U through Windows' own walk and kills it.+ The filter would be defeated by the kill it protects.++ Reach is kept without it: each survivor is re-collected at kill time through the+ SAME creation-time validation, so anything it started after the snapshot is killed+ too, and anything merely linked to a recycled number is not. Losing the table means+ killing fewer processes rather than more, which is the right way for a forced tree+ kill to fail: a leaked worker is caught by the next sweep, and someone else's process+ is not recoverable.++ Returns the pids still running at the end. ``taskkill /F`` can fail outright (access+ denied, a protected process) and can also report success on a process that has not+ finished dying, so the answer is re-read from the pid rather than taken from the exit+ status. A survivor reported here is what stops the caller from deleting the record and+ the pidfile that are the only remaining handles on it.+ """+ attempted: "list[tuple[int, Optional[str]]]" = []+ unresolved: "list[tuple[int, Optional[str]]]" = []+ for pid, identity in reversed(collected):+ if not _signalable(pid) or not _pid_alive(pid):+ continue+ if not _provably_the_same(pid, identity):+ # Three outcomes here, not two, and the middle one used to vanish. A pid that+ # is PROVABLY somebody else is not ours and is simply dropped. A pid whose+ # identity cannot be read on either side is unknown: refusing to signal it is+ # right, but reporting nothing about it told the caller the sweep was complete,+ # so the record and the pidfile went and a live worker was left with nothing+ # naming it. Unknown is carried out as an unresolved survivor instead: never+ # signalled, always reported.+ if (+ _pid_alive(pid)+ and not _pid_is_zombie(pid)+ and not _provably_different(pid, identity)+ ):+ unresolved.append((pid, identity))+ continue+ # Started after the snapshot, and validated the same way rather than inherited+ # from a parent-pid link. Deepest first, as above.+ #+ # Repeated, not done once. Each `taskkill` below has the same fifteen second+ # ceiling, so a late descendant has a long window of its own in which to start a+ # child before its turn comes -- and a child of a late child was in neither walk, so+ # the sweep reported nothing about it and the caller deleted the record and the+ # pidfile while it held a GPU. Bounded rather than unbounded: a process that+ # respawns faster than it can be killed is not something a loop wins, and the answer+ # for it is the honest one below -- unresolved, which keeps the record.+ killed_below: "set[int]" = set()+ still_growing = True+ for _round in range(_LATE_WALK_ROUNDS):+ progressed = _windows_kill_below(+ pid, attempted, unresolved, killed_below, _SUBTREE_CAPTURE_DEPTH, identity+ )+ if progressed is None:+ # This walk is what covers anything the survivor started AFTER the snapshot.+ # Failing it and carrying on used to kill the survivor and then report+ # nothing, so a grandchild only this walk could have named was left with the+ # record and the pidfile deleted out from under it.+ #+ # The survivor itself is still killed: it is collected and identity-verified,+ # and refusing to kill it because a walk BELOW it failed would leave the very+ # process this sweep exists for running. What changes is the report: the pid+ # is carried out as unresolved, which keeps the record, and the next sweep+ # gets another walk at whatever is under it.+ unresolved.append((pid, identity))+ still_growing = False+ break+ if not progressed:+ still_growing = False+ break+ if still_growing:+ # The rounds ran out with the walk still producing pids. Whatever is under this+ # survivor has not been accounted for, so it is reported rather than reported+ # gone.+ unresolved.append((pid, identity))+ try:+ _windows_terminate_pid(pid, identity)+ except Exception: # noqa: BLE001 - best effort, like the rest of this+ pass+ attempted.append((pid, identity))+ # `not _provably_different`, not `_provably_the_same`. This is the ACCOUNTING step, not a+ # decision to signal anything: a pid that is plainly still running and whose identity+ # cannot be read right now -- handle pressure, access denied -- was proof of nothing, and+ # requiring proof here dropped it from the report entirely, so the caller deleted the+ # record and the pidfile that were the only handles on a process the kill had failed to+ # stop. Proof is still required before signalling, above; it is not required to say "this+ # is still running".+ #+ # Settled first, for the same reason the POSIX sweep settles: `TerminateProcess` is+ # asynchronous, so a descendant that died on the spot is still open and still+ # signalable on the line after the kill, and reporting it keeps the record and the+ # pidfile that the next launch then sweeps for nothing.+ survivors = _survivors_after_settling(+ attempted,+ lambda pid, identity: (+ _pid_alive(pid) and not _pid_is_zombie(pid) and not _provably_different(pid, identity)+ ),+ )+ # Deepest first throughout, and deduplicated: a pid whose late walk failed is reported+ # unresolved AND may still be alive after its own kill, so the two lists can name it+ # twice and the caller adopts each entry.+ ordered: "list[tuple[int, Optional[str]]]" = []+ seen: "set[int]" = set()+ for pid, identity in unresolved + survivors:+ if pid in seen:+ continue+ seen.add(pid)+ ordered.append((pid, identity))+ return ordered+++def _windows_terminate_validated_tree(pid: int, identity: "Optional[str]" = None) -> bool:+ """What ``taskkill /T /F`` was for, with the collector's filter kept intact.++ Same contract as `_windows_terminate_tree`: True when nothing of this tree is left+ running, False when something survived and the record naming it has to outlive the+ call. The difference is how the tree is enumerated. ``/T`` asks Windows, which walks+ the live parent-pid links; those links are stale by design (the creating pid is+ recorded once and never cleared), so a stranger that merely inherited a recycled+ number is reached and killed. `_windows_collect_descendants` is the filter that exists+ to reject exactly that, and routing a forced kill through ``/T`` hands the rejected+ process back to the kill anyway.++ Descendants are enumerated BEFORE the root is signalled: once the root exits its own+ identity stops being readable, and the collector needs it as the ancestry floor. The+ root is then stopped FIRST, before the snapshot is worked through, so it cannot keep+ extending the tree while each `taskkill` spends its budget.++ A tree this cannot enumerate collapses to killing the root alone and answering False,+ which is the same answer the ``/T`` fallback gave when taskkill was unavailable, and+ it fails towards leaking a worker rather than towards killing a stranger. False here+ is what keeps the record, so a later sweep still has a handle on whatever the failed+ walk did not name.+ """+ # The caller's identity, not a fresh read of the number. The leader can exit and its+ # pid be recycled between the caller's check and this line, and re-deriving the+ # identity here would bless the replacement: the collection below would enumerate the+ # stranger's tree and `_windows_terminate_pid` would terminate it through a handle+ # whose identity it just confirmed matches. Nothing is signalled in that case, and+ # False keeps the record, which is the same direction every other failure here fails.+ if identity is not None and not _provably_the_same(pid, identity):+ return False+ descendants, known = _windows_collect_descendants_known(pid, identity)+ # The root goes FIRST, the moment the snapshot exists. Killing the snapshot first spends+ # one `taskkill` per descendant, each with a 15 second ceiling, and the root is still+ # running for all of it: anything it starts in that window is in no snapshot, the+ # read-back below only examines what was snapshotted, and the caller is told the tree is+ # gone. Stopping the root cannot orphan the descendants here -- they are already named,+ # with their identities, in `descendants` -- which is the whole reason the snapshot is+ # taken before anything is signalled.+ if _signalable(pid) and _pid_alive(pid):+ try:+ _windows_terminate_pid(pid, identity if identity is not None else _pid_identity(pid))+ except Exception: # noqa: BLE001 - best effort, like the rest of this+ pass+ # And the descendants go through the survivor sweep's own terminator rather than a+ # plain loop over the snapshot. The same 15 second ceiling applies to each `taskkill`+ # here, so a snapshotted descendant has a long window in which to start a child of its+ # own before its turn comes; that child is in no snapshot, and a read-back over the+ # snapshot alone cannot see it. `_windows_terminate_collected` re-collects each+ # survivor through the SAME creation-time validation immediately before killing it, so+ # a late child is reached, a stranger on a recycled number still is not, and anything+ # it cannot account for comes back as a survivor instead of as silence.+ survivors = _windows_terminate_collected(descendants)+ # An unenumerable tree is not an empty one, so the root-only kill above is all that+ # happened and this cannot answer True. Same rule as the collector it calls: killing+ # fewer processes and keeping the record beats deleting the only handle on a worker+ # the walk could not see.+ if not known:+ return False+ # Read back on the root too: a taskkill that reported success still has to have taken+ # effect, and "the leader is gone" was never the question.+ #+ # With the same grace as the descendants above, and for the same reason.+ # `TerminateProcess` returns before the process is gone, so on a tree with no+ # descendants -- the ordinary case -- this read landed microseconds after the kill and+ # answered False for a leader that was already dying. False here is what keeps the+ # lifetime record and the pidfile, so the shutdown sweep reported a survivor that did+ # not exist and the record it wrote outlived the process by a launch.+ if _survivors_after_settling(+ [(pid, identity)],+ lambda candidate, _identity: _pid_alive(candidate) and not _pid_is_zombie(candidate),+ ):+ return False+ return not survivorsdef _still_the_same(pid: int, identity: "Optional[str]") -> bool:@@ -725,6 +1554,42 @@ def _still_the_same(pid: int, identity: "Optional[str]") -> bool:return _same_identity(identity, current)+def _provably_different(pid: int, identity: "Optional[str]") -> bool:+ """True only when the pid is provably a DIFFERENT process than it was.++ The third answer `_provably_the_same` cannot give. That one folds "somebody else" and+ "cannot tell" into the same False, which is right for deciding whether to signal and+ wrong for deciding whether to report: a number that has moved on to a stranger is not+ our leaked worker and must not be adopted, while one we merely cannot read might be.+ """+ if identity is None:+ return False+ current = _pid_identity(pid)+ if current is None:+ return False+ return not _same_identity(identity, current)+++def _provably_the_same(pid: int, identity: "Optional[str]") -> bool:+ """True only when the pid is provably the SAME process it was at collection.++ The fail-closed counterpart of `_still_the_same`. That one answers "is this+ provably somebody else", which is the right question for a SIGTERM aimed at a+ pid this process still owns a record for. It is the wrong question for the+ Windows survivor sweep: there the answer arrives after the leader has already+ been terminated, an unreadable identity is exactly what a pid that has been+ recycled looks like, and the action taken is ``taskkill /T /F``, which reaches+ everything the number now owns. So an identity that cannot be read on either+ side leaves the process alone.+ """+ if identity is None:+ return False+ current = _pid_identity(pid)+ if current is None:+ return False+ return _same_identity(identity, current)++def _group_member_pids(pgid: int) -> "Optional[list[int]]":"""Pids in a process group, or None when they cannot be enumerated."""if _is_linux():@@ -916,6 +1781,18 @@ def _pid_alive(pid: int) -> bool:return True+def pid_is_running(pid: "Optional[int]") -> bool:+ """Whether a pid is a process that is still executing.++ The public spelling of the liveness probe, for an owner that has to decide+ whether a child it tried to kill is actually gone. An exited child nobody has+ waited on is not running, so it does not count here.+ """+ if not is_signalable_pid(pid):+ return False+ return _pid_alive(pid) and not _pid_is_zombie(pid)++def _pid_is_zombie(pid: int) -> bool:"""An exited child nobody waited on. It answers signals like a live process,so a survivor check has to tell the two apart."""@@ -962,19 +1839,49 @@ def _identity_for_record(pid: int, attempts: int = 3) -> Optional[str]:return None-def adopt_pid(pid: Optional[int]) -> None:+def adopt_pid(+ pid: Optional[int],+ identity: "Optional[str]" = None,+ *,+ from_snapshot: bool = False,+) -> None:"""Track a child (e.g. a multiprocessing worker started after the parent jobwas set up) and, on Windows, assign it to the job as belt-and-suspenders.- Tolerates a None or already-exited pid."""+ Tolerates a None or already-exited pid.++ *identity* is the creation-time identity the CALLER already established for this pid.+ Pass it whenever the pid came from an earlier snapshot: a survivor reported by a sweep+ can exit between the sweep's last liveness check and this call, and the number is then+ free for anything. Without the check, that replacement is recorded as this process's+ child and, where a job object is active, assigned to a job that kills its members when+ the app closes. Given one, this adopts only a pid that is PROVABLY still the same+ process, and records the identity that was verified rather than re-reading it.++ ``from_snapshot`` is how a caller says that its None means "this pid's identity could not+ be READ", which is not the same claim as omitting the argument for a child this process+ has just spawned. The POSIX collector returns ``(pid, None)`` for a survivor it could not+ classify, and capturing an identity now would record whatever holds the number at this+ moment -- exactly the recycled stranger the identity check exists to keep out. A caller+ passing pids from an earlier snapshot sets it, and an unreadable one is then not adopted+ at all.+ """# `not pid` already rejected None and 0. pid 1 is init, and recording it is# what turns the sweep into a kill of everything the user owns.if not _signalable(pid):return+ if identity is None and from_snapshot:+ # Unknown from a snapshot adopts nobody either: see `from_snapshot` above.+ return+ if identity is not None and not _provably_the_same(pid, identity):+ # Unknown adopts nobody: a pid whose identity cannot be confirmed may already be a+ # stranger, and adopting one is not recoverable.+ return# Here as well as in the Linux spawn path: this is the first thing that# writes a record, and without the handler a fork child keeps this# process's children and later claims them as its own._adopt_fork_reset()- identity = _identity_for_record(pid)+ if identity is None:+ identity = _identity_for_record(pid)pgid = _own_process_group(pid)with _record_lock:_tracked_pids[pid] = identity@@ -991,9 +1898,30 @@ def adopt_pid(pid: Optional[int]) -> None:kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]kernel32.OpenProcess.restype = wintypes.HANDLEPROCESS_SET_QUOTA, PROCESS_TERMINATE = 0x0100, 0x0001- handle = kernel32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, pid)+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000+ handle = kernel32.OpenProcess(+ PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION,+ False,+ pid,+ )if handle:- kernel32.AssignProcessToJobObject(_win_job_handle, handle)+ # Checked HERE, through the handle that is about to be assigned, not on the+ # pid earlier. The check above happens before the record write and the+ # breadcrumb flush, and the process can exit anywhere in that interval; the+ # number is then free, and this `OpenProcess` can land on whatever took it.+ # Assigning a stranger to a job whose limit is kill-on-close means closing+ # Unsloth kills a process that has nothing to do with it. The handle refers+ # to one process for its whole lifetime, so a creation time read through it+ # answers about the process `AssignProcessToJobObject` will act on.+ #+ # Unreadable is not a match: no identity to compare against, or times that+ # cannot be read, means the assignment is skipped. It has always been+ # belt-and-suspenders -- the spawn path puts children in the job directly --+ # so skipping it costs a second line of defence, while getting it wrong+ # kills a stranger.+ opened = _windows_identity_of_handle(kernel32, handle)+ if identity is not None and opened is not None and opened == identity:+ kernel32.AssignProcessToJobObject(_win_job_handle, handle)kernel32.CloseHandle(handle)except Exception:pass@@ -1080,8 +2008,10 @@ def terminate_all(timeout: float = 5.0) -> "list[int]":try:if _is_windows():# The tree: a leader killed alone strands its workers, and the- # record naming them is cleared right after.- tree_stands = not _windows_terminate_tree(pid)+ # record naming them is cleared right after. Through the validated+ # collector, never taskkill /T: the same rejected-stranger problem+ # applies here as on the single-pid path.+ tree_stands = not _windows_terminate_validated_tree(pid, identity)else:_posix_terminate(pid, timeout)except Exception:@@ -1104,11 +2034,22 @@ def terminate_all(timeout: float = 5.0) -> "list[int]":return survivors-def terminate_pid(pid: "Optional[int]", timeout: float = 5.0) -> None:+def terminate_pid(+ pid: "Optional[int]",+ timeout: float = 5.0,+ *,+ owner_verified: bool = False,+) -> None:"""Stop one tracked child now, tree and all, and drop its record.For an owner that has to give up on a child before its own shutdown, andcannot leave it for a sweep that will not run while this process lives.++ ``owner_verified`` is for a caller that still holds a live handle on the child,+ a Popen it has not yet dropped, and so does not need this function to re-derive+ ownership from a start time it may no longer be able to read. It only waives the+ "cannot prove this is ours" refusal below; a pid that provably belongs to a+ different process now is still left alone."""# The public entry point, so the floor goes here: `_windows_terminate_tree` is reached without passing through the# POSIX helper that would otherwise carry the check.@@ -1126,7 +2067,7 @@ def terminate_pid(pid: "Optional[int]", timeout: float = 5.0) -> None:# group either, so there is no group of ours left to reap here.forget_pid(pid)return- if _pid_alive(pid) and (identity is None or current is None):+ if not owner_verified and _pid_alive(pid) and (identity is None or current is None):# Cannot prove this is still our child. Leave it alone and keep the# record: the startup sweep repeats the test with a fresh reading.return@@ -1134,8 +2075,11 @@ def terminate_pid(pid: "Optional[int]", timeout: float = 5.0) -> None:try:if _is_windows():# False is "only the leader was signalled": nothing else names those- # workers, so the record has to outlive this call.- tree_stands = not _windows_terminate_tree(pid)+ # workers, so the record has to outlive this call. Not taskkill /T: it+ # re-expands through the live parent-pid links, so a stranger holding a+ # recycled number that `_windows_collect_descendants` rejected is killed+ # by the very sweep that filter protects.+ tree_stands = not _windows_terminate_validated_tree(pid, identity)else:_posix_terminate(pid, timeout)# A leader that exited first takes getpgid with it, so _posix_terminate@@ -1249,8 +2193,14 @@ def _reap_one_record(path, timeout: float) -> "tuple[list[int], bool]":if _is_windows():# The tree, not the leader: this fallback runs when the Job Object# is unavailable, and killing a leader alone strands its workers- # while the record that named them is deleted.- tree_stands = not _windows_terminate_tree(pid)+ # while the record that named them is deleted. Through the validated+ # collector rather than taskkill /T, for the same reason the live path+ # uses it: /T re-walks the raw parent-pid links, which are stale by+ # design, so a stranger holding a recycled number that+ # `_windows_collect_descendants` rejected would be killed by the very+ # sweep that filter exists to protect. A record deferred to the next+ # application start must not be the way back in.+ tree_stands = not _windows_terminate_validated_tree(pid, identity)else:_posix_terminate(pid, timeout = timeout)killed.append(pid)@@ -1346,6 +2296,66 @@ def _reap_orphaned_group(pgid: object, pid: int, timeout: float) -> bool:return True+def _windows_terminate_pid(pid: int, identity: "Optional[str]" = None) -> bool:+ """``taskkill /F`` for ONE pid. No ``/T``, so no tree expansion.++ The counterpart of `_windows_terminate_tree` for a caller that has already+ established which pids it is entitled to kill and must not have Windows add to that+ set from the live parent-pid links. Caller has verified the identity.++ `identity` is that verification, carried in so the FALLBACK below can repeat it. The+ caller's check happened before the `taskkill`, and that call has a fifteen second+ ceiling: the process can exit inside it -- which is the case the fallback exists for --+ and Windows is then free to hand its number to something else. Signalling on the number+ alone at that point kills a stranger. Without an identity the fallback is skipped+ rather than guessed at: a leaked worker is caught by the next sweep, somebody else's+ process is not recoverable.+ """+ import subprocess++ # The handle first, because it is the only spelling of this that cannot be redirected.+ # `taskkill /PID` resolves the number inside itself, after the caller's check and after+ # this process has spent time getting here, so a pid that was freed in between takes the+ # kill with it onto whatever inherited the number. Through a handle there is no second+ # lookup: the creation time is read from the same object the terminate acts on.+ through_handle = _windows_terminate_through_a_handle(pid, identity)+ if through_handle is not None:+ return through_handle++ # The handle could not be opened at all, so the only thing left is the number -- and+ # `taskkill /PID` resolves that number itself, which is the very race the handle route+ # exists to close. Ownership is therefore re-established HERE, immediately before the+ # spawn, rather than after it: the caller's own check happened before the collection, a+ # descendant can have exited since, and signalling on a number nothing can vouch for is+ # how an unrelated process gets killed. With no identity to check against there is+ # nothing to establish, and a leaked worker is caught by the next sweep while somebody+ # else's process is not recoverable.+ if not _provably_the_same(pid, identity):+ return False++ try:+ completed = subprocess.run(+ ["taskkill", "/PID", str(pid), "/F"],+ capture_output = True,+ timeout = 15,+ creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),+ )+ # 128 is "already gone", as in the tree call below.+ if completed.returncode in (0, 128):+ return True+ except (OSError, subprocess.SubprocessError):+ pass+ # Asked again, because `taskkill` has a fifteen second ceiling and the process can exit+ # inside it -- which is the case this fallback exists for -- leaving the number free.+ if not _provably_the_same(pid, identity):+ return False+ try:+ os.kill(pid, signal.SIGTERM)+ except OSError:+ pass+ return False++def _windows_terminate_tree(pid: int) -> bool:"""``taskkill /T /F``. True when the whole tree is gone.@@ -1439,3 +2449,4 @@ def _posix_terminate_one(pid: int, group_leader: bool, timeout: float) -> None:killer(pid, signal.SIGKILL)except Exception:pass+ _settle_after_the_kill(pid, group_leader)diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rsindex c8dc2bd7427..57e7550e12f 100644--- a/studio/src-tauri/src/preflight.rs+++ b/studio/src-tauri/src/preflight.rs@@ -321,6 +321,19 @@ pub async fn desktop_preflight_result_with_state();return Ok((choose_preflight(managed, backend), None));}+ // The spawned arm self-heals too, but only for a child that has actually+ // exited: a handle with no validated port is usually a cold start still+ // importing torch, and clearing that would abandon a healthy launch. A+ // child that died without its stdout reaching EOF is invisible to the+ // crash detector, and the handle it leaves behind makes every later+ // launch answer "Backend is already running." (#9756).+ if crate::process::clear_spawned_backend_if_exited(+ state,+ snapshot.generation,+ "state owner probe no longer verifies",+ ) {+ return Ok((choose_preflight(managed, backend), None));+ }return Ok((choose_owned_transitional_preflight(&managed, snapshot.port),None,diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 5dae83906cd..5879e422fa3 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -1233,6 +1233,60 @@ pub(crate) fn clear_adopted_backend_if_current(true}+/// Drop a spawned backend handle whose child has provably exited, so a launch can spawn.+///+/// The counterpart of `clear_adopted_backend_if_current` for the arm this app owns. A+/// `Spawned` handle with no validated port is normally a healthy cold start still+/// importing torch, so a probe that does not verify is on its own no reason to clear+/// anything: this fires only on an exit status the child has actually reported. Without+/// it, a child that died without its stdout ever reaching EOF, which is the one case the+/// crash detector in `read_output_stream` cannot see, leaves `has_owned_backend` true for+/// the life of the app: every launch then answers `Backend is already running.` and every+/// preflight answers `desktop_owned_backend_starting`.+///+/// Unlike the adopted case, this app wrote the owner file, so it is removed here too.+pub(crate) fn clear_spawned_backend_if_exited(+ state: &BackendState,+ generation: u64,+ reason: &str,+) -> bool {+ let mut proc = match state.lock() {+ Ok(guard) => guard,+ Err(poisoned) => poisoned.into_inner(),+ };+ if proc.generation != generation {+ return false;+ }+ let status = match proc+ .owned+ .as_mut()+ .and_then(OwnedBackendHandle::spawned_child_mut)+ {+ // One look, not the thirty of `exit_status_after_stdout_closed`. This runs on the+ // preflight a window mount drives, so it must not block it for three seconds, and+ // a child merely slow to be reaped is answered by the next preflight instead.+ Some(child) => match child.try_wait() {+ Ok(Some(status)) => status.to_string(),+ Ok(None) => return false,+ Err(error) => {+ warn!("Could not read the spawned backend's exit status: {error}");+ return false;+ }+ },+ // Adopted, or nothing owned at all. Neither belongs to this function.+ None => return false,+ };++ warn!("Clearing spawned backend state after {reason}; the child had exited: {status}");+ if let Some(owned) = proc.owned.take() {+ owned.remove_owner_metadata();+ }+ proc.port = None;+ proc.diagnostics_session = None;+ proc.adopted_watchdog_generation = None;+ true+}+pub(crate) fn claim_adopted_watchdog_if_current(state: &BackendState, generation: u64) -> bool {let mut proc = match state.lock() {Ok(guard) => guard,@@ -3113,6 +3167,136 @@ mod tests {(port, tx, handle)}+ // ── #9756: a spawned handle whose child has exited must not block the next launch ──+ //+ // The crash detector in `read_output_stream` clears the handle when the child's+ // stdout reaches EOF, and `stop_backend_inner` clears it on a deliberate stop. A+ // child that dies without either happening leaves the handle behind, and from then+ // on `has_owned_backend` refuses every launch with "Backend is already running."+ // while preflight reports `desktop_owned_backend_starting`.++ #[cfg(unix)]+ const ALREADY_EXITED: [&str; 3] = ["/bin/sh", "-c", "exit 3"];+ #[cfg(unix)]+ const STILL_RUNNING: [&str; 3] = ["/bin/sh", "-c", "exec sleep 30"];+ #[cfg(windows)]+ const ALREADY_EXITED: [&str; 3] = ["cmd", "/C", "exit 3"];+ #[cfg(windows)]+ const STILL_RUNNING: [&str; 3] = ["cmd", "/C", "ping -n 31 127.0.0.1"];++ // Shaped like the real spawn in `start_backend`: a process group on Unix, a bare+ // Child on Windows, where the app-wide job object already covers the tree.+ fn spawn_test_child(args: &[&str]) -> Box<dyn ChildWrapper + Send> {+ let mut cmd = Command::new(args[0]);+ cmd.args(&args[1..])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ #[cfg(unix)]+ {+ let mut wrap = CommandWrap::from(cmd);+ wrap.wrap(ProcessGroup::leader());+ wrap.spawn().expect("spawn test child")+ }+ #[cfg(windows)]+ {+ Box::new(cmd.spawn().expect("spawn test child"))+ }+ }++ // Reaped before the handle is built, so the test is about the clear and not about+ // racing the kernel; `exit_status_after_stdout_closed_tests` already covers the race.+ fn spawn_and_reap() -> Box<dyn ChildWrapper + Send> {+ let mut child = spawn_test_child(&ALREADY_EXITED);+ for _ in 0..100 {+ match child.try_wait() {+ Ok(Some(_)) => return child,+ Ok(None) => std::thread::sleep(Duration::from_millis(50)),+ Err(error) => panic!("could not poll the test child: {error}"),+ }+ }+ panic!("the test child never exited");+ }++ fn state_with_spawned(child: Box<dyn ChildWrapper + Send>, generation: u64) -> BackendState {+ let state = new_backend_state();+ {+ let mut proc = state.lock().unwrap();+ proc.generation = generation;+ proc.port = Some(8888);+ proc.owned = Some(OwnedBackendHandle::spawned(child, None, 4242, generation));+ }+ state+ }++ #[test]+ fn a_dead_spawned_backend_is_cleared_and_stops_blocking_a_launch() {+ let state = state_with_spawned(spawn_and_reap(), 5);+ assert!(+ state.lock().unwrap().has_owned_backend(),+ "precondition: this is what makes start_backend answer Backend is already running."+ );+ assert!(clear_spawned_backend_if_exited(&state, 5, "test"));+ let proc = state.lock().unwrap();+ assert!(!proc.has_owned_backend(), "the dead handle still blocks a launch");+ assert!(proc.port.is_none());+ assert!(proc.diagnostics_session.is_none());+ }++ #[test]+ fn a_live_spawned_backend_is_left_alone() {+ // The regression guard that matters more than the fix: a handle with no+ // validated port is usually a cold start still importing torch, and clearing it+ // would abandon a backend that is about to come up.+ let state = state_with_spawned(spawn_test_child(&STILL_RUNNING), 5);+ assert!(!clear_spawned_backend_if_exited(&state, 5, "test"));+ {+ let mut proc = state.lock().unwrap();+ assert!(proc.has_owned_backend(), "cleared a backend that was still running");+ assert_eq!(proc.port, Some(8888));+ if let Some(child) = proc+ .owned+ .as_mut()+ .and_then(OwnedBackendHandle::spawned_child_mut)+ {+ let _ = child.start_kill();+ }+ }+ }++ #[test]+ fn a_dead_spawned_backend_from_an_older_generation_is_left_alone() {+ // A launch that has already moved on owns the handle now.+ let state = state_with_spawned(spawn_and_reap(), 5);+ assert!(!clear_spawned_backend_if_exited(&state, 4, "test"));+ assert!(state.lock().unwrap().has_owned_backend());+ }++ #[test]+ fn an_adopted_backend_is_not_this_functions_business() {+ // clear_adopted_backend_if_current owns that arm, and it probes liveness a+ // different way: an adopted handle carries no child to try_wait on.+ let state = new_backend_state();+ let owner = crate::desktop_backend_owner::test_owner_state(+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "desktop-owner-token",+ 8888,+ );+ {+ let mut proc = state.lock().unwrap();+ proc.generation = 5;+ proc.owned = Some(OwnedBackendHandle::adopted(owner, 8888, 4242, 5));+ }+ assert!(!clear_spawned_backend_if_exited(&state, 5, "test"));+ assert!(state.lock().unwrap().has_owned_backend());+ }++ #[test]+ fn nothing_owned_is_not_an_error() {+ let state = new_backend_state();+ state.lock().unwrap().generation = 5;+ assert!(!clear_spawned_backend_if_exited(&state, 5, "test"));+ }+#[test]fn stop_backend_rolls_back_shutdown_flag_when_adopted_stop_fails() {let (port, stop_listener, listener_thread) = listening_non_studio_port();