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 the desktop health watchdog killing a backend that is busy generating (#8990)

Michael Han0488fe094a01
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 2bb2e5491e8..10ffa7ef031 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1574,6 +1574,23 @@ def _torch_warm_in_progress() -> bool:
return bool(status["started"] and not status["finished"] and status["alive"])
+def _inference_active() -> bool:
+ """True while at least one generation is in flight.
+
+ Published so the desktop health watchdog can tell a backend that is busy serving from
+ one that has died: a saturated host can stall the event loop past a probe budget, and
+ killing there ends a response the user is still waiting on.
+
+ A len() under a threading.Lock held only for that read, so the route stays cheap.
+ Failures report "not busy", the same answer as before this field existed.
+ """
+ try:
+ from state import active_generations
+ return active_generations.count() > 0
+ except Exception:
+ return False
+
+
@app.get("/api/liveness")
async def liveness_check():
"""Cheap process liveness for desktop port validation."""
@@ -1599,6 +1616,12 @@ async def liveness_check():
# detection nor waits on it and the route stays cheap.
if _torch_warm_in_progress():
alive["torch_warm_in_progress"] = True
+ # Startup is not the only window where a healthy backend can miss probes: an
+ # oversubscribed host generating on every slot stalls this loop the same way, long
+ # after the warm is over. The watchdog widens its failure budget on this marker
+ # rather than ending a stream that is still producing tokens.
+ if _inference_active():
+ alive["inference_active"] = True
if _hardware_snapshot() is None:
alive["hardware_detecting"] = True
if os.environ.get(DISABLE_ENV_VAR) == "1":
@@ -1650,6 +1673,10 @@ async def health_check(request: Request):
# to have liveness, so the warm marker has to reach it by the same path.
if _torch_warm_in_progress():
base["torch_warm_in_progress"] = True
+ # Lockstep with /api/liveness for the same reason: the fallback route has to carry the
+ # busy marker too, or an older backend loses the widened budget.
+ if _inference_active():
+ base["inference_active"] = True
if snapshot is None:
# chat_only above is the pre-detection default, not a measurement; clients should re-read.
base["hardware_detecting"] = True
diff --git a/studio/backend/tests/test_liveness_reports_inference_active.py b/studio/backend/tests/test_liveness_reports_inference_active.py
new file mode 100644
index 00000000000..4fc71fb0dca
--- /dev/null
+++ b/studio/backend/tests/test_liveness_reports_inference_active.py
@@ -0,0 +1,165 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Invariant: /api/liveness says whether the backend is generating, and stays cheap.
+
+The desktop health watchdog probes this route every 15s with a 10s budget and declares the
+backend dead after 3 consecutive misses. Startup is not the only window where a healthy
+backend misses three in a row: a host serving a model far larger than it can hold runs at
+fractions of a token per second, and the loop feeding those streams goes quiet the same way
+the warm thread's `import torch` makes it go quiet. Killing there ends a response the user
+is still waiting on, and the window reports it as "Server stopped unexpectedly" (#8945).
+
+So liveness carries an `inference_active` marker and the watchdog widens its failure budget
+while the last answered probe was generating. Only for probes that time out: a refused
+connection means the port is gone, and that is still reported at three strikes.
+
+The marker must not cost what health costs: it is a len() under a lock already held for
+microseconds, never a wait on the generations themselves.
+
+CPU-only, no network, no GPU, no weights.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = Path(__file__).resolve().parent.parent # studio/backend
+_COMMANDS_RS = _BACKEND_DIR.parent / "src-tauri" / "src" / "commands.rs"
+
+
+_SNIPPET = r"""
+import json, os, threading, time
+
+# Keep the real warm out of the way: it would import the ML stack, and this file is about
+# the busy marker, not the warm one.
+os.environ["UNSLOTH_STUDIO_DISABLE_TORCH_WARM"] = "1"
+
+import main
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from state import active_generations
+
+hw = main._hw_module
+hw.DEVICE = hw.DeviceType.CPU
+hw.CHAT_ONLY = True
+hw.CHAT_ONLY_REASON = "no_accelerator"
+hw.DETECTION_COMPLETE.set()
+
+def must_not_run(*_):
+ raise AssertionError("liveness started hardware detection")
+
+hw.ensure_hardware_detected = must_not_run
+
+app = FastAPI()
+app.add_api_route("/api/liveness", main.liveness_check, methods = ["GET"])
+client = TestClient(app)
+
+def probe():
+ started = time.perf_counter()
+ response = client.get("/api/liveness")
+ elapsed = time.perf_counter() - started
+ body = response.json()
+ return {
+ "status_code": response.status_code,
+ "status": body.get("status"),
+ "service": body.get("service"),
+ "elapsed": elapsed,
+ "inference_active": body.get("inference_active"),
+ "has_busy_key": "inference_active" in body,
+ }
+
+idle_before = probe()
+with active_generations.ActiveGeneration(threading.Event(), thread_id = "t1", kind = "messages"):
+ busy = probe()
+idle_after = probe()
+
+print("RESULT" + json.dumps({
+ "idle_before": idle_before,
+ "busy": busy,
+ "idle_after": idle_after,
+}))
+"""
+
+
+def _probe() -> dict:
+ proc = subprocess.run(
+ [sys.executable, "-c", _SNIPPET],
+ cwd = str(_BACKEND_DIR),
+ capture_output = True,
+ text = True,
+ timeout = 900,
+ )
+ assert (
+ proc.returncode == 0
+ ), f"probe failed\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr[-4000:]}"
+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT"))
+ return json.loads(line[len("RESULT") :])
+
+
+def test_liveness_reports_a_generation_in_flight():
+ """The regression: nothing in the reply distinguished a backend stalled under four
+ concurrent generations from one that had exited, so the watchdog killed both."""
+ result = _probe()
+
+ assert result["busy"]["status_code"] == 200
+ assert result["busy"]["status"] == "alive"
+ assert result["busy"]["service"] == "Unsloth UI Backend"
+ assert result["busy"]["inference_active"] is True, (
+ "liveness does not say the backend is generating; the watchdog cannot tell a busy "
+ "backend from a dead one and kills the stream at three missed probes"
+ )
+
+
+def test_the_marker_disappears_once_nothing_is_generating():
+ """The wide budget is for a backend that is producing tokens. Leaving the marker lit
+ after the last stream ends would arm it for the rest of the session, and a genuinely
+ hung backend would sit unreported."""
+ result = _probe()
+
+ assert not result["idle_before"][
+ "has_busy_key"
+ ], "liveness reports inference_active before anything was registered"
+ assert not result["idle_after"]["has_busy_key"], (
+ "liveness still reports inference_active after the generation finished; the "
+ "watchdog would keep the widened budget armed against a hung backend"
+ )
+
+
+def test_the_marker_costs_nothing_to_read():
+ """A probe every 15s cannot pay for anything that waits, which is why the route reads
+ a registry len() rather than asking the backend what it is doing."""
+ result = _probe()
+
+ for state, sample in result.items():
+ assert sample["elapsed"] < 0.5, (
+ f"/api/liveness took {sample['elapsed']:.2f}s while {state}; it must read the "
+ f"registry rather than wait on the generations in it"
+ )
+
+
+def test_the_desktop_watchdog_still_reads_the_marker():
+ """Cross-language guard: the marker only does anything because commands.rs reads it,
+ and either side can be changed without the other."""
+ assert _COMMANDS_RS.is_file(), f"{_COMMANDS_RS} moved; update this guard"
+ rust = _COMMANDS_RS.read_text(encoding = "utf-8")
+ probe = rust[rust.index("async fn check_health_inner") :]
+ end = probe.find("\n}\n")
+ if end != -1:
+ probe = probe[: end + 3]
+
+ assert '"inference_active"' in probe, (
+ "the watchdog probe no longer reads inference_active, so a backend stalled mid "
+ "generation is killed at three missed probes again"
+ )
+ assert "HEALTH_WATCHDOG_MAX_FAILURES_BUSY" in rust, (
+ "commands.rs no longer defines a widened failure budget; reading the marker "
+ "without acting on it changes nothing"
+ )
+ assert "fn watchdog_failure_budget" in rust, (
+ "the budget is no longer chosen in one place; the busy case and the dead-port "
+ "case have to stay distinguishable"
+ )
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index 47f49b19ba5..dedc0faba15 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -9,6 +9,19 @@ use tauri::{AppHandle, Emitter};
const BACKEND_STARTUP_GRACE_PERIOD: Duration = Duration::from_secs(5 * 60);
const HEALTH_WATCHDOG_INTERVAL: Duration = Duration::from_secs(15);
const HEALTH_WATCHDOG_MAX_FAILURES: u32 = 3;
+/// Strikes allowed when the last answered probe said the backend was generating and the
+/// ones since then timed out rather than being refused.
+///
+/// Three strikes is ~75s of silence here, not 45s: the loop sleeps HEALTH_WATCHDOG_INTERVAL
+/// and only then probes, so a strike that TIMES OUT costs 15s + 10s, where a refused one
+/// costs only the 15s. A saturated host clears 75s easily -- a model that does not fit runs
+/// at fractions of a token per second, and the loop serving it can miss several probes in a
+/// row while the response is still being produced. Killing there ends a stream the user is
+/// waiting on and reports it as "Server stopped unexpectedly". Twelve strikes is ~300s.
+///
+/// Only the stalled case gets this. A refused connection still counts against the plain
+/// budget, so a backend that really died is reported just as fast as before.
+const HEALTH_WATCHDOG_MAX_FAILURES_BUSY: u32 = 12;
/// Per-probe HTTP budget for the launcher's liveness probe.
///
/// Generous on purpose. The backend imports torch and transformers on a background warm
@@ -23,6 +36,15 @@ const HEALTH_WATCHDOG_MAX_FAILURES: u32 = 3;
/// than retrying, and `backend/tests/test_health_answers_within_probe_budget.py` derives
/// `_HEALTH_DETECT_BUDGET_S` from that number.
const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(10);
+/// Budget for the single last-chance probe spent before a stalled backend is declared dead.
+///
+/// Deliberately above HEALTH_WATCHDOG_INTERVAL, unlike the per-cycle budget: this one is not
+/// part of the cadence. It runs at most once per backend, and only when the alternative is
+/// killing it, so overlapping the next probe is not a concern -- there is no next probe if
+/// this one does not save the backend. 30s covers a loop running a couple of probe budgets
+/// behind, which is the regime where a generation is still producing tokens but nothing
+/// answers within 10s.
+const HEALTH_CONFIRM_PROBE_TIMEOUT: Duration = Duration::from_secs(30);
fn should_count_watchdog_failure(has_seen_healthy: bool, elapsed_since_start: Duration) -> bool {
has_seen_healthy || elapsed_since_start >= BACKEND_STARTUP_GRACE_PERIOD
@@ -42,6 +64,109 @@ fn watchdog_seen_healthy_after(previous: bool, alive: bool, warming_up: bool) ->
!warming_up
}
+/// Whether the backend was generating, given what the latest probe reported.
+///
+/// Same shape as the warm-up latch above: only an answer updates it. A probe that got
+/// nothing leaves the last answer standing, which is the whole point here, since the
+/// stall being ridden out is exactly when no answer comes back.
+fn watchdog_inference_active_after(previous: bool, alive: bool, inference_active: bool) -> bool {
+ if !alive {
+ return previous;
+ }
+ inference_active
+}
+
+/// What a failed probe says about the port.
+///
+/// A spent budget means a process accepted the connection and did not answer, which is the
+/// stall the busy budget exists for. Anything else (refused, reset, no route) means nothing
+/// is serving there, and that is death.
+fn liveness_from_probe_error(error: &reqwest::Error) -> BackendLiveness {
+ BackendLiveness {
+ probe_timed_out: error.is_timeout(),
+ ..BackendLiveness::default()
+ }
+}
+
+/// Whether a failed adopted-path check is a stall rather than a dead port.
+///
+/// The ownership probe cannot answer this on its own: every transport error inside it becomes
+/// `NotVerified`, indistinguishable from a port that a different process now owns. The
+/// pre-probe can: it answered, from an Unsloth backend, on this port. Silence from the
+/// requests after that is the same stall the owned path already rides out.
+///
+/// `different_owner` is the one thing the probe *can* say for certain, so it overrides both:
+/// an adopted backend that exits while the busy latch is set leaves a freed port, and a
+/// restarted Unsloth backend binding it answers the pre-probe just as the old one did. That
+/// answer is not silence -- the ownership probe got a complete reply naming a different root,
+/// token or no desktop owner at all -- so it is a takeover, not a stall, and the port must be
+/// cleared on the normal three-strike budget rather than held for twelve.
+fn adopted_failure_is_a_stall(verified: bool, served_alive: bool, different_owner: bool) -> bool {
+ !verified && served_alive && !different_owner
+}
+
+/// Whether the last-chance probe brought back evidence that a generation is still running.
+///
+/// Not `alive && inference_active`. On the adopted path `alive` means "the ownership probe
+/// re-verified us", and that probe's two extra loopback requests are exactly what a
+/// saturated backend drops -- the one this probe exists to reach. Such a backend answers
+/// the pre-probe with the busy marker set and then goes quiet, so requiring verification
+/// threw away the answer and cleared a backend mid-response, which is the loss this whole
+/// path is for. A stalled port that says it is generating is kept; silence is not, and a
+/// port a different Unsloth backend took over never reaches here with the marker set.
+fn watchdog_confirm_keeps_backend(confirmed: &BackendLiveness) -> bool {
+ confirmed.inference_active && (confirmed.alive || confirmed.probe_timed_out)
+}
+
+/// Whether to spend one long last-chance probe before declaring a backend dead.
+///
+/// The busy budget can only widen on a marker that some probe actually brought back, and
+/// there is a window where none can: a generation that starts just after an idle answer
+/// and saturates the loop before the next probe leaves the latch false for the rest of its
+/// life, so it dies on the plain three-strike budget with a response in flight -- the exact
+/// loss this change is for. Nothing in the backend can close that window, because a starved
+/// loop cannot answer at all, and the desktop UI cannot either: #8945 is an external
+/// agentic client posting straight to `/v1/messages`, with no frontend in the path.
+///
+/// What can close it is asking once more, with a budget wide enough that a loop running
+/// tens of seconds behind still gets a word in. Only ever spent on a stall: a refused port
+/// is death and is still reported at three strikes, at the same speed, with no extra wait.
+fn watchdog_should_confirm_before_death(
+ consecutive_failures: u32,
+ budget: u32,
+ probe_timed_out: bool,
+) -> bool {
+ consecutive_failures >= budget && probe_timed_out
+}
+
+/// Whether the watchdog may still act on the backend it set out to watch.
+///
+/// Every probe is an await, and the last-chance one is 30s wide on top of the 10s cycle
+/// probe, so up to 40s of wall clock passes between reading the state at the top of the
+/// loop and spending the verdict on it. A stop or a restart lands in that window as a
+/// swapped handle: `start_backend` bumps the generation and stores a new child, and
+/// `stop_backend` has no generation guard of its own, so a watchdog acting on its
+/// pre-await snapshot kills the replacement and reports the healthy new backend as
+/// crashed. The generation is the identity the probe never carried, and the shutdown flag
+/// covers the stop that has not been followed by a start yet.
+fn watchdog_may_still_act(
+ current_generation: u64,
+ watched_generation: u64,
+ has_owned: bool,
+ shutting_down: bool,
+) -> bool {
+ current_generation == watched_generation && has_owned && !shutting_down
+}
+
+/// Consecutive failures tolerated before the backend is declared dead.
+fn watchdog_failure_budget(inference_active: bool, probe_timed_out: bool) -> u32 {
+ if inference_active && probe_timed_out {
+ HEALTH_WATCHDOG_MAX_FAILURES_BUSY
+ } else {
+ HEALTH_WATCHDOG_MAX_FAILURES
+ }
+}
+
async fn managed_install_ready_after_repair() -> bool {
crate::preflight::managed_install_ready().await
}
@@ -310,13 +435,21 @@ struct BackendLiveness {
/// The backend answered but has not finished its background warm, so the ML-stack
/// imports on its warm thread are still in flight. Alive, but not yet done starting.
warming_up: bool,
+ /// The backend answered and had at least one generation in flight. On the adopted path
+ /// this is the pre-probe's reading, which survives an ownership re-check that went
+ /// silent; readers that need "answered right now" pair it with `alive`.
+ inference_active: bool,
+ /// The probe ran out of budget rather than being refused, so a process is still
+ /// holding the port. Silence from a closed port is death; silence from an accepted
+ /// connection is a stall.
+ probe_timed_out: bool,
}
/// Check if an Unsloth backend is running on the given port.
/// Expects JSON with status=="alive" (or "healthy") AND service=="Unsloth UI Backend".
#[tauri::command]
pub async fn check_health(port: u16) -> Result<bool, String> {
- match check_health_inner(port).await {
+ match check_health_inner(port, HEALTH_PROBE_TIMEOUT).await {
Ok(liveness) => Ok(liveness.alive),
Err(e) => {
// Network errors are not command errors — just means not healthy
@@ -334,8 +467,16 @@ pub async fn check_health(port: u16) -> Result<bool, String> {
/// which is the reason it was added. Backends older than that route answer 404, so fall
/// back to health for them, the same order `process::generic_backend_health_ok` and
/// `desktop_backend_owner::fetch_liveness` already use.
-async fn check_health_inner(port: u16) -> Result<BackendLiveness, reqwest::Error> {
- let client = crate::loopback_http::client(HEALTH_PROBE_TIMEOUT)?;
+///
+/// The budget is a parameter rather than the constant, because the last-chance probe the
+/// watchdog spends before declaring a stalled backend dead needs a wider one: a loop that
+/// is starved past 10s is exactly the loop whose answer decides whether a generation is
+/// still running, and abandoning that read at 10s is what leaves the question unanswered.
+async fn check_health_inner(
+ port: u16,
+ budget: Duration,
+) -> Result<BackendLiveness, reqwest::Error> {
+ let client = crate::loopback_http::client(budget)?;
let mut json = None;
for path in ["/api/liveness", "/api/health"] {
let resp = client
@@ -392,10 +533,19 @@ async fn check_health_inner(port: u16) -> Result<BackendLiveness, reqwest::Error
.and_then(|v| v.as_bool())
.unwrap_or(false);
+ // Absent on a backend too old to publish it, which reads as "not busy": the widened
+ // budget is the only thing such a backend loses.
+ let inference_active = json
+ .get("inference_active")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
let alive = live && correct_service;
Ok(BackendLiveness {
alive,
warming_up: alive && (warming || (detecting && !deferred)),
+ inference_active: alive && inference_active,
+ probe_timed_out: false,
})
}
@@ -404,9 +554,13 @@ async fn check_watchdog_health(
generation: u64,
port: u16,
has_adopted: bool,
+ budget: Duration,
) -> BackendLiveness {
if !has_adopted {
- return check_health_inner(port).await.unwrap_or_default();
+ return match check_health_inner(port, budget).await {
+ Ok(liveness) => liveness,
+ Err(error) => liveness_from_probe_error(&error),
+ };
}
let snapshot = match process::owned_backend_snapshot(state) {
@@ -422,38 +576,85 @@ async fn check_watchdog_health(
let Some(owner) = snapshot.owner else {
return BackendLiveness::default();
};
+ // Ask the backend before asking who owns it. The ownership probe folds every transport
+ // error into "not verified", so classifying the failure has to happen here or a stalled
+ // adopted backend is indistinguishable from a dead one and loses the busy budget.
+ //
+ // Nothing is skipped by returning early: the probe's own first step is this same GET,
+ // on the same port with the same budget and the same /api/liveness -> /api/health
+ // fallback, so a port that answers nothing here cannot verify ownership either.
+ let served = match check_health_inner(port, budget).await {
+ Ok(liveness) => liveness,
+ Err(error) => return liveness_from_probe_error(&error),
+ };
// HEALTH_PROBE_TIMEOUT, not the ownership path's default 2s. Every request inside the
// probe would otherwise time out during the very GIL stall this watchdog is supposed to
// ride out, so the backend came back unverified and the warm-up read below -- which is
// gated on that verification -- never ran at all.
+ let ownership = crate::desktop_backend_owner::probe_owned_backend_state_with_timeout(
+ owner,
+ Some(port),
+ false,
+ budget,
+ )
+ .await;
let verified = matches!(
- crate::desktop_backend_owner::probe_owned_backend_state_with_timeout(
- owner,
- Some(port),
- false,
- HEALTH_PROBE_TIMEOUT,
- )
- .await,
+ ownership,
crate::desktop_backend_owner::OwnedBackendProbe::Verified(_)
);
- // The ownership probe answers "is this still our process", not "is startup over", so
- // ask the backend itself as well. An adopted backend having served one request before
- // this app attached is the same fallacy the owned path fixes below: a force-quit during
- // a cold start leaves the backend running and still importing the ML stack, and the app
- // relaunches straight onto it. Without a warm-up signal that host is declared dead three
- // probes later while it is perfectly healthy.
+ // The one failure the probe can be certain about: a complete answer naming an owner that
+ // is not ours. Everything else it reports could be silence.
+ let different_owner = crate::desktop_backend_owner::probe_saw_a_different_owner(&ownership);
+ // The ownership probe answers "is this still our process", not "is startup over", which
+ // is why the read above is consulted as well. An adopted backend having served one
+ // request before this app attached is the same fallacy the owned path fixes below: a
+ // force-quit during a cold start leaves the backend running and still importing the ML
+ // stack, and the app relaunches straight onto it. Without a warm-up signal that host is
+ // declared dead three probes later while it is perfectly healthy.
//
- // Only consulted when ownership verified, so a foreign process on the port cannot hold
- // the grace open. A failed read reports not-warming, which is the conservative answer:
- // it lets the failure count rather than extending the grace on a backend we cannot read.
- let warming_up = if verified {
- check_health_inner(port).await.unwrap_or_default().warming_up
- } else {
- false
- };
+ adopted_backend_liveness(verified, &served, different_owner)
+}
+
+/// Fold the adopted path's two readings -- what the backend served and what the ownership
+/// probe made of it -- into one verdict.
+///
+/// `alive` and `warming_up` stay gated on verification, so a foreign process on the port
+/// cannot hold the startup grace open.
+fn adopted_backend_liveness(
+ verified: bool,
+ served: &BackendLiveness,
+ different_owner: bool,
+) -> BackendLiveness {
BackendLiveness {
alive: verified,
- warming_up,
+ warming_up: verified && served.warming_up,
+ // NOT gated on verification, for the same reason `probe_timed_out` below is not.
+ // The ownership probe's extra requests are the ones a saturated backend drops, so
+ // requiring verification here discards the one thing the pre-probe did bring back:
+ // this backend, on this port, said a generation was in flight. That is precisely
+ // the evidence the last-chance confirmation spends, and gating it meant a stalled
+ // adopted backend answered "still generating" and was cleared anyway, mid-response.
+ //
+ // A takeover still clears it: `different_owner` is a complete answer naming someone
+ // else, so the generation it reports is not ours to protect. Every other reader
+ // gates on `alive` already (`watchdog_inference_active_after` returns the previous
+ // latch when the probe did not answer), so nothing else changes shape here.
+ inference_active: served.inference_active && !different_owner,
+ // The read above answering does not mean the whole check answered. The ownership
+ // probe issues two more loopback requests -- its own `/api/liveness` and the
+ // `/api/auth/desktop-login` compatibility POST -- each with its own budget, and it
+ // folds a timeout on either into "not verified". Hard-coding this false there gave
+ // the three-strike budget to an adopted backend that had just told us it was
+ // generating, which is the kill this whole change exists to prevent. Worse, the
+ // narrower budget is re-read on every failure, so one such cycle could fire the
+ // kill immediately on a count already past three.
+ //
+ // The read is the evidence: an Unsloth backend answered on this port, so silence
+ // from the rest of the check is a stall, not an empty port. A refused port never
+ // reaches here -- it returns above with `probe_timed_out` set from the error, and a
+ // port a different Unsloth backend has taken over is excluded by `different_owner`,
+ // since that one answered rather than fell silent.
+ probe_timed_out: adopted_failure_is_a_stall(verified, served.alive, different_owner),
}
}
@@ -1006,7 +1207,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert!(!liveness.warming_up);
@@ -1019,7 +1222,9 @@ mod tests {
// "healthy" from /api/health and 404s liveness.
let (port, paths) = probe_test_backend(None, ready_health(false)).await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert_eq!(
@@ -1039,7 +1244,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert!(
@@ -1063,7 +1270,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert!(
@@ -1086,7 +1295,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert!(!liveness.warming_up);
@@ -1105,7 +1316,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.warming_up);
}
@@ -1123,7 +1336,9 @@ mod tests {
)
.await;
- let liveness = super::check_health_inner(port).await.unwrap();
+ let liveness = super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap();
assert!(liveness.alive);
assert!(!liveness.warming_up);
@@ -1138,7 +1353,9 @@ mod tests {
.await;
assert_eq!(
- super::check_health_inner(port).await.unwrap(),
+ super::check_health_inner(port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap(),
super::BackendLiveness::default()
);
}
@@ -1245,6 +1462,553 @@ mod tests {
assert!(super::watchdog_seen_healthy_after(false, true, false));
}
+ #[test]
+ fn a_backend_that_stalls_while_generating_is_not_killed_at_three_strikes() {
+ // #8945. Four concurrent requests against a 27B Q8 on an APU ran at 0.28 tok/s, the
+ // loop serving them went quiet, and three probes later the response the user was
+ // waiting on was killed and reported as "Server stopped unexpectedly".
+ let mut generating = false;
+ generating = super::watchdog_inference_active_after(generating, true, true);
+ assert!(generating);
+ // Silence leaves the last answer standing: no answer is exactly what a stall gives.
+ generating = super::watchdog_inference_active_after(generating, false, false);
+ assert!(generating);
+ assert_eq!(
+ super::watchdog_failure_budget(generating, true),
+ super::HEALTH_WATCHDOG_MAX_FAILURES_BUSY
+ );
+ assert!(super::HEALTH_WATCHDOG_MAX_FAILURES_BUSY > super::HEALTH_WATCHDOG_MAX_FAILURES);
+ }
+
+ #[test]
+ fn a_dead_port_is_still_declared_dead_at_three_strikes() {
+ // The budget widens for a stall, never for a refusal, so a backend that really
+ // exited is reported just as fast as before. Same for one that was idle.
+ assert_eq!(
+ super::watchdog_failure_budget(true, false),
+ super::HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ assert_eq!(
+ super::watchdog_failure_budget(false, true),
+ super::HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ }
+
+ /// A port that completes the handshake and then says nothing, which is what a stalled
+ /// backend looks like from here. The accepted streams are parked, not dropped: closing
+ /// one would answer the probe with a reset and the request would fail early.
+ async fn stalling_test_backend() -> u16 {
+ let listener = TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .expect("probe test needs a loopback port");
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ let mut parked = Vec::new();
+ while let Ok((stream, _)) = listener.accept().await {
+ parked.push(stream);
+ }
+ });
+ port
+ }
+
+ #[tokio::test]
+ async fn a_port_that_accepts_and_never_answers_reads_as_a_stall() {
+ // The premise of the busy budget: a saturated backend still holds its port open, so
+ // the probe runs out of budget rather than being refused.
+ let port = stalling_test_backend().await;
+ let client = crate::loopback_http::client(Duration::from_millis(250)).unwrap();
+
+ let error = client
+ .get(format!("http://127.0.0.1:{port}/api/liveness"))
+ .send()
+ .await
+ .expect_err("a parked connection cannot answer");
+
+ assert!(
+ super::liveness_from_probe_error(&error).probe_timed_out,
+ "a spent probe budget is not being classified as a stall, so a backend that is \
+ merely busy gets the three-strike budget"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_port_with_nothing_on_it_reads_as_death_not_a_stall() {
+ // The other half: a backend that really exited leaves a closed port, and that must
+ // still be declared dead at three strikes.
+ let port = {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ port
+ };
+ let client = crate::loopback_http::client(Duration::from_secs(5)).unwrap();
+
+ let error = client
+ .get(format!("http://127.0.0.1:{port}/api/liveness"))
+ .send()
+ .await
+ .expect_err("nothing is listening on this port");
+
+ let liveness = super::liveness_from_probe_error(&error);
+ assert!(!liveness.probe_timed_out, "a refused port read as a stall");
+ assert_eq!(
+ super::watchdog_failure_budget(true, liveness.probe_timed_out),
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ "a dead port inherits the busy budget from the last answer it gave"
+ );
+ }
+
+ #[tokio::test]
+ async fn the_busy_marker_survives_the_wire() {
+ // End to end through the same client and parser the watchdog uses, so the field name
+ // is checked against what main.py publishes rather than against itself.
+ let (busy_port, _) = probe_test_backend(
+ Some(
+ r#"{"status":"alive","service":"Unsloth UI Backend","inference_active":true}"#
+ .to_string(),
+ ),
+ ready_health(false),
+ )
+ .await;
+ let (idle_port, _) = probe_test_backend(
+ Some(r#"{"status":"alive","service":"Unsloth UI Backend"}"#.to_string()),
+ ready_health(false),
+ )
+ .await;
+
+ assert!(
+ super::check_health_inner(busy_port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap()
+ .inference_active
+ );
+ // Absent on an older backend, which reads as idle rather than as busy forever.
+ assert!(
+ !super::check_health_inner(idle_port, super::HEALTH_PROBE_TIMEOUT)
+ .await
+ .unwrap()
+ .inference_active
+ );
+ }
+
+ #[test]
+ fn both_watchdog_paths_classify_a_failed_probe() {
+ // The adopted path folds every transport error into "not verified", so it has to
+ // classify the failure itself. Hard-coding it false there killed a stalled adopted
+ // backend at three strikes while the owned path rode the same stall out.
+ // Normalise line endings first: include_str! embeds CRLF on Windows checkouts.
+ let src = include_str!("commands.rs").replace("\r\n", "\n");
+ let start = src
+ .find("async fn check_watchdog_health")
+ .expect("check_watchdog_health moved; update this guard");
+ let body = &src[start..];
+ let body = &body[..body.find("\n}\n").expect("could not find the function end")];
+
+ assert_eq!(
+ body.matches("liveness_from_probe_error").count(),
+ 2,
+ "the owned and adopted branches must both classify a failed probe"
+ );
+ }
+
+ #[test]
+ fn a_backend_that_answers_idle_gives_the_wide_budget_back() {
+ // The latch follows the last answer, so a finished stream drops straight back to
+ // three strikes rather than leaving the wide budget armed for the whole session.
+ let generating = super::watchdog_inference_active_after(true, true, false);
+ assert!(!generating);
+ assert_eq!(
+ super::watchdog_failure_budget(generating, true),
+ super::HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ }
+
+ #[test]
+ fn an_adopted_backend_that_answers_and_then_stalls_keeps_the_busy_budget() {
+ // The ownership check issues two more loopback requests after the read that already
+ // answered, and folds a timeout on either into "not verified". Reporting that as a
+ // refusal handed a generating adopted backend the three-strike budget.
+ assert!(super::adopted_failure_is_a_stall(false, true, false));
+ assert_eq!(
+ super::watchdog_failure_budget(
+ true,
+ super::adopted_failure_is_a_stall(false, true, false)
+ ),
+ super::HEALTH_WATCHDOG_MAX_FAILURES_BUSY
+ );
+ }
+
+ #[test]
+ fn a_stalled_adopted_backend_that_says_it_is_generating_survives_the_confirmation() {
+ // The shape the last-chance probe really brings back from a saturated adopted
+ // backend: the pre-probe answered with the busy marker, and the ownership probe's
+ // two extra loopback requests timed out behind it, so nothing is verified. Judging
+ // that on `alive` threw the answer away and cleared the backend with the response
+ // still streaming, which is the kill this whole path exists to prevent.
+ let served = super::BackendLiveness {
+ alive: true,
+ warming_up: false,
+ inference_active: true,
+ probe_timed_out: false,
+ };
+ let confirmed = super::adopted_backend_liveness(false, &served, false);
+ assert!(
+ !confirmed.alive,
+ "an unverified re-check is not a live answer"
+ );
+ assert!(super::watchdog_confirm_keeps_backend(&confirmed));
+
+ // Silence is still death: the same unverified re-check with nothing served.
+ let quiet =
+ super::adopted_backend_liveness(false, &super::BackendLiveness::default(), false);
+ assert!(!super::watchdog_confirm_keeps_backend(&quiet));
+
+ // So is an idle backend that answered: only a generation buys the reprieve.
+ let idle = super::adopted_backend_liveness(
+ true,
+ &super::BackendLiveness {
+ alive: true,
+ warming_up: false,
+ inference_active: false,
+ probe_timed_out: false,
+ },
+ false,
+ );
+ assert!(!super::watchdog_confirm_keeps_backend(&idle));
+
+ // And a port a different Unsloth backend took over answers with its own generation,
+ // which is not ours to hold the port open for.
+ let taken_over = super::adopted_backend_liveness(false, &served, true);
+ assert!(!super::watchdog_confirm_keeps_backend(&taken_over));
+ }
+
+ #[test]
+ fn a_port_another_backend_took_over_stays_on_the_normal_budget() {
+ // An adopted backend that exits mid-generation leaves the busy latch set, and the
+ // freed port is routinely rebound by the next Unsloth backend the user starts. That
+ // one answers the pre-probe exactly as the old one did, so `served.alive` is true
+ // while the ownership probe rejects it -- with a complete answer, not silence.
+ //
+ // Calling that a stall gave a foreign port twelve strikes instead of three: 12 * 15s
+ // = ~180s of a backend the app still shows as running, against ~45s, plus a
+ // last-chance probe that is spent for nothing.
+ assert!(!super::adopted_failure_is_a_stall(false, true, true));
+ assert_eq!(
+ super::watchdog_failure_budget(
+ true,
+ super::adopted_failure_is_a_stall(false, true, true)
+ ),
+ super::HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ assert!(!super::watchdog_should_confirm_before_death(
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ super::adopted_failure_is_a_stall(false, true, true),
+ ));
+ }
+
+ #[test]
+ fn an_adopted_port_that_answered_nothing_is_not_called_a_stall() {
+ // The read is the only evidence there is. Without it the failure is a dead port,
+ // and a dead port must still be reported at three strikes.
+ assert!(!super::adopted_failure_is_a_stall(false, false, false));
+ assert_eq!(
+ super::watchdog_failure_budget(
+ true,
+ super::adopted_failure_is_a_stall(false, false, false)
+ ),
+ super::HEALTH_WATCHDOG_MAX_FAILURES
+ );
+ // And a check that passed is not a failure at all, so it is not a stall either.
+ assert!(!super::adopted_failure_is_a_stall(true, true, false));
+ }
+
+ #[test]
+ fn a_generation_that_starts_between_probes_still_gets_one_last_chance() {
+ // The latch can only be set by a probe that answered. A generation that starts just
+ // after an idle answer and saturates the loop before the next probe never sets it,
+ // so it dies on three strikes with a response in flight unless something asks again.
+ assert!(super::watchdog_should_confirm_before_death(
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ true,
+ ));
+ // Not before the budget is actually spent: the normal cadence is untouched.
+ assert!(!super::watchdog_should_confirm_before_death(
+ super::HEALTH_WATCHDOG_MAX_FAILURES - 1,
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ true,
+ ));
+ // And never for a refused port, so a backend that really exited is reported at the
+ // same speed as before, with no extra wait bolted on.
+ assert!(!super::watchdog_should_confirm_before_death(
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ super::HEALTH_WATCHDOG_MAX_FAILURES,
+ false,
+ ));
+ }
+
+ #[test]
+ fn the_last_chance_budget_is_wider_than_the_one_that_gave_up() {
+ // The point of the extra probe is a budget the per-cycle one cannot afford. Equal
+ // budgets would just repeat the read that already failed.
+ assert!(super::HEALTH_CONFIRM_PROBE_TIMEOUT > super::HEALTH_PROBE_TIMEOUT);
+ }
+
+ /// What one watchdog cycle got back from the port.
+ #[derive(Clone, Copy, Debug)]
+ enum Probe {
+ Answered { warming: bool, busy: bool },
+ TimedOut,
+ Refused,
+ }
+
+ fn answered(busy: bool) -> Probe {
+ Probe::Answered {
+ warming: false,
+ busy,
+ }
+ }
+
+ /// Replay a timeline through the watchdog's failure accounting and report the wall
+ /// clock at which the backend was declared dead, or `None` if it survived.
+ ///
+ /// Mirrors the loop in `health_watchdog` rather than calling it: the loop needs an
+ /// `AppHandle` and a real 15s sleep per cycle. Every decision it makes comes from the
+ /// helpers below, so the arithmetic being checked here is the arithmetic it runs.
+ /// `confirms` supplies what the last-chance probe gets back, in order.
+ fn simulate_watchdog(probes: &[Probe], confirms: &[Probe]) -> Option<u64> {
+ let interval = super::HEALTH_WATCHDOG_INTERVAL.as_secs();
+ let probe_budget = super::HEALTH_PROBE_TIMEOUT.as_secs();
+ let confirm_budget = super::HEALTH_CONFIRM_PROBE_TIMEOUT.as_secs();
+
+ let mut failures: u32 = 0;
+ let mut was_generating = false;
+ let mut elapsed: u64 = 0;
+ let mut next_confirm = 0usize;
+
+ for probe in probes {
+ elapsed += interval;
+ let liveness = match *probe {
+ Probe::Answered { warming, busy } => super::BackendLiveness {
+ alive: true,
+ warming_up: warming,
+ inference_active: busy,
+ probe_timed_out: false,
+ },
+ Probe::TimedOut => {
+ elapsed += probe_budget;
+ super::BackendLiveness {
+ probe_timed_out: true,
+ ..super::BackendLiveness::default()
+ }
+ }
+ Probe::Refused => super::BackendLiveness::default(),
+ };
+
+ if liveness.alive {
+ was_generating = super::watchdog_inference_active_after(
+ was_generating,
+ liveness.alive,
+ liveness.inference_active,
+ );
+ failures = 0;
+ continue;
+ }
+
+ let budget = super::watchdog_failure_budget(was_generating, liveness.probe_timed_out);
+ failures += 1;
+ if super::watchdog_should_confirm_before_death(
+ failures,
+ budget,
+ liveness.probe_timed_out,
+ ) {
+ let confirm = confirms
+ .get(next_confirm)
+ .copied()
+ .unwrap_or(Probe::TimedOut);
+ next_confirm += 1;
+ match confirm {
+ Probe::Answered { busy: true, .. } => {
+ was_generating = true;
+ failures = 0;
+ continue;
+ }
+ Probe::Answered { busy: false, .. } => {}
+ Probe::TimedOut => elapsed += confirm_budget,
+ Probe::Refused => {}
+ }
+ }
+ if failures >= budget {
+ return Some(elapsed);
+ }
+ }
+ None
+ }
+
+ #[test]
+ fn simulated_timelines_kill_only_what_should_be_killed() {
+ let plain = super::HEALTH_WATCHDOG_MAX_FAILURES as usize;
+ let busy = super::HEALTH_WATCHDOG_MAX_FAILURES_BUSY as usize;
+ let interval = super::HEALTH_WATCHDOG_INTERVAL.as_secs();
+ let probe_budget = super::HEALTH_PROBE_TIMEOUT.as_secs();
+ let confirm_budget = super::HEALTH_CONFIRM_PROBE_TIMEOUT.as_secs();
+ let stall_cycle = interval + probe_budget;
+
+ // A healthy idle backend is never touched.
+ assert_eq!(simulate_watchdog(&vec![answered(false); 200], &[]), None);
+ // Neither is one that answers while it generates, which is the #8945 log: liveness
+ // came back every 15s right up to the end.
+ assert_eq!(simulate_watchdog(&vec![answered(true); 200], &[]), None);
+ // A backend still importing the ML stack answers, so it never counts a failure.
+ assert_eq!(
+ simulate_watchdog(
+ &vec![
+ Probe::Answered {
+ warming: true,
+ busy: false
+ };
+ 200
+ ],
+ &[]
+ ),
+ None
+ );
+
+ // A backend that exited leaves a refused port, and dies at three strikes with no
+ // last-chance wait bolted on: 3 x 15s, exactly what it cost before this change.
+ let mut dead = vec![answered(false)];
+ dead.extend(vec![Probe::Refused; plain]);
+ assert_eq!(simulate_watchdog(&dead, &[]), Some(interval * 4));
+ // Even one that was generating when it went: the busy budget is for silence from a
+ // port that is still accepting, never for a refusal.
+ let mut died_generating = vec![answered(true)];
+ died_generating.extend(vec![Probe::Refused; plain]);
+ assert_eq!(simulate_watchdog(&died_generating, &[]), Some(interval * 4));
+
+ // The regression this PR is for: answered busy, then the loop goes quiet. It has to
+ // survive far past three strikes.
+ let mut stalling = vec![answered(true)];
+ stalling.extend(vec![Probe::TimedOut; busy - 1]);
+ assert_eq!(simulate_watchdog(&stalling, &[]), None);
+
+ // A backend that is genuinely wedged is still killed, just later. Bounded, and the
+ // bound is checked so nobody can widen it by accident.
+ let mut wedged = vec![answered(true)];
+ wedged.extend(vec![Probe::TimedOut; busy + 4]);
+ assert_eq!(
+ simulate_watchdog(&wedged, &[Probe::TimedOut]),
+ Some(interval + busy as u64 * stall_cycle + confirm_budget)
+ );
+
+ // Codex #3: the generation starts between two probes, so no answer ever reports it.
+ // Before the last-chance probe this died at three strikes; now the probe that a
+ // starved loop can still answer within 30s reports the generation and it lives.
+ let mut started_between_probes = vec![answered(false)];
+ started_between_probes.extend(vec![Probe::TimedOut; 40]);
+ assert_eq!(
+ simulate_watchdog(
+ &started_between_probes,
+ &[answered(true); 8] // one per spent budget
+ ),
+ None
+ );
+ // Without an answer to that probe it still dies, one confirm budget later than the
+ // three strikes it used to take. That is the whole cost to a hung idle backend.
+ assert_eq!(
+ simulate_watchdog(&started_between_probes, &[Probe::TimedOut]),
+ Some(interval + plain as u64 * stall_cycle + confirm_budget)
+ );
+ // And an answer that says the backend is idle is not a reprieve: a backend that is
+ // alive but unresponsive and doing nothing dies exactly where it did before.
+ assert_eq!(
+ simulate_watchdog(&started_between_probes, &[answered(false)]),
+ Some(interval + plain as u64 * stall_cycle)
+ );
+
+ // A stream that finishes hands the wide budget straight back.
+ let mut finished = vec![answered(true), answered(false)];
+ finished.extend(vec![Probe::Refused; plain]);
+ assert_eq!(simulate_watchdog(&finished, &[]), Some(interval * 5));
+
+ // Mixed causes: stalling on the busy budget and then the port disappears. The
+ // budget is re-read per failure, so the refusal ends it immediately rather than
+ // waiting out the remaining busy strikes.
+ let mut stalled_then_gone = vec![answered(true)];
+ stalled_then_gone.extend(vec![Probe::TimedOut; 5]);
+ stalled_then_gone.push(Probe::Refused);
+ assert_eq!(
+ simulate_watchdog(&stalled_then_gone, &[]),
+ Some(interval + 5 * stall_cycle + interval)
+ );
+
+ // A backend that answers every other probe never accumulates a budget at all.
+ let flapping: Vec<Probe> = (0..200)
+ .map(|i| {
+ if i % 2 == 0 {
+ answered(true)
+ } else {
+ Probe::TimedOut
+ }
+ })
+ .collect();
+ assert_eq!(simulate_watchdog(&flapping, &[]), None);
+ }
+
+ /// A port that answers, but only after `delay`. This is the regime the last-chance
+ /// probe exists for: the loop is running behind, not gone.
+ async fn slow_test_backend(delay: Duration, body: &'static str) -> u16 {
+ let listener = TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .expect("probe test needs a loopback port");
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buffer = [0; 2048];
+ if stream.read(&mut buffer).await.is_err() {
+ return;
+ }
+ tokio::time::sleep(delay).await;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes()).await;
+ });
+ }
+ });
+ port
+ }
+
+ #[tokio::test]
+ async fn a_wider_budget_reaches_a_backend_the_per_cycle_one_gives_up_on() {
+ // Measured, not asserted from the constants: the same port, the same parser, one
+ // budget that expires before the answer and one that does not.
+ let port = slow_test_backend(
+ Duration::from_millis(600),
+ r#"{"status":"alive","service":"Unsloth UI Backend","inference_active":true}"#,
+ )
+ .await;
+
+ let gave_up = super::check_health_inner(port, Duration::from_millis(150))
+ .await
+ .expect_err("a 150ms budget cannot outlast a 600ms answer");
+ assert!(
+ super::liveness_from_probe_error(&gave_up).probe_timed_out,
+ "a slow-but-answering backend must read as a stall, not as a dead port"
+ );
+
+ let confirmed = super::check_health_inner(port, Duration::from_secs(5))
+ .await
+ .expect("a 5s budget outlasts a 600ms answer");
+ assert!(confirmed.alive);
+ assert!(
+ confirmed.inference_active,
+ "the wider probe must still parse the busy marker, or the reprieve never fires"
+ );
+ }
+
#[test]
fn conflict_message_only_blames_a_terminal_for_a_same_install_backend() {
let message = |reason: &str| {
@@ -1284,6 +2048,56 @@ mod tests {
);
}
}
+
+ #[test]
+ fn a_restart_during_the_last_chance_probe_is_not_declared_dead() {
+ // The watched generation is the only identity this task has: `check_health_inner`
+ // matches on a service name, so a probe answer says "an Unsloth backend is on this
+ // port", never "the one I was started for". Anything that is not still generation
+ // G with a handle stored and no stop in flight has to end the loop rather than
+ // reach `stop_backend`, which takes whatever handle is stored *now*.
+ assert!(super::watchdog_may_still_act(7, 7, true, false));
+ // Restarted under the probe: start_backend bumped the generation and stored a new
+ // child, so the kill below would land on the replacement.
+ assert!(!super::watchdog_may_still_act(8, 7, true, false));
+ // Stopped and not started again: the handle is gone, so there is nothing to kill
+ // and "server stopped unexpectedly" would contradict the stop the user asked for.
+ assert!(!super::watchdog_may_still_act(7, 7, false, false));
+ // A stop in flight: stop_backend sets the flag before it takes the handle, so this
+ // is the same restart caught one instant earlier.
+ assert!(!super::watchdog_may_still_act(7, 7, true, true));
+ }
+
+ #[test]
+ fn the_watchdog_rereads_the_generation_after_the_confirm_probe() {
+ // HEALTH_CONFIRM_PROBE_TIMEOUT is 30s on top of the 10s cycle probe, so up to 40s
+ // of wall clock separates the generation check at the top of the loop from the
+ // kill at the bottom, and both stop_server and start_server are async commands
+ // that run while this task is parked on the await. Losing the re-read reinstates a
+ // 40s window in which a user restarting a hung backend has the new one killed.
+ // Normalised line endings for the same reason as the guard above: include_str!
+ // embeds CRLF on the Windows runner.
+ let src = include_str!("commands.rs").replace("\r\n", "\n");
+ let start = src
+ .find("async fn health_watchdog")
+ .expect("health_watchdog moved; update this guard");
+ let body = &src[start..];
+ let body = &body[..body.find("\n}\n").expect("could not find the function end")];
+
+ let confirm = body
+ .find("HEALTH_CONFIRM_PROBE_TIMEOUT")
+ .expect("the last-chance probe is gone; update this guard");
+ let guard = body
+ .find("watchdog_may_still_act")
+ .expect("the post-probe generation re-read is gone");
+ let kill = body
+ .rfind("stop_backend")
+ .expect("the unresponsive-backend kill moved");
+ assert!(
+ confirm < guard && guard < kill,
+ "the generation re-read must sit between the last-chance probe and the kill"
+ );
+ }
}
/// Periodic health check that detects deadlocked or hung backends.
@@ -1291,6 +2105,8 @@ mod tests {
/// but legitimate backend boot is not killed. After the backend has answered a probe
/// that says its warm-up is finished, or after the startup grace expires, 3 consecutive
/// failed checks emit `server-crashed` so the frontend can offer a restart.
+/// A backend last seen generating gets the wider `HEALTH_WATCHDOG_MAX_FAILURES_BUSY`
+/// budget for probes that time out, since a saturated host stalls one that is healthy.
async fn health_watchdog(
app: AppHandle,
state: BackendState,
@@ -1304,6 +2120,7 @@ async fn health_watchdog(
let started_at = Instant::now();
let mut consecutive_failures: u32 = 0;
let mut has_seen_healthy = count_failures_immediately;
+ let mut was_generating = false;
loop {
tokio::time::sleep(HEALTH_WATCHDOG_INTERVAL).await;
@@ -1380,7 +2197,9 @@ async fn health_watchdog(
continue;
};
- let liveness = check_watchdog_health(&state, generation, port, has_adopted).await;
+ let liveness =
+ check_watchdog_health(&state, generation, port, has_adopted, HEALTH_PROBE_TIMEOUT)
+ .await;
if liveness.alive {
// One answer is proof of life, not proof that startup is over. The backend
// imports the ML stack on a warm thread and those C-extension imports hold the
@@ -1395,6 +2214,11 @@ async fn health_watchdog(
}
has_seen_healthy =
watchdog_seen_healthy_after(has_seen_healthy, liveness.alive, liveness.warming_up);
+ was_generating = watchdog_inference_active_after(
+ was_generating,
+ liveness.alive,
+ liveness.inference_active,
+ );
consecutive_failures = 0;
} else if !should_count_failure {
info!(
@@ -1402,12 +2226,75 @@ async fn health_watchdog(
port
);
} else {
+ let budget = watchdog_failure_budget(was_generating, liveness.probe_timed_out);
consecutive_failures += 1;
warn!(
- "Health watchdog: failure {}/{} on port {}",
- consecutive_failures, HEALTH_WATCHDOG_MAX_FAILURES, port
+ "Health watchdog: failure {}/{} on port {}{}",
+ consecutive_failures,
+ budget,
+ port,
+ if budget > HEALTH_WATCHDOG_MAX_FAILURES {
+ " (backend last seen generating, probe timed out)"
+ } else {
+ ""
+ }
);
- if consecutive_failures >= HEALTH_WATCHDOG_MAX_FAILURES {
+ if watchdog_should_confirm_before_death(
+ consecutive_failures,
+ budget,
+ liveness.probe_timed_out,
+ ) {
+ // The budget is spent and the port is still accepting connections. Before
+ // ending a response that may still be streaming, ask once with a budget the
+ // per-cycle one cannot afford. An answer here is not a reprieve on its own:
+ // only a backend that says it is generating gets the count reset, so one
+ // that is alive but idle and unresponsive still dies, as it did before.
+ let confirmed = check_watchdog_health(
+ &state,
+ generation,
+ port,
+ has_adopted,
+ HEALTH_CONFIRM_PROBE_TIMEOUT,
+ )
+ .await;
+ if watchdog_confirm_keeps_backend(&confirmed) {
+ warn!(
+ "Health watchdog: backend on port {} answered the last-chance probe and is still generating, not declaring it dead",
+ port
+ );
+ has_seen_healthy = watchdog_seen_healthy_after(
+ has_seen_healthy,
+ confirmed.alive,
+ confirmed.warming_up,
+ );
+ was_generating = true;
+ consecutive_failures = 0;
+ continue;
+ }
+ }
+ // The verdict below is about the backend that was current when this cycle read
+ // the state, and both probes above have awaited since. Re-read before spending
+ // it: `stop_backend` acts on whatever handle is stored now, so a restart during
+ // the last-chance probe would have this task kill the replacement instead.
+ let (current_generation, still_owned) = {
+ let proc = match state.lock() {
+ Ok(p) => p,
+ Err(_) => break,
+ };
+ (proc.generation, proc.has_owned_backend())
+ };
+ if !watchdog_may_still_act(
+ current_generation,
+ generation,
+ still_owned,
+ shutdown.load(Ordering::SeqCst),
+ ) {
+ info!(
+ "Health watchdog: backend changed while the health probe was in flight, exiting without declaring it dead"
+ );
+ break;
+ }
+ if consecutive_failures >= budget {
diagnostics::record_backend_watchdog(
&diagnostics,
generation,
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
index 64c47a42c0d..b127de8544f 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -91,6 +91,24 @@ pub(crate) enum OwnedBackendProbe {
Verified(VerifiedOwnedBackend),
}
+/// `NotVerified` reason for a port that answered the probe in full and named an owner that is
+/// not this app's.
+///
+/// Kept apart from `owned_backend_not_found`, which also covers a port that said nothing at
+/// all. The health watchdog needs the difference: silence from a port an Unsloth backend just
+/// answered on is a stall and earns the wide busy budget, while a complete answer carrying a
+/// different root id, a different token or no desktop owner at all is proof that the backend
+/// this app adopted is gone and something else has the port.
+pub(crate) const OWNED_BACKEND_OWNER_MISMATCH: &str = "owned_backend_owner_mismatch";
+
+/// Whether a failed probe answered with a different owner rather than falling silent.
+pub(crate) fn probe_saw_a_different_owner(probe: &OwnedBackendProbe) -> bool {
+ matches!(
+ probe,
+ OwnedBackendProbe::NotVerified { reason } if reason == OWNED_BACKEND_OWNER_MISMATCH
+ )
+}
+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PreviousAppPidStatus {
Dead,
@@ -940,6 +958,9 @@ pub(crate) async fn probe_owned_backend_state_with_timeout(
None => desktop_candidate_ports().collect(),
};
let mut verified = Vec::new();
+ // Set only by a complete, parsed answer that names someone else. A transport error or a
+ // non-success status leaves it alone, so silence never reads as a takeover.
+ let mut answered_with_a_different_owner = false;
for port in ports {
let liveness = match fetch_liveness(port, timeout).await {
Ok(Some(liveness)) => liveness,
@@ -953,6 +974,7 @@ pub(crate) async fn probe_owned_backend_state_with_timeout(
}
};
if !liveness_verifies_metadata(&liveness, &owner.metadata) {
+ answered_with_a_different_owner = true;
continue;
}
if let Some(reason) = lifecycle_control_block_reason(&liveness) {
@@ -990,10 +1012,12 @@ pub(crate) async fn probe_owned_backend_state_with_timeout(
if verified.len() != 1 {
return OwnedBackendProbe::NotVerified {
- reason: if verified.is_empty() {
- "owned_backend_not_found".to_string()
- } else {
+ reason: if !verified.is_empty() {
"owned_backend_ambiguous".to_string()
+ } else if answered_with_a_different_owner {
+ OWNED_BACKEND_OWNER_MISMATCH.to_string()
+ } else {
+ "owned_backend_not_found".to_string()
},
};
}
@@ -1511,6 +1535,139 @@ mod tests {
}
}
+ /// A backend that answers the ownership probe's first request and then goes quiet, the
+ /// way a saturated one does. The later connections are parked, not closed: closing them
+ /// would answer with a reset, which is a different failure entirely.
+ async fn owned_backend_that_stalls_after_the_first_request() -> u16 {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpListener;
+
+ let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let body = format!(
+ r#"{{"status":"alive","service":"Unsloth UI Backend","desktop_protocol_version":{},"desktop_manageability_version":{},"supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"studio_root_id":"{}","desktop_owner":{{"kind":"{}","token_sha256":"{}"}},"inference_active":true}}"#,
+ crate::preflight::DESKTOP_PROTOCOL_VERSION,
+ crate::preflight::DESKTOP_MANAGEABILITY_VERSION,
+ ROOT_ID,
+ OWNER_KIND_TAURI,
+ token_sha256(TOKEN),
+ );
+ tokio::spawn(async move {
+ let mut answered = false;
+ let mut parked = Vec::new();
+ while let Ok((mut socket, _)) = listener.accept().await {
+ if answered {
+ parked.push(socket);
+ continue;
+ }
+ answered = true;
+ let mut chunk = [0u8; 2048];
+ let _ = socket.read(&mut chunk).await;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ }
+ });
+ port
+ }
+
+ #[tokio::test]
+ async fn a_stall_after_the_first_request_is_indistinguishable_from_a_foreign_port() {
+ // Why the health watchdog cannot ask this probe whether a failure was a stall: the
+ // liveness GET succeeds and verifies ownership, then the desktop-login POST runs out
+ // of budget, and the answer that comes back carries no trace of which it was. The
+ // watchdog has to classify the failure from its own read instead, which is what
+ // `commands::adopted_failure_is_a_stall` does. Only the opposite case is decidable
+ // here, and is reported as `OWNED_BACKEND_OWNER_MISMATCH`: a port that answered in
+ // full for somebody else did not fall silent, so it is not a stall.
+ let port = owned_backend_that_stalls_after_the_first_request().await;
+ // The probe never touches the file, so nothing has to exist on disk for this.
+ let owner = BackendOwnerState::from_metadata(
+ std::env::temp_dir().join("unsloth-stall-after-first-request.json"),
+ metadata(std::process::id(), Some(port)),
+ );
+
+ let probe = probe_owned_backend_state_with_timeout(
+ owner,
+ Some(port),
+ false,
+ Duration::from_millis(400),
+ )
+ .await;
+
+ match probe {
+ OwnedBackendProbe::Unmanageable { reason, .. } => {
+ assert_eq!(reason, "desktop_login_probe_failed");
+ }
+ OwnedBackendProbe::NotVerified { reason } => {
+ assert_eq!(reason, "owned_backend_not_found");
+ }
+ other => panic!("a stalled owned backend should not verify: {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn a_port_taken_over_by_another_backend_is_reported_as_an_owner_mismatch() {
+ // The other half of the classification above. A backend the app adopted can exit and
+ // have its port rebound by the next Unsloth backend the user starts, which answers
+ // the watchdog's pre-probe exactly as the old one did. The probe gets a complete
+ // reply here, not silence, so it must say so: the watchdog reads this to keep the
+ // dead adopted backend on the normal three-strike budget instead of the busy one.
+ //
+ // A backend started outside the app omits `desktop_owner` entirely (main.py only
+ // emits the key when one is loaded), and a second app instance sends a different
+ // token hash. Both are takeovers.
+ for body in [
+ // Same install, so the root id matches; no desktop owner at all.
+ r#"{"status":"alive","service":"Unsloth UI Backend","studio_root_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","supports_desktop_auth":true,"supports_desktop_backend_ownership":true}"#,
+ // A desktop-owned backend, but not the one this app is holding.
+ r#"{"status":"alive","service":"Unsloth UI Backend","studio_root_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","supports_desktop_auth":true,"supports_desktop_backend_ownership":true,"desktop_owner":{"kind":"tauri","token_sha256":"0000000000000000000000000000000000000000000000000000000000000000"}}"#,
+ ] {
+ let (port, _, server) = http_sequence_server(vec![("200 OK", body)]).await;
+ let owner = BackendOwnerState::from_metadata(
+ std::env::temp_dir().join("unsloth-port-taken-over.json"),
+ metadata(std::process::id(), Some(port)),
+ );
+
+ let probe = probe_owned_backend_state_with_timeout(
+ owner,
+ Some(port),
+ false,
+ Duration::from_secs(5),
+ )
+ .await;
+ server.await.unwrap();
+
+ assert!(
+ probe_saw_a_different_owner(&probe),
+ "a port answering for a different owner read as silence: {probe:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_port_that_says_nothing_is_not_reported_as_an_owner_mismatch() {
+ // The guard on the above: a closed port and a stalled one both fail to verify, and
+ // neither is evidence that someone else took the port. Only a parsed answer is.
+ let port = closed_port();
+ let owner = BackendOwnerState::from_metadata(
+ std::env::temp_dir().join("unsloth-silent-port.json"),
+ metadata(std::process::id(), Some(port)),
+ );
+
+ let probe =
+ probe_owned_backend_state_with_timeout(owner, Some(port), false, Duration::from_secs(5))
+ .await;
+
+ assert!(!probe_saw_a_different_owner(&probe), "{probe:?}");
+ assert!(matches!(
+ probe,
+ OwnedBackendProbe::NotVerified { ref reason } if reason == "owned_backend_not_found"
+ ));
+ }
+
#[test]
fn legacy_manageability_backend_stays_lifecycle_controllable() {
// A backend from the previous app version reports manageability 1.
diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rs
index 2d3c14ae257..062ec6279fa 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -705,6 +705,16 @@ mod tests {
struct ManagedCapabilityCacheHome {
path: PathBuf,
previous: Option<std::ffi::OsString>,
+ /// Held for as long as the override is installed.
+ ///
+ /// The tokio mutex above only keeps these two tests off each other. `set_var` is
+ /// process-wide, and other test modules read the environment through `dirs` under
+ /// `PROCESS_ENV_LOCK` -- `main.rs`'s `with_xdg_data_home` above all. Writing the
+ /// environment outside that lock lets glibc free the old entry under a concurrent
+ /// reader, so `webview_profile_root` resolves the real `~/.local/share` instead of
+ /// the tempdir the caller set, and the three webview-profile tests then collide on
+ /// one lock file. Declared last so it outlives the restore in `Drop` below.
+ _env: std::sync::MutexGuard<'static, ()>,
}
#[cfg(unix)]
@@ -712,6 +722,9 @@ mod tests {
fn new(test_name: &str) -> Self {
use std::time::{SystemTime, UNIX_EPOCH};
+ let _env = crate::native_path_policy::PROCESS_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
@@ -723,7 +736,11 @@ mod tests {
std::fs::create_dir_all(&path).unwrap();
let previous = std::env::var_os("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME");
std::env::set_var("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME", &path);
- Self { path, previous }
+ Self {
+ path,
+ previous,
+ _env,
+ }
}
}