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
fix(studio): keep child spawns alive under a pid-1 parent (#7894)
Maheswar Kumar036400e51674
diff --git a/studio/backend/tests/test_process_lifetime.py b/studio/backend/tests/test_process_lifetime.pyindex c36cd754053..9dd5c3a1479 100644--- a/studio/backend/tests/test_process_lifetime.py+++ b/studio/backend/tests/test_process_lifetime.py@@ -98,9 +98,9 @@ def test_child_popen_kwargs_linux_vs_other(monkeypatch):def test_compose_preexec_runs_pdeathsig_then_existing(monkeypatch):calls = []monkeypatch.setattr(pl, "_is_linux", lambda: True)- monkeypatch.setattr(pl, "_pdeathsig_preexec", lambda: calls.append("death"))- pl.compose_preexec(lambda: calls.append("existing"))()- assert calls == ["death", "existing"] # ordering matters for sandbox hooks+ monkeypatch.setattr(pl, "_pdeathsig_preexec", lambda owner: calls.append(("death", owner)))+ pl.compose_preexec(lambda: calls.append("existing"), 4242)()+ assert calls == [("death", 4242), "existing"] # ordering matters for sandbox hooksdef test_compose_preexec_passthrough_off_linux(monkeypatch):@@ -110,6 +110,110 @@ def test_compose_preexec_passthrough_off_linux(monkeypatch):assert pl.compose_preexec(None) is None+def test_child_popen_kwargs_binds_the_spawning_pid(monkeypatch):+ # Compare against the forking pid, so a healthy child of a pid-1 parent is+ # not mistaken for an orphan (#7886).+ seen = []+ monkeypatch.setattr(pl, "_is_linux", lambda: True)+ monkeypatch.setattr(pl, "_pdeathsig_preexec", lambda owner: seen.append(owner))+ pl.child_popen_kwargs()["preexec_fn"]()+ assert seen == [os.getpid()]+++# ── Orphan decision inside the preexec hook ──+++class _ExitCalled(BaseException):+ """Stands in for os._exit, which a test cannot survive. A BaseException so+ the hook's own `except Exception` does not swallow it."""+++def _run_preexec(monkeypatch, *, owner_pid, getppid):+ # prctl is stubbed so the decision runs on any platform.+ import ctypes++ class _Libc:+ def prctl(self, *args):+ return 0++ def _no_exit(code):+ raise _ExitCalled(code)++ monkeypatch.setattr(ctypes, "CDLL", lambda *a, **k: _Libc())+ monkeypatch.setattr(pl.os, "getppid", lambda: getppid)+ monkeypatch.setattr(pl.os, "_exit", _no_exit)+ pl._pdeathsig_preexec(owner_pid)+++def test_pdeathsig_keeps_child_whose_parent_is_pid_1(monkeypatch):+ # Studio as a container entrypoint runs as pid 1, so a healthy child sees+ # getppid() == 1; killing it took down every llama-server spawn (#7886).+ _run_preexec(monkeypatch, owner_pid = 1, getppid = 1)+++def test_pdeathsig_exits_when_reparented_away_from_the_owner(monkeypatch):+ with pytest.raises(_ExitCalled):+ _run_preexec(monkeypatch, owner_pid = 4242, getppid = 1)+++def _bind_with_parent(monkeypatch, parent):+ import multiprocessing++ seen, exited = [], []+ monkeypatch.setattr(pl, "_is_linux", lambda: True)+ monkeypatch.setattr(pl, "_pdeathsig_preexec", lambda owner: seen.append(owner))+ monkeypatch.setattr(pl.os, "_exit", lambda code: exited.append(code))+ monkeypatch.setattr(multiprocessing, "parent_process", lambda: parent)+ pl.bind_current_process_to_parent_lifetime()+ return seen, exited+++def test_bind_keeps_a_worker_whose_creator_is_alive(monkeypatch):+ # The decision comes from the creator's sentinel, not a pid compare: under+ # forkserver the kernel parent is the fork server, so pids would read every+ # healthy worker as orphaned.+ seen, exited = _bind_with_parent(monkeypatch, _FakeParent(4242, alive = True))+ assert seen == [os.getppid()] # PDEATHSIG still bound to the kernel parent+ assert exited == []+++def test_bind_exits_when_the_creator_is_already_gone(monkeypatch):+ seen, exited = _bind_with_parent(monkeypatch, _FakeParent(4242, alive = False))+ assert seen == [os.getppid()]+ assert exited == [1]+++def test_bind_only_arms_pdeathsig_outside_a_multiprocessing_worker(monkeypatch):+ # No creator to consult and nothing orphaned: arm PDEATHSIG, decide nothing.+ seen, exited = _bind_with_parent(monkeypatch, None)+ assert seen == [os.getppid()]+ assert exited == []+++def test_bind_keeps_a_non_worker_whose_parent_is_pid_1(monkeypatch):+ # Runs the REAL hook: a non-worker under a container init sees getppid() == 1,+ # which the bare fallback killed outright.+ import ctypes+ import multiprocessing++ exited = []+ monkeypatch.setattr(pl, "_is_linux", lambda: True)+ monkeypatch.setattr(ctypes, "CDLL", lambda *a, **k: type("L", (), {"prctl": lambda *_: 0})())+ monkeypatch.setattr(pl.os, "getppid", lambda: 1)+ monkeypatch.setattr(pl.os, "_exit", lambda code: exited.append(code))+ monkeypatch.setattr(multiprocessing, "parent_process", lambda: None)+ pl.bind_current_process_to_parent_lifetime()+ assert exited == []+++class _FakeParent:+ def __init__(self, pid, alive):+ self.pid, self._alive = pid, alive++ def is_alive(self):+ return self._alive++# ── Real Linux PDEATHSIG: child dies when the parent dies abnormally ──diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.pyindex c63227ae867..c52a8221fca 100644--- a/studio/backend/utils/process_lifetime.py+++ b/studio/backend/utils/process_lifetime.py@@ -152,13 +152,20 @@ def _install_windows_job() -> None:# ── Child binding ──-def _pdeathsig_preexec() -> None:- # Runs in the forked child before exec. prctl is Linux-only; the getppid- # check closes the race where the parent died before this ran.+def _pdeathsig_preexec(owner_pid: Optional[int] = None) -> None:+ # Runs in the forked child before exec (PR_SET_PDEATHSIG does not survive the+ # fork); the getppid check closes the race where the parent died first.+ # owner_pid is the spawner's pid, read pre-fork. A bare `getppid() == 1` also+ # matches a parent that legitimately IS pid 1, which is how Studio runs as a+ # container entrypoint: it killed every llama-server before exec (#7886). It+ # also misses reparenting to a subreaper, whose pid is not 1.try:import ctypes+ctypes.CDLL("libc.so.6", use_errno = True).prctl(_PR_SET_PDEATHSIG, signal.SIGTERM)- if os.getppid() == 1:+ parent_pid = os.getppid()+ orphaned = parent_pid != owner_pid if owner_pid is not None else parent_pid == 1+ if orphaned:os._exit(1)except Exception:pass@@ -168,20 +175,44 @@ def bind_current_process_to_parent_lifetime() -> None:"""Bind the CURRENT process to its parent's death (Linux). For multiprocessingchildren, which cannot take a preexec_fn, so the parent cannot setPR_SET_PDEATHSIG for them -- the child must do it itself at startup."""- if _is_linux():- _pdeathsig_preexec()+ if not _is_linux():+ return+ parent = None+ try:+ import multiprocessing+ parent = multiprocessing.parent_process()+ except Exception:+ pass+ if parent is None:+ # No creator to consult and nothing orphaned, so only arm PDEATHSIG: the+ # bare getppid() == 1 test would kill a parent-is-pid-1 process (#7886).+ _pdeathsig_preexec(os.getppid())+ return+ # PDEATHSIG binds to the kernel parent; "orphaned" comes from the creator's+ # sentinel, not a pid compare, since under forkserver the kernel parent is the+ # fork server and comparing would kill every healthy worker. The sentinel is+ # exact under spawn and forkserver; under fork a sibling can inherit the+ # creator's write end and read stale-alive, but PDEATHSIG covers fork. A+ # forkserver creator dying later stays uncovered, as on main.+ _pdeathsig_preexec(os.getppid())+ try:+ if not parent.is_alive():+ os._exit(1)+ except Exception:+ pass-def compose_preexec(existing: Optional[Callable[[], None]]) -> Optional[Callable[[], None]]:+def compose_preexec(+ existing: Optional[Callable[[], None]], owner_pid: Optional[int] = None+) -> Optional[Callable[[], None]]:"""Run the PDEATHSIG hook then any caller-supplied preexec (Linux only)."""if not _is_linux():return existing- if existing is None:- return _pdeathsig_preexecdef _composed() -> None:- _pdeathsig_preexec()- existing()+ _pdeathsig_preexec(owner_pid)+ if existing is not None:+ existing()return _composed@@ -194,7 +225,9 @@ def child_popen_kwargs(preexec_fn: Optional[Callable[[], None]] = None) -> dict:``**child_popen_kwargs()`` alongside the caller's existing kwargs."""if _is_linux():- return {"preexec_fn": compose_preexec(preexec_fn)}+ # os.getpid() runs in the spawner, so the child tells real reparenting+ # apart from a parent that is pid 1 (see _pdeathsig_preexec).+ return {"preexec_fn": compose_preexec(preexec_fn, os.getpid())}return {}