Skip to content

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

fix(agent): give every session host a unique transcript key

oxoxDev88796fb41a9a
diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
index 75bde0344a..dbc58e5f82 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs
@@ -458,23 +458,7 @@ impl SessionHostBuilder {
agent_definition_id: agent_definition_name.clone(),
session_history_locator: self.session_history_locator,
session_history_locator_memo: std::sync::OnceLock::new(),
- session_key: {
- let unix_ts = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- let sanitized: String = agent_definition_name
- .chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
- c
- } else {
- '_'
- }
- })
- .collect();
- format!("{unix_ts}_{sanitized}")
- },
+ session_key: crate::agent::session_host::session_key::mint(&agent_definition_name),
session_parent_prefix: self.session_parent_prefix,
session: None,
on_progress: None,
diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs
index 80e7431c90..155378d557 100644
--- a/crates/openhuman-core/src/agent/session_host/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@ -24,6 +24,7 @@
//! | [`driver`] | OpenHuman model/harness `SessionDriver`. |
//! | [`hooks`] | Product preparation/commit/terminal hooks. |
//! | [`runtime`] | Public accessors and `run_single` / `run_interactive`. |
+//! | [`session_key`] | Minting and renaming the per-host transcript key. |
//!
//! External callers should import [`OpenHumanSessionHost`] and [`SessionHostBuilder`] from
//! `crate::agent`, which re-exports them from this module.
@@ -45,6 +46,7 @@ mod live_tools;
mod resume_bound_session_tests;
mod runtime;
mod runtime_session;
+mod session_key;
pub(crate) mod stop_summary;
mod turn;
// `pub(crate)` since issue #6014: the tool-call-cap instruction is now appended
diff --git a/crates/openhuman-core/src/agent/session_host/runtime/accessors/runtime.rs b/crates/openhuman-core/src/agent/session_host/runtime/accessors/runtime.rs
index 3f244ff73c..bbf0a8a38a 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime/accessors/runtime.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/accessors/runtime.rs
@@ -116,36 +116,15 @@ impl OpenHumanSessionHost {
/// transcripts per thread so each conversation thread gets its own
/// transcript namespace instead of sharing one by agent type.
///
- /// Also rebuilds [`Self::session_key`] so the next call to
- /// `persist_session_transcript` writes to a path keyed by the new
- /// name. Without this, persist would keep using the builder-time
- /// name (e.g. `"orchestrator"`) while
- /// `find_latest_transcript` searches for the post-rename name (e.g.
- /// `"orchestrator_thread-6ad6d"`), and resume on cold boot would
- /// silently miss every prior transcript — the LLM would then run
- /// each new turn with no conversation history.
+ /// Also swaps the agent part of [`Self::session_key`] for the new name,
+ /// keeping its timestamp and token.
pub fn set_agent_definition_name(&mut self, name: impl Into<String>) {
let name = name.into();
- let sanitized: String = name
- .chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
- c
- } else {
- '_'
- }
- })
- .collect();
- // Preserve the original unix-timestamp prefix from the builder
- // so sub-agent spawn collisions remain impossible. Falls back
- // to "0" if the existing key is in an unexpected shape.
- let prefix = self
- .session_key
- .split_once('_')
- .map(|(p, _)| p)
- .filter(|p| !p.is_empty())
- .unwrap_or("0");
- self.session_key = format!("{prefix}_{sanitized}");
+ self.session_key = crate::agent::session_host::session_key::rename(
+ &self.session_key,
+ &self.agent_definition_name,
+ &name,
+ );
self.agent_definition_name = name;
self.rebuild_tool_policy_session();
self.sync_runtime_tool_surface();
diff --git a/crates/openhuman-core/src/agent/session_host/session_key.rs b/crates/openhuman-core/src/agent/session_host/session_key.rs
new file mode 100644
index 0000000000..5fbfdafd7c
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/session_key.rs
@@ -0,0 +1,61 @@
+//! Session keys: `{unix_ts}_{token}_{agent}`, unique per session host.
+//!
+//! The leading segment stays whole unix seconds because transcript views read
+//! a spawn time from it. The token is twelve lowercase hex digits and carries
+//! no `_`, so the agent part can be swapped without parsing the agent name.
+
+const TOKEN_LEN: usize = 12;
+
+/// Maps an agent name onto the characters a transcript stem allows.
+pub(crate) fn sanitize(name: &str) -> String {
+ name.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
+ c
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+/// A fresh key for a session host running `agent`.
+pub(crate) fn mint(agent: &str) -> String {
+ let unix_ts = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let token = uuid::Uuid::new_v4().simple().to_string();
+ let key = format!("{unix_ts}_{}_{}", &token[..TOKEN_LEN], sanitize(agent));
+ tracing::debug!(session_key = %key, "[session_host] minted session key");
+ key
+}
+
+/// `key` with its agent part replaced by `new_agent`, keeping the timestamp
+/// and token. A key not minted for `old_agent` is replaced by a fresh one.
+pub(crate) fn rename(key: &str, old_agent: &str, new_agent: &str) -> String {
+ let prefix = key
+ .strip_suffix(sanitize(old_agent).as_str())
+ .and_then(|rest| rest.strip_suffix('_'))
+ .and_then(|rest| rest.split_once('_'))
+ .filter(|(unix, token)| {
+ unix.parse::<u64>().is_ok()
+ && token.len() == TOKEN_LEN
+ && token.bytes().all(|b| b.is_ascii_hexdigit())
+ });
+ match prefix {
+ Some((unix, token)) => format!("{unix}_{token}_{}", sanitize(new_agent)),
+ None => {
+ tracing::debug!(
+ session_key = %key,
+ old_agent,
+ "[session_host] session key has an unexpected shape; minting a new one"
+ );
+ mint(new_agent)
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "session_key_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/session_host/session_key_tests.rs b/crates/openhuman-core/src/agent/session_host/session_key_tests.rs
new file mode 100644
index 0000000000..20f866f87a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/session_key_tests.rs
@@ -0,0 +1,162 @@
+use super::*;
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use crate::storage::sessions::splice_fixture_tests::{blank_meta, memory_locator};
+use tinyagents_session::transcript::TranscriptLocator;
+
+fn parts(key: &str) -> (&str, &str, &str) {
+ let mut it = key.splitn(3, '_');
+ (
+ it.next().unwrap(),
+ it.next().unwrap(),
+ it.next().unwrap_or(""),
+ )
+}
+
+#[test]
+fn mint_is_unique_for_one_agent_within_a_second() {
+ let keys: HashSet<String> = (0..1_000).map(|_| mint("orchestrator")).collect();
+ assert_eq!(keys.len(), 1_000);
+}
+
+#[test]
+fn mint_keeps_unix_seconds_first_and_a_token_without_underscores() {
+ let key = mint("tools_agent");
+ let (unix, token, agent) = parts(&key);
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ let unix: u64 = unix.parse().expect("first segment is unix seconds");
+ assert!(unix <= now && now - unix < 60, "{key}");
+ assert_eq!(token.len(), TOKEN_LEN, "{key}");
+ assert!(token.bytes().all(|b| b.is_ascii_hexdigit()), "{key}");
+ assert_eq!(agent, "tools_agent");
+}
+
+#[test]
+fn mint_sanitizes_the_agent_name() {
+ let key = mint("my agent/v2");
+ assert!(key.ends_with("_my_agent_v2"), "{key}");
+}
+
+#[test]
+fn rename_keeps_timestamp_and_token_across_names_with_underscores() {
+ let key = mint("tools_agent");
+ let renamed = rename(&key, "tools_agent", "workflow_builder");
+ let (unix, token, _) = parts(&key);
+ assert_eq!(renamed, format!("{unix}_{token}_workflow_builder"));
+ let back = rename(&renamed, "workflow_builder", "orchestrator_thread-6ad6d");
+ assert_eq!(back, format!("{unix}_{token}_orchestrator_thread-6ad6d"));
+}
+
+#[test]
+fn rename_of_an_unexpected_key_mints_a_fresh_one() {
+ for key in [
+ "1713000000_orchestrator",
+ "not-a-key",
+ "",
+ "x_abcdefabcdef_orchestrator",
+ ] {
+ let renamed = rename(key, "orchestrator", "planner");
+ let (unix, token, agent) = parts(&renamed);
+ assert!(unix.parse::<u64>().is_ok(), "{key} -> {renamed}");
+ assert_eq!(token.len(), TOKEN_LEN, "{key} -> {renamed}");
+ assert_eq!(agent, "planner", "{key} -> {renamed}");
+ }
+}
+
+#[test]
+fn rename_with_the_wrong_old_name_mints_a_fresh_one() {
+ let key = mint("orchestrator");
+ let renamed = rename(&key, "planner", "critic");
+ assert!(renamed.ends_with("_critic"), "{renamed}");
+ assert_ne!(parts(&renamed).1, parts(&key).1);
+}
+
+#[test]
+fn overlapping_unthreaded_runs_of_one_agent_keep_separate_transcripts() {
+ std::thread::Builder::new()
+ .stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(overlapping_unthreaded_runs());
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread panicked");
+}
+
+fn scheduled_turn() -> crate::agent::session_host::TurnOverrides {
+ crate::agent::session_host::TurnOverrides {
+ suppress_transcript_autoload: true,
+ ..Default::default()
+ }
+}
+
+fn transcript_text(locator: &Arc<dyn TranscriptLocator>, stem: &str) -> String {
+ locator
+ .open_stem(stem, blank_meta())
+ .expect("bind transcript")
+ .messages()
+ .expect("read transcript")
+ .into_iter()
+ .map(|row| row.content)
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+async fn overlapping_unthreaded_runs() {
+ let _ = crate::agent_registry::host_definition::AgentDefinitionRegistry::init_global_builtins();
+ let root = tempfile::tempdir().expect("tempdir");
+ let locator = memory_locator();
+ let new_host = |replies: Vec<String>| {
+ let model = Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::replies(replies).with_profile(
+ tinyinference_llm::model::ModelProfile {
+ tool_calling: true,
+ ..Default::default()
+ },
+ ),
+ );
+ let chat_model: Arc<dyn tinyinference_llm::model::ChatModel<()>> = model;
+ crate::agent::SessionHostBuilder::new()
+ .with_session_history_locator(Arc::clone(&locator))
+ .chat_model(chat_model)
+ .tools(Vec::new())
+ .workspace_dir(root.path().join("workspace"))
+ .action_dir(root.path().to_path_buf())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect))
+ .build()
+ .expect("session build")
+ };
+ for round in 1..=2 {
+ let mut a = new_host(vec![format!("reply-a{round}")]);
+ let mut b = new_host(vec![format!("reply-b{round}")]);
+ assert_eq!(a.agent_definition_name(), b.agent_definition_name());
+ if round == 2 {
+ a.set_agent_definition_name("scheduled_agent");
+ b.set_agent_definition_name("scheduled_agent");
+ }
+ assert_ne!(a.session_key(), b.session_key(), "round {round}");
+ a.set_next_turn_overrides(scheduled_turn());
+ b.set_next_turn_overrides(scheduled_turn());
+ let prompt_a = format!("prompt-a{round}");
+ let prompt_b = format!("prompt-b{round}");
+ let (ra, rb) = tokio::join!(a.run_single(&prompt_a), b.run_single(&prompt_b));
+ assert_eq!(ra.expect("run a"), format!("reply-a{round}"));
+ assert_eq!(rb.expect("run b"), format!("reply-b{round}"));
+
+ let text_a = transcript_text(&locator, a.session_key());
+ let text_b = transcript_text(&locator, b.session_key());
+ assert!(text_a.contains(&prompt_a) && text_a.contains(&format!("reply-a{round}")));
+ assert!(text_b.contains(&prompt_b) && text_b.contains(&format!("reply-b{round}")));
+ assert!(!text_a.contains(&prompt_b), "a's transcript holds b's turn");
+ assert!(!text_b.contains(&prompt_a), "b's transcript holds a's turn");
+ }
+}