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.

Stop six backend tests waiting on the clock instead of on a signal (#8975)

Daniel Han63e371a36a2a
diff --git a/studio/backend/tests/test_child_lifetime_boundary.py b/studio/backend/tests/test_child_lifetime_boundary.py
index 2ab4567cdbd..0d41cb279f8 100644
--- a/studio/backend/tests/test_child_lifetime_boundary.py
+++ b/studio/backend/tests/test_child_lifetime_boundary.py
@@ -91,7 +91,15 @@ def _run_case(tmp_path: Path, mode: str) -> bool:
else:
os.kill(parent.pid, 9)
parent.wait(timeout = 30)
- time.sleep(5)
+ # Poll the 5s reaping grace out instead of sleeping through it. The verdict
+ # is identical -- "still alive after 5s" is still "survived" -- but where the
+ # payload does die (Linux PR_SET_PDEATHSIG) it dies in milliseconds, so the
+ # answer is available long before the window ends. Only the platforms that
+ # genuinely leak the payload now pay the full 5s, and they are the ones the
+ # window was written for.
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline and _alive(payload_pid):
+ time.sleep(0.05)
survived = _alive(payload_pid)
print(f"\n[{sys.platform}] mode={mode}: payload {payload_pid} survived = {survived}")
return survived
diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.py
index d072fab0d56..5d8390265d8 100644
--- a/studio/backend/tests/test_cloudflare_tunnel.py
+++ b/studio/backend/tests/test_cloudflare_tunnel.py
@@ -14,6 +14,7 @@ import io
import os
import sys
import tarfile
+import threading as _real_threading
import types
from pathlib import Path
from typing import Optional
@@ -350,8 +351,20 @@ def test_runtime_callback_covers_process_start_through_stop(monkeypatch):
def start(self):
pass
+ # Scope the fake Thread to cloudflare_tunnel. `setattr(ct.threading, "Thread", ...)`
+ # replaced threading.Thread for the whole process, so utils.process_lifetime's child
+ # spawner -- which start()s a helper thread and then waits up to 5s for it to signal
+ # readiness -- got a Thread whose start() does nothing and burned its full 5s backstop
+ # before falling back to an inline spawn. Rebinding the module reference on `ct`
+ # leaves the fake exactly where this test wants it.
+ class _ThreadingShim:
+ Thread = _NoReaderThread
+
+ def __getattr__(self, name):
+ return getattr(_real_threading, name)
+
monkeypatch.setattr(ct.subprocess, "Popen", fake_popen)
- monkeypatch.setattr(ct.threading, "Thread", _NoReaderThread)
+ monkeypatch.setattr(ct, "threading", _ThreadingShim())
monkeypatch.setattr(ct, "ensure_cloudflared", lambda: starts_admitted.append(True))
try:
tunnel = ct.CloudflareTunnel(8080, "/bin/cloudflared")
diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.py
index a73b68f624b..313d6aa87ed 100644
--- a/studio/backend/tests/test_openai_auto_download.py
+++ b/studio/backend/tests/test_openai_auto_download.py
@@ -1479,7 +1479,14 @@ def test_a_cold_scan_that_never_finishes_says_so_instead_of_guessing(monkeypatch
monkeypatch.setattr(resolver, "_scan", (0.0, {}))
monkeypatch.setattr(inference_route, "_COLD_INDEX_WAIT_S", 0.05)
released = threading.Event()
- monkeypatch.setattr(resolver, "_build_index", lambda: (released.wait(5), {})[1])
+ # 0.5, not 5. The scan runs on the event loop's default executor, so the
+ # `asyncio.run` below does not return until it finishes -- and the
+ # `released.set()` that would end it early sits in this test's `finally`, which
+ # cannot run until `asyncio.run` has returned. The stall is therefore always
+ # waited out in full, and 5s of it was spent after every assertion in the test
+ # had already been checked. 0.5s is still 10x the 0.05s budget the route is
+ # given, so the scan is exactly as unfinished when the 503 is asserted.
+ monkeypatch.setattr(resolver, "_build_index", lambda: (released.wait(0.5), {})[1])
warmed = []
monkeypatch.setattr(resolver, "warm_index_soon", lambda: warmed.append(1))
loaded = _Loaded("unsloth/A-GGUF", "UD-Q4_K_XL")
diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.py
index fb79c4e0d81..52cb817c06f 100644
--- a/studio/backend/tests/test_orphaned_children.py
+++ b/studio/backend/tests/test_orphaned_children.py
@@ -1991,7 +1991,15 @@ def test_the_installer_waits_for_its_validation_group_not_the_leader(tmp_path):
grandchild = int(proc.stdout.readline().strip())
assert _alive(grandchild)
- gone = installer._terminate_validation_server(proc)
+ # grace = 1.0, not the 5.0 default. Both the leader and its child ignore
+ # SIGTERM on purpose, so every one of the four grace windows inside
+ # _terminate_validation_server (leader wait, group wait, post-SIGKILL group
+ # wait, final leader wait) is paid in full: 20s of pure waiting for a test
+ # about escalation order. 1.0s is still 20x what a SIGKILLed group needs to
+ # be reaped, and the escalation under test is unchanged -- the leader still
+ # has to outlive its SIGTERM and the group still has to be SIGKILLed for
+ # `gone` to come back True.
+ gone = installer._terminate_validation_server(proc, grace = 1.0)
assert gone is True, "reported a stop with the group still up"
time.sleep(0.3)
assert not _alive(grandchild), "the leader went and its child stayed"
diff --git a/studio/backend/tests/test_startup_llama_probe_non_blocking.py b/studio/backend/tests/test_startup_llama_probe_non_blocking.py
index eb5b8d0b5ff..6831bc77b06 100644
--- a/studio/backend/tests/test_startup_llama_probe_non_blocking.py
+++ b/studio/backend/tests/test_startup_llama_probe_non_blocking.py
@@ -12,6 +12,7 @@ run on a daemon thread, and are skipped entirely when update checks are disabled
from __future__ import annotations
import sys
+import threading
import time
from pathlib import Path
@@ -25,7 +26,11 @@ import main # noqa: E402
import utils.llama_cpp_freshness as freshness # noqa: E402
from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
-SLEEP = 5.0
+# Deadlock backstops, not pacing. Nothing waits these out on a passing run: the
+# freshness stub blocks until the test releases it, and the test releases it as
+# soon as the non-blocking claim has been checked. They exist so a regression
+# hangs for 30s and fails rather than hanging CI forever.
+_BACKSTOP_S = 30.0
class _FakeApp:
@@ -57,10 +62,19 @@ def _fast_capability_probe(monkeypatch):
def test_probe_does_not_block_startup(monkeypatch):
"""`_start_llama_cpp_probes_if_enabled` returns immediately even though the
- freshness check sleeps for SLEEP seconds, then populates app.state later."""
+ freshness check is still stalled, then populates app.state later."""
+
+ entered = threading.Event()
+ release = threading.Event()
def _slow_freshness(_bin, **_kw):
- time.sleep(SLEEP)
+ # Blocks until the test lets it go rather than for a fixed number of
+ # seconds. Strictly stronger than the old `time.sleep(5)`: the check is
+ # stalled for as long as the caller-blocking assertion needs it to be,
+ # so a probe that ran inline would hang here forever instead of merely
+ # being 5s slow, and the suite pays no wall clock for it.
+ entered.set()
+ assert release.wait(_BACKSTOP_S), "the test never released the freshness check"
return {"stale": False, "behind": False}
monkeypatch.setattr(freshness, "check_prebuilt_freshness", _slow_freshness)
@@ -72,10 +86,15 @@ def test_probe_does_not_block_startup(monkeypatch):
assert elapsed < 0.5, f"startup probe blocked the caller for {elapsed:.2f}s"
- # The daemon thread eventually populates app.state once the slow check returns.
- deadline = time.monotonic() + SLEEP + 5
+ # The stall has to be real for the timing above to mean anything: the probe
+ # must actually be sitting inside the freshness check while the caller runs on.
+ assert entered.wait(_BACKSTOP_S), "the probe thread never reached the freshness check"
+ release.set()
+
+ # The daemon thread eventually populates app.state once the check returns.
+ deadline = time.monotonic() + _BACKSTOP_S
while app.state.llama_cpp_freshness is None and time.monotonic() < deadline:
- time.sleep(0.1)
+ time.sleep(0.01)
assert app.state.llama_cpp_freshness == {"stale": False, "behind": False}
@@ -91,8 +110,16 @@ def test_disable_env_skips_probe_entirely(monkeypatch):
monkeypatch.setenv("UNSLOTH_DISABLE_UPDATE_CHECK", "1")
app = _FakeApp()
+ before = {t for t in threading.enumerate()}
main._start_llama_cpp_probes_if_enabled(app)
- time.sleep(0.5)
+ # Checked, not slept for. The old `time.sleep(0.5)` only proved the probe had
+ # not called back *within 0.5s*; enumerating the threads proves no probe thread
+ # was ever created, which is what "skips the probe entirely" means, and it is
+ # true the instant the call returns.
+ started = [
+ t for t in threading.enumerate() if t not in before and t.name == "llama-cpp-startup-probe"
+ ]
+ assert started == [], "a probe thread was started despite UNSLOTH_DISABLE_UPDATE_CHECK=1"
assert calls == [], "freshness check ran despite UNSLOTH_DISABLE_UPDATE_CHECK=1"
assert app.state.llama_cpp_freshness is None
diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.py
index 1077bce6b98..449d0686c44 100644
--- a/studio/backend/tests/test_tool_output_streaming.py
+++ b/studio/backend/tests/test_tool_output_streaming.py
@@ -43,6 +43,45 @@ from core.inference.tools import _bash_exec, _python_exec
from test_llama_cpp_tool_loop import _done, _make_backend, _sse
+# ── grandchild-survival probes ───────────────────────────────────
+#
+# Several tests below prove a negative: a backgrounded grandchild that holds the
+# leader's stdout open must NOT get to write its sentinel, because the drain is
+# required to kill the process group. Proving that used to mean giving the
+# grandchild a fixed `sleep 3` fuse and then sleeping 4s past it, which spends 4
+# real seconds per test doing nothing, and is itself scheduling-sensitive (a
+# runner that stalls the grandchild by more than a second turns a genuine leak
+# into a pass).
+#
+# Instead the grandchild now spins on a gate file the test owns, so it lives
+# indefinitely -- which is a stronger guarantee that it outlives the finite
+# timeout than "3 > 1" was -- and fires the instant the test opens the gate. A
+# grandchild that survived the group kill writes its sentinel within one poll
+# interval of the gate appearing, so a short bounded window detects the leak;
+# a grandchild that was killed can never write it, gate or no gate.
+
+_GATE_POLL_S = 0.02
+# How long a surviving grandchild is given to notice the gate and write. Two
+# orders of magnitude over its own poll interval; a leak shows up in ~20ms.
+_LEAK_WINDOW_S = 1.0
+
+
+def _gated_grandchild_sh(gate: Path, sentinel: Path) -> str:
+ """Shell for a grandchild that holds stdout and writes *sentinel* once *gate* exists."""
+ return f"while [ ! -f '{gate}' ]; do sleep {_GATE_POLL_S}; done; touch '{sentinel}'"
+
+
+def _assert_grandchild_was_killed(gate: Path, sentinel: Path) -> None:
+ """Open the gate, then require the sentinel to stay absent for the whole window."""
+ gate.write_text("go")
+ deadline = time.monotonic() + _LEAK_WINDOW_S
+ while time.monotonic() < deadline:
+ assert (
+ not sentinel.exists()
+ ), "a grandchild survived the process-group kill and wrote its sentinel"
+ time.sleep(0.02)
+
+
def _run_stream(invoke, **kwargs):
"""Drive the wrapper generator; return (events, result)."""
gen = stream_tool_execution(invoke, **kwargs)
@@ -539,11 +578,11 @@ def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
# the reaped parent leaves the grandchild running; the drain must kill the
# process group captured before the wait so the grandchild never writes.
sentinel = tmp_path / "grandchild_ran"
- command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ 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)
assert "timed out" in result
- time.sleep(4.0) # past the grandchild's 3s sleep
- assert not sentinel.exists(), "grandchild survived the timeout process-group kill"
+ _assert_grandchild_was_killed(gate, sentinel)
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
@@ -553,26 +592,26 @@ def test_bash_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
# unless the group captured right after spawn is killed too. Must match the
# streaming path's exited-leader handling.
sentinel = tmp_path / "grandchild_ran"
- command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ gate = tmp_path / "gate"
+ command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
result = _bash_exec(command, timeout = 1) # no output_callback -> communicate path
assert "timed out" in result
- time.sleep(4.0)
- assert not sentinel.exists(), "non-streaming timeout leaked a stdout-holding grandchild"
+ _assert_grandchild_was_killed(gate, sentinel)
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
def test_python_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
sentinel = tmp_path / "grandchild_ran"
+ gate = tmp_path / "gate"
code = (
"import subprocess\n"
- f"subprocess.Popen(['bash', '-c', \"sleep 3; touch '{sentinel}'\"])\n"
+ f"subprocess.Popen(['bash', '-c', \"{_gated_grandchild_sh(gate, sentinel)}\"])\n"
"print('parent-done')\n"
"import time; time.sleep(30)\n"
)
result = _python_exec(code, timeout = 1) # no output_callback -> communicate path
assert "timed out" in result
- time.sleep(4.0)
- assert not sentinel.exists(), "non-streaming timeout leaked a stdout-holding grandchild"
+ _assert_grandchild_was_killed(gate, sentinel)
def test_drain_process_output_without_posix_process_group_apis(monkeypatch):
@@ -608,8 +647,9 @@ def test_captured_group_survives_fast_leader_reap(tmp_path):
from core.inference.tools import _capture_process_group, _drain_process_output
sentinel = tmp_path / "grandchild_ran"
+ gate = tmp_path / "gate"
proc = _sp.Popen(
- ["bash", "-c", f"( sleep 3; touch '{sentinel}' ) & echo parent-done"],
+ ["bash", "-c", f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"],
stdout = _sp.PIPE,
stderr = _sp.STDOUT,
text = True,
@@ -622,8 +662,7 @@ def test_captured_group_survives_fast_leader_reap(tmp_path):
output, timed_out = _drain_process_output(proc, 0.5, None, pgid = pgid)
assert timed_out
assert "parent-done" in output
- time.sleep(4.0)
- assert not sentinel.exists(), "pre-captured group failed to reap the grandchild"
+ _assert_grandchild_was_killed(gate, sentinel)
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
@@ -638,14 +677,18 @@ def test_finite_drain_honors_cancel_after_leader_exit(tmp_path):
from core.inference.tools import _capture_process_group, _drain_process_output
sentinel = tmp_path / "grandchild_late"
+ gate = tmp_path / "gate"
# Grandchild holds the pipe open, streams every 0.2s, and touches the sentinel
- # only after 10s -- well past the cancel. The leader exits immediately, so the
- # drain enters the finite branch with a live, chatty reader.
+ # only once the test opens the gate -- which it does after the cancel. Gate,
+ # not a 10s fuse: the old version had to be slept past in full (11s), and it
+ # also silently weakened if the loop ever ran fast enough to finish early.
+ # The leader exits immediately, so the drain enters the finite branch with a
+ # live, chatty reader either way.
proc = _sp.Popen(
[
"bash",
"-c",
- "( for i in $(seq 1 100); do echo tick-$i; sleep 0.2; done; "
+ f"( while [ ! -f '{gate}' ]; do echo tick; sleep 0.2; done; "
f"touch '{sentinel}' ) & echo parent-done",
],
stdout = _sp.PIPE,
@@ -669,8 +712,7 @@ def test_finite_drain_honors_cancel_after_leader_exit(tmp_path):
# Cancellation is not a timeout: the budget never elapsed.
assert not timed_out
assert "parent-done" in output
- time.sleep(11.0) # past the grandchild's 10s sentinel write
- assert not sentinel.exists(), "cancel did not kill the stdout-holding grandchild group"
+ _assert_grandchild_was_killed(gate, sentinel)
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
@@ -688,10 +730,11 @@ def test_streamed_wait_timeout_kills_grandchild_when_leader_reaped(tmp_path, mon
monkeypatch.setattr(_tools_mod, "_kill_process_tree", lambda proc: None)
sentinel = tmp_path / "grandchild_ran"
+ gate = tmp_path / "gate"
# Leader sleeps past the timeout so proc.wait() genuinely times out; a same-group
# grandchild holds stdout and would touch the sentinel unless the group is killed.
proc = _sp.Popen(
- ["bash", "-c", f"( sleep 3; touch '{sentinel}' ) & sleep 30"],
+ ["bash", "-c", f"( {_gated_grandchild_sh(gate, sentinel)} ) & sleep 30"],
stdout = _sp.PIPE,
stderr = _sp.STDOUT,
text = True,
@@ -702,11 +745,7 @@ def test_streamed_wait_timeout_kills_grandchild_when_leader_reaped(tmp_path, mon
output, timed_out = _drain_process_output(proc, 0.5, None, pgid = pgid)
assert timed_out
- time.sleep(4.0) # past the grandchild's 3s sleep
- assert not sentinel.exists(), (
- "streamed wait timeout leaked a stdout-holding grandchild when the "
- "process-tree kill short-circuited on the reaped leader"
- )
+ _assert_grandchild_was_killed(gate, sentinel)
# ── GGUF loop regression: model-visible messages unchanged ───────
@@ -1207,7 +1246,8 @@ def test_bash_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_pa
# the fix communicate() blocked until the grandchild finished. The unified drain
# kills the captured group on cancel instead.
sentinel = tmp_path / "grandchild_ran"
- command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ gate = tmp_path / "gate"
+ command = f"( {_gated_grandchild_sh(gate, sentinel)} ) & echo parent-done"
cancel_event = threading.Event()
timer = threading.Timer(0.5, cancel_event.set)
timer.start()
@@ -1218,16 +1258,16 @@ def test_bash_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_pa
timer.cancel()
assert time.monotonic() - started < 2.5
assert result == "Execution cancelled."
- time.sleep(3.5)
- assert not sentinel.exists(), "non-streaming cancel leaked a stdout-holding grandchild"
+ _assert_grandchild_was_killed(gate, sentinel)
@pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")
def test_python_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_path):
sentinel = tmp_path / "grandchild_ran"
+ gate = tmp_path / "gate"
code = (
"import subprocess\n"
- f"subprocess.Popen(['bash', '-c', \"sleep 3; touch '{sentinel}'\"])\n"
+ f"subprocess.Popen(['bash', '-c', \"{_gated_grandchild_sh(gate, sentinel)}\"])\n"
"print('parent-done')\n"
)
cancel_event = threading.Event()
@@ -1240,5 +1280,4 @@ def test_python_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_
timer.cancel()
assert time.monotonic() - started < 2.5
assert result == "Execution cancelled."
- time.sleep(3.5)
- assert not sentinel.exists(), "non-streaming cancel leaked a stdout-holding grandchild"
+ _assert_grandchild_was_killed(gate, sentinel)