orch-cli 0.119.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! Assignment of task and review runs to the nodes of a cluster. The leader picks a node from the
//! registry and writes `owner_node` and its term with the status change, see `docs/content/docs/cluster.md`

use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};

use crate::store::Task;
use crate::store::TaskStatus;
use crate::store::TaskStore;
use crate::store::cluster::lease::{self, Lease};
use crate::store::cluster::registry::{self, Entry};

/// The `last_error` of a routed task that waits for a node, followed by the repo
pub(crate) const WAITING_PREFIX: &str = "waiting for a node with ";

/// A run the leader gives to one node, under the leader's term
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Assignment {
    pub(crate) node: String,
    pub(crate) term: u64,
}

impl Assignment {
    /// The task fields written with the status change, in the same command. The first lease
    /// covers the time until the node sees the assignment and renews it
    pub(crate) fn fields(&self) -> [(&'static str, serde_json::Value); 3] {
        [
            ("owner_node", serde_json::json!(self.node)),
            ("owner_term", serde_json::json!(self.term)),
            (
                "lease_until",
                serde_json::json!(Lease::load().until(Utc::now())),
            ),
        ]
    }
}

/// Where a run goes
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Placement {
    /// No cluster: run here, as on one machine
    Single,
    /// This node runs it
    Here(Assignment),
    /// Another node runs it once it sees the assignment
    There(Assignment),
    /// No online node hosts the repo with the agent and a free slot
    Waiting,
}

/**
 * Pick the node for a run of `repo`. It must be online, not a witness, host the repo, have `agent`
 * (any agent when None) and have fewer than `max_parallel` runs of this kind. The node with the
 * most free slots wins, then this node, then the lowest name, so every leader picks the same way
 **/
pub(crate) fn choose(
    entries: &[Entry],
    running: &HashMap<String, usize>,
    me: &str,
    repo: &str,
    agent: Option<&str>,
    now: DateTime<Utc>,
) -> Option<String> {
    entries
        .iter()
        .filter(|e| e.online_at(now) && e.can_run(repo, agent))
        .filter_map(|e| {
            let busy = running.get(&e.node).copied().unwrap_or(0);
            let free = e.max_parallel.checked_sub(busy).filter(|f| *f > 0)?;
            Some((free, e))
        })
        .max_by(|(fa, a), (fb, b)| {
            fa.cmp(fb)
                .then_with(|| (a.node == me).cmp(&(b.node == me)))
                .then_with(|| b.node.cmp(&a.node))
        })
        .map(|(_, e)| e.node.clone())
}

/// Place a run of `repo` that moves the task to `status` (`in_progress` or `in_review`). A task
/// `orch task move` pinned to a node runs only there
pub(crate) async fn place(
    store: &TaskStore,
    repo: &str,
    agent: Option<&str>,
    status: TaskStatus,
    pinned: Option<&str>,
) -> Placement {
    let Some(node) = store.node() else {
        return Placement::Single;
    };
    let mut entries = match registry::read(store).await {
        Ok(entries) => entries,
        Err(e) => {
            tracing::warn!(repo, err = %e, "cannot read the node registry, the run waits");
            return Placement::Waiting;
        }
    };
    if let Some(pinned) = pinned {
        entries.retain(|e| e.node == pinned);
    }

    let running = match store.running_per_node(status).await {
        Ok(running) => running,
        Err(e) => {
            tracing::warn!(repo, err = %e, "cannot count the runs per node, the run waits");
            return Placement::Waiting;
        }
    };
    let Some(chosen) = choose(&entries, &running, node.name(), repo, agent, Utc::now()) else {
        return Placement::Waiting;
    };
    let assignment = Assignment {
        term: node.term(),
        node: chosen,
    };
    if assignment.node == node.name() {
        Placement::Here(assignment)
    } else {
        Placement::There(assignment)
    }
}

/// The node `orch task move` gave a routed task to, read from the store
pub(crate) async fn pinned_node(store: &TaskStore, repo: &str, task_id: &str) -> Option<String> {
    store.node()?;
    let id = store.resolve_task_id(repo, task_id).await.ok()??;
    let task = store.get(id).await.ok()?;
    (task.status == TaskStatus::Routed)
        .then_some(task.owner_node)
        .flatten()
}

/// The agents an online host of `repo` can run, for the router. None on one machine, or when no
/// host is online, so routing goes on and the task waits for a node at dispatch
pub(crate) async fn host_agents(store: &TaskStore, repo: &str) -> Option<HashSet<String>> {
    store.node()?;
    let entries = registry::read(store).await.ok()?;
    let now = Utc::now();
    let agents: HashSet<String> = entries
        .iter()
        .filter(|e| e.online_at(now) && !e.witness && e.hosts(repo))
        .flat_map(|e| e.agents.iter().cloned())
        .collect();
    (!agents.is_empty()).then_some(agents)
}

/// Show on the task that it waits for a node. Written once, so it neither burns an attempt nor
/// touches `updated_at`
pub(crate) async fn note_waiting(store: &TaskStore, repo: &str, task_id: &str) {
    let Ok(Some(id)) = store.resolve_task_id(repo, task_id).await else {
        return;
    };
    let Ok(task) = store.get(id).await else {
        return;
    };
    if task.last_error.starts_with(WAITING_PREFIX) {
        tracing::debug!(task_id, repo, "still waiting for a node");
        return;
    }

    tracing::info!(task_id, repo, "no online node can run the task, it waits");
    let reason = format!("{WAITING_PREFIX}{repo}");
    if let Err(e) = store
        .set_fields_silent(id, &[("last_error", serde_json::json!(reason))])
        .await
    {
        tracing::warn!(task_id, err = %e, "failed to record the wait for a node");
    }
}

/// The `last_error` of a task whose owner's lease ran out
pub(crate) fn owner_waiting(node: &str) -> String {
    format!("waiting for {node}, its lease expired")
}

/**
 * True when another node runs the task, so this node's tmux sessions say nothing about it. The
 * owner's lease tells whether that node is alive. When it expired, the task shows that it waits for
 * the node and keeps its owner: the work may exist only there, and the node resumes it when it is
 * back. Nothing here burns an attempt or touches `updated_at`
 **/
pub(crate) async fn held_elsewhere(store: &TaskStore, task: &Task) -> bool {
    if !store.runs_elsewhere(task) {
        return false;
    }

    let Some(owner) = task.owner_node.as_deref() else {
        return true;
    };
    let note = owner_waiting(owner);
    let alive = lease::valid(task.lease_until.as_deref(), Utc::now());
    let last_error = match (alive, task.last_error == note) {
        (true, true) => {
            tracing::info!(
                task_id = task.id,
                node = owner,
                "the owner renewed its lease"
            );
            String::new()
        }
        (false, false) => {
            tracing::warn!(
                task_id = task.id,
                node = owner,
                lease_until = task.lease_until.as_deref().unwrap_or("-"),
                "the owner's lease expired, the task waits for it"
            );
            note
        }
        _ => return true,
    };
    if let Err(e) = store
        .set_fields_silent(task.id, &[("last_error", serde_json::json!(last_error))])
        .await
    {
        tracing::warn!(task_id = task.id, err = %e, "failed to record the owner's lease state");
    }

    true
}

/// `held_elsewhere` for a task known by its repo and id. False when the task is not found
pub(crate) async fn held_elsewhere_by_ref(store: &TaskStore, repo: &str, task_id: &str) -> bool {
    if store.node().is_none() {
        return false;
    }

    let Ok(Some(id)) = store.resolve_task_id(repo, task_id).await else {
        return false;
    };
    match store.get(id).await {
        Ok(task) => held_elsewhere(store, &task).await,
        Err(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    fn entry(node: &str, projects: &[&str], agents: &[&str], max: usize) -> Entry {
        Entry {
            node: node.into(),
            projects: projects.iter().map(ToString::to_string).collect(),
            agents: agents.iter().map(ToString::to_string).collect(),
            max_parallel: max,
            version: None,
            witness: false,
            seen: Utc::now().to_rfc3339(),
        }
    }

    #[test]
    fn a_repo_only_one_node_hosts_goes_to_that_node() {
        let entries = [
            entry("a", &["o/one"], &["claude"], 4),
            entry("b", &["o/one", "o/two"], &["claude"], 4),
        ];
        let got = choose(
            &entries,
            &HashMap::new(),
            "a",
            "o/two",
            Some("claude"),
            Utc::now(),
        );
        assert_eq!(got.as_deref(), Some("b"));
    }

    #[test]
    fn an_agent_only_one_node_has_goes_to_that_node() {
        let entries = [
            entry("a", &["o/r"], &["claude"], 4),
            entry("b", &["o/r"], &["claude", "codex"], 4),
        ];
        let got = choose(
            &entries,
            &HashMap::new(),
            "a",
            "o/r",
            Some("codex"),
            Utc::now(),
        );
        assert_eq!(got.as_deref(), Some("b"));
    }

    #[test]
    fn a_full_node_gets_nothing() {
        let entries = [
            entry("a", &["o/r"], &["claude"], 2),
            entry("b", &["o/r"], &["claude"], 1),
        ];
        let running = HashMap::from([("a".to_string(), 2), ("b".to_string(), 0)]);
        let got = choose(&entries, &running, "a", "o/r", Some("claude"), Utc::now());
        assert_eq!(got.as_deref(), Some("b"));

        let running = HashMap::from([("a".to_string(), 2), ("b".to_string(), 1)]);
        assert_eq!(
            choose(&entries, &running, "a", "o/r", Some("claude"), Utc::now()),
            None
        );
    }

    #[test]
    fn offline_nodes_and_witnesses_get_nothing() {
        let mut offline = entry("b", &["o/r"], &["claude"], 4);
        offline.seen = (Utc::now() - Duration::minutes(10)).to_rfc3339();
        let mut witness = entry("w", &["o/r"], &["claude"], 4);
        witness.witness = true;
        let entries = [offline, witness];
        assert_eq!(
            choose(
                &entries,
                &HashMap::new(),
                "a",
                "o/r",
                Some("claude"),
                Utc::now()
            ),
            None
        );
    }

    #[test]
    fn a_tie_goes_to_this_node() {
        let entries = [
            entry("a", &["o/r"], &["claude"], 2),
            entry("b", &["o/r"], &["claude"], 2),
        ];
        let got = choose(&entries, &HashMap::new(), "b", "o/r", None, Utc::now());
        assert_eq!(got.as_deref(), Some("b"));
        let got = choose(&entries, &HashMap::new(), "c", "o/r", None, Utc::now());
        assert_eq!(got.as_deref(), Some("a"));
    }
}