orch-cli 0.117.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
//! A cluster node starts the task and review runs the leader assigned to it. The Raft log carries
//! the assignment, so there is no separate leader to worker protocol

use std::sync::Arc;

use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use tokio::sync::{RwLock, Semaphore, mpsc};

use super::ProjectEngine;
use super::dispatch::{Run, start_run};
use crate::backends::Status;
use crate::channels::capture::CaptureService;
use crate::engine::chore::{self, Checkout, Execute};
use crate::engine::router::{Router, get_route_result};
use crate::engine::runner::WeightSignal;
use crate::engine::subscribers::review::{ReviewRun, run_review};
use crate::engine::tasks;
use crate::engine::tasks::dispatch_guard::DispatchGuard;
use crate::engine::tick::repo_context::REPO_CONTEXT;
use crate::store::cluster::Node;
use crate::store::{Task, TaskStatus, TaskStore};
use crate::sys::tmux::TmuxManager;

/// The engine state a worker pass needs
#[derive(Clone, Copy)]
pub(crate) struct Worker<'a> {
    pub(crate) tmux: &'a Arc<TmuxManager>,
    pub(crate) capture: &'a Arc<CaptureService>,
    pub(crate) semaphore: &'a Arc<Semaphore>,
    pub(crate) review_semaphore: &'a Arc<Semaphore>,
    pub(crate) router: &'a Arc<RwLock<Router>>,
    pub(crate) weight_tx: &'a mpsc::Sender<WeightSignal>,
    pub(crate) dispatching: &'a Arc<DashMap<String, String>>,
}

/// Start every run assigned to this node that is not running yet. Does nothing on one machine
pub(crate) async fn run_assigned(engines: &[ProjectEngine], worker: Worker<'_>) {
    let Some(store) = engines.first().map(|e| &e.store) else {
        return;
    };
    let Some(node) = store.node().cloned() else {
        return;
    };
    // Leader work that needs a checkout of a project this node hosts
    let checkout: Arc<dyn Execute> = Arc::new(Checkout {
        dirs: engines
            .iter()
            .filter(|e| e.hosted)
            .map(|e| (e.repo.clone(), e.project_dir.clone()))
            .collect(),
    });
    chore::run_assigned(store, &checkout).await;
    end_moved_sessions(store, worker.tmux, &node).await;
    for engine in engines {
        REPO_CONTEXT
            .scope(engine.repo.clone(), async {
                start_tasks(engine, worker, &node).await;
                start_reviews(engine, worker, &node).await;
            })
            .await;
    }
}

/**
 * Kill this node's sessions for the tasks `orch task move` gave to another node. The worktree and
 * the local branch stay, they may hold commits that were never pushed. A node that was offline
 * does this when it is back
 **/
pub(crate) async fn end_moved_sessions(store: &TaskStore, tmux: &TmuxManager, node: &Node) {
    let ids = match store.moved_from(node.name()).await {
        Ok(ids) => ids,
        Err(e) => {
            tracing::warn!(err = %e, "failed to list the tasks that moved away");
            return;
        }
    };
    'ids: for id in ids {
        if let Ok(task) = store.get(id).await {
            let ext = tasks::store_task_to_external(&task);
            for name in [ext.id.0.clone(), format!("{}-review", ext.id.0)] {
                let session = tmux.session_name(&task.repo, &name);
                if !tmux.session_exists(&session).await {
                    continue;
                }

                tracing::info!(task_id = %ext.id.0, session, "the task moved to another node, killing its session here");
                if let Err(e) = tmux.kill_session(&session).await {
                    tracing::warn!(session, err = %e, "failed to kill the session of a moved task");
                    continue 'ids;
                }
            }
        }

        if let Err(e) = store.clear_moved(id).await {
            tracing::warn!(task_id = id, err = %e, "failed to clear the move");
        }
    }
}

async fn owned(engine: &ProjectEngine, node: &Node, status: TaskStatus) -> Vec<Task> {
    match engine.store.list_by_status(&engine.repo, status).await {
        Ok(tasks) => tasks
            .into_iter()
            .filter(|t| t.owner_node.as_deref() == Some(node.name()))
            .collect(),
        Err(e) => {
            tracing::warn!(err = %e, status = status.as_str(), "failed to list assigned runs");
            Vec::new()
        }
    }
}

/// Claim the dispatch key, unless this node already runs the task
fn claim(
    dispatching: &Arc<DashMap<String, String>>,
    key: String,
    id: &str,
) -> Option<DispatchGuard> {
    match dispatching.entry(key.clone()) {
        Entry::Occupied(_) => None,
        Entry::Vacant(slot) => {
            slot.insert(id.to_string());
            Some(DispatchGuard::new(Arc::clone(dispatching), key))
        }
    }
}

/**
 * True when the assignment may start here. One from a term older than an assignment this node
 * already started goes back to `back`, so the current leader assigns it again. The release only
 * applies while this node still holds it under that term
 **/
async fn accept(engine: &ProjectEngine, node: &Node, task: &Task, back: Status) -> bool {
    let term = task.owner_term.unwrap_or(0);
    if node.accept_assignment(u64::try_from(term).unwrap_or(0)) {
        return true;
    }

    let ext = tasks::store_task_to_external(task);
    tracing::warn!(task_id = %ext.id.0, term, "rejecting an assignment from an older term");
    let status = match back {
        Status::NeedsReview => TaskStatus::NeedsReview,
        _ => TaskStatus::Routed,
    };
    match engine
        .store
        .release_assignment(task.id, node.name(), term, status)
        .await
    {
        Ok(true) if !tasks::is_internal_id(&ext.id.0) => {
            if let Err(e) = engine.backend.update_status(&ext.id, back).await {
                tracing::warn!(task_id = %ext.id.0, err = %e, "failed to mirror the released status");
            }
        }
        Ok(_) => {}
        Err(e) => tracing::warn!(task_id = %ext.id.0, err = %e, "failed to release the assignment"),
    }

    false
}

async fn start_tasks(engine: &ProjectEngine, worker: Worker<'_>, node: &Node) {
    for task in owned(engine, node, TaskStatus::InProgress).await {
        let ext = tasks::store_task_to_external(&task);
        let task_id = ext.id.0.clone();
        let Some(guard) = claim(
            worker.dispatching,
            format!("{}/{task_id}", engine.repo),
            &task_id,
        ) else {
            continue;
        };
        if worker
            .tmux
            .session_exists(&worker.tmux.session_name(&engine.repo, &task_id))
            .await
        {
            continue;
        }

        if !accept(engine, node, &task, Status::Routed).await {
            continue;
        }

        let Ok(permit) = Arc::clone(worker.semaphore).try_acquire_owned() else {
            tracing::debug!(
                task_id,
                "no free slot for an assigned task, next tick tries again"
            );
            return;
        };
        let route = get_route_result(&engine.store, &engine.repo, &task_id)
            .await
            .ok();
        tracing::info!(task_id, term = task.owner_term, "starting an assigned task");
        let run = Run {
            backend: Arc::clone(&engine.backend),
            tmux: Arc::clone(worker.tmux),
            runner: Arc::clone(&engine.runner),
            capture: Arc::clone(worker.capture),
            task_manager: Arc::clone(&engine.task_manager),
            weight_tx: worker.weight_tx.clone(),
            store: Arc::clone(&engine.store),
            repo: engine.repo.clone(),
        };
        start_run(run, ext, route, guard, permit).await;
    }
}

async fn start_reviews(engine: &ProjectEngine, worker: Worker<'_>, node: &Node) {
    for task in owned(engine, node, TaskStatus::InReview).await {
        let ext = tasks::store_task_to_external(&task);
        let task_id = ext.id.0.clone();
        let Some(guard) = claim(
            worker.dispatching,
            format!("{}/{task_id}", engine.repo),
            &task_id,
        ) else {
            continue;
        };
        let session = worker
            .tmux
            .session_name(&engine.repo, &format!("{task_id}-review"));
        if worker.tmux.session_exists(&session).await {
            continue;
        }

        // A recorded decision means the review ran and the task waits on the merge
        if matches!(
            engine.store.in_review_entry(task.id).await,
            Ok(Some((_, true)))
        ) {
            continue;
        }

        if !accept(engine, node, &task, Status::NeedsReview).await {
            continue;
        }

        let Ok(permit) = Arc::clone(worker.review_semaphore).try_acquire_owned() else {
            tracing::debug!(
                task_id,
                "no free slot for an assigned review, next tick tries again"
            );
            return;
        };
        tracing::info!(
            task_id,
            term = task.owner_term,
            "starting an assigned review"
        );
        let run = ReviewRun {
            backend: Arc::clone(&engine.backend),
            tmux: Arc::clone(worker.tmux),
            router: Arc::clone(worker.router),
            task_manager: Arc::clone(&engine.task_manager),
            store: Arc::clone(&engine.store),
            repo: engine.repo.clone(),
        };
        tokio::spawn(REPO_CONTEXT.scope(engine.repo.clone(), run_review(run, ext, guard, permit)));
    }
}