Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(conversations): add comprehensive unit and integration tests for conversation buffer and store

Steven Enamakelf7995b73b3d8
diff --git a/crates/openhuman-core/src/memory/conversations/buffer_tests.rs b/crates/openhuman-core/src/memory/conversations/buffer_tests.rs
index 4563e55b7b..622220fa92 100644
--- a/crates/openhuman-core/src/memory/conversations/buffer_tests.rs
+++ b/crates/openhuman-core/src/memory/conversations/buffer_tests.rs
@@ -1 +1,177 @@
use super::*;
+use chrono::TimeZone;
+
+fn at(secs: i64) -> DateTime<Utc> {
+ Utc.timestamp_opt(1_700_000_000 + secs, 0).single().unwrap()
+}
+
+fn turn(thread: &str, user: &str, assistant: &str, secs: i64) -> CommittedTurn {
+ CommittedTurn {
+ thread_id: thread.to_string(),
+ agent_id: None,
+ workspace: None,
+ channel: None,
+ user: user.to_string(),
+ assistant: assistant.to_string(),
+ tool_calls: Vec::new(),
+ at: at(secs),
+ }
+}
+
+#[test]
+fn push_flushes_exactly_when_the_batch_is_full() {
+ let mut buffer = ConversationBuffer::default();
+ assert!(buffer.push(turn("t", "a", "b", 0), 4, 3).is_none());
+ assert!(buffer.push(turn("t", "c", "d", 1), 5, 3).is_none());
+ assert_eq!(buffer.pending("t"), 2);
+ let batch = buffer.push(turn("t", "e", "f", 2), 6, 3).expect("full");
+ assert_eq!(batch.thread_id, "t");
+ assert_eq!(batch.first, 4);
+ assert_eq!(batch.last(), 6);
+ assert_eq!(batch.turns.len(), 3);
+ assert_eq!(buffer.pending("t"), 0);
+
+ // The next batch starts at the index it is handed.
+ assert!(buffer.push(turn("t", "g", "h", 3), 7, 3).is_none());
+ let rest = buffer.take_all();
+ assert_eq!(rest.len(), 1);
+ assert_eq!(rest[0].first, 7);
+}
+
+#[test]
+fn threads_are_batched_independently() {
+ let mut buffer = ConversationBuffer::default();
+ assert!(buffer.push(turn("a", "1", "1", 0), 0, 2).is_none());
+ assert!(buffer.push(turn("b", "1", "1", 0), 0, 2).is_none());
+ let full = buffer.push(turn("a", "2", "2", 1), 1, 2).expect("a is full");
+ assert_eq!(full.thread_id, "a");
+ assert_eq!(buffer.pending("a"), 0);
+ assert_eq!(buffer.pending("b"), 1);
+}
+
+#[test]
+fn a_zero_batch_size_still_flushes_every_turn() {
+ let mut buffer = ConversationBuffer::default();
+ assert!(buffer.push(turn("t", "a", "b", 0), 0, 0).is_some());
+}
+
+#[test]
+fn take_idle_returns_only_quiet_threads_at_the_boundary() {
+ let mut buffer = ConversationBuffer::default();
+ buffer.push(turn("quiet", "a", "b", 0), 0, 10);
+ buffer.push(turn("busy", "a", "b", 50), 0, 10);
+ // 59s after the quiet thread's last turn: not yet idle for 60s.
+ assert!(buffer.take_idle(at(59), 60).is_empty());
+ let ready = buffer.take_idle(at(60), 60);
+ assert_eq!(ready.len(), 1);
+ assert_eq!(ready[0].thread_id, "quiet");
+ assert_eq!(buffer.pending("quiet"), 0);
+ assert_eq!(buffer.pending("busy"), 1);
+ let later = buffer.take_idle(at(200), 60);
+ assert_eq!(later.len(), 1);
+ assert_eq!(later[0].thread_id, "busy");
+}
+
+#[test]
+fn a_new_turn_resets_the_idle_clock() {
+ let mut buffer = ConversationBuffer::default();
+ buffer.push(turn("t", "a", "b", 0), 0, 10);
+ buffer.push(turn("t", "c", "d", 100), 1, 10);
+ assert!(buffer.take_idle(at(120), 60).is_empty());
+ assert_eq!(buffer.take_idle(at(160), 60).len(), 1);
+}
+
+#[test]
+fn take_all_and_pending_on_an_empty_buffer() {
+ let mut buffer = ConversationBuffer::default();
+ assert_eq!(buffer.pending("nobody"), 0);
+ assert!(buffer.take_all().is_empty());
+ assert!(buffer.take_idle(at(0), 1).is_empty());
+}
+
+#[test]
+fn channel_tag_is_lowercased() {
+ assert_eq!(channel_tag("Telegram"), "channel:telegram");
+}
+
+#[test]
+fn into_item_carries_meta_and_keeps_tool_call_names_and_ids_only() {
+ let mut first = turn("thread-9", "list files", "here they are", 0);
+ first.agent_id = Some("orchestrator".into());
+ first.workspace = Some("/work".into());
+ first.channel = Some("Web".into());
+ first.tool_calls = vec![
+ ToolCallRef {
+ name: "shell".into(),
+ id: Some("call-1".into()),
+ },
+ ToolCallRef {
+ name: "file_read".into(),
+ id: None,
+ },
+ ];
+ let second = turn("thread-9", "thanks", "you're welcome", 30);
+ let item = Batch {
+ thread_id: "thread-9".into(),
+ first: 10,
+ turns: vec![first, second],
+ }
+ .into_item();
+
+ let StoreItem::Conversation { turns, meta } = item else {
+ panic!("expected a conversation");
+ };
+ assert_eq!(meta.thread_id.as_deref(), Some("thread-9"));
+ assert_eq!(meta.agent_id.as_deref(), Some("orchestrator"));
+ assert_eq!(meta.workspace.as_deref(), Some("/work"));
+ assert_eq!(meta.turns, Some(TurnRange { first: 10, last: 11 }));
+ assert_eq!(meta.source.kind, SourceKind::Conversation);
+ assert_eq!(meta.source.id.as_deref(), Some("thread-9"));
+ assert_eq!(meta.tags, vec!["channel:web".to_string()]);
+ assert_eq!(meta.observed_at, Some(at(30)));
+
+ assert_eq!(turns.len(), 4);
+ assert_eq!(turns[0].role, Role::User);
+ assert_eq!(turns[1].role, Role::Assistant);
+ assert_eq!(turns[1].tool_calls.len(), 2);
+ assert_eq!(turns[1].tool_calls[0].name, "shell");
+ assert_eq!(turns[1].tool_calls[0].id.as_deref(), Some("call-1"));
+ assert_eq!(turns[1].tool_calls[1].id, None);
+ assert!(turns[0].tool_calls.is_empty());
+ // The serialised item has no place for arguments.
+ let json = serde_json::to_string(&turns[1].tool_calls).unwrap();
+ assert!(!json.contains("arguments") && !json.contains("args"), "{json}");
+}
+
+#[test]
+fn into_item_skips_blank_sides_and_labels_tool_only_replies() {
+ let mut tool_only = turn("t", "run it", " ", 0);
+ tool_only.tool_calls = vec![ToolCallRef {
+ name: "shell".into(),
+ id: Some("c".into()),
+ }];
+ let silent = turn("t", " ", "just talking", 1);
+ let StoreItem::Conversation { turns, meta } = (Batch {
+ thread_id: "t".into(),
+ first: 0,
+ turns: vec![tool_only, silent],
+ })
+ .into_item() else {
+ panic!("expected a conversation");
+ };
+ assert_eq!(turns.len(), 3);
+ assert_eq!(turns[1].text, "(tool calls only)");
+ assert_eq!(turns[2].role, Role::Assistant);
+ assert_eq!(turns[2].text, "just talking");
+ assert!(meta.tags.is_empty(), "no channel, no tag");
+}
+
+#[test]
+fn last_of_a_single_turn_batch_is_its_first() {
+ let batch = Batch {
+ thread_id: "t".into(),
+ first: 5,
+ turns: vec![turn("t", "a", "b", 0)],
+ };
+ assert_eq!(batch.last(), 5);
+}
diff --git a/crates/openhuman-core/src/memory/conversations/mod_tests.rs b/crates/openhuman-core/src/memory/conversations/mod_tests.rs
index 4563e55b7b..1d2f5aa88b 100644
--- a/crates/openhuman-core/src/memory/conversations/mod_tests.rs
+++ b/crates/openhuman-core/src/memory/conversations/mod_tests.rs
@@ -1 +1,279 @@
use super::*;
+use crate::memory::test_fixtures::{bind_reference, config_in, stored};
+use chrono::Duration;
+use tinymemory::{ItemKind, MetaFilter, ToolCallRef};
+
+fn turn(thread: &str, text: &str, at: DateTime<Utc>) -> CommittedTurn {
+ CommittedTurn {
+ thread_id: thread.to_string(),
+ agent_id: Some("orchestrator".into()),
+ workspace: Some("/work".into()),
+ channel: Some("web".into()),
+ user: text.to_string(),
+ assistant: format!("re: {text}"),
+ tool_calls: vec![ToolCallRef {
+ name: "shell".into(),
+ id: Some("call-1".into()),
+ }],
+ at,
+ }
+}
+
+async fn conversations_in(engine: &tinymemory::conformance::ReferenceEngine) -> Vec<tinymemory::Hit> {
+ stored(
+ engine,
+ MetaFilter {
+ kinds: vec![ItemKind::Conversation],
+ ..MetaFilter::default()
+ },
+ )
+ .await
+}
+
+#[tokio::test]
+async fn a_full_batch_is_stored_as_one_conversation_item() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 2;
+ let engine = bind_reference(&config);
+ let now = Utc::now();
+
+ record_turn(&config, turn("t-batch", "first question", now)).await;
+ assert_eq!(pending_turns(&config.workspace_dir, "t-batch"), 1);
+ assert!(conversations_in(&engine).await.is_empty(), "not yet");
+
+ record_turn(&config, turn("t-batch", "second question", now)).await;
+ assert_eq!(pending_turns(&config.workspace_dir, "t-batch"), 0);
+ let items = conversations_in(&engine).await;
+ assert_eq!(items.len(), 1);
+ let item = &items[0];
+ assert_eq!(item.meta.thread_id.as_deref(), Some("t-batch"));
+ assert_eq!(item.meta.turns.map(|t| (t.first, t.last)), Some((0, 1)));
+ assert!(item.text.contains("first question") && item.text.contains("second question"));
+
+ let recent = recent(&config.workspace_dir);
+ assert_eq!(recent.len(), 1);
+ assert_eq!(recent[0].thread_id, "t-batch");
+ assert_eq!(recent[0].turns, 2);
+
+ // The next batch continues the thread's numbering.
+ record_turn(&config, turn("t-batch", "third", now)).await;
+ record_turn(&config, turn("t-batch", "fourth", now)).await;
+ let items = conversations_in(&engine).await;
+ assert_eq!(items.len(), 2);
+ assert!(items
+ .iter()
+ .any(|i| i.meta.turns.map(|t| (t.first, t.last)) == Some((2, 3))));
+}
+
+#[tokio::test]
+async fn idle_threads_are_flushed_without_waiting_on_a_clock() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 50;
+ config.memory.conversations.idle_secs = 120;
+ let engine = bind_reference(&config);
+ let started = Utc::now();
+
+ record_turn(&config, turn("t-idle", "hello", started)).await;
+ assert_eq!(flush_idle(&config, started + Duration::seconds(119)).await, 0);
+ assert!(conversations_in(&engine).await.is_empty());
+ assert_eq!(pending_turns(&config.workspace_dir, "t-idle"), 1);
+
+ assert_eq!(flush_idle(&config, started + Duration::seconds(120)).await, 1);
+ assert_eq!(conversations_in(&engine).await.len(), 1);
+ assert_eq!(pending_turns(&config.workspace_dir, "t-idle"), 0);
+ assert_eq!(flush_idle(&config, started + Duration::seconds(500)).await, 0);
+}
+
+#[tokio::test]
+async fn flush_all_stores_every_pending_thread() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 50;
+ let engine = bind_reference(&config);
+ record_turn(&config, turn("t-one", "a", Utc::now())).await;
+ record_turn(&config, turn("t-two", "b", Utc::now())).await;
+ assert_eq!(flush_all(&config).await, 2);
+ assert_eq!(conversations_in(&engine).await.len(), 2);
+ assert_eq!(flush_all(&config).await, 0);
+}
+
+#[tokio::test]
+async fn disabled_conversations_and_memory_off_are_no_ops() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 1;
+ let engine = bind_reference(&config);
+
+ config.memory.conversations.enabled = false;
+ record_turn(&config, turn("t-disabled", "x", Utc::now())).await;
+ assert_eq!(pending_turns(&config.workspace_dir, "t-disabled"), 0);
+ assert!(conversations_in(&engine).await.is_empty());
+ assert!(!state_path(&config.workspace_dir).exists());
+
+ let tmp_off = tempfile::tempdir().unwrap();
+ let mut off = config_in(&tmp_off);
+ off.memory.conversations.batch_turns = 1;
+ record_turn(&off, turn("t-off", "x", Utc::now())).await;
+ assert_eq!(pending_turns(&off.workspace_dir, "t-off"), 0);
+ assert!(recent(&off.workspace_dir).is_empty());
+}
+
+#[tokio::test]
+async fn stored_conversations_carry_tool_names_and_ids_but_no_arguments() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 1;
+ let engine = bind_reference(&config);
+ record_turn(&config, turn("t-tools", "run ls", Utc::now())).await;
+ let items = conversations_in(&engine).await;
+ assert_eq!(items.len(), 1);
+ let json = serde_json::to_string(&items[0]).unwrap();
+ assert!(json.contains("shell"), "{json}");
+ assert!(json.contains("call-1"), "{json}");
+ assert!(!json.contains("arguments"), "{json}");
+ // Turn text never touches the bookkeeping file.
+ let state = std::fs::read_to_string(state_path(&config.workspace_dir)).unwrap();
+ assert!(!state.contains("run ls"), "{state}");
+}
+
+#[tokio::test]
+async fn a_failed_store_drops_the_batch_without_recording_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 1;
+ // A conversation with blank text on both sides is invalid for the engine.
+ let mut blank = turn("t-blank", " ", Utc::now());
+ blank.assistant = String::new();
+ blank.tool_calls.clear();
+ bind_reference(&config);
+ record_turn(&config, blank).await;
+ assert_eq!(pending_turns(&config.workspace_dir, "t-blank"), 0);
+ assert!(recent(&config.workspace_dir).is_empty());
+}
+
+#[tokio::test]
+async fn recent_is_capped_and_newest_first() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 1;
+ bind_reference(&config);
+ for n in 0..RECENT_LIMIT + 3 {
+ record_turn(&config, turn(&format!("t-{n}"), "msg", Utc::now())).await;
+ }
+ let listed = recent(&config.workspace_dir);
+ assert_eq!(listed.len(), RECENT_LIMIT);
+ assert_eq!(listed[0].thread_id, format!("t-{}", RECENT_LIMIT + 2));
+}
+
+#[test]
+fn turn_counters_are_per_thread_and_survive_in_the_state_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let ws = tmp.path();
+ let now = Utc::now();
+ assert_eq!(next_turn_index(ws, "a", now), 0);
+ assert_eq!(next_turn_index(ws, "a", now), 1);
+ assert_eq!(next_turn_index(ws, "b", now), 0);
+ assert_eq!(next_turn_index(ws, "a", now), 2);
+}
+
+#[test]
+fn thread_counters_are_pruned_oldest_first() {
+ let tmp = tempfile::tempdir().unwrap();
+ let ws = tmp.path();
+ let base = Utc::now() - Duration::days(1);
+ let mut state = ConversationsState::default();
+ for n in 0..THREAD_COUNTER_LIMIT {
+ state.threads.insert(
+ format!("old-{n:04}"),
+ ThreadCounter {
+ next: 1,
+ touched_at: base + Duration::seconds(n as i64),
+ },
+ );
+ }
+ write_state(ws, &state);
+ assert_eq!(next_turn_index(ws, "fresh", Utc::now()), 0);
+ let after = read_state(ws);
+ assert_eq!(after.threads.len(), THREAD_COUNTER_LIMIT);
+ assert!(after.threads.contains_key("fresh"));
+ assert!(!after.threads.contains_key("old-0000"), "the oldest went first");
+}
+
+#[test]
+fn an_unreadable_state_file_starts_fresh() {
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(tmp.path().join("memory")).unwrap();
+ std::fs::write(state_path(tmp.path()), "{not json").unwrap();
+ assert!(recent(tmp.path()).is_empty());
+ assert_eq!(next_turn_index(tmp.path(), "t", Utc::now()), 0);
+}
+
+#[tokio::test]
+async fn forget_channel_removes_only_that_channels_conversations() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.conversations.batch_turns = 1;
+ let engine = bind_reference(&config);
+ let mut telegram = turn("t-tg", "from telegram", Utc::now());
+ telegram.channel = Some("Telegram".into());
+ record_turn(&config, telegram).await;
+ record_turn(&config, turn("t-web", "from web", Utc::now())).await;
+ assert_eq!(conversations_in(&engine).await.len(), 2);
+
+ assert_eq!(forget_channel(&config, "telegram").await.unwrap(), 1);
+ let left = conversations_in(&engine).await;
+ assert_eq!(left.len(), 1);
+ assert_eq!(left[0].meta.thread_id.as_deref(), Some("t-web"));
+
+ let tmp_off = tempfile::tempdir().unwrap();
+ assert_eq!(
+ forget_channel(&config_in(&tmp_off), "telegram").await.unwrap(),
+ 0,
+ "memory off forgets nothing and is not an error"
+ );
+}
+
+#[test]
+fn view_and_apply_set_validate_and_report() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ for bad in [
+ ConversationsSetParams {
+ batch_turns: Some(0),
+ ..ConversationsSetParams::default()
+ },
+ ConversationsSetParams {
+ batch_turns: Some(MAX_BATCH_TURNS + 1),
+ ..ConversationsSetParams::default()
+ },
+ ConversationsSetParams {
+ idle_secs: Some(0),
+ ..ConversationsSetParams::default()
+ },
+ ConversationsSetParams {
+ idle_secs: Some(MAX_IDLE_SECS + 1),
+ ..ConversationsSetParams::default()
+ },
+ ] {
+ assert_eq!(
+ apply_set(&mut config, &bad).unwrap_err().code(),
+ crate::memory::error::INVALID_REQUEST
+ );
+ }
+ apply_set(
+ &mut config,
+ &ConversationsSetParams {
+ enabled: Some(false),
+ batch_turns: Some(7),
+ idle_secs: Some(33),
+ },
+ )
+ .unwrap();
+ let view = view(&config);
+ assert!(!view.enabled);
+ assert_eq!(view.batch_turns, 7);
+ assert_eq!(view.idle_secs, 33);
+ assert!(view.recent.is_empty());
+}