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
fix(logs): include the backend session log in the support diagnostics report (#8877)
Leo Borcherdingb57ad5989309
diff --git a/studio/src-tauri/src/diagnostics/report.rs b/studio/src-tauri/src/diagnostics/report.rsindex 303cba8b18c..268d5c59888 100644--- a/studio/src-tauri/src/diagnostics/report.rs+++ b/studio/src-tauri/src/diagnostics/report.rs@@ -1,7 +1,7 @@use std::fs::{self, File};use std::io::{Read, Seek, SeekFrom};-use std::path::Path;-use std::time::UNIX_EPOCH;+use std::path::{Path, PathBuf};+use std::time::{SystemTime, UNIX_EPOCH};use super::phase_log::{collect_phase_groups, path_has_symlink};use super::redaction::{redact_text, RedactionReport};@@ -363,6 +363,34 @@ fn append_log_sections(append_tail_section(out, &path, name, "local-app-log", warnings);}+ let server_log_dir = logs_dir().join("server");+ let server_logs = newest_server_logs_in(&server_log_dir, SERVER_LOG_TAIL_FILES, warnings);+ if server_logs.is_empty() {+ // Name the directory: an adopted backend can take its studio root from+ // sys.prefix (storage_roots.py `_infer_studio_home_from_venv`), past any+ // env scrub, so bare "unavailable" cannot be told from "logs elsewhere".+ out.push_str(&format!(+ "backend_session_logs=unavailable searched={}\n",+ server_log_dir.display()+ ));+ }+ for path in server_logs {+ let label = path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or("server.log")+ .to_string();+ append_tail_section_capped(+ out,+ &path,+ &label,+ "backend-session-log",+ SERVER_LOG_TAIL_MAX_LINES,+ SERVER_LOG_TAIL_MAX_BYTES,+ warnings,+ );+ }+let phase_groups = collect_phase_groups(snapshot, warnings);if phase_groups.is_empty() {out.push_str("phase_logs=unavailable\n");@@ -381,6 +409,106 @@ fn append_log_sections(}}+/// Two, so a crash and the restart after it both land in one report.+const SERVER_LOG_TAIL_FILES: usize = 2;++/// Smaller than the other tails on purpose: enforce_report_limit chops the END of+/// the body, so bytes spent here come out of the phase logs below, and a faulthandler+/// dump is a few KB at the end of the file, which is the half read_tail returns.+const SERVER_LOG_TAIL_MAX_LINES: usize = 400;+const SERVER_LOG_TAIL_MAX_BYTES: usize = 64 * 1024;++/// Newest `server-*.log` files, most recent first.+///+/// run.py's `_setup_server_disk_logging` aims faulthandler here, so when the GPU+/// runtime aborts this holds the Python stack naming the call that died, and no+/// other file Studio keeps does.+///+/// Only two are collected, so an entry is rejected HERE rather than later in+/// `read_tail`: one that merely matches the name would otherwise spend a slot and+/// push the real crash log out. `scan_phase_logs_in_dir` screens during selection+/// for the same reason.+fn newest_server_logs_in(dir: &Path, max: usize, warnings: &mut Vec<String>) -> Vec<PathBuf> {+ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(error) => {+ // Missing is the ordinary case, not a fault: a --no-torch host,+ // UNSLOTH_STUDIO_NO_FILE_LOG=1, or a backend never started. Anything+ // else, a permission wall above all, is worth saying out loud.+ if error.kind() != std::io::ErrorKind::NotFound {+ warnings.push(format!(+ "backend session log dir unavailable: {} ({})",+ dir.display(),+ error+ ));+ }+ return Vec::new();+ }+ };+ let mut logs: Vec<(SystemTime, PathBuf)> = Vec::new();+ for entry in entries.flatten() {+ let path = entry.path();+ let Some(name) = entry.file_name().to_str().map(str::to_owned) else {+ continue;+ };+ if !name.starts_with("server-") || !name.ends_with(".log") {+ continue;+ }+ // The header and the path print verbatim into a line-oriented, ```text-fenced+ // report, and a Unix filename may hold a newline or a backtick, so a matching+ // name could forge report structure.+ if name.contains(|ch: char| ch.is_control() || ch == '`') {+ warnings.push(format!(+ "ignored backend session log with an unprintable name in {}",+ dir.display()+ ));+ continue;+ }+ if path_has_symlink(&path) {+ warnings.push(format!(+ "ignored backend session log symlink: {}",+ path.display()+ ));+ continue;+ }+ let Ok(metadata) = entry.metadata() else {+ continue;+ };+ // Regular files only. A directory reads back as EISDIR; a FIFO is worse,+ // since `File::open` on one blocks until a writer appears, hanging report+ // generation rather than failing it.+ if !metadata.is_file() {+ warnings.push(format!(+ "ignored non-regular backend session log: {}",+ path.display()+ ));+ continue;+ }+ // `metadata` is `stat`, which needs no permission on the file itself, so a+ // log we cannot read still looks like a candidate here and would spend a slot+ // that `read_tail` only refuses afterwards. A backend once started under sudo+ // leaves exactly that behind. Safe to open now: non-regular files are already+ // out, so this cannot be the FIFO that blocks.+ if let Err(error) = File::open(&path) {+ warnings.push(format!(+ "ignored unreadable backend session log: {} ({})",+ path.display(),+ error+ ));+ continue;+ }+ let Ok(modified) = metadata.modified() else {+ continue;+ };+ logs.push((modified, path));+ }+ // mtime decides; the name breaks an exact tie, descending like the mtime. `pidN`+ // is not zero-padded, so that tie-break is stable, not chronological.+ logs.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));+ logs.truncate(max);+ logs.into_iter().map(|(_, path)| path).collect()+}+fn append_tail_section(out: &mut String,path: &Path,@@ -388,7 +516,28 @@ fn append_tail_section(source: &str,warnings: &mut Vec<String>,) {- match read_tail(path, TAIL_MAX_LINES, TAIL_MAX_BYTES) {+ append_tail_section_capped(+ out,+ path,+ label,+ source,+ TAIL_MAX_LINES,+ TAIL_MAX_BYTES,+ warnings,+ );+}++#[allow(clippy::too_many_arguments)]+fn append_tail_section_capped(+ out: &mut String,+ path: &Path,+ label: &str,+ source: &str,+ max_lines: usize,+ max_bytes: usize,+ warnings: &mut Vec<String>,+) {+ match read_tail(path, max_lines, max_bytes) {Ok(tail) => {out.push_str(&format!("file={} label={} source={} size_bytes={} mtime_ms={} included_bytes={} included_lines={} truncated={}\n",@@ -511,7 +660,7 @@ fn render_footer(warnings: &[String], redaction: &RedactionReport) -> String {));footer.push_str("redaction_scope=ANSI, private keys, URL credentials, auth headers, cookies, token patterns, assignment-style secrets, studio/home paths, emails\n");footer.push_str(- "report_bounds=log sections <=1000 lines/200KiB each; total clipboard text <=1MiB\n",+ "report_bounds=log sections <=1000 lines/200KiB each; backend session logs <=400 lines/64KiB each; total clipboard text <=1MiB\n",);footer.push_str("known_v1_gap=elevated apt helper may buffer subprocess output before diagnostics caps it\n");footer.push_str("known_v1_gap=normal install elevation resume is linked in same-run state/report history; disk fallback conservatively includes recent install attempts but has no explicit install_group_id in V1\n");@@ -593,6 +742,223 @@ mod tests {assert!(report.contains("<studio_home>"));}+ fn server_log_dir(tag: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!(+ "unsloth-server-logs-{}-{}",+ tag,+ std::process::id()+ ));+ let _ = fs::remove_dir_all(&dir);+ fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn collect_names(dir: &Path, max: usize) -> (Vec<String>, Vec<String>) {+ let mut warnings = Vec::new();+ let found = newest_server_logs_in(dir, max, &mut warnings);+ let names = found+ .iter()+ .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())+ .collect();+ (names, warnings)+ }++ #[test]+ fn server_logs_are_newest_first_and_capped() {+ let dir = server_log_dir("order");+ for stamp in ["20260101-000000", "20260102-000000", "20260103-000000"] {+ fs::write(dir.join(format!("server-{stamp}-pid1.log")), b"x").unwrap();+ }++ let (names, _) = collect_names(&dir, 2);+ assert_eq!(+ names,+ vec![+ "server-20260103-000000-pid1.log",+ "server-20260102-000000-pid1.log"+ ]+ );+ fs::remove_dir_all(&dir).unwrap();+ }++ /// The test above cannot say WHICH key ordered it, since its names and mtimes+ /// agree. Make them disagree. A copied or restored log carries a stamp that is+ /// not its mtime, and the crash we want is the one written last.+ #[test]+ fn server_logs_order_by_mtime_not_by_name() {+ let dir = server_log_dir("order-key");+ let stale_name = dir.join("server-20260109-000000-pid9.log");+ let fresh_name = dir.join("server-20260101-000000-pid1.log");+ fs::write(&stale_name, b"x").unwrap();+ // Coarser than any filesystem timestamp granularity in play here.+ std::thread::sleep(std::time::Duration::from_millis(1100));+ fs::write(&fresh_name, b"x").unwrap();++ let (names, _) = collect_names(&dir, 1);+ assert_eq!(names, vec!["server-20260101-000000-pid1.log"]);+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn server_logs_ignore_unrelated_files() {+ let dir = server_log_dir("filter");+ fs::write(dir.join("server-20260101-000000-pid1.log"), b"x").unwrap();+ fs::write(dir.join("tauri.log"), b"x").unwrap();+ fs::write(dir.join("server-notes.txt"), b"x").unwrap();++ let (names, _) = collect_names(&dir, 5);+ assert_eq!(names, vec!["server-20260101-000000-pid1.log"]);+ fs::remove_dir_all(&dir).unwrap();+ }++ /// An entry that matches the name but cannot be read must not spend one of the+ /// two slots: rejecting it later in `read_tail` still costs the real crash log.+ #[test]+ fn unreadable_entries_never_take_a_slot_from_a_real_log() {+ let dir = server_log_dir("crowding");+ let real = dir.join("server-20260101-000000-pid1.log");+ fs::write(&real, b"Current thread 0x1 (most recent call first):\n").unwrap();+ fs::create_dir_all(dir.join("server-20260102-000000-pid2.log")).unwrap();+ #[cfg(unix)]+ {+ let decoy = dir.join("decoy.txt");+ fs::write(&decoy, b"not a session log\n").unwrap();+ std::os::unix::fs::symlink(&decoy, dir.join("server-20260103-000000-pid3.log"))+ .unwrap();+ }++ let (names, warnings) = collect_names(&dir, 2);+ assert_eq!(names, vec!["server-20260101-000000-pid1.log"]);+ assert!(warnings.iter().any(|w| w.contains("non-regular")));+ #[cfg(unix)]+ assert!(warnings.iter().any(|w| w.contains("symlink")));+ fs::remove_dir_all(&dir).unwrap();+ }++ /// A regular file we cannot open is the same defect wearing different clothes:+ /// `stat` needs no permission on the file, so it survives every check above and+ /// spends a slot. A backend once started under sudo leaves two of these behind.+ #[cfg(unix)]+ #[test]+ fn an_unreadable_log_never_takes_a_slot_from_a_readable_one() {+ use std::os::unix::fs::PermissionsExt;+ let dir = server_log_dir("unreadable");+ fs::write(+ dir.join("server-20260101-000000-pid1.log"),+ b"Current thread 0x1 (most recent call first):\n",+ )+ .unwrap();+ let locked: Vec<PathBuf> = [+ "server-20260102-000000-pid2.log",+ "server-20260103-000000-pid3.log",+ ]+ .iter()+ .map(|name| {+ let path = dir.join(name);+ fs::write(&path, b"locked\n").unwrap();+ fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap();+ path+ })+ .collect();++ // Mode 000 does not deny root, or anyone holding CAP_DAC_OVERRIDE, so in a+ // root container the fixture cannot express its own precondition and the+ // assertions below would report an environment, not a defect. Probe rather+ // than test the uid, since the capability can be held without being root.+ // Same reason test_recommended_folders_permission.py skips itself as root.+ if File::open(&locked[0]).is_ok() {+ for path in &locked {+ fs::set_permissions(path, fs::Permissions::from_mode(0o644)).unwrap();+ }+ fs::remove_dir_all(&dir).unwrap();+ eprintln!("skipped: this user can read a mode-000 file");+ return;+ }++ let (names, warnings) = collect_names(&dir, 2);+ // Restore before asserting, so a failure still leaves a removable directory.+ for path in &locked {+ fs::set_permissions(path, fs::Permissions::from_mode(0o644)).unwrap();+ }+ fs::remove_dir_all(&dir).unwrap();++ assert_eq!(names, vec!["server-20260101-000000-pid1.log"]);+ assert_eq!(+ warnings.iter().filter(|w| w.contains("unreadable")).count(),+ 2+ );+ }++ /// A newline in the name forges `key=value` lines in a report a maintainer then+ /// reads as structure.+ #[cfg(unix)]+ #[test]+ fn server_logs_reject_names_that_could_forge_report_structure() {+ let dir = server_log_dir("inject");+ fs::write(dir.join("server-20260101\ninjected=yes\n-pid1.log"), b"x").unwrap();+ fs::write(dir.join("server-20260102-000000-pid2.log"), b"x").unwrap();++ let (names, warnings) = collect_names(&dir, 5);+ assert_eq!(names, vec!["server-20260102-000000-pid2.log"]);+ assert!(warnings.iter().any(|w| w.contains("unprintable name")));+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn server_log_section_stays_inside_its_smaller_budget() {+ let dir = server_log_dir("budget");+ let path = dir.join("server-20260101-000000-pid1.log");+ // Wide lines so the BYTE cap binds first: with short ones the line cap alone+ // keeps the section small and raising the byte cap would go unnoticed.+ let wide = "x".repeat(1024);+ let bulk: String = (0..1_000).map(|i| format!("line {i} {wide}\n")).collect();+ fs::write(+ &path,+ format!("{bulk}Current thread 0x1 (most recent call first):\n"),+ )+ .unwrap();++ let mut out = String::new();+ let mut warnings = Vec::new();+ append_tail_section_capped(+ &mut out,+ &path,+ "server.log",+ "backend-session-log",+ SERVER_LOG_TAIL_MAX_LINES,+ SERVER_LOG_TAIL_MAX_BYTES,+ &mut warnings,+ );++ // A literal, not a multiple of the constant under test, which would scale with+ // any raise and never catch one. 80 KiB clears the 64 KiB cap and its header+ // while still catching a raise far short of TAIL_MAX_BYTES; at the 128 KiB+ // this once allowed, a mutation to 100 KiB passed unnoticed.+ assert!(+ out.len() < 80 * 1024,+ "section grew into the phase-log budget: {}",+ out.len()+ );+ assert!(+ TAIL_MAX_BYTES >= 80 * 1024,+ "budget headroom assumption broke"+ );+ // The faulthandler stack sits at the end of the file, so the tail must keep it.+ assert!(out.contains("Current thread 0x1 (most recent call first):"));+ fs::remove_dir_all(&dir).unwrap();+ }++ #[test]+ fn server_logs_absent_directory_is_empty() {+ let missing =+ std::env::temp_dir().join(format!("unsloth-no-server-logs-{}", std::process::id()));+ let _ = fs::remove_dir_all(&missing);+ let mut warnings = Vec::new();+ assert!(newest_server_logs_in(&missing, 2, &mut warnings).is_empty());+ // A backend that never started is the ordinary case, not a warning.+ assert!(warnings.is_empty(), "{warnings:?}");+ }+#[test]fn tail_handles_missing_and_non_utf8() {let missing =@@ -606,4 +972,72 @@ mod tests {assert!(tail.text.contains('�'));let _ = fs::remove_file(path);}++ /// The worst of the three. `read_tail` runs on the blocking pool behind the+ /// support-report command, so reaching a FIFO does not skip a log, it wedges the+ /// thread and the report never returns. On a deadline, because a regression here+ /// hangs the suite rather than failing it.+ #[cfg(unix)]+ #[test]+ fn a_fifo_named_like_a_log_cannot_wedge_the_report() {+ use std::ffi::CString;+ let dir = server_log_dir("fifo");+ fs::write(+ dir.join("server-20260101-000000-pid1.log"),+ b"Current thread 0x1 (most recent call first):\n",+ )+ .unwrap();+ let fifo = dir.join("server-20260103-000000-pid3.log");+ let name = CString::new(fifo.as_os_str().to_str().unwrap()).unwrap();+ assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0);++ let (tx, rx) = std::sync::mpsc::channel();+ let probe = dir.clone();+ std::thread::spawn(move || {+ let mut warnings = Vec::new();+ let found = newest_server_logs_in(&probe, 2, &mut warnings);+ let mut out = String::new();+ for path in &found {+ append_tail_section_capped(+ &mut out,+ path,+ "server.log",+ "backend-session-log",+ SERVER_LOG_TAIL_MAX_LINES,+ SERVER_LOG_TAIL_MAX_BYTES,+ &mut warnings,+ );+ }+ let _ = tx.send(out);+ });+ let out = rx+ .recv_timeout(std::time::Duration::from_secs(20))+ .expect("collection blocked on the fifo");+ assert!(out.contains("Current thread 0x1 (most recent call first):"));++ let _ = fs::remove_file(&fifo);+ let _ = fs::remove_dir_all(&dir);+ }++ /// The section sits above the phase logs and enforce_report_limit chops the END,+ /// so a report that overflows the clipboard budget must still carry the stack.+ #[test]+ fn a_truncated_report_still_carries_the_crash_stack() {+ let stack = "Current thread 0x1 (most recent call first):";+ let mut body = String::from("Unsloth Support Diagnostics\n\n== Log tails ==\n");+ body.push_str(&format!(+ "file=server.log source=backend-session-log\n```text\n{stack}\n```\n"+ ));+ body.push_str(&"phase log filler line\n".repeat(60_000));+ let footer = render_footer(&["w".to_string()], &RedactionReport::default());+ assert!(+ body.len() + footer.len() > REPORT_MAX_BYTES,+ "fixture no longer overflows"+ );++ let out = enforce_report_limit(body, footer);+ assert!(out.len() <= REPORT_MAX_BYTES);+ assert!(out.contains("report truncated"));+ assert!(out.contains(stack));+ }}