The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(session-host): cover transcript compatibility edge cases
Steven Enamakele4fe85a9c867
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.rsindex 30e2ee128e..9eab6f4376 100644--- a/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/transcript_compat_tests.rs@@ -11,18 +11,20 @@//! session-store journal projection of each row; the file-to-store dual-write//! it served is gone, so that key was removed from them and nothing else.)//!-//! Regenerate only when deliberately adding a scenario:-//! `OH_REGEN_SESSION_COMPAT=1 cargo test -p openhuman --lib regenerate_session_compat -- --ignored`.-+//! The fixtures are classic `session_raw/*.jsonl` files. Nothing writes that+//! layout any more, so a scenario is loaded the way an upgrade loads it: the+//! files are placed in a workspace and imported once into the store the host+//! then resumes from. The capture generator that wrote them with the retired+//! file writer was removed with that writer; the committed files and goldens+//! are the corpus.++use std::collections::{BTreeMap, HashMap};use std::path::{Path, PathBuf};-use std::sync::Arc;+use std::sync::{Arc, LazyLock, Mutex};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 tinyagents_session::transcript::{SessionRef, TranscriptLocator};use tinyinference_llm::message::{AssistantMessage, ContentBlock};use tinyinference_llm::model::{ChatModel, ModelProfile, ModelResponse};use tinyinference_llm::tool::ToolCall;@@ -171,15 +173,17 @@ pub(super) fn model(responses: Vec<ModelResponse>, native: bool) -> Arc<Scripted}))}-/// These suites pin the classic JSONL transcript format and its resume-/// behaviour, so their hosts write through the file locator explicitly (the-/// default for a host with no session store is the workspace's driver store).-pub(super) fn file_locator(- root: &Path,-) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {- Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(- root.join("workspace"),- ))+/// The transcript store of the workspace under `root`, one per root so that two+/// hosts built over the same root (two "processes") share the conversation.+pub(super) fn store_locator(root: &Path) -> Arc<dyn TranscriptLocator> {+ static STORES: LazyLock<Mutex<HashMap<PathBuf, Arc<dyn TranscriptLocator>>>> =+ LazyLock::new(Mutex::default);+ let mut stores = STORES.lock().unwrap_or_else(|e| e.into_inner());+ Arc::clone(+ stores+ .entry(root.to_path_buf())+ .or_insert_with(super::super::session_store::splice_fixture::memory_locator),+ )}pub(super) fn build_host(@@ -190,7 +194,7 @@ pub(super) fn build_host() -> crate::agent::OpenHumanSessionHost {let chat_model: Arc<dyn ChatModel<()>> = model;let builder = crate::agent::SessionHostBuilder::new()- .with_session_history_locator(file_locator(root))+ .with_session_history_locator(store_locator(root)).chat_model(chat_model).tools(tools()).workspace_dir(root.join("workspace"))@@ -224,8 +228,49 @@ pub(super) fn session_raw(root: &Path) -> PathBuf {root.join("workspace").join("session_raw")}-pub(super) fn stem_path(root: &Path, stem: &str) -> PathBuf {- resolve_keyed_transcript_path(&root.join("workspace"), stem).expect("keyed path")+/// Where a classic fixture for `stem` is placed before the import.+pub(super) fn classic_path(root: &Path, stem: &str) -> PathBuf {+ session_raw(root).join(format!("{stem}.jsonl"))+}++/// Imports the classic files placed under the workspace's `session_raw/` into+/// the root's store, as the first start after an upgrade does.+pub(super) fn import_placed(root: &Path) {+ tinyagents_session::legacy::import_transcripts(+ &root.join("workspace"),+ store_locator(root).as_ref(),+ )+ .expect("import the placed fixtures");+}++/// Everything the root's store holds for `session`'s thread, by stem: the+/// session's generation chain and any pre-identity roots, each as its model+/// messages and recorded tools.+pub(super) fn store_tree(+ root: &Path,+ thread: &str,+ session: &SessionRef,+) -> BTreeMap<String, Value> {+ let locator = store_locator(root);+ let mut out = BTreeMap::new();+ let mut put = |stem: String, read: Arc<dyn tinyagents_session::transcript::TranscriptRead>| {+ let session = read.read_session().expect("read").expect("session");+ out.insert(+ stem,+ json!({"messages": to_json(&session.messages), "tools": session.tools}),+ );+ };+ for generation in locator.session_chain(session) {+ if let Some(read) = locator.read_session_transcript(&generation) {+ put(tinyagents_session::transcript::session_stem(&generation), read);+ }+ }+ if let Some(found) = locator.thread_transcripts(thread, None) {+ for root_transcript in found.roots {+ put(root_transcript.stem, root_transcript.transcript);+ }+ }+ out}/// Place a scenario's committed files where the resume path looks for them.@@ -236,31 +281,33 @@ pub(super) fn place_fixture(root: &Path, scenario: &Scenario, stem: &str, varianlet name = scenario.name;match scenario.layout {Layout::Head => {- std::fs::copy(+ place(fixture(&format!("{name}{variant}.jsonl")),- stem_path(root, stem),- )- .expect("copy head fixture");+ classic_path(root, stem),+ );}Layout::Chain => {- std::fs::copy(fixture(&format!("{name}.g0.jsonl")), stem_path(root, stem))- .expect("copy sealed generation");- std::fs::copy(+ place(fixture(&format!("{name}.g0.jsonl")), classic_path(root, stem));+ place(fixture(&format!("{name}.g1.jsonl")),- stem_path(root, &format!("{stem}.g1")),- )- .expect("copy head generation");+ classic_path(root, &format!("{stem}.g1")),+ );}Layout::Legacy => {for index in 1..=2 {- std::fs::copy(+ place(fixture(&format!("{name}.legacy{index}.jsonl")),- stem_path(root, &format!("170000000{index}_orchestrator")),- )- .expect("copy legacy root");+ classic_path(root, &format!("170000000{index}_orchestrator")),+ );}}}+ import_placed(root);+}++fn place(from: PathBuf, to: PathBuf) {+ std::fs::create_dir_all(to.parent().expect("a file path")).expect("create session_raw");+ std::fs::copy(from, to).expect("place a classic fixture");}fn to_json<T: serde::Serialize>(value: &T) -> Value {@@ -364,233 +411,6 @@ fn every_committed_transcript_resumes_to_the_recorded_model_view() {}}-// ----------------------------------------------------------------------------// 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, agent: &str, created: &str) -> TranscriptMeta {- TranscriptMeta {- agent_name: agent.into(),- agent_id: Some(agent.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 agent = build_host(root.path(), model(Vec::new(), true), true, &thread)- .agent_definition_id- .clone();- 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, &agent, 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());-}-/// Archived declarations survive replay, but retired executors never return.#[cfg(feature = "voice")]#[test]@@ -635,7 +455,7 @@ fn assert_retired_tool_replay(identity_bound: bool) {);let chat_model: Arc<dyn ChatModel<()>> = first_model;let mut first = crate::agent::SessionHostBuilder::new()- .with_session_history_locator(file_locator(root.path()))+ .with_session_history_locator(store_locator(root.path())).chat_model(chat_model).tools(vec![Box::new(ArchivedAudioTool)]).permanent_tool_names(std::collections::HashSet::from([RETIRED.to_string()]))@@ -649,8 +469,10 @@ fn assert_retired_tool_replay(identity_bound: bool) {.turn("save this old conversation").await.expect("archive turn");- let transcript_path = stem_path(root.path(), &first.session_id().expect("session id"));- let archived = read_transcript(&transcript_path).expect("saved transcript");+ let archived = super::super::session_store::splice_fixture::head_of_full(+ &store_locator(root.path()),+ "retired-audio-thread",+ );assert!(archived.tools.as_ref()@@ -659,7 +481,7 @@ fn assert_retired_tool_replay(identity_bound: bool) {.expect("declarations array").iter().any(|spec| spec["name"] == RETIRED));- let archived_bytes = std::fs::read(&transcript_path).expect("archived bytes");+ let archived_rows = to_json(&archived.messages);drop(first);let next = model(@@ -674,7 +496,7 @@ fn assert_retired_tool_replay(identity_bound: bool) {} else {let chat_model: Arc<dyn ChatModel<()>> = next.clone();crate::agent::SessionHostBuilder::new()- .with_session_history_locator(file_locator(root.path()))+ .with_session_history_locator(store_locator(root.path())).chat_model(chat_model).tools(tools()).workspace_dir(workspace.clone())@@ -700,8 +522,14 @@ fn assert_retired_tool_replay(identity_bound: bool) {// An explicit host tool belt is authoritative, while archived declarations// remain intact in the durable transcript.assert_eq!(- std::fs::read(&transcript_path).expect("resumed bytes"),- archived_bytes+ to_json(+ &super::super::session_store::splice_fixture::head_of_full(+ &store_locator(root.path()),+ "retired-audio-thread",+ )+ .messages+ ),+ archived_rows);let output = resumed.turn("continue this conversation")