From ddb4e352c92782156623f84099993b25bf5bbdcc Mon Sep 17 00:00:00 2001 From: dsh Date: Thu, 5 Nov 2026 04:00:47 +0800 Subject: [PATCH 01/11] fix(backend): verify the old backend exited before respawning on restart --- src-tauri/src/app_constants.rs | 7 + src-tauri/src/app_types.rs | 15 +- src-tauri/src/backend/launch.rs | 3 + src-tauri/src/backend/process_lifecycle.rs | 111 +++++- src-tauri/src/backend/restart.rs | 292 +++++++++++++++- src-tauri/src/process_control.rs | 377 ++++++++++++++++++++- 6 files changed, 790 insertions(+), 15 deletions(-) diff --git a/src-tauri/src/app_constants.rs b/src-tauri/src/app_constants.rs index 19cc5f6a..4021df15 100644 --- a/src-tauri/src/app_constants.rs +++ b/src-tauri/src/app_constants.rs @@ -9,6 +9,13 @@ pub(crate) const DESKTOP_AUTH_REQUEST_TIMEOUT_MS: u64 = 2_500; pub(crate) const GRACEFUL_RESTART_START_TIME_TIMEOUT_MS: u64 = 1_800; pub(crate) const GRACEFUL_RESTART_POLL_INTERVAL_MS: u64 = 350; pub(crate) const GRACEFUL_STOP_TIMEOUT_MS: u64 = 10_000; +// Upper bound for confirming the previously spawned backend has really left the OS +// before a restart is allowed to spawn a replacement. The stop path can spend up to +// GRACEFUL_STOP_TIMEOUT_MS plus the force-kill follow-up, so this only covers the +// final "PID is gone" hand-off; it must stay short enough that a genuine failure is +// reported to the user instead of turning a restart into a long hang. +pub(crate) const BACKEND_EXIT_CONFIRM_TIMEOUT_MS: u64 = 3_000; +pub(crate) const BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS: u64 = 100; #[cfg(target_os = "windows")] pub(crate) const SYSTEM_SHUTDOWN_STOP_TIMEOUT_MS: u64 = 2_000; pub(crate) const DEFAULT_BACKEND_READY_POLL_INTERVAL_MS: u64 = 300; diff --git a/src-tauri/src/app_types.rs b/src-tauri/src/app_types.rs index b27a4b8c..15dfb15e 100644 --- a/src-tauri/src/app_types.rs +++ b/src-tauri/src/app_types.rs @@ -4,13 +4,15 @@ use std::{ path::PathBuf, process::Child, sync::{ - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU32, Ordering}, Arc, Mutex, }, }; use tauri::menu::{CheckMenuItem, MenuItem}; -use crate::{backend, desktop_auth::DesktopSessionSecret, exit_state, DEFAULT_BACKEND_URL}; +use crate::{ + backend, desktop_auth::DesktopSessionSecret, exit_state, process_control, DEFAULT_BACKEND_URL, +}; #[derive(Clone)] pub(crate) struct TrayMenuState { @@ -67,6 +69,10 @@ pub(crate) struct LaunchPlan { #[derive(Debug)] pub(crate) struct BackendState { pub(crate) child: Mutex>, + /// Identity of the last process this shell spawned, captured while it was still + /// running. Kept separately from `child` because the `Child` handle is consumed or + /// dropped while the OS may still be tearing the process down. + pub(crate) last_spawned_identity: Mutex>, pub(crate) backend_url: String, pub(crate) restart_auth_token: Mutex>, pub(crate) desktop_session_secret: DesktopSessionSecret, @@ -75,6 +81,9 @@ pub(crate) struct BackendState { pub(crate) exit_state: Mutex, pub(crate) is_spawning: AtomicBool, pub(crate) is_restarting: AtomicBool, + /// PID the current restart flow stopped, or 0 when nothing was stopped. Set before + /// the stop so the flow can confirm that exact process left the OS before respawning. + pub(crate) restart_stop_pid: AtomicU32, } #[derive(Debug, serde::Serialize)] @@ -128,6 +137,7 @@ impl Default for BackendState { fn default() -> Self { Self { child: Mutex::new(None), + last_spawned_identity: Mutex::new(None), backend_url: backend::config::normalize_backend_url( &env::var("ASTRBOT_BACKEND_URL") .unwrap_or_else(|_| DEFAULT_BACKEND_URL.to_string()), @@ -141,6 +151,7 @@ impl Default for BackendState { exit_state: Mutex::new(exit_state::ExitStateMachine::default()), is_spawning: AtomicBool::new(false), is_restarting: AtomicBool::new(false), + restart_stop_pid: AtomicU32::new(0), } } } diff --git a/src-tauri/src/backend/launch.rs b/src-tauri/src/backend/launch.rs index edab9580..bdf78558 100644 --- a/src-tauri/src/backend/launch.rs +++ b/src-tauri/src/backend/launch.rs @@ -533,6 +533,9 @@ impl BackendState { .child .lock() .map_err(|_| "Backend process lock poisoned.")? = Some(child); + // Record the identity while the process is certainly alive; a later restart uses + // it to prove the process is gone instead of trusting the `Child` handle. + self.record_spawned_identity(child_pid); if let Some(log_path) = backend_log_path { self.start_backend_log_rotation_worker(app, log_path, child_pid); } else { diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 7370f694..4857a138 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -11,10 +11,32 @@ use std::{ use tauri::{AppHandle, Manager}; use crate::{ - append_desktop_log, logging, process_control, BackendState, BACKEND_LOG_MAX_BYTES, + append_desktop_log, logging, process_control, BackendState, + BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS, BACKEND_EXIT_CONFIRM_TIMEOUT_MS, BACKEND_LOG_MAX_BYTES, BACKEND_LOG_ROTATION_CHECK_INTERVAL, GRACEFUL_STOP_TIMEOUT_MS, LOG_BACKUP_COUNT, }; +/// Confirmation that the process captured by an identity has really left the OS. +/// +/// `Child::try_wait` is not enough on its own: a handle whose process already died (or +/// whose PID was recycled) reaps immediately, so a stop that never touched the real +/// backend would still look successful. The probe below asks the OS about the PID, which +/// is the observable fact a restart is allowed to depend on. +fn confirm_process_identity_exit(identity: process_control::ProcessIdentity) -> Result<(), String> { + let outcome = process_control::wait_for_process_identity_exit( + identity, + Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), + ); + if outcome == process_control::ProcessExitOutcome::StillRunning { + return Err(format!( + "Backend process is still running after the stop request: pid={}, waited {}ms. Stop it manually before starting another backend.", + identity.pid, BACKEND_EXIT_CONFIRM_TIMEOUT_MS + )); + } + Ok(()) +} + impl BackendState { pub(crate) fn stop_backend(&self) -> Result<(), String> { self.stop_backend_with_timeout(Duration::from_millis(GRACEFUL_STOP_TIMEOUT_MS)) @@ -31,8 +53,16 @@ impl BackendState { return Ok(()); }; + // Capture the identity before stopping: it is the only thing that can later + // separate "our backend exited" from "some other process answers on that PID". + let identity = process_control::capture_process_identity(child.id()); + if process_control::stop_child_process_gracefully(child, timeout, append_desktop_log) { + // Drop the reaped handle before confirming. Keeping it would leave a `Child` + // whose `try_wait` reports `Some` forever; a retried stop would then taskkill + // that stale PID even after the OS recycled it for an unrelated process. *guard = None; + confirm_process_identity_exit(identity)?; return Ok(()); } @@ -54,6 +84,8 @@ impl BackendState { return Ok(()); }; + // System shutdown is time critical, so unlike the restart flow it does not spend + // extra time confirming the exit; the OS is about to terminate everything anyway. if process_control::stop_child_process_for_system_shutdown( child, timeout, @@ -69,6 +101,63 @@ impl BackendState { )) } + /// Remember which process was just spawned, while it is certainly still alive. + pub(crate) fn record_spawned_identity(&self, pid: u32) { + let identity = process_control::capture_process_identity(pid); + match self.last_spawned_identity.lock() { + Ok(mut guard) => *guard = Some(identity), + Err(error) => append_desktop_log(&format!( + "backend last-spawned identity lock poisoned on spawn: pid={pid}, error={error}" + )), + } + } + + /// Identity recorded for `pid`, used to detect PID recycling across a restart. + pub(crate) fn spawned_identity_for( + &self, + pid: u32, + ) -> Option { + match self.last_spawned_identity.lock() { + Ok(guard) => guard.filter(|identity| identity.pid == pid), + Err(error) => { + append_desktop_log(&format!( + "backend last-spawned identity lock poisoned when reading pid={pid}: {error}" + )); + None + } + } + } + + /// PID of the child handle this shell still tracks, without polling it. + pub(crate) fn tracked_child_pid(&self) -> Option { + match self.child.lock() { + Ok(guard) => guard.as_ref().map(std::process::Child::id), + Err(error) => { + append_desktop_log(&format!( + "backend child lock poisoned when reading tracked pid: {error}" + )); + None + } + } + } + + /// PID the shell last spawned, kept even after the `Child` handle was dropped. + /// + /// This is what lets a restart name the backend that it must confirm gone when the + /// handle was already reaped — the exact situation that used to hide a still-running + /// backend behind a handle reporting `None`. + pub(crate) fn last_recorded_pid(&self) -> Option { + match self.last_spawned_identity.lock() { + Ok(guard) => guard.map(|identity| identity.pid), + Err(error) => { + append_desktop_log(&format!( + "backend last-spawned identity lock poisoned when reading pid: {error}" + )); + None + } + } + } + pub(crate) fn stop_backend_log_rotation_worker(&self) { match self.log_rotator_stop.lock() { Ok(mut guard) => { @@ -95,19 +184,27 @@ impl BackendState { } }; - let Some(child) = guard.as_mut() else { - return false; + let poll = { + let Some(child) = guard.as_mut() else { + return false; + }; + if child.id() != child_pid { + return false; + } + child.try_wait() }; - if child.id() != child_pid { - return false; - } - match child.try_wait() { + match poll { Ok(None) => true, Ok(Some(status)) => { append_desktop_log(&format!( "backend process exited, stop log rotator worker: pid={child_pid}, status={status}" )); + // Drop the reaped handle right away. Keeping it would leave a `Child` + // whose `try_wait` returns `Some` instantly, and the restart flow would + // read that as "backend already stopped" while the PID may already have + // been recycled by an unrelated process. + *guard = None; false } Err(error) => { diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index ad06dd3f..0c71c998 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -7,11 +7,72 @@ use std::{ use tauri::AppHandle; use crate::{ - append_desktop_log, append_restart_log, backend, AtomicFlagGuard, BackendBridgeState, - BackendState, LaunchPlan, GRACEFUL_RESTART_POLL_INTERVAL_MS, + append_desktop_log, append_restart_log, backend, process_control, AtomicFlagGuard, + BackendBridgeState, BackendState, LaunchPlan, BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS, + BACKEND_EXIT_CONFIRM_TIMEOUT_MS, GRACEFUL_RESTART_POLL_INTERVAL_MS, GRACEFUL_RESTART_REQUEST_TIMEOUT_MS, }; +/// Gate a respawn on observable facts instead of the previous `Child` handle. +/// +/// Two independent checks run before any spawn, in this order: +/// 1. the process this shell stopped is gone from the OS PID table (catches a reused PID +/// and a handle that reaped without the backend actually dying); +/// 2. nothing else answers on the backend endpoint (catches a backend this shell never +/// tracked, for example one started from a terminal). +/// +/// The endpoint probe is a closure so it is evaluated only after the PID gate passes. +/// Sampling it up front would judge the port while the old backend is still shutting +/// down, and a backend that leaves during the wait would be reported as a conflict. +/// +/// Both failures return an error instead of force-killing the PID. After a multi-second +/// pause the PID may already belong to an unrelated process, and terminating an unknown +/// process is worse than telling the user to stop the old backend manually. +fn preflight_before_respawn( + stopped_pid: u32, + identity: Option, + timeout: Duration, + poll_interval: Duration, + probe: P, + endpoint_probe: E, + backend_url: &str, +) -> Result<(), String> +where + P: Fn(u32) -> process_control::ProcessProbe, + E: FnOnce() -> bool, +{ + if stopped_pid != 0 { + let identity = identity.unwrap_or(process_control::ProcessIdentity { + pid: stopped_pid, + created_at: None, + }); + let outcome = process_control::wait_for_process_identity_exit_with( + identity, + timeout, + poll_interval, + probe, + ); + if outcome == process_control::ProcessExitOutcome::StillRunning { + return Err(format!( + "Previous backend is still running: pid={stopped_pid} did not exit within {}ms. Stop it manually before starting another backend.", + timeout.as_millis() + )); + } + } + + if !endpoint_probe() { + return Err(backend_endpoint_conflict_error(backend_url)); + } + + Ok(()) +} + +fn backend_endpoint_conflict_error(backend_url: &str) -> String { + format!( + "Backend endpoint {backend_url} is still answering after the restart stop. Another backend is already running; stop it manually before restarting AstrBot Desktop." + ) +} + impl BackendState { fn sanitize_auth_token(auth_token: Option<&str>) -> Option { let token = auth_token?; @@ -239,15 +300,64 @@ impl BackendState { } fn stop_backend_for_restart_flow(&self) -> Result<(), String> { + // Remember which PID to confirm before spawning. The tracked handle wins; when it + // is already gone it was reaped after an earlier exit, and the PID recorded at + // spawn time is the one that must still be proven gone. + let pid = self + .tracked_child_pid() + .or_else(|| self.last_recorded_pid()) + .unwrap_or(0); + self.restart_stop_pid.store(pid, Ordering::Release); self.stop_backend() } + /// Refuse to spawn unless the old backend is provably gone. + /// + /// Runs both gates exactly once, in this order: + /// 1) the process this shell stopped is gone from the OS PID table; + /// 2) nothing answers on the backend endpoint. + /// + /// The first catches a reused PID and a handle that reaped while the backend lived on. + /// The second catches a backend this shell never tracked — including the Windows + /// double-bind case, where a second Hypercorn bind would silently succeed because the + /// Python side sets SO_REUSEADDR. + /// + /// A failure returns an error instead of force-killing the PID: after a multi-second + /// pause the PID may already belong to an unrelated process, and terminating an + /// unknown process is worse than telling the user to stop the old backend manually. + fn confirm_previous_backend_exited(&self) -> Result<(), String> { + let stopped_pid = self.restart_stop_pid.swap(0, Ordering::AcqRel); + let identity = self.spawned_identity_for(stopped_pid); + let result = preflight_before_respawn( + stopped_pid, + identity, + Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), + process_control::probe_process, + || { + !self.ping_backend(backend::runtime::backend_ping_timeout_ms( + append_desktop_log, + )) + }, + &self.backend_url, + ); + match &result { + Ok(()) if stopped_pid != 0 => append_restart_log(&format!( + "previous backend confirmed exited before respawn: pid={stopped_pid}" + )), + Ok(()) => {} + Err(error) => append_restart_log(error), + } + result + } + fn launch_backend_after_restart( &self, app: &AppHandle, plan: &LaunchPlan, ) -> Result<(), String> { let _spawn_guard = AtomicFlagGuard::set(&self.is_spawning); + self.confirm_previous_backend_exited()?; self.start_backend_process(app, plan)?; self.wait_for_backend(plan) } @@ -317,8 +427,13 @@ impl BackendState { #[cfg(test)] mod tests { - use super::BackendState; - use crate::backend::restart_strategy::RestartStrategy; + use std::sync::Mutex; + + use super::{backend_endpoint_conflict_error, preflight_before_respawn, BackendState}; + use crate::{ + backend::restart_strategy::RestartStrategy, process_control::ProcessIdentity, + process_control::ProcessProbe, + }; #[test] fn sanitize_auth_token_rejects_empty_and_newline_tokens() { @@ -358,4 +473,173 @@ mod tests { RestartStrategy::ManagedWithGracefulFallback ); } + + fn identity(pid: u32, created_at: Option) -> Option { + Some(ProcessIdentity { pid, created_at }) + } + + #[test] + fn preflight_blocks_the_spawn_while_the_old_pid_is_still_alive() { + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || true, + "http://127.0.0.1:6185/", + ); + + let error = result.expect_err("a still-running backend must block the respawn"); + assert!(error.contains("still running"), "unexpected error: {error}"); + assert!(error.contains("pid=14360"), "unexpected error: {error}"); + assert!( + error.contains("Stop it manually"), + "the error must tell the user what to do: {error}" + ); + } + + #[test] + fn preflight_allows_the_spawn_once_the_old_pid_is_gone() { + let probes = Mutex::new(Vec::new()); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(1_000), + std::time::Duration::from_millis(10), + |pid| { + probes.lock().expect("lock probes").push(pid); + ProcessProbe::Missing + }, + || true, + "http://127.0.0.1:6185/", + ); + + assert!(result.is_ok(), "unexpected error: {result:?}"); + assert_eq!( + *probes.lock().expect("lock probes"), + vec![14360], + "a gone PID should be answered on the first probe" + ); + } + + #[test] + fn preflight_treats_a_recycled_pid_as_exited() { + // The PID answers, but the creation stamp differs, so it is a different process. + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(80), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(999), + }, + || true, + "http://127.0.0.1:6185/", + ); + + assert!(result.is_ok(), "unexpected error: {result:?}"); + } + + #[test] + fn preflight_reports_a_timeout_when_the_old_pid_never_leaves() { + let start = std::time::Instant::now(); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(60), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || true, + "http://127.0.0.1:6185/", + ); + + assert!(result.is_err()); + assert!( + start.elapsed() >= std::time::Duration::from_millis(60), + "the wait must honour the timeout before reporting failure" + ); + } + + #[test] + fn preflight_blocks_the_spawn_when_the_endpoint_still_answers() { + // The tracked PID exited, but something else still serves the backend URL. + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Missing, + || false, + "http://127.0.0.1:6185/", + ); + + let error = result.expect_err("an answering endpoint must block the respawn"); + assert_eq!( + error, + backend_endpoint_conflict_error("http://127.0.0.1:6185/") + ); + } + + #[test] + fn preflight_skips_the_endpoint_probe_when_the_pid_gate_fails() { + // The PID failure must short-circuit before the (expensive) endpoint probe runs. + let endpoint_called = std::cell::Cell::new(false); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(20), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || { + endpoint_called.set(true); + true + }, + "http://127.0.0.1:6185/", + ); + + assert!(result.is_err()); + assert!( + !endpoint_called.get(), + "the endpoint probe must not run once the PID gate already failed" + ); + } + + #[test] + fn preflight_without_a_stopped_pid_only_checks_the_endpoint() { + let ok = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("no PID means nothing to probe"), + || true, + "http://127.0.0.1:6185/", + ); + assert!(ok.is_ok()); + + let blocked = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("no PID means nothing to probe"), + || false, + "http://127.0.0.1:6185/", + ); + assert!(blocked.is_err()); + } + + #[test] + fn conflicting_endpoint_error_names_the_url_and_the_remedy() { + let message = backend_endpoint_conflict_error("http://127.0.0.1:6185/"); + assert!(message.contains("http://127.0.0.1:6185/")); + assert!(message.contains("stop it manually")); + } } diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index 43149372..58a68323 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -12,17 +12,42 @@ use std::{ use windows_sys::Win32::{ Foundation::{ CloseHandle, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_NOT_FOUND, - ERROR_NO_MORE_FILES, HANDLE, INVALID_HANDLE_VALUE, + ERROR_NO_MORE_FILES, FILETIME, HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE, }, System::{ Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, }, - Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}, + Threading::{ + GetExitCodeProcess, GetProcessTimes, OpenProcess, TerminateProcess, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, + }, }, }; +/// Identity of a process this shell spawned and still believes it owns. +/// +/// `created_at` is the platform creation timestamp when the platform exposes one. +/// Comparing it across probes is what keeps a recycled PID from being mistaken for the +/// backend that was captured before a stop. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ProcessIdentity { + pub(crate) pid: u32, + pub(crate) created_at: Option, +} + +/// Result of a single liveness probe for one PID. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProcessProbe { + /// No running process owns this PID. + Missing, + /// A running process owns this PID; `created_at` is set when the platform reports it. + Alive { created_at: Option }, + /// The platform refused to answer. Callers must not read this as proof of exit. + Unknown, +} + const FORCE_STOP_WAIT_MIN_MS: u64 = 200; #[cfg(target_os = "windows")] const WINDOWS_GRACEFUL_STOP_NONZERO_WAIT_MS: u64 = 350; @@ -213,6 +238,219 @@ fn is_process_snapshot_end_error(error: &io::Error) -> bool { code as u32 == ERROR_NO_MORE_FILES } +/// Probe a PID for liveness on Windows without trusting any `Child` handle. +/// +/// `OpenProcess` fails with `ERROR_INVALID_PARAMETER` only when the PID is truly gone, +/// so it separates "no such process" from "the process exists but denies us access". +/// A live process is additionally stamped with its creation time, which is what makes +/// PID recycling detectable: a recycled PID would come back with a different stamp. +#[cfg(target_os = "windows")] +fn probe_pid_windows(pid: u32) -> ProcessProbe { + if pid == 0 { + return ProcessProbe::Missing; + } + + let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; + if handle.is_null() { + let error = io::Error::last_os_error(); + return match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_INVALID_PARAMETER) => ProcessProbe::Missing, + // The PID still resolves but we may not query it: treat as alive so a + // permission problem can never be mistaken for a clean exit. + Some(ERROR_ACCESS_DENIED) => ProcessProbe::Alive { created_at: None }, + _ => ProcessProbe::Unknown, + }; + } + + let mut exit_code: u32 = 0; + let exit_code_ok = unsafe { GetExitCodeProcess(handle, &mut exit_code) } != 0; + if exit_code_ok && exit_code != STILL_ACTIVE as u32 { + close_handle(handle); + return ProcessProbe::Missing; + } + + let created_at = process_creation_time(handle); + close_handle(handle); + + if !exit_code_ok { + return ProcessProbe::Unknown; + } + + ProcessProbe::Alive { created_at } +} + +/// Read a process creation timestamp in 100 ns units, matching `FILETIME` semantics. +#[cfg(target_os = "windows")] +fn process_creation_time(handle: HANDLE) -> Option { + let mut creation = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let mut exit = creation; + let mut kernel = creation; + let mut user = creation; + let ok = + unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) } != 0; + if !ok { + return None; + } + + Some((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime)) +} + +/// Probe a PID for liveness on Unix via the `/proc` filesystem, which also exposes the +/// process start time needed for recycling detection. +#[cfg(not(target_os = "windows"))] +fn probe_pid_unix(pid: u32) -> ProcessProbe { + use std::{fs, path::Path}; + + if pid == 0 { + return ProcessProbe::Missing; + } + + let proc_dir = Path::new("/proc").join(pid.to_string()); + if !proc_dir.exists() { + return if Path::new("/proc/self").exists() { + ProcessProbe::Missing + } else { + // No procfs: honour POSIX signal 0 as the liveness test instead. + probe_pid_with_signal(pid) + }; + } + + let stat = match fs::read_to_string(proc_dir.join("stat")) { + Ok(stat) => stat, + Err(error) if error.kind() == io::ErrorKind::NotFound => return ProcessProbe::Missing, + Err(_) => return ProcessProbe::Unknown, + }; + + // A zombie or dead task still holds a /proc entry but no longer runs, so treat both + // as exited. Field 3 of /proc//stat is the state letter, after the "(name)" tail. + let state = stat + .rsplit_once(')') + .map(|(_, trailer)| trailer.trim_start().chars().next()); + if matches!(state, Some('Z') | Some('X') | Some('x')) { + return ProcessProbe::Missing; + } + + let created_at = stat + .rsplit_once(')') + .and_then(|(_, trailer)| trailer.split_whitespace().nth(19)) + .and_then(|value| value.parse::().ok()); + + ProcessProbe::Alive { created_at } +} + +#[cfg(not(target_os = "windows"))] +fn probe_pid_with_signal(pid: u32) -> ProcessProbe { + // `SystemTime` has no per-process creation stamp, so recycling stays undetectable + // on exotic platforms; falling back to `Unknown` would be worse than a plain probe. + match unsafe_libc_kill_zero(pid) { + Ok(()) => ProcessProbe::Alive { created_at: None }, + Err(()) => ProcessProbe::Missing, + } +} + +#[cfg(not(target_os = "windows"))] +fn unsafe_libc_kill_zero(pid: u32) -> Result<(), ()> { + // Signal 0 performs the permission and existence checks without delivering a signal. + let result = std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::null()) + .status(); + match result { + Ok(status) if status.success() => Ok(()), + _ => Err(()), + } +} + +/// Probe one PID for liveness. Never blocks longer than a couple of system calls. +pub(crate) fn probe_process(pid: u32) -> ProcessProbe { + #[cfg(target_os = "windows")] + { + probe_pid_windows(pid) + } + #[cfg(not(target_os = "windows"))] + { + probe_pid_unix(pid) + } +} + +fn probe_matches_identity(probe: ProcessProbe, identity: ProcessIdentity) -> bool { + match probe { + ProcessProbe::Missing => false, + ProcessProbe::Unknown => true, + ProcessProbe::Alive { created_at } => match (identity.created_at, created_at) { + (Some(expected), Some(actual)) => expected == actual, + // Without a timestamp on either side the PID alone is all we have, so a + // live process on that PID must be treated as the old backend. + _ => true, + }, + } +} + +/// Capture the identity of a still-running process, so later probes can tell the +/// original process apart from a recycled PID. +pub(crate) fn capture_process_identity(pid: u32) -> ProcessIdentity { + let created_at = match probe_process(pid) { + ProcessProbe::Alive { created_at } => created_at, + ProcessProbe::Missing | ProcessProbe::Unknown => None, + }; + ProcessIdentity { pid, created_at } +} + +/// Outcome of waiting for a previously spawned process to disappear. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProcessExitOutcome { + /// The PID is gone, or it now belongs to a different process. + Exited, + /// The PID still answers and still matches the captured identity. + StillRunning, +} + +/// Poll until the captured process is gone or `timeout` elapses. +/// +/// This deliberately ignores the `Child` handle. `Child::try_wait` reports `Some` for a +/// handle whose process is long gone, which is exactly how a restart used to conclude +/// "backend stopped" while an unrelated process still held the listening port. +pub(crate) fn wait_for_process_identity_exit( + identity: ProcessIdentity, + timeout: Duration, + poll_interval: Duration, +) -> ProcessExitOutcome { + wait_for_process_identity_exit_with(identity, timeout, poll_interval, probe_process) +} + +/// Same as [`wait_for_process_identity_exit`] with an injectable probe, so the timeout and +/// recycling rules can be exercised without spawning real processes. +pub(crate) fn wait_for_process_identity_exit_with( + identity: ProcessIdentity, + timeout: Duration, + poll_interval: Duration, + probe: F, +) -> ProcessExitOutcome +where + F: Fn(u32) -> ProcessProbe, +{ + let start = Instant::now(); + let poll_interval = poll_interval.max(Duration::from_millis(10)); + + loop { + if !probe_matches_identity(probe(identity.pid), identity) { + return ProcessExitOutcome::Exited; + } + + if start.elapsed() >= timeout { + return ProcessExitOutcome::StillRunning; + } + + let remaining = timeout.saturating_sub(start.elapsed()); + thread::sleep(poll_interval.min(remaining)); + } +} + #[cfg(target_os = "windows")] fn terminate_process_by_pid(pid: u32) -> io::Result<()> { let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) }; @@ -454,4 +692,139 @@ mod tests { assert_eq!(snapshot.len(), 1); assert!(snapshot[0].contains("shorten graceful wait")); } + + fn test_identity(pid: u32, created_at: Option) -> ProcessIdentity { + ProcessIdentity { pid, created_at } + } + + #[test] + fn missing_probe_never_matches_a_identity() { + assert!(!probe_matches_identity( + ProcessProbe::Missing, + test_identity(42, Some(7)) + )); + assert!(!probe_matches_identity( + ProcessProbe::Missing, + test_identity(42, None) + )); + } + + #[test] + fn alive_probe_matches_only_when_the_creation_stamp_agrees() { + assert!(probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(7) + }, + test_identity(42, Some(7)) + )); + assert!( + !probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(8) + }, + test_identity(42, Some(7)) + ), + "a different creation stamp means the PID was recycled" + ); + assert!( + probe_matches_identity( + ProcessProbe::Alive { created_at: None }, + test_identity(42, None) + ), + "without timestamps the PID alone is the only evidence left" + ); + assert!( + probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(7) + }, + test_identity(42, None) + ), + "an unknown expected stamp must not clear a live PID" + ); + } + + #[test] + fn unknown_probe_is_treated_as_still_running() { + assert!( + probe_matches_identity(ProcessProbe::Unknown, test_identity(42, Some(7))), + "a probe the OS refused to answer must never be read as proof of exit" + ); + } + + #[test] + fn wait_returns_exited_as_soon_as_the_probe_reports_missing() { + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(1_000), + Duration::from_millis(10), + |_| ProcessProbe::Missing, + ); + + assert_eq!(outcome, ProcessExitOutcome::Exited); + } + + #[test] + fn wait_returns_still_running_after_the_timeout_elapses() { + let start = Instant::now(); + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(50), + Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(7), + }, + ); + + assert_eq!(outcome, ProcessExitOutcome::StillRunning); + assert!( + start.elapsed() >= Duration::from_millis(50), + "the timeout must actually be spent before giving up" + ); + } + + #[test] + fn wait_keeps_polling_until_a_late_exit_is_observed() { + let remaining = Mutex::new(3_u8); + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(2_000), + Duration::from_millis(10), + |_| { + let mut remaining = remaining.lock().expect("lock remaining"); + if *remaining == 0 { + ProcessProbe::Missing + } else { + *remaining -= 1; + ProcessProbe::Alive { + created_at: Some(7), + } + } + }, + ); + + assert_eq!(outcome, ProcessExitOutcome::Exited); + } + + #[test] + fn wait_treats_the_current_process_as_alive() { + // Sanity check of the real probe: this test process is definitely running, so a + // zero timeout must report it as still there rather than missing. + let identity = capture_process_identity(std::process::id()); + let outcome = + wait_for_process_identity_exit(identity, Duration::ZERO, Duration::from_millis(10)); + assert_eq!(outcome, ProcessExitOutcome::StillRunning); + } + + #[test] + fn wait_reports_an_impossible_pid_as_exited() { + // PID 0 is never a real user process on Windows, and the Unix probe rejects it too. + let identity = test_identity(0, None); + let outcome = wait_for_process_identity_exit( + identity, + Duration::from_millis(50), + Duration::from_millis(10), + ); + assert_eq!(outcome, ProcessExitOutcome::Exited); + } } From 2da4a9e3c460704537f50a3a118cb4c04b59cf61 Mon Sep 17 00:00:00 2001 From: dsh-verify Date: Thu, 5 Nov 2026 04:22:25 +0800 Subject: [PATCH 02/11] fix(restart): stop stale child handles and make strategy test platform-aware - stop_backend_with_timeout: poll the tracked Child before taskkill so an already reaped handle can never be used as a stop target (PID recycling hazard), and release the child lock before the exit-confirmation wait. - stop_identity: prefer the identity captured at spawn time over a re-read taken after the stop, which can describe a recycled PID. - restart_strategy_delegates_to_strategy_module: expect ManagedSkipGraceful on Windows, matching compute_restart_strategy; the test was red on Windows before this branch and stayed red after it. --- src-tauri/src/backend/process_lifecycle.rs | 59 ++++++++++++++++++---- src-tauri/src/backend/restart.rs | 11 ++-- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 4857a138..bee175a2 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -49,19 +49,51 @@ impl BackendState { .lock() .map_err(|_| "Backend process lock poisoned.".to_string())?; - let Some(child) = guard.as_mut() else { - return Ok(()); + // A `Child` whose process already exited still answers `try_wait` with `Some` + // forever, and its PID may already belong to an unrelated process. Sending + // `taskkill /pid` to that handle would kill the wrong process, so the stale handle + // is dropped here instead of being used as a stop target. + let (pid, already_exited) = { + let Some(child) = guard.as_mut() else { + return Ok(()); + }; + let pid = child.id(); + match child.try_wait() { + Ok(Some(status)) => (pid, Some(status.to_string())), + Ok(None) => (pid, None), + Err(error) => { + append_desktop_log(&format!( + "failed to poll backend process status before stop: pid={pid}, error={error}" + )); + (pid, None) + } + } }; + if let Some(status) = already_exited { + append_desktop_log(&format!( + "backend process already exited before stop, drop stale handle: pid={pid}, status={status}" + )); + *guard = None; + return Ok(()); + } + + // Prefer the identity captured while the process was certainly alive. Re-reading it + // here could describe a recycled PID instead of the backend this shell spawned. + let identity = self.stop_identity(pid); - // Capture the identity before stopping: it is the only thing that can later - // separate "our backend exited" from "some other process answers on that PID". - let identity = process_control::capture_process_identity(child.id()); + let graceful = { + let Some(child) = guard.as_mut() else { + return Ok(()); + }; + process_control::stop_child_process_gracefully(child, timeout, append_desktop_log) + }; - if process_control::stop_child_process_gracefully(child, timeout, append_desktop_log) { - // Drop the reaped handle before confirming. Keeping it would leave a `Child` - // whose `try_wait` reports `Some` forever; a retried stop would then taskkill - // that stale PID even after the OS recycled it for an unrelated process. + if graceful { + // Drop the reaped handle before confirming so a retried stop cannot taskkill + // the stale PID, and release the child lock before the confirming wait so the + // bridge and readiness probes are not blocked for the whole timeout. *guard = None; + drop(guard); confirm_process_identity_exit(identity)?; return Ok(()); } @@ -72,6 +104,15 @@ impl BackendState { )) } + /// Identity to hold a stop against, preferring the one recorded at spawn time. + /// + /// The recorded identity was captured while the process was certainly alive; capturing + /// again after the fact can describe a recycled PID. + fn stop_identity(&self, pid: u32) -> process_control::ProcessIdentity { + self.spawned_identity_for(pid) + .unwrap_or_else(|| process_control::capture_process_identity(pid)) + } + #[cfg(target_os = "windows")] pub(crate) fn stop_backend_for_system_shutdown(&self, timeout: Duration) -> Result<(), String> { self.stop_backend_log_rotation_worker(); diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index 0c71c998..429c3650 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -468,10 +468,15 @@ mod tests { }; let state = BackendState::default(); - assert_eq!( - state.restart_strategy(&plan, true), + // A managed child on Windows packaged mode skips the graceful restart path; the + // graceful fallback only applies elsewhere. Keep the platform in the expectation so + // the delegating wrapper is asserted against the same inputs the strategy module sees. + let expected = if cfg!(target_os = "windows") { + RestartStrategy::ManagedSkipGraceful + } else { RestartStrategy::ManagedWithGracefulFallback - ); + }; + assert_eq!(state.restart_strategy(&plan, true), expected); } fn identity(pid: u32, created_at: Option) -> Option { From 6ec787a488c283b7a9a6faf390147d3d4bd2dd93 Mon Sep 17 00:00:00 2001 From: JosephTian876 Date: Thu, 5 Nov 2026 12:56:28 +0800 Subject: [PATCH 03/11] fix(process_control): correct the unix process state probe type chars().next() returns Option, so mapping over rsplit_once produced Option> and the matches! guard did not compile. The unix probe sits behind cfg(not(target_os = "windows")), so a Windows build never type-checked it and the failure only appeared on the Linux CI job. --- src-tauri/src/process_control.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index 58a68323..f718d734 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -328,7 +328,7 @@ fn probe_pid_unix(pid: u32) -> ProcessProbe { // as exited. Field 3 of /proc//stat is the state letter, after the "(name)" tail. let state = stat .rsplit_once(')') - .map(|(_, trailer)| trailer.trim_start().chars().next()); + .and_then(|(_, trailer)| trailer.trim_start().chars().next()); if matches!(state, Some('Z') | Some('X') | Some('x')) { return ProcessProbe::Missing; } From f14f3f56423989e720caeb5aaeecb88469d6dc85 Mon Sep 17 00:00:00 2001 From: JosephTian876 Date: Thu, 5 Nov 2026 13:13:53 +0800 Subject: [PATCH 04/11] fix(process_control): keep an inconclusive signal probe out of the exit verdict The signal fallback treated every non-zero `kill -0` as proof that the PID was gone. A `kill` invocation that fails on its own (command unavailable, unexpected error) says nothing about the process, so the restart preflight could accept a still-running backend as exited. The stderr is now classified: "no such process" means exited, a permission error means the process exists under another user, and anything else reports Unknown, which the caller treats as still running. --- src-tauri/src/process_control.rs | 43 +++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index f718d734..8c9bc06e 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -345,24 +345,30 @@ fn probe_pid_unix(pid: u32) -> ProcessProbe { fn probe_pid_with_signal(pid: u32) -> ProcessProbe { // `SystemTime` has no per-process creation stamp, so recycling stays undetectable // on exotic platforms; falling back to `Unknown` would be worse than a plain probe. - match unsafe_libc_kill_zero(pid) { - Ok(()) => ProcessProbe::Alive { created_at: None }, - Err(()) => ProcessProbe::Missing, - } -} - -#[cfg(not(target_os = "windows"))] -fn unsafe_libc_kill_zero(pid: u32) -> Result<(), ()> { // Signal 0 performs the permission and existence checks without delivering a signal. - let result = std::process::Command::new("kill") + let output = std::process::Command::new("kill") .args(["-0", &pid.to_string()]) .stdout(Stdio::null()) - .stderr(Stdio::null()) + .stderr(Stdio::piped()) .stdin(Stdio::null()) - .status(); - match result { - Ok(status) if status.success() => Ok(()), - _ => Err(()), + .output(); + match output { + Ok(output) if output.status.success() => ProcessProbe::Alive { created_at: None }, + Ok(output) => { + let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); + if stderr.contains("no such process") { + ProcessProbe::Missing + } else if stderr.contains("permitted") || stderr.contains("permission denied") { + // The PID exists but belongs to another user, so it is still alive. + ProcessProbe::Alive { created_at: None } + } else { + // The `kill` invocation itself failed, which says nothing about the PID. + // Reporting Unknown makes the caller refuse the restart instead of + // assuming a clean exit. + ProcessProbe::Unknown + } + } + Err(_) => ProcessProbe::Unknown, } } @@ -827,4 +833,13 @@ mod tests { ); assert_eq!(outcome, ProcessExitOutcome::Exited); } + + #[test] + #[cfg(not(target_os = "windows"))] + fn signal_probe_reports_a_missing_pid_as_exited() { + // The signal fallback only runs where procfs is unavailable. A PID that cannot + // exist must come back as Missing; reporting Unknown would make the restart + // preflight treat a dead process as alive and refuse a valid restart. + assert_eq!(probe_pid_with_signal(u32::MAX - 1), ProcessProbe::Missing); + } } From 29474323aea6714e5f2b91697814b723083fd38d Mon Sep 17 00:00:00 2001 From: JosephTian876 Date: Thu, 5 Nov 2026 13:13:53 +0800 Subject: [PATCH 05/11] fix(backend): gate the failed-update respawn on the exit confirmation The failed-install recovery path called `start_backend_process` directly, bypassing the exit confirmation the restart flow uses. The update flow stops the backend before installing, so recovery could spawn a replacement while the old process still served the endpoint. Recovery now runs the same confirmation first, and any stop records the PID it targeted so that confirmation has something to check. --- src-tauri/src/backend/process_lifecycle.rs | 5 +++++ src-tauri/src/backend/restart.rs | 2 +- src-tauri/src/bridge/commands.rs | 3 +++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index bee175a2..2e023b06 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -80,6 +80,11 @@ impl BackendState { // Prefer the identity captured while the process was certainly alive. Re-reading it // here could describe a recycled PID instead of the backend this shell spawned. let identity = self.stop_identity(pid); + // Remember the target so any caller that respawns afterwards can confirm the PID is + // really gone. The restart flow sets this itself; recording it here as well covers + // the paths that stop the backend without going through a restart first, such as + // the update flow's failed-install recovery. + self.restart_stop_pid.store(pid, Ordering::Release); let graceful = { let Some(child) = guard.as_mut() else { diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index 429c3650..019fc2d1 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -325,7 +325,7 @@ impl BackendState { /// A failure returns an error instead of force-killing the PID: after a multi-second /// pause the PID may already belong to an unrelated process, and terminating an /// unknown process is worse than telling the user to stop the old backend manually. - fn confirm_previous_backend_exited(&self) -> Result<(), String> { + pub(crate) fn confirm_previous_backend_exited(&self) -> Result<(), String> { let stopped_pid = self.restart_stop_pid.swap(0, Ordering::AcqRel); let identity = self.spawned_identity_for(stopped_pid); let result = preflight_before_respawn( diff --git a/src-tauri/src/bridge/commands.rs b/src-tauri/src/bridge/commands.rs index c81eab97..112add3b 100644 --- a/src-tauri/src/bridge/commands.rs +++ b/src-tauri/src/bridge/commands.rs @@ -181,6 +181,9 @@ fn build_restart_backend_after_failed_install( "update install failed before exit, revalidating resources before restarting managed backend", ); let restart_plan = state.resolve_launch_plan(&app_handle)?; + // The update flow stopped the backend before installing. Only respawn once the old + // process is provably gone, otherwise the replacement would serve alongside it. + state.confirm_previous_backend_exited()?; state.start_backend_process(&app_handle, &restart_plan)?; state.wait_for_backend(&restart_plan) } From 54ad6481d008ea4636ebf770bba287120be9828a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sat, 14 Nov 2026 23:24:46 +0900 Subject: [PATCH 06/11] test: use a valid missing PID in signal probe test --- src-tauri/src/process_control.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index 8c9bc06e..48fe07a2 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -837,9 +837,15 @@ mod tests { #[test] #[cfg(not(target_os = "windows"))] fn signal_probe_reports_a_missing_pid_as_exited() { - // The signal fallback only runs where procfs is unavailable. A PID that cannot - // exist must come back as Missing; reporting Unknown would make the restart - // preflight treat a dead process as alive and refuse a valid restart. - assert_eq!(probe_pid_with_signal(u32::MAX - 1), ProcessProbe::Missing); + // Reap a real child so the PID is valid but no longer exists. An out-of-range + // PID can be rejected as invalid input by kill rather than reported as missing. + let mut child = Command::new("sh") + .args(["-c", "exit 0"]) + .spawn() + .expect("spawn short-lived child"); + let pid = child.id(); + assert!(child.wait().expect("reap short-lived child").success()); + + assert_eq!(probe_pid_with_signal(pid), ProcessProbe::Missing); } } From 19ca27cfe8906967bdd955511104c1ce0b019d6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 15 Nov 2026 00:23:16 +0900 Subject: [PATCH 07/11] fix(process): keep procfs metadata errors inconclusive --- src-tauri/src/process_control.rs | 74 +++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 11 deletions(-) diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index 48fe07a2..e7742f24 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -301,21 +301,28 @@ fn process_creation_time(handle: HANDLE) -> Option { /// Probe a PID for liveness on Unix via the `/proc` filesystem, which also exposes the /// process start time needed for recycling detection. #[cfg(not(target_os = "windows"))] -fn probe_pid_unix(pid: u32) -> ProcessProbe { - use std::{fs, path::Path}; +fn probe_pid_unix(pid: u32, proc_root: &std::path::Path) -> ProcessProbe { + use std::fs; if pid == 0 { return ProcessProbe::Missing; } - let proc_dir = Path::new("/proc").join(pid.to_string()); - if !proc_dir.exists() { - return if Path::new("/proc/self").exists() { - ProcessProbe::Missing - } else { - // No procfs: honour POSIX signal 0 as the liveness test instead. - probe_pid_with_signal(pid) - }; + let proc_dir = proc_root.join(pid.to_string()); + match fs::metadata(&proc_dir) { + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return match fs::metadata(proc_root.join("self")) { + Ok(_) => ProcessProbe::Missing, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // No procfs: honour POSIX signal 0 as the liveness test instead. + probe_pid_with_signal(pid) + } + Err(_) => ProcessProbe::Unknown, + }; + } + // An unreadable entry does not prove that the process has exited. + Err(_) => return ProcessProbe::Unknown, } let stat = match fs::read_to_string(proc_dir.join("stat")) { @@ -380,7 +387,7 @@ pub(crate) fn probe_process(pid: u32) -> ProcessProbe { } #[cfg(not(target_os = "windows"))] { - probe_pid_unix(pid) + probe_pid_unix(pid, std::path::Path::new("/proc")) } } @@ -848,4 +855,49 @@ mod tests { assert_eq!(probe_pid_with_signal(pid), ProcessProbe::Missing); } + + #[test] + #[cfg(unix)] + fn proc_probe_keeps_metadata_errors_inconclusive() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::fs::create_dir(proc_root.path().join("self")).expect("create self entry"); + let pid_entry = proc_root.path().join("42"); + std::os::unix::fs::symlink("42", &pid_entry).expect("create symlink loop"); + assert!(std::fs::metadata(pid_entry).is_err()); + + assert_eq!(probe_pid_unix(42, proc_root.path()), ProcessProbe::Unknown); + } + + #[test] + #[cfg(unix)] + fn proc_probe_keeps_procfs_detection_errors_inconclusive() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::os::unix::fs::symlink("self", proc_root.path().join("self")) + .expect("create self symlink loop"); + + assert_eq!( + probe_pid_unix(std::process::id(), proc_root.path()), + ProcessProbe::Unknown + ); + } + + #[test] + #[cfg(unix)] + fn proc_probe_reports_a_missing_entry_when_procfs_is_available() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::fs::create_dir(proc_root.path().join("self")).expect("create self entry"); + + assert_eq!(probe_pid_unix(42, proc_root.path()), ProcessProbe::Missing); + } + + #[test] + #[cfg(unix)] + fn proc_probe_uses_signal_when_procfs_is_absent() { + let fixture = tempfile::tempdir().expect("create absent proc fixture"); + + assert_eq!( + probe_pid_unix(std::process::id(), &fixture.path().join("absent")), + ProcessProbe::Alive { created_at: None } + ); + } } From 4d3a6c5a31f8d394b296463ee33e850a5e75d5f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 15 Nov 2026 00:23:16 +0900 Subject: [PATCH 08/11] fix(backend): serialize lifecycle actions and bound restart probes --- src-tauri/src/app_types.rs | 15 -- src-tauri/src/backend/http.rs | 210 ++++++++++++++++++++- src-tauri/src/backend/launch.rs | 16 +- src-tauri/src/backend/process_lifecycle.rs | 33 ++-- src-tauri/src/backend/restart.rs | 209 ++++++++++++++------ src-tauri/src/bridge/commands.rs | 7 +- 6 files changed, 389 insertions(+), 101 deletions(-) diff --git a/src-tauri/src/app_types.rs b/src-tauri/src/app_types.rs index 15dfb15e..15c40a0a 100644 --- a/src-tauri/src/app_types.rs +++ b/src-tauri/src/app_types.rs @@ -115,11 +115,6 @@ pub(crate) struct AtomicFlagGuard<'a> { } impl<'a> AtomicFlagGuard<'a> { - pub(crate) fn set(flag: &'a AtomicBool) -> Self { - flag.store(true, Ordering::Relaxed); - Self { flag } - } - pub(crate) fn try_set(flag: &'a AtomicBool) -> Option { flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok()?; @@ -162,16 +157,6 @@ mod tests { use super::AtomicFlagGuard; - #[test] - fn atomic_flag_guard_set_resets_flag_on_drop() { - let flag = AtomicBool::new(false); - { - let _guard = AtomicFlagGuard::set(&flag); - assert!(flag.load(Ordering::Relaxed)); - } - assert!(!flag.load(Ordering::Relaxed)); - } - #[test] fn atomic_flag_guard_try_set_rejects_double_set_until_drop() { let flag = AtomicBool::new(false); diff --git a/src-tauri/src/backend/http.rs b/src-tauri/src/backend/http.rs index 4b77f4db..18e4093c 100644 --- a/src-tauri/src/backend/http.rs +++ b/src-tauri/src/backend/http.rs @@ -1,10 +1,10 @@ use std::{ io::{ErrorKind, Read, Write}, - net::{TcpStream, ToSocketAddrs}, + net::{SocketAddr, TcpStream, ToSocketAddrs}, time::{Duration, Instant}, }; -use url::Url; +use url::{Host, Url}; use crate::{ backend::http_response, @@ -15,6 +15,84 @@ use crate::{ const MAX_BACKEND_HTTP_HEADER_BYTES: usize = 64 * 1024; const MAX_BACKEND_HTTP_BODY_BYTES: usize = 32 * 1024 * 1024; +/// Require refused connections on every resolved address before permitting a respawn. +fn confirm_backend_endpoint_available_with_resolver( + backend_url: &str, + timeout: Duration, + resolve: F, +) -> Result<(), String> +where + F: FnOnce(String, u16) -> std::io::Result> + Send + 'static, +{ + let inconclusive = |reason: &str| { + format!( + "Cannot confirm backend endpoint {backend_url} is available: {reason}. Refusing to start another backend." + ) + }; + let deadline = Instant::now() + .checked_add(timeout) + .ok_or_else(|| inconclusive("invalid probe timeout"))?; + let parsed = + Url::parse(backend_url).map_err(|error| inconclusive(&format!("invalid URL: {error}")))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(inconclusive("unsupported backend URL scheme")); + } + let port = parsed + .port_or_known_default() + .ok_or_else(|| inconclusive("URL has no port"))?; + let addrs = match parsed.host() { + Some(Host::Ipv4(ip)) => vec![SocketAddr::from((ip, port))], + Some(Host::Ipv6(ip)) => vec![SocketAddr::from((ip, port))], + Some(Host::Domain(host)) => { + let host = host.to_string(); + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + // The OS resolver cannot be cancelled. Bound the caller's wait and let a + // late worker discard its result after the receiver has been dropped. + std::thread::Builder::new() + .name("backend-endpoint-resolver".to_string()) + .spawn(move || { + let _ = sender.send(resolve(host, port)); + }) + .map_err(|error| { + inconclusive(&format!("could not start name resolution: {error}")) + })?; + let remaining = deadline + .checked_duration_since(Instant::now()) + .filter(|remaining| !remaining.is_zero()) + .ok_or_else(|| inconclusive("probe timed out during name resolution"))?; + receiver + .recv_timeout(remaining) + .map_err(|error| inconclusive(&format!("name resolution did not finish: {error}")))? + .map_err(|error| inconclusive(&format!("name resolution failed: {error}")))? + } + None => return Err(inconclusive("URL has no host")), + }; + if addrs.is_empty() { + return Err(inconclusive("name resolution returned no addresses")); + } + + for address in addrs { + let remaining = deadline + .checked_duration_since(Instant::now()) + .filter(|remaining| !remaining.is_zero()) + .ok_or_else(|| inconclusive("probe timed out"))?; + match TcpStream::connect_timeout(&address, remaining) { + Ok(_) => { + return Err(format!( + "Backend endpoint {backend_url} is already answering. Stop the existing backend before starting another." + )); + } + Err(error) if error.kind() == ErrorKind::ConnectionRefused => {} + Err(error) => { + return Err(inconclusive(&format!( + "connection to {address} failed: {error}" + ))); + } + } + } + Ok(()) +} + trait ResponseReader: Read { fn set_response_read_timeout(&self, timeout: Duration) -> std::io::Result<()>; } @@ -33,6 +111,18 @@ struct BackendRequestOptions<'a> { } impl BackendState { + pub(crate) fn confirm_backend_endpoint_available(&self, timeout_ms: u64) -> Result<(), String> { + confirm_backend_endpoint_available_with_resolver( + &self.backend_url, + Duration::from_millis(timeout_ms.max(1)), + |host, port| { + (host.as_str(), port) + .to_socket_addrs() + .map(Iterator::collect) + }, + ) + } + pub(crate) fn ping_backend(&self, timeout_ms: u64) -> bool { let parsed = match Url::parse(&self.backend_url) { Ok(url) => url, @@ -374,6 +464,122 @@ fn read_http_response_bytes( mod tests { use super::*; + #[test] + fn restart_endpoint_probe_rejects_invalid_urls() { + let state = BackendState { + backend_url: "not a backend URL".to_string(), + ..BackendState::default() + }; + + assert!( + state.confirm_backend_endpoint_available(50).is_err(), + "an invalid endpoint must not authorize a replacement backend" + ); + } + + #[test] + fn restart_endpoint_probe_rejects_a_listening_backend() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let state = BackendState { + backend_url: format!( + "http://{}/", + listener.local_addr().expect("listener address") + ), + ..BackendState::default() + }; + + let error = state + .confirm_backend_endpoint_available(200) + .expect_err("an answering endpoint must block a respawn"); + assert!(error.contains("already answering")); + } + + #[test] + fn restart_endpoint_probe_accepts_refused_loopback_connections() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().expect("listener address"); + drop(listener); + + let result = confirm_backend_endpoint_available_with_resolver( + &format!("http://{address}/"), + Duration::from_millis(200), + |_, _| panic!("numeric addresses must not invoke DNS"), + ); + assert!( + result.is_ok(), + "a refused connection must permit respawn: {result:?}" + ); + } + + #[test] + fn restart_endpoint_probe_does_not_treat_resolution_errors_as_available() { + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .expect_err("an inconclusive resolution must block a respawn"); + + assert!(error.contains("Cannot confirm backend endpoint")); + assert!(error.contains("name resolution failed")); + } + + #[test] + fn restart_endpoint_probe_rejects_empty_resolution_results() { + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + Duration::from_millis(200), + |_, _| Ok(Vec::new()), + ) + .is_err()); + } + + #[test] + fn restart_endpoint_probe_bounds_hostname_resolution_by_the_total_deadline() { + let (release, blocked) = std::sync::mpsc::channel(); + let (finished, completed) = std::sync::mpsc::channel(); + let start = Instant::now(); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + Duration::from_millis(100), + move |_, _| { + let _ = blocked.recv_timeout(Duration::from_secs(2)); + let _ = finished.send(()); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ); + let elapsed = start.elapsed(); + let _ = release.send(()); + completed + .recv_timeout(Duration::from_secs(1)) + .expect("resolver worker must finish after being released"); + + assert!(result.is_err(), "a timed-out probe must block a respawn"); + assert!( + elapsed < Duration::from_secs(1), + "DNS must share the probe deadline instead of blocking for {elapsed:?}" + ); + } + + #[test] + fn restart_endpoint_probe_checks_every_resolved_address() { + let available_listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("bind available address"); + let available = available_listener.local_addr().expect("available address"); + let occupied_listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("bind occupied address"); + let occupied = occupied_listener.local_addr().expect("occupied address"); + drop(available_listener); + + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + Duration::from_millis(200), + move |_, _| Ok(vec![available, occupied]), + ) + .expect_err("one answering address must block a respawn"); + assert!(error.contains("already answering")); + } + #[test] fn is_complete_http_response_respects_content_length() { let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"; diff --git a/src-tauri/src/backend/launch.rs b/src-tauri/src/backend/launch.rs index bdf78558..380d8bca 100644 --- a/src-tauri/src/backend/launch.rs +++ b/src-tauri/src/backend/launch.rs @@ -516,6 +516,16 @@ impl BackendState { command.stderr(Stdio::null()); } + // Keep the child-slot check and spawn in the same critical section, including + // callers that do not hold the high-level backend action reservation. + let mut child_guard = self + .child + .lock() + .map_err(|_| "Backend process lock poisoned.")?; + if child_guard.is_some() { + append_desktop_log("backend child already exists, skip re-spawn"); + return Ok(()); + } let child = command.spawn().map_err(|error| { format!( "Failed to spawn backend process with command {:?}: {}", @@ -529,13 +539,11 @@ impl BackendState { build_debug_command(plan), plan.cwd.display() )); - *self - .child - .lock() - .map_err(|_| "Backend process lock poisoned.")? = Some(child); + *child_guard = Some(child); // Record the identity while the process is certainly alive; a later restart uses // it to prove the process is gone instead of trusting the `Child` handle. self.record_spawned_identity(child_pid); + drop(child_guard); if let Some(log_path) = backend_log_path { self.start_backend_log_rotation_worker(app, log_path, child_pid); } else { diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 2e023b06..9a3b45ed 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -16,12 +16,7 @@ use crate::{ BACKEND_LOG_ROTATION_CHECK_INTERVAL, GRACEFUL_STOP_TIMEOUT_MS, LOG_BACKUP_COUNT, }; -/// Confirmation that the process captured by an identity has really left the OS. -/// -/// `Child::try_wait` is not enough on its own: a handle whose process already died (or -/// whose PID was recycled) reaps immediately, so a stop that never touched the real -/// backend would still look successful. The probe below asks the OS about the PID, which -/// is the observable fact a restart is allowed to depend on. +/// Confirm the recorded process identity independently without signalling a reused PID. fn confirm_process_identity_exit(identity: process_control::ProcessIdentity) -> Result<(), String> { let outcome = process_control::wait_for_process_identity_exit( identity, @@ -30,7 +25,7 @@ fn confirm_process_identity_exit(identity: process_control::ProcessIdentity) -> ); if outcome == process_control::ProcessExitOutcome::StillRunning { return Err(format!( - "Backend process is still running after the stop request: pid={}, waited {}ms. Stop it manually before starting another backend.", + "Backend exit could not be confirmed after the stop request: pid={}, waited {}ms. The process may still be running or its identity may be unavailable. Wait and retry; stop it manually only after verifying it is the backend.", identity.pid, BACKEND_EXIT_CONFIRM_TIMEOUT_MS )); } @@ -49,15 +44,25 @@ impl BackendState { .lock() .map_err(|_| "Backend process lock poisoned.".to_string())?; - // A `Child` whose process already exited still answers `try_wait` with `Some` - // forever, and its PID may already belong to an unrelated process. Sending - // `taskkill /pid` to that handle would kill the wrong process, so the stale handle - // is dropped here instead of being used as a stop target. + // A completed `Child` is not evidence that the backend endpoint is unused. + // Drop it without another stop request; callers verify the endpoint before + // reporting a bridge stop or spawning a replacement. let (pid, already_exited) = { let Some(child) = guard.as_mut() else { + if let Some(pid) = self.last_recorded_pid() { + let _ = self.restart_stop_pid.compare_exchange( + 0, + pid, + Ordering::AcqRel, + Ordering::Acquire, + ); + } return Ok(()); }; let pid = child.id(); + // Keep the stop target even when this handle has already exited, so update + // recovery and retries run the same process confirmation as a restart. + self.restart_stop_pid.store(pid, Ordering::Release); match child.try_wait() { Ok(Some(status)) => (pid, Some(status.to_string())), Ok(None) => (pid, None), @@ -80,12 +85,6 @@ impl BackendState { // Prefer the identity captured while the process was certainly alive. Re-reading it // here could describe a recycled PID instead of the backend this shell spawned. let identity = self.stop_identity(pid); - // Remember the target so any caller that respawns afterwards can confirm the PID is - // really gone. The restart flow sets this itself; recording it here as well covers - // the paths that stop the backend without going through a restart first, such as - // the update flow's failed-install recovery. - self.restart_stop_pid.store(pid, Ordering::Release); - let graceful = { let Some(child) = guard.as_mut() else { return Ok(()); diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index 019fc2d1..5b1ec688 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -16,10 +16,9 @@ use crate::{ /// Gate a respawn on observable facts instead of the previous `Child` handle. /// /// Two independent checks run before any spawn, in this order: -/// 1. the process this shell stopped is gone from the OS PID table (catches a reused PID -/// and a handle that reaped without the backend actually dying); -/// 2. nothing else answers on the backend endpoint (catches a backend this shell never -/// tracked, for example one started from a terminal). +/// 1. the recorded process identity is no longer present, allowing a reused PID only +/// when its creation timestamp proves that it is a different process; +/// 2. the backend endpoint explicitly refuses connections on every resolved address. /// /// The endpoint probe is a closure so it is evaluated only after the PID gate passes. /// Sampling it up front would judge the port while the old backend is still shutting @@ -35,11 +34,10 @@ fn preflight_before_respawn( poll_interval: Duration, probe: P, endpoint_probe: E, - backend_url: &str, ) -> Result<(), String> where P: Fn(u32) -> process_control::ProcessProbe, - E: FnOnce() -> bool, + E: FnOnce() -> Result<(), String>, { if stopped_pid != 0 { let identity = identity.unwrap_or(process_control::ProcessIdentity { @@ -54,23 +52,13 @@ where ); if outcome == process_control::ProcessExitOutcome::StillRunning { return Err(format!( - "Previous backend is still running: pid={stopped_pid} did not exit within {}ms. Stop it manually before starting another backend.", + "Previous backend exit could not be confirmed: pid={stopped_pid} still exists or cannot be inspected after {}ms. Wait and retry. Stop it manually only after verifying it is the backend.", timeout.as_millis() )); } } - if !endpoint_probe() { - return Err(backend_endpoint_conflict_error(backend_url)); - } - - Ok(()) -} - -fn backend_endpoint_conflict_error(backend_url: &str) -> String { - format!( - "Backend endpoint {backend_url} is still answering after the restart stop. Another backend is already running; stop it manually before restarting AstrBot Desktop." - ) + endpoint_probe() } impl BackendState { @@ -171,21 +159,20 @@ impl BackendState { } pub(crate) fn stop_backend_for_bridge(&self) -> Result<(), String> { + let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning) + .ok_or_else(|| "Backend action already in progress.".to_string())?; let has_managed_child = self .child .lock() .map_err(|_| "Backend process lock poisoned.".to_string())? .is_some(); if has_managed_child { - return self.stop_backend(); + self.stop_backend()?; } - if self.ping_backend(backend::runtime::backend_ping_timeout_ms( + self.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms( append_desktop_log, - )) { - return Err("Backend is running but not managed by desktop process.".to_string()); - } - Ok(()) + )) } fn has_managed_child(&self) -> Result { @@ -314,19 +301,18 @@ impl BackendState { /// Refuse to spawn unless the old backend is provably gone. /// /// Runs both gates exactly once, in this order: - /// 1) the process this shell stopped is gone from the OS PID table; - /// 2) nothing answers on the backend endpoint. + /// 1) the recorded process identity is no longer present; + /// 2) the backend endpoint explicitly refuses connections. /// - /// The first catches a reused PID and a handle that reaped while the backend lived on. - /// The second catches a backend this shell never tracked — including the Windows - /// double-bind case, where a second Hypercorn bind would silently succeed because the - /// Python side sets SO_REUSEADDR. + /// An unknown process identity or endpoint result blocks the replacement. A missing + /// creation timestamp can also conservatively block a reused PID, so a failed check + /// preserves the target for a retry instead of asserting that the backend is alive. /// /// A failure returns an error instead of force-killing the PID: after a multi-second /// pause the PID may already belong to an unrelated process, and terminating an /// unknown process is worse than telling the user to stop the old backend manually. pub(crate) fn confirm_previous_backend_exited(&self) -> Result<(), String> { - let stopped_pid = self.restart_stop_pid.swap(0, Ordering::AcqRel); + let stopped_pid = self.restart_stop_pid.load(Ordering::Acquire); let identity = self.spawned_identity_for(stopped_pid); let result = preflight_before_respawn( stopped_pid, @@ -335,12 +321,19 @@ impl BackendState { Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), process_control::probe_process, || { - !self.ping_backend(backend::runtime::backend_ping_timeout_ms( + self.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms( append_desktop_log, )) }, - &self.backend_url, ); + if result.is_ok() { + let _ = self.restart_stop_pid.compare_exchange( + stopped_pid, + 0, + Ordering::AcqRel, + Ordering::Acquire, + ); + } match &result { Ok(()) if stopped_pid != 0 => append_restart_log(&format!( "previous backend confirmed exited before respawn: pid={stopped_pid}" @@ -356,7 +349,6 @@ impl BackendState { app: &AppHandle, plan: &LaunchPlan, ) -> Result<(), String> { - let _spawn_guard = AtomicFlagGuard::set(&self.is_spawning); self.confirm_previous_backend_exited()?; self.start_backend_process(app, plan)?; self.wait_for_backend(plan) @@ -369,6 +361,8 @@ impl BackendState { ) -> Result<(), String> { append_restart_log("backend restart requested"); + let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning) + .ok_or_else(|| "Backend action already in progress.".to_string())?; let _restart_guard = AtomicFlagGuard::try_set(&self.is_restarting) .ok_or_else(|| "Backend action already in progress.".to_string())?; let plan = self.resolve_launch_plan(app)?; @@ -427,14 +421,102 @@ impl BackendState { #[cfg(test)] mod tests { - use std::sync::Mutex; + use std::{ + net::TcpListener, + process::{Command, Stdio}, + sync::{atomic::Ordering, Mutex}, + }; - use super::{backend_endpoint_conflict_error, preflight_before_respawn, BackendState}; + use super::{preflight_before_respawn, BackendState}; use crate::{ backend::restart_strategy::RestartStrategy, process_control::ProcessIdentity, process_control::ProcessProbe, }; + #[test] + fn bridge_stop_rejects_an_action_already_in_progress() { + let state = BackendState { + backend_url: "invalid URL".to_string(), + ..BackendState::default() + }; + state.is_spawning.store(true, Ordering::Release); + + assert_eq!( + state.stop_backend_for_bridge(), + Err("Backend action already in progress.".to_string()) + ); + assert!(state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn bridge_stop_reports_an_answering_backend_after_dropping_a_stale_child() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + child.wait().expect("reap the child"); + let state = BackendState { + child: Mutex::new(Some(child)), + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + + assert!(state.stop_backend_for_bridge().is_err()); + assert!(state.child.lock().unwrap().is_none()); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn bridge_stop_rejects_an_inconclusive_endpoint_probe() { + let state = BackendState { + backend_url: "invalid URL".to_string(), + ..BackendState::default() + }; + + let error = state + .stop_backend_for_bridge() + .expect_err("a failed probe must not report a successful stop"); + assert!(error.contains("Cannot confirm backend endpoint")); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn failed_endpoint_confirmation_retains_the_pid_for_a_retry() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + let pid = child.id(); + child.wait().expect("reap the child"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + state.restart_stop_pid.store(pid, Ordering::Release); + + assert!(state.confirm_previous_backend_exited().is_err()); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + drop(listener); + assert_eq!(state.confirm_previous_backend_exited(), Ok(())); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + } + + #[test] + fn stopping_an_empty_child_slot_remembers_the_last_spawned_identity() { + let state = BackendState::default(); + let pid = std::process::id(); + state.record_spawned_identity(pid); + + assert_eq!(state.stop_backend(), Ok(())); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + } + #[test] fn sanitize_auth_token_rejects_empty_and_newline_tokens() { assert_eq!(BackendState::sanitize_auth_token(None), None); @@ -493,12 +575,18 @@ mod tests { |_| ProcessProbe::Alive { created_at: Some(100), }, - || true, - "http://127.0.0.1:6185/", + || Ok(()), ); let error = result.expect_err("a still-running backend must block the respawn"); - assert!(error.contains("still running"), "unexpected error: {error}"); + assert!( + error.contains("could not be confirmed"), + "unexpected error: {error}" + ); + assert!( + error.contains("Wait and retry"), + "unexpected error: {error}" + ); assert!(error.contains("pid=14360"), "unexpected error: {error}"); assert!( error.contains("Stop it manually"), @@ -518,8 +606,7 @@ mod tests { probes.lock().expect("lock probes").push(pid); ProcessProbe::Missing }, - || true, - "http://127.0.0.1:6185/", + || Ok(()), ); assert!(result.is_ok(), "unexpected error: {result:?}"); @@ -541,8 +628,7 @@ mod tests { |_| ProcessProbe::Alive { created_at: Some(999), }, - || true, - "http://127.0.0.1:6185/", + || Ok(()), ); assert!(result.is_ok(), "unexpected error: {result:?}"); @@ -559,8 +645,7 @@ mod tests { |_| ProcessProbe::Alive { created_at: Some(100), }, - || true, - "http://127.0.0.1:6185/", + || Ok(()), ); assert!(result.is_err()); @@ -579,15 +664,11 @@ mod tests { std::time::Duration::from_millis(50), std::time::Duration::from_millis(10), |_| ProcessProbe::Missing, - || false, - "http://127.0.0.1:6185/", + || Err("endpoint occupied".to_string()), ); let error = result.expect_err("an answering endpoint must block the respawn"); - assert_eq!( - error, - backend_endpoint_conflict_error("http://127.0.0.1:6185/") - ); + assert_eq!(error, "endpoint occupied"); } #[test] @@ -604,9 +685,8 @@ mod tests { }, || { endpoint_called.set(true); - true + Ok(()) }, - "http://127.0.0.1:6185/", ); assert!(result.is_err()); @@ -624,8 +704,7 @@ mod tests { std::time::Duration::from_millis(50), std::time::Duration::from_millis(10), |_| panic!("no PID means nothing to probe"), - || true, - "http://127.0.0.1:6185/", + || Ok(()), ); assert!(ok.is_ok()); @@ -635,16 +714,24 @@ mod tests { std::time::Duration::from_millis(50), std::time::Duration::from_millis(10), |_| panic!("no PID means nothing to probe"), - || false, - "http://127.0.0.1:6185/", + || Err("endpoint occupied".to_string()), ); assert!(blocked.is_err()); } #[test] - fn conflicting_endpoint_error_names_the_url_and_the_remedy() { - let message = backend_endpoint_conflict_error("http://127.0.0.1:6185/"); - assert!(message.contains("http://127.0.0.1:6185/")); - assert!(message.contains("stop it manually")); + fn preflight_preserves_an_inconclusive_endpoint_error() { + let result = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("there is no stopped PID to probe"), + || Err("DNS resolution timed out; endpoint availability is unknown".to_string()), + ); + assert_eq!( + result, + Err("DNS resolution timed out; endpoint availability is unknown".to_string()) + ); } } diff --git a/src-tauri/src/bridge/commands.rs b/src-tauri/src/bridge/commands.rs index 112add3b..9e6d1d60 100644 --- a/src-tauri/src/bridge/commands.rs +++ b/src-tauri/src/bridge/commands.rs @@ -27,8 +27,8 @@ use crate::bridge::updater_types::{ }; use crate::{ append_desktop_log, restart_backend_flow, runtime_paths, shell_locale, tray, update_channel, - BackendBridgeResult, BackendBridgeState, BackendState, DesktopAuthBridgeResult, - DEFAULT_SHELL_LOCALE, + AtomicFlagGuard, BackendBridgeResult, BackendBridgeState, BackendState, + DesktopAuthBridgeResult, DEFAULT_SHELL_LOCALE, }; fn resolve_update_channel(app_handle: &AppHandle) -> update_channel::UpdateChannel { @@ -769,6 +769,9 @@ pub(crate) async fn desktop_bridge_install_app_update( AppUpdateProgress::stage("installing"), ); let state = app_handle.state::(); + let Some(_spawn_guard) = AtomicFlagGuard::try_set(&state.is_spawning) else { + return map_update_install_error("Backend action already in progress."); + }; let stop_managed_backend = cfg!(target_os = "windows") && has_managed_backend_child(&state); let restart_backend_after_failed_install = if stop_managed_backend { match state.resolve_launch_plan(&app_handle) { From 5765ecc732c4f2a1f40b8948062e080cc4b5691d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 15 Nov 2026 00:51:51 +0900 Subject: [PATCH 09/11] fix(backend): coordinate exit and bound resolver retries Reject replacement spawns once desktop exit begins while holding the child slot. Retain one outstanding DNS resolver across retries, redact endpoint diagnostics, log early stop-confirmation failures, and strengthen deadline regressions. --- src-tauri/src/app_types.rs | 3 + src-tauri/src/backend/http.rs | 244 +++++++++++++++++++-- src-tauri/src/backend/launch.rs | 97 +++++++- src-tauri/src/backend/process_lifecycle.rs | 64 +++++- src-tauri/src/backend/restart.rs | 7 +- 5 files changed, 385 insertions(+), 30 deletions(-) diff --git a/src-tauri/src/app_types.rs b/src-tauri/src/app_types.rs index 15c40a0a..0e80c834 100644 --- a/src-tauri/src/app_types.rs +++ b/src-tauri/src/app_types.rs @@ -74,6 +74,8 @@ pub(crate) struct BackendState { /// dropped while the OS may still be tearing the process down. pub(crate) last_spawned_identity: Mutex>, pub(crate) backend_url: String, + /// Keep a timed-out DNS worker reserved until it finishes, so retries stay bounded. + pub(crate) endpoint_resolver: Mutex>>, pub(crate) restart_auth_token: Mutex>, pub(crate) desktop_session_secret: DesktopSessionSecret, pub(crate) startup_loading_mode: Mutex>, @@ -138,6 +140,7 @@ impl Default for BackendState { .unwrap_or_else(|_| DEFAULT_BACKEND_URL.to_string()), DEFAULT_BACKEND_URL, ), + endpoint_resolver: Mutex::new(None), restart_auth_token: Mutex::new(None), desktop_session_secret: DesktopSessionSecret::generate() .expect("failed to generate secure desktop session secret"), diff --git a/src-tauri/src/backend/http.rs b/src-tauri/src/backend/http.rs index 18e4093c..e2b85a5a 100644 --- a/src-tauri/src/backend/http.rs +++ b/src-tauri/src/backend/http.rs @@ -18,22 +18,29 @@ const MAX_BACKEND_HTTP_BODY_BYTES: usize = 32 * 1024 * 1024; /// Require refused connections on every resolved address before permitting a respawn. fn confirm_backend_endpoint_available_with_resolver( backend_url: &str, + resolver_worker: &std::sync::Mutex>>, timeout: Duration, resolve: F, ) -> Result<(), String> where F: FnOnce(String, u16) -> std::io::Result> + Send + 'static, { + let parsed = Url::parse(backend_url); + // Diagnostics need only the network origin. Userinfo, paths, queries and fragments + // can contain credentials, and invalid input must never be echoed as a fallback. + let display_url = match &parsed { + Ok(url) if matches!(url.scheme(), "http" | "https") => url.origin().ascii_serialization(), + _ => "".to_string(), + }; let inconclusive = |reason: &str| { format!( - "Cannot confirm backend endpoint {backend_url} is available: {reason}. Refusing to start another backend." + "Cannot confirm backend endpoint {display_url} is available: {reason}. Refusing to start another backend." ) }; let deadline = Instant::now() .checked_add(timeout) .ok_or_else(|| inconclusive("invalid probe timeout"))?; - let parsed = - Url::parse(backend_url).map_err(|error| inconclusive(&format!("invalid URL: {error}")))?; + let parsed = parsed.map_err(|error| inconclusive(&format!("invalid URL: {error}")))?; if !matches!(parsed.scheme(), "http" | "https") { return Err(inconclusive("unsupported backend URL scheme")); } @@ -45,17 +52,33 @@ where Some(Host::Ipv6(ip)) => vec![SocketAddr::from((ip, port))], Some(Host::Domain(host)) => { let host = host.to_string(); + let mut worker = resolver_worker + .lock() + .map_err(|_| inconclusive("name resolution worker lock poisoned"))?; + if worker.as_ref().is_some_and(|worker| !worker.is_finished()) { + return Err(inconclusive( + "previous name resolution is still running; retry after it finishes", + )); + } + if let Some(finished) = worker.take() { + // A panicked resolver has finished too; joining releases its resources + // and leaves a fresh attempt possible without poisoning this mutex. + let _ = finished.join(); + } let (sender, receiver) = std::sync::mpsc::sync_channel(1); - // The OS resolver cannot be cancelled. Bound the caller's wait and let a - // late worker discard its result after the receiver has been dropped. - std::thread::Builder::new() - .name("backend-endpoint-resolver".to_string()) - .spawn(move || { - let _ = sender.send(resolve(host, port)); - }) - .map_err(|error| { - inconclusive(&format!("could not start name resolution: {error}")) - })?; + // The OS resolver cannot be cancelled. Retain its handle after a timeout + // so another probe cannot accumulate another outstanding resolver. + *worker = Some( + std::thread::Builder::new() + .name("backend-endpoint-resolver".to_string()) + .spawn(move || { + let _ = sender.send(resolve(host, port)); + }) + .map_err(|error| { + inconclusive(&format!("could not start name resolution: {error}")) + })?, + ); + drop(worker); let remaining = deadline .checked_duration_since(Instant::now()) .filter(|remaining| !remaining.is_zero()) @@ -79,7 +102,7 @@ where match TcpStream::connect_timeout(&address, remaining) { Ok(_) => { return Err(format!( - "Backend endpoint {backend_url} is already answering. Stop the existing backend before starting another." + "Backend endpoint {display_url} is already answering. Stop the existing backend before starting another." )); } Err(error) if error.kind() == ErrorKind::ConnectionRefused => {} @@ -114,6 +137,7 @@ impl BackendState { pub(crate) fn confirm_backend_endpoint_available(&self, timeout_ms: u64) -> Result<(), String> { confirm_backend_endpoint_available_with_resolver( &self.backend_url, + &self.endpoint_resolver, Duration::from_millis(timeout_ms.max(1)), |host, port| { (host.as_str(), port) @@ -464,6 +488,191 @@ fn read_http_response_bytes( mod tests { use super::*; + #[test] + fn restart_endpoint_probe_retries_do_not_accumulate_blocked_resolvers() { + let resolver_worker = std::sync::Mutex::new(None); + let starts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut releases = Vec::new(); + let mut completions = Vec::new(); + for _ in 0..4 { + let (release, blocked) = std::sync::mpsc::channel(); + let (started, started_receiver) = std::sync::mpsc::channel(); + let (finished, completed) = std::sync::mpsc::channel(); + let starts_for_worker = std::sync::Arc::clone(&starts); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(30), + move |_, _| { + starts_for_worker.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let _ = started.send(()); + let _ = blocked.recv_timeout(Duration::from_secs(2)); + let _ = finished.send(()); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ); + assert!(result.is_err()); + let _ = started_receiver.recv_timeout(Duration::from_secs(1)); + releases.push(release); + completions.push(completed); + } + for release in releases { + let _ = release.send(()); + } + for completed in completions { + let _ = completed.recv_timeout(Duration::from_secs(1)); + } + assert_eq!( + starts.load(std::sync::atomic::Ordering::SeqCst), + 1, + "a timed-out resolver must retain its reservation until it finishes" + ); + } + + #[test] + fn restart_endpoint_probe_can_retry_after_the_timed_out_resolver_finishes() { + let resolver_worker = std::sync::Mutex::new(None); + let (release, blocked) = std::sync::mpsc::channel(); + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(30), + move |_, _| { + let _ = blocked.recv_timeout(Duration::from_secs(2)); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ) + .is_err()); + release.send(()).expect("release blocked resolver"); + let deadline = Instant::now() + Duration::from_secs(1); + while !resolver_worker + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_finished() + { + assert!( + Instant::now() < deadline, + "resolver must finish after release" + ); + std::thread::sleep(Duration::from_millis(1)); + } + + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().unwrap(); + drop(listener); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + move |_, _| Ok(vec![address]), + ); + assert!( + result.is_ok(), + "finished resolver must allow retry: {result:?}" + ); + } + + #[test] + fn restart_endpoint_probe_can_retry_after_the_resolver_panics() { + let resolver_worker = std::sync::Mutex::new(None); + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + |_, _| panic!("resolver panic for regression test"), + ) + .is_err()); + let deadline = Instant::now() + Duration::from_secs(1); + while !resolver_worker + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_finished() + { + assert!(Instant::now() < deadline, "panicked resolver must finish"); + std::thread::sleep(Duration::from_millis(1)); + } + + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .unwrap_err(); + assert!( + error.contains("name resolution failed"), + "retry did not run: {error}" + ); + assert!(!resolver_worker.is_poisoned()); + } + + #[test] + fn restart_endpoint_resolution_errors_redact_url_credentials() { + let error = confirm_backend_endpoint_available_with_resolver( + "http://sample-user:sample-password@backend.invalid:6185/?token=sample-token", + &std::sync::Mutex::new(None), + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .unwrap_err(); + assert!(error.contains("name resolution failed")); + assert!(error.contains("http://backend.invalid:6185")); + assert!(!error.contains("sample-user")); + assert!(!error.contains("sample-password")); + assert!(!error.contains("sample-token")); + } + + #[test] + fn restart_endpoint_errors_redact_credentials_without_changing_the_url() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let backend_url = format!( + "http://sample-user:sample-password@{}/?token=sample-token#sample-fragment", + listener.local_addr().expect("listener address") + ); + let state = BackendState { + backend_url: backend_url.clone(), + ..BackendState::default() + }; + let error = state.confirm_backend_endpoint_available(200).unwrap_err(); + assert!(!error.contains("sample-user"), "username leaked: {error}"); + assert!( + !error.contains("sample-password"), + "password leaked: {error}" + ); + assert!(!error.contains("sample-token"), "query leaked: {error}"); + assert!( + !error.contains("sample-fragment"), + "fragment leaked: {error}" + ); + assert!(error.contains(&listener.local_addr().unwrap().to_string())); + assert_eq!(state.backend_url, backend_url); + } + + #[test] + fn restart_endpoint_errors_never_echo_unparseable_or_unsupported_input() { + for backend_url in [ + "http://sample-user:sample-password@[invalid/", + "custom:sample-user:sample-password@backend", + ] { + let error = confirm_backend_endpoint_available_with_resolver( + backend_url, + &std::sync::Mutex::new(None), + Duration::from_millis(100), + |_, _| panic!("invalid endpoint must not resolve"), + ) + .unwrap_err(); + assert!(!error.contains("sample-user"), "username leaked: {error}"); + assert!( + !error.contains("sample-password"), + "password leaked: {error}" + ); + } + } + #[test] fn restart_endpoint_probe_rejects_invalid_urls() { let state = BackendState { @@ -502,6 +711,7 @@ mod tests { let result = confirm_backend_endpoint_available_with_resolver( &format!("http://{address}/"), + &std::sync::Mutex::new(None), Duration::from_millis(200), |_, _| panic!("numeric addresses must not invoke DNS"), ); @@ -515,6 +725,7 @@ mod tests { fn restart_endpoint_probe_does_not_treat_resolution_errors_as_available() { let error = confirm_backend_endpoint_available_with_resolver( "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), Duration::from_millis(200), |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), ) @@ -528,6 +739,7 @@ mod tests { fn restart_endpoint_probe_rejects_empty_resolution_results() { assert!(confirm_backend_endpoint_available_with_resolver( "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), Duration::from_millis(200), |_, _| Ok(Vec::new()), ) @@ -541,6 +753,7 @@ mod tests { let start = Instant::now(); let result = confirm_backend_endpoint_available_with_resolver( "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), Duration::from_millis(100), move |_, _| { let _ = blocked.recv_timeout(Duration::from_secs(2)); @@ -556,7 +769,7 @@ mod tests { assert!(result.is_err(), "a timed-out probe must block a respawn"); assert!( - elapsed < Duration::from_secs(1), + elapsed >= Duration::from_millis(100) && elapsed < Duration::from_millis(350), "DNS must share the probe deadline instead of blocking for {elapsed:?}" ); } @@ -573,6 +786,7 @@ mod tests { let error = confirm_backend_endpoint_available_with_resolver( "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), Duration::from_millis(200), move |_, _| Ok(vec![available, occupied]), ) diff --git a/src-tauri/src/backend/launch.rs b/src-tauri/src/backend/launch.rs index 380d8bca..14fc4143 100644 --- a/src-tauri/src/backend/launch.rs +++ b/src-tauri/src/backend/launch.rs @@ -516,15 +516,37 @@ impl BackendState { command.stderr(Stdio::null()); } + let Some(child_pid) = self.spawn_backend_command(&mut command, plan)? else { + return Ok(()); + }; + if let Some(log_path) = backend_log_path { + self.start_backend_log_rotation_worker(app, log_path, child_pid); + } else { + self.stop_backend_log_rotation_worker(); + } + Ok(()) + } + + /// Spawn and register the child atomically with respect to exit cleanup. + fn spawn_backend_command( + &self, + command: &mut Command, + plan: &crate::LaunchPlan, + ) -> Result, String> { // Keep the child-slot check and spawn in the same critical section, including // callers that do not hold the high-level backend action reservation. let mut child_guard = self .child .lock() .map_err(|_| "Backend process lock poisoned.")?; + // Exit marks the state before taking this same child lock. If exit wins, + // refuse the replacement; if spawn wins, cleanup sees and stops the child. + if self.is_quitting() { + return Err("Desktop is exiting; refusing to start the backend.".to_string()); + } if child_guard.is_some() { append_desktop_log("backend child already exists, skip re-spawn"); - return Ok(()); + return Ok(None); } let child = command.spawn().map_err(|error| { format!( @@ -544,12 +566,7 @@ impl BackendState { // it to prove the process is gone instead of trusting the `Child` handle. self.record_spawned_identity(child_pid); drop(child_guard); - if let Some(log_path) = backend_log_path { - self.start_backend_log_rotation_worker(app, log_path, child_pid); - } else { - self.stop_backend_log_rotation_worker(); - } - Ok(()) + Ok(Some(child_pid)) } } @@ -590,6 +607,72 @@ mod tests { ASTRBOT_DASHBOARD_PORT_ENV, ]; + #[test] + fn spawn_backend_command_coordinates_with_exit_cleanup() { + use crate::{lifecycle::cleanup, BackendState, LaunchPlan}; + + let executable = env::current_exe().expect("test executable"); + let plan = LaunchPlan { + cmd: executable.to_string_lossy().into_owned(), + args: vec!["--help".to_string()], + cwd: env::current_dir().expect("current directory"), + root_dir: None, + webui_dir: None, + webui_cache_version: None, + packaged_core_version: None, + packaged_webui_index_sha256: None, + packaged_webui_entry_digests: None, + startup_heartbeat_path: None, + packaged_mode: false, + }; + + let state = BackendState::default(); + let spawned = state + .spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()), + &plan, + ) + .expect("spawn before exit starts"); + assert_eq!(state.tracked_child_pid(), spawned); + assert!(spawned.is_some()); + assert!(state.try_begin_exit_cleanup()); + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + assert!(state.child.lock().unwrap().is_none()); + + for cleanup_completed in [false, true] { + let state = BackendState::default(); + if cleanup_completed { + assert!(state.try_begin_exit_cleanup()); + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } else { + state.mark_quitting(); + } + let result = state.spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()), + &plan, + ); + let mut child = state.child.lock().unwrap().take(); + if let Some(child) = child.as_mut() { + let _ = child.kill(); + child.wait().expect("reap unexpected replacement"); + } + + assert!( + child.is_none(), + "shutdown must not leave a replacement child" + ); + assert!( + result.is_err_and(|error| error.contains("exiting")), + "shutdown must reject the spawn before running the command" + ); + } + } + fn get_command_env_value(command: &Command, key: &str) -> Option> { command .get_envs() diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 9a3b45ed..0ce9511a 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -11,23 +11,32 @@ use std::{ use tauri::{AppHandle, Manager}; use crate::{ - append_desktop_log, logging, process_control, BackendState, + append_desktop_log, append_restart_log, logging, process_control, BackendState, BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS, BACKEND_EXIT_CONFIRM_TIMEOUT_MS, BACKEND_LOG_MAX_BYTES, BACKEND_LOG_ROTATION_CHECK_INTERVAL, GRACEFUL_STOP_TIMEOUT_MS, LOG_BACKUP_COUNT, }; /// Confirm the recorded process identity independently without signalling a reused PID. -fn confirm_process_identity_exit(identity: process_control::ProcessIdentity) -> Result<(), String> { +fn confirm_process_identity_exit( + identity: process_control::ProcessIdentity, + timeout: Duration, + log: F, +) -> Result<(), String> +where + F: FnOnce(&str), +{ let outcome = process_control::wait_for_process_identity_exit( identity, - Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + timeout, Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), ); if outcome == process_control::ProcessExitOutcome::StillRunning { - return Err(format!( + let error = format!( "Backend exit could not be confirmed after the stop request: pid={}, waited {}ms. The process may still be running or its identity may be unavailable. Wait and retry; stop it manually only after verifying it is the backend.", - identity.pid, BACKEND_EXIT_CONFIRM_TIMEOUT_MS - )); + identity.pid, timeout.as_millis() + ); + log(&error); + return Err(error); } Ok(()) } @@ -98,7 +107,11 @@ impl BackendState { // bridge and readiness probes are not blocked for the whole timeout. *guard = None; drop(guard); - confirm_process_identity_exit(identity)?; + confirm_process_identity_exit( + identity, + Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + append_restart_log, + )?; return Ok(()); } @@ -307,3 +320,40 @@ impl BackendState { }); } } + +#[cfg(test)] +mod tests { + use super::confirm_process_identity_exit; + use crate::process_control; + use std::time::Duration; + + #[test] + fn failed_stop_confirmation_logs_the_returned_error() { + let identity = process_control::capture_process_identity(std::process::id()); + let mut messages = Vec::new(); + + let error = confirm_process_identity_exit(identity, Duration::ZERO, |message| { + messages.push(message.to_string()); + }) + .expect_err("a live process must fail exit confirmation"); + + assert_eq!(messages, vec![error]); + } + + #[test] + fn successful_stop_confirmation_does_not_log_an_error() { + let identity = process_control::ProcessIdentity { + pid: 0, + created_at: None, + }; + let mut messages = Vec::new(); + + assert_eq!( + confirm_process_identity_exit(identity, Duration::ZERO, |message| { + messages.push(message.to_string()); + }), + Ok(()) + ); + assert!(messages.is_empty()); + } +} diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index 5b1ec688..ceca54d9 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -649,10 +649,15 @@ mod tests { ); assert!(result.is_err()); + let elapsed = start.elapsed(); assert!( - start.elapsed() >= std::time::Duration::from_millis(60), + elapsed >= std::time::Duration::from_millis(60), "the wait must honour the timeout before reporting failure" ); + assert!( + elapsed < std::time::Duration::from_millis(310), + "the wait must stay within the timeout plus scheduling tolerance: {elapsed:?}" + ); } #[test] From 286be98b39d45f4997e2fe6f068ba07dbeaf58ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 15 Nov 2026 01:17:27 +0900 Subject: [PATCH 10/11] fix(backend): guard updates and unmanaged restart fallbacks Confirm process exit and endpoint availability before installing Windows updates, including retries after stale child cleanup. Route managed starts through one preflight, reject uncertain unmanaged fallback, and cover concurrent exit with controlled scheduling. Document external endpoint ownership limits. --- docs/environment-variables.md | 11 +- src-tauri/src/backend/launch.rs | 113 +++++++++++++++- src-tauri/src/backend/process_lifecycle.rs | 10 ++ src-tauri/src/backend/readiness.rs | 22 +++ src-tauri/src/backend/restart.rs | 96 +++++++++---- src-tauri/src/bridge/commands.rs | 149 +++++++++++++++++---- 6 files changed, 351 insertions(+), 50 deletions(-) diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 1a9c29b0..ab90c315 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -1,6 +1,7 @@ # AstrBot Desktop 环境变量清单 -更新时间:2026-03-13 +更新时间:2026-11-15 + 主要来源:桌面运行时 Rust 模块(如 `src-tauri/src/backend/config.rs`、`src-tauri/src/update_channel.rs`、`src-tauri/src/bridge/updater_messages.rs`、`src-tauri/src/runtime_paths.rs`、`src-tauri/src/launch_plan.rs`)、资源准备脚本(`scripts/prepare-resources*.mjs`)和发布工作流(`.github/workflows/build-desktop-tauri.yml`)。以下按主要解析/写入阶段分组。 ## 1. 桌面运行时直接读取(`src-tauri`) @@ -30,6 +31,14 @@ | `ASTRBOT_DESKTOP_UPDATER_STABLE_ENDPOINT` | stable 通道 manifest URL 覆盖 | 未设置则读 `plugins.updater.channelEndpoints.stable`,再回退 `plugins.updater.endpoints[0]` | | `ASTRBOT_DESKTOP_UPDATER_NIGHTLY_ENDPOINT` | nightly 通道 manifest URL 覆盖 | 未设置则读 `plugins.updater.channelEndpoints.nightly` | +### 外部后端与托管后端的地址 + +`ASTRBOT_BACKEND_URL` 设置桌面端连接的地址,不会改变后端子进程实际使用的 dashboard host/port;后者由 `DASHBOARD_HOST` / `ASTRBOT_DASHBOARD_HOST`、对应端口变量及 `cmd_config.json` 决定。由桌面端托管后端时,这两组配置应指向同一个后端监听端点。 + +如果只需连接独立运行的本机或远端后端,请同时设置 `ASTRBOT_BACKEND_URL` 和 `ASTRBOT_BACKEND_AUTO_START=0`。首次连接时,地址可达就使用已有服务;地址不可达则报告错误,不自动创建替代后端。非托管后端通过后端 API 重启;重启超时后,桌面端不会自动启动一个托管进程来替代它。 + +托管进程停止后的重启及 Windows 更新准备,会检查配置地址是否仍有 TCP listener。非回环地址可能是本机局域网地址或指向本机的域名,因此不会仅因地址不是 `localhost` 就跳过检查。如果配置地址指向独立远端服务或持续监听的反向代理,TCP listener 仍存在时会保守拒绝替代启动;该检查无法判断代理后的旧进程是否已经退出。 + ## 2. 源码与资源准备(开发态运行时 / `prepare-resources` / backend build) | 变量 | 用途 | 默认值/行为 | diff --git a/src-tauri/src/backend/launch.rs b/src-tauri/src/backend/launch.rs index 14fc4143..2a142941 100644 --- a/src-tauri/src/backend/launch.rs +++ b/src-tauri/src/backend/launch.rs @@ -406,6 +406,10 @@ impl BackendState { return Ok(()); } + // Every replacement and initial managed start shares this gate. Do not hold + // the child mutex while waiting; the final spawn checks exit under that lock. + self.confirm_previous_backend_exited()?; + if !plan.cwd.exists() { fs::create_dir_all(&plan.cwd).map_err(|error| { format!( @@ -516,7 +520,13 @@ impl BackendState { command.stderr(Stdio::null()); } - let Some(child_pid) = self.spawn_backend_command(&mut command, plan)? else { + let Some(child_pid) = self.spawn_backend_command( + &mut command, + plan, + #[cfg(test)] + || {}, + )? + else { return Ok(()); }; if let Some(log_path) = backend_log_path { @@ -532,7 +542,16 @@ impl BackendState { &self, command: &mut Command, plan: &crate::LaunchPlan, + #[cfg(test)] after_quitting_check: impl FnOnce(), ) -> Result, String> { + #[cfg(test)] + let check_quitting = || { + let quitting = self.is_quitting(); + after_quitting_check(); + quitting + }; + #[cfg(not(test))] + let check_quitting = || self.is_quitting(); // Keep the child-slot check and spawn in the same critical section, including // callers that do not hold the high-level backend action reservation. let mut child_guard = self @@ -541,7 +560,7 @@ impl BackendState { .map_err(|_| "Backend process lock poisoned.")?; // Exit marks the state before taking this same child lock. If exit wins, // refuse the replacement; if spawn wins, cleanup sees and stops the child. - if self.is_quitting() { + if check_quitting() { return Err("Desktop is exiting; refusing to start the backend.".to_string()); } if child_guard.is_some() { @@ -633,6 +652,7 @@ mod tests { .arg("--help") .stdout(std::process::Stdio::null()), &plan, + || {}, ) .expect("spawn before exit starts"); assert_eq!(state.tracked_child_pid(), spawned); @@ -655,6 +675,7 @@ mod tests { .arg("--help") .stdout(std::process::Stdio::null()), &plan, + || {}, ); let mut child = state.child.lock().unwrap().take(); if let Some(child) = child.as_mut() { @@ -673,6 +694,94 @@ mod tests { } } + #[test] + fn spawn_backend_command_keeps_the_child_lock_from_exit_check_through_spawn() { + use std::{ + sync::{mpsc, TryLockError}, + time::Duration, + }; + + use crate::{lifecycle::cleanup, BackendState, LaunchPlan}; + + let executable = env::current_exe().expect("test executable"); + let plan = LaunchPlan { + cmd: executable.to_string_lossy().into_owned(), + args: vec!["--help".to_string()], + cwd: env::current_dir().expect("current directory"), + root_dir: None, + webui_dir: None, + webui_cache_version: None, + packaged_core_version: None, + packaged_webui_index_sha256: None, + packaged_webui_entry_digests: None, + startup_heartbeat_path: None, + packaged_mode: false, + }; + let state = BackendState::default(); + let (checked_tx, checked_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + + std::thread::scope(|scope| { + let spawning_state = &state; + let spawning = scope.spawn(move || { + spawning_state.spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()), + &plan, + || { + checked_tx.send(()).expect("announce exit-check barrier"); + resume_rx + .recv_timeout(Duration::from_secs(5)) + .expect("resume after marking exit"); + }, + ) + }); + + checked_rx + .recv_timeout(Duration::from_secs(5)) + .expect("spawn reaches the exit-check barrier"); + assert!(state.try_begin_exit_cleanup()); + let child_locked_during_check = match state.child.try_lock() { + Ok(guard) => { + drop(guard); + false + } + Err(TryLockError::WouldBlock) => true, + Err(TryLockError::Poisoned(_)) => panic!("child slot lock poisoned"), + }; + if !child_locked_during_check { + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } + resume_tx.send(()).expect("release spawn barrier"); + if child_locked_during_check { + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } + let result = spawning.join().expect("spawn worker finishes"); + let mut unexpected_child = state.child.lock().unwrap().take(); + if let Some(child) = unexpected_child.as_mut() { + let _ = child.kill(); + child.wait().expect("reap unexpected replacement"); + } + + assert!( + unexpected_child.is_none(), + "exit cleanup must not leave a replacement child" + ); + assert!( + child_locked_during_check, + "the exit-state query must run while holding the child lock" + ); + assert!( + matches!(result, Ok(Some(_))), + "spawn that won the exit-state check must register a child for cleanup: {result:?}" + ); + }); + } + fn get_command_env_value(command: &Command, key: &str) -> Option> { command .get_envs() diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 0ce9511a..60ac42a2 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -46,6 +46,16 @@ impl BackendState { self.stop_backend_with_timeout(Duration::from_millis(GRACEFUL_STOP_TIMEOUT_MS)) } + /// Stop and verify both the process and endpoint before a Windows installation. + pub(crate) fn stop_backend_before_update_install(&self) -> Result<(), String> { + self.stop_backend().map_err(|error| { + format!("Failed to stop backend before Windows update install: {error}") + })?; + self.confirm_previous_backend_exited().map_err(|error| { + format!("Failed to confirm backend exit before Windows update install: {error}") + }) + } + pub(crate) fn stop_backend_with_timeout(&self, timeout: Duration) -> Result<(), String> { self.stop_backend_log_rotation_worker(); let mut guard = self diff --git a/src-tauri/src/backend/readiness.rs b/src-tauri/src/backend/readiness.rs index 6f7f33cf..16613dd2 100644 --- a/src-tauri/src/backend/readiness.rs +++ b/src-tauri/src/backend/readiness.rs @@ -551,6 +551,28 @@ mod tests { use super::*; + #[test] + fn readiness_does_not_equate_slow_http_with_an_available_endpoint() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + // The listener accepts TCP handshakes but never responds to HTTP requests. + let (http_status, tcp_reachable) = state.probe_backend_readiness("/", 50); + assert!(http_status.is_none()); + assert!(tcp_reachable); + assert!( + state.ping_backend(50), + "the initial readiness branch must skip spawning" + ); + let error = state + .confirm_previous_backend_exited() + .expect_err("the final spawn gate must reject a surviving TCP listener"); + assert!(error.contains("already answering")); + assert!(state.child.lock().unwrap().is_none()); + } + fn sha256_hex(payload: &[u8]) -> String { format!("{:x}", Sha256::digest(payload)) } diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index ceca54d9..594fe1b9 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -39,6 +39,8 @@ where P: Fn(u32) -> process_control::ProcessProbe, E: FnOnce() -> Result<(), String>, { + // A first managed start has no stopped PID. An uncertain unmanaged restart + // must be rejected by its strategy before it can reach this endpoint-only gate. if stopped_pid != 0 { let identity = identity.unwrap_or(process_control::ProcessIdentity { pid: stopped_pid, @@ -218,19 +220,9 @@ impl BackendState { fn execute_graceful_restart_strategy( &self, strategy: backend::restart_strategy::RestartStrategy, - auth_token: Option<&str>, - previous_start_time: Option, - packaged_mode: bool, + outcome: backend::restart_strategy::GracefulRestartOutcome, ) -> Result<(), String> { - // Contract: this function interprets the pure (strategy, outcome) pair and either - // returns early on a completed graceful restart or performs the managed fallback path. - let outcome = match strategy { - backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => { - backend::restart_strategy::GracefulRestartOutcome::RequestRejected - } - _ => self.try_graceful_restart_and_wait(auth_token, previous_start_time, packaged_mode), - }; - + // Interpret the strategy and observed API outcome before any managed fallback. match (strategy, outcome) { ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -271,10 +263,11 @@ impl BackendState { backend::restart_strategy::RestartStrategy::UnmanagedWithGracefulProbe, backend::restart_strategy::GracefulRestartOutcome::WaitFailed(error), ) => { - append_restart_log(&format!( - "graceful restart did not complete for unmanaged backend, bootstrap managed restart: {error}" - )); - self.stop_backend_for_restart_flow() + let error = format!( + "Graceful restart did not complete and backend is not desktop-managed; refusing to start a replacement because the old process may still be restarting: {error}" + ); + append_restart_log(&error); + Err(error) } ( backend::restart_strategy::RestartStrategy::UnmanagedWithGracefulProbe, @@ -349,7 +342,6 @@ impl BackendState { app: &AppHandle, plan: &LaunchPlan, ) -> Result<(), String> { - self.confirm_previous_backend_exited()?; self.start_backend_process(app, plan)?; self.wait_for_backend(plan) } @@ -374,12 +366,17 @@ impl BackendState { } let restart_auth_token = normalized_param.or_else(|| self.get_restart_auth_token()); let previous_start_time = self.fetch_backend_start_time(); - match self.execute_graceful_restart_strategy( - strategy, - restart_auth_token.as_deref(), - previous_start_time, - plan.packaged_mode, - ) { + let outcome = match strategy { + backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => { + backend::restart_strategy::GracefulRestartOutcome::RequestRejected + } + _ => self.try_graceful_restart_and_wait( + restart_auth_token.as_deref(), + previous_start_time, + plan.packaged_mode, + ), + }; + match self.execute_graceful_restart_strategy(strategy, outcome) { Ok(()) if strategy != backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => { @@ -433,6 +430,57 @@ mod tests { process_control::ProcessProbe, }; + #[test] + fn unmanaged_restart_timeout_never_authorizes_managed_fallback() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + // A listener disappearing during a restart is not proof its process exited. + drop(listener); + assert_eq!(state.confirm_backend_endpoint_available(200), Ok(())); + + let result = state.execute_graceful_restart_strategy( + RestartStrategy::UnmanagedWithGracefulProbe, + crate::backend::restart_strategy::GracefulRestartOutcome::WaitFailed( + "restart timed out between listeners".to_string(), + ), + ); + + let error = result.expect_err("an untracked restart must not enter managed fallback"); + assert!(error.contains("not desktop-managed"), "{error}"); + assert!( + error.contains("restart timed out between listeners"), + "{error}" + ); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + assert!(state.child.lock().unwrap().is_none()); + } + + #[test] + fn unmanaged_restart_completion_and_rejection_do_not_touch_managed_state() { + use crate::backend::restart_strategy::GracefulRestartOutcome; + + for outcome in [ + GracefulRestartOutcome::Completed, + GracefulRestartOutcome::RequestRejected, + ] { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + let completed = outcome == GracefulRestartOutcome::Completed; + + let result = state.execute_graceful_restart_strategy( + RestartStrategy::UnmanagedWithGracefulProbe, + outcome, + ); + + assert_eq!(result.is_ok(), completed); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 14360); + assert!(state.child.lock().unwrap().is_none()); + } + } + #[test] fn bridge_stop_rejects_an_action_already_in_progress() { let state = BackendState { @@ -702,7 +750,7 @@ mod tests { } #[test] - fn preflight_without_a_stopped_pid_only_checks_the_endpoint() { + fn preflight_for_a_first_managed_start_only_checks_the_endpoint() { let ok = preflight_before_respawn( 0, None, diff --git a/src-tauri/src/bridge/commands.rs b/src-tauri/src/bridge/commands.rs index 9e6d1d60..f2365c98 100644 --- a/src-tauri/src/bridge/commands.rs +++ b/src-tauri/src/bridge/commands.rs @@ -107,7 +107,14 @@ fn short_circuit_update_install( } } -fn has_managed_backend_child(state: &BackendState) -> bool { +fn has_managed_backend_or_pending_stop(state: &BackendState) -> bool { + if state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire) + != 0 + { + return true; + } match state.child.lock() { Ok(guard) => guard.is_some(), Err(_) => { @@ -133,21 +140,31 @@ where install_update, || Ok(()), restart_backend_after_failed_install, - backend_was_stopped, + || Ok(backend_was_stopped), ) } -fn run_native_update_install_with_validation( +fn run_native_update_install_with_validation< + InstallUpdate, + ValidateInstall, + RestartBackend, + PrepareBackend, +>( install_update: InstallUpdate, validate_install: ValidateInstall, restart_backend_after_failed_install: Option, - backend_was_stopped: bool, + prepare_backend: PrepareBackend, ) -> DesktopAppUpdateResult where InstallUpdate: FnOnce() -> Result<(), String>, ValidateInstall: FnOnce() -> Result<(), String>, RestartBackend: FnOnce() -> Result<(), String>, + PrepareBackend: FnOnce() -> Result, { + let backend_was_stopped = match prepare_backend() { + Ok(stopped) => stopped, + Err(error) => return map_update_install_error(error), + }; let failure = match install_update() { Ok(()) => validate_install() .err() @@ -181,9 +198,8 @@ fn build_restart_backend_after_failed_install( "update install failed before exit, revalidating resources before restarting managed backend", ); let restart_plan = state.resolve_launch_plan(&app_handle)?; - // The update flow stopped the backend before installing. Only respawn once the old - // process is provably gone, otherwise the replacement would serve alongside it. - state.confirm_previous_backend_exited()?; + // The shared launch path confirms process exit and endpoint availability again + // after the installation attempt, before creating any replacement. state.start_backend_process(&app_handle, &restart_plan)?; state.wait_for_backend(&restart_plan) } @@ -772,7 +788,8 @@ pub(crate) async fn desktop_bridge_install_app_update( let Some(_spawn_guard) = AtomicFlagGuard::try_set(&state.is_spawning) else { return map_update_install_error("Backend action already in progress."); }; - let stop_managed_backend = cfg!(target_os = "windows") && has_managed_backend_child(&state); + let stop_managed_backend = + cfg!(target_os = "windows") && has_managed_backend_or_pending_stop(&state); let restart_backend_after_failed_install = if stop_managed_backend { match state.resolve_launch_plan(&app_handle) { Ok(_) => {} @@ -790,17 +807,6 @@ pub(crate) async fn desktop_bridge_install_app_update( None }; - let backend_was_stopped = if stop_managed_backend { - if let Err(error) = state.stop_backend() { - return map_update_install_error(format!( - "Failed to stop backend before Windows update install: {error}" - )); - } - true - } else { - false - }; - let expected_version = update.version.clone(); let validation_app_handle = app_handle.clone(); let result = run_native_update_install_with_validation( @@ -812,7 +818,13 @@ pub(crate) async fn desktop_bridge_install_app_update( ) }, restart_backend_after_failed_install, - backend_was_stopped, + || { + if !stop_managed_backend { + return Ok(false); + } + state.stop_backend_before_update_install()?; + Ok(true) + }, ); if result.ok { app_handle.request_restart(); @@ -944,6 +956,97 @@ mod tests { assert_eq!(result, map_update_install_ok()); } + #[test] + fn windows_update_install_does_not_proceed_while_an_untracked_endpoint_answers() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind surviving backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn stale backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("wait for stale backend child"); + *state.child.lock().unwrap() = Some(child); + let events = RefCell::new(Vec::new()); + + for _ in 0..2 { + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + || { + if !has_managed_backend_or_pending_stop(&state) { + return Ok(false); + } + state.stop_backend_before_update_install()?; + Ok(true) + }, + ); + + assert!( + !result.ok, + "a surviving listener must block Windows installation" + ); + assert!(result + .reason + .as_deref() + .unwrap() + .contains("already answering")); + assert!( + events.borrow().is_empty(), + "installer and recovery must not run" + ); + assert!(state.child.lock().unwrap().is_none()); + assert_ne!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0, + "a rejected preparation must retain the stop target" + ); + } + } + + #[test] + fn run_native_update_install_prepares_before_installing_and_validating() { + let events = RefCell::new(Vec::new()); + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + || { + events.borrow_mut().push("prepare"); + Ok(true) + }, + ); + assert!(result.ok); + assert_eq!(*events.borrow(), vec!["prepare", "install", "validate"]); + } + #[test] fn run_native_update_install_skips_restart_when_backend_was_not_stopped() { let mut restart_called = false; @@ -1027,7 +1130,7 @@ mod tests { restart_events.borrow_mut().push("restart"); Ok(()) }), - true, + || Ok(true), ); assert_eq!(*events.borrow(), vec!["restart"]); @@ -1040,7 +1143,7 @@ mod tests { } #[test] - fn has_managed_backend_child_returns_false_when_lock_is_poisoned() { + fn has_managed_backend_or_pending_stop_returns_false_when_lock_is_poisoned() { let state = BackendState::default(); let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { let _guard = state @@ -1050,6 +1153,6 @@ mod tests { panic!("poison backend child lock"); })); - assert!(!has_managed_backend_child(&state)); + assert!(!has_managed_backend_or_pending_stop(&state)); } } From 2f3fd856a41896dc490f463eab6c164e1e55859e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=B0=B8=E8=B5=AB?= <1259085392@qq.com> Date: Sun, 15 Nov 2026 01:39:09 +0900 Subject: [PATCH 11/11] fix(backend): preserve ownership through restart and update recovery --- src-tauri/src/backend/restart.rs | 180 ++++++++++++++--- src-tauri/src/backend/restart_strategy.rs | 12 +- src-tauri/src/bridge/commands.rs | 227 +++++++++++++++++----- 3 files changed, 333 insertions(+), 86 deletions(-) diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index 594fe1b9..a775559c 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -163,13 +163,9 @@ impl BackendState { pub(crate) fn stop_backend_for_bridge(&self) -> Result<(), String> { let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning) .ok_or_else(|| "Backend action already in progress.".to_string())?; - let has_managed_child = self - .child - .lock() - .map_err(|_| "Backend process lock poisoned.".to_string())? - .is_some(); - if has_managed_child { + if self.has_managed_backend()? { self.stop_backend()?; + return self.confirm_previous_backend_exited(); } self.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms( @@ -177,13 +173,29 @@ impl BackendState { )) } - fn has_managed_child(&self) -> Result { - self.child + /// Keep desktop ownership after an exited child is reaped or a stop is retried. + pub(crate) fn has_managed_backend(&self) -> Result { + let has_child = self + .child + .lock() + .map(|guard| guard.is_some()) + .map_err(|error| { + let message = + format!("backend child lock poisoned while resolving managed state: {error}"); + append_desktop_log(&message); + message + })?; + if has_child || self.restart_stop_pid.load(Ordering::Acquire) != 0 { + return Ok(true); + } + + // Reaping an exited child must not change who manages its replacement. + self.last_spawned_identity .lock() .map(|guard| guard.is_some()) .map_err(|error| { let message = format!( - "backend child lock poisoned while resolving restart strategy: {error}" + "backend spawn identity lock poisoned while resolving managed state: {error}" ); append_desktop_log(&message); message @@ -193,12 +205,12 @@ impl BackendState { fn restart_strategy( &self, plan: &LaunchPlan, - has_managed_child: bool, + has_managed_backend: bool, ) -> backend::restart_strategy::RestartStrategy { backend::restart_strategy::compute_restart_strategy( cfg!(target_os = "windows"), plan.packaged_mode, - has_managed_child, + has_managed_backend, ) } @@ -221,7 +233,9 @@ impl BackendState { &self, strategy: backend::restart_strategy::RestartStrategy, outcome: backend::restart_strategy::GracefulRestartOutcome, - ) -> Result<(), String> { + ) -> Result { + use backend::restart_strategy::RestartAction; + // Interpret the strategy and observed API outcome before any managed fallback. match (strategy, outcome) { ( @@ -233,13 +247,14 @@ impl BackendState { backend::restart_strategy::GracefulRestartOutcome::Completed, ) => { append_restart_log("graceful restart completed via backend api"); - Ok(()) + Ok(RestartAction::GracefulCompleted) } (backend::restart_strategy::RestartStrategy::ManagedSkipGraceful, _) => { append_restart_log( "skip graceful restart for packaged windows managed backend; using managed restart", ); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -248,7 +263,8 @@ impl BackendState { append_restart_log(&format!( "graceful restart did not complete, fallback to managed restart: {error}" )); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -257,7 +273,8 @@ impl BackendState { append_restart_log( "graceful restart request was rejected, fallback to managed restart", ); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::UnmanagedWithGracefulProbe, @@ -358,8 +375,8 @@ impl BackendState { let _restart_guard = AtomicFlagGuard::try_set(&self.is_restarting) .ok_or_else(|| "Backend action already in progress.".to_string())?; let plan = self.resolve_launch_plan(app)?; - let has_managed_child = self.has_managed_child()?; - let strategy = self.restart_strategy(&plan, has_managed_child); + let has_managed_backend = self.has_managed_backend()?; + let strategy = self.restart_strategy(&plan, has_managed_backend); let normalized_param = Self::sanitize_auth_token(auth_token); if let Some(token) = normalized_param.as_deref() { self.set_restart_auth_token(Some(token)); @@ -376,21 +393,16 @@ impl BackendState { plan.packaged_mode, ), }; - match self.execute_graceful_restart_strategy(strategy, outcome) { - Ok(()) - if strategy != backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => - { - self.verify_running_resource_identity( + match self.execute_graceful_restart_strategy(strategy, outcome)? { + backend::restart_strategy::RestartAction::GracefulCompleted => self + .verify_running_resource_identity( &plan, backend::runtime::backend_ping_timeout_ms(append_desktop_log).max(1_000), - )?; - return Ok(()); + ), + backend::restart_strategy::RestartAction::LaunchManagedReplacement => { + self.launch_backend_after_restart(app, &plan) } - Ok(()) => {} - Err(error) => return Err(error), } - - self.launch_backend_after_restart(app, &plan) } pub(crate) fn bridge_state(&self, app: &AppHandle) -> BackendBridgeState { @@ -431,15 +443,119 @@ mod tests { }; #[test] - fn unmanaged_restart_timeout_never_authorizes_managed_fallback() { + fn managed_backend_classification_survives_a_reaped_child() { + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + let state = BackendState::default(); + state.record_spawned_identity(child.id()); + child.wait().expect("reap the child"); + + assert!(state.child.lock().unwrap().is_none()); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + assert!( + state.has_managed_backend().unwrap(), + "reaping the child must not discard desktop ownership of its backend" + ); + } + + #[test] + fn managed_backend_classification_recognizes_a_pending_stop() { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + + assert!( + state.has_managed_backend().unwrap(), + "a pending stop must retain desktop management even without a child handle" + ); + } + + #[test] + fn backend_without_a_managed_child_or_history_stays_unmanaged() { + assert!(!BackendState::default().has_managed_backend().unwrap()); + } + + #[test] + fn bridge_stop_retry_does_not_clear_a_live_pending_process() { let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); let state = BackendState { backend_url: format!("http://{}/", listener.local_addr().unwrap()), ..BackendState::default() }; - // A listener disappearing during a restart is not proof its process exited. drop(listener); - assert_eq!(state.confirm_backend_endpoint_available(200), Ok(())); + let pid = std::process::id(); + state.record_spawned_identity(pid); + state.restart_stop_pid.store(pid, Ordering::Release); + + let error = state + .stop_backend_for_bridge() + .expect_err("a refused endpoint does not prove the pending process exited"); + + assert!(error.contains("could not be confirmed"), "{error}"); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn managed_restart_fallback_requests_a_replacement_after_stopping() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + for outcome in [ + GracefulRestartOutcome::WaitFailed("backend exited".to_string()), + GracefulRestartOutcome::RequestRejected, + ] { + let state = BackendState::default(); + let result = state.execute_graceful_restart_strategy( + RestartStrategy::ManagedWithGracefulFallback, + outcome, + ); + + assert_eq!(result, Ok(RestartAction::LaunchManagedReplacement)); + } + } + + #[test] + fn completed_graceful_restart_does_not_request_a_replacement() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + for strategy in [ + RestartStrategy::ManagedWithGracefulFallback, + RestartStrategy::UnmanagedWithGracefulProbe, + ] { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + + assert_eq!( + state + .execute_graceful_restart_strategy(strategy, GracefulRestartOutcome::Completed), + Ok(RestartAction::GracefulCompleted) + ); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 14360); + } + } + + #[test] + fn packaged_windows_restart_requests_a_replacement_after_stopping() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + let state = BackendState::default(); + assert_eq!( + state.execute_graceful_restart_strategy( + RestartStrategy::ManagedSkipGraceful, + GracefulRestartOutcome::RequestRejected, + ), + Ok(RestartAction::LaunchManagedReplacement) + ); + } + + #[test] + fn unmanaged_restart_timeout_never_authorizes_managed_fallback() { + let state = BackendState::default(); + // A timed-out unmanaged restart must be rejected without consulting the + // endpoint: a transient refusal would not prove that its process exited. let result = state.execute_graceful_restart_strategy( RestartStrategy::UnmanagedWithGracefulProbe, diff --git a/src-tauri/src/backend/restart_strategy.rs b/src-tauri/src/backend/restart_strategy.rs index 670aed03..20236e82 100644 --- a/src-tauri/src/backend/restart_strategy.rs +++ b/src-tauri/src/backend/restart_strategy.rs @@ -12,14 +12,20 @@ pub(crate) enum GracefulRestartOutcome { RequestRejected, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RestartAction { + GracefulCompleted, + LaunchManagedReplacement, +} + pub(crate) fn compute_restart_strategy( is_windows: bool, packaged_mode: bool, - has_managed_child: bool, + has_managed_backend: bool, ) -> RestartStrategy { - if is_windows && packaged_mode && has_managed_child { + if is_windows && packaged_mode && has_managed_backend { RestartStrategy::ManagedSkipGraceful - } else if has_managed_child { + } else if has_managed_backend { RestartStrategy::ManagedWithGracefulFallback } else { RestartStrategy::UnmanagedWithGracefulProbe diff --git a/src-tauri/src/bridge/commands.rs b/src-tauri/src/bridge/commands.rs index f2365c98..8f5dfeaa 100644 --- a/src-tauri/src/bridge/commands.rs +++ b/src-tauri/src/bridge/commands.rs @@ -107,23 +107,27 @@ fn short_circuit_update_install( } } -fn has_managed_backend_or_pending_stop(state: &BackendState) -> bool { - if state - .restart_stop_pid - .load(std::sync::atomic::Ordering::Acquire) - != 0 - { - return true; - } - match state.child.lock() { - Ok(guard) => guard.is_some(), - Err(_) => { - append_desktop_log( - "backend child lock poisoned while checking managed backend state; assuming no managed backend child", - ); - false - } +#[cfg(test)] +fn update_backend_state(managed: bool) -> BackendState { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve backend endpoint"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + drop(listener); + if managed { + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn managed backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("reap managed backend child"); + *state.child.lock().unwrap() = Some(child); } + state } #[cfg(test)] @@ -136,34 +140,41 @@ where InstallUpdate: FnOnce() -> Result<(), String>, RestartBackend: FnOnce() -> Result<(), String>, { + let state = update_backend_state(backend_was_stopped); run_native_update_install_with_validation( install_update, || Ok(()), restart_backend_after_failed_install, - || Ok(backend_was_stopped), + &state, + true, ) } -fn run_native_update_install_with_validation< - InstallUpdate, - ValidateInstall, - RestartBackend, - PrepareBackend, ->( +fn run_native_update_install_with_validation( install_update: InstallUpdate, validate_install: ValidateInstall, restart_backend_after_failed_install: Option, - prepare_backend: PrepareBackend, + state: &BackendState, + is_windows: bool, ) -> DesktopAppUpdateResult where InstallUpdate: FnOnce() -> Result<(), String>, ValidateInstall: FnOnce() -> Result<(), String>, RestartBackend: FnOnce() -> Result<(), String>, - PrepareBackend: FnOnce() -> Result, { - let backend_was_stopped = match prepare_backend() { - Ok(stopped) => stopped, - Err(error) => return map_update_install_error(error), + let backend_was_stopped = if is_windows { + match state.has_managed_backend() { + Ok(true) => { + if let Err(error) = state.stop_backend_before_update_install() { + return map_update_install_error(error); + } + true + } + Ok(false) => false, + Err(error) => return map_update_install_error(error), + } + } else { + false }; let failure = match install_update() { Ok(()) => validate_install() @@ -788,8 +799,14 @@ pub(crate) async fn desktop_bridge_install_app_update( let Some(_spawn_guard) = AtomicFlagGuard::try_set(&state.is_spawning) else { return map_update_install_error("Backend action already in progress."); }; - let stop_managed_backend = - cfg!(target_os = "windows") && has_managed_backend_or_pending_stop(&state); + let stop_managed_backend = if cfg!(target_os = "windows") { + match state.has_managed_backend() { + Ok(managed) => managed, + Err(error) => return map_update_install_error(error), + } + } else { + false + }; let restart_backend_after_failed_install = if stop_managed_backend { match state.resolve_launch_plan(&app_handle) { Ok(_) => {} @@ -818,13 +835,8 @@ pub(crate) async fn desktop_bridge_install_app_update( ) }, restart_backend_after_failed_install, - || { - if !stop_managed_backend { - return Ok(false); - } - state.stop_backend_before_update_install()?; - Ok(true) - }, + &state, + cfg!(target_os = "windows"), ); if result.ok { app_handle.request_restart(); @@ -989,13 +1001,8 @@ mod tests { events.borrow_mut().push("recover"); Ok(()) }), - || { - if !has_managed_backend_or_pending_stop(&state) { - return Ok(false); - } - state.stop_backend_before_update_install()?; - Ok(true) - }, + &state, + true, ); assert!( @@ -1023,8 +1030,31 @@ mod tests { } #[test] - fn run_native_update_install_prepares_before_installing_and_validating() { + fn windows_update_install_keeps_ownership_after_the_child_slot_is_cleared() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind surviving backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn previously managed backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("reap previously managed backend child"); + drop(child); + assert!(state.child.lock().unwrap().is_none()); + assert_eq!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0 + ); let events = RefCell::new(Vec::new()); + let result = run_native_update_install_with_validation( || { events.borrow_mut().push("install"); @@ -1038,13 +1068,92 @@ mod tests { events.borrow_mut().push("recover"); Ok(()) }), + &state, + true, + ); + + assert!( + !result.ok, + "a surviving endpoint of a previously managed backend must block installation" + ); + assert!(result + .reason + .as_deref() + .unwrap() + .contains("already answering")); + assert!( + events.borrow().is_empty(), + "installer and recovery must not run" + ); + } + + #[test] + fn windows_update_install_does_not_manage_an_external_only_backend() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind external backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let events = RefCell::new(Vec::new()); + + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Err("installer failed".to_string()) + }, || { - events.borrow_mut().push("prepare"); - Ok(true) + events.borrow_mut().push("validate"); + Ok(()) }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, + ); + + assert_eq!( + result, + map_update_install_error("Failed to install update: installer failed") + ); + assert_eq!(*events.borrow(), vec!["install"]); + assert!(state.last_recorded_pid().is_none()); + } + + #[test] + fn run_native_update_install_prepares_before_installing_and_validating() { + let state = update_backend_state(true); + let events = RefCell::new(Vec::new()); + let result = run_native_update_install_with_validation( + || { + assert!( + state.child.lock().unwrap().is_none(), + "the managed child must be cleared before installation" + ); + assert_eq!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0, + "the stop target must be confirmed before installation" + ); + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, ); assert!(result.ok); - assert_eq!(*events.borrow(), vec!["prepare", "install", "validate"]); + assert_eq!(*events.borrow(), vec!["install", "validate"]); } #[test] @@ -1120,6 +1229,7 @@ mod tests { #[test] fn run_native_update_install_rejects_post_install_validation_failures() { + let state = update_backend_state(true); let events = Rc::new(RefCell::new(Vec::new())); let restart_events = Rc::clone(&events); @@ -1130,7 +1240,8 @@ mod tests { restart_events.borrow_mut().push("restart"); Ok(()) }), - || Ok(true), + &state, + true, ); assert_eq!(*events.borrow(), vec!["restart"]); @@ -1143,7 +1254,7 @@ mod tests { } #[test] - fn has_managed_backend_or_pending_stop_returns_false_when_lock_is_poisoned() { + fn windows_update_install_refuses_a_poisoned_backend_ownership_lock() { let state = BackendState::default(); let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { let _guard = state @@ -1153,6 +1264,20 @@ mod tests { panic!("poison backend child lock"); })); - assert!(!has_managed_backend_or_pending_stop(&state)); + let installed = RefCell::new(false); + let result = run_native_update_install_with_validation( + || { + *installed.borrow_mut() = true; + Ok(()) + }, + || Ok(()), + None:: Result<(), String>>, + &state, + true, + ); + + assert!(!result.ok); + assert!(result.reason.as_deref().unwrap().contains("lock poisoned")); + assert!(!*installed.borrow()); } }