Repository navigation
fix(backend): confirm the previous backend exited before respawning on restart - #191
Conversation
…m-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.
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src-tauri/src/process_control.rs" line_range="365" />
<code_context>
+ .status();
+ match result {
+ Ok(status) if status.success() => Ok(()),
+ _ => Err(()),
+ }
+}
</code_context>
<issue_to_address>
**Live backend can be duplicated**
When the non-procfs fallback runs and `kill -0` fails because the PID is inaccessible or the command cannot run, `unsafe_libc_kill_zero` treats every failure as `Missing`, and `probe_pid_with_signal` lets the PID gate accept that as proof of exit. The endpoint check can then pass while the old process is still running, so the restart spawns a replacement beside it.
Distinguish a missing PID from permission and command-execution failures, and do not treat those failures as proof that the process exited.
Also at `src-tauri/src/process_control.rs:350`.
</issue_to_address>
### Comment 2
<location path="src-tauri/src/backend/restart.rs" line_range="360" />
<code_context>
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)
</code_context>
<issue_to_address>
**Update recovery bypasses exit checks**
When a Windows update install fails after the stop reports success but the old backend is still running or answering, the failed-update recovery closure calls `start_backend_process` directly, bypassing `confirm_previous_backend_exited`. If the backend still serves the endpoint after the update stop reports success, recovery spawns a replacement anyway.
Apply the same PID and endpoint preflight to the failed-update recovery path before it starts the backend.
</issue_to_address>
### Comment 3
<location path="src-tauri/src/backend/restart.rs" line_range="44" />
<code_context>
+ P: Fn(u32) -> process_control::ProcessProbe,
+ E: FnOnce() -> bool,
+{
+ if stopped_pid != 0 {
+ let identity = identity.unwrap_or(process_control::ProcessIdentity {
+ pid: stopped_pid,
</code_context>
<issue_to_address>
**Untracked backend can be duplicated**
When the restart has no recorded PID and an unmanaged backend is temporarily not accepting connections, or has not yet bound its endpoint, `preflight_before_respawn` skips the PID wait and relies on one endpoint probe, which passes during that gap. `start_backend_process` then starts a replacement alongside the unmanaged backend when it resumes or binds.
Do not approve a restart based on a single endpoint probe when no tracked PID is available; confirm the endpoint remains unavailable over the restart confirmation window.
Also at `src-tauri/src/backend/restart.rs:63-64`.
</issue_to_address>
### Comment 4
<location path="src-tauri/src/backend/restart.rs" line_range="360" />
<code_context>
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)
</code_context>
<issue_to_address>
**Two backends serve the endpoint**
When another backend binds the endpoint after the probe succeeds but before the replacement starts, `confirm_previous_backend_exited` closes its probe before `start_backend_process` runs, leaving a gap for another backend to bind. The replacement then starts too, and both backends serve the endpoint.
Make checking and starting the replacement atomic against competing starters, for example by reserving the endpoint through startup.
Also at `src-tauri/src/backend/restart.rs:63-65`.
</issue_to_address>
### Comment 5
<location path="src-tauri/src/backend/restart.rs" line_range="310" />
<code_context>
+ .tracked_child_pid()
+ .or_else(|| self.last_recorded_pid())
+ .unwrap_or(0);
+ self.restart_stop_pid.store(pid, Ordering::Release);
self.stop_backend()
}
</code_context>
<issue_to_address>
**A concurrent start bypasses preflight**
When a readiness request runs after the old endpoint stops answering but before the restart flow sets `is_spawning`, `ensure_backend_ready` can observe the endpoint as down during this stop/confirmation window while `is_spawning` is still false, then start a backend before `launch_backend_after_restart` begins its guarded preflight. The restart can consequently fail its endpoint check after another action has already spawned a replacement, leaving the restart caller with an error and backend startup in progress outside its flow.
Acquire a shared backend-action guard before stopping and confirming, and make readiness startup honor it until the restart completes or fails.
</issue_to_address>
### Comment 6
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="77" />
<code_context>
+ // 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();
</code_context>
<issue_to_address>
**Stale stop reports success**
When the tracked child has exited but a descendant or other process continues serving the backend endpoint, and `stop_backend()` is called outside the restart flow, `stop_backend()` returns `Ok(())` without checking the endpoint or otherwise confirming shutdown, so callers outside the restart preflight—including the bridge stop path—are told the backend stopped even when a descendant or replacement process still serves it.
For non-restart stop callers, verify the endpoint is no longer serving before returning success, or return an error when shutdown cannot be confirmed.
</issue_to_address>
### Comment 7
<location path="src-tauri/src/backend/launch.rs" line_range="538" />
<code_context>
.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);
</code_context>
<issue_to_address>
**Early exit can capture a recycled PID**
When the newly spawned backend exits quickly and its PID is reused before `record_spawned_identity` probes it, `record_spawned_identity` probes the PID after `Command::spawn` returns and after the child is stored, so the child can exit and the OS can reuse its PID before the probe. The replacement process's creation stamp is then recorded as the backend's identity; the restart preflight later sees that same process and waits out the timeout, refusing a valid restart.
Capture the creation stamp from the spawned process handle, or record an observed early exit so a later process reusing that PID cannot be mistaken for the backend.
</issue_to_address>Sourcery assessment
Approval pending. 7 findings to address first.
Blocking findings: src-tauri/src/process_control.rs:365, src-tauri/src/backend/restart.rs:360, src-tauri/src/backend/restart.rs:44, src-tauri/src/backend/restart.rs:360, src-tauri/src/backend/restart.rs:310, and 2 more
chars().next() returns Option<char>, so mapping over rsplit_once produced Option<Option<char>> 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.
…it 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.
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.
|
Thanks. Two of the seven are real defects and are fixed; the other five are windows this PR Fixed
Failed-update recovery (restart.rs:360, commands.rs:184) — fixed in 2947432. The recovery Not fixed, deliberatelyEndpoint/start TOCTOU (restart.rs:360). Closing it means holding the listening socket Single endpoint probe when no PID is tracked (restart.rs:44). An unmanaged backend (one the Concurrent readiness start during the stop window (restart.rs:310). Non-restart stop callers (process_lifecycle.rs:77).
|
Windows-side verification for 2947432No code change in this round; the diff is unchanged. This is evidence CI cannot produce: Same commands, run on a Windows host at
Host: rustc 1.98.0 (88d9e12ae 2026-08-18), The Windows code path compiles, and the two tests that exercise the real probe rather than the injectable one ( I also re-checked the unstable-API question in the review thread about |
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 11 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="64-68" />
<code_context>
+ 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)
+ }
+ }
</code_context>
<issue_to_address>
**Unrelated process gets terminated**
When `Child::try_wait()` returns an error after the original process exits and its PID is reused, `stop_backend_with_timeout` continues into `stop_child_process_gracefully` with the same PID, and the Windows stop path can issue `taskkill` against the unrelated process now using it.
Abort PID-based termination when `try_wait()` errors instead of passing that PID to the graceful-stop path.
</issue_to_address>
### Comment 2
<location path="src-tauri/src/backend/restart.rs" line_range="360" />
<code_context>
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)
</code_context>
<issue_to_address>
**Concurrent respawns duplicate backends**
When restart and failed-install recovery overlap and both reach their respawn paths, a restart and failed-update recovery can both pass this check before either stores a child; `start_backend_process` checks the child slot before spawning but does not hold that lock across the spawn, so both callers start a backend and the callers see competing servers.
Use one exclusive respawn reservation across every caller, held through the child-slot check and process spawn.
Also at `src-tauri/src/bridge/commands.rs:186`.
</issue_to_address>
### Comment 3
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="58" />
<code_context>
+ // 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();
</code_context>
<issue_to_address>
**Recovery skips the PID gate**
When failed-install recovery runs after the tracked child has already been removed from the child slot, and the old backend is still alive but not answering at the endpoint probe, the failed-install recovery calls `confirm_previous_backend_exited` after `stop_backend` returns, but this early return leaves `restart_stop_pid` unset when the child slot is already empty. The confirmation then checks only the endpoint, so a previously spawned backend that is still alive but not yet answering can be missed and a replacement can be spawned beside it.
Before the early return for an empty child slot, preserve the last recorded PID as the stop target when appropriate, or have failed-install recovery capture and set it before calling `stop_backend`.
Also at `src-tauri/src/bridge/commands.rs:186`.
</issue_to_address>
### Comment 4
<location path="src-tauri/src/backend/restart.rs" line_range="338" />
<code_context>
+ 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,
+ ))
</code_context>
<issue_to_address>
**Live backend mistaken for free endpoint**
When DNS resolution or a TCP probe fails while an unmanaged backend still holds the endpoint, `ping_backend` returns `false` for probe errors as well as an unused endpoint, so the negated endpoint probe treats an inconclusive result as proof the endpoint is free and preflight permits a replacement beside the running backend.
Make the endpoint probe distinguish an unused endpoint from resolution or connection errors, and do not allow respawn on an inconclusive result.
Also at `src-tauri/src/backend/restart.rs:337`.
</issue_to_address>
### Comment 5
<location path="src-tauri/src/process_control.rs" line_range="311-315" />
<code_context>
+ 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)
</code_context>
<issue_to_address>
**Live process mistaken for exited**
When metadata access to `/proc/<pid>` is denied while `/proc/self` remains accessible, `probe_pid_unix` uses `Path::exists()`, which also returns false for metadata errors, and classifies the tracked process as `Missing`; the PID gate then allows a replacement while the old process is still running.
Distinguish a genuinely missing proc entry from metadata errors and do not classify an inaccessible entry as a missing process.
</issue_to_address>
### Comment 6
<location path="src-tauri/src/backend/restart.rs" line_range="44" />
<code_context>
+ P: Fn(u32) -> process_control::ProcessProbe,
+ E: FnOnce() -> bool,
+{
+ if stopped_pid != 0 {
+ let identity = identity.unwrap_or(process_control::ProcessIdentity {
+ pid: stopped_pid,
</code_context>
<issue_to_address>
**Unmanaged backend duplicated during restart**
When `stopped_pid` is zero and an unmanaged backend is temporarily unreachable or has not yet begun listening at the endpoint probe, `preflight_before_respawn` skips the PID wait and accepts one failed endpoint probe, then spawns a replacement while the unmanaged backend is still restarting or starting and can come up alongside it.
Retry endpoint checks over the unmanaged restart or startup window before allowing respawn.
</issue_to_address>
### Comment 7
<location path="src-tauri/src/backend/restart.rs" line_range="329" />
<code_context>
+ /// 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 identity = self.spawned_identity_for(stopped_pid);
+ let result = preflight_before_respawn(
</code_context>
<issue_to_address>
**Retry skips PID confirmation**
When a failed-install recovery times out while the old PID remains alive, then an update is retried before that backend begins answering on its endpoint, `confirm_previous_backend_exited` clears `restart_stop_pid` before checking the PID, so a timeout leaves no target for a later confirmation. After failed-install recovery has dropped the child handle, a subsequent update attempt can skip the managed-child recovery path and rely only on the endpoint probe; if the old backend is still alive but not yet listening, the replacement starts alongside it.
Keep the stopped PID available after a failed PID gate, and ensure recovery retries still run the PID confirmation even when the child handle has already been cleared.
</issue_to_address>
### Comment 8
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="76-77" />
<code_context>
+ append_desktop_log(&format!(
+ "backend process already exited before stop, drop stale handle: pid={pid}, status={status}"
+ ));
+ *guard = None;
return Ok(());
+ }
+
</code_context>
<issue_to_address>
**Stop reports success while backend answers**
When a stale tracked child exists while another backend or surviving process still answers on `backend_url`, `stop_backend_with_timeout` returns `Ok(())` immediately after dropping the stale child, without checking the endpoint. `stop_backend_for_bridge` has already taken its managed-child branch, so it skips its unmanaged-backend ping and the caller sees a successful stop while a backend still answers.
After dropping a stale child, have the bridge stop path check the endpoint and return the existing unmanaged-backend error when it still answers.
</issue_to_address>
### Comment 9
<location path="src-tauri/src/backend/restart.rs" line_range="63-65" />
<code_context>
+ }
+ }
+
+ if !endpoint_probe() {
+ return Err(backend_endpoint_conflict_error(backend_url));
+ }
+
+ Ok(())
</code_context>
<issue_to_address>
**Endpoint can become occupied before spawn**
When an unmanaged backend starts serving `backend_url` between the endpoint probe and the replacement’s bind, a separate backend can start listening after `endpoint_probe()` reports the endpoint free but before `start_backend_process()` binds it. The preflight then passes and the replacement starts alongside that backend, so the restart can still create the conflict it is intended to prevent.
Where feasible, serialize managed backend starts and make the replacement’s bind fail closed if the endpoint was claimed after preflight.
</issue_to_address>
### Comment 10
<location path="src-tauri/src/backend/restart.rs" line_range="338-341" />
<code_context>
+ 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,
+ );
</code_context>
<issue_to_address>
**Restart preflight blocks on DNS**
When the configured backend URL uses a hostname and name resolution stalls or resolves to multiple unreachable addresses, `confirm_previous_backend_exited` calls `ping_backend` synchronously; DNS resolution has no timeout, and the connect timeout applies separately to each resolved address, so the restart preflight can block well beyond the configured timeout instead of returning the error promptly.
Bound hostname resolution and the total endpoint probe duration by the configured timeout.
</issue_to_address>
### Comment 11
<location path="src-tauri/src/process_control.rs" line_range="356" />
<code_context>
+ .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();
</code_context>
<issue_to_address>
**PID reuse blocks macOS restarts**
When a restart runs on macOS or another non-procfs platform and the exited backend's PID is reused before the probe observes it as missing, on platforms without `/proc`, `probe_pid_with_signal` reports a live PID without a creation timestamp, and `probe_matches_identity` treats a live PID with a missing stamp as the original process. If the backend exits and its PID is quickly reused, the wait reports `StillRunning` until timeout and the restart is refused even though the backend exited.
Use a platform-specific process creation identity where available, or clearly surface this ambiguous-PID timeout as a retryable condition rather than asserting the old backend is still running.
Also at `src-tauri/src/process_control.rs:394-395`.
</issue_to_address>Sourcery assessment
Approval pending. 11 findings to address first.
Blocking findings: src-tauri/src/backend/process_lifecycle.rs:68, src-tauri/src/backend/restart.rs:360, src-tauri/src/backend/process_lifecycle.rs:58, src-tauri/src/backend/restart.rs:338, src-tauri/src/process_control.rs:315, and 6 more
zouyonghe
left a comment
There was a problem hiding this comment.
Follow-up for the review on 54ad648, implemented in 19ca27c and 4d3a6c5 on this PR's original branch.
Changes
- Comments 2 and the managed portion of 9: restart, bridge stop, and update installation/recovery now reserve the existing
is_spawningflag atomically for the full operation. Startup readiness already uses the same reservation. The final child-slot check,Command::spawn, identity record, and child storage are also protected by one child mutex critical section. The non-exclusive guard setter was removed. - Comments 3 and 7: empty/stale-child stop paths retain the recorded stop target. Confirmation no longer consumes it up front; it clears the target only after both gates succeed. A failed endpoint confirmation and a subsequent successful retry are covered using a real exited child and TCP listener. This hardens the state handling; it does not claim that the original report's same-PID-still-alive/empty-child scenario was reproduced.
- Comments 4 and 10: restart and bridge-stop confirmation now use a dedicated
Resultendpoint probe. Invalid URLs, DNS failures, empty results, timeouts, and other inconclusive connection errors block the operation. Only explicit connection refusal on every resolved address authorizes a replacement. Numeric IPv4/IPv6 avoid DNS; hostname resolution and all connects share one deadline. The existing readiness/HTTP ping behavior is unchanged. - Comment 5: procfs metadata checks distinguish
NotFoundfrom inaccessible/failed metadata. Errors inspecting either the PID entry or procfs availability remainUnknown, rather than authorizing a replacement. Real filesystem-error fixtures cover both branches and the signal fallback. - Comment 8: bridge stop checks endpoint availability after dropping a stale tracked child, instead of immediately reporting success. A real completed child plus an active listener reproduces the old behavior and verifies rejection after the fix. An inconclusive endpoint probe also cannot report a successful stop.
- Comment 11: the conservative no-timestamp identity policy remains. Timeout messages now describe an unconfirmed exit and explicitly suggest retrying, rather than asserting that the old backend is definitely still running. They do not advise killing an unverified recycled PID.
Findings not represented as reproduced defects
- Comment 1: continuing after
try_waiterrors is a source property, but the claimed Windows PID-reuse/foreign-process termination scenario was not reproduced. A valid Rust WindowsChildretains its process handle. Windows documents that a process identifier can be reused only after all handles are closed and the process object is freed: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information . No claim is made that this alleged termination path was fixed or reproduced. - Comment 6: a normal unmanaged restart returns after the graceful strategy; it does not fall through to the managed respawn path described in the comment. Repeating endpoint snapshots cannot prove that an unknown external process is absent during cold start.
- Comment 9, external-process portion: managed starts are serialized here, but an independent process can still claim the endpoint after a probe. Closing that window requires exclusive binding/ownership at the backend itself. This Rust-side preflight does not reserve the Python backend's listening socket.
Validation
- The new regressions were observed failing before their corresponding fixes: metadata errors, invalid endpoint authorization, unbounded resolver wait, stale-child bridge-stop success, busy-action stop, and lost pending PID.
- macOS / rustc 1.93.1:
cargo test --manifest-path src-tauri/Cargo.toml --locked --bin astrbot-desktop-tauri -- --nocapture— 246 passed, 0 failed. cargo fmt --manifest-path src-tauri/Cargo.toml --all -- --check— passed.cargo clippy --manifest-path src-tauri/Cargo.toml --locked --all-targets -- -D warnings— passed.cargo check --manifest-path src-tauri/Cargo.toml --lockedandgit diff --check— passed.
The caller's DNS wait is bounded; the standard-library OS resolver cannot be cancelled, so a timed-out resolver worker can outlive that call until the OS returns. There are no new dependencies. Native Windows packaged-runtime restart/update and a complete concurrent-spawn end-to-end test were not run, and the checks above are not presented as evidence for those scenarios.
Current-head GitHub validation (4d3a6c5): all four checks passed. The Linux Rust job ran 248 tests, all passed: https://github.com/AstrBotDevs/AstrBot-desktop/actions/runs/43609917241 . The PR remains open; no merge was performed.
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 7 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src-tauri/src/backend/restart.rs" line_range="352-353" />
<code_context>
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)
}
</code_context>
<issue_to_address>
**Replacement survives shell shutdown**
When exit cleanup runs after the child slot is cleared but before the restart task finishes confirmation and spawning, `stop_backend_for_exit` sees an empty child slot and requests shell exit while the restart task continues to `start_backend_process`, leaving the replacement running without its shell.
Coordinate exit cleanup with restart confirmation and spawning so cleanup either cancels the restart or waits for it and stops any replacement.
Also at `src-tauri/src/backend/process_lifecycle.rs:100-101`.
</issue_to_address>
### Comment 2
<location path="src-tauri/src/backend/restart.rs" line_range="352-353" />
<code_context>
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)
}
</code_context>
<issue_to_address>
**Two backends serve the endpoint**
When another backend binds the URL after the refusal probe but before the replacement binds, `confirm_previous_backend_exited` does not reserve the endpoint, so its probe passes and `start_backend_process` starts the replacement alongside the other backend.
Make endpoint availability checking and replacement startup prevent another backend from claiming the endpoint between them.
Also at `src-tauri/src/backend/http.rs:94`.
</issue_to_address>
### Comment 3
<location path="src-tauri/src/backend/http.rs" line_range="53" />
<code_context>
+ // 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));
+ })
</code_context>
<issue_to_address>
**Resolver threads accumulate**
When hostname resolution remains blocked past the probe timeout and callers retry, `recv_timeout` stops waiting but does not stop the detached thread blocked in `resolve`; each retry starts another thread, eventually consuming process thread resources.
Bound or cancel resolver work, or otherwise limit and reuse resolver workers so timed-out probes do not leave an unbounded number of threads behind.
</issue_to_address>
### Comment 4
<location path="src-tauri/src/process_control.rs" line_range="343-346" />
<code_context>
+ return ProcessProbe::Missing;
+ }
+
+ let created_at = stat
+ .rsplit_once(')')
+ .and_then(|(_, trailer)| trailer.split_whitespace().nth(19))
+ .and_then(|value| value.parse::<u64>().ok());
+
+ ProcessProbe::Alive { created_at }
</code_context>
<issue_to_address>
**Recycled PID blocks restart**
When a PID is reused quickly enough that both processes receive the same `/proc` start-time tick, the `/proc/<pid>/stat` start time is recorded in clock ticks, so an unrelated process reusing the PID within the same tick can have the same stamp; the identity check then treats it as the old backend, waits until timeout, and rejects the restart.
Use a process-creation identity with finer resolution, or treat the Linux tick value as potentially ambiguous and avoid waiting on it as definitive identity evidence.
Also at `src-tauri/src/process_control.rs:399`.
</issue_to_address>
### Comment 5
<location path="src-tauri/src/backend/http.rs" line_range="29" />
<code_context>
+{
+ let inconclusive = |reason: &str| {
+ format!(
+ "Cannot confirm backend endpoint {backend_url} is available: {reason}. Refusing to start another backend."
+ )
+ };
</code_context>
<issue_to_address>
**Backend URL credentials leak**
When a user or launcher configures `ASTRBOT_BACKEND_URL` with credentials in its userinfo and restart preflight fails, the error strings include the full `backend_url`, and `confirm_previous_backend_exited` writes failures to the restart log and returns them to the caller. Credentials embedded in the URL are therefore exposed in logs and bridge error responses.
Redact username and password from the URL before including it in errors or logs.
Also at `src-tauri/src/backend/http.rs:82`, `src-tauri/src/backend/restart.rs:342`.
</issue_to_address>
### Comment 6
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="27-31" />
<code_context>
+ .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) => {
</code_context>
<issue_to_address>
**Stop confirmation failures miss restart logs**
When the stop request returns success but the OS probe still sees the recorded process, `confirm_process_identity_exit` returns an error without logging it, and the restart path propagates that stop error before reaching `confirm_previous_backend_exited`, where preflight failures are logged. The restart log therefore omits this exit-confirmation failure even though the caller receives an error.
Log the exit-confirmation error to the restart log before returning it.
</issue_to_address>
### Comment 7
<location path="src-tauri/src/backend/http.rs" line_range="559" />
<code_context>
+
+ 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:?}"
+ );
</code_context>
<issue_to_address>
**Timeout regressions pass these tests**
When the timeout implementation starts exceeding its configured deadline, a regression that waits 900 ms for the DNS probe still satisfies `restart_endpoint_probe_bounds_hostname_resolution_by_the_total_deadline`’s `< 1s` assertion at `ib`, despite its 100 ms timeout. `preflight_reports_a_timeout_when_the_old_pid_never_leaves` only asserts `elapsed >= 60ms` at `ok`, so an arbitrarily late timeout also passes; neither test catches an excessive wait.
Assert a reasonable upper bound as well as the lower bound, allowing only a small scheduling tolerance.
Also at `src-tauri/src/backend/restart.rs:653`.
</issue_to_address>Sourcery assessment
Approval pending. 6 findings to address first.
Blocking findings: src-tauri/src/backend/restart.rs:353, src-tauri/src/backend/restart.rs:353, src-tauri/src/backend/http.rs:53, src-tauri/src/process_control.rs:346, src-tauri/src/backend/http.rs:29, and 1 more
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.
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="91" />
<code_context>
}
+ let Some(child_pid) = self.spawn_backend_command(&mut command, plan)? else {
+ return Ok(());
+ };
+ if let Some(log_path) = backend_log_path {
</code_context>
<issue_to_address>
**Updates start duplicate backends**
When a managed child handle is stale during a successful Windows update while another process still owns the backend endpoint, `stop_backend()` clears the stale handle and returns success, so the update skips `confirm_previous_backend_exited`; after restart, `ensure_backend_ready()` can spawn another backend before the surviving listener answers its HTTP ping, leaving both processes running and risking resources used by the survivor.
Confirm the backend endpoint is no longer served before proceeding with the update and before readiness can spawn a replacement.
Also at `src-tauri/src/bridge/commands.rs:772`.
</issue_to_address>
### Comment 2
<location path="src-tauri/src/backend/launch.rs" line_range="640" />
<code_context>
+ .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());
</code_context>
<issue_to_address>
**Concurrent exit still spawns child**
When the spawn path checks the quitting flag without holding the child-slot lock through the spawn, `spawn_backend_command_coordinates_with_exit_cleanup` exercises spawn-then-exit and exit-then-spawn serially at lines 640–653, so a regression that checks `is_quitting()` outside the child-slot lock still passes. During a concurrent exit, quitting can begin between that check and the spawn, leaving a replacement child running.
Add a barrier-controlled concurrency test that races exit cleanup with spawn and verifies no child can be left running.
</issue_to_address>
### Comment 3
<location path="src-tauri/src/backend/restart.rs" line_range="42" />
<code_context>
+ P: Fn(u32) -> process_control::ProcessProbe,
+ E: FnOnce() -> Result<(), String>,
+{
+ if stopped_pid != 0 {
+ let identity = identity.unwrap_or(process_control::ProcessIdentity {
+ pid: stopped_pid,
</code_context>
<issue_to_address>
**Untracked backend can be duplicated**
When an unmanaged backend’s accepted graceful restart times out while the old process is between listeners, `preflight_before_respawn` skips the PID check when `stopped_pid` is zero and treats a refused endpoint connection as sufficient to launch a replacement. The old unmanaged backend can still be restarting and bind the port after the replacement starts.
When no stopped PID is available, do not use a transient refused connection alone to authorize a fallback spawn; fail safely or require evidence that the old backend restart has finished.
Also at `src-tauri/src/backend/restart.rs:296`.
</issue_to_address>
### Comment 4
<location path="src-tauri/src/backend/http.rs" line_range="104-106" />
<code_context>
+ .ok_or_else(|| inconclusive("probe timed out"))?;
+ match TcpStream::connect_timeout(&address, remaining) {
+ Ok(_) => {
+ return Err(format!(
+ "Backend endpoint {display_url} is already answering. Stop the existing backend before starting another."
+ ));
+ }
+ Err(error) if error.kind() == ErrorKind::ConnectionRefused => {}
</code_context>
<issue_to_address>
**Configured remote backend blocks restarts**
When `ASTRBOT_BACKEND_URL` points to a reachable non-local backend while this shell is restarting its managed backend, `confirm_backend_endpoint_available_with_resolver` treats any successful TCP connection as the old backend still answering, so a reachable server at the configured URL blocks the replacement even after the managed process exits.
Restrict the endpoint conflict check to addresses the managed backend is expected to serve, or skip it for configured remote endpoints.
</issue_to_address>Sourcery assessment
Approval pending. 4 findings to address first.
Blocking findings: src-tauri/src/backend/process_lifecycle.rs:91, src-tauri/src/backend/launch.rs:640, src-tauri/src/backend/restart.rs:42, src-tauri/src/backend/http.rs:106
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.
|
@sourcery-ai review |
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src-tauri/src/bridge/commands.rs" line_range="111" />
<code_context>
-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)
</code_context>
<issue_to_address>
**Updates skip a live backend**
When the log rotator clears the child slot while a backend remains alive and no stop PID is pending, `has_managed_backend_or_pending_stop` returns false, so the update flow skips `stop_backend_before_update_install` and runs the installer without checking the endpoint or recorded process identity; the live backend goes undetected during installation.
Make update preparation check the endpoint or recorded process identity even when neither a child nor a stop PID is recorded.
Also at `src-tauri/src/backend/process_lifecycle.rs:275`, `src-tauri/src/bridge/commands.rs:116`.
</issue_to_address>
### Comment 2
<location path="src-tauri/src/backend/launch.rs" line_range="417" />
<code_context>
+ // 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() {
</code_context>
<issue_to_address>
**Two backends claim the endpoint**
When another backend claims the configured endpoint after the preflight succeeds but before `command.spawn()`, `start_backend_process` continues through launch preparation, and the final child-slot check only checks for a child tracked by this shell, so it starts the managed backend alongside the other backend; both can serve the same port.
Recheck that the endpoint is still available immediately before spawning the replacement.
Also at `src-tauri/src/backend/launch.rs:576`.
</issue_to_address>
### Comment 3
<location path="src-tauri/src/backend/process_lifecycle.rs" line_range="275" />
<code_context>
+ append_desktop_log(&format!(
+ "backend process already exited before stop, drop stale handle: pid={pid}, status={status}"
+ ));
+ *guard = None;
return Ok(());
+ }
</code_context>
<issue_to_address>
**Restart loses an exited managed backend**
When the log rotator observes a managed backend exit before a restart request and the backend endpoint is unavailable, `child_matches_pid_and_alive` clears the child slot, and `restart_strategy` uses that slot alone to decide whether the backend is managed despite the saved spawn identity. `restart_backend` treats the failed graceful probe as an unmanaged-backend error and returns without launching a replacement.
Use the saved spawn identity to preserve managed-backend classification after the child slot is cleared.
Also at `src-tauri/src/backend/restart.rs:266-270`.
</issue_to_address>
### Comment 4
<location path="src-tauri/src/backend/restart.rs" line_range="119-130" />
<code_context>
.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,
- )) {
</code_context>
<issue_to_address>
**Bridge retries skip pending PID**
When a stop attempt clears the child slot but times out confirming its PID, and a bridge-stop retry occurs while that process is still alive but not accepting TCP connections, `stop_backend_for_bridge` skips `stop_backend()` when the child slot is empty and checks only the endpoint. After an earlier stop cleared the child but failed PID confirmation, a retry therefore reports success if the backend temporarily refuses connections, even though `restart_stop_pid` still identifies a process that has not exited.
When a stop PID is pending, make the bridge path confirm that process identity exited before treating endpoint refusal as a successful stop.
</issue_to_address>
### Comment 5
<location path="src-tauri/src/bridge/commands.rs" line_range="979" />
<code_context>
-
let expected_version = update.version.clone();
let validation_app_handle = app_handle.clone();
let result = run_native_update_install_with_validation(
</code_context>
<issue_to_address>
**Update gate bypasses command**
When the production update caller stops invoking the preparation check, `windows_update_install_does_not_proceed_while_an_untracked_endpoint_answers` passes because its test-supplied closure manually calls `stop_backend_before_update_install`; it never exercises `desktop_bridge_install_app_update`. If that production caller skips the stop check, this test still passes, so an unsafe update can proceed unnoticed.
Exercise the production caller’s preparation wiring rather than reproducing it in the test closure.
</issue_to_address>Sourcery assessment
Approval pending. 5 findings to address first.
Blocking findings: src-tauri/src/bridge/commands.rs:111, src-tauri/src/backend/launch.rs:417, src-tauri/src/backend/process_lifecycle.rs:275, src-tauri/src/backend/restart.rs:130, src-tauri/src/bridge/commands.rs:979
Problem
A reaped or absent
Childhandle does not prove that the configured backend endpoint is unused. Previously, restart and failed-update recovery could treat a successful stop as sufficient to launch a replacement without independently checking the recorded process and listener.Reaping also cleared the only input used to classify a backend as desktop-managed. That could turn a previously managed backend into the unmanaged restart strategy, preventing recovery after it exited. Separately, the managed graceful-fallback result was indistinguishable from graceful completion, so the non-Windows fallback could stop successfully and return without launching its replacement.
Changes
Validation
aarch64-apple-darwin: 271 unit tests passed.cargo fmt --all -- --check, locked strict Clippy for all targets, lockedcargo check, andgit diff --checkpassed.2f3fd856a41896dc490f463eab6c164e1e55859e: all four GitHub checks passed. The Ubuntu Rust job ran 272 tests with zero failures, in addition to rustfmt, strict Clippy, and cargo check.Limits
The endpoint probe observes availability; it cannot reserve the Python listener. An independent process can still claim the address after a successful probe. Adding another probe would only narrow that window. This PR does not claim atomic ownership of an externally shared socket.
Missing creation timestamps and inconclusive probes deliberately refuse replacement rather than assume exit. A continuously listening reverse proxy or an independently configured remote endpoint can also block managed replacement; URL locality alone is not ownership evidence. Use
ASTRBOT_BACKEND_AUTO_START=0for an independently managed backend.Native Windows installer execution, packaged GUI restart, and the production double-backend scenario have not been reproduced end to end in this verification. The dedicated Windows system-session shutdown path is unchanged.