rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A Rho subagent run's slot in the global pool, which it gives back while
//! it waits for an answer to its question and takes again, in line, before
//! its next model request.
//!
//! A subagent's question goes to the session that started it, and the agent
//! that answers it may itself need a slot to do so: a started session that
//! answers through `sessions answer`. Were the asking run to keep its slot,
//! a full budget would wait for an answer that waits for the budget. So the
//! run gives the slot back while any question is open, and its runtime's
//! [`ModelRequestGate`] takes one again before the next request: kept for
//! the run once no question is open, or held for that one request while one
//! still is. Meanwhile its status is `queued`, with its place in line.

use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use futures_util::FutureExt;
use rho_sdk::{ModelRequestGate, ModelRequestGateFuture, ModelRequestPermit, SessionId};
use rho_tools::cancellation::RunCancellation;
use tokio::sync::watch;

use super::{AgentConcurrency, QueueWatch, RuntimePermits};

/// A Rho run's slot, its runtime's model request gate.
pub(crate) struct RunSlot {
    state: Mutex<SlotState>,
    concurrency: AgentConcurrency,
    /// Where the run stands while it waits for a slot again: the watch the
    /// run's host lists its queue place by.
    queue: QueueWatch,
    wait: watch::Sender<SlotWait>,
}

enum SlotState {
    /// Holds the slot; dropping the permits gives it back.
    Holding { _permits: RuntimePermits },
    /// Gave the slot back for questions, `open` of them still unanswered;
    /// the next request takes a slot again.
    Lent { open: usize },
    /// The run ended; no request takes a slot again.
    Ended,
}

/// Whether a run waits in line for a slot it gave back, which its status
/// shows as `queued`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SlotWait {
    #[default]
    NotWaiting,
    InLine,
}

impl RunSlot {
    /// The slot `permits` hold, of a run in `concurrency`'s global pool that
    /// `queue` follows.
    pub(crate) fn new(
        permits: RuntimePermits,
        concurrency: &AgentConcurrency,
        queue: QueueWatch,
    ) -> Self {
        Self {
            state: Mutex::new(SlotState::Holding { _permits: permits }),
            concurrency: concurrency.clone(),
            queue,
            wait: watch::Sender::default(),
        }
    }

    /// Gives the slot back while the question this guard stands for is
    /// open.
    pub(crate) fn asking(self: &Arc<Self>) -> Asking {
        let mut state = self.state();
        match &mut *state {
            SlotState::Holding { .. } => *state = SlotState::Lent { open: 1 },
            SlotState::Lent { open } => *open += 1,
            SlotState::Ended => {}
        }
        Asking(Arc::clone(self))
    }

    /// Whether the run waits in line for its slot, as it changes.
    pub(crate) fn wait(&self) -> watch::Receiver<SlotWait> {
        self.wait.subscribe()
    }

    /// Gives the slot back for good, once the run ended.
    pub(crate) fn release(&self) {
        *self.state() = SlotState::Ended;
    }

    fn state(&self) -> MutexGuard<'_, SlotState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// An open question of the run; the run may keep a slot again once every
/// one is dropped.
pub(crate) struct Asking(Arc<RunSlot>);

impl Drop for Asking {
    fn drop(&mut self) {
        match &mut *self.0.state() {
            SlotState::Lent { open } => *open -= 1,
            // A slot is kept only with no question open; an ended run
            // counts none.
            SlotState::Holding { .. } | SlotState::Ended => {}
        }
    }
}

impl ModelRequestGate for RunSlot {
    fn admit<'a>(&'a self, _session_id: &'a SessionId) -> ModelRequestGateFuture<'a> {
        Box::pin(async move {
            match &*self.state() {
                SlotState::Holding { .. } | SlotState::Ended => return ModelRequestPermit::free(),
                SlotState::Lent { .. } => {}
            }
            // Only dropping this wait, as a cancel does, ends it.
            let never = RunCancellation::new();
            let acquire = self.concurrency.rejoin(&self.queue).acquire(&never);
            tokio::pin!(acquire);
            let permits = match acquire.as_mut().now_or_never() {
                Some(permits) => permits,
                None => {
                    let _in_line = InLine::shown(&self.wait);
                    acquire.await
                }
            };
            let Some(permits) = permits else {
                tracing::error!(
                    "an uncancelled wait for a slot ended without one; the request goes unbudgeted"
                );
                return ModelRequestPermit::free();
            };
            let mut state = self.state();
            match &*state {
                SlotState::Lent { open: 0 } => {
                    *state = SlotState::Holding { _permits: permits };
                    ModelRequestPermit::free()
                }
                SlotState::Lent { .. } | SlotState::Holding { .. } | SlotState::Ended => {
                    ModelRequestPermit::holding(permits)
                }
            }
        })
    }
}

/// The run's wait in line, shown until dropped, as the wait ends or is
/// dropped.
struct InLine<'a>(&'a watch::Sender<SlotWait>);

impl<'a> InLine<'a> {
    fn shown(wait: &'a watch::Sender<SlotWait>) -> Self {
        wait.send_replace(SlotWait::InLine);
        Self(wait)
    }
}

impl Drop for InLine<'_> {
    fn drop(&mut self) {
        self.0.send_replace(SlotWait::NotWaiting);
    }
}

/// A run holding the only slot of a one-slot pool, which `queue` follows.
#[cfg(test)]
pub(crate) fn holding_the_only_slot() -> (AgentConcurrency, Arc<RunSlot>, QueueWatch) {
    let pool = AgentConcurrency::new(super::ConcurrencyLimits {
        total: 1,
        claude_requested: 1,
    });
    let permits = pool
        .join(super::CapacityClass::Rho)
        .acquire(&RunCancellation::new())
        .now_or_never()
        .flatten()
        .expect("a free slot");
    let queue = QueueWatch::default();
    let slot = Arc::new(RunSlot::new(permits, &pool, queue.clone()));
    (pool, slot, queue)
}

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