rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{collections::BTreeSet, sync::Arc, time::Duration};

use pretty_assertions::assert_eq;
use tempfile::TempDir;

use crate::{
    app::{
        daemon_host::{
            jobs::{JobRecord, JobRegistry, JobStore},
            sessions::{
                engine::Engine,
                feed::ResumeFrom,
                pull_request_wake::watch_for_tests,
                test_sessions::{load, Load},
                LoadedSession, Sessions,
            },
        },
        pull_requests::ScriptedForge,
    },
    tools::workflow_tracker::WorkflowFinishedSnapshot,
};

const GRACE: Duration = Duration::from_secs(60);

/// The jobs of `sessions`.
fn jobs_of<'a>(sessions: impl IntoIterator<Item = &'a Arc<LoadedSession>>) -> BTreeSet<String> {
    sessions
        .into_iter()
        .map(|session| session.job.to_string())
        .collect()
}

/// The ids of `records`.
fn ids(records: Vec<JobRecord>) -> BTreeSet<String> {
    records
        .into_iter()
        .map(|record| record.id.to_string())
        .collect()
}

// Covers: sweeps less than a grace apart only mark an idle session idle;
// one a grace after the first unloads a saved one, tearing its runtime down
// and turning away requests that found it before, and discards one that
// has saved nothing the same way, its job gone. A session with a turn
// under way, one a client follows, saved or not, one a request used since
// the first sweep, and one whose own question waits for its answer, which
// only a loaded session can take, stay loaded (#1661).
// Owner: daemon idle session unload (unit).
#[tokio::test]
async fn a_session_idle_for_the_grace_leaves_and_no_other() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let jobs = Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap()));
    let sessions = Sessions::new(jobs, home.path(), ScriptedForge::new());
    let busy = load(&sessions, &root, Load::Busy).await;
    let followed = load(&sessions, &root, Load::Saved).await;
    let _follower = followed.feed.attach(ResumeFrom::default());
    let followed_unsaved = load(&sessions, &root, Load::Unsaved).await;
    let _unsaved_follower = followed_unsaved.feed.attach(ResumeFrom::default());
    let used = load(&sessions, &root, Load::Saved).await;
    let unsaved = load(&sessions, &root, Load::Unsaved).await;
    let idle = load(&sessions, &root, Load::Saved).await;
    let asking = load(&sessions, &root, Load::Asking).await;
    let everything = jobs_of(sessions.loaded().values());

    sessions.sweep(GRACE).await;
    sessions.sweep(GRACE).await;
    let within_the_grace = jobs_of(sessions.loaded().values());
    drop(used.enter());
    tokio::time::pause();
    tokio::time::advance(GRACE).await;
    tokio::time::resume();
    sessions.sweep(GRACE).await;
    let mut torn_down = Vec::new();
    for session in [&idle, &unsaved] {
        torn_down.push((
            session.engine.lock().await.is_none(),
            session.enter().is_none(),
        ));
    }

    let kept = jobs_of([&busy, &followed, &followed_unsaved, &used, &asking]);
    let recorded = jobs_of([&busy, &followed, &followed_unsaved, &used, &idle, &asking]);
    assert_eq!(
        (
            within_the_grace,
            jobs_of(sessions.loaded().values()),
            torn_down,
            ids(sessions.jobs.list()),
        ),
        (everything, kept, vec![(true, true); 2], recorded)
    );
}

// Covers: the idle unload keeps the opening of a saved session, so pull
// request news can reopen it, only when it watches a pull request and its
// client asked for daemon turns: otherwise nothing could wake it, and the
// client's credentials would sit in memory for nothing.
// Owner: daemon idle session unload.
#[tokio::test]
async fn an_unloaded_session_keeps_its_opening_only_while_a_watch_can_wake_it() {
    // (how it is loaded, whether it watches a pull request, whether its
    // opening is kept)
    let cases = [
        (Load::Waking, true, true),
        (Load::Waking, false, false),
        (Load::Saved, true, false),
    ];
    let mut unloaded = Vec::new();
    for (loaded_as, watches, _) in cases {
        let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
        let jobs = Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap()));
        let forge = ScriptedForge::new();
        let sessions = Sessions::new(jobs, home.path(), forge.clone());
        let session = load(&sessions, &root, loaded_as).await;
        if watches {
            let inbox = sessions.pull_requests.inbox(&session.id, root.path());
            watch_for_tests(&forge, &inbox).await;
        }

        sessions.sweep(GRACE).await;
        tokio::time::pause();
        tokio::time::advance(GRACE).await;
        tokio::time::resume();
        sessions.sweep(GRACE).await;
        unloaded.push((
            sessions.loaded().is_empty(),
            sessions.pull_requests.keeps_opening(&session.id),
        ));
    }

    assert_eq!(unloaded, cases.map(|(_, _, kept)| (true, kept)).to_vec());
}

// Covers: a finished result no turn took keeps a session the daemon wakes
// loaded and a daemon upgrade waiting, since a wake will deliver it, until
// the wake gave up on it (a delivery turn ended without taking it, nothing
// left running): then only live work counts, so the session may unload and
// an upgrade go ahead; a turn's start re-arms the wake, and the result
// counts again. Kills: the unload and upgrade checks ignoring the give-up
// (the session stays loaded, and every upgrade waits, for good), and a
// give-up that outlives the next turn's start.
// Owner: daemon idle session unload and upgrade hold.
#[tokio::test]
async fn a_result_the_wake_gave_up_on_holds_neither_the_session_nor_an_upgrade() {
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    let jobs = Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap()));
    let sessions = Sessions::new(jobs, home.path(), ScriptedForge::new());
    let session = load(&sessions, &root, Load::Waking).await;
    {
        let engine = session.engine.lock().await;
        let Some(Engine::Rho(runtime)) = engine.as_ref() else {
            panic!("the fixture session runs on Rho's loop");
        };
        let workflows = runtime.tools().workflow_tracker();
        let owner = Some(session.id.to_string());
        assert!(workflows.register_start("wf-1", "fixture", "digest", owner));
        workflows.mark_finished(
            "wf-1",
            WorkflowFinishedSnapshot {
                lifecycle: "completed".into(),
                outcome: Some("success".into()),
                nodes: Vec::new(),
                error: None,
                outputs: Vec::new(),
            },
        );
    }
    // (keeps it loaded, keeps an upgrade waiting)
    let holds = |session: &LoadedSession| {
        (
            session.runtime_keeps_loaded(),
            session.keeps_upgrade_waiting(),
        )
    };

    let waiting = holds(&session);
    session.give_up_waking();
    let given_up = holds(&session);
    session.rearm_wake();
    let rearmed = holds(&session);

    assert_eq!(
        (waiting, given_up, rearmed),
        ((true, true), (false, false), (true, true))
    );
}