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: let repair proceed past a backend that is not ours (#8459)

Daniel Hanba282168aeea
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
index 1ab267aa949..8705acf9a4c 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -1052,6 +1052,16 @@ async fn probe_verified_owned_backend_at_path_with_expected(
Ok(probe_owned_backend_state(owner, port, true).await)
}
+/// False only when the pid is provably gone.
+///
+/// A pid we cannot resolve counts as running: on Windows an OpenProcess that
+/// fails for anything but a bad pid usually means the process is there and
+/// owned by somebody else, and every caller here treats "still running" as the
+/// safe answer.
+pub(crate) fn pid_is_not_dead(pid: u32) -> bool {
+ process_liveness(pid) != PreviousAppPidStatus::Dead
+}
+
fn previous_app_pid_status(pid: u32) -> PreviousAppPidStatus {
if pid == 0 || pid == std::process::id() {
return PreviousAppPidStatus::AliveOrCurrent;
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 6d725af9b03..9e4219a258a 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -18,6 +18,7 @@ mod native_intents;
mod native_path_policy;
mod preflight;
mod process;
+mod process_identity;
mod update;
mod windows_job;
mod x11_threads;
diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rs
index 552bf4c398c..a43bc8138b3 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -1,5 +1,6 @@
mod backend;
mod managed;
+mod pid_records;
mod types;
mod version;
@@ -7,7 +8,7 @@ use crate::desktop_backend_owner::{
OwnedBackendProbe, OwnedBackendReadiness, VerifiedOwnedBackend,
};
use backend::probe_existing_backends;
-use log::warn;
+use log::{info, warn};
pub use managed::managed_install_ready;
use managed::probe_managed_install;
use std::path::PathBuf;
@@ -163,15 +164,30 @@ fn choose_ownerless_spawned_preflight(
}
}
-fn mutation_blocker_from_probe(probe: BackendProbe) -> Option<ExternalBackendConflict> {
+fn mutation_blocker_from_probe(
+ probe: BackendProbe,
+ live_local_backend: &dyn Fn(u16) -> Option<u32>,
+) -> Option<ExternalBackendConflict> {
match probe {
- // A launch may step over an unadoptable backend; rewriting the venv may
- // not. We cannot prove an id-less backend is not running out of our own
- // install, so a mutation still refuses, exactly as it did before.
- BackendProbe::ExternalConflict { port, reason }
- | BackendProbe::Unrelated { port, reason } => {
+ BackendProbe::ExternalConflict { port, reason } => {
Some(ExternalBackendConflict { port, reason })
}
+ // An id-less backend may be this install serving from a terminal, in
+ // which case rewriting the venv underneath it would break it. It may
+ // equally be a remote Studio behind a port forward, and refusing on
+ // that leaves a stale install with no way to repair itself, since
+ // repair is what the app runs automatically. The local per-port record
+ // is what tells the two apart, so it, not the port, decides.
+ BackendProbe::Unrelated { port, reason } => match live_local_backend(port) {
+ Some(pid) => {
+ info!("Desktop preflight: mutation blocked by local backend {pid} on port {port}");
+ Some(ExternalBackendConflict { port, reason })
+ }
+ None => {
+ info!("Desktop preflight: mutation may proceed past port {port} ({reason}): no live backend of this install is recorded there");
+ None
+ }
+ },
BackendProbe::Ready { port } => Some(ExternalBackendConflict {
port,
reason: "same_root_external_backend_active".to_string(),
@@ -186,7 +202,9 @@ pub async fn mutation_blocking_backend_ignoring(
backend::probe_backend_ports(ignored_ports)
.await
.into_iter()
- .find_map(mutation_blocker_from_probe)
+ .find_map(|probe| {
+ mutation_blocker_from_probe(probe, &pid_records::live_backend_pid_on_port)
+ })
}
pub async fn desktop_preflight_result() -> DesktopPreflightResult {
@@ -432,7 +450,7 @@ mod tests {
#[test]
fn mutation_blocker_blocks_ready_external_backends() {
assert_eq!(
- mutation_blocker_from_probe(BackendProbe::Ready { port: 8890 }),
+ mutation_blocker_from_probe(BackendProbe::Ready { port: 8890 }, &|_| None),
Some(ExternalBackendConflict {
port: 8890,
reason: "same_root_external_backend_active".to_string(),
@@ -973,15 +991,18 @@ exit 1
assert_eq!(result.port, None);
}
- /// ...but a venv rewrite underneath it is still refused, because we cannot
- /// rule out that it is our own install serving from a terminal.
+ /// ...and a venv rewrite is still refused while a local backend of this
+ /// install is recorded on the port, because it would break that backend.
#[test]
- fn an_unrelated_backend_still_blocks_mutations() {
+ fn an_unrelated_backend_blocks_mutations_when_it_is_recorded_locally() {
assert_eq!(
- mutation_blocker_from_probe(BackendProbe::Unrelated {
- port: 8899,
- reason: "ambiguous_root_external_backend_active".to_string(),
- }),
+ mutation_blocker_from_probe(
+ BackendProbe::Unrelated {
+ port: 8899,
+ reason: "ambiguous_root_external_backend_active".to_string(),
+ },
+ &|port| (port == 8899).then_some(4242)
+ ),
Some(ExternalBackendConflict {
port: 8899,
reason: "ambiguous_root_external_backend_active".to_string(),
@@ -989,6 +1010,42 @@ exit 1
);
}
+ /// The follow-up report: a stale install auto-runs a repair, and an id-less
+ /// backend reached over a port forward left it erroring on every attempt
+ /// with nothing the user could stop locally.
+ #[test]
+ fn an_unrecorded_unrelated_backend_does_not_block_a_repair() {
+ assert_eq!(
+ mutation_blocker_from_probe(
+ BackendProbe::Unrelated {
+ port: 8888,
+ reason: "ambiguous_root_external_backend_active".to_string(),
+ },
+ &|_| None
+ ),
+ None
+ );
+ }
+
+ /// A local record is only consulted for the unattributable case: a backend
+ /// that identified itself as a conflict blocks either way.
+ #[test]
+ fn an_external_conflict_blocks_mutations_without_a_local_record() {
+ assert_eq!(
+ mutation_blocker_from_probe(
+ BackendProbe::ExternalConflict {
+ port: 8890,
+ reason: "desktop_backend_version_too_old".to_string(),
+ },
+ &|_| None
+ ),
+ Some(ExternalBackendConflict {
+ port: 8890,
+ reason: "desktop_backend_version_too_old".to_string(),
+ })
+ );
+ }
+
#[tokio::test]
async fn backend_route_404_is_old() {
let probe =
diff --git a/studio/src-tauri/src/preflight/pid_records.rs b/studio/src-tauri/src/preflight/pid_records.rs
new file mode 100644
index 00000000000..13379d2c7b7
--- /dev/null
+++ b/studio/src-tauri/src/preflight/pid_records.rs
@@ -0,0 +1,670 @@
+use crate::process_identity::ProcessOrigin;
+use std::path::Path;
+
+/// The pid of a live backend of THIS install that is serving `port`, if one is
+/// recorded.
+///
+/// A mutation rewrites the install tree, so the question it has to answer about
+/// an unattributable backend is not "is something listening" but "is a live
+/// process running out of the tree I am about to overwrite". A health probe
+/// cannot answer that: a Studio reached through an SSH forward answers from
+/// 127.0.0.1 exactly like a local one.
+///
+/// The server records itself on bind, in a per-port `studio-{port}-{pid}.pid`
+/// file and, for older builds, in a bare `studio.pid`. Those records are hints
+/// only: they outlive crashes, the per-port write is best effort, and the OS
+/// reuses pids. So each recorded pid is checked against the process actually
+/// wearing it, by start time and by what it is running.
+pub(super) fn live_backend_pid_on_port(port: u16) -> Option<u32> {
+ let root = record_root();
+ let interpreters = crate::process_identity::interpreters_of(&root);
+ let probe = Probe {
+ is_live: &|pid| {
+ crate::desktop_backend_owner::pid_is_not_dead(pid)
+ && !crate::process_identity::is_zombie(pid)
+ },
+ origin: &|pid| crate::process_identity::origin_of(pid, &root, &interpreters),
+ started_at: &crate::process_identity::process_start_time_secs,
+ };
+ live_backend_pid_in(&root, port, &probe)
+}
+
+#[cfg(test)]
+pub(super) static TEST_RECORD_ROOT: std::sync::Mutex<Option<std::path::PathBuf>> =
+ std::sync::Mutex::new(None);
+
+/// Where the server writes its records. Overridable in tests so the end to end
+/// case can be driven without touching the real studio home.
+fn record_root() -> std::path::PathBuf {
+ #[cfg(test)]
+ if let Ok(guard) = TEST_RECORD_ROOT.lock() {
+ if let Some(root) = guard.clone() {
+ return root;
+ }
+ }
+ crate::diagnostics::studio_dir()
+}
+
+/// What the OS is asked about a recorded pid, injected so the decision below
+/// can be tested without real processes to point it at.
+struct Probe<'a> {
+ /// False only when the pid is provably gone.
+ is_live: &'a dyn Fn(u32) -> bool,
+ origin: &'a dyn Fn(u32) -> ProcessOrigin,
+ /// Unix epoch seconds the process started, when the OS will say.
+ started_at: &'a dyn Fn(u32) -> Option<f64>,
+}
+
+/// A record and the process wearing its pid, once the two have been compared.
+enum Recorded {
+ /// The pid is gone, or belongs to a process that started at a different
+ /// time, so the record is left over from a crash.
+ Stale,
+ /// Live, and running out of this install.
+ OurBackend,
+ /// Live, and running an interpreter this install's venv defers to. It may
+ /// be our backend and may be any other program sharing that interpreter.
+ MaybeOurs,
+ /// Live, and running something else entirely.
+ Foreign,
+ /// Live, and the OS would not say what it is running.
+ Opaque,
+}
+
+/// The Python side uses the same one-second window in `_pid_is_studio_backend`.
+const START_TIME_TOLERANCE_SECS: f64 = 1.0;
+
+fn classify(pid: u32, recorded_start: Option<f64>, probe: &Probe) -> Recorded {
+ if !(probe.is_live)(pid) {
+ return Recorded::Stale;
+ }
+ // A recorded start time that disagrees is proof the pid was reused, which
+ // no amount of executable evidence can override: the process the record
+ // described is gone.
+ if let (Some(recorded), Some(actual)) = (recorded_start, (probe.started_at)(pid)) {
+ if (actual - recorded).abs() > START_TIME_TOLERANCE_SECS {
+ return Recorded::Stale;
+ }
+ }
+ match (probe.origin)(pid) {
+ ProcessOrigin::InsideTree => Recorded::OurBackend,
+ ProcessOrigin::SharedInterpreter => Recorded::MaybeOurs,
+ ProcessOrigin::Elsewhere => Recorded::Foreign,
+ ProcessOrigin::Unknown => Recorded::Opaque,
+ }
+}
+
+fn live_backend_pid_in(root: &Path, port: u16, probe: &Probe) -> Option<u32> {
+ if let Some(pid) = per_port_record_pid(root, port, probe) {
+ return Some(pid);
+ }
+ legacy_record_pid(root, probe)
+}
+
+/// A record naming this exact port is strong evidence on its own, so anything
+/// short of proof that the pid belongs elsewhere leaves it standing.
+fn per_port_record_pid(root: &Path, port: u16, probe: &Probe) -> Option<u32> {
+ let prefix = format!("studio-{port}-");
+ for entry in std::fs::read_dir(root).ok()?.flatten() {
+ let file_name = entry.file_name();
+ let Some(name) = file_name.to_str() else {
+ continue;
+ };
+ // The pid comes from the name, not the body: the name is what the
+ // binding process wrote about itself, and no partial write can garble
+ // it. The body is read only for the start time.
+ let Some(pid) = name
+ .strip_prefix(&prefix)
+ .and_then(|rest| rest.strip_suffix(".pid"))
+ .and_then(|pid| pid.parse::<u32>().ok())
+ else {
+ continue;
+ };
+ match classify(pid, recorded_start_time(&entry.path()), probe) {
+ Recorded::OurBackend | Recorded::MaybeOurs | Recorded::Opaque => return Some(pid),
+ Recorded::Foreign | Recorded::Stale => continue,
+ }
+ }
+ None
+}
+
+/// The legacy record names no port, and a build old enough to be the id-less
+/// backend we are asking about is exactly the build that writes only this file.
+/// It is also the sole record when a per-port write failed.
+///
+/// It carries no start time, so a reused pid cannot be ruled out here the way
+/// it can above. A process the OS will not describe is therefore not enough to
+/// strand a repair on, while one that could be running our own interpreter is.
+fn legacy_record_pid(root: &Path, probe: &Probe) -> Option<u32> {
+ let body = std::fs::read_to_string(root.join("studio.pid")).ok()?;
+ // pid 0 and 1 are never a backend, and signalling either would be a bug.
+ let pid = body
+ .lines()
+ .next()?
+ .trim()
+ .parse::<u32>()
+ .ok()
+ .filter(|pid| *pid > 1)?;
+ // A current build writes a per-port record too, so if this pid has one it
+ // has already been considered under the port it actually serves, and the
+ // portless record must not be read as claiming this one. Without that, the
+ // app's own backend on an ignored port answers for every other candidate
+ // port and the mutation never reaches the step that stops it.
+ // `_legacy_studio_on_port` skips the same case on the Python side.
+ if has_a_per_port_record(root, pid) {
+ return None;
+ }
+ match classify(pid, None, probe) {
+ Recorded::OurBackend | Recorded::MaybeOurs => Some(pid),
+ Recorded::Foreign | Recorded::Opaque | Recorded::Stale => None,
+ }
+}
+
+/// Whether `pid` is named by a per-port record, on any port.
+///
+/// Either answer settles the legacy record: a record that still stands has
+/// already been judged under the port it names, and one that no longer stands
+/// says the pid was reused, which the untimed legacy record cannot see.
+fn has_a_per_port_record(root: &Path, pid: u32) -> bool {
+ let suffix = format!("-{pid}.pid");
+ let Ok(entries) = std::fs::read_dir(root) else {
+ return false;
+ };
+ for entry in entries.flatten() {
+ let file_name = entry.file_name();
+ let Some(name) = file_name.to_str() else {
+ continue;
+ };
+ if name.starts_with("studio-") && name.ends_with(&suffix) {
+ return true;
+ }
+ }
+ false
+}
+
+/// Line two of a record, written by the server as `psutil` epoch seconds. A
+/// blank or absent line means the server could not determine it.
+fn recorded_start_time(path: &Path) -> Option<f64> {
+ std::fs::read_to_string(path)
+ .ok()?
+ .lines()
+ .nth(1)?
+ .trim()
+ .parse()
+ .ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ const RECORDED: u32 = 4242;
+ const RECORDED_8888: &str = "studio-8888-4242.pid";
+
+ struct Home {
+ dir: tempfile::TempDir,
+ }
+
+ impl Home {
+ fn new() -> Self {
+ Self {
+ dir: tempfile::tempdir().unwrap(),
+ }
+ }
+
+ fn path(&self) -> PathBuf {
+ self.dir.path().to_path_buf()
+ }
+
+ fn record(&self, name: &str, body: &str) -> &Self {
+ std::fs::write(self.dir.path().join(name), body).unwrap();
+ self
+ }
+ }
+
+ fn probe(origin: &dyn Fn(u32) -> ProcessOrigin) -> Probe<'_> {
+ Probe {
+ is_live: &|_| true,
+ origin,
+ started_at: &|_| None,
+ }
+ }
+
+ fn gone<'a>() -> Probe<'a> {
+ Probe {
+ is_live: &|_| false,
+ origin: &|_| unreachable!("a dead pid is never attributed"),
+ started_at: &|_| unreachable!("a dead pid is never timed"),
+ }
+ }
+
+ fn ours(_pid: u32) -> ProcessOrigin {
+ ProcessOrigin::InsideTree
+ }
+
+ fn shared(_pid: u32) -> ProcessOrigin {
+ ProcessOrigin::SharedInterpreter
+ }
+
+ fn theirs(_pid: u32) -> ProcessOrigin {
+ ProcessOrigin::Elsewhere
+ }
+
+ fn opaque(_pid: u32) -> ProcessOrigin {
+ ProcessOrigin::Unknown
+ }
+
+ #[test]
+ fn a_live_record_from_our_tree_is_found() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "");
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&ours)),
+ Some(RECORDED)
+ );
+ }
+
+ /// These pile up: a crashed server never removes its own record.
+ #[test]
+ fn a_dead_record_is_ignored() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &gone()), None);
+ }
+
+ #[test]
+ fn a_reused_pid_running_another_tree_is_ignored() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "");
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&theirs)),
+ None
+ );
+ }
+
+ /// The pid was reused by a process sharing our base interpreter, so the
+ /// executable proves nothing. The recorded start time still does.
+ #[test]
+ fn a_recorded_start_time_that_disagrees_settles_a_reused_pid() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "4242\n1000.0\n127.0.0.1");
+ let reused = Probe {
+ is_live: &|_| true,
+ origin: &shared,
+ started_at: &|_| Some(9999.0),
+ };
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &reused), None);
+ }
+
+ #[test]
+ fn a_matching_start_time_leaves_the_record_standing() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "4242\n1000.0\n127.0.0.1");
+ let same = Probe {
+ is_live: &|_| true,
+ origin: &shared,
+ started_at: &|_| Some(1000.4),
+ };
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &same),
+ Some(RECORDED)
+ );
+ }
+
+ /// An untimed record cannot be checked, so it is trusted, exactly as
+ /// `_pid_is_studio_backend` trusts one on the Python side.
+ #[test]
+ fn a_record_without_a_start_time_is_not_second_guessed() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "4242\n\n127.0.0.1");
+ let timed = Probe {
+ is_live: &|_| true,
+ origin: &shared,
+ started_at: &|_| Some(9999.0),
+ };
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &timed),
+ Some(RECORDED)
+ );
+ }
+
+ /// A backend behind a symlinked venv or a Windows trampoline cannot be
+ /// positively attributed, and a record naming its port must still block.
+ #[test]
+ fn a_shared_interpreter_on_a_recorded_port_blocks() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "");
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&shared)),
+ Some(RECORDED)
+ );
+ }
+
+ #[test]
+ fn a_per_port_record_we_cannot_attribute_still_blocks() {
+ let home = Home::new();
+ home.record(RECORDED_8888, "");
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&opaque)),
+ Some(RECORDED)
+ );
+ }
+
+ #[test]
+ fn a_record_for_another_port_is_ignored() {
+ let home = Home::new();
+ home.record("studio-8889-4242.pid", "");
+ // A port that merely starts with the digits of ours is another port.
+ home.record("studio-88881-4242.pid", "");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &probe(&ours)), None);
+ }
+
+ /// A pre-upgrade server records itself here and nowhere else, and it is
+ /// precisely the kind of build that reports no install id.
+ #[test]
+ fn a_live_legacy_record_from_our_tree_blocks() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&ours)),
+ Some(RECORDED)
+ );
+ }
+
+ /// On macOS a backend behind the symlinked venv is never more than
+ /// "maybe", and a legacy record is all a pre-upgrade one leaves.
+ #[test]
+ fn a_legacy_record_on_a_shared_interpreter_blocks() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&shared)),
+ Some(RECORDED)
+ );
+ }
+
+ /// The app's own backend on an ignored port writes both records. The
+ /// portless one must not then answer for every other candidate port, or a
+ /// mutation never reaches the step that stops that backend.
+ #[test]
+ fn a_legacy_record_for_a_pid_that_serves_a_known_port_is_ignored() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+ home.record("studio-9001-4242.pid", "");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &probe(&ours)), None);
+ // ...while the port it does serve still blocks.
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 9001, &probe(&ours)),
+ Some(RECORDED)
+ );
+ }
+
+ /// A per-port record that no longer stands settles the legacy one too: it
+ /// says the pid was reused, which an untimed record cannot see for itself.
+ #[test]
+ fn a_contradicted_per_port_record_silences_the_legacy_one() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+ home.record("studio-9001-4242.pid", "4242\n1000.0\n");
+ let reused = Probe {
+ is_live: &|_| true,
+ origin: &ours,
+ started_at: &|_| Some(9999.0),
+ };
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &reused), None);
+ }
+
+ #[test]
+ fn a_legacy_record_from_another_tree_is_ignored() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&theirs)),
+ None
+ );
+ }
+
+ /// The legacy record names no port and carries no start time, so a process
+ /// the OS will not describe is not evidence enough to strand a repair.
+ #[test]
+ fn a_legacy_record_we_cannot_attribute_does_not_block() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+
+ assert_eq!(
+ live_backend_pid_in(&home.path(), 8888, &probe(&opaque)),
+ None
+ );
+ }
+
+ #[test]
+ fn a_stale_legacy_record_is_ignored() {
+ let home = Home::new();
+ home.record("studio.pid", &RECORDED.to_string());
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &gone()), None);
+ }
+
+ #[test]
+ fn a_malformed_legacy_record_is_ignored() {
+ let home = Home::new();
+ home.record("studio.pid", "1");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &probe(&ours)), None);
+
+ home.record("studio.pid", "not a pid");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &probe(&ours)), None);
+ }
+
+ /// The reported case: the backend on the port is reached over an SSH
+ /// forward, so this install recorded nothing anywhere.
+ #[test]
+ fn nothing_recorded_means_nothing_local() {
+ let home = Home::new();
+ home.record("studio-8888-notapid.pid", "");
+
+ assert_eq!(live_backend_pid_in(&home.path(), 8888, &probe(&ours)), None);
+ }
+
+ #[test]
+ fn a_missing_studio_home_is_not_an_error() {
+ let home = Home::new();
+
+ assert_eq!(
+ live_backend_pid_in(&home.path().join("absent"), 8888, &probe(&ours)),
+ None
+ );
+ }
+}
+
+/// Real processes and real files, driven through `live_backend_pid_on_port`
+/// rather than the injected probe above: these are the cases the injected tests
+/// cannot vouch for, because the thing under test is what the OS reports.
+#[cfg(test)]
+mod system_tests {
+ use super::*;
+ use std::path::PathBuf;
+ use std::process::{Child, Command};
+
+ /// Serialises the record-root override, which is process-wide.
+ static ROOT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+ struct RecordRoot {
+ _guard: std::sync::MutexGuard<'static, ()>,
+ dir: PathBuf,
+ written: Vec<PathBuf>,
+ }
+
+ impl RecordRoot {
+ /// Rooted at our own executable's directory, so this process attributes
+ /// as a backend of that tree exactly the way a real one does.
+ fn at_our_own_tree() -> Self {
+ let guard = ROOT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ let dir = std::env::current_exe()
+ .unwrap()
+ .parent()
+ .unwrap()
+ .to_path_buf();
+ *TEST_RECORD_ROOT.lock().unwrap() = Some(dir.clone());
+ Self {
+ _guard: guard,
+ dir,
+ written: Vec::new(),
+ }
+ }
+
+ fn record(&mut self, name: &str, body: &str) {
+ let path = self.dir.join(name);
+ std::fs::write(&path, body).unwrap();
+ self.written.push(path);
+ }
+ }
+
+ impl Drop for RecordRoot {
+ fn drop(&mut self) {
+ for path in &self.written {
+ let _ = std::fs::remove_file(path);
+ }
+ *TEST_RECORD_ROOT.lock().unwrap() = None;
+ }
+ }
+
+ /// A live process that is definitely not running out of our tree.
+ fn spawn_foreign() -> Child {
+ #[cfg(windows)]
+ let mut command = {
+ let mut c = Command::new("cmd.exe");
+ c.args(["/c", "ping", "-n", "60", "127.0.0.1"]);
+ c
+ };
+ #[cfg(not(windows))]
+ let mut command = {
+ let mut c = Command::new("sleep");
+ c.arg("60");
+ c
+ };
+ command.spawn().expect("a foreign process should start")
+ }
+
+ /// The reported case reproduced end to end: a backend of this install is
+ /// recorded on the port, and the repair has to refuse.
+ #[test]
+ fn a_recorded_live_backend_of_this_install_is_found() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let me = std::process::id();
+ root.record(&format!("studio-8888-{me}.pid"), "");
+
+ assert_eq!(live_backend_pid_on_port(8888), Some(me));
+ }
+
+ /// The other half of it: the port answers, but nothing local claims it, so
+ /// the repair proceeds. This is the SSH forward from the report.
+ #[test]
+ fn an_unrecorded_port_finds_nothing() {
+ let _root = RecordRoot::at_our_own_tree();
+
+ assert_eq!(live_backend_pid_on_port(8890), None);
+ }
+
+ #[test]
+ fn a_record_for_a_process_that_exited_is_ignored() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let mut child = spawn_foreign();
+ let pid = child.id();
+ child.kill().unwrap();
+ child.wait().unwrap();
+ root.record(&format!("studio-8891-{pid}.pid"), "");
+
+ assert_eq!(live_backend_pid_on_port(8891), None);
+ }
+
+ /// A live process that is not a backend of ours must not veto a repair,
+ /// which is what a stale record with a reused pid looks like.
+ #[test]
+ fn a_record_pointing_at_a_foreign_live_process_is_ignored() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let mut child = spawn_foreign();
+ root.record(&format!("studio-8892-{}.pid", child.id()), "");
+
+ let found = live_backend_pid_on_port(8892);
+ child.kill().unwrap();
+ child.wait().unwrap();
+
+ assert_eq!(found, None);
+ }
+
+ /// A record whose start time names a different process settles it even
+ /// when the executable cannot.
+ #[test]
+ fn a_record_whose_start_time_disagrees_is_ignored() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let me = std::process::id();
+ root.record(&format!("studio-8894-{me}.pid"), &format!("{me}\n1.0\n"));
+
+ assert_eq!(live_backend_pid_on_port(8894), None);
+ }
+
+ /// ...and one that matches is left standing. The recorded time is read
+ /// from the OS rather than hardcoded, which also checks the two agree.
+ #[test]
+ fn a_record_whose_start_time_agrees_is_found() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let me = std::process::id();
+ let started = crate::process_identity::process_start_time_secs(me)
+ .expect("this platform should report its own start time");
+ root.record(
+ &format!("studio-8895-{me}.pid"),
+ &format!("{me}\n{started}\n"),
+ );
+
+ assert_eq!(live_backend_pid_on_port(8895), Some(me));
+ }
+
+ /// A crashed backend the app has not reaped keeps its pid and answers a
+ /// liveness check, but its socket is gone. Its record must not block.
+ #[cfg(unix)]
+ #[test]
+ fn a_record_for_an_unreaped_process_is_ignored() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let mut child = spawn_foreign();
+ let pid = child.id();
+ child.kill().unwrap();
+ for _ in 0..200 {
+ if crate::process_identity::is_zombie(pid) {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ root.record(&format!("studio-8896-{pid}.pid"), "");
+
+ let found = live_backend_pid_on_port(8896);
+ child.wait().unwrap();
+
+ assert_eq!(found, None);
+ }
+
+ #[test]
+ fn a_legacy_record_naming_this_install_is_found() {
+ let mut root = RecordRoot::at_our_own_tree();
+ let me = std::process::id();
+ root.record("studio.pid", &me.to_string());
+
+ assert_eq!(live_backend_pid_on_port(8893), Some(me));
+ }
+}
diff --git a/studio/src-tauri/src/preflight/types.rs b/studio/src-tauri/src/preflight/types.rs
index 85f209b6576..56884061792 100644
--- a/studio/src-tauri/src/preflight/types.rs
+++ b/studio/src-tauri/src/preflight/types.rs
@@ -43,7 +43,8 @@ pub(super) enum BackendProbe {
ExternalConflict { port: u16, reason: String },
/// A backend answered here, but it is not adoptable and not provably ours:
/// it reports no install id, so it may be a remote Studio behind a tunnel or
- /// an install that predates the id. Launching skips the port; mutating flows
- /// still refuse, since they cannot rule out our own venv underneath it.
+ /// an install that predates the id. Launching skips the port; a mutation
+ /// refuses only when a live local process is attributable to this install,
+ /// which is the one thing a health probe cannot tell us.
Unrelated { port: u16, reason: String },
}
diff --git a/studio/src-tauri/src/process_identity.rs b/studio/src-tauri/src/process_identity.rs
new file mode 100644
index 00000000000..729c06af8a8
--- /dev/null
+++ b/studio/src-tauri/src/process_identity.rs
@@ -0,0 +1,660 @@
+//! Which install tree a live process is running out of.
+
+use std::path::{Path, PathBuf};
+
+/// Absolute path of the executable behind `pid`, when the OS will say.
+///
+/// None means unknown, never "no such process": a pid belonging to another user
+/// is refused on every platform here, and callers must not read that as absence.
+pub(crate) fn executable_path(pid: u32) -> Option<PathBuf> {
+ executable_path_impl(pid)
+}
+
+/// Where a live process is running from, relative to an install tree.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum ProcessOrigin {
+ /// Positively this install.
+ InsideTree,
+ /// Running an interpreter this install's venv defers to, so it may be ours
+ /// and may be any other program using the same base interpreter.
+ SharedInterpreter,
+ /// Positively not this install.
+ Elsewhere,
+ /// The OS would not say.
+ Unknown,
+}
+
+/// The interpreters a backend of an install may appear to be running.
+pub(crate) struct TreeInterpreters {
+ shared: Vec<PathBuf>,
+ /// A venv is there but its `pyvenv.cfg` could not be read, so the base
+ /// interpreter behind it is unknown. A damaged install is exactly the state
+ /// that triggers a repair, so this must not read as "definitely not ours".
+ base_unknown: bool,
+}
+
+/// Where `pid` is running from.
+///
+/// `interpreters` covers the executables a process inside the tree may be
+/// running without the tree appearing anywhere in its image path. On unix uv
+/// symlinks `bin/python` at the base interpreter, which `install.sh` documents,
+/// and both `/proc/{pid}/exe` and `proc_pidpath` report the resolved target. On
+/// Windows uv's `Scripts/python.exe` is a trampoline that spawns the base
+/// interpreter as a child, so the image is the base one there too.
+pub(crate) fn origin_of(pid: u32, tree: &Path, interpreters: &TreeInterpreters) -> ProcessOrigin {
+ // argv[0] keeps the path as invoked, so it still names the venv where the
+ // image path no longer does. Positive evidence only: a process can be given
+ // any argv, and there is no platform where its absence means anything.
+ if let Some(argv0) = first_argument(pid) {
+ if path_is_within(&argv0, tree) {
+ return ProcessOrigin::InsideTree;
+ }
+ }
+ let Some(exe) = executable_path(pid) else {
+ return ProcessOrigin::Unknown;
+ };
+ if path_is_within(&exe, tree) {
+ return ProcessOrigin::InsideTree;
+ }
+ if interpreters.base_unknown
+ || interpreters
+ .shared
+ .iter()
+ .any(|shared| is_same_path(shared, &exe))
+ {
+ return ProcessOrigin::SharedInterpreter;
+ }
+ ProcessOrigin::Elsewhere
+}
+
+fn is_same_path(left: &Path, right: &Path) -> bool {
+ // Simplified on both sides: canonicalize hands back an extended-length
+ // \\?\C:\... path on Windows while QueryFullProcessImageNameW hands back a
+ // plain one, and comparing those two forms never matches.
+ simplified(left).to_string_lossy().to_lowercase()
+ == simplified(right).to_string_lossy().to_lowercase()
+}
+
+/// A Windows extended-length path in its ordinary form. A no-op elsewhere.
+fn simplified(path: &Path) -> PathBuf {
+ let text = path.to_string_lossy();
+ if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
+ return PathBuf::from(format!(r"\\{rest}"));
+ }
+ match text.strip_prefix(r"\\?\") {
+ Some(rest) => PathBuf::from(rest.to_string()),
+ None => path.to_path_buf(),
+ }
+}
+
+/// The command line's argv[0] for `pid`.
+///
+/// Linux only. macOS needs a KERN_PROCARGS2 sysctl and Windows reads the
+/// remote PEB, neither of which is implemented. On those two a backend started
+/// through a venv is therefore a shared-interpreter answer rather than a
+/// positive one, which still blocks on a record naming the port.
+#[cfg(target_os = "linux")]
+fn first_argument(pid: u32) -> Option<PathBuf> {
+ let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
+ let argv0 = cmdline.split(|byte| *byte == 0).next()?;
+ if argv0.is_empty() {
+ return None;
+ }
+ Some(PathBuf::from(String::from_utf8_lossy(argv0).into_owned()))
+}
+
+#[cfg(not(target_os = "linux"))]
+fn first_argument(_pid: u32) -> Option<PathBuf> {
+ None
+}
+
+/// Interpreters a backend of this install may be running through.
+///
+/// Both venv layouts, since `~/.unsloth/studio` is shared with the CLI
+/// installer and an older install still has the `.venv` one. Canonicalized so
+/// the comparison meets the same resolved path the OS reports; an entry that
+/// does not resolve is dropped, since nothing can be running it.
+pub(crate) fn interpreters_of(tree: &Path) -> TreeInterpreters {
+ let mut shared: Vec<PathBuf> = Vec::new();
+ let mut base_unknown = false;
+ for name in ["unsloth_studio", ".venv"] {
+ let venv = tree.join(name);
+ if !venv.is_dir() {
+ continue;
+ }
+ for (dir, exe) in [("bin", "python"), ("Scripts", "python.exe")] {
+ if let Ok(target) = std::fs::canonicalize(venv.join(dir).join(exe)) {
+ if !shared.contains(&target) {
+ shared.push(target);
+ }
+ }
+ }
+ // Unknown covers both "the config would not say" and "it named a base
+ // interpreter that is not there": a uv venv whose base interpreter was
+ // deleted or moved is a damaged install, which is the state a repair
+ // runs in, and its backend is still running out of the old one.
+ let bases = base_interpreters_of(&venv);
+ let mut resolved_a_base = false;
+ for base in bases {
+ if let Ok(target) = std::fs::canonicalize(base) {
+ resolved_a_base = true;
+ if !shared.contains(&target) {
+ shared.push(target);
+ }
+ }
+ }
+ if !resolved_a_base {
+ base_unknown = true;
+ }
+ }
+ TreeInterpreters {
+ shared,
+ base_unknown,
+ }
+}
+
+/// The base interpreters a venv defers to, from its `pyvenv.cfg`.
+fn base_interpreters_of(venv: &Path) -> Vec<PathBuf> {
+ let Ok(config) = std::fs::read_to_string(venv.join("pyvenv.cfg")) else {
+ return Vec::new();
+ };
+ let mut home = None;
+ let mut version = None;
+ for line in config.lines() {
+ let Some((key, value)) = line.split_once('=') else {
+ continue;
+ };
+ match key.trim() {
+ // The documented key: the directory holding the interpreter this
+ // venv was built from.
+ "home" => home = Some(PathBuf::from(value.trim())),
+ "version_info" => {
+ let mut parts = value.trim().split('.');
+ if let (Some(major), Some(minor)) = (parts.next(), parts.next()) {
+ version = Some(format!("{major}.{minor}"));
+ }
+ }
+ _ => {}
+ }
+ }
+ let Some(home) = home else {
+ return Vec::new();
+ };
+ let mut names = vec![
+ "python.exe".to_string(),
+ "python3.exe".to_string(),
+ "python".to_string(),
+ "python3".to_string(),
+ ];
+ if let Some(version) = version {
+ names.push(format!("python{version}"));
+ names.push(format!("python{version}.exe"));
+ }
+ names.into_iter().map(|name| home.join(name)).collect()
+}
+
+/// Whether `pid` has exited but has not been reaped.
+///
+/// A zombie holds its pid and answers `kill(pid, 0)`, so a liveness check alone
+/// reads a crashed backend as running. It matters here because the desktop app
+/// spawns the backend and does not wait on it, so a crash leaves a zombie for
+/// as long as the app lives, and the record would block every repair until the
+/// app exited. The socket is already released by then.
+///
+/// Windows has no equivalent: an exited process is signalled, which the
+/// liveness check already reads as dead.
+pub(crate) fn is_zombie(pid: u32) -> bool {
+ is_zombie_impl(pid)
+}
+
+#[cfg(target_os = "linux")]
+fn is_zombie_impl(pid: u32) -> bool {
+ // Field 3 of /proc/{pid}/stat, read from the last ')' so a comm containing
+ // spaces or parentheses cannot shift the offset.
+ let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
+ return false;
+ };
+ let Some(after_comm) = stat.rfind(')').map(|at| &stat[at + 1..]) else {
+ return false;
+ };
+ after_comm.split_whitespace().next() == Some("Z")
+}
+
+#[cfg(target_os = "macos")]
+fn is_zombie_impl(pid: u32) -> bool {
+ // SZOMB from sys/proc.h, which libc does not re-export.
+ const SZOMB: u32 = 5;
+ if pid > i32::MAX as u32 {
+ return false;
+ }
+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
+ let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
+ let written = unsafe {
+ libc::proc_pidinfo(
+ pid as i32,
+ libc::PROC_PIDTBSDINFO,
+ 0,
+ &mut info as *mut _ as *mut libc::c_void,
+ size,
+ )
+ };
+ written == size && info.pbi_status == SZOMB
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
+fn is_zombie_impl(_pid: u32) -> bool {
+ false
+}
+
+/// Unix epoch seconds at which `pid` started, when the OS will say.
+///
+/// Compared against the start time the server recorded next to its pid, which
+/// is what tells a live backend apart from an unrelated process that inherited
+/// its pid after a crash. `psutil.Process.create_time()` writes the same clock
+/// on the Python side.
+pub(crate) fn process_start_time_secs(pid: u32) -> Option<f64> {
+ process_start_time_impl(pid)
+}
+
+#[cfg(target_os = "linux")]
+fn process_start_time_impl(pid: u32) -> Option<f64> {
+ // Field 22 of /proc/{pid}/stat, in clock ticks since boot. Parsed from the
+ // last ')' onwards because field 2 is the comm, which may itself contain
+ // spaces and parentheses.
+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
+ let after_comm = &stat[stat.rfind(')')? + 1..];
+ let ticks: f64 = after_comm.split_whitespace().nth(19)?.parse().ok()?;
+ let hz = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
+ if hz <= 0 {
+ return None;
+ }
+ Some(boot_time_secs()? + ticks / hz as f64)
+}
+
+#[cfg(target_os = "linux")]
+fn boot_time_secs() -> Option<f64> {
+ let stat = std::fs::read_to_string("/proc/stat").ok()?;
+ stat.lines()
+ .find_map(|line| line.strip_prefix("btime "))
+ .and_then(|value| value.trim().parse::<f64>().ok())
+}
+
+#[cfg(target_os = "macos")]
+fn process_start_time_impl(pid: u32) -> Option<f64> {
+ if pid > i32::MAX as u32 {
+ return None;
+ }
+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
+ let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
+ let written = unsafe {
+ libc::proc_pidinfo(
+ pid as i32,
+ libc::PROC_PIDTBSDINFO,
+ 0,
+ &mut info as *mut _ as *mut libc::c_void,
+ size,
+ )
+ };
+ if written != size {
+ return None;
+ }
+ Some(info.pbi_start_tvsec as f64 + info.pbi_start_tvusec as f64 / 1_000_000.0)
+}
+
+#[cfg(windows)]
+fn process_start_time_impl(pid: u32) -> Option<f64> {
+ use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
+ use windows_sys::Win32::System::Threading::{
+ GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ // 100ns intervals between 1601-01-01 and 1970-01-01.
+ const EPOCH_OFFSET: u64 = 116_444_736_000_000_000;
+ unsafe {
+ let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if handle.is_null() {
+ return None;
+ }
+ let mut created = FILETIME {
+ dwLowDateTime: 0,
+ dwHighDateTime: 0,
+ };
+ let mut ignored = created;
+ let ok = GetProcessTimes(
+ handle,
+ &mut created,
+ &mut ignored,
+ &mut ignored,
+ &mut ignored,
+ );
+ let _ = CloseHandle(handle);
+ if ok == 0 {
+ return None;
+ }
+ let ticks =
+ ((created.dwHighDateTime as u64) << 32) | created.dwLowDateTime as u64;
+ Some(ticks.checked_sub(EPOCH_OFFSET)? as f64 / 10_000_000.0)
+ }
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
+fn process_start_time_impl(_pid: u32) -> Option<f64> {
+ None
+}
+
+fn path_is_within(path: &Path, tree: &Path) -> bool {
+ // Compared case-insensitively throughout: Windows paths differ in case for
+ // the same file, and a false negative here silently drops a real blocker.
+ // Component-wise, so a sibling tree with a shared name prefix cannot match.
+ let mut tree_parts = tree.components();
+ let mut path_parts = path.components();
+ loop {
+ let Some(expected) = tree_parts.next() else {
+ return true;
+ };
+ let Some(actual) = path_parts.next() else {
+ return false;
+ };
+ let expected = expected.as_os_str().to_string_lossy().to_lowercase();
+ let actual = actual.as_os_str().to_string_lossy().to_lowercase();
+ if expected != actual {
+ return false;
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn executable_path_impl(pid: u32) -> Option<PathBuf> {
+ std::fs::read_link(format!("/proc/{pid}/exe")).ok()
+}
+
+#[cfg(target_os = "macos")]
+fn executable_path_impl(pid: u32) -> Option<PathBuf> {
+ if pid > i32::MAX as u32 {
+ return None;
+ }
+ // PROC_PIDPATHINFO_MAXSIZE, which libc does not re-export.
+ let mut buffer = vec![0u8; 4 * libc::MAXPATHLEN as usize];
+ let written = unsafe {
+ libc::proc_pidpath(
+ pid as i32,
+ buffer.as_mut_ptr() as *mut libc::c_void,
+ buffer.len() as u32,
+ )
+ };
+ if written <= 0 {
+ return None;
+ }
+ buffer.truncate(written as usize);
+ Some(PathBuf::from(String::from_utf8(buffer).ok()?))
+}
+
+#[cfg(windows)]
+fn executable_path_impl(pid: u32) -> Option<PathBuf> {
+ use std::os::windows::ffi::OsStringExt;
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Threading::{
+ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32,
+ PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ unsafe {
+ // The limited right, not PROCESS_QUERY_INFORMATION: it is granted for
+ // processes at a higher integrity level, which a Studio started from an
+ // elevated terminal is.
+ let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if handle.is_null() {
+ return None;
+ }
+ let mut buffer = vec![0u16; 32768];
+ let mut length = buffer.len() as u32;
+ let ok = QueryFullProcessImageNameW(
+ handle,
+ PROCESS_NAME_WIN32,
+ buffer.as_mut_ptr(),
+ &mut length,
+ );
+ let _ = CloseHandle(handle);
+ if ok == 0 {
+ return None;
+ }
+ buffer.truncate(length as usize);
+ Some(PathBuf::from(std::ffi::OsString::from_wide(&buffer)))
+ }
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
+fn executable_path_impl(_pid: u32) -> Option<PathBuf> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tree_with_venv(base: Option<&Path>, layout: &str) -> tempfile::TempDir {
+ let tree = tempfile::tempdir().unwrap();
+ let venv = tree.path().join("unsloth_studio");
+ std::fs::create_dir_all(venv.join(layout)).unwrap();
+ if let Some(base) = base {
+ std::fs::write(
+ venv.join("pyvenv.cfg"),
+ format!("home = {}\nversion_info = 3.13.12\n", base.display()),
+ )
+ .unwrap();
+ }
+ tree
+ }
+
+ #[test]
+ fn our_own_executable_is_resolvable() {
+ let pid = std::process::id();
+ let exe = executable_path(pid).expect("this platform should resolve its own path");
+
+ assert_eq!(exe, std::env::current_exe().unwrap());
+ }
+
+ #[test]
+ fn this_platform_reports_its_own_start_time() {
+ let started =
+ process_start_time_secs(std::process::id()).expect("a start time should be readable");
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+
+ // Started in the past, and this millennium: a wrong epoch base or a
+ // wrong clock tick divisor would land far outside that.
+ assert!(started <= now + 1.0, "start {started} is after now {now}");
+ assert!(started > 1_000_000_000.0, "start {started} is not an epoch");
+ }
+
+ #[test]
+ fn a_process_is_inside_the_tree_that_contains_it() {
+ let exe = std::env::current_exe().unwrap();
+ let tree = exe.parent().unwrap().to_path_buf();
+ let none = TreeInterpreters {
+ shared: Vec::new(),
+ base_unknown: false,
+ };
+
+ assert_eq!(
+ origin_of(std::process::id(), &tree, &none),
+ ProcessOrigin::InsideTree
+ );
+ assert_eq!(
+ origin_of(std::process::id(), Path::new("/definitely/elsewhere"), &none),
+ ProcessOrigin::Elsewhere
+ );
+ }
+
+ /// The reported venv case: uv symlinks bin/python at the base interpreter,
+ /// so the image path leaves the tree entirely. Reading that as "not ours"
+ /// would rewrite the venv underneath a live backend.
+ #[test]
+ fn a_process_running_a_shared_interpreter_is_not_read_as_elsewhere() {
+ let exe = std::env::current_exe().unwrap();
+ let shared = TreeInterpreters {
+ shared: vec![exe],
+ base_unknown: false,
+ };
+
+ assert_eq!(
+ origin_of(
+ std::process::id(),
+ Path::new("/definitely/elsewhere"),
+ &shared
+ ),
+ ProcessOrigin::SharedInterpreter
+ );
+ }
+
+ /// A damaged install is exactly the state a repair runs in, so an
+ /// unreadable pyvenv.cfg must not read as "definitely not ours" on the
+ /// platforms that have no argv[0] to fall back on.
+ #[test]
+ fn an_unknown_base_interpreter_is_not_read_as_elsewhere() {
+ let unknown = TreeInterpreters {
+ shared: Vec::new(),
+ base_unknown: true,
+ };
+
+ assert_eq!(
+ origin_of(
+ std::process::id(),
+ Path::new("/definitely/elsewhere"),
+ &unknown
+ ),
+ ProcessOrigin::SharedInterpreter
+ );
+ }
+
+ #[test]
+ fn a_venv_whose_config_cannot_be_read_flags_its_base_as_unknown() {
+ let tree = tree_with_venv(None, "bin");
+
+ assert!(interpreters_of(tree.path()).base_unknown);
+ }
+
+ /// uv's Windows trampoline spawns the base interpreter as a child, so the
+ /// venv path is absent from the running image and pyvenv.cfg is the only
+ /// thing tying the two together.
+ #[test]
+ fn the_base_interpreter_from_pyvenv_cfg_is_listed() {
+ let base = tempfile::tempdir().unwrap();
+ let interpreter = base
+ .path()
+ .join(if cfg!(windows) { "python.exe" } else { "python3.13" });
+ std::fs::write(&interpreter, "").unwrap();
+ let tree = tree_with_venv(Some(base.path()), "Scripts");
+
+ let found = interpreters_of(tree.path());
+
+ assert!(!found.base_unknown);
+ assert_eq!(found.shared, vec![std::fs::canonicalize(&interpreter).unwrap()]);
+ }
+
+ /// A uv venv whose base interpreter was deleted or moved: the config still
+ /// names it, so the candidates are built, but none of them resolve. That is
+ /// a damaged install, which is exactly when a repair runs.
+ #[test]
+ fn a_base_interpreter_that_no_longer_exists_is_flagged_unknown() {
+ let missing = tempfile::tempdir().unwrap();
+ let base = missing.path().join("gone");
+ let tree = tree_with_venv(Some(&base), "bin");
+
+ let found = interpreters_of(tree.path());
+
+ assert!(found.base_unknown);
+ }
+
+ #[test]
+ fn a_tree_with_no_venv_at_all_is_not_flagged_unknown() {
+ let tree = tempfile::tempdir().unwrap();
+
+ let found = interpreters_of(tree.path());
+
+ assert!(!found.base_unknown);
+ assert!(found.shared.is_empty());
+ }
+
+ /// A crashed backend the desktop app has not reaped still answers
+ /// kill(pid, 0), and its record would block every repair until the app
+ /// exited. Reproduced with a real unreaped child.
+ #[cfg(unix)]
+ #[test]
+ fn a_zombie_is_not_a_live_process() {
+ let mut child = std::process::Command::new("sleep")
+ .arg("60")
+ .spawn()
+ .unwrap();
+ let pid = child.id();
+
+ assert!(!is_zombie(pid), "a running child is not a zombie");
+
+ child.kill().unwrap();
+ // Deliberately not reaped yet: Child::wait is what clears the zombie,
+ // and leaving it is the state under test.
+ let mut zombie = false;
+ for _ in 0..200 {
+ if is_zombie(pid) {
+ zombie = true;
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ }
+ child.wait().unwrap();
+
+ assert!(zombie, "a killed but unreaped child should read as a zombie");
+ assert!(!is_zombie(std::process::id()), "we are not a zombie");
+ }
+
+ #[test]
+ fn a_shared_name_prefix_is_not_containment() {
+ assert!(!path_is_within(
+ Path::new("/home/u/.unsloth/studio-old/bin/python"),
+ Path::new("/home/u/.unsloth/studio"),
+ ));
+ assert!(path_is_within(
+ Path::new("/home/u/.unsloth/studio/unsloth_studio/bin/python"),
+ Path::new("/home/u/.unsloth/studio"),
+ ));
+ }
+
+ /// Windows reports the same file under different casings, and a false
+ /// negative here silently drops a real blocker.
+ #[test]
+ fn containment_ignores_case() {
+ assert!(path_is_within(
+ Path::new("/Users/U/.Unsloth/Studio/unsloth_studio/python"),
+ Path::new("/users/u/.unsloth/studio"),
+ ));
+ }
+
+ #[test]
+ fn a_tree_contains_itself_but_not_its_parent() {
+ let tree = Path::new("/home/u/.unsloth/studio");
+
+ assert!(path_is_within(tree, tree));
+ assert!(!path_is_within(Path::new("/home/u/.unsloth"), tree));
+ }
+
+ /// canonicalize hands back an extended-length path on Windows while
+ /// QueryFullProcessImageNameW hands back a plain one, and the same file
+ /// must compare equal across the two forms.
+ #[test]
+ fn an_extended_length_path_equals_its_plain_form() {
+ assert!(is_same_path(
+ Path::new(r"\\?\C:\Users\u\.unsloth\studio\python.exe"),
+ Path::new(r"C:\Users\U\.unsloth\studio\python.exe"),
+ ));
+ assert!(is_same_path(
+ Path::new(r"\\?\UNC\server\share\python.exe"),
+ Path::new(r"\\server\share\python.exe"),
+ ));
+ assert!(!is_same_path(
+ Path::new(r"\\?\C:\Users\u\python.exe"),
+ Path::new(r"C:\Users\u\other.exe"),
+ ));
+ }
+}