Skip to content

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

chore: files changed crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs

Steven Enamakel5edf379ea3b3
diff --git a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs
new file mode 100644
index 0000000000..76be47795d
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs
@@ -0,0 +1,489 @@
+//! Persisted-format compatibility corpus (wave 5, message & journal format).
+//!
+//! Every file under `tests/fixtures/session_compat/` is a literal transcript,
+//! legacy root, sub-agent checkpoint or session-store capture written by the
+//! release that preceded the message-type migration. Each scenario is loaded
+//! through the real resume path and compared with a committed golden
+//! (`*.golden.json`) holding what the model sees after resume (the committed
+//! history, the frozen system prefix, the recorded tool list, the next provider
+//! request) and what the session-store journal projection derives from each
+//! row. The goldens were generated by the pre-migration code and must never be
+//! regenerated to make a migration pass.
+//!
+//! Regenerate only when deliberately adding a scenario:
+//! `OH_REGEN_SESSION_COMPAT=1 cargo test -p openhuman --lib regenerate_session_compat -- --ignored`.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use serde_json::{json, Value};
+use tinyagents_harness::testkit::ScriptedModel;
+use tinyagents_session::transcript::{
+ read_transcript, resolve_keyed_transcript_path, write_transcript, TranscriptMessage,
+ TranscriptMeta,
+};
+use tinyinference_llm::message::{AssistantMessage, ContentBlock};
+use tinyinference_llm::model::{ChatModel, ModelProfile, ModelResponse};
+use tinyinference_llm::tool::ToolCall;
+
+const FIXTURE_DIR: &str = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../../tests/fixtures/session_compat"
+);
+
+/// How a scenario's fixture files are laid out in a fresh workspace.
+#[derive(Clone, Copy, PartialEq)]
+enum Layout {
+ /// One head transcript at the session's own stem.
+ Head,
+ /// A sealed generation 0 plus its generation 1 head.
+ Chain,
+ /// Timestamp-stem roots written before session identity existed; the first
+ /// resume adopts them into the session's own file.
+ Legacy,
+}
+
+struct Scenario {
+ name: &'static str,
+ native: bool,
+ layout: Layout,
+}
+
+const SCENARIOS: &[Scenario] = &[
+ Scenario { name: "plain", native: true, layout: Layout::Head },
+ Scenario { name: "native_tools", native: true, layout: Layout::Head },
+ Scenario { name: "image_user", native: true, layout: Layout::Head },
+ Scenario { name: "xml_tools", native: false, layout: Layout::Head },
+ Scenario { name: "compaction_record", native: true, layout: Layout::Head },
+ Scenario { name: "generation_chain", native: true, layout: Layout::Chain },
+ Scenario { name: "legacy_adopted", native: true, layout: Layout::Legacy },
+];
+
+fn thread_id(name: &str) -> String {
+ format!("compat-{name}")
+}
+
+fn fixture(name: &str) -> PathBuf {
+ Path::new(FIXTURE_DIR).join(name)
+}
+
+struct EchoTool;
+
+#[async_trait::async_trait]
+impl tinytools::Tool for EchoTool {
+ fn name(&self) -> &str {
+ "echo"
+ }
+ fn description(&self) -> &str {
+ "echoes"
+ }
+ fn parameters_schema(&self) -> Value {
+ json!({"type": "object", "properties": {"q": {"type": "string"}}})
+ }
+ async fn execute(&self, args: Value) -> anyhow::Result<tinytools::ToolResult> {
+ Ok(tinytools::ToolResult::success(format!("echo:{args}")))
+ }
+}
+
+struct BoomTool;
+
+#[async_trait::async_trait]
+impl tinytools::Tool for BoomTool {
+ fn name(&self) -> &str {
+ "boom"
+ }
+ fn description(&self) -> &str {
+ "always fails"
+ }
+ fn parameters_schema(&self) -> Value {
+ json!({"type": "object"})
+ }
+ async fn execute(&self, _args: Value) -> anyhow::Result<tinytools::ToolResult> {
+ Ok(tinytools::ToolResult::error("boom: exit 1"))
+ }
+}
+
+fn tools() -> Vec<Box<dyn tinytools::Tool>> {
+ vec![Box::new(EchoTool), Box::new(BoomTool)]
+}
+
+fn call(id: &str, name: &str, arguments: Value) -> ToolCall {
+ ToolCall {
+ id: id.into(),
+ name: name.into(),
+ arguments,
+ invalid: None,
+ }
+}
+
+fn response(blocks: Vec<ContentBlock>, tool_calls: Vec<ToolCall>) -> ModelResponse {
+ let mut out = ModelResponse::assistant("");
+ out.message = AssistantMessage {
+ id: None,
+ content: blocks,
+ tool_calls,
+ usage: None,
+ origin: None,
+ };
+ out
+}
+
+fn model(responses: Vec<ModelResponse>, native: bool) -> Arc<ScriptedModel> {
+ Arc::new(ScriptedModel::new(responses).with_profile(ModelProfile {
+ tool_calling: native,
+ ..Default::default()
+ }))
+}
+
+fn build_host(
+ root: &Path,
+ model: Arc<ScriptedModel>,
+ native: bool,
+ thread: &str,
+) -> crate::agent::OpenHumanSessionHost {
+ let chat_model: Arc<dyn ChatModel<()>> = model;
+ let builder = crate::agent::SessionHostBuilder::new()
+ .chat_model(chat_model)
+ .tools(tools())
+ .workspace_dir(root.join("workspace"))
+ .action_dir(root.to_path_buf())
+ .memory(crate::memory::test_support::noop_memory());
+ let builder = if native {
+ builder.tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect))
+ } else {
+ builder.tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))
+ };
+ let mut host = builder.build().expect("session build");
+ host.set_thread_id(Some(thread));
+ host
+}
+
+fn run_async<F: std::future::Future<Output = ()> + Send + 'static>(future: F) {
+ std::thread::Builder::new()
+ .stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(move || {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(future);
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread panicked");
+}
+
+fn session_raw(root: &Path) -> PathBuf {
+ root.join("workspace").join("session_raw")
+}
+
+fn stem_path(root: &Path, stem: &str) -> PathBuf {
+ resolve_keyed_transcript_path(&root.join("workspace"), stem).expect("keyed path")
+}
+
+/// Place a scenario's committed files where the resume path looks for them.
+fn place_fixture(root: &Path, scenario: &Scenario, stem: &str) {
+ let name = scenario.name;
+ match scenario.layout {
+ Layout::Head => {
+ std::fs::copy(fixture(&format!("{name}.jsonl")), stem_path(root, stem))
+ .expect("copy head fixture");
+ }
+ Layout::Chain => {
+ std::fs::copy(fixture(&format!("{name}.g0.jsonl")), stem_path(root, stem))
+ .expect("copy sealed generation");
+ std::fs::copy(
+ fixture(&format!("{name}.g1.jsonl")),
+ stem_path(root, &format!("{stem}.g1")),
+ )
+ .expect("copy head generation");
+ }
+ Layout::Legacy => {
+ for index in 1..=2 {
+ std::fs::copy(
+ fixture(&format!("{name}.legacy{index}.jsonl")),
+ stem_path(root, &format!("170000000{index}_orchestrator")),
+ )
+ .expect("copy legacy root");
+ }
+ }
+ }
+}
+
+fn to_json<T: serde::Serialize>(value: &T) -> Value {
+ serde_json::to_value(value).expect("serialize")
+}
+
+/// Everything the model and the journal observe after resuming a scenario.
+async fn snapshot(scenario: &'static Scenario) -> Value {
+ let root = tempfile::tempdir().expect("tempdir");
+ let next = model(vec![ModelResponse::assistant("next reply")], scenario.native);
+ let mut host = build_host(root.path(), next.clone(), scenario.native, &thread_id(scenario.name));
+ let stem = host.session_id().expect("bound session id");
+ place_fixture(root.path(), scenario, &stem);
+
+ assert!(
+ host.resume_bound_session().await.expect("resume"),
+ "{}: fixture must resume",
+ scenario.name
+ );
+ let runtime = host.runtime_session.as_ref().expect("resumed runtime session");
+ let history = to_json(&runtime.history());
+ let prefix = to_json(&runtime.prefix_snapshot().messages());
+ let recorded_tools = runtime
+ .recorded_tools()
+ .map(|snapshot| snapshot.to_json())
+ .unwrap_or(Value::Null);
+
+ // The head the journal projector reads: the session's own file for a
+ // head/legacy layout (adoption writes it), the g1 file for a chain.
+ let head_stem = if scenario.layout == Layout::Chain {
+ format!("{stem}.g1")
+ } else {
+ stem.clone()
+ };
+ let transcript = read_transcript(&stem_path(root.path(), &head_stem)).expect("read head");
+ let journal: Vec<Value> = transcript
+ .messages
+ .into_iter()
+ .map(|row| to_json(&crate::agent::session_import::projector::journal_message_from_transcript(row)))
+ .collect();
+
+ host.turn("next message").await.expect("next turn");
+ let request = next.requests().last().expect("next request").messages.clone();
+
+ json!({
+ "history": history,
+ "prefix": prefix,
+ "recorded_tools": recorded_tools,
+ "journal": journal,
+ "next_request": to_json(&request),
+ })
+}
+
+fn golden(name: &str) -> Value {
+ let raw = std::fs::read_to_string(fixture(&format!("{name}.golden.json")))
+ .unwrap_or_else(|error| panic!("golden for {name}: {error}"));
+ serde_json::from_str(&raw).expect("golden json")
+}
+
+#[test]
+fn every_committed_transcript_resumes_to_the_recorded_model_view() {
+ for scenario in SCENARIOS {
+ run_async(async move {
+ let got = snapshot(scenario).await;
+ let want = golden(scenario.name);
+ assert_eq!(
+ got,
+ want,
+ "{}: resumed model view drifted from the committed golden",
+ scenario.name
+ );
+ });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Fixture generation (run once, against the pre-migration code).
+// ---------------------------------------------------------------------------
+
+fn copy_session(root: &Path, stem: &str, dest: &Path) {
+ std::fs::copy(stem_path(root, stem), dest).expect("capture transcript");
+}
+
+fn legacy_meta(thread: &str, created: &str) -> TranscriptMeta {
+ TranscriptMeta {
+ agent_name: "orchestrator".into(),
+ agent_id: Some("orchestrator".into()),
+ agent_type: None,
+ dispatcher: "native".into(),
+ provider: None,
+ model: None,
+ created: created.into(),
+ updated: created.into(),
+ turn_count: 1,
+ prefix_message_count: None,
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ thread_id: Some(thread.into()),
+ task_id: None,
+ session_id: None,
+ parent_session_id: None,
+ }
+}
+
+async fn capture_turns(name: &str, native: bool, responses: Vec<ModelResponse>, turns: &[&str]) {
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut host = build_host(root.path(), model(responses, native), native, &thread_id(name));
+ let stem = host.session_id().expect("session id");
+ for turn in turns {
+ host.turn(turn).await.expect("capture turn");
+ }
+ drop(host);
+ copy_session(root.path(), &stem, &fixture(&format!("{name}.jsonl")));
+}
+
+async fn capture_all() {
+ std::fs::create_dir_all(FIXTURE_DIR).expect("fixture dir");
+ let text = |s: &str| response(vec![ContentBlock::Text(s.into())], Vec::new());
+
+ capture_turns("plain", true, vec![text("alpha"), text("beta")], &["one", "two"]).await;
+
+ capture_turns(
+ "native_tools",
+ true,
+ vec![
+ response(
+ vec![
+ ContentBlock::Thinking { text: "plan the calls".into(), signature: None },
+ ContentBlock::Text("checking".into()),
+ ],
+ vec![
+ call("call_echo", "echo", json!({"q": "hi"})),
+ call("call_boom", "boom", json!({})),
+ ],
+ ),
+ text("done with tools"),
+ text("second turn"),
+ ],
+ &["use the tools", "and again"],
+ )
+ .await;
+
+ capture_turns(
+ "image_user",
+ true,
+ vec![text("saw it")],
+ &["look [IMAGE:data:image/png;base64,iVBORw0KGgo=] please"],
+ )
+ .await;
+
+ capture_turns(
+ "xml_tools",
+ false,
+ vec![
+ text("<tool_call>{\"name\":\"echo\",\"arguments\":{\"q\":\"x\"}}</tool_call>"),
+ text("<tool_call>{\"name\":\"boom\",\"arguments\":{}}</tool_call>"),
+ text("xml done"),
+ ],
+ &["xml please"],
+ )
+ .await;
+
+ // A reduction written into the same file: the reader replays the
+ // compaction record wholesale.
+ {
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut host = build_host(
+ root.path(),
+ model(vec![text("alpha"), text("beta"), text("gamma")], true),
+ true,
+ &thread_id("compaction_record"),
+ );
+ let stem = host.session_id().expect("session id");
+ for turn in ["one", "two", "three"] {
+ host.turn(turn).await.expect("capture turn");
+ }
+ drop(host);
+ let path = stem_path(root.path(), &stem);
+ let transcript = read_transcript(&path).expect("read");
+ let keep: Vec<TranscriptMessage> = transcript
+ .messages
+ .iter()
+ .enumerate()
+ .filter(|(index, row)| row.role == "system" || *index + 2 >= transcript.messages.len())
+ .map(|(_, row)| row.clone())
+ .collect();
+ tinyagents_session::transcript::append_transcript_turn(
+ &path,
+ &transcript.messages,
+ &keep,
+ &transcript.meta,
+ None,
+ None,
+ )
+ .expect("append compaction");
+ copy_session(root.path(), &stem, &fixture("compaction_record.jsonl"));
+ }
+
+ // A sealed generation 0 and the generation 1 that succeeded it.
+ {
+ let root = tempfile::tempdir().expect("tempdir");
+ let mut host = build_host(
+ root.path(),
+ model(vec![text("alpha"), text("beta")], true),
+ true,
+ &thread_id("generation_chain"),
+ );
+ let stem = host.session_id().expect("session id");
+ for turn in ["one", "two"] {
+ host.turn(turn).await.expect("capture turn");
+ }
+ drop(host);
+ let path = stem_path(root.path(), &stem);
+ let transcript = read_transcript(&path).expect("read");
+ let g1_stem = format!("{stem}.g1");
+ let mut meta = transcript.meta.clone();
+ meta.session_id = Some(g1_stem.clone());
+ meta.parent_session_id = Some(stem.clone());
+ let keep: Vec<TranscriptMessage> = transcript
+ .messages
+ .iter()
+ .enumerate()
+ .filter(|(index, row)| row.role == "system" || *index + 2 >= transcript.messages.len())
+ .map(|(_, row)| row.clone())
+ .collect();
+ write_transcript(&stem_path(root.path(), &g1_stem), &keep, &meta, None).expect("g1");
+ copy_session(root.path(), &stem, &fixture("generation_chain.g0.jsonl"));
+ copy_session(root.path(), &g1_stem, &fixture("generation_chain.g1.jsonl"));
+ }
+
+ // Two root transcripts as a release that predated session identity left
+ // them: no `session_id`, a timestamp stem, thread id only in `_meta`.
+ {
+ let root = tempfile::tempdir().expect("tempdir");
+ let thread = thread_id("legacy_adopted");
+ let rows = |n: usize| {
+ vec![
+ TranscriptMessage::new("system", "legacy system prompt"),
+ TranscriptMessage::new("user", format!("legacy question {n}")),
+ TranscriptMessage::assistant(format!("legacy answer {n}")),
+ ]
+ };
+ for (index, created) in [(1, "2025-01-01T00:00:00Z"), (2, "2025-01-02T00:00:00Z")] {
+ let path = stem_path(root.path(), &format!("170000000{index}_orchestrator"));
+ let mut messages = rows(index);
+ if index == 2 {
+ messages.remove(0);
+ }
+ write_transcript(&path, &messages, &legacy_meta(&thread, created), None)
+ .expect("legacy root");
+ copy_session(
+ root.path(),
+ &format!("170000000{index}_orchestrator"),
+ &fixture(&format!("legacy_adopted.legacy{index}.jsonl")),
+ );
+ }
+ let _ = session_raw(root.path());
+ }
+
+ for scenario in SCENARIOS {
+ let snapshot = snapshot(scenario).await;
+ std::fs::write(
+ fixture(&format!("{}.golden.json", scenario.name)),
+ serde_json::to_string_pretty(&snapshot).expect("golden") + "\n",
+ )
+ .expect("write golden");
+ }
+}
+
+#[test]
+#[ignore = "regenerates the committed corpus; run deliberately (OH_REGEN_SESSION_COMPAT=1)"]
+fn regenerate_session_compat() {
+ if std::env::var("OH_REGEN_SESSION_COMPAT").as_deref() != Ok("1") {
+ return;
+ }
+ run_async(capture_all());
+}