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: let workers spawn the killable Hugging Face prefetch child (#9625)

oobabooga718fbf8613e5
diff --git a/studio/backend/tests/test_process_lifetime.py b/studio/backend/tests/test_process_lifetime.py
index 9dd5c3a1479..7bd411cddf0 100644
--- a/studio/backend/tests/test_process_lifetime.py
+++ b/studio/backend/tests/test_process_lifetime.py
@@ -9,6 +9,7 @@ Windows Job Object path is exercised with a mocked kernel32 so it runs on CI.
from __future__ import annotations
+import multiprocessing.process
import os
import signal
import subprocess
@@ -421,3 +422,114 @@ def test_windows_job_install_degrades_on_assign_failure(monkeypatch):
pl._install_windows_job()
assert pl._win_job_handle is None # not retained when assignment fails
assert "close" in log # the orphaned job handle is closed
+
+
+# Daemonic workers spawning children (#9094)
+
+
+_NESTED_CHILD_SCRIPT = """
+import multiprocessing as mp
+import sys
+
+sys.path.insert(0, {backend!r})
+
+CTX = mp.get_context("spawn")
+
+
+def _grandchild(marker):
+ with open(marker, "w") as handle:
+ handle.write("ran")
+
+
+def _worker(queue, marker):
+ try:
+ proc = CTX.Process(target = _grandchild, args = (marker,), daemon = True)
+ proc.start()
+ proc.join(30)
+ queue.put("started exit={{}}".format(proc.exitcode))
+ except Exception as exc:
+ queue.put("refused {{}}: {{}}".format(type(exc).__name__, exc))
+
+
+def _no_shim(target, *args, **kwargs):
+ return target(*args, **kwargs)
+
+
+if __name__ == "__main__":
+ from utils.native_path_leases import run_without_native_path_secret
+
+ arm, marker = sys.argv[1], sys.argv[2]
+ entry = run_without_native_path_secret if arm == "shim" else _no_shim
+ queue = CTX.Queue()
+ worker = CTX.Process(target = entry, args = (_worker, queue, marker), daemon = True)
+ worker.start()
+ print("parent-sees-daemon", worker.daemon, flush = True)
+ print("worker", queue.get(timeout = 60), flush = True)
+ worker.join(30)
+"""
+
+
+def _run_nested_child_arm(tmp_path, arm: str) -> tuple[str, bool]:
+ script = tmp_path / f"nested_{arm}.py"
+ script.write_text(_NESTED_CHILD_SCRIPT.format(backend = str(_BACKEND)))
+ marker = tmp_path / f"grandchild_{arm}.txt"
+ proc = subprocess.run(
+ [sys.executable, str(script), arm, str(marker)],
+ capture_output = True,
+ text = True,
+ timeout = 180,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return proc.stdout, marker.exists()
+
+
+ not __debug__,
+ reason = "CPython's daemonic-children guard is an assert, so -O strips it and a "
+ "daemonic worker spawns freely -- this arm would assert the opposite of "
+ "what it means",
+)
+def test_daemonic_worker_cannot_spawn_children_without_the_shim(tmp_path):
+ stdout, grandchild_ran = _run_nested_child_arm(tmp_path, "plain")
+ assert "refused AssertionError: daemonic processes are not allowed to have children" in stdout
+ assert not grandchild_ran
+
+
+def test_daemonic_worker_spawns_children_through_the_shim(tmp_path):
+ stdout, grandchild_ran = _run_nested_child_arm(tmp_path, "shim")
+ assert "worker started exit=0" in stdout
+ assert grandchild_ran
+ # The parent still sees the worker as daemonic.
+ assert "parent-sees-daemon True" in stdout
+
+
+def test_allow_child_processes_clears_only_the_daemon_bit(monkeypatch):
+ # Do not mutate the pytest process's real multiprocessing config.
+ config = {"daemon": True, "authkey": b"secret", "semprefix": "/mp"}
+ monkeypatch.setattr(
+ multiprocessing.process, "current_process", lambda: type("P", (), {"_config": config})()
+ )
+ pl.allow_child_processes()
+ assert config == {"daemon": False, "authkey": b"secret", "semprefix": "/mp"}
+
+
+def test_allow_child_processes_survives_a_missing_config(monkeypatch):
+ monkeypatch.setattr(multiprocessing.process, "current_process", lambda: type("P", (), {})())
+ pl.allow_child_processes()
+
+
+def test_an_older_process_lifetime_still_gets_the_parent_death_binding(monkeypatch):
+ """A tree without `allow_child_processes` must keep the binding that predates it.
+
+ Importing both names in one statement would raise ImportError for the whole
+ block, costing the worker its parent-death binding as well.
+ """
+ from utils import native_path_leases
+
+ calls = []
+ monkeypatch.setattr(pl, "bind_current_process_to_parent_lifetime", lambda: calls.append("bind"))
+ monkeypatch.delattr(pl, "allow_child_processes")
+
+ native_path_leases.run_without_native_path_secret(lambda: None)
+
+ assert calls == ["bind"]
diff --git a/studio/backend/utils/native_path_leases.py b/studio/backend/utils/native_path_leases.py
index b66087f128c..ce28bb8f957 100644
--- a/studio/backend/utils/native_path_leases.py
+++ b/studio/backend/utils/native_path_leases.py
@@ -122,11 +122,19 @@ def run_without_native_path_secret(
# Runs in the spawned child: bind it to the parent's death (Linux), since
# multiprocessing children cannot be given a preexec_fn by the parent. Shared
# entrypoint for the inference/export/training/data-recipe workers.
+ # Two try blocks, not one: allow_child_processes is the newer name, so on an
+ # older process_lifetime.py a combined import would lose the binding as well.
try:
from utils.process_lifetime import bind_current_process_to_parent_lifetime
bind_current_process_to_parent_lifetime()
except Exception:
pass
+ try:
+ # Clear the worker's daemon policy so HF prefetch can spawn (#9094).
+ from utils.process_lifetime import allow_child_processes
+ allow_child_processes()
+ except Exception:
+ pass
global _CACHED_LEASE_SECRET, _SCRUB_SAVED_SECRET
os.environ.pop(LEASE_SECRET_ENV, None)
diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py
index fe8a49abac4..04b9caaad52 100644
--- a/studio/backend/utils/process_lifetime.py
+++ b/studio/backend/utils/process_lifetime.py
@@ -334,6 +334,26 @@ def bind_current_process_to_parent_lifetime() -> None:
pass
+def allow_child_processes() -> None:
+ """Allow the current multiprocessing worker to spawn children (#9094).
+
+ Children inherit the cleared flag, since `Process.__init__` copies `_config`.
+ A grandchild that does not pass `daemon =` itself is therefore non-daemonic,
+ and `_exit_function` joins those unconditionally and without a timeout, so it
+ would hold the worker's exit open forever. Everything a worker reaches today
+ passes `daemon = True`; keep it that way.
+ """
+ try:
+ from multiprocessing import process as multiprocessing_process
+
+ # This config is child-local; the parent's Process handle stays daemonic.
+ config = getattr(multiprocessing_process.current_process(), "_config", None)
+ if isinstance(config, dict):
+ config["daemon"] = False
+ except Exception:
+ pass
+
+
def compose_preexec(
existing: Optional[Callable[[], None]], owner_pid: Optional[int] = None
) -> Optional[Callable[[], None]]: