orch-cli 0.113.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::TaskStatus;
use crate::store::TaskStore;
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
    pub(crate) fn fields(&self) -> [(&'static str, serde_json::Value); 2] {
        [
            ("owner_node", serde_json::json!(self.node)),
            ("owner_term", serde_json::json!(self.term)),
        ]
    }
}

/// 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`)
pub(crate) async fn place(
    store: &TaskStore,
    repo: &str,
    agent: Option<&str>,
    status: TaskStatus,
) -> Placement {
    let Some(node) = store.node() else {
        return Placement::Single;
    };
    let 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;
        }
    };
    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 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");
    }
}

#[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"));
    }
}