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: stop Terminal calls hanging when a command starts a background process (#16210)

Nilay63e18a1fcc88
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index b2323595597..3dd59407071 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -20018,6 +20018,31 @@ class _WindowsToolJob:
return False
return bool(self._kernel32.TerminateJobObject(self._handle, 1))
+ def active_processes(self) -> "int | None":
+ """JOBOBJECT_BASIC_ACCOUNTING_INFORMATION.ActiveProcesses; None when the query fails."""
+ if not self._handle:
+ return None
+ import ctypes
+
+ class _Accounting(ctypes.Structure):
+ _fields_ = [("times", ctypes.c_int64 * 4)] + [
+ (name, ctypes.c_uint32)
+ for name in (
+ "TotalPageFaultCount",
+ "TotalProcesses",
+ "ActiveProcesses",
+ "TotalTerminatedProcesses",
+ )
+ ]
+
+ info = _Accounting()
+ # 1 = JobObjectBasicAccountingInformation
+ if not self._kernel32.QueryInformationJobObject(
+ self._handle, 1, ctypes.byref(info), ctypes.sizeof(info), None
+ ):
+ return None
+ return info.ActiveProcesses
+
def close(self) -> None:
handle, self._handle = self._handle, None
if handle:
@@ -20048,6 +20073,14 @@ def _windows_job_capture(proc) -> "_WindowsToolJob | None":
kernel32.AssignProcessToJobObject.restype = BOOL
kernel32.TerminateJobObject.argtypes = [H, UINT]
kernel32.TerminateJobObject.restype = BOOL
+ kernel32.QueryInformationJobObject.argtypes = [
+ H,
+ ctypes.c_int,
+ ctypes.c_void_p,
+ wintypes.DWORD,
+ ctypes.c_void_p,
+ ]
+ kernel32.QueryInformationJobObject.restype = BOOL
kernel32.CloseHandle.argtypes = [H]
kernel32.CloseHandle.restype = BOOL
@@ -20143,6 +20176,22 @@ def _killpg_captured(pgid) -> None:
pass
+def _captured_group_alive(pgid) -> bool:
+ """False when no member provably remains; a pid-only Windows capture cannot tell, nor kill one."""
+ if pgid is None:
+ return False
+ if isinstance(pgid, tuple):
+ if pgid[0] != "windows-job":
+ return False
+ active = pgid[1].active_processes()
+ return active is None or active > 0
+ try:
+ os.killpg(pgid, 0)
+ except (ProcessLookupError, PermissionError, OSError):
+ return False
+ return True
+
+
def _cancel_watcher(
proc,
cancel_event,
@@ -21240,6 +21289,13 @@ def _missing_path_hint(output: str, workdir: str | None = None) -> str:
# Kept past the spill's head so a trailing traceback still reaches `_missing_path_hint`; also the drain's read size.
_DRAIN_TAIL_CHARS = 64 * 1024
+_DRAIN_EOF_GRACE_S = 1.5
+# A holder that never lets the reader go quiet is still stopped this long after the leader exits.
+_DRAIN_BUSY_CAP_S = 10.0
+_BACKGROUND_STOPPED_NOTE = (
+ "[Background processes still writing to this output were stopped when the command exited. "
+ "To keep one running, redirect its output to a file, e.g. `nohup cmd > out.log 2>&1 &`.]\n"
+)
def _drain_process_output(
@@ -21254,13 +21310,14 @@ def _drain_process_output(
chunks: list[str] = []
tail: "deque[str]" = deque()
kept = joined = tail_chars = omitted_chars = omitted_lines = 0
+ last_read = time.monotonic()
# Captured before waiting so a pipe-holding grandchild can be killed after the leader is reaped.
if pgid is None:
pgid = _capture_process_group(proc)
def _reader() -> None:
- nonlocal kept, joined, tail_chars, omitted_chars, omitted_lines
+ nonlocal kept, joined, tail_chars, omitted_chars, omitted_lines, last_read
try:
# Sized reads: a newline-free stream would otherwise arrive as one unbounded "line".
for line in iter(lambda: proc.stdout.readline(_DRAIN_TAIL_CHARS), ""):
@@ -21285,6 +21342,7 @@ def _drain_process_output(
output_callback(line)
except Exception: # noqa: BLE001 - observer must never kill the tool
logger.debug("tool output_callback raised", exc_info = True)
+ last_read = time.monotonic()
except (ValueError, OSError):
pass # pipe closed during kill
@@ -21303,30 +21361,38 @@ def _drain_process_output(
proc.wait(timeout = 5)
except subprocess.TimeoutExpired:
pass
- # A grandchild that inherited stdout can hold the pipe open past the main process's exit.
+ # A grandchild holding the inherited stdout outlives the leader: stop the group once the reader has
+ # sat idle for the grace, so a slow drain never kills a redirected background job.
+ background_stopped = False
if not timed_out:
- if timeout is not None:
- # Poll cancel_event in slices: the cancel watcher is gone once the leader exits.
- deadline = started_at + timeout
- while reader.is_alive():
- remaining = deadline - time.monotonic()
- if remaining <= 0:
- timed_out = True
- _killpg_captured(pgid)
- break
- if cancel_event is not None and cancel_event.is_set():
- _killpg_captured(pgid)
- break
- reader.join(timeout = min(0.5, remaining))
- else:
- # Unlimited timeout drains until the pipe closes, like communicate(timeout=None); cancel stops it.
- while reader.is_alive():
- if cancel_event is not None and cancel_event.is_set():
- _killpg_captured(pgid)
- break
- reader.join(timeout = 0.5)
+ exited_at = time.monotonic()
+ deadline = None if timeout is None else started_at + timeout
+ # Poll cancel_event in slices: the cancel watcher is gone once the leader exits.
+ while reader.is_alive():
+ if cancel_event is not None and cancel_event.is_set():
+ _killpg_captured(pgid)
+ break
+ now = time.monotonic()
+ past_deadline = deadline is not None and now >= deadline
+ give_up = (
+ now - max(exited_at, last_read) >= _DRAIN_EOF_GRACE_S
+ or now - exited_at >= _DRAIN_BUSY_CAP_S
+ or past_deadline
+ )
+ if give_up and _captured_group_alive(pgid):
+ _killpg_captured(pgid)
+ background_stopped = True
+ break
+ if past_deadline:
+ timed_out = True
+ _killpg_captured(pgid)
+ break
+ reader.join(timeout = 0.25)
reader.join(timeout = 5)
- return "".join(chunks) + "".join(tail), timed_out, (omitted_chars, omitted_lines)
+ output = "".join(chunks) + "".join(tail)
+ if background_stopped:
+ output += ("\n" if output and not output.endswith("\n") else "") + _BACKGROUND_STOPPED_NOTE
+ return output, timed_out, (omitted_chars, omitted_lines)
_MAX_REPORTED_FILES = 25
diff --git a/studio/backend/tests/test_drain_background_process.py b/studio/backend/tests/test_drain_background_process.py
new file mode 100644
index 00000000000..fe2fb72f248
--- /dev/null
+++ b/studio/backend/tests/test_drain_background_process.py
@@ -0,0 +1,215 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A backgrounded process holding stdout must not stall a call whose leader already exited."""
+
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+from core.inference.tools import (
+ _bash_exec,
+ _capture_process_group,
+ _drain_process_output,
+ _killpg_captured,
+)
+
+posix_only = pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
+
+
+def _spawn(script):
+ proc = subprocess.Popen(
+ ["bash", "-c", script],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ stdin = subprocess.DEVNULL,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ start_new_session = True,
+ )
+ return proc, _capture_process_group(proc)
+
+
+def _spawn_py(code):
+ # Windows has no sessions: _capture_process_group puts the leader in a job object instead.
+ extra = {} if sys.platform == "win32" else {"start_new_session": True}
+ proc = subprocess.Popen(
+ [sys.executable, "-c", code],
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ stdin = subprocess.DEVNULL,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ **extra,
+ )
+ return proc, _capture_process_group(proc)
+
+
+def _group_alive(pgid):
+ proc_dir = Path("/proc")
+ if proc_dir.is_dir():
+ for stat in proc_dir.glob("[0-9]*/stat"):
+ try:
+ fields = stat.read_text().rsplit(")", 1)[1].split()
+ except (OSError, IndexError):
+ continue
+ # A reparented zombie is harmless; only a running member counts.
+ if int(fields[2]) == pgid and fields[0] != "Z":
+ return True
+ return False
+ try:
+ os.killpg(pgid, 0)
+ except ProcessLookupError:
+ return False
+ return True
+
+
+def _assert_group_gone(pgid):
+ deadline = time.monotonic() + 3
+ while _group_alive(pgid) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not _group_alive(pgid), "the backgrounded process outlived the call"
+
+
+def _cleanup(pgid):
+ try:
+ os.killpg(pgid, 9)
+ except OSError:
+ pass
+
+
+@posix_only
+def test_backgrounded_process_does_not_stall_finite_drain():
+ proc, pgid = _spawn("sleep 30 & echo started")
+ try:
+ started = time.monotonic()
+ output, timed_out, _ = _drain_process_output(proc, 10, None, pgid = pgid)
+ elapsed = time.monotonic() - started
+ assert elapsed < 5, f"drain waited {elapsed:.1f}s for the backgrounded sleep"
+ assert not timed_out
+ assert proc.returncode == 0
+ assert output.startswith("started\n")
+ assert "nohup" in output
+ _assert_group_gone(pgid)
+ finally:
+ _cleanup(pgid)
+
+
+@posix_only
+def test_backgrounded_process_does_not_stall_unlimited_drain():
+ proc, pgid = _spawn("sleep 30 & echo started")
+ result = {}
+
+ def drain():
+ result["value"] = _drain_process_output(proc, None, None, pgid = pgid)
+
+ try:
+ started = time.monotonic()
+ worker = threading.Thread(target = drain, daemon = True)
+ worker.start()
+ worker.join(timeout = 8)
+ assert not worker.is_alive(), "timeout=None drain hung on the backgrounded sleep"
+ assert time.monotonic() - started < 5
+ output, timed_out, _ = result["value"]
+ assert not timed_out
+ assert proc.returncode == 0
+ assert "started" in output
+ _assert_group_gone(pgid)
+ finally:
+ _cleanup(pgid)
+
+
+@posix_only
[email protected]("timeout", [10, None])
+def test_short_lived_background_output_is_still_captured(timeout):
+ proc, pgid = _spawn("( sleep 0.3; echo late ) & echo early")
+ try:
+ output, timed_out, _ = _drain_process_output(proc, timeout, None, pgid = pgid)
+ assert not timed_out
+ assert output == "early\nlate\n"
+ finally:
+ _cleanup(pgid)
+
+
[email protected]("timeout", [10, None])
+def test_slow_consumer_is_not_reported_as_a_stopped_background_process(timeout):
+ # The grace expires while the reader is still busy; with the group empty, nothing was stopped.
+ proc, pgid = _spawn_py("print('one'); print('two'); print('three')")
+ try:
+ output, timed_out, _ = _drain_process_output(
+ proc, timeout, lambda _line: time.sleep(0.8), pgid = pgid
+ )
+ assert not timed_out
+ assert output.splitlines() == ["one", "two", "three"]
+ finally:
+ _killpg_captured(pgid)
+
+
+@posix_only
+def test_slow_consumer_leaves_a_redirected_background_job_running():
+ proc, pgid = _spawn("sleep 30 >/dev/null 2>&1 & echo $!; echo one; echo two; echo three")
+ try:
+ output, timed_out, _ = _drain_process_output(
+ proc, 20, lambda _line: time.sleep(0.8), pgid = pgid
+ )
+ assert not timed_out
+ assert "nohup" not in output
+ bg_pid = int(output.splitlines()[0])
+ os.kill(bg_pid, 0)
+ finally:
+ _cleanup(pgid)
+
+
+@posix_only
+def test_background_job_that_never_goes_quiet_is_still_stopped():
+ proc, pgid = _spawn("( while :; do echo tick; sleep 0.1; done ) & echo started")
+ try:
+ started = time.monotonic()
+ output, timed_out, _ = _drain_process_output(proc, None, None, pgid = pgid)
+ assert time.monotonic() - started < 15
+ assert not timed_out
+ assert "started\n" in output
+ assert "nohup" in output
+ _assert_group_gone(pgid)
+ finally:
+ _cleanup(pgid)
+
+
+def test_child_holding_stdout_is_stopped_on_every_platform():
+ code = (
+ "import subprocess, sys\n"
+ "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])\n"
+ "print('started', flush=True)\n"
+ )
+ proc, pgid = _spawn_py(code)
+ try:
+ started = time.monotonic()
+ output, timed_out, _ = _drain_process_output(proc, 20, None, pgid = pgid)
+ assert time.monotonic() - started < 8
+ assert not timed_out
+ assert output.startswith("started")
+ assert "nohup" in output
+ finally:
+ _killpg_captured(pgid)
+
+
+@posix_only
+def test_bash_exec_reports_the_command_not_a_timeout():
+ started = time.monotonic()
+ result = _bash_exec("sleep 30 & echo started", timeout = 10, disable_sandbox = True)
+ elapsed = time.monotonic() - started
+ assert elapsed < 5, f"Terminal call stalled {elapsed:.1f}s on a backgrounded process"
+ assert "started" in result
+ assert "timed out" not in result
+ assert not result.startswith("Exit code")
diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.py
index ac0220faa5d..56f187ec09a 100644
--- a/studio/backend/tests/test_tool_output_streaming.py
+++ b/studio/backend/tests/test_tool_output_streaming.py
@@ -572,31 +572,28 @@ def test_bash_exec_invalid_utf8_identical_with_streaming():
_os_isolated_tools(),
reason = "a PID namespace kills the background job with the leader; see below",
)
-def test_bash_exec_unlimited_timeout_waits_for_grandchild_output():
- # With timeout=None the drain waits for EOF like communicate(), keeping late output.
+def test_bash_exec_unlimited_timeout_stops_grandchild_holding_stdout():
+ # Like the PID namespace, a job still holding stdout after the leader exits ends with the call.
command = "( sleep 7; echo late-grandchild-output ) & echo parent-done"
chunks: list[str] = []
+ started = time.monotonic()
result = _bash_exec(command, timeout = None, output_callback = chunks.append)
+ assert time.monotonic() - started < 5
assert "parent-done" in result
- assert "late-grandchild-output" in result
- assert "late-grandchild-output" in "".join(chunks)
+ assert "late-grandchild-output" not in result
+ assert "late-grandchild-output" not in "".join(chunks)
@pytest.mark.skipif(
not _os_isolated_tools(), reason = "no PID namespace here, so nothing reaps the job"
)
def test_bash_exec_unlimited_timeout_does_not_wait_for_a_job_the_namespace_reaps():
- from core.inference import tools as tools_module
-
command = "( sleep 7; echo late-grandchild-output ) & echo parent-done"
started = time.monotonic()
result = _bash_exec(command, timeout = None, output_callback = lambda _t: None)
elapsed = time.monotonic() - started
assert "parent-done" in result
- if tools_module._last_tool_execution_record.os_isolation:
- assert elapsed < 5
- else:
- assert "late-grandchild-output" in result
+ assert elapsed < 5
def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
@@ -605,8 +602,8 @@ def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
gate = tmp_path / "gate"
command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
result = _bash_exec(command, timeout = 1, output_callback = lambda _t: None)
- if not _os_isolated_tools():
- assert "timed out" in result
+ assert "parent-done" in result
+ assert "timed out" not in result
_assert_grandchild_was_killed(gate, sentinel)
@@ -617,8 +614,8 @@ def test_bash_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
gate = tmp_path / "gate"
command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
result = _bash_exec(command, timeout = 1)
- if not _os_isolated_tools():
- assert "timed out" in result
+ assert "parent-done" in result
+ assert "timed out" not in result
_assert_grandchild_was_killed(gate, sentinel)
@@ -679,7 +676,7 @@ def test_captured_group_survives_fast_leader_reap(tmp_path):
proc.wait()
output, timed_out, _ = _drain_process_output(proc, 0.5, None, pgid = pgid)
- assert timed_out
+ assert not timed_out
assert "parent-done" in output
_assert_grandchild_was_killed(gate, sentinel)