Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(app): reap llama-server routers an older Jan left running at startup

thinhlpg099edc6c4d61
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index cc0ce8d44..893effbdb 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -60,6 +60,7 @@ dependencies = [
"sha2",
"sqlx",
"syntect",
+ "sysinfo",
"tar",
"tauri",
"tauri-build",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3289170d3..9bda35be9 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -294,6 +294,9 @@ reqwest13 = { package = "reqwest", version = "0.13", default-features = false, f
tauri-plugin-updater = { version = "2", optional = true }
once_cell = "1.18"
tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true }
+# Process table for the startup sweep of engines orphaned by an in-place update
+# (core/system/orphans.rs). Same version as the hardware and mlx plugins.
+sysinfo = "0.34.2"
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "rustls-tls"], default-features = false }
diff --git a/src-tauri/src/core/system/mod.rs b/src-tauri/src/core/system/mod.rs
index b3948e3c7..e76eff015 100644
--- a/src-tauri/src/core/system/mod.rs
+++ b/src-tauri/src/core/system/mod.rs
@@ -1,2 +1,5 @@
pub mod commands;
pub mod shutdown;
+// Process-table sweep; desktop-only, `sysinfo` is not a mobile dependency.
+#[cfg(not(any(target_os = "android", target_os = "ios")))]
+pub mod orphans;
diff --git a/src-tauri/src/core/system/orphans.rs b/src-tauri/src/core/system/orphans.rs
new file mode 100644
index 000000000..29cae8298
--- /dev/null
+++ b/src-tauri/src/core/system/orphans.rs
@@ -0,0 +1,329 @@
+//! Startup sweep for engines that an older Jan left running across an update.
+//!
+//! Up to 0.8.4 the engine was a `llama-server` router child of the desktop app.
+//! The in-app updater leaves the old app without running its exit cleanup (see
+//! `shutdown`), and 0.8.4 has shipped, so that version cannot be fixed. Every
+//! user who updates from it ends up with its router still running, holding RAM
+//! and VRAM and, on Linux, pinning the old AppImage mount. On Windows it also
+//! survives uninstalling Jan, because the binary lives in the data folder.
+//! The only place left to clean it up is the new version's startup.
+//!
+//! A process is swept only when all of these hold:
+//! - it is `llama-server`,
+//! - it was started with `--models-preset <data folder>/llamacpp/router.preset.ini`,
+//! the preset file Jan writes, so it belongs to this data folder,
+//! - its parent is gone or is not a Jan process, so a Jan that is still running
+//! (another instance, or this one) keeps its engine.
+//!
+//! Its descendants, the per-model children the router spawns, go with it.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
+
+const ROUTER_BINARY: &str = "llama-server";
+const ROUTER_PRESET_FILE: &str = "router.preset.ini";
+const PRESET_FLAG: &str = "--models-preset";
+
+/// The slice of a process the matcher needs, so it can be tested without
+/// spawning anything.
+#[derive(Debug, Clone)]
+pub struct ProcInfo {
+ pub pid: u32,
+ pub parent: Option<u32>,
+ pub name: String,
+ pub cmd: Vec<String>,
+}
+
+fn normalize(path: &str) -> String {
+ path.replace('\\', "/").to_ascii_lowercase()
+}
+
+fn is_router_binary(name: &str) -> bool {
+ let name = name.to_ascii_lowercase();
+ let stem = name.strip_suffix(".exe").unwrap_or(&name);
+ stem == ROUTER_BINARY
+}
+
+/// The value of `--models-preset`, in either `--flag value` or `--flag=value`
+/// form.
+fn preset_arg(cmd: &[String]) -> Option<&str> {
+ let mut args = cmd.iter();
+ while let Some(arg) = args.next() {
+ if arg == PRESET_FLAG {
+ return args.next().map(String::as_str);
+ }
+ if let Some(value) = arg
+ .strip_prefix(PRESET_FLAG)
+ .and_then(|r| r.strip_prefix('='))
+ {
+ return Some(value);
+ }
+ }
+ None
+}
+
+/// Whether `proc` is a router started from Jan's preset under `llamacpp_dir`.
+fn is_jan_router(proc: &ProcInfo, llamacpp_dir: &str) -> bool {
+ if !is_router_binary(&proc.name) {
+ return false;
+ }
+ let Some(preset) = preset_arg(&proc.cmd) else {
+ return false;
+ };
+ let preset = normalize(preset);
+ preset.rsplit('/').next() == Some(ROUTER_PRESET_FILE)
+ && preset.starts_with(&format!("{llamacpp_dir}/"))
+}
+
+/// A Jan process, judged by name: `Jan`, `jan`, `Jan.exe`, `Jan-Desktop.exe`.
+fn is_jan(name: &str) -> bool {
+ name.to_ascii_lowercase().contains("jan")
+}
+
+/// Orphaned when the parent no longer exists, was adopted by init (pid 1), or is
+/// something other than Jan. The last case covers a systemd user session
+/// adopting the process on Linux, where the new parent is not pid 1.
+fn is_orphaned(proc: &ProcInfo, by_pid: &HashMap<u32, &ProcInfo>) -> bool {
+ match proc.parent {
+ None | Some(1) => true,
+ Some(parent) => by_pid.get(&parent).is_none_or(|p| !is_jan(&p.name)),
+ }
+}
+
+/// Pids to kill, children before their router.
+pub fn orphaned_engine_pids(procs: &[ProcInfo], data_folder: &Path) -> Vec<u32> {
+ let llamacpp_dir = normalize(&data_folder.join("llamacpp").to_string_lossy());
+ let llamacpp_dir = llamacpp_dir.trim_end_matches('/');
+ let by_pid: HashMap<u32, &ProcInfo> = procs.iter().map(|p| (p.pid, p)).collect();
+
+ let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
+ for p in procs {
+ if let Some(parent) = p.parent {
+ children.entry(parent).or_default().push(p.pid);
+ }
+ }
+
+ let mut victims = Vec::new();
+ let mut seen = HashSet::new();
+ for router in procs
+ .iter()
+ .filter(|p| is_jan_router(p, llamacpp_dir) && is_orphaned(p, &by_pid))
+ {
+ // Post-order walk: descendants first, so killing the router never
+ // leaves a child to be adopted.
+ let mut order = vec![router.pid];
+ let mut i = 0;
+ while i < order.len() {
+ if let Some(kids) = children.get(&order[i]) {
+ order.extend(kids.iter().copied());
+ }
+ i += 1;
+ }
+ for pid in order.into_iter().rev() {
+ if seen.insert(pid) {
+ victims.push(pid);
+ }
+ }
+ }
+ victims
+}
+
+/// Kills every engine an older Jan left behind. Returns how many processes were
+/// killed. Blocking: run it off the async runtime.
+pub fn sweep_orphaned_engines(data_folder: &Path) -> usize {
+ // A fresh install, or a user who never ran the llama.cpp engine, has
+ // nothing to sweep and should not pay for a process-table scan.
+ if !data_folder.join("llamacpp").is_dir() {
+ return 0;
+ }
+
+ let mut system = System::new();
+ system.refresh_processes_specifics(
+ ProcessesToUpdate::All,
+ true,
+ ProcessRefreshKind::nothing().with_cmd(UpdateKind::Always),
+ );
+ let procs: Vec<ProcInfo> = system
+ .processes()
+ .values()
+ .map(|p| ProcInfo {
+ pid: p.pid().as_u32(),
+ parent: p.parent().map(Pid::as_u32),
+ name: p.name().to_string_lossy().into_owned(),
+ cmd: p
+ .cmd()
+ .iter()
+ .map(|a| a.to_string_lossy().into_owned())
+ .collect(),
+ })
+ .collect();
+
+ let victims = orphaned_engine_pids(&procs, data_folder);
+ let mut killed = 0;
+ for pid in victims {
+ let Some(process) = system.process(Pid::from_u32(pid)) else {
+ continue;
+ };
+ log::warn!(
+ "Killing llama-server left running by a previous Jan: pid {pid}, parent {:?}",
+ process.parent()
+ );
+ if process.kill() {
+ killed += 1;
+ } else {
+ log::warn!("Could not kill orphaned llama-server pid {pid}");
+ }
+ }
+ killed
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ const DATA: &str = "/home/u/.local/share/Jan/data";
+ const PRESET: &str = "/home/u/.local/share/Jan/data/llamacpp/router.preset.ini";
+
+ fn proc(pid: u32, parent: Option<u32>, name: &str, cmd: &[&str]) -> ProcInfo {
+ ProcInfo {
+ pid,
+ parent,
+ name: name.to_string(),
+ cmd: cmd.iter().map(|s| s.to_string()).collect(),
+ }
+ }
+
+ fn router(pid: u32, parent: Option<u32>) -> ProcInfo {
+ proc(
+ pid,
+ parent,
+ "llama-server",
+ &[
+ "/opt/llama-server",
+ "--models-preset",
+ PRESET,
+ "--port",
+ "1337",
+ ],
+ )
+ }
+
+ fn sweep(procs: &[ProcInfo]) -> Vec<u32> {
+ orphaned_engine_pids(procs, &PathBuf::from(DATA))
+ }
+
+ #[test]
+ fn a_router_adopted_by_init_is_swept_with_its_children_first() {
+ let procs = [
+ router(200, Some(1)),
+ proc(
+ 201,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ ),
+ proc(
+ 202,
+ Some(200),
+ "llama-server",
+ &["llama-server", "-m", "b.gguf"],
+ ),
+ ];
+ let victims = sweep(&procs);
+ assert_eq!(victims.last(), Some(&200), "router goes last: {victims:?}");
+ assert_eq!(victims.len(), 3);
+ }
+
+ #[test]
+ fn a_router_whose_jan_is_still_running_is_left_alone() {
+ for jan in ["Jan", "jan", "Jan.exe", "Jan-Desktop.exe"] {
+ let procs = [proc(50, Some(1), jan, &[jan]), router(200, Some(50))];
+ assert!(sweep(&procs).is_empty(), "{jan} still owns its engine");
+ }
+ }
+
+ #[test]
+ fn a_router_adopted_by_a_systemd_user_session_is_swept() {
+ let procs = [
+ proc(900, Some(1), "systemd", &["systemd", "--user"]),
+ router(200, Some(900)),
+ ];
+ assert_eq!(sweep(&procs), vec![200]);
+ }
+
+ #[test]
+ fn a_router_whose_parent_exited_is_swept() {
+ // Windows does not reparent: the parent pid just stops existing.
+ assert_eq!(sweep(&[router(200, Some(4242))]), vec![200]);
+ assert_eq!(sweep(&[router(200, None)]), vec![200]);
+ }
+
+ #[test]
+ fn a_router_of_another_data_folder_is_left_alone() {
+ let other = proc(
+ 200,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/srv/other/llamacpp/router.preset.ini",
+ ],
+ );
+ assert!(sweep(&[other]).is_empty());
+ }
+
+ #[test]
+ fn a_llama_server_that_is_not_a_jan_router_is_left_alone() {
+ // The user's own llama-server, with or without a preset of their own.
+ let plain = proc(
+ 200,
+ Some(1),
+ "llama-server",
+ &["llama-server", "-m", "a.gguf"],
+ );
+ let own_preset = proc(
+ 201,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/home/u/presets/mine.ini",
+ ],
+ );
+ // A preset with the right name but outside the data folder's llamacpp dir.
+ let lookalike = proc(
+ 202,
+ Some(1),
+ "llama-server",
+ &[
+ "llama-server",
+ "--models-preset",
+ "/home/u/.local/share/Jan/data/llamacpp-other/router.preset.ini",
+ ],
+ );
+ assert!(sweep(&[plain, own_preset, lookalike]).is_empty());
+ }
+
+ #[test]
+ fn the_equals_form_and_windows_paths_match() {
+ let eq = proc(
+ 200,
+ Some(4242),
+ "llama-server.exe",
+ &[
+ "C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\backends\\b1\\llama-server.exe",
+ "--models-preset=C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\router.preset.ini",
+ ],
+ );
+ let victims = orphaned_engine_pids(
+ &[eq],
+ &PathBuf::from("C:\\Users\\u\\AppData\\Roaming\\Jan\\data"),
+ );
+ assert_eq!(victims, vec![200]);
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 8a0be5a8b..dd9efe0df 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -373,6 +373,19 @@ pub fn run() {
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
+ // A Jan up to 0.8.4 leaves its llama-server router running across an
+ // in-app update; that version cannot be fixed, so reap it here.
+ #[cfg(not(any(target_os = "ios", target_os = "android")))]
+ {
+ let data_folder = get_jan_data_folder_path(app.handle().clone());
+ tauri::async_runtime::spawn_blocking(move || {
+ let killed = core::system::orphans::sweep_orphaned_engines(&data_folder);
+ if killed > 0 {
+ log::warn!("Reaped {killed} engine process(es) left by a previous Jan");
+ }
+ });
+ }
+
// Start migration
let mut store_path = get_jan_data_folder_path(app.handle().clone());
store_path.push("store.json");