Skip to main content

ant_core/node/daemon/
supervisor.rs

1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use tokio::sync::{broadcast, RwLock};
7use tokio::time::MissedTickBehavior;
8use tokio_util::sync::CancellationToken;
9
10use crate::error::{Error, Result};
11use crate::node::binary::extract_version;
12use crate::node::daemon::disk;
13use crate::node::daemon::health::{DiskThresholds, FleetHealth};
14use crate::node::events::NodeEvent;
15use crate::node::process::spawn::spawn_node;
16use crate::node::registry::NodeRegistry;
17use crate::node::types::{
18    EvictionRecord, NodeConfig, NodeStarted, NodeStatus, NodeStopFailed, NodeStopped,
19    StopNodeResult,
20};
21
22/// Exit code ant-node uses to ask its service manager (this daemon) to restart it after replacing
23/// its own binary in place during an auto-upgrade. On Unix ant-node exits `0`; on Windows it exits
24/// with this code. Mirrors `RESTART_EXIT_CODE` in ant-node's `upgrade::apply`. Kept as a local const
25/// so this crate need not depend on that symbol.
26const RESTART_EXIT_CODE: i32 = 100;
27
28/// How often the low-disk monitor checks free space at node data directories and evicts a node if a
29/// partition has fallen to its eviction threshold.
30pub const EVICTION_POLL_INTERVAL: Duration = Duration::from_secs(30);
31
32/// Safety bound on how many nodes the monitor will evict within a single check, so a misconfigured
33/// threshold or a measurement glitch can never wipe a whole fleet in one tick.
34const MAX_EVICTIONS_PER_CYCLE: usize = 4;
35
36/// How often the liveness poll verifies that each Running node's OS process still exists.
37///
38/// Nodes the current daemon spawned are watched via their owned `Child` handle in
39/// `monitor_node`, so this poll exists purely to catch exits of nodes adopted across
40/// a daemon restart (whose `Child` handle died with the previous daemon). Five seconds
41/// is a rough trade-off: long enough that the syscall cost is negligible, short enough
42/// that a crashed adopted node still looks broken to the user within a few heartbeats.
43pub const LIVENESS_POLL_INTERVAL: Duration = Duration::from_secs(5);
44
45/// Path of the pid file a running node writes to so a future daemon instance can
46/// adopt it across restarts. Lives alongside the node's other on-disk state.
47fn node_pid_file(data_dir: &Path) -> PathBuf {
48    data_dir.join("node.pid")
49}
50
51/// Persist the running node's PID to `<data_dir>/node.pid`. Best-effort: a failure
52/// here only costs us the ability to adopt the node after a daemon restart, so we
53/// warn and continue rather than aborting the start.
54fn write_node_pid(data_dir: &Path, pid: u32) {
55    let path = node_pid_file(data_dir);
56    if let Err(e) = std::fs::write(&path, pid.to_string()) {
57        tracing::warn!(
58            "Failed to write node pid file at {}: {e}. Node will still run, but a future \
59             daemon restart will not be able to adopt it.",
60            path.display()
61        );
62    }
63}
64
65/// Remove the pid file. Called on every terminal-exit path in `monitor_node` so the
66/// next daemon doesn't try to adopt a PID belonging to a process that's gone.
67fn remove_node_pid(data_dir: &Path) {
68    let _ = std::fs::remove_file(node_pid_file(data_dir));
69}
70
71/// Read the pid file without validating liveness. Returns `None` if the file is
72/// missing or its contents can't be parsed as a u32.
73fn read_node_pid(data_dir: &Path) -> Option<u32> {
74    std::fs::read_to_string(node_pid_file(data_dir))
75        .ok()
76        .and_then(|s| s.trim().parse().ok())
77}
78
79/// Scan the OS process table for a running node that matches `config`, as a
80/// fallback for when `<data_dir>/node.pid` is missing or stale.
81///
82/// Nodes spawned by a pre-adoption daemon never had a pid file written, so
83/// without this scan the first restart after installing the adoption fix
84/// would leave every previously-running node classified as Stopped. The scan
85/// matches on:
86///
87/// - executable path identical to `config.binary_path`, AND
88/// - command line containing `--root-dir` (as a standalone arg or
89///   `--root-dir=<path>`) whose value resolves to `config.data_dir`.
90///
91/// The double match keeps us safe when multiple nodes share the same binary
92/// on disk (common on installs where one copy services several data dirs).
93///
94/// Returns `None` if no running process matches.
95fn find_running_node_process(sys: &sysinfo::System, config: &NodeConfig) -> Option<u32> {
96    let target_data_dir = config.data_dir.as_path();
97    for (pid, process) in sys.processes() {
98        // On Linux, `sys.processes()` enumerates /proc/<pid>/task/<tid> too, so
99        // worker threads appear alongside their thread-group leader and share
100        // the same exe + cmdline. Skip threads — we want the TGID (the real
101        // process), which is the only PID safe to signal.
102        if process.thread_kind().is_some() {
103            continue;
104        }
105        let Some(exe) = process.exe() else {
106            continue;
107        };
108        if exe != config.binary_path.as_path() {
109            continue;
110        }
111
112        let cmd = process.cmd();
113        let matches_root_dir = cmd.iter().enumerate().any(|(i, arg)| {
114            let arg = arg.to_string_lossy();
115            if let Some(value) = arg.strip_prefix("--root-dir=") {
116                Path::new(value) == target_data_dir
117            } else if arg == "--root-dir" {
118                cmd.get(i + 1)
119                    .map(|v| Path::new(&*v.to_string_lossy()) == target_data_dir)
120                    .unwrap_or(false)
121            } else {
122                false
123            }
124        });
125
126        if matches_root_dir {
127            return Some(pid.as_u32());
128        }
129    }
130    None
131}
132
133/// Check whether `pid` refers to a live, non-thread process. On Linux,
134/// `kill(tid, 0)` returns success for any thread's TID, not just the
135/// thread-group leader — so liveness alone is not enough to trust a PID
136/// loaded from the pid file. Consulting sysinfo's `thread_kind()` tells us
137/// whether the entry is a userland thread (TID) vs. the actual process
138/// (TGID). A missing sysinfo entry with a live PID is still treated as a
139/// process, since older daemons could have written the PID before sysinfo
140/// saw it.
141fn pid_is_live_process(pid: u32, sys: &sysinfo::System) -> bool {
142    if !is_process_alive(pid) {
143        return false;
144    }
145    match sys.process(sysinfo::Pid::from_u32(pid)) {
146        Some(process) => process.thread_kind().is_none(),
147        None => true,
148    }
149}
150
151/// Determine the PID to adopt for a node, trying the pid file first and
152/// falling back to a process-table scan. On successful scan, writes the pid
153/// file so the next adoption takes the fast path.
154///
155/// Returns `None` if no live process can be attributed to this node.
156fn resolve_adopted_pid(config: &NodeConfig, sys: &sysinfo::System) -> Option<u32> {
157    if let Some(pid) = read_node_pid(&config.data_dir) {
158        if pid_is_live_process(pid, sys) {
159            return Some(pid);
160        }
161        // Pid file points at a dead process or a thread TID (legacy daemons
162        // could record a TID because the fallback scan saw threads). Don't
163        // leave it around to mislead the next adoption pass.
164        remove_node_pid(&config.data_dir);
165    }
166
167    let pid = find_running_node_process(sys, config)?;
168    write_node_pid(&config.data_dir, pid);
169    Some(pid)
170}
171
172/// Build an `Instant` that reports the real process start time when
173/// `.elapsed()` is called on it — so uptime survives daemon restarts
174/// accurately for adopted nodes.
175///
176/// `sysinfo::Process::start_time()` returns seconds since the UNIX epoch
177/// (wall clock). `Instant` is monotonic and can't be constructed from a
178/// wall-clock value directly, so we back-date `Instant::now()` by the
179/// process's age. Returns `None` if the PID isn't in the snapshot (the
180/// process exited between scan and this call), if the system clock looks
181/// broken, or if subtraction would overflow (unrealistically-old process
182/// start times).
183fn process_started_at(sys: &sysinfo::System, pid: u32) -> Option<Instant> {
184    let start_secs = sys.process(sysinfo::Pid::from_u32(pid))?.start_time();
185    let now_secs = std::time::SystemTime::now()
186        .duration_since(std::time::UNIX_EPOCH)
187        .ok()?
188        .as_secs();
189    let age = now_secs.saturating_sub(start_secs);
190    Instant::now().checked_sub(Duration::from_secs(age))
191}
192
193/// Maximum restart attempts before marking a node as errored.
194const MAX_CRASHES_BEFORE_ERRORED: u32 = 5;
195
196/// Window in which crashes are counted. If this many crashes happen within
197/// this duration, the node is marked errored.
198const CRASH_WINDOW: Duration = Duration::from_secs(300); // 5 minutes
199
200/// If a node runs for this long without crashing, reset the crash counter.
201const STABLE_DURATION: Duration = Duration::from_secs(300); // 5 minutes
202
203/// Maximum backoff delay between restarts.
204const MAX_BACKOFF: Duration = Duration::from_secs(60);
205
206/// Manages running node processes. Holds child process handles and runtime state.
207pub struct Supervisor {
208    event_tx: broadcast::Sender<NodeEvent>,
209    /// Runtime status of each node, keyed by node ID.
210    node_states: HashMap<u32, NodeRuntime>,
211    /// Nodes adopted from a previous daemon instance, which have no owning `monitor_node`
212    /// task (their `Child` handle died with the previous daemon). Exit detection and, on
213    /// auto-upgrade, respawn for these nodes happen in the liveness monitor instead. A node
214    /// leaves this set once this daemon (re)spawns it and owns a `monitor_node` for it.
215    adopted: HashSet<u32>,
216    /// Nodes currently being evicted (stop + data-dir delete in progress). Checked and set under
217    /// the supervisor write lock, so it atomically excludes a concurrent `start_node` for the whole
218    /// stop/delete window — before which the persisted eviction marker is not yet visible.
219    evicting: HashSet<u32>,
220}
221
222struct NodeRuntime {
223    status: NodeStatus,
224    pid: Option<u32>,
225    started_at: Option<Instant>,
226    restart_count: u32,
227    first_crash_at: Option<Instant>,
228}
229
230impl Supervisor {
231    pub fn new(event_tx: broadcast::Sender<NodeEvent>) -> Self {
232        Self {
233            event_tx,
234            node_states: HashMap::new(),
235            adopted: HashSet::new(),
236            evicting: HashSet::new(),
237        }
238    }
239
240    /// Whether `node_id` was adopted from a previous daemon instance and is therefore not
241    /// backed by an owning `monitor_node` task in this daemon.
242    pub fn is_adopted(&self, node_id: u32) -> bool {
243        self.adopted.contains(&node_id)
244    }
245
246    /// Mark a node as under eviction so `start_node` refuses it for the whole stop/delete window.
247    /// Both this and the `start_node` check run under the supervisor write lock, so a concurrent
248    /// start can never slip in and spawn the node while its data directory is being deleted.
249    fn begin_evicting(&mut self, node_id: u32) {
250        self.evicting.insert(node_id);
251    }
252
253    /// Clear the eviction-in-progress flag (the persisted `eviction` marker keeps the node
254    /// unstartable afterwards).
255    fn finish_evicting(&mut self, node_id: u32) {
256        self.evicting.remove(&node_id);
257    }
258
259    /// Mark a node as owned by this daemon (i.e. it now has a `monitor_node` task). Clears
260    /// any adopted flag so the liveness monitor leaves its exit handling to `monitor_node`.
261    fn mark_owned(&mut self, node_id: u32) {
262        self.adopted.remove(&node_id);
263    }
264
265    /// Start a node by spawning the actual process.
266    ///
267    /// Returns `NodeStarted` on success. Spawns a background monitoring task
268    /// that watches the child process and handles restart logic.
269    pub async fn start_node(
270        &mut self,
271        config: &NodeConfig,
272        supervisor_ref: Arc<RwLock<Supervisor>>,
273        registry_ref: Arc<RwLock<NodeRegistry>>,
274    ) -> Result<NodeStarted> {
275        let node_id = config.id;
276
277        // An evicted node's data directory has been deleted; it must not be restarted. Recovery is
278        // to dismiss it (remove from the registry) and add a fresh node. The persisted marker covers
279        // the settled case; the in-progress `evicting` set (set under this same lock) covers the
280        // window where the delete is still running and the marker's config may not be visible yet.
281        if config.eviction.is_some() || self.evicting.contains(&node_id) {
282            return Err(Error::NodeEvicted(node_id));
283        }
284
285        if let Some(state) = self.node_states.get(&node_id) {
286            if state.status == NodeStatus::Running {
287                return Err(Error::NodeAlreadyRunning(node_id));
288            }
289        }
290
291        let _ = self.event_tx.send(NodeEvent::NodeStarting { node_id });
292
293        let mut child = spawn_node_from_config(config).await?;
294        let pid = child
295            .id()
296            .ok_or_else(|| Error::ProcessSpawn("Failed to get PID from spawned process".into()))?;
297
298        // Brief health check: give the process a moment to start, then check if it
299        // exited immediately. This catches errors like invalid CLI arguments or missing
300        // shared libraries. We use timeout + wait() rather than try_wait() because
301        // tokio's child reaper requires the wait future to be polled.
302        match tokio::time::timeout(Duration::from_secs(1), child.wait()).await {
303            Ok(Ok(exit_status)) => {
304                // Process already exited — read stderr for details.
305                // spawn_node always redirects stderr to a file in the log dir
306                // (falling back to data_dir when no log dir is configured).
307                let spawn_log_dir = config.log_dir.as_deref().unwrap_or(&config.data_dir);
308                let stderr_path = spawn_log_dir.join("stderr.log");
309                let stderr_msg = std::fs::read_to_string(&stderr_path).unwrap_or_default();
310                let detail = if stderr_msg.trim().is_empty() {
311                    format!("exit code: {exit_status}")
312                } else {
313                    stderr_msg.trim().to_string()
314                };
315                self.node_states.insert(
316                    node_id,
317                    NodeRuntime {
318                        status: NodeStatus::Errored,
319                        pid: None,
320                        started_at: None,
321                        restart_count: 0,
322                        first_crash_at: None,
323                    },
324                );
325                return Err(Error::ProcessSpawn(format!(
326                    "Node {node_id} exited immediately: {detail}"
327                )));
328            }
329            Ok(Err(e)) => {
330                return Err(Error::ProcessSpawn(format!(
331                    "Failed to check node process status: {e}"
332                )));
333            }
334            Err(_) => {} // Timeout — process is still running after 1s, good
335        }
336
337        self.node_states.insert(
338            node_id,
339            NodeRuntime {
340                status: NodeStatus::Running,
341                pid: Some(pid),
342                started_at: Some(Instant::now()),
343                restart_count: 0,
344                first_crash_at: None,
345            },
346        );
347        // This daemon now owns the process and spawns a `monitor_node` for it below, so it is
348        // no longer (or never was) an adopted node the liveness monitor must respawn.
349        self.mark_owned(node_id);
350
351        let _ = self.event_tx.send(NodeEvent::NodeStarted { node_id, pid });
352
353        let result = NodeStarted {
354            node_id,
355            service_name: config.service_name.clone(),
356            pid,
357        };
358
359        // Spawn monitoring task
360        let event_tx = self.event_tx.clone();
361        let config = config.clone();
362        tokio::spawn(async move {
363            monitor_node(child, config, supervisor_ref, registry_ref, event_tx).await;
364        });
365
366        Ok(result)
367    }
368
369    /// Stop a node by gracefully terminating its process.
370    ///
371    /// Sends SIGTERM (Unix) or kills (Windows), waits up to 10 seconds for exit,
372    /// then sends SIGKILL if needed. The monitor task detects the Stopping status
373    /// and exits cleanly without attempting a restart.
374    pub async fn stop_node(&mut self, node_id: u32) -> Result<()> {
375        let state = self
376            .node_states
377            .get_mut(&node_id)
378            .ok_or(Error::NodeNotFound(node_id))?;
379
380        if state.status != NodeStatus::Running {
381            return Err(Error::NodeNotRunning(node_id));
382        }
383
384        let pid = state.pid;
385
386        let _ = self.event_tx.send(NodeEvent::NodeStopping { node_id });
387        state.status = NodeStatus::Stopping;
388
389        if let Some(pid) = pid {
390            graceful_kill(pid).await;
391        }
392
393        // Update state after kill
394        let state = self.node_states.get_mut(&node_id).unwrap();
395        state.status = NodeStatus::Stopped;
396        state.pid = None;
397        state.started_at = None;
398
399        let _ = self.event_tx.send(NodeEvent::NodeStopped { node_id });
400
401        Ok(())
402    }
403
404    /// Stop all running nodes, returning an aggregate result.
405    pub async fn stop_all_nodes(&mut self, configs: &[(u32, String)]) -> StopNodeResult {
406        let mut stopped = Vec::new();
407        let mut failed = Vec::new();
408        let mut already_stopped = Vec::new();
409
410        for (node_id, service_name) in configs {
411            let node_id = *node_id;
412            match self.node_status(node_id) {
413                Ok(NodeStatus::Running) => {}
414                Ok(_) => {
415                    already_stopped.push(node_id);
416                    continue;
417                }
418                Err(_) => {
419                    already_stopped.push(node_id);
420                    continue;
421                }
422            }
423
424            match self.stop_node(node_id).await {
425                Ok(()) => {
426                    stopped.push(NodeStopped {
427                        node_id,
428                        service_name: service_name.clone(),
429                    });
430                }
431                Err(Error::NodeNotRunning(_)) => {
432                    already_stopped.push(node_id);
433                }
434                Err(e) => {
435                    failed.push(NodeStopFailed {
436                        node_id,
437                        service_name: service_name.clone(),
438                        error: e.to_string(),
439                    });
440                }
441            }
442        }
443
444        StopNodeResult {
445            stopped,
446            failed,
447            already_stopped,
448        }
449    }
450
451    /// Get the status of a node.
452    pub fn node_status(&self, node_id: u32) -> Result<NodeStatus> {
453        self.node_states
454            .get(&node_id)
455            .map(|s| s.status)
456            .ok_or(Error::NodeNotFound(node_id))
457    }
458
459    /// Get the PID of a running node.
460    pub fn node_pid(&self, node_id: u32) -> Option<u32> {
461        self.node_states.get(&node_id).and_then(|s| s.pid)
462    }
463
464    /// Get the uptime of a running node in seconds.
465    pub fn node_uptime_secs(&self, node_id: u32) -> Option<u64> {
466        self.node_states
467            .get(&node_id)
468            .and_then(|s| s.started_at.map(|t| t.elapsed().as_secs()))
469    }
470
471    /// Check whether a node is running.
472    pub fn is_running(&self, node_id: u32) -> bool {
473        self.node_states
474            .get(&node_id)
475            .is_some_and(|s| s.status == NodeStatus::Running)
476    }
477
478    /// Get counts of nodes in each state: (running, stopped, errored).
479    pub fn node_counts(&self) -> (u32, u32, u32) {
480        let mut running = 0u32;
481        let mut stopped = 0u32;
482        let mut errored = 0u32;
483        for state in self.node_states.values() {
484            match state.status {
485                NodeStatus::Running | NodeStatus::Starting => running += 1,
486                // An evicted node is not running; count it alongside stopped for these totals.
487                NodeStatus::Stopped | NodeStatus::Stopping | NodeStatus::Evicted => stopped += 1,
488                NodeStatus::Errored => errored += 1,
489            }
490        }
491        (running, stopped, errored)
492    }
493
494    /// Update the runtime state for a node (used by the monitor task).
495    fn update_state(&mut self, node_id: u32, status: NodeStatus, pid: Option<u32>) {
496        if let Some(state) = self.node_states.get_mut(&node_id) {
497            state.status = status;
498            state.pid = pid;
499            if status == NodeStatus::Running {
500                state.started_at = Some(Instant::now());
501            } else {
502                // Clear uptime tracking for non-running states so status
503                // responses don't report a stale `uptime_secs` after the node
504                // exits (e.g. liveness monitor detecting an external kill).
505                state.started_at = None;
506            }
507        }
508    }
509
510    /// Restore running-node state from a previous daemon instance.
511    ///
512    /// For each registered node, determines the PID to adopt via
513    /// `resolve_adopted_pid`: try `<data_dir>/node.pid` first, and if it's
514    /// missing or stale, fall back to a process-table scan matching the
515    /// node's binary path and `--root-dir` argument. Live matches are
516    /// inserted into `node_states` as `Running`.
517    ///
518    /// The scan is what covers the upgrade path: nodes spawned by a
519    /// pre-adoption daemon never had a pid file written, so without the
520    /// fallback the first restart after installing this fix would still
521    /// leave every previously-running node classified as Stopped.
522    ///
523    /// Must be called before the HTTP server starts accepting requests —
524    /// the window between `Supervisor::new` and adoption is where the API
525    /// would otherwise report live nodes as Stopped. Adopted nodes have no
526    /// associated `monitor_node` task (the `tokio::process::Child` handle
527    /// belonged to the previous daemon, and `tokio::process::Child::wait`
528    /// only works for the process's actual parent). Their exits are
529    /// detected instead by the `spawn_liveness_monitor` polling task.
530    ///
531    /// Returns the list of node IDs that were adopted.
532    pub fn adopt_from_registry(&mut self, registry: &NodeRegistry) -> Vec<u32> {
533        // Populated upfront so every adopted node gets its real start time via
534        // `process_started_at`, not just those that went through the scan
535        // fallback. The extra ~50 ms at daemon startup is a one-time cost
536        // that's cheaper than users seeing uptime reset every time the daemon
537        // restarts.
538        let mut sys = sysinfo::System::new();
539        sys.refresh_processes_specifics(
540            sysinfo::ProcessesToUpdate::All,
541            true,
542            sysinfo::ProcessRefreshKind::everything(),
543        );
544
545        let mut adopted = Vec::new();
546        for config in registry.list() {
547            let Some(pid) = resolve_adopted_pid(config, &sys) else {
548                continue;
549            };
550            self.node_states.insert(
551                config.id,
552                NodeRuntime {
553                    status: NodeStatus::Running,
554                    pid: Some(pid),
555                    // Back-date to the real process start time so uptime
556                    // reported to the API is wall-clock accurate across
557                    // daemon restarts. Falls back to `Instant::now()` only
558                    // if sysinfo can't report the start time (PID raced out
559                    // of the snapshot, or a broken clock) — better to show
560                    // uptime counting from adoption than to claim the node
561                    // is Stopped.
562                    started_at: Some(process_started_at(&sys, pid).unwrap_or_else(Instant::now)),
563                    restart_count: 0,
564                    first_crash_at: None,
565                },
566            );
567            // No owning `monitor_node` exists for an adopted process (its `Child` died with the
568            // previous daemon), so flag it for the liveness monitor to handle its exit/respawn.
569            self.adopted.insert(config.id);
570            let _ = self.event_tx.send(NodeEvent::NodeStarted {
571                node_id: config.id,
572                pid,
573            });
574            adopted.push(config.id);
575        }
576        adopted
577    }
578
579    /// Record a crash and determine if the node should be restarted or marked errored.
580    /// Returns (should_restart, attempt_number, backoff_duration).
581    fn record_crash(&mut self, node_id: u32) -> (bool, u32, Duration) {
582        let state = match self.node_states.get_mut(&node_id) {
583            Some(s) => s,
584            None => return (false, 0, Duration::ZERO),
585        };
586
587        let now = Instant::now();
588
589        // Check if we were stable long enough to reset crash counter
590        if let Some(started_at) = state.started_at {
591            if started_at.elapsed() >= STABLE_DURATION {
592                state.restart_count = 0;
593                state.first_crash_at = None;
594            }
595        }
596
597        state.restart_count += 1;
598        let attempt = state.restart_count;
599
600        if state.first_crash_at.is_none() {
601            state.first_crash_at = Some(now);
602        }
603
604        // Check if too many crashes in the window
605        if let Some(first_crash) = state.first_crash_at {
606            if attempt >= MAX_CRASHES_BEFORE_ERRORED
607                && now.duration_since(first_crash) < CRASH_WINDOW
608            {
609                state.status = NodeStatus::Errored;
610                state.pid = None;
611                state.started_at = None;
612                return (false, attempt, Duration::ZERO);
613            }
614        }
615
616        // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s, 60s cap
617        let backoff_secs = 1u64 << (attempt - 1).min(5);
618        let backoff = Duration::from_secs(backoff_secs).min(MAX_BACKOFF);
619
620        (true, attempt, backoff)
621    }
622}
623
624/// Background task: monitor free disk space at each node's data directory and, when a partition
625/// falls to its eviction threshold, automatically evict a node to reclaim space.
626///
627/// Each tick it (1) measures every running node's data directory grouped by partition, (2) refreshes
628/// the shared [`FleetHealth`] snapshot so the CLI/GUI can show how close the fleet is to an
629/// eviction, and (3) evicts the selected candidate on any partition that is at/below the threshold
630/// *and* still has at least two nodes (so a node remains to benefit). Eviction stops the process,
631/// deletes the data directory, records a persisted [`EvictionRecord`], and emits an event. It
632/// re-measures and may evict again — bounded by `MAX_EVICTIONS_PER_CYCLE` — because a single
633/// eviction may not free enough on a heavily over-provisioned partition.
634///
635/// The task exits when `shutdown` is cancelled.
636pub fn spawn_eviction_monitor(
637    registry: Arc<RwLock<NodeRegistry>>,
638    supervisor: Arc<RwLock<Supervisor>>,
639    event_tx: broadcast::Sender<NodeEvent>,
640    health: Arc<RwLock<FleetHealth>>,
641    thresholds: DiskThresholds,
642    interval: Duration,
643    shutdown: CancellationToken,
644) {
645    tokio::spawn(async move {
646        let mut ticker = tokio::time::interval(interval);
647        ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
648        // Skip the immediate first tick so we don't evict while nodes are still starting up.
649        ticker.tick().await;
650
651        loop {
652            tokio::select! {
653                _ = shutdown.cancelled() => return,
654                _ = ticker.tick() => {},
655            }
656
657            run_eviction_cycle(&registry, &supervisor, &event_tx, &health, &thresholds).await;
658        }
659    });
660}
661
662/// Run one disk-pressure check: evict as needed (bounded), then refresh the health snapshot.
663async fn run_eviction_cycle(
664    registry: &Arc<RwLock<NodeRegistry>>,
665    supervisor: &Arc<RwLock<Supervisor>>,
666    event_tx: &broadcast::Sender<NodeEvent>,
667    health: &Arc<RwLock<FleetHealth>>,
668    thresholds: &DiskThresholds,
669) {
670    for _ in 0..MAX_EVICTIONS_PER_CYCLE {
671        let partitions = disk::partition_states(running_nodes(registry, supervisor).await);
672
673        // A partition needs an eviction when it is at/below the threshold and has a spare node to
674        // sacrifice (≥2 nodes, so one remains). The sole-node case is deliberately left for the
675        // health layer to surface as Critical rather than auto-evicting the only node.
676        let target = partitions
677            .iter()
678            .find(|p| p.available_bytes <= thresholds.eviction_bytes && p.nodes.len() >= 2);
679
680        let Some(partition) = target else {
681            // Nothing more to evict: publish the current health and finish this cycle.
682            publish_health(
683                health,
684                event_tx,
685                FleetHealth::from_partitions(&partitions, thresholds),
686            )
687            .await;
688            return;
689        };
690
691        let Some(candidate) = partition.eviction_candidate().cloned() else {
692            break;
693        };
694
695        evict_node(
696            registry,
697            supervisor,
698            event_tx,
699            &candidate,
700            partition.available_bytes,
701        )
702        .await;
703    }
704
705    // Reached the per-cycle eviction cap (or hit a candidate-less partition): refresh health so the
706    // snapshot reflects reality before the next tick.
707    let partitions = disk::partition_states(running_nodes(registry, supervisor).await);
708    publish_health(
709        health,
710        event_tx,
711        FleetHealth::from_partitions(&partitions, thresholds),
712    )
713    .await;
714}
715
716/// Snapshot of currently-running, non-evicted nodes as `(id, data_dir)` pairs.
717async fn running_nodes(
718    registry: &Arc<RwLock<NodeRegistry>>,
719    supervisor: &Arc<RwLock<Supervisor>>,
720) -> Vec<(u32, PathBuf)> {
721    let reg = registry.read().await;
722    let sup = supervisor.read().await;
723    reg.list()
724        .into_iter()
725        .filter(|config| config.eviction.is_none())
726        .filter(|config| matches!(sup.node_status(config.id), Ok(NodeStatus::Running)))
727        .map(|config| (config.id, config.data_dir.clone()))
728        .collect()
729}
730
731/// Delete a directory tree, retrying briefly to tolerate transient locks.
732///
733/// A node we just killed can hold its data files open for a short moment after exit — on Windows
734/// especially (its LMDB memory map and its own copied `ant-node` binary), and antivirus/indexers can
735/// grab transient handles — so `remove_dir_all` fails with "access denied / in use" until the OS
736/// releases them. A bounded exponential backoff gives it time; on Unix the first attempt almost
737/// always succeeds. Returns `Ok` on success or if the directory is already gone.
738async fn remove_dir_all_with_retry(path: &Path) -> std::io::Result<()> {
739    const MAX_ATTEMPTS: u32 = 8;
740    let mut delay = Duration::from_millis(100);
741    for attempt in 1..=MAX_ATTEMPTS {
742        match std::fs::remove_dir_all(path) {
743            Ok(()) => return Ok(()),
744            // Already gone — nothing left to reclaim; treat as success.
745            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
746            Err(e) if attempt == MAX_ATTEMPTS => return Err(e),
747            Err(_) => {
748                tokio::time::sleep(delay).await;
749                delay = (delay * 2).min(Duration::from_secs(1));
750            }
751        }
752    }
753    Ok(())
754}
755
756/// Write (or overwrite) a node's persisted eviction marker and save the registry.
757async fn persist_eviction_marker(
758    registry: &Arc<RwLock<NodeRegistry>>,
759    node_id: u32,
760    reason: &str,
761    evicted_at: u64,
762    reclaimed_bytes: u64,
763) {
764    let mut reg = registry.write().await;
765    if let Ok(config) = reg.get_mut(node_id) {
766        config.eviction = Some(EvictionRecord {
767            reason: reason.to_string(),
768            evicted_at,
769            reclaimed_bytes,
770        });
771    }
772    if let Err(e) = reg.save() {
773        tracing::error!("Eviction: failed to persist registry for node {node_id}: {e}");
774    }
775}
776
777/// Evict a single node: make it unstartable, stop it, delete its data directory, finalise the
778/// persisted marker, and emit an event.
779///
780/// Ordering matters for safety. The node is made unstartable *before* the stop/delete window — via
781/// the in-memory `evicting` flag (set under the supervisor lock, so it atomically excludes a
782/// concurrent `start_node`) and a persisted eviction marker (which also survives a daemon crash
783/// mid-delete). Only then do we stop and delete. Rollback is deliberately not attempted: once the
784/// process is stopped the node stays `Evicted` (terminal) whether or not the delete succeeds.
785async fn evict_node(
786    registry: &Arc<RwLock<NodeRegistry>>,
787    supervisor: &Arc<RwLock<Supervisor>>,
788    event_tx: &broadcast::Sender<NodeEvent>,
789    candidate: &disk::NodeDiskUsage,
790    available_before: u64,
791) {
792    let node_id = candidate.node_id;
793    let reclaimable = candidate.size_bytes;
794    let evicted_at = now_unix_secs();
795
796    // 1. Make the node unstartable up front (before we touch the process or its files).
797    supervisor.write().await.begin_evicting(node_id);
798    let pending_reason = format!(
799        "Automatically evicted to reclaim disk space: only {} free on its partition. \
800         Deleting its data directory to recover ~{}.",
801        fmt_bytes(available_before),
802        fmt_bytes(reclaimable),
803    );
804    persist_eviction_marker(registry, node_id, &pending_reason, evicted_at, reclaimable).await;
805
806    // 2. Stop the process (still marked Running, so this actually kills it). The monitor_node task
807    //    sees the Stopping/Stopped transition and will not respawn it.
808    if let Err(e) = supervisor.write().await.stop_node(node_id).await {
809        tracing::warn!("Eviction: failed to stop node {node_id} before deletion: {e}");
810    }
811
812    // 3. Delete the data directory — this reclaims the disk space. A just-killed node can briefly
813    //    hold its files open (LMDB memory map, its own copied binary); on Windows `remove_dir_all`
814    //    then fails until the OS releases the handles, so retry with backoff.
815    let deleted = match remove_dir_all_with_retry(&candidate.data_dir).await {
816        Ok(()) => true,
817        Err(e) => {
818            tracing::error!(
819                "Eviction: could not delete data dir {} for node {node_id} after retries: {e}. \
820                 Disk space was NOT reclaimed; manual cleanup may be required.",
821                candidate.data_dir.display()
822            );
823            false
824        }
825    };
826
827    // 4. Finalise the marker to reflect what actually happened, flip runtime state to Evicted, and
828    //    clear the in-progress flag (the persisted marker keeps the node unstartable from here).
829    let (reclaimed_bytes, reason) = if deleted {
830        (
831            reclaimable,
832            format!(
833                "Automatically evicted to reclaim disk space: only {} free on its partition. \
834                 Its data directory was deleted, recovering ~{}.",
835                fmt_bytes(available_before),
836                fmt_bytes(reclaimable),
837            ),
838        )
839    } else {
840        (
841            0,
842            format!(
843                "Automatically evicted due to low disk space (only {} free on its partition), but \
844                 its data directory could not be deleted, so space was not reclaimed. Manual \
845                 cleanup of {} may be needed.",
846                fmt_bytes(available_before),
847                candidate.data_dir.display(),
848            ),
849        )
850    };
851    persist_eviction_marker(registry, node_id, &reason, evicted_at, reclaimed_bytes).await;
852    {
853        let mut sup = supervisor.write().await;
854        sup.update_state(node_id, NodeStatus::Evicted, None);
855        sup.finish_evicting(node_id);
856    }
857
858    tracing::info!(
859        "Evicted node {node_id}, reclaimed ~{} ({reason})",
860        fmt_bytes(reclaimed_bytes)
861    );
862    let _ = event_tx.send(NodeEvent::NodeEvicted {
863        node_id,
864        reason,
865        reclaimed_bytes,
866    });
867}
868
869/// Store the new health snapshot, emitting a `FleetHealthChanged` event if the overall level moved.
870async fn publish_health(
871    health: &Arc<RwLock<FleetHealth>>,
872    event_tx: &broadcast::Sender<NodeEvent>,
873    next: FleetHealth,
874) {
875    let changed = {
876        let mut current = health.write().await;
877        let changed = current.overall != next.overall;
878        *current = next.clone();
879        changed
880    };
881    if changed {
882        let _ = event_tx.send(NodeEvent::FleetHealthChanged {
883            overall: serde_json::to_value(next.overall)
884                .ok()
885                .and_then(|v| v.as_str().map(str::to_owned))
886                .unwrap_or_default(),
887        });
888    }
889}
890
891/// Current Unix time in whole seconds. Falls back to 0 if the clock is before the epoch.
892fn now_unix_secs() -> u64 {
893    std::time::SystemTime::now()
894        .duration_since(std::time::UNIX_EPOCH)
895        .map(|d| d.as_secs())
896        .unwrap_or(0)
897}
898
899/// Format a byte count as a human-friendly string (GiB/MiB), matching the health layer's style.
900fn fmt_bytes(bytes: u64) -> String {
901    const MIB: f64 = 1024.0 * 1024.0;
902    const GIB: f64 = 1024.0 * MIB;
903    let b = bytes as f64;
904    if b >= GIB {
905        format!("{:.2} GiB", b / GIB)
906    } else {
907        format!("{:.0} MiB", b / MIB)
908    }
909}
910
911/// Build CLI arguments for the node binary from a NodeConfig.
912pub fn build_node_args(config: &NodeConfig) -> Vec<String> {
913    let mut args = vec![
914        "--rewards-address".to_string(),
915        config.rewards_address.clone(),
916        "--root-dir".to_string(),
917        config.data_dir.display().to_string(),
918    ];
919
920    if let Some(ref log_dir) = config.log_dir {
921        args.push("--enable-logging".to_string());
922        args.push("--log-dir".to_string());
923        args.push(log_dir.display().to_string());
924    }
925
926    if let Some(port) = config.node_port {
927        args.push("--port".to_string());
928        args.push(port.to_string());
929    }
930
931    for peer in &config.bootstrap_peers {
932        args.push("--bootstrap".to_string());
933        args.push(peer.clone());
934    }
935
936    if let Some(channel) = config.upgrade_channel {
937        args.push("--upgrade-channel".to_string());
938        args.push(channel.to_string());
939    }
940
941    // The daemon's supervisor is the service manager. Tell ant-node not to spawn its own
942    // replacement on auto-upgrade; instead, exit cleanly and let us respawn. Without this,
943    // ant-node's default spawn-grandchild-then-exit flow races for the node's port during
944    // the parent's graceful shutdown and the grandchild fails to bind.
945    args.push("--stop-on-upgrade".to_string());
946
947    // Always emit the EVM network so the node's payment network is explicit rather than relying on
948    // the binary's built-in default.
949    args.push("--evm-network".to_string());
950    args.push(config.evm_network.as_arg().to_string());
951
952    args
953}
954
955/// Whether `exit_code` is one ant-node uses to hand its restart to this daemon after replacing its
956/// own binary during an auto-upgrade: `0` on Unix, [`RESTART_EXIT_CODE`] on Windows (both under
957/// `--stop-on-upgrade`, which the daemon always sets). A matching code is necessary but not
958/// sufficient — the caller additionally confirms the on-disk binary version drifted before treating
959/// the exit as an upgrade rather than a crash.
960fn is_upgrade_restart_exit_code(exit_code: Option<i32>) -> bool {
961    matches!(exit_code, Some(0) | Some(RESTART_EXIT_CODE))
962}
963
964/// Spawn a node process from a NodeConfig.
965///
966/// Writes `<data_dir>/node.pid` on successful spawn so that a future daemon instance
967/// can adopt the running process via `Supervisor::adopt_from_registry`. The file is
968/// cleaned up by `monitor_node` on the node's terminal exit.
969async fn spawn_node_from_config(config: &NodeConfig) -> Result<tokio::process::Child> {
970    let args = build_node_args(config);
971    let env_vars: Vec<(String, String)> = config.env_variables.clone().into_iter().collect();
972
973    let log_dir = config
974        .log_dir
975        .as_deref()
976        .unwrap_or(config.data_dir.as_path());
977
978    let child = spawn_node(&config.binary_path, &args, &env_vars, log_dir).await?;
979    if let Some(pid) = child.id() {
980        write_node_pid(&config.data_dir, pid);
981    }
982    Ok(child)
983}
984
985/// Monitor a node process. On exit, handle restart logic. On permanent exit
986/// (user stop, crash limit, errored), cleans up the pid file so a subsequent
987/// daemon restart doesn't try to adopt a dead process.
988async fn monitor_node(
989    child: tokio::process::Child,
990    mut config: NodeConfig,
991    supervisor: Arc<RwLock<Supervisor>>,
992    registry: Arc<RwLock<NodeRegistry>>,
993    event_tx: broadcast::Sender<NodeEvent>,
994) {
995    monitor_node_inner(child, &mut config, supervisor, registry, event_tx).await;
996    remove_node_pid(&config.data_dir);
997}
998
999async fn monitor_node_inner(
1000    mut child: tokio::process::Child,
1001    config: &mut NodeConfig,
1002    supervisor: Arc<RwLock<Supervisor>>,
1003    registry: Arc<RwLock<NodeRegistry>>,
1004    event_tx: broadcast::Sender<NodeEvent>,
1005) {
1006    let node_id = config.id;
1007
1008    loop {
1009        // Wait for the process to exit
1010        let exit_status = child.wait().await;
1011
1012        // Intentional stops must not respawn. Stopped/Stopping are user-initiated; Evicted means
1013        // the daemon deleted the data dir to reclaim space.
1014        let status_at_exit = {
1015            let sup = supervisor.read().await;
1016            sup.node_status(node_id).ok()
1017        };
1018        if matches!(
1019            status_at_exit,
1020            Some(NodeStatus::Stopped) | Some(NodeStatus::Stopping) | Some(NodeStatus::Evicted)
1021        ) {
1022            return;
1023        }
1024
1025        let exit_code = exit_status.ok().and_then(|s| s.code());
1026
1027        // A process-reported exit that wasn't user-initiated (filtered above) is either an
1028        // auto-upgrade or a crash. In neither case should the node be parked in `Stopped` — that
1029        // state is reserved for intentional user stops.
1030        //
1031        // ant-node runs with `--stop-on-upgrade`: after replacing its own binary in place it exits
1032        // cleanly and relies on this daemon to restart it (`0` on Unix, `RESTART_EXIT_CODE` on
1033        // Windows). Distinguish an upgrade from a crash by whether the on-disk binary's version
1034        // drifted from the registry — the reliable signal, independent of platform exit code. On an
1035        // upgrade we respawn directly (no backoff, no crash counter) and refresh the recorded
1036        // version via `respawn_upgraded_node`.
1037        if is_upgrade_restart_exit_code(exit_code) {
1038            if let Ok(disk_version) = extract_version(&config.binary_path).await {
1039                if disk_version != config.version {
1040                    match respawn_upgraded_node(config, &supervisor, &registry, &event_tx).await {
1041                        Ok(new_child) => {
1042                            child = new_child;
1043                            continue;
1044                        }
1045                        Err(e) => {
1046                            let _ = event_tx.send(NodeEvent::NodeErrored {
1047                                node_id,
1048                                message: format!("Failed to respawn after upgrade: {e}"),
1049                            });
1050                            let mut sup = supervisor.write().await;
1051                            sup.update_state(node_id, NodeStatus::Errored, None);
1052                            return;
1053                        }
1054                    }
1055                }
1056            }
1057            // Clean exit but the binary didn't change — fall through to the crash / restart path.
1058            // We report the crash with the exit code preserved; the crash counter guards against
1059            // infinite restart loops if the process keeps exiting immediately.
1060        }
1061
1062        // Crash (or clean exit that wasn't an upgrade)
1063        let _ = event_tx.send(NodeEvent::NodeCrashed { node_id, exit_code });
1064
1065        let (should_restart, attempt, backoff) = {
1066            let mut sup = supervisor.write().await;
1067            sup.record_crash(node_id)
1068        };
1069
1070        if !should_restart {
1071            let _ = event_tx.send(NodeEvent::NodeErrored {
1072                node_id,
1073                message: format!(
1074                    "Node crashed {} times within {} seconds, giving up",
1075                    MAX_CRASHES_BEFORE_ERRORED,
1076                    CRASH_WINDOW.as_secs()
1077                ),
1078            });
1079            return;
1080        }
1081
1082        let _ = event_tx.send(NodeEvent::NodeRestarting { node_id, attempt });
1083
1084        tokio::time::sleep(backoff).await;
1085
1086        // Try to restart
1087        match spawn_node_from_config(&*config).await {
1088            Ok(new_child) => {
1089                let pid = match new_child.id() {
1090                    Some(pid) => pid,
1091                    None => {
1092                        // Process exited before we could read its PID
1093                        let _ = event_tx.send(NodeEvent::NodeErrored {
1094                            node_id,
1095                            message: "Restarted process exited before PID could be read"
1096                                .to_string(),
1097                        });
1098                        let mut sup = supervisor.write().await;
1099                        sup.update_state(node_id, NodeStatus::Errored, None);
1100                        return;
1101                    }
1102                };
1103                {
1104                    let mut sup = supervisor.write().await;
1105                    sup.update_state(node_id, NodeStatus::Running, Some(pid));
1106                }
1107                let _ = event_tx.send(NodeEvent::NodeStarted { node_id, pid });
1108                child = new_child;
1109            }
1110            Err(e) => {
1111                let _ = event_tx.send(NodeEvent::NodeErrored {
1112                    node_id,
1113                    message: format!("Failed to restart node: {e}"),
1114                });
1115                let mut sup = supervisor.write().await;
1116                sup.update_state(node_id, NodeStatus::Errored, None);
1117                return;
1118            }
1119        }
1120    }
1121}
1122
1123/// Respawn a node that exited to apply an in-place auto-upgrade of its own binary.
1124///
1125/// On success: persists the new version to the registry, updates the in-memory config clone,
1126/// sets status back to Running, and fires `NodeUpgraded`.
1127async fn respawn_upgraded_node(
1128    config: &mut NodeConfig,
1129    supervisor: &Arc<RwLock<Supervisor>>,
1130    registry: &Arc<RwLock<NodeRegistry>>,
1131    event_tx: &broadcast::Sender<NodeEvent>,
1132) -> Result<tokio::process::Child> {
1133    let node_id = config.id;
1134    let old_version = config.version.clone();
1135
1136    let new_child = spawn_node_from_config(config).await?;
1137    let pid = new_child
1138        .id()
1139        .ok_or_else(|| Error::ProcessSpawn("Failed to get PID after upgrade respawn".into()))?;
1140
1141    // Read the new version from the replaced binary. If this fails we still consider the respawn
1142    // successful; we just don't refresh the recorded version this round.
1143    let new_version = extract_version(&config.binary_path).await.ok();
1144
1145    if let Some(ref version) = new_version {
1146        config.version = version.clone();
1147        let mut reg = registry.write().await;
1148        if let Ok(stored) = reg.get_mut(node_id) {
1149            stored.version = version.clone();
1150            let _ = reg.save();
1151        }
1152    }
1153
1154    {
1155        let mut sup = supervisor.write().await;
1156        if let Some(state) = sup.node_states.get_mut(&node_id) {
1157            state.status = NodeStatus::Running;
1158            state.pid = Some(pid);
1159            state.started_at = Some(Instant::now());
1160            state.restart_count = 0;
1161            state.first_crash_at = None;
1162        }
1163    }
1164
1165    let _ = event_tx.send(NodeEvent::NodeStarted { node_id, pid });
1166    if let Some(version) = new_version {
1167        let _ = event_tx.send(NodeEvent::NodeUpgraded {
1168            node_id,
1169            old_version,
1170            new_version: version,
1171        });
1172    }
1173
1174    Ok(new_child)
1175}
1176
1177/// Timeout for graceful shutdown before force-killing.
1178const GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
1179
1180/// Send SIGTERM to a process, wait for it to exit, and SIGKILL if it doesn't.
1181async fn graceful_kill(pid: u32) {
1182    send_signal_term(pid);
1183
1184    // Poll for process exit
1185    let start = Instant::now();
1186    loop {
1187        if !is_process_alive(pid) {
1188            return;
1189        }
1190        if start.elapsed() >= GRACEFUL_SHUTDOWN_TIMEOUT {
1191            break;
1192        }
1193        tokio::time::sleep(Duration::from_millis(100)).await;
1194    }
1195
1196    // Force kill if still alive
1197    send_signal_kill(pid);
1198
1199    // Brief wait for force kill to take effect
1200    for _ in 0..10 {
1201        if !is_process_alive(pid) {
1202            return;
1203        }
1204        tokio::time::sleep(Duration::from_millis(50)).await;
1205    }
1206}
1207
1208/// Decide whether the liveness monitor should flip a node it found dead to `Stopped`.
1209///
1210/// `snapshot_pid` is the PID the sweep captured and then observed to be dead. `current_pid`
1211/// and `current_status` are the node's recorded state at the moment of the decision — which
1212/// may differ from the snapshot (e.g. an upgrade respawn replaced the PID with a live one
1213/// while leaving the status `Running`).
1214///
1215/// We only stop the node if it is still `Running` AND the recorded PID is still the one we
1216/// observed dead. The PID check is essential: between the snapshot and now, an upgrade (or
1217/// crash) respawn can have replaced the dead `snapshot_pid` with a live `current_pid` while
1218/// keeping the status `Running`. Stopping in that case would clobber a healthy, freshly
1219/// respawned process (the "running node reported as stopped after an upgrade" bug).
1220fn liveness_should_stop(
1221    snapshot_pid: u32,
1222    current_pid: Option<u32>,
1223    current_status: Option<NodeStatus>,
1224) -> bool {
1225    current_status == Some(NodeStatus::Running) && current_pid == Some(snapshot_pid)
1226}
1227
1228/// Poll each Running node's PID for OS liveness every `LIVENESS_POLL_INTERVAL`,
1229/// flipping dead ones to `Stopped` and emitting `NodeStopped`.
1230///
1231/// Exists to detect exits of nodes adopted across a daemon restart
1232/// (`Supervisor::adopt_from_registry`). Daemon-spawned nodes have a
1233/// `monitor_node` task awaiting on the owned `Child` handle, which detects
1234/// exit immediately — the poll is redundant-but-harmless for them. Adopted
1235/// nodes don't have a `Child` (it died with the previous daemon), so the poll
1236/// is the only way the supervisor learns that one has exited.
1237///
1238/// The task terminates when `shutdown` is cancelled.
1239pub fn spawn_liveness_monitor(
1240    registry: Arc<RwLock<NodeRegistry>>,
1241    supervisor: Arc<RwLock<Supervisor>>,
1242    event_tx: broadcast::Sender<NodeEvent>,
1243    interval: Duration,
1244    shutdown: CancellationToken,
1245) {
1246    tokio::spawn(async move {
1247        let mut ticker = tokio::time::interval(interval);
1248        // Don't burst-catchup after a Windows sleep/hibernate: a flood of liveness
1249        // probes serves no purpose, and uniform `Skip` policy across supervisor
1250        // monitors keeps post-wake behaviour predictable.
1251        ticker.set_missed_tick_behavior(MissedTickBehavior::Skip);
1252        loop {
1253            tokio::select! {
1254                _ = shutdown.cancelled() => return,
1255                _ = ticker.tick() => {}
1256            }
1257
1258            // Snapshot candidates to release locks before the per-process syscalls.
1259            let candidates: Vec<(u32, u32, PathBuf)> =
1260                {
1261                    let sup = supervisor.read().await;
1262                    let reg = registry.read().await;
1263                    reg.list()
1264                        .into_iter()
1265                        .filter_map(|config| {
1266                            let pid = sup.node_pid(config.id)?;
1267                            matches!(sup.node_status(config.id), Ok(NodeStatus::Running))
1268                                .then_some((config.id, pid, config.data_dir.clone()))
1269                        })
1270                        .collect()
1271                };
1272
1273            for (node_id, pid, data_dir) in candidates {
1274                if is_process_alive(pid) {
1275                    continue;
1276                }
1277
1278                // Adopted nodes have no owning `monitor_node`, so this poll is their only
1279                // supervisor. If such a node's process died and the on-disk binary version has
1280                // drifted from the registry, the exit was an auto-upgrade — `--stop-on-upgrade`
1281                // expects the service manager (us) to restart it. Respawn it on the new binary
1282                // and hand it a `monitor_node`, rather than leaving it dead and flagged Stopped.
1283                if supervisor.read().await.is_adopted(node_id) {
1284                    let config = {
1285                        let reg = registry.read().await;
1286                        reg.get(node_id).ok().cloned()
1287                    };
1288                    if let Some(mut config) = config {
1289                        let drifted = matches!(
1290                            extract_version(&config.binary_path).await,
1291                            Ok(disk_version) if disk_version != config.version
1292                        );
1293                        if drifted {
1294                            match respawn_upgraded_node(
1295                                &mut config,
1296                                &supervisor,
1297                                &registry,
1298                                &event_tx,
1299                            )
1300                            .await
1301                            {
1302                                Ok(child) => {
1303                                    // Now owned by this daemon: clear the adopted flag and give
1304                                    // it a monitor_node so future exits are handled there.
1305                                    supervisor.write().await.mark_owned(node_id);
1306                                    let sup_ref = Arc::clone(&supervisor);
1307                                    let reg_ref = Arc::clone(&registry);
1308                                    let ev = event_tx.clone();
1309                                    tokio::spawn(async move {
1310                                        monitor_node(child, config, sup_ref, reg_ref, ev).await;
1311                                    });
1312                                    continue;
1313                                }
1314                                Err(e) => {
1315                                    let _ = event_tx.send(NodeEvent::NodeErrored {
1316                                        node_id,
1317                                        message: format!(
1318                                            "Failed to respawn adopted node after upgrade: {e}"
1319                                        ),
1320                                    });
1321                                    let mut sup = supervisor.write().await;
1322                                    sup.update_state(node_id, NodeStatus::Errored, None);
1323                                    sup.mark_owned(node_id);
1324                                    remove_node_pid(&data_dir);
1325                                    continue;
1326                                }
1327                            }
1328                        }
1329                    }
1330                }
1331
1332                let mut sup = supervisor.write().await;
1333                // Re-check under the write lock to avoid racing with a concurrent
1334                // start/stop that flipped the state between the snapshot and now.
1335                if !liveness_should_stop(pid, sup.node_pid(node_id), sup.node_status(node_id).ok())
1336                {
1337                    continue;
1338                }
1339                sup.update_state(node_id, NodeStatus::Stopped, None);
1340                let _ = event_tx.send(NodeEvent::NodeStopped { node_id });
1341                remove_node_pid(&data_dir);
1342            }
1343        }
1344    });
1345}
1346
1347#[cfg(unix)]
1348fn pid_to_i32(pid: u32) -> Option<i32> {
1349    i32::try_from(pid).ok().filter(|&p| p > 0)
1350}
1351
1352#[cfg(unix)]
1353fn send_signal_term(pid: u32) {
1354    if let Some(pid) = pid_to_i32(pid) {
1355        unsafe {
1356            libc::kill(pid, libc::SIGTERM);
1357        }
1358    }
1359}
1360
1361#[cfg(unix)]
1362fn send_signal_kill(pid: u32) {
1363    if let Some(pid) = pid_to_i32(pid) {
1364        unsafe {
1365            libc::kill(pid, libc::SIGKILL);
1366        }
1367    }
1368}
1369
1370#[cfg(unix)]
1371fn is_process_alive(pid: u32) -> bool {
1372    let Some(pid) = pid_to_i32(pid) else {
1373        return false;
1374    };
1375    let ret = unsafe { libc::kill(pid, 0) };
1376    if ret == 0 {
1377        return true;
1378    }
1379    // EPERM means the process exists but we lack permission to signal it
1380    std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1381}
1382
1383#[cfg(windows)]
1384fn send_signal_term(pid: u32) {
1385    use windows_sys::Win32::System::Console::{
1386        AttachConsole, FreeConsole, GenerateConsoleCtrlEvent, SetConsoleCtrlHandler, CTRL_C_EVENT,
1387    };
1388
1389    unsafe {
1390        // Detach from our own console (no-op if daemon has none, which is
1391        // typical since it's spawned with DETACHED_PROCESS).
1392        FreeConsole();
1393
1394        // Attach to the target process's console and send Ctrl+C
1395        if AttachConsole(pid) != 0 {
1396            // Disable Ctrl+C handling so GenerateConsoleCtrlEvent doesn't
1397            // terminate us while we're attached to the node's console.
1398            SetConsoleCtrlHandler(None, 1);
1399            GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
1400            // Detach from the node's console first — once detached, the
1401            // async Ctrl+C event can only reach the node, not us.
1402            FreeConsole();
1403            // Brief delay to let the event drain before re-enabling our
1404            // handler. Without this, the handler thread can process the
1405            // event between FreeConsole and SetConsoleCtrlHandler.
1406            std::thread::sleep(std::time::Duration::from_millis(50));
1407            // Restore Ctrl+C handling so `daemon run` (foreground mode)
1408            // can still be stopped via Ctrl+C / tokio::signal::ctrl_c().
1409            SetConsoleCtrlHandler(None, 0);
1410        }
1411    }
1412}
1413
1414#[cfg(windows)]
1415fn send_signal_kill(pid: u32) {
1416    use windows_sys::Win32::Foundation::CloseHandle;
1417    use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
1418
1419    unsafe {
1420        let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
1421        if !handle.is_null() {
1422            TerminateProcess(handle, 1);
1423            CloseHandle(handle);
1424        }
1425    }
1426}
1427
1428#[cfg(windows)]
1429fn is_process_alive(pid: u32) -> bool {
1430    use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
1431    use windows_sys::Win32::System::Threading::{
1432        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
1433    };
1434
1435    unsafe {
1436        let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
1437        if handle.is_null() {
1438            return false;
1439        }
1440        let mut exit_code: u32 = 0;
1441        let success = GetExitCodeProcess(handle, &mut exit_code);
1442        CloseHandle(handle);
1443        success != 0 && exit_code == STILL_ACTIVE as u32
1444    }
1445}
1446
1447#[cfg(test)]
1448mod tests {
1449    use super::*;
1450    use crate::node::types::{EvmNetwork, UpgradeChannel};
1451
1452    #[tokio::test]
1453    async fn remove_dir_all_with_retry_deletes_tree_and_tolerates_missing() {
1454        let tmp = tempfile::tempdir().unwrap();
1455        let dir = tmp.path().join("node-data");
1456        std::fs::create_dir_all(dir.join("sub")).unwrap();
1457        std::fs::write(dir.join("sub").join("data.mdb"), vec![0u8; 128]).unwrap();
1458
1459        // Deletes an existing tree.
1460        remove_dir_all_with_retry(&dir).await.unwrap();
1461        assert!(!dir.exists());
1462
1463        // Idempotent: an already-gone path is treated as success (no error).
1464        remove_dir_all_with_retry(&dir).await.unwrap();
1465    }
1466
1467    #[tokio::test]
1468    async fn start_node_rejects_a_node_being_evicted() {
1469        let (tx, _rx) = broadcast::channel(16);
1470        let sup = Arc::new(RwLock::new(Supervisor::new(tx)));
1471
1472        let tmp = tempfile::tempdir().unwrap();
1473        let reg = Arc::new(RwLock::new(
1474            NodeRegistry::load(&tmp.path().join("reg.json")).unwrap(),
1475        ));
1476
1477        let config = NodeConfig {
1478            id: 7,
1479            service_name: "node7".to_string(),
1480            rewards_address: "0xabc".to_string(),
1481            data_dir: tmp.path().join("node-7"),
1482            log_dir: None,
1483            node_port: None,
1484            binary_path: "/bin/node".into(),
1485            version: "0.1.0".to_string(),
1486            env_variables: HashMap::new(),
1487            bootstrap_peers: vec![],
1488            upgrade_channel: None,
1489            evm_network: EvmNetwork::default(),
1490            eviction: None,
1491        };
1492
1493        // Flagged as evicting -> start is refused before any spawn attempt, closing the race with
1494        // the concurrent stop/delete in evict_node.
1495        sup.write().await.begin_evicting(7);
1496        let res = sup
1497            .write()
1498            .await
1499            .start_node(&config, sup.clone(), reg.clone())
1500            .await;
1501        assert!(matches!(res, Err(Error::NodeEvicted(7))));
1502
1503        // Clearing the flag removes the in-progress guard (the persisted marker takes over).
1504        sup.write().await.finish_evicting(7);
1505        assert!(!sup.read().await.evicting.contains(&7));
1506    }
1507
1508    #[test]
1509    fn adopted_flag_lifecycle() {
1510        let (tx, _rx) = broadcast::channel(16);
1511        let mut sup = Supervisor::new(tx);
1512
1513        // Nodes are not adopted by default.
1514        assert!(!sup.is_adopted(1));
1515
1516        // adopt_from_registry flags nodes carried over from a previous daemon.
1517        sup.adopted.insert(1);
1518        assert!(sup.is_adopted(1));
1519
1520        // Once this daemon (re)spawns the node and owns a monitor_node for it, the flag
1521        // clears so the liveness monitor stops treating its exit as needing a respawn.
1522        sup.mark_owned(1);
1523        assert!(!sup.is_adopted(1));
1524    }
1525
1526    // Regression test for the "running node reported as stopped after an upgrade" bug.
1527    //
1528    // A daemon-spawned node was respawned by monitor_node after an upgrade, so the recorded
1529    // state is now Running with a live PID_new. A liveness sweep that snapshotted the old,
1530    // now-dead PID then acts: it must NOT mark the node Stopped, because the running process
1531    // is the new one. `liveness_should_stop` guards against this by also requiring the recorded
1532    // PID to still match the one the sweep observed dead.
1533    #[test]
1534    fn liveness_does_not_stop_node_respawned_under_it() {
1535        let dead_snapshot_pid = 1000; // PID the sweep captured and found dead
1536        let live_respawned_pid = Some(2000); // PID_new from the upgrade respawn (alive)
1537        assert!(
1538            !liveness_should_stop(
1539                dead_snapshot_pid,
1540                live_respawned_pid,
1541                Some(NodeStatus::Running)
1542            ),
1543            "liveness must not stop a node whose PID changed under it (respawned with a live PID)"
1544        );
1545    }
1546
1547    #[test]
1548    fn build_node_args_basic() {
1549        let config = NodeConfig {
1550            id: 1,
1551            service_name: "node1".to_string(),
1552            rewards_address: "0xabc123".to_string(),
1553            data_dir: "/data/node-1".into(),
1554            log_dir: Some("/logs/node-1".into()),
1555            node_port: Some(12000),
1556            binary_path: "/bin/node".into(),
1557            version: "0.1.0".to_string(),
1558            env_variables: HashMap::new(),
1559            bootstrap_peers: vec!["peer1".to_string(), "peer2".to_string()],
1560            upgrade_channel: None,
1561            evm_network: EvmNetwork::default(),
1562            eviction: None,
1563        };
1564
1565        let args = build_node_args(&config);
1566
1567        assert!(args.contains(&"--rewards-address".to_string()));
1568        assert!(args.contains(&"0xabc123".to_string()));
1569        assert!(args.contains(&"--root-dir".to_string()));
1570        assert!(args.contains(&"/data/node-1".to_string()));
1571        assert!(args.contains(&"--enable-logging".to_string()));
1572        assert!(args.contains(&"--log-dir".to_string()));
1573        assert!(args.contains(&"/logs/node-1".to_string()));
1574        assert!(args.contains(&"--port".to_string()));
1575        assert!(args.contains(&"12000".to_string()));
1576        assert!(args.contains(&"--bootstrap".to_string()));
1577        assert!(args.contains(&"peer1".to_string()));
1578        assert!(args.contains(&"peer2".to_string()));
1579        assert!(args.contains(&"--stop-on-upgrade".to_string()));
1580        // No upgrade channel configured -> no --upgrade-channel argument.
1581        assert!(!args.contains(&"--upgrade-channel".to_string()));
1582        // EVM network defaults to Arbitrum One, emitted as a --evm-network flag.
1583        assert_eq!(evm_network_arg(&args), Some("arbitrum-one"));
1584    }
1585
1586    /// Return the value following `--evm-network` in a built arg list, if present.
1587    fn evm_network_arg(args: &[String]) -> Option<&str> {
1588        let idx = args.iter().position(|a| a == "--evm-network")?;
1589        args.get(idx + 1).map(String::as_str)
1590    }
1591
1592    #[test]
1593    fn build_node_args_emits_evm_network_flag() {
1594        let mut config = NodeConfig {
1595            id: 1,
1596            service_name: "node1".to_string(),
1597            rewards_address: "0xabc".to_string(),
1598            data_dir: "/data/node-1".into(),
1599            log_dir: None,
1600            node_port: None,
1601            binary_path: "/bin/node".into(),
1602            version: "0.1.0".to_string(),
1603            env_variables: HashMap::new(),
1604            bootstrap_peers: vec![],
1605            upgrade_channel: None,
1606            evm_network: EvmNetwork::ArbitrumSepolia,
1607            eviction: None,
1608        };
1609
1610        let args = build_node_args(&config);
1611        assert_eq!(evm_network_arg(&args), Some("arbitrum-sepolia"));
1612
1613        config.evm_network = EvmNetwork::ArbitrumOne;
1614        let args = build_node_args(&config);
1615        assert_eq!(evm_network_arg(&args), Some("arbitrum-one"));
1616    }
1617
1618    #[test]
1619    fn build_node_args_includes_upgrade_channel() {
1620        let mut config = NodeConfig {
1621            id: 1,
1622            service_name: "node1".to_string(),
1623            rewards_address: "0xabc".to_string(),
1624            data_dir: "/data/node-1".into(),
1625            log_dir: None,
1626            node_port: None,
1627            binary_path: "/bin/node".into(),
1628            version: "0.1.0".to_string(),
1629            env_variables: HashMap::new(),
1630            bootstrap_peers: vec![],
1631            upgrade_channel: Some(UpgradeChannel::Beta),
1632            evm_network: EvmNetwork::default(),
1633            eviction: None,
1634        };
1635
1636        let args = build_node_args(&config);
1637        let idx = args
1638            .iter()
1639            .position(|a| a == "--upgrade-channel")
1640            .expect("--upgrade-channel should be present");
1641        assert_eq!(args[idx + 1], "beta");
1642
1643        config.upgrade_channel = Some(UpgradeChannel::Stable);
1644        let args = build_node_args(&config);
1645        let idx = args.iter().position(|a| a == "--upgrade-channel").unwrap();
1646        assert_eq!(args[idx + 1], "stable");
1647    }
1648
1649    #[test]
1650    fn build_node_args_minimal() {
1651        let config = NodeConfig {
1652            id: 1,
1653            service_name: "node1".to_string(),
1654            rewards_address: "0xabc".to_string(),
1655            data_dir: "/data/node-1".into(),
1656            log_dir: None,
1657            node_port: None,
1658            binary_path: "/bin/node".into(),
1659            version: "0.1.0".to_string(),
1660            env_variables: HashMap::new(),
1661            bootstrap_peers: vec![],
1662            upgrade_channel: None,
1663            evm_network: EvmNetwork::default(),
1664            eviction: None,
1665        };
1666
1667        let args = build_node_args(&config);
1668
1669        assert!(args.contains(&"--rewards-address".to_string()));
1670        assert!(args.contains(&"--root-dir".to_string()));
1671        assert!(!args.contains(&"--enable-logging".to_string()));
1672        assert!(!args.contains(&"--log-dir".to_string()));
1673        assert!(!args.contains(&"--port".to_string()));
1674        assert!(!args.contains(&"--bootstrap".to_string()));
1675        assert!(args.contains(&"--stop-on-upgrade".to_string()));
1676    }
1677
1678    #[test]
1679    fn record_crash_backoff_increases() {
1680        let (tx, _rx) = broadcast::channel(16);
1681        let mut sup = Supervisor::new(tx);
1682
1683        // Insert a running node
1684        sup.node_states.insert(
1685            1,
1686            NodeRuntime {
1687                status: NodeStatus::Running,
1688                pid: Some(100),
1689                started_at: Some(Instant::now()),
1690                restart_count: 0,
1691                first_crash_at: None,
1692            },
1693        );
1694
1695        let (should_restart, attempt, backoff) = sup.record_crash(1);
1696        assert!(should_restart);
1697        assert_eq!(attempt, 1);
1698        assert_eq!(backoff, Duration::from_secs(1));
1699
1700        let (should_restart, attempt, backoff) = sup.record_crash(1);
1701        assert!(should_restart);
1702        assert_eq!(attempt, 2);
1703        assert_eq!(backoff, Duration::from_secs(2));
1704
1705        let (should_restart, attempt, backoff) = sup.record_crash(1);
1706        assert!(should_restart);
1707        assert_eq!(attempt, 3);
1708        assert_eq!(backoff, Duration::from_secs(4));
1709
1710        let (should_restart, attempt, backoff) = sup.record_crash(1);
1711        assert!(should_restart);
1712        assert_eq!(attempt, 4);
1713        assert_eq!(backoff, Duration::from_secs(8));
1714
1715        // 5th crash within window → errored
1716        let (should_restart, attempt, _) = sup.record_crash(1);
1717        assert!(!should_restart);
1718        assert_eq!(attempt, 5);
1719        assert_eq!(sup.node_states[&1].status, NodeStatus::Errored);
1720    }
1721
1722    #[test]
1723    fn node_counts_tracks_states() {
1724        let (tx, _rx) = broadcast::channel(16);
1725        let mut sup = Supervisor::new(tx);
1726
1727        sup.node_states.insert(
1728            1,
1729            NodeRuntime {
1730                status: NodeStatus::Running,
1731                pid: Some(100),
1732                started_at: Some(Instant::now()),
1733                restart_count: 0,
1734                first_crash_at: None,
1735            },
1736        );
1737        sup.node_states.insert(
1738            2,
1739            NodeRuntime {
1740                status: NodeStatus::Stopped,
1741                pid: None,
1742                started_at: None,
1743                restart_count: 0,
1744                first_crash_at: None,
1745            },
1746        );
1747        sup.node_states.insert(
1748            3,
1749            NodeRuntime {
1750                status: NodeStatus::Errored,
1751                pid: None,
1752                started_at: None,
1753                restart_count: 5,
1754                first_crash_at: None,
1755            },
1756        );
1757
1758        let (running, stopped, errored) = sup.node_counts();
1759        assert_eq!(running, 1);
1760        assert_eq!(stopped, 1);
1761        assert_eq!(errored, 1);
1762    }
1763
1764    #[test]
1765    fn upgrade_restart_exit_code_covers_unix_and_windows() {
1766        // Unix upgrade exit and the Windows RESTART_EXIT_CODE both count as candidate upgrade
1767        // restarts; anything else (crash codes, signals with no code) does not. The version-drift
1768        // check in `monitor_node_inner` is what actually confirms an upgrade — this only gates it.
1769        assert!(is_upgrade_restart_exit_code(Some(0)));
1770        assert!(is_upgrade_restart_exit_code(Some(RESTART_EXIT_CODE)));
1771        assert!(!is_upgrade_restart_exit_code(Some(1)));
1772        assert!(!is_upgrade_restart_exit_code(Some(101)));
1773        assert!(!is_upgrade_restart_exit_code(None));
1774    }
1775
1776    #[tokio::test]
1777    async fn stop_node_not_found() {
1778        let (tx, _rx) = broadcast::channel(16);
1779        let mut sup = Supervisor::new(tx);
1780
1781        let result = sup.stop_node(999).await;
1782        assert!(matches!(result, Err(Error::NodeNotFound(999))));
1783    }
1784
1785    #[tokio::test]
1786    async fn stop_node_not_running() {
1787        let (tx, _rx) = broadcast::channel(16);
1788        let mut sup = Supervisor::new(tx);
1789
1790        sup.node_states.insert(
1791            1,
1792            NodeRuntime {
1793                status: NodeStatus::Stopped,
1794                pid: None,
1795                started_at: None,
1796                restart_count: 0,
1797                first_crash_at: None,
1798            },
1799        );
1800
1801        let result = sup.stop_node(1).await;
1802        assert!(matches!(result, Err(Error::NodeNotRunning(1))));
1803    }
1804
1805    #[tokio::test]
1806    async fn stop_all_nodes_mixed_states() {
1807        let (tx, _rx) = broadcast::channel(16);
1808        let mut sup = Supervisor::new(tx);
1809
1810        // Node 1: running (but with a fake PID that won't exist)
1811        sup.node_states.insert(
1812            1,
1813            NodeRuntime {
1814                status: NodeStatus::Running,
1815                pid: Some(999999),
1816                started_at: Some(Instant::now()),
1817                restart_count: 0,
1818                first_crash_at: None,
1819            },
1820        );
1821        // Node 2: already stopped
1822        sup.node_states.insert(
1823            2,
1824            NodeRuntime {
1825                status: NodeStatus::Stopped,
1826                pid: None,
1827                started_at: None,
1828                restart_count: 0,
1829                first_crash_at: None,
1830            },
1831        );
1832
1833        let configs = vec![(1, "node1".to_string()), (2, "node2".to_string())];
1834
1835        let result = sup.stop_all_nodes(&configs).await;
1836
1837        assert_eq!(result.stopped.len(), 1);
1838        assert_eq!(result.stopped[0].node_id, 1);
1839        assert_eq!(result.stopped[0].service_name, "node1");
1840        assert_eq!(result.already_stopped, vec![2]);
1841        assert!(result.failed.is_empty());
1842    }
1843}