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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio desktop: give port validation probes the health watchdog's 10 s budget (#15670)
Daniel Hanb2e2ea8b3b13
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rsindex b8483d4ffbd..e8c98ee1dac 100644--- a/studio/src-tauri/src/desktop_backend_owner.rs+++ b/studio/src-tauri/src/desktop_backend_owner.rs@@ -1715,6 +1715,80 @@ mod tests {}}+ /// First liveness answer delayed by `stall` (warm-up holding the GIL); desktop-login gets 401.+ async fn owned_backend_that_answers_after(stall: Duration) -> 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":"{}"}}}}"#,+ crate::preflight::DESKTOP_PROTOCOL_VERSION,+ crate::preflight::DESKTOP_MANAGEABILITY_VERSION,+ ROOT_ID,+ OWNER_KIND_TAURI,+ token_sha256(TOKEN),+ );+ tokio::spawn(async move {+ let mut first = true;+ while let Ok((mut socket, _)) = listener.accept().await {+ let mut chunk = [0u8; 4096];+ let read = socket.read(&mut chunk).await.unwrap_or(0);+ let request = String::from_utf8_lossy(&chunk[..read]).into_owned();+ let response = if request.starts_with("GET /api/liveness") {+ if first {+ first = false;+ tokio::time::sleep(stall).await;+ }+ format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ )+ } else {+ "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"+ .to_string()+ };+ let _ = socket.write_all(response.as_bytes()).await;+ }+ });+ port+ }++ #[tokio::test]+ async fn a_backend_answering_after_a_gil_stall_verifies_within_the_port_validation_budget() {+ let stall = Duration::from_millis(2_500);+ assert!(stall > LOCAL_HTTP_TIMEOUT);+ assert!(stall < crate::process::PORT_VALIDATION_PROBE_TIMEOUT);++ let port = owned_backend_that_answers_after(stall).await;+ let owner = BackendOwnerState::from_metadata(+ std::env::temp_dir().join("unsloth-gil-stall-default-budget.json"),+ metadata(std::process::id(), Some(port)),+ );+ let probe = probe_owned_backend_state(owner, Some(port), false).await;+ assert!(!matches!(probe, OwnedBackendProbe::Verified(_)), "{probe:?}");++ let port = owned_backend_that_answers_after(stall).await;+ let owner = BackendOwnerState::from_metadata(+ std::env::temp_dir().join("unsloth-gil-stall-validation-budget.json"),+ metadata(std::process::id(), Some(port)),+ );+ let started = std::time::Instant::now();+ let probe = probe_owned_backend_state_with_timeout(+ owner,+ Some(port),+ false,+ crate::process::PORT_VALIDATION_PROBE_TIMEOUT,+ )+ .await;+ assert!(+ matches!(probe, OwnedBackendProbe::Verified(VerifiedOwnedBackend { port: verified, .. }) if verified == port),+ "{probe:?}"+ );+ assert!(started.elapsed() < stall + Duration::from_secs(2));+ }+#[tokio::test]async fn a_port_taken_over_by_another_backend_is_reported_as_an_owner_mismatch() {// A rebound port answers the pre-probe in full, so the probe must report the mismatch (thediff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 85c762f5891..87ecb0309a0 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -3529,9 +3529,9 @@ pub fn start_backend(Ok(generation)}-async fn generic_backend_health_ok(port: u16) -> bool {+async fn generic_backend_health_ok(port: u16, timeout: Duration) -> bool {let started = std::time::Instant::now();- let client = match crate::loopback_http::client(Duration::from_secs(2)) {+ let client = match crate::loopback_http::client(timeout) {Ok(client) => client,Err(error) => {warn!("Could not build backend validation client: {}", error);@@ -3611,6 +3611,8 @@ async fn generic_backend_health_ok(port: u16) -> bool {/// Doubling backoff: each probe costs two requests against a busy backend.const PORT_VALIDATION_RETRY_MIN: Duration = Duration::from_millis(250);+/// The health watchdog's per-request budget: warm-up right after TAURI_PORT can hold the GIL past 2s.+pub(crate) const PORT_VALIDATION_PROBE_TIMEOUT: Duration = Duration::from_secs(10);const PORT_VALIDATION_RETRY_MAX: Duration = Duration::from_secs(5);async fn validate_candidate_port(@@ -3650,16 +3652,24 @@ async fn validate_candidate_port(break false;}attempts += 1;+ // Never past the deadline: the answer would be discarded anyway.+ let budget = PORT_VALIDATION_PROBE_TIMEOUT+ .min(deadline.saturating_duration_since(std::time::Instant::now()));let ok = if let Some(owner) = owner.clone() {matches!(- crate::desktop_backend_owner::probe_owned_backend_state(owner, Some(port), false)- .await,+ crate::desktop_backend_owner::probe_owned_backend_state_with_timeout(+ owner,+ Some(port),+ false,+ budget,+ )+ .await,crate::desktop_backend_owner::OwnedBackendProbe::Verified(crate::desktop_backend_owner::VerifiedOwnedBackend { port: verified_port, .. }) if verified_port == port)} else {- generic_backend_health_ok(port).await+ generic_backend_health_ok(port, budget).await};if ok {// A late success must not emit server-port after server-start-timeout.@@ -5873,6 +5883,27 @@ mod managed_cli_working_dir_tests {}}+#[cfg(test)]+mod port_validation_budget_tests {+ #[test]+ fn port_validation_probes_use_the_validation_budget() {+ let src = include_str!("process.rs").replace("\r\n", "\n");+ let start = src+ .find("async fn validate_candidate_port(")+ .expect("validate_candidate_port moved; update this guard");+ let body = &src[start..];+ let body = &body[..body.find("\n}\n").expect("could not find the function end")];+ assert!(body.contains("PORT_VALIDATION_PROBE_TIMEOUT"));+ assert!(body.contains("probe_owned_backend_state_with_timeout("));+ assert!(body.contains("generic_backend_health_ok(port, budget)"));+ assert!(!body.contains("probe_owned_backend_state(owner"));+ assert!(+ super::PORT_VALIDATION_PROBE_TIMEOUT >= std::time::Duration::from_secs(10),+ "keep the validation budget at least the health watchdog's"+ );+ }+}+// Real processes: stdout can EOF before the exit is visible to try_wait.#[cfg(test)]#[cfg(unix)]