use crate::common::*;
use async_trait::async_trait;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use troupekit::{Agent, KitError, Progress, Storage};
use troupekit_core::error::{CoreError, ProviderError, ProviderErrorKind};
use troupekit_core::ids::RunId;
use troupekit_core::inmem::InMemCheckpoints;
use troupekit_core::store::{Checkpoint, CheckpointStore};
use troupekit_graph::testing::{text_reply, FnModel};
const LONG: Duration = Duration::from_secs(60);
#[derive(Default)]
struct Recording {
inner: InMemCheckpoints,
steps: Mutex<Vec<u64>>,
}
#[async_trait]
impl CheckpointStore for Recording {
async fn save(&self, cp: Checkpoint) -> Result<(), CoreError> {
let step = cp.step;
self.inner.save(cp).await?;
self.steps.lock().unwrap().push(step);
Ok(())
}
async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
self.inner.latest(run_id).await
}
}
fn counting_model() -> Arc<FnModel> {
Arc::new(FnModel::new("fake/m", |_req| text_reply("counted", 10)))
}
#[tokio::test]
async fn start_returns_id_before_any_model_call() {
let model = counting_model();
let store = Arc::new(InMemCheckpoints::default());
let built = Agent::new("counter")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
assert_eq!(model.calls(), 0);
assert_eq!(store.latest(run_id).await.unwrap().unwrap().step, 0);
assert_eq!(built.resume(run_id).await.unwrap(), "counted");
assert_eq!(model.calls(), 1);
}
#[tokio::test]
async fn start_needs_durable_storage() {
let built = greeter().build().await.unwrap();
let err = built.start("hello").await.unwrap_err();
assert!(matches!(err, KitError::Config { .. }), "{err:?}");
assert_eq!(
err.to_string(),
"agent `greeter`: start needs Storage::sqlite(..) or Storage::custom(..) checkpoints"
);
let err = greeter().start("hello").await.unwrap_err();
assert!(matches!(err, KitError::Config { .. }), "{err:?}");
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn started_run_resumes_in_new_process_shape() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("runs.db");
let expected = greeter().run("I am Ada").await.unwrap();
let (first, run_id) = greeter()
.checkpoints(Storage::sqlite(&path))
.start("I am Ada")
.await
.unwrap();
drop(first);
let second = greeter()
.checkpoints(Storage::sqlite(&path))
.build()
.await
.unwrap();
assert_eq!(second.resume(run_id).await.unwrap(), expected);
}
#[tokio::test]
async fn resume_for_zero_budget_is_pending() {
let model = counting_model();
let store = Arc::new(Recording::default());
let built = Agent::new("counter")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
let progress = built.resume_for(run_id, Duration::ZERO).await.unwrap();
assert_eq!(progress, Progress::Pending { run_id });
assert_eq!(*store.steps.lock().unwrap(), vec![0]);
assert_eq!(model.calls(), 0);
}
#[tokio::test]
async fn resume_for_large_budget_is_done() {
let built = greeter()
.checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
.build()
.await
.unwrap();
let run_id = built.start("I am Ada").await.unwrap();
let progress = built.resume_for(run_id, LONG).await.unwrap();
assert_eq!(progress, Progress::Done("Hello! You said: I am Ada".into()));
let again = built.resume_for(run_id, Duration::ZERO).await.unwrap();
assert_eq!(again, Progress::Done("Hello! You said: I am Ada".into()));
}
#[tokio::test]
async fn resume_for_saves_after_every_step() {
let store = Arc::new(Recording::default());
let built = Agent::new("calc")
.instructions("Use the add tool.")
.model("fake/m")
.model_client(calc_model())
.tool(add_tool())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = built.start("What is 2 + 40?").await.unwrap();
let progress = built.resume_for(run_id, LONG).await.unwrap();
assert_eq!(progress, Progress::Done("The sum is 42".into()));
let steps = store.steps.lock().unwrap().clone();
assert!(steps.len() >= 3, "{steps:?}");
let expected: Vec<u64> = (0..steps.len() as u64).collect();
assert_eq!(steps, expected);
}
#[test]
fn defaults_are_the_safe_values() {
assert_eq!(troupekit::MAX_STEPS_PER_WINDOW, 10_000);
assert_eq!(troupekit::MAX_PERSONA_BYTES, 1024 * 1024);
}
fn rate_limited(retry_after_ms: u64) -> Arc<FnModel> {
Arc::new(FnModel::new("fake/m", move |_req| {
Err(
ProviderError::new(ProviderErrorKind::RateLimited, "slow down")
.with_retry_after(retry_after_ms),
)
}))
}
#[tokio::test]
async fn resume_for_keeps_the_retry_wait_across_windows() {
let model = rate_limited(20_000);
let built = Agent::new("limited")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.retries(5)
.checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
for _ in 0..3 {
let progress = built
.resume_for(run_id, Duration::from_millis(50))
.await
.unwrap();
assert_eq!(progress, Progress::Pending { run_id });
}
assert_eq!(model.calls(), 1, "a saved retry wait is not skipped");
}
#[tokio::test]
async fn retry_cap_holds_across_resume_for_windows() {
let model = rate_limited(150);
let built = Agent::new("limited")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.retries(2)
.checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
let window = Duration::from_millis(100);
for _ in 0..2 {
let progress = built.resume_for(run_id, window).await.unwrap();
assert_eq!(progress, Progress::Pending { run_id });
tokio::time::sleep(Duration::from_millis(200)).await;
}
let err = built.resume_for(run_id, window).await.unwrap_err();
assert!(
matches!(err, KitError::Retries { attempts: 2, .. }),
"{err:?}"
);
assert_eq!(model.calls(), 3);
}
#[tokio::test]
async fn resume_keeps_retries_counted_by_resume_for() {
let model = rate_limited(300);
let built = Agent::new("limited")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.retries(1)
.checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
let progress = built
.resume_for(run_id, Duration::from_millis(100))
.await
.unwrap();
assert_eq!(progress, Progress::Pending { run_id });
let waited = std::time::Instant::now();
let err = built.resume(run_id).await.unwrap_err();
assert!(
waited.elapsed() >= Duration::from_millis(150),
"resume waits out the saved retry wait"
);
assert!(
matches!(err, KitError::Retries { attempts: 1, .. }),
"{err:?}"
);
assert_eq!(model.calls(), 2);
}
#[tokio::test]
async fn exhausted_checkpoint_is_refused_before_another_step() {
let failures = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let seen = failures.clone();
let model = Arc::new(FnModel::new("fake/m", move |_req| {
if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2 {
return Err(
ProviderError::new(ProviderErrorKind::RateLimited, "slow down").with_retry_after(1),
);
}
text_reply("late", 10)
}));
let built = Agent::new("limited")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.retries(1)
.checkpoints(Storage::custom(Arc::new(InMemCheckpoints::default())))
.build()
.await
.unwrap();
let run_id = built.start("hello").await.unwrap();
let err = built.resume_for(run_id, LONG).await.unwrap_err();
assert!(
matches!(err, KitError::Retries { attempts: 1, .. }),
"{err:?}"
);
assert_eq!(model.calls(), 2);
let err = built.resume_for(run_id, LONG).await.unwrap_err();
assert!(
matches!(err, KitError::Retries { attempts: 1, .. }),
"{err:?}"
);
let err = built.resume(run_id).await.unwrap_err();
assert!(
matches!(err, KitError::Retries { attempts: 1, .. }),
"{err:?}"
);
assert_eq!(model.calls(), 2);
}
#[derive(Default)]
struct FailingSaves {
seen: Mutex<Vec<RunId>>,
}
#[async_trait]
impl CheckpointStore for FailingSaves {
async fn save(&self, cp: Checkpoint) -> Result<(), CoreError> {
self.seen.lock().unwrap().push(cp.run_id);
Err(CoreError::InvalidMessage("disk full".into()))
}
async fn latest(&self, _run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
Ok(None)
}
}
#[tokio::test]
async fn save_failure_during_run_keeps_the_run_id() {
let store = Arc::new(FailingSaves::default());
let built = Agent::new("saver")
.instructions("Answer.")
.model("fake/m")
.model_client(counting_model())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let err = built.run("hello").await.unwrap_err();
assert_in_run(err, &store);
let err = built.run_with("hello").await.unwrap_err();
assert_in_run(err, &store);
}
fn assert_in_run(err: KitError, store: &FailingSaves) {
let seen = *store.seen.lock().unwrap().last().unwrap();
match err {
KitError::InRun { run_id, source } => {
assert_eq!(run_id, seen);
assert!(!matches!(*source, KitError::InRun { .. }), "{source:?}");
}
other => panic!("expected InRun, got {other:?}"),
}
}
fn user_capped() -> (
Arc<troupekit_agent::InMemoryLedger>,
troupekit_agent::Limits,
) {
let ledger = Arc::new(troupekit_agent::InMemoryLedger::default());
let limits = troupekit_agent::Limits {
user: Some(troupekit_agent::PeriodLimit {
key: "user-1".into(),
max_usd_micros: 10,
}),
..Default::default()
};
(ledger, limits)
}
async fn spend_past_the_cap(ledger: &troupekit_agent::InMemoryLedger) {
use troupekit_core::store::UsageLedger;
let spent = troupekit_core::event::Usage {
input_tokens: 0,
output_tokens: 0,
cost_usd_micros: 1_000,
};
ledger.record("user-1", spent).await.unwrap();
}
#[tokio::test]
async fn resume_for_refuses_a_run_of_another_agent() {
let store = Arc::new(InMemCheckpoints::default());
let model = counting_model();
let first = Agent::new("counter")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = first.start("hello").await.unwrap();
let other = Agent::new("other")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let err = other.resume_for(run_id, LONG).await.unwrap_err();
assert!(matches!(err, KitError::Config { .. }), "{err:?}");
assert!(
err.to_string().contains("was started by agent `counter`"),
"{err}"
);
assert_eq!(model.calls(), 0, "a refused run makes no model call");
}
#[tokio::test]
async fn resume_for_applies_the_stricter_current_limits() {
let store = Arc::new(InMemCheckpoints::default());
let model = counting_model();
let loose = Agent::new("counter")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = loose.start("hello").await.unwrap();
let (ledger, limits) = user_capped();
spend_past_the_cap(&ledger).await;
let strict = Agent::new("counter")
.instructions("Answer.")
.model("fake/m")
.model_client(model.clone())
.limits(limits)
.ledger(ledger)
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let resumed = strict.resume_for(run_id, LONG).await;
assert!(
matches!(resumed, Err(KitError::Paused { .. })),
"{resumed:?}"
);
assert_eq!(
model.calls(),
0,
"a user past the current cap gets no model call"
);
}
#[tokio::test]
async fn graph_resume_for_applies_the_stricter_current_limits() {
let store = Arc::new(InMemCheckpoints::default());
let model = counting_model();
let node = || {
Agent::new("drafter")
.instructions("Draft.")
.model("fake/m")
.model_client(model.clone())
};
let loose = troupekit::Graph::new("g")
.agent("draft", node())
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let run_id = loose.start("hi").await.unwrap();
let (ledger, limits) = user_capped();
spend_past_the_cap(&ledger).await;
let strict = troupekit::Graph::new("g")
.agent("draft", node())
.limits(limits)
.ledger(ledger)
.checkpoints(Storage::custom(store.clone()))
.build()
.await
.unwrap();
let resumed = strict.resume_for(run_id, LONG).await;
assert!(
matches!(resumed, Err(KitError::Paused { .. })),
"{resumed:?}"
);
assert_eq!(
model.calls(),
0,
"a user past the current cap gets no model call"
);
}
#[test]
fn successful_run_needs_no_timer() {
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let answer = runtime.block_on(async {
let built = greeter().build().await.unwrap();
built.run("I am Ada").await.unwrap()
});
assert_eq!(answer, "Hello! You said: I am Ada");
}