rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Upgrading the daemon in place (#1713): noticing that its executable was
//! replaced, waiting until no job is in progress, then restarting, which
//! re-executes the replacement as the same process.
//!
//! The daemon checks its executable every [`UPGRADE_CHECK_INTERVAL`], and at
//! once when a client newer than the daemon says hello. A replacement must
//! print its rho version before the daemon trusts it (see
//! [`Executable::probe`]); from then on `rho/daemon/status` reports the
//! upgrade pending, and the daemon keeps serving and taking new work until a
//! check finds nothing the restart would cut short: no job in progress, no
//! login under way, and no loaded session with work of its own (see
//! `Sessions::upgrade_blockers`). Jobs waiting for input count as in
//! progress until a restarted daemon can ask again (#1660, #1661).
//!
//! A newer client whose daemon's executable was not replaced, as when an
//! installer put the new version at another path, cannot upgrade it; the
//! daemon logs that once per client version.
//!
//! An update a person's frontend ran on the daemon's machine
//! (`machine_update.rs`) holds the watch until it is settled, then says how
//! the daemon moves onto the rho it installed ([`Follow`]).

use std::{
    future::Future,
    sync::{Mutex, MutexGuard, PoisonError},
    time::Duration,
};

use rho_protocol::ClientInfo;
use tokio::sync::Notify;

use super::{machine_update::Follow, DaemonHost};
use crate::daemon::{Executable, FileIdentity, ProbeError};

/// How often the daemon checks whether its executable was replaced and,
/// once it was, whether it is idle.
//
// Each check is one `stat(2)` of the executable (2.4 µs median over 10,000
// runs on ext4, measured through Python's `os.stat`, so an upper bound) and,
// while an upgrade waits, one count of the job records under their lock. 1 s keeps that negligible while bounding how long an
// idle daemon runs a replaced binary, and how long an upgrade waits after
// the last job ends. docs/protocol.md states it, for how late a restart may
// notice a replaced executable (`rho/daemon/stopping`).
const UPGRADE_CHECK_INTERVAL: Duration = Duration::from_secs(1);

/// What the daemon knows of its upgrade.
#[derive(Default)]
pub(super) struct Upgrades {
    /// The version of the replacement the daemon waits to re-execute.
    pending: Mutex<Option<String>>,
    /// The newest version of a client newer than the daemon.
    newer_client: Mutex<Option<String>>,
    /// Wakes the watch once such a client said hello.
    heard_newer: Notify,
}

/// Where the watch stands between checks.
#[derive(Default)]
pub(super) struct Watch {
    /// The replacement last probed to an answer, whether it proved itself
    /// rho or not, so each is run once; one that could not run is tried
    /// again at the next check.
    probed: Option<FileIdentity>,
    /// The newer client version last warned about.
    warned: Option<String>,
}

/// What a check found the daemon should do.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Check {
    /// Keep running this binary.
    Wait,
    /// Restart once no job is in progress.
    Upgrade,
}

impl Upgrades {
    /// Notes the client a connection's hello named: a newer one wakes the
    /// watch, so the daemon looks for its replacement at once.
    pub(super) fn heard(&self, client: &ClientInfo) {
        if !crate::update::version_is_newer(&client.version, env!("CARGO_PKG_VERSION")) {
            return;
        }
        let mut newest = lock(&self.newer_client);
        if newest
            .as_deref()
            .is_none_or(|newest| crate::update::version_is_newer(&client.version, newest))
        {
            *newest = Some(client.version.clone());
        }
        drop(newest);
        self.heard_newer.notify_one();
    }

    /// The version of the replacement the daemon waits to re-execute.
    pub(super) fn pending(&self) -> Option<String> {
        lock(&self.pending).clone()
    }

    /// Resolves after `interval`, or sooner once a newer client said hello.
    pub(super) async fn next_check(&self, interval: &mut tokio::time::Interval) {
        tokio::select! {
            _ = interval.tick() => {}
            () = self.heard_newer.notified() => {}
        }
    }

    /// Checks `executable` for a replacement, running a new one with
    /// `--version`, and records what the upgrade waits for.
    pub(super) async fn check(&self, executable: &Executable, watch: &mut Watch) -> Check {
        let Some(replacement) = executable.replacement() else {
            *lock(&self.pending) = None;
            watch.probed = None;
            let newer_client = lock(&self.newer_client).clone();
            if newer_client.is_some() && watch.warned != newer_client {
                tracing::warn!(
                    client = newer_client.as_deref(),
                    executable = %executable.path().display(),
                    "a newer rho client connected, but the daemon's executable was not \
                     replaced; restart the daemon from the newer rho to upgrade it"
                );
                watch.warned = newer_client;
            }
            return Check::Wait;
        };
        if watch.probed != Some(replacement.identity) {
            let probed = executable.probe().await;
            match &probed {
                Ok(version) => tracing::info!(
                    %version,
                    executable = %executable.path().display(),
                    "the daemon's executable was replaced; upgrading once nothing would be cut short"
                ),
                Err(error) if error.is_transient() => tracing::debug!(
                    %error,
                    executable = %executable.path().display(),
                    "could not probe the daemon's replaced executable; trying again"
                ),
                Err(error) => tracing::warn!(
                    %error,
                    executable = %executable.path().display(),
                    "the daemon's executable was replaced by one that is not rho; not upgrading"
                ),
            }
            if !probed.as_ref().is_err_and(ProbeError::is_transient) {
                watch.probed = Some(replacement.identity);
            }
            *lock(&self.pending) = probed.ok();
        }
        match *lock(&self.pending) {
            Some(_) => Check::Upgrade,
            None => Check::Wait,
        }
    }
}

impl DaemonHost {
    /// Restarts the daemon once `executable` was replaced and nothing would
    /// be cut short, checking every [`UPGRADE_CHECK_INTERVAL`], or moves it
    /// onto the rho an update on its machine installed, as that update
    /// said; ends once the daemon stops. While an update runs or waits to
    /// be settled, it does neither.
    pub(in crate::app) async fn upgrade_when_replaced(&self, executable: &Executable) {
        let mut checks = tokio::time::interval(UPGRADE_CHECK_INTERVAL);
        checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        let mut watch = Watch::default();
        loop {
            tokio::select! {
                () = self.upgrades.next_check(&mut checks) => {}
                () = self.shutdown.requested() => return,
            }
            let mut watching = Watching {
                host: self,
                executable,
                watch: &mut watch,
            };
            match at_check(&mut watching).await {
                None => {}
                Some((Begin::Restart, follow)) => {
                    tracing::info!(?follow, "upgrading in place");
                    self.begin_restart();
                    return;
                }
                Some((Begin::Replace, follow)) => {
                    tracing::info!(
                        ?follow,
                        "stopping for the rho an update installed at another path"
                    );
                    self.begin_replace();
                    return;
                }
            }
        }
    }

    /// Claims the daemon idle for an upgrade, unless anything would be cut
    /// short; once claimed, the restart follows at once. Closing the job
    /// registry is the claim: no turn starts after it. It closes only if no
    /// job went in progress since the daemon was found idle, before the
    /// other checks, so a turn that began and ended meanwhile cannot leave
    /// work those checks missed. Background work and subagents both start in
    /// a turn; only a login or a settings change sent between the checks and
    /// the close escapes them, and the restart then ends it as a stop would.
    fn claim_idle(&self) -> bool {
        let Some(idle) = self.jobs.idle() else {
            return false;
        };
        super::work_outside_jobs(&self.logins, &self.sessions) == 0
            && self.jobs.close_if_still(idle)
    }
}

/// How the daemon moves onto a new rho.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Begin {
    /// Re-executes the rho at its path.
    Restart,
    /// Stops, so the next client starts the rho at another path.
    Replace,
}

/// What a check asks of the daemon; tests give a stand-in.
trait Watched {
    /// What updates on the daemon's machine leave the watch to do
    /// ([`super::machine_update::Updates::follow`]).
    fn follow(&self) -> Follow;
    /// Whether the daemon's executable was replaced by a rho, probed, it
    /// can restart onto.
    fn replaced(&mut self) -> impl Future<Output = bool> + Send;
    /// Commits the daemon to the move `follow` asks, claiming it idle
    /// ([`DaemonHost::claim_idle`]) first when `once_idle`; false, and no
    /// commitment, when an update started or settled since the check saw
    /// `follow`, or the daemon is not idle
    /// ([`super::machine_update::Updates::commit`]). Once it committed, the
    /// move must follow.
    fn commit(&mut self, follow: Follow, once_idle: bool) -> bool;
}

/// What the watch begins at a check, and the [`Follow`] it began it for:
/// nothing while an update holds it; otherwise an upgrade onto a replaced
/// executable once idle, or the move a settled update asked for. A restart
/// runs the file at the daemon's path, so it begins only once the watch
/// probed a rho there, also for an update that asked for one now: until
/// then the check waits, as one without an update would. A probe can take
/// [`crate::daemon::Executable::probe`]'s time, during which an update may
/// start or settle, so the commitment looks at updates again.
async fn at_check(watched: &mut impl Watched) -> Option<(Begin, Follow)> {
    let follow = watched.follow();
    let (begin, once_idle) = match follow {
        Follow::Held => return None,
        Follow::Watch => (Begin::Restart, true),
        Follow::RestartNow => (Begin::Restart, false),
        Follow::Replace { once_idle } => (Begin::Replace, once_idle),
    };
    if begin == Begin::Restart && !watched.replaced().await {
        return None;
    }
    watched.commit(follow, once_idle).then_some((begin, follow))
}

/// The daemon at a check, watching `executable`.
struct Watching<'a> {
    host: &'a DaemonHost,
    executable: &'a Executable,
    watch: &'a mut Watch,
}

impl Watched for Watching<'_> {
    fn follow(&self) -> Follow {
        self.host.machine.updates().follow()
    }

    async fn replaced(&mut self) -> bool {
        self.host.upgrades.check(self.executable, self.watch).await == Check::Upgrade
    }

    fn commit(&mut self, follow: Follow, once_idle: bool) -> bool {
        let host = self.host;
        host.machine
            .updates()
            .commit(follow, || !once_idle || host.claim_idle())
    }
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    // Each value is replaced whole, so a panic cannot leave one half-set.
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

#[cfg(test)]
#[path = "upgrade_tests.rs"]
mod tests;