Skip to content

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.

Studio: never signal pid 0 or pid 1 from the lifetime reaper (#8797)

Daniel Han7e3039ecaf79
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 1a478e0f3b7..bc1164760d9 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -95,6 +95,7 @@ from utils.subprocess_compat import (
windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
)
from utils.process_lifetime import child_popen_kwargs as _child_popen_kwargs
+from utils.process_lifetime import is_signalable_pid as _is_signalable_pid
from core.inference.tool_call_parser import (
MAX_ACT_REPROMPTS as _MAX_REPROMPTS,
NUDGE_TOOL_CALLS_STATUS as _NUDGE_TOOL_CALLS_STATUS,
@@ -16930,8 +16931,17 @@ class LlamaCppBackend:
@staticmethod
def _leading_process_group(pid):
- """The pid's own process group, when it leads one. None otherwise."""
- if not pid or os.name != "posix" or not hasattr(os, "getpgid"):
+ """The pid's own process group, when it leads one. None otherwise.
+
+ `not pid` rejects 0 and None but not 1, and `getpgid(1) == 1`, so init
+ reads as a group leader here and the caller below would then broadcast
+ SIGKILL to every process the user owns. The pid comes from a live Popen
+ today so it cannot be 1, but the floor is a line and the consequence of
+ losing that property later is not recoverable.
+ """
+ if not _is_signalable_pid(pid):
+ return None
+ if os.name != "posix" or not hasattr(os, "getpgid"):
return None
try:
pgid = os.getpgid(pid)
@@ -16942,7 +16952,9 @@ class LlamaCppBackend:
@staticmethod
def _kill_process_group(pgid):
"""Take down what the leader left behind, if anything is still there."""
- if pgid is None or not hasattr(os, "killpg"):
+ if not _is_signalable_pid(pgid):
+ return # killpg(1) is kill(-1); killpg(0) is our own group
+ if not hasattr(os, "killpg"):
return
try:
os.killpg(pgid, signal.SIGKILL)
@@ -17229,7 +17241,12 @@ class LlamaCppBackend:
except Exception:
pid = -1
- if pid <= 0:
+ # `pid <= 0` let pid 1 through. The cmdline check further down is what
+ # actually keeps this honest and init cannot pass it, but the reaper in
+ # process_lifetime had a start-time identity check that was just as
+ # convincing and a record naming pid 1 still went through it, so the
+ # cheap bound goes in front of the clever one here too.
+ if not _is_signalable_pid(pid):
cls._unlink_pidfile(path) # garbage record
return 0
if pid == os.getpid():
@@ -17491,6 +17508,14 @@ class LlamaCppBackend:
# -- Ownership check, orphan check, kill ---------------------------
for pid, binary, kill in candidates:
+ # Floored here rather than in each enumerator: both the /proc scan
+ # and the psutil scan feed this loop, and a third one added later
+ # would too. Not hypothetical for pid 1 either, since #7894
+ # established Studio can run as a container entrypoint, and a
+ # container whose entrypoint is llama-server puts a process this
+ # sweep recognises at pid 1. Killing it takes the container down.
+ if not _is_signalable_pid(pid):
+ continue
# Ownership: exact match OR binary under a known root.
is_ours = binary in exact_binaries or any(
binary.is_relative_to(root) for root in resolved_roots
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.py
index 626fab772d9..8b9c0053db0 100644
--- a/studio/backend/hub/utils/download_registry.py
+++ b/studio/backend/hub/utils/download_registry.py
@@ -55,6 +55,11 @@ from typing import Callable, Iterator, Literal, NamedTuple, Optional, Sequence
from loggers import get_logger
+# One floor, one name, shared. Written out by hand in each module it was needed
+# in at first, and the site that got missed was missed because "who enforces it"
+# was a question you answered by reading rather than by grepping.
+from utils.process_lifetime import is_signalable_pid
+
from hub.utils import state_dir
from hub.utils.state_dir import RepoType
@@ -269,6 +274,11 @@ def _kill_orphan(pid: int) -> bool:
reason to hold up startup -- and answering False there matters: a survivor must keep its
breadcrumb and must not have its live partial claimed as ours to delete.
"""
+ # Its caller floors the pid too. Repeated here because this one sends the
+ # signal, and a helper that kills should not depend on every future caller
+ # having checked first.
+ if not is_signalable_pid(pid):
+ return False
try:
os.kill(pid, signal.SIGTERM if sys.platform == "win32" else signal.SIGKILL)
except OSError:
@@ -378,11 +388,19 @@ def reap_orphan_workers() -> None:
continue
pid = data.get("pid") if isinstance(data, dict) else None
repo_id = data.get("repo_id") if isinstance(data, dict) else None
- if not isinstance(pid, int) or pid <= 0:
- _safe_unlink(entry)
- continue
+ # pid 1 as well as 0 and negatives. The cmdline check below is what
+ # actually keeps this honest and init cannot pass it, but the same was
+ # true of the reaper's start-time check until a record naming pid 1
+ # slipped through it, so the cheap bound goes in front of the clever one.
+ signalable = is_signalable_pid(pid)
try:
- if not _process_alive(pid):
+ if not signalable:
+ # Nothing is signalled on this record's word, but its repo fields
+ # are still readable, and the settle below is what preserves the
+ # partial's resume marker. Unlinking straight from here would cost
+ # the user a restarted download to pay for a bug that is ours.
+ pass
+ elif not _process_alive(pid):
# Already gone, which is better proof than killing it ourselves. Its partial
# is ours to sweep even though this invocation reaped nothing.
reaped.append((data.get("repo_type") or "model", repo_id, data.get("hub_cache")))
diff --git a/studio/backend/tests/test_process_lifetime_never_signals_init.py b/studio/backend/tests/test_process_lifetime_never_signals_init.py
new file mode 100644
index 00000000000..2b1ec759e4f
--- /dev/null
+++ b/studio/backend/tests/test_process_lifetime_never_signals_init.py
@@ -0,0 +1,432 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The reaper must never signal pid 0 or pid 1.
+
+`killpg(1, sig)` is not "process group 1". POSIX defines it as `kill(-1, sig)`:
+every process the caller has permission to signal. So a single record naming
+pid 1 as a child turns the startup sweep into a SIGTERM of everything the user
+owns, a five second wait, then a SIGKILL of the same.
+
+That is not hypothetical. It was observed on a shared build box, from a record
+holding `{"pid": 1, "identity": "...", "pgid": 1}`: starting Studio killed the
+user's tmux server and all twenty of their unrelated agent processes within one
+second, then SIGKILLed the replacement tmux server exactly `timeout` later.
+
+Nothing rejected it on the way in or on the way out:
+
+ * `adopt_pid` guarded `not pid`, which rejects None and 0 but not 1.
+ * The recycled-pid defence compares a recorded start time against the current
+ one. init's start time never changes, so a recorded pid 1 matches forever.
+ The check designed to make this safe is what guaranteed it fired.
+ * `getpgid(1) == 1`, so pid 1 reads as a group leader and selects `killpg`.
+ * The liveness probe between SIGTERM and SIGKILL is `killpg(1, 0)`, which can
+ never fail, so the grace period always runs to completion.
+
+These tests assert the outcome rather than the helper: no signalling call in
+this module is reached with a pid below 2, on any path, and the same floor is
+asserted at the sibling boundaries in `llama_cpp` and `download_registry` that
+signal on a pid they read from disk rather than one they hold a handle to.
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import utils.process_lifetime as pl # noqa: E402
+
+IS_POSIX = os.name == "posix"
+
+
+def recorded_signals(monkeypatch):
+ """Capture every signal this module would send, and send none of them."""
+ sent: "list[tuple[str, int, int]]" = []
+
+ def _kill(pid, sig):
+ sent.append(("kill", pid, sig))
+
+ def _killpg(pgid, sig):
+ sent.append(("killpg", pgid, sig))
+
+ monkeypatch.setattr(pl.os, "kill", _kill)
+ if hasattr(pl.os, "killpg"):
+ monkeypatch.setattr(pl.os, "killpg", _killpg)
+ return sent
+
+
+# --- the guard itself ------------------------------------------------------
+
+
[email protected]("pid", [None, 0, 1, -1, -12345, "1", 1.0, True, False])
+def test_unsignalable_values_are_rejected(pid):
+ """`True` is here for the floor's benefit, not the bool check's: `True >= 2`
+ is already False, so `not isinstance(pid, bool)` is belt to the floor's
+ braces and this case would still pass without it. It earns its place by
+ pinning the behaviour if the floor is ever expressed a different way."""
+ assert pl.is_signalable_pid(pid) is False
+
+
+def test_the_public_name_is_the_internal_one():
+ """Other modules import the public spelling. If the two ever come apart, the
+ floor stops meaning one thing across Studio, which is how a site gets missed."""
+ assert pl._signalable is pl.is_signalable_pid
+
+
[email protected]("pid", [2, 3, 12345, 4194304])
+def test_real_pids_are_accepted(pid):
+ assert pl._signalable(pid) is True
+
+
+# --- the write side: the bad record cannot be created ----------------------
+
+
+def test_adopt_pid_refuses_init(monkeypatch):
+ monkeypatch.setattr(pl, "_tracked_pids", {})
+ monkeypatch.setattr(pl, "_tracked_pgids", {})
+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)
+ pl.adopt_pid(1)
+ assert pl._tracked_pids == {}, "pid 1 must never enter the record"
+ assert pl._tracked_pgids == {}
+
+
[email protected](not IS_POSIX, reason = "process groups are POSIX only")
+def test_own_process_group_refuses_group_one(monkeypatch):
+ monkeypatch.setattr(pl.os, "getpgid", lambda pid: 1)
+ assert pl._own_process_group(1) is None
+
+
+# --- the signal side: an existing bad record cannot fire -------------------
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_posix_terminate_sends_nothing_for_init(recorded_signals):
+ pl._posix_terminate(1, timeout = 0.01)
+ assert recorded_signals == [], "killpg(1, sig) is kill(-1, sig): every process the user owns"
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pid", [0, 1])
+def test_posix_terminate_one_sends_nothing(recorded_signals, pid):
+ pl._posix_terminate_one(pid, group_leader = True, timeout = 0.01)
+ pl._posix_terminate_one(pid, group_leader = False, timeout = 0.01)
+ assert recorded_signals == []
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_reap_orphaned_group_refuses_group_one(recorded_signals):
+ assert pl._reap_orphaned_group(1, 1, timeout = 0.01) is False
+ assert recorded_signals == []
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_terminate_descendants_skips_init(recorded_signals, monkeypatch):
+ monkeypatch.setattr(pl, "_still_the_same", lambda pid, identity: True)
+ pl.terminate_descendants([(1, "irrelevant")], timeout = 0.01)
+ assert recorded_signals == []
+
+
+# --- the end to end case that actually happened ----------------------------
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_poisoned_record_is_dropped_not_retried(tmp_path, monkeypatch, recorded_signals):
+ """A record written by a build without the guard must fire nothing, and must
+ not survive to be retried on every subsequent launch."""
+ import json
+
+ record = tmp_path / "4157196.json"
+ record.write_text(
+ json.dumps(
+ {
+ "owner_pid": 4157196,
+ "owner_identity": "243506968",
+ # Verbatim from the record that caused the incident. "963" is
+ # init's start time in jiffies on that machine, so it is not
+ # portable, and nothing here compares against it: the pid floor
+ # short-circuits before identity is ever read. It stays because a
+ # regression test for a specific incident should carry the bytes
+ # that caused it.
+ "children": [{"pid": 1, "identity": "963", "pgid": 1}],
+ }
+ ),
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(pl, "_breadcrumb_dir", lambda: tmp_path)
+ # The owner is long gone, which is what makes the sweep consider the record.
+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == 1)
+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)
+
+ reaped = pl.reap_recorded_children(timeout = 0.01)
+
+ assert recorded_signals == [], "the sweep must not signal init"
+ assert reaped == [], "nothing was reaped, so nothing may be reported as reaped"
+ assert (
+ not record.exists()
+ ), "a poisoned record must be unlinked, or every launch retries it forever"
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pgid", [0, 1])
+def test_poisoned_pgid_does_not_make_a_record_immortal(
+ tmp_path, monkeypatch, recorded_signals, pgid
+):
+ """A real pid paired with a poisoned pgid.
+
+ `killpg(1, 0)` is `kill(-1, 0)` and `killpg(0, 0)` is our own group, so both
+ always succeed. Without a floor `_group_has_members` answers True for either,
+ the entry is held `unresolved`, and the record is never unlinked: retried on
+ every launch forever, which is the opposite of what dropping a poisoned
+ record is for. The pid floor cannot catch this one, because the pid is fine.
+ """
+ import json
+
+ record = tmp_path / "555555.json"
+ record.write_text(
+ json.dumps(
+ {
+ "owner_pid": 555555,
+ "owner_identity": "111",
+ "children": [{"pid": 424242, "identity": "222", "pgid": pgid}],
+ }
+ ),
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(pl, "_breadcrumb_dir", lambda: tmp_path)
+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: False) # the child is long gone
+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)
+
+ pl.reap_recorded_children(timeout = 0.01)
+
+ assert [s for s in recorded_signals if s[1] < 2] == [], "not even a probe below pid 2"
+ assert not record.exists(), "a record with a poisoned pgid must not be immortal"
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pgid", [None, 0, 1, -1, True, "1"])
+def test_group_has_members_refuses_unsignalable_groups(recorded_signals, pgid):
+ assert pl._group_has_members(pgid) is False
+ assert recorded_signals == []
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pid", [0, 1, True])
+def test_terminate_pid_sends_nothing(recorded_signals, monkeypatch, pid):
+ """`terminate_pid` is the public single-child stop. Its old `if not pid:`
+ admitted 1, and on Windows it reaches `_windows_terminate_tree` without
+ passing through the POSIX helper that carries the other floor."""
+ monkeypatch.setattr(pl, "_tracked_pids", {pid: "963"})
+ monkeypatch.setattr(pl, "_tracked_pgids", {pid: pid})
+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)
+
+ pl.terminate_pid(pid, timeout = 0.01)
+
+ assert recorded_signals == []
+
+
+def test_terminate_all_never_signals_a_poisoned_tracked_pid(monkeypatch, recorded_signals):
+ """The in-memory table cannot hold a 1 now, but `terminate_all` is what runs
+ at shutdown and at `atexit`, so it carries its own floor. Nothing else covers
+ that line: the existing suites drive it with real spawned pids only."""
+ monkeypatch.setattr(pl, "_tracked_pids", {1: "963", 0: "0"})
+ monkeypatch.setattr(pl, "_tracked_pgids", {1: 1, 0: 0})
+ monkeypatch.setattr(pl, "_write_breadcrumb", lambda: None)
+
+ pl.terminate_all(timeout = 0.01)
+
+ assert recorded_signals == []
+
+
+# --- the same shape elsewhere: the llama-server group killer ---------------
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pid", [None, 0, 1, -1, True])
+def test_leading_process_group_never_returns_init(monkeypatch, pid):
+ """`getpgid(1) == 1`, so without a floor init reads as a group leader and the
+ killer below broadcasts SIGKILL with no SIGTERM grace at all."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(os, "getpgid", lambda p: p)
+ assert LlamaCppBackend._leading_process_group(pid) is None
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
[email protected]("pgid", [None, 0, 1, -1, True])
+def test_kill_process_group_sends_nothing_for_init(monkeypatch, pgid):
+ from core.inference import llama_cpp as lc
+
+ sent: "list[tuple[int, int]]" = []
+ monkeypatch.setattr(lc.os, "killpg", lambda g, s: sent.append((g, s)))
+ lc.LlamaCppBackend._kill_process_group(pgid)
+ assert sent == []
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_kill_process_group_still_kills_a_real_group(monkeypatch):
+ """The floor must not disarm the cleanup it guards."""
+ from core.inference import llama_cpp as lc
+
+ sent: "list[tuple[int, int]]" = []
+ monkeypatch.setattr(lc.os, "killpg", lambda g, s: sent.append((g, s)))
+ lc.LlamaCppBackend._kill_process_group(424242)
+ assert [g for g, _s in sent] == [424242]
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_valid_record_still_reaps(tmp_path, monkeypatch, recorded_signals):
+ """The guard must not disarm the feature it protects: a real child is still
+ signalled."""
+ import json
+
+ record = tmp_path / "999999.json"
+ record.write_text(
+ json.dumps(
+ {
+ "owner_pid": 999999,
+ "owner_identity": "111",
+ "children": [{"pid": 424242, "identity": "222", "pgid": 424242}],
+ }
+ ),
+ encoding = "utf-8",
+ )
+ monkeypatch.setattr(pl, "_breadcrumb_dir", lambda: tmp_path)
+ monkeypatch.setattr(pl, "_pid_alive", lambda pid: pid == 424242)
+ monkeypatch.setattr(pl, "_pid_is_zombie", lambda pid: False)
+ monkeypatch.setattr(pl, "_identity_or_none", lambda pid: "222")
+ monkeypatch.setattr(pl.os, "getpgid", lambda pid: pid)
+
+ reaped = pl.reap_recorded_children(timeout = 0.01)
+
+ assert 424242 in reaped
+ # The signal number is asserted, not just the pid. Without it a fully
+ # disarmed reaper passes: `_group_has_members` emits `killpg(pid, 0)` as a
+ # liveness probe, and a bare `pid == 424242` match accepts that probe as
+ # proof of a kill that never happened.
+ assert any(
+ pid == 424242 and sig == signal.SIGTERM for _call, pid, sig in recorded_signals
+ ), "a genuine orphan must still be sent a terminating signal"
+
+
+# --- the sibling reapers that read a pid off disk ---------------------------
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_llama_pidfile_reaper_refuses_init(tmp_path, monkeypatch, recorded_signals):
+ """The llama-server pidfile is the other place a pid arrives from disk rather
+ than from a live handle, which is the precondition the incident needed.
+
+ Every check behind the floor is stubbed to say yes, deliberately. Leave them
+ real and this test passes with the floor removed, because `_pid_is_llama_server(1)`
+ is False on a normal box and it is the cmdline check, not the floor, doing the
+ work. #7894 established Studio can run as a container entrypoint, and a
+ container whose entrypoint is llama-server has a process at pid 1 that answers
+ yes to all of them.
+ """
+ from core.inference import llama_cpp as lc
+
+ pidfile = tmp_path / "llama-server.pid"
+ pidfile.write_text("1:963", encoding = "utf-8")
+ monkeypatch.setattr(
+ lc.LlamaCppBackend, "_server_pidfile_path", classmethod(lambda cls: pidfile)
+ )
+ monkeypatch.setattr(lc.LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False))
+ monkeypatch.setattr(lc.LlamaCppBackend, "_pid_start_identity", staticmethod(lambda pid: "963"))
+ monkeypatch.setattr(lc.LlamaCppBackend, "_pid_is_llama_server", staticmethod(lambda pid: True))
+ monkeypatch.setattr(lc.os, "kill", lambda pid, sig: recorded_signals.append(("kill", pid, sig)))
+
+ assert lc.LlamaCppBackend._reap_recorded_pid() == 0, "init is never a reaped orphan"
+ assert recorded_signals == [], "not even with every identity check saying yes"
+ assert not pidfile.exists(), "a pidfile naming init is garbage, not something to retry"
+
+
[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")
+def test_llama_orphan_sweep_skips_init(tmp_path, monkeypatch):
+ """The orphan sweep must not kill pid 1 even when pid 1 looks exactly like an
+ owned, parentless llama-server.
+
+ That is not a contrived shape: #7894 established Studio can run as a
+ container entrypoint, and a container whose entrypoint is llama-server puts
+ a process this sweep recognises at pid 1. Killing it takes the container
+ down. The /proc scan and the psutil scan both feed one kill loop, so the
+ floor sits on the loop rather than in each scanner.
+ """
+ from core.inference import llama_cpp as llama_cpp_module
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ owned_dir = tmp_path / "unsloth-test-llama"
+ owned_dir.mkdir()
+ binary = owned_dir / "llama-server"
+ binary.write_text("x")
+
+ mypid = os.getpid()
+ root = tmp_path / "fake-proc"
+ root.mkdir()
+ for pid in (1, mypid + 1):
+ d = root / str(pid)
+ d.mkdir()
+ # Same 52-field stat shape the scanner parses; only comm and the start
+ # time field are read.
+ fields = " ".join(["0"] * 50)
+ (d / "stat").write_bytes(f"{pid} (llama-server) S {fields}".encode())
+ (d / "exe").symlink_to(binary)
+
+ killed: "list[int]" = []
+ monkeypatch.setenv("LLAMA_SERVER_PATH", str(binary))
+ monkeypatch.setattr(llama_cpp_module, "_PROC_ROOT", str(root))
+ monkeypatch.setattr(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0))
+ monkeypatch.setattr(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False))
+ monkeypatch.setattr(os, "kill", lambda pid, sig: killed.append(pid))
+
+ LlamaCppBackend._kill_orphaned_servers()
+
+ assert 1 not in killed, "the sweep must never SIGKILL init"
+ assert killed == [mypid + 1], "the genuine owned orphan must still be reaped"
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_download_registry_never_signals_init(tmp_path, monkeypatch):
+ """`reap_orphan_workers` had no test at all, so its floor had no test either:
+ reverting it to the old `pid <= 0` passed the whole suite."""
+ import json
+
+ from hub.utils import download_registry as dr
+
+ sent: "list[tuple[int, int]]" = []
+ monkeypatch.setattr(dr.os, "kill", lambda pid, sig: sent.append((pid, sig)))
+ monkeypatch.setattr(dr.state_dir, "workers_dir", lambda: tmp_path)
+ settled: "list[object]" = []
+ monkeypatch.setattr(dr, "_settle_orphaned_download", lambda *a, **k: settled.append(a))
+ monkeypatch.setattr(dr, "_boot_sweep", lambda reaped: None)
+
+ entry = tmp_path / "poisoned.json"
+ entry.write_text(
+ json.dumps({"pid": 1, "repo_type": "model", "repo_id": "Org/Model"}), encoding = "utf-8"
+ )
+
+ dr.reap_orphan_workers()
+
+ assert sent == [], "the download reaper must not signal init either"
+ assert not entry.exists(), "the poisoned breadcrumb is dropped"
+ assert settled, "the partial must still be settled, or the user re-downloads from scratch"
+
+
[email protected](not IS_POSIX, reason = "POSIX signalling path")
+def test_kill_orphan_refuses_init_on_its_own(monkeypatch):
+ """The helper that sends the signal carries the floor itself, so it does not
+ depend on every future caller having checked first."""
+ from hub.utils import download_registry as dr
+
+ sent: "list[tuple[int, int]]" = []
+ monkeypatch.setattr(dr.os, "kill", lambda pid, sig: sent.append((pid, sig)))
+ assert dr._kill_orphan(1) is False
+ assert sent == []
diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py
index fa918654215..fe8a49abac4 100644
--- a/studio/backend/utils/process_lifetime.py
+++ b/studio/backend/utils/process_lifetime.py
@@ -36,6 +36,49 @@ _PR_SET_PDEATHSIG = 1
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
_JobObjectExtendedLimitInformation = 9
+# The lowest pid this module will ever record or signal.
+#
+# kill(2) gives 0, 1 and negatives a different meaning to every other value, and
+# each of those meanings is catastrophic here:
+#
+# kill(0, sig) this process's entire group, i.e. Studio and its siblings
+# killpg(1, sig) the same call as kill(-1, sig): EVERY process the caller
+# has permission to signal, not "process group 1"
+# kill(-n, sig) process group n
+#
+# The middle one is not hypothetical. A record naming pid 1 as a child reaches
+# _posix_terminate, getpgid(1) == 1 makes it look like a group leader, and the
+# killpg branch then SIGTERMs every process belonging to the user, waits the
+# grace period, and SIGKILLs them too. Nothing rejected it on the way: the
+# identity check compares recorded start-time against current, and init's start
+# time never changes, so a recorded pid 1 matches forever.
+#
+# Guarded at both ends. Nothing below this is recorded, so the bad record cannot
+# be created, and nothing below this is signalled, so records written by an
+# older build cannot fire.
+_LOWEST_SIGNALABLE_PID = 2
+
+
+def is_signalable_pid(pid: object) -> bool:
+ """Whether `pid` names a process that may be recorded or signalled.
+
+ `bool` is excluded explicitly: it is an `int` subclass, so True would
+ otherwise read as pid 1.
+
+ Public because the floor has to hold at every signalling boundary in Studio,
+ not just this module's. It was written out by hand in four places at first,
+ and the site that got missed was missed precisely because "who enforces the
+ floor" was a question you had to answer by reading rather than by grepping
+ for one name.
+ """
+ return isinstance(pid, int) and not isinstance(pid, bool) and pid >= _LOWEST_SIGNALABLE_PID
+
+
+# The internal spelling, kept so this module's own call sites and their tests
+# read the same as before.
+_signalable = is_signalable_pid
+
+
_lock = threading.Lock()
_spawner_lock = threading.Lock()
_spawner: "Optional[_Spawner]" = None
@@ -539,7 +582,12 @@ def _group_has_members(pgid: object) -> bool:
not been waited on is still a member, so a group whose every member is a
zombie would read as alive and keep its record forever.
"""
- if not isinstance(pgid, int) or _is_windows() or not hasattr(os, "killpg"):
+ # `killpg(1, 0)` is `kill(-1, 0)`, which always succeeds, so without the floor
+ # this answers True for group 1 unconditionally. That delivers no signal, but
+ # it pins the record as unresolved: a legacy entry pairing a real pid with a
+ # poisoned pgid would then be retried on every launch forever, which is the
+ # opposite of what the reaper's drop-on-poison path is for.
+ if not _signalable(pgid) or _is_windows() or not hasattr(os, "killpg"):
return False
try:
os.killpg(pgid, 0)
@@ -644,7 +692,7 @@ def terminate_descendants(
return
live: "list[tuple[int, Optional[str]]]" = []
for pid, identity in collected:
- if not _still_the_same(pid, identity):
+ if not _signalable(pid) or not _still_the_same(pid, identity):
continue
try:
os.kill(pid, signal.SIGTERM)
@@ -918,7 +966,9 @@ def adopt_pid(pid: Optional[int]) -> None:
"""Track a child (e.g. a multiprocessing worker started after the parent job
was set up) and, on Windows, assign it to the job as belt-and-suspenders.
Tolerates a None or already-exited pid."""
- if not pid:
+ # `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
# 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
@@ -968,6 +1018,8 @@ def terminate_all(timeout: float = 5.0) -> "list[int]":
with _record_lock:
_tracked_pids.pop(pid, None)
pgid = _tracked_pgids.pop(pid, None)
+ if not _signalable(pid):
+ continue # dropped, not kept: see _LOWEST_SIGNALABLE_PID
current = _pid_identity(pid)
if not _pid_alive(pid):
# Same as the startup sweep: a leader that exited first can still
@@ -1027,7 +1079,11 @@ def terminate_pid(pid: "Optional[int]", timeout: float = 5.0) -> None:
For an owner that has to give up on a child before its own shutdown, and
cannot leave it for a sweep that will not run while this process lives.
"""
- if not pid:
+ # The public entry point, so the floor goes here rather than only in the
+ # POSIX helper below: `_windows_terminate_tree` is reached without passing
+ # through it, and a caller should not have to know which platform's path
+ # happens to carry the check.
+ if not _signalable(pid):
return
with _record_lock:
identity = _tracked_pids.get(pid)
@@ -1141,7 +1197,12 @@ def _reap_one_record(path, timeout: float) -> "tuple[list[int], bool]":
children = record.get("children")
for entry in children if isinstance(children, list) else []:
pid = entry.get("pid") if isinstance(entry, dict) else None
- if not isinstance(pid, int):
+ if not _signalable(pid):
+ # Records written by a build without the guard can name pid 1, and
+ # signalling that is a kill of everything the user owns. Dropped
+ # rather than deferred: leaving `unresolved` alone lets the record be
+ # unlinked, so a poisoned one is gone after a single startup instead
+ # of being retried on every launch forever.
continue
# A zombie is a dead leader nobody has waited on: it holds nothing, and
# signalling it would burn the whole grace period answering probes.
@@ -1214,6 +1275,8 @@ def _own_process_group(pid: int) -> Optional[int]:
pgid = os.getpgid(pid)
except Exception:
return None
+ if not _signalable(pgid):
+ return None # killpg(1) is a broadcast, killpg(0) is our own group
return pgid if pgid == pid else None
@@ -1225,8 +1288,8 @@ def _reap_orphaned_group(pgid: object, pid: int, timeout: float) -> bool:
a process group, so it cannot have been handed to an unrelated group while
members remain.
"""
- if not isinstance(pgid, int) or pgid != pid or _is_windows() or not hasattr(os, "killpg"):
- return False
+ if not _signalable(pgid) or pgid != pid or _is_windows() or not hasattr(os, "killpg"):
+ return False # killpg(1) is kill(-1); see _LOWEST_SIGNALABLE_PID
try:
os.killpg(pgid, 0) # the group is still there
except Exception:
@@ -1312,6 +1375,8 @@ def _posix_terminate(pid: int, timeout: float = 5.0) -> None:
# SIGTERM, give the child up to `timeout` to exit, then SIGKILL. Reaping
# belongs to the child's owner (or init for orphans). Prefer the group
# (covers grandchildren) when pid leads its own group.
+ if not _signalable(pid):
+ return # see _LOWEST_SIGNALABLE_PID
group_leader = False
try:
group_leader = os.getpgid(pid) == pid
@@ -1329,6 +1394,11 @@ def _posix_terminate(pid: int, timeout: float = 5.0) -> None:
def _posix_terminate_one(pid: int, group_leader: bool, timeout: float) -> None:
+ # Belt and braces with the caller: this is the last line before the signal,
+ # and killpg(1) would reach every process the user owns. See
+ # _LOWEST_SIGNALABLE_PID.
+ if not _signalable(pid):
+ return
killer = os.killpg if group_leader else os.kill
try:
killer(pid, signal.SIGTERM)