{
+ 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 +252,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) => {
@@ -165,3 +330,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/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 ad06dd3f..a775559c 100644
--- a/src-tauri/src/backend/restart.rs
+++ b/src-tauri/src/backend/restart.rs
@@ -7,11 +7,62 @@ 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 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
+/// 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,
+) -> Result<(), String>
+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,
+ 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 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()
+ ));
+ }
+ }
+
+ endpoint_probe()
+}
+
impl BackendState {
fn sanitize_auth_token(auth_token: Option<&str>) -> Option {
let token = auth_token?;
@@ -110,30 +161,41 @@ impl BackendState {
}
pub(crate) fn stop_backend_for_bridge(&self) -> Result<(), 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();
+ let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning)
+ .ok_or_else(|| "Backend action already in progress.".to_string())?;
+ if self.has_managed_backend()? {
+ self.stop_backend()?;
+ return self.confirm_previous_backend_exited();
}
- 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 {
- 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
@@ -143,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,
)
}
@@ -170,19 +232,11 @@ impl BackendState {
fn execute_graceful_restart_strategy(
&self,
strategy: backend::restart_strategy::RestartStrategy,
- auth_token: Option<&str>,
- previous_start_time: Option,
- packaged_mode: bool,
- ) -> 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),
- };
+ outcome: backend::restart_strategy::GracefulRestartOutcome,
+ ) -> Result {
+ use backend::restart_strategy::RestartAction;
+ // Interpret the strategy and observed API outcome before any managed fallback.
match (strategy, outcome) {
(
backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback,
@@ -193,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,
@@ -208,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,
@@ -217,16 +273,18 @@ 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,
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,
@@ -239,15 +297,68 @@ 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 recorded process identity is no longer present;
+ /// 2) the backend endpoint explicitly refuses connections.
+ ///
+ /// 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.load(Ordering::Acquire);
+ 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.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms(
+ append_desktop_log,
+ ))
+ },
+ );
+ 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}"
+ )),
+ 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.start_backend_process(app, plan)?;
self.wait_for_backend(plan)
}
@@ -259,37 +370,39 @@ 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)?;
- 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));
}
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,
- ) {
- Ok(())
- if strategy != backend::restart_strategy::RestartStrategy::ManagedSkipGraceful =>
- {
- self.verify_running_resource_identity(
+ 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)? {
+ 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 {
@@ -317,8 +430,256 @@ impl BackendState {
#[cfg(test)]
mod tests {
- use super::BackendState;
- use crate::backend::restart_strategy::RestartStrategy;
+ use std::{
+ net::TcpListener,
+ process::{Command, Stdio},
+ sync::{atomic::Ordering, Mutex},
+ };
+
+ use super::{preflight_before_respawn, BackendState};
+ use crate::{
+ backend::restart_strategy::RestartStrategy, process_control::ProcessIdentity,
+ process_control::ProcessProbe,
+ };
+
+ #[test]
+ 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()
+ };
+ drop(listener);
+ 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,
+ 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 {
+ 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() {
@@ -353,9 +714,193 @@ 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 {
+ 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),
+ },
+ || Ok(()),
+ );
+
+ let error = result.expect_err("a still-running backend must block the respawn");
+ 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"),
+ "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
+ },
+ || Ok(()),
+ );
+
+ 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),
+ },
+ || Ok(()),
+ );
+
+ 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),
+ },
+ || Ok(()),
+ );
+
+ assert!(result.is_err());
+ let elapsed = start.elapsed();
+ assert!(
+ 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]
+ 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,
+ || Err("endpoint occupied".to_string()),
+ );
+
+ let error = result.expect_err("an answering endpoint must block the respawn");
+ assert_eq!(error, "endpoint occupied");
+ }
+
+ #[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);
+ Ok(())
+ },
+ );
+
+ assert!(result.is_err());
+ assert!(
+ !endpoint_called.get(),
+ "the endpoint probe must not run once the PID gate already failed"
+ );
+ }
+
+ #[test]
+ fn preflight_for_a_first_managed_start_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"),
+ || Ok(()),
+ );
+ 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"),
+ || Err("endpoint occupied".to_string()),
+ );
+ assert!(blocked.is_err());
+ }
+
+ #[test]
+ 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/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 c81eab97..8f5dfeaa 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 {
@@ -107,16 +107,27 @@ fn short_circuit_update_install(
}
}
-fn has_managed_backend_child(state: &BackendState) -> bool {
- 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)]
@@ -129,11 +140,13 @@ 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,
- backend_was_stopped,
+ &state,
+ true,
)
}
@@ -141,13 +154,28 @@ fn run_native_update_install_with_validation,
- backend_was_stopped: bool,
+ state: &BackendState,
+ is_windows: bool,
) -> DesktopAppUpdateResult
where
InstallUpdate: FnOnce() -> Result<(), String>,
ValidateInstall: FnOnce() -> Result<(), String>,
RestartBackend: FnOnce() -> Result<(), String>,
{
+ 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()
.err()
@@ -181,6 +209,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 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)
}
@@ -766,7 +796,17 @@ pub(crate) async fn desktop_bridge_install_app_update(
AppUpdateProgress::stage("installing"),
);
let state = app_handle.state::();
- let stop_managed_backend = cfg!(target_os = "windows") && has_managed_backend_child(&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 = 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(_) => {}
@@ -784,17 +824,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(
@@ -806,7 +835,8 @@ pub(crate) async fn desktop_bridge_install_app_update(
)
},
restart_backend_after_failed_install,
- backend_was_stopped,
+ &state,
+ cfg!(target_os = "windows"),
);
if result.ok {
app_handle.request_restart();
@@ -938,6 +968,194 @@ 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(())
+ }),
+ &state,
+ 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 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");
+ Ok(())
+ },
+ || {
+ events.borrow_mut().push("validate");
+ Ok(())
+ },
+ Some(|| {
+ 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("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!["install", "validate"]);
+ }
+
#[test]
fn run_native_update_install_skips_restart_when_backend_was_not_stopped() {
let mut restart_called = false;
@@ -1011,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);
@@ -1021,6 +1240,7 @@ mod tests {
restart_events.borrow_mut().push("restart");
Ok(())
}),
+ &state,
true,
);
@@ -1034,7 +1254,7 @@ mod tests {
}
#[test]
- fn has_managed_backend_child_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
@@ -1044,6 +1264,20 @@ mod tests {
panic!("poison backend child lock");
}));
- assert!(!has_managed_backend_child(&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());
}
}
diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs
index 43149372..e7742f24 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,232 @@ 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, proc_root: &std::path::Path) -> ProcessProbe {
+ use std::fs;
+
+ if pid == 0 {
+ return ProcessProbe::Missing;
+ }
+
+ 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")) {
+ 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(')')
+ .and_then(|(_, 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.
+ // Signal 0 performs the permission and existence checks without delivering a signal.
+ let output = std::process::Command::new("kill")
+ .args(["-0", &pid.to_string()])
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .stdin(Stdio::null())
+ .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,
+ }
+}
+
+/// 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, std::path::Path::new("/proc"))
+ }
+}
+
+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 +705,199 @@ 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);
+ }
+
+ #[test]
+ #[cfg(not(target_os = "windows"))]
+ fn signal_probe_reports_a_missing_pid_as_exited() {
+ // 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);
+ }
+
+ #[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 }
+ );
+ }
}