diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs index d3f1fde2efa..564c0ca15de 100644 --- a/crates/openhuman-core/src/agent/mod.rs +++ b/crates/openhuman-core/src/agent/mod.rs @@ -75,6 +75,6 @@ pub(crate) mod turn_policy; pub(crate) mod turn_progress; #[allow(unused_imports)] pub use session_host::{ - CompactOptions, CompactOutcome, HostTools, HostTurnTools, OpenHumanSessionHost, - SessionHostBuilder, TurnContext, TurnOverrides, + CompactOptions, CompactOutcome, HostTools, HostTurnTools, MemoryBlockPrewarm, + OpenHumanSessionHost, SessionHostBuilder, TurnContext, TurnOverrides, }; diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index 41861b6dd2e..e3bb84f29ae 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -55,7 +55,7 @@ pub(crate) mod test_support; pub use codec::OpenHumanTranscriptCodec; pub type OpenHumanSessionHooks = tinyagents_runtime::FnSessionHooks; -pub use runtime_session::{CompactOptions, CompactOutcome}; +pub use runtime_session::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides}; // Re-export the duplicate-tool-spec guard for sibling harness modules diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs index 33888059da0..0e9269b742b 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs @@ -9,6 +9,8 @@ pub use compact::{CompactOptions, CompactOutcome}; #[path = "runtime_session_enrichment.rs"] mod enrichment; pub(super) mod memory_block; +mod memory_block_ready; +pub use memory_block_ready::MemoryBlockPrewarm; mod permanent; mod post_commit; #[path = "runtime_session/prelude.rs"] diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs index a47daf2056c..182eb597870 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block.rs @@ -37,11 +37,25 @@ //! [`with_memory_block`]. Doing nothing is also correct: the next turn finds //! the inherited block and renders a fresh one. //! -//! Logs: `[memory_block] rendered|kept|empty|error` with the thread and agent -//! ids and the block's token count; never its content. +//! **Off the critical path.** With `[memory] memory_block_deadline_ms` a +//! generation start waits that long for its render: when the deadline lapses +//! the turn keeps the recorded block (a cold thread sends none), logs +//! `[memory_block] deferred`, and the render finishes in the background into +//! `memory_block_ready.rs`, where the next generation start takes it. A host +//! can fill the same store ahead of a turn with +//! [`OpenHumanSessionHost::prewarm_memory_block`]. +//! +//! Logs: `[memory_block] rendered|ready|kept|empty|deferred|error` with the +//! thread and agent ids, the block's token count and, for a render, its +//! `elapsed_ms` (the per-step breakdown is `[memory_block] read` at debug); +//! never its content. + +use std::sync::Arc; +use std::time::Instant; use tinyagents_runtime::{PrefixSnapshot, SessionStateView, TranscriptCodec, TurnPreparation}; use tinyinference_llm::message::Message; +use tinymemory_tools::layout::identity::ResolvedIdentity; use super::super::types::OpenHumanSessionHost; use super::OpenHumanTurnPrelude; @@ -82,6 +96,20 @@ pub(super) enum RenderedBlock { Empty, /// The read failed. Failed, + /// The deadline lapsed before the render finished (see + /// `memory_block_ready.rs`): the render goes on in the background. + Deferred, + /// A block rendered ahead of this generation start; `None` when that + /// render found nothing known. + Ready(Option), +} + +/// What a read of memory is made as: the session's config and acting +/// identity. +#[derive(Clone)] +pub(super) struct MemoryScope { + pub(super) config: Arc, + pub(super) identity: ResolvedIdentity, } impl OpenHumanTurnPrelude { @@ -93,31 +121,55 @@ impl OpenHumanTurnPrelude { .map(|block| block.max_tokens) } - /// Reads memory as this session's identity and renders the block. - pub(super) async fn render_memory_block(&self, max_tokens: u32, reason: &str) -> RenderedBlock { - let thread_id = self.thread_id.as_deref().unwrap_or(""); - let agent_id = self.agent_definition_id.as_str(); + /// The config and identity this session reads memory as; `None` when it + /// cannot read memory at all. + pub(super) async fn memory_scope(&self, reason: &str) -> Option { let config = match self.memory_config().await { Some(config) if self.memory_readable() => config, _ => { tracing::debug!( - thread_id, - agent_id, + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), reason, tokens = 0, "[memory_block] empty: memory unavailable to this session" ); - return RenderedBlock::Empty; + return None; } }; let identity = self.memory_identity(&config); - match render::read(&config, &identity, max_tokens).await { + Some(MemoryScope { config, identity }) + } + + /// Reads memory as this session's identity and renders the block. + pub(super) async fn render_memory_block(&self, max_tokens: u32, reason: &str) -> RenderedBlock { + match self.memory_scope(reason).await { + Some(scope) => self.render_in(&scope, max_tokens, reason).await, + None => RenderedBlock::Empty, + } + } + + /// Reads memory within `scope` and renders the block, logging how long it + /// took. + pub(super) async fn render_in( + &self, + scope: &MemoryScope, + max_tokens: u32, + reason: &str, + ) -> RenderedBlock { + let thread_id = self.thread_id.as_deref().unwrap_or(""); + let agent_id = self.agent_definition_id.as_str(); + let started = Instant::now(); + let read = render::read(&scope.config, &scope.identity, max_tokens).await; + let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + match read { Ok(Some(text)) => { tracing::info!( thread_id, agent_id, reason, tokens = tinymemory_tools::recall::estimate_tokens(&text), + elapsed_ms, "[memory_block] rendered" ); RenderedBlock::Block(Message::system(text)) @@ -128,6 +180,7 @@ impl OpenHumanTurnPrelude { agent_id, reason, tokens = 0, + elapsed_ms, "[memory_block] empty" ); RenderedBlock::Empty @@ -138,6 +191,7 @@ impl OpenHumanTurnPrelude { agent_id, reason, %error, + elapsed_ms, "[memory_block] error: keeping the recorded block" ); RenderedBlock::Failed @@ -183,10 +237,11 @@ impl OpenHumanTurnPrelude { None }; let block = match reason { - Some(reason) => match self.render_memory_block(max_tokens, reason).await { + Some(reason) => match self.block_for_generation(max_tokens, reason).await { RenderedBlock::Block(block) => Some(block), + RenderedBlock::Ready(block) => block, RenderedBlock::Empty => None, - RenderedBlock::Failed => recorded.clone(), + RenderedBlock::Failed | RenderedBlock::Deferred => recorded.clone(), }, None => { tracing::debug!( @@ -262,7 +317,10 @@ impl OpenHumanSessionHost { .await { RenderedBlock::Block(block) => Some(block), - RenderedBlock::Empty | RenderedBlock::Failed => None, + RenderedBlock::Empty + | RenderedBlock::Failed + | RenderedBlock::Deferred + | RenderedBlock::Ready(_) => None, } } } diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs new file mode 100644 index 00000000000..f25ef78db2b --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs @@ -0,0 +1,234 @@ +//! Memory blocks rendered ahead of the generation that uses them. +//! +//! A render that finished away from a turn's critical path waits here until +//! the next transcript generation starts: one the deadline lapsed on (see +//! `memory_block.rs`) or one a host asked for ahead of its turn +//! ([`OpenHumanSessionHost::prewarm_memory_block`]). Sessions are built per +//! turn, so the store is process-wide, keyed by what the block was read for: +//! workspace, memory identity and token budget. +//! +//! A block is taken at most once, and only by a generation start, so a +//! generation in flight keeps the prefix it was sent. One older than +//! [`READY_MAX_AGE`] is dropped as stale, and the store holds at most +//! [`READY_CAPACITY`] blocks, the oldest making room. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use tinymemory_tools::layout::identity::ResolvedIdentity; + +use tinyinference_llm::message::Message; + +use super::super::types::OpenHumanSessionHost; +use super::memory_block::{MemoryScope, RenderedBlock}; +use super::OpenHumanTurnPrelude; + +/// What [`OpenHumanSessionHost::prewarm_memory_block`] did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MemoryBlockPrewarm { + /// A block was rendered and is waiting for the next generation start. + Ready, + /// A fresh block was already waiting; nothing was read. + AlreadyReady, + /// The agent has no memory block, or memory is not readable by this + /// session. + Unavailable, + /// The read failed; nothing is waiting. + Failed, +} + +impl OpenHumanSessionHost { + /// Renders the memory block ahead of a turn, for the next generation + /// start of this session's memory identity to take instead of reading + /// memory on the turn's own path. A host calls it when a message arrives + /// and the turn is still some way off. Nothing is read when a fresh block + /// already waits. + pub async fn prewarm_memory_block(&self) -> MemoryBlockPrewarm { + let prelude = self.create_turn_prelude(false); + let Some(max_tokens) = prelude.memory_block_budget() else { + return MemoryBlockPrewarm::Unavailable; + }; + let Some(scope) = prelude.memory_scope("prewarm").await else { + return MemoryBlockPrewarm::Unavailable; + }; + let key = ready_key(&scope, max_tokens); + if contains(&key) { + return MemoryBlockPrewarm::AlreadyReady; + } + match prelude.render_in(&scope, max_tokens, "prewarm").await { + RenderedBlock::Block(block) => put(key, Some(block.text())), + RenderedBlock::Empty => put(key, None), + _ => return MemoryBlockPrewarm::Failed, + } + MemoryBlockPrewarm::Ready + } +} + +impl OpenHumanTurnPrelude { + /// The block a generation start sends: one rendered ahead of it, else a + /// render, within `[memory] memory_block_deadline_ms` when set. A render + /// that outlasts the deadline is [`RenderedBlock::Deferred`] and ends in + /// the store for the next generation start. + pub(super) async fn block_for_generation( + &self, + max_tokens: u32, + reason: &str, + ) -> RenderedBlock { + let Some(scope) = self.memory_scope(reason).await else { + return RenderedBlock::Empty; + }; + let key = ready_key(&scope, max_tokens); + if let Some(ready) = take(&key) { + tracing::info!( + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), + reason, + tokens = ready + .as_deref() + .map_or(0, tinymemory_tools::recall::estimate_tokens), + "[memory_block] ready" + ); + return RenderedBlock::Ready(ready.map(Message::system)); + } + let Some(deadline) = scope + .config + .memory + .memory_block_deadline_ms + .map(Duration::from_millis) + else { + return self.render_in(&scope, max_tokens, reason).await; + }; + let (sender, mut receiver) = tokio::sync::oneshot::channel(); + let prelude = self.clone(); + let reason_owned = reason.to_string(); + let scope_owned = scope.clone(); + self.spawn_memory_work(async move { + let rendered = prelude + .render_in(&scope_owned, max_tokens, &reason_owned) + .await; + // Nobody waiting any more: the render is for the next start. + if let Err(rendered) = sender.send(rendered) { + match rendered { + RenderedBlock::Block(block) => put(key, Some(block.text())), + RenderedBlock::Empty => put(key, None), + _ => {} + } + } + }); + match tokio::time::timeout(deadline, &mut receiver).await { + Ok(Ok(rendered)) => rendered, + // The work was dropped (a retired profile). + Ok(Err(_)) => RenderedBlock::Failed, + Err(_) => { + // Close first, so a render landing now is either received + // here or sent to the store, never lost between the two. + receiver.close(); + if let Ok(rendered) = receiver.try_recv() { + return rendered; + } + tracing::info!( + thread_id = self.thread_id.as_deref().unwrap_or(""), + agent_id = self.agent_definition_id.as_str(), + reason, + deadline_ms = deadline.as_millis() as u64, + "[memory_block] deferred: the render goes on in the background" + ); + RenderedBlock::Deferred + } + } + } +} + +/// What a block read in `scope` with `max_tokens` is stored under. +fn ready_key(scope: &MemoryScope, max_tokens: u32) -> ReadyKey { + ReadyKey { + workspace: scope.config.workspace_dir.clone(), + identity: scope.identity.clone(), + max_tokens, + } +} + +/// How long a rendered block stays usable. +pub(super) const READY_MAX_AGE: Duration = Duration::from_secs(60 * 60); + +/// Most blocks held at once. +pub(super) const READY_CAPACITY: usize = 256; + +/// What a block was read for. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(super) struct ReadyKey { + pub(super) workspace: PathBuf, + pub(super) identity: ResolvedIdentity, + pub(super) max_tokens: u32, +} + +/// Blocks waiting for a generation start. `None` is a render that found +/// nothing known. +#[derive(Default)] +pub(super) struct ReadyBlocks { + entries: Mutex, Instant)>>, +} + +impl ReadyBlocks { + /// Holds `block` for `key`, replacing an earlier one. + pub(super) fn put_at(&self, key: ReadyKey, block: Option, now: Instant) { + let mut entries = self.lock(); + entries.retain(|_, (_, at)| fresh(*at, now)); + if entries.len() >= READY_CAPACITY && !entries.contains_key(&key) { + let oldest = entries + .iter() + .min_by_key(|(_, (_, at))| *at) + .map(|(key, _)| key.clone()); + if let Some(oldest) = oldest { + entries.remove(&oldest); + } + } + entries.insert(key, (block, now)); + } + + /// The block ready for `key`, removed; `None` when there is none or it is + /// stale. `Some(None)` is a ready render that found nothing known. + pub(super) fn take_at(&self, key: &ReadyKey, now: Instant) -> Option> { + let (block, at) = self.lock().remove(key)?; + fresh(at, now).then_some(block) + } + + /// Whether a fresh block is ready for `key`. + pub(super) fn contains_at(&self, key: &ReadyKey, now: Instant) -> bool { + self.lock().get(key).is_some_and(|(_, at)| fresh(*at, now)) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap, Instant)>> { + self.entries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// Whether a block put at `at` is still usable at `now`. +fn fresh(at: Instant, now: Instant) -> bool { + now.saturating_duration_since(at) <= READY_MAX_AGE +} + +static READY: LazyLock = LazyLock::new(ReadyBlocks::default); + +/// Holds `block` for `key` in the process-wide store. +pub(super) fn put(key: ReadyKey, block: Option) { + READY.put_at(key, block, Instant::now()); +} + +/// Takes the block ready for `key` from the process-wide store. +pub(super) fn take(key: &ReadyKey) -> Option> { + READY.take_at(key, Instant::now()) +} + +/// Whether the process-wide store holds a fresh block for `key`. +pub(super) fn contains(key: &ReadyKey) -> bool { + READY.contains_at(key, Instant::now()) +} + +#[cfg(test)] +#[path = "memory_block_ready_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs new file mode 100644 index 00000000000..33fa19acb2d --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready_tests.rs @@ -0,0 +1,85 @@ +use super::*; + +use crate::config::Config; + +fn key(agent: &str, max_tokens: u32) -> ReadyKey { + ReadyKey { + workspace: PathBuf::from("/workspace"), + identity: tinymemory_tools::layout::identity::Identity::agent(agent) + .resolve(&crate::memory::scope::identity_pins(&Config::default())), + max_tokens, + } +} + +#[test] +fn a_ready_block_is_taken_once() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + assert!(ready.contains_at(&key("a", 500), now)); + assert_eq!( + ready.take_at(&key("a", 500), now), + Some(Some("block".into())) + ); + assert_eq!(ready.take_at(&key("a", 500), now), None); + assert!(!ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn a_render_that_found_nothing_is_ready_too() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), None, now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(None)); +} + +#[test] +fn a_block_is_not_taken_for_another_identity_or_budget() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + assert_eq!(ready.take_at(&key("b", 500), now), None); + assert_eq!(ready.take_at(&key("a", 400), now), None); + assert!(ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn a_stale_block_is_dropped() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("block".into()), now); + let later = now + READY_MAX_AGE + Duration::from_secs(1); + assert!(!ready.contains_at(&key("a", 500), later)); + assert_eq!(ready.take_at(&key("a", 500), later), None); + assert_eq!( + ready.take_at(&key("a", 500), now), + None, + "and gone for good" + ); +} + +#[test] +fn a_newer_block_replaces_an_older_one() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key("a", 500), Some("old".into()), now); + ready.put_at(key("a", 500), Some("new".into()), now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(Some("new".into()))); +} + +#[test] +fn the_oldest_block_makes_room_at_capacity() { + let ready = ReadyBlocks::default(); + let start = Instant::now(); + for n in 0..=READY_CAPACITY { + let at = start + Duration::from_millis(n as u64); + ready.put_at(key(&format!("agent-{n}"), 500), Some("block".into()), at); + } + let now = start + Duration::from_secs(1); + assert!( + !ready.contains_at(&key("agent-0", 500), now), + "the oldest left" + ); + assert!(ready.contains_at(&key("agent-1", 500), now)); + assert!(ready.contains_at(&key(&format!("agent-{READY_CAPACITY}"), 500), now)); +} diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs index 4ab0bf5589c..62bcdfd713c 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_tests.rs @@ -2,11 +2,12 @@ use super::*; use std::sync::Arc; use super::super::prompt_refresh::PROMPT_UPDATE_NOTE; +use super::super::MemoryBlockPrewarm; use crate::agent::prompts::SystemPromptBuilder; use crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink; use crate::agent_registry::host_definition::{AgentDefinitionRegistry, MemoryBlock}; use crate::config::Config; -use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine}; +use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine, SlowEngine}; use crate::storage::sessions::splice_fixture_tests::memory_locator; use tinyagents_definition::PromptSource; use tinyagents_runtime::{SessionTurnRequest, TranscriptTarget}; @@ -425,3 +426,213 @@ async fn a_generation_opened_outside_a_turn_can_take_a_fresh_block() { without.definition = Some(Arc::new(definition)); assert_eq!(without.memory_block_for_new_generation().await, None); } + +/// `config` with the memory-block deadline set to `ms`. +fn with_deadline(mut config: Config, ms: u64) -> Config { + config.memory.memory_block_deadline_ms = Some(ms); + config +} + +const SLOW: std::time::Duration = std::time::Duration::from_secs(5); + +/// A resumed thread whose recorded prefix carries a block and whose prompt is +/// replaced: its turn opens a generation and so renders a fresh block. +fn generation_start() -> (PrefixSnapshot, Vec) { + ( + PrefixSnapshot::new(vec![Message::system(PROMPT), block("- teal")]), + vec![ + Message::system(PROMPT), + block("- teal"), + Message::user("hello"), + ], + ) +} + +#[tokio::test(start_paused = true)] +async fn memory_block_render_respects_deadline() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, "You are blocky, v2.", true); + let (recorded, history) = generation_start(); + + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + + assert!( + started.elapsed() <= std::time::Duration::from_millis(400), + "{:?}", + started.elapsed() + ); + let offered = prepared.prefix.expect("a refreshed prefix"); + assert_eq!(offered.messages()[0].text(), "You are blocky, v2."); + assert_eq!(offered.messages().last(), Some(&block("- teal"))); +} + +#[tokio::test(start_paused = true)] +async fn a_cold_thread_sends_no_block_when_the_render_lapses() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + + assert!(started.elapsed() <= std::time::Duration::from_millis(400)); + let messages = sent(&prepared, &empty); + assert!(!messages.iter().any(is_memory_block), "{messages:?}"); + assert_eq!(messages.first().map(Message::text).as_deref(), Some(PROMPT)); +} + +#[tokio::test(start_paused = true)] +async fn deferred_memory_block_is_used_next_generation() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, "You are blocky, v2.", true); + let (recorded, history) = generation_start(); + + let (current, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let current = current.prefix.expect("a refreshed prefix"); + assert_eq!(current.messages().last(), Some(&block("- teal"))); + assert!( + !current + .messages() + .iter() + .any(|m| m.text().contains("Lisbon")), + "the render that lapsed never reaches the generation in flight" + ); + + // The render finishes in the background; the next generation start takes it. + tokio::time::sleep(SLOW).await; + let reads = engine.reads(); + let started = tokio::time::Instant::now(); + let (next, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let next = next.prefix.expect("a refreshed prefix"); + assert!( + next.messages() + .last() + .expect("a block") + .text() + .contains("Lisbon"), + "{next:?}" + ); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + assert_eq!(engine.reads(), reads, "taken, not read again"); +} + +#[tokio::test(start_paused = true)] +async fn a_render_inside_the_deadline_is_used_and_not_kept_for_later() { + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(std::time::Duration::from_millis(100)); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); + assert_eq!(engine.reads(), 2); + + // Nothing was left over, so the next generation start reads again. + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 4); +} + +#[tokio::test(start_paused = true)] +async fn prewarmed_memory_block_skips_render_on_turn() { + let tmp = tempfile::tempdir().unwrap(); + // No deadline: the turn must not render at all. + let config = config_in(&tmp); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + + let host = host(&config, PROMPT, false); + assert_eq!(host.prewarm_memory_block().await, MemoryBlockPrewarm::Ready); + assert_eq!(engine.reads(), 2); + assert_eq!( + host.prewarm_memory_block().await, + MemoryBlockPrewarm::AlreadyReady + ); + assert_eq!( + engine.reads(), + 2, + "a block already waiting is not read again" + ); + + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + let started = tokio::time::Instant::now(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + assert_eq!(engine.reads(), 2, "the turn read nothing"); + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); +} + +#[tokio::test(start_paused = true)] +async fn a_prewarm_is_taken_by_one_generation_start_only() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_millis(10)); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + host(&config, PROMPT, false).prewarm_memory_block().await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 2); + prepare(&prelude, true, &view(&empty, &[], None)).await; + assert_eq!(engine.reads(), 4, "the second start renders for itself"); +} + +#[tokio::test] +async fn a_failed_prewarm_leaves_the_turn_to_render() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + RefusingEngine::out_of_credits().bind(&config); + assert_eq!( + host(&config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Failed + ); + + learn( + &bind_reference(&config), + &config, + "The user lives in Lisbon", + ) + .await; + let prelude = prelude(&config, PROMPT, false); + let empty = PrefixSnapshot::default(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + let messages = sent(&prepared, &empty); + assert!(messages.last().expect("a block").text().contains("Lisbon")); +} + +#[tokio::test] +async fn an_agent_without_a_memory_block_has_nothing_to_prewarm() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + bind_reference(&config); + let mut without = host(&config, PROMPT, false); + let mut definition = (**without.definition.as_ref().expect("a definition")).clone(); + definition.extensions.memory_block = None; + without.definition = Some(Arc::new(definition)); + assert_eq!( + without.prewarm_memory_block().await, + MemoryBlockPrewarm::Unavailable + ); +} diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs index 6158437cd9e..21f05b39066 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/compact.rs @@ -1,6 +1,6 @@ //! Compacting a thread's stored conversation with no model turn. -use crate::agent::session_host::{CompactOptions, CompactOutcome}; +use crate::agent::session_host::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; use crate::config::Config; use super::session_turn::{apply_turn_overrides, build_turn_agent, AgentChatTarget}; @@ -49,3 +49,31 @@ pub fn compact_thread_for<'a>( session.compact_bound_history(options).await }) } + +/// Render `thread_id`'s memory block now, on `target`'s session built as a +/// turn's is, for that thread's next generation start to take. See +/// [`OpenHumanSessionHost::prewarm_memory_block`] +/// (crate::agent::OpenHumanSessionHost::prewarm_memory_block). +/// +/// # Errors +/// +/// When `thread_id` is blank or the session cannot be built. +#[inline(never)] +pub fn prewarm_memory_block_for<'a>( + config: &'a mut Config, + target: AgentChatTarget<'a>, + thread_id: &'a str, +) -> futures::future::BoxFuture<'a, anyhow::Result> { + Box::pin(async move { + let thread_id = thread_id.trim(); + if thread_id.is_empty() { + anyhow::bail!("prewarm_memory_block needs a thread id"); + } + let ctx = crate::core::runtime::DispatchCtx::from_weak(None); + let mut session = build_turn_agent(&ctx, config, &target, Some(thread_id), None, None) + .await + .map_err(anyhow::Error::msg)?; + session.set_thread_id(Some(thread_id)); + Ok(session.prewarm_memory_block().await) + }) +} diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs b/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs index 7609444a90c..daf2e5fdf9a 100644 --- a/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs +++ b/crates/openhuman-core/src/agent_runs/agent_chat/mod.rs @@ -8,7 +8,7 @@ pub(crate) mod guards; pub(crate) mod params; mod session_turn; -pub use compact::compact_thread_for; +pub use compact::{compact_thread_for, prewarm_memory_block_for}; pub use envelope::AgentChatReply; pub use session_turn::{ agent_chat, agent_chat_for, agent_chat_reply_for, agent_chat_reply_for_controlled, diff --git a/crates/openhuman-core/src/config/schema/memory.rs b/crates/openhuman-core/src/config/schema/memory.rs index 6fd7f20cc57..e09e1162001 100644 --- a/crates/openhuman-core/src/config/schema/memory.rs +++ b/crates/openhuman-core/src/config/schema/memory.rs @@ -6,6 +6,7 @@ //! # agent_id = "writer-7" # host binding: every agent on this config is this memory agent //! # root = "team:acme" # host binding: the layout root (one per tenant) //! # recall_each_turn_ms = 1500 # host binding: recall the current message, waiting this long +//! # memory_block_deadline_ms = 300 # host binding: render the memory block for at most this long //! //! [memory.engines.cortexdb] //! endpoint = "https://api-v1.cortexdb.ai" # key in the keychain as "memory-cortexdb" @@ -122,6 +123,14 @@ pub struct MemoryConfig { /// background for an earlier turn. #[serde(skip_serializing_if = "Option::is_none")] pub recall_each_turn_ms: Option, + /// Host binding: wait at most this many milliseconds for the memory block + /// a new transcript generation renders before the first model call. When + /// the deadline lapses the turn keeps the block its thread recorded (a + /// cold thread sends none), and the render finishes in the background + /// for the next generation's start. Unset (the default), a generation + /// start waits for the render however long it takes. + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_block_deadline_ms: Option, /// Where memory sits on the engine: `legacy` (the shared /// `app:tinymemory` tree, the default) or `v3` (the signed-in person's /// own `org:` subtree, chats pooled at `ws:main`). Switched by the @@ -233,6 +242,7 @@ impl Default for MemoryConfig { agent_id: None, root: None, recall_each_turn_ms: None, + memory_block_deadline_ms: None, layout: MemoryLayoutMode::Legacy, conversations: MemoryConversationsConfig::default(), recall: RecallSettings::default(), diff --git a/crates/openhuman-core/src/config/schema/memory_tests.rs b/crates/openhuman-core/src/config/schema/memory_tests.rs index 7bbedc44763..5198d7b876f 100644 --- a/crates/openhuman-core/src/config/schema/memory_tests.rs +++ b/crates/openhuman-core/src/config/schema/memory_tests.rs @@ -415,3 +415,19 @@ fn recall_each_turn_is_an_optional_host_binding_in_milliseconds() { let written = toml::to_string(&config).expect("serializes"); assert!(written.contains("recall_each_turn_ms = 1500"), "{written}"); } + +#[test] +fn memory_block_deadline_is_an_optional_host_binding_in_milliseconds() { + assert_eq!(MemoryConfig::default().memory_block_deadline_ms, None); + let unset = toml::to_string(&MemoryConfig::default()).expect("serializes"); + assert!(!unset.contains("memory_block_deadline_ms"), "{unset}"); + + let config: MemoryConfig = + toml::from_str("memory_block_deadline_ms = 300").expect("the binding parses"); + assert_eq!(config.memory_block_deadline_ms, Some(300)); + let written = toml::to_string(&config).expect("serializes"); + assert!( + written.contains("memory_block_deadline_ms = 300"), + "{written}" + ); +} diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md index b603641184c..5cfe044cbc7 100644 --- a/crates/openhuman-core/src/memory/README.md +++ b/crates/openhuman-core/src/memory/README.md @@ -179,6 +179,14 @@ host already puts in the system prompt: a pack whose every cited hit it excludes is left out (TinyMemory renders the pack, so single lines cannot be dropped yet). +The memory block a new transcript generation renders (see +`agent/session_host/runtime_session/memory_block.rs`) can likewise be taken off +the turn's path: `[memory] memory_block_deadline_ms` (embed: +`MemoryBinding::memory_block_deadline`) bounds the wait, a render that lapses +is kept for the next generation start (`[memory_block] deferred`), and +`Agent::prewarm_memory_block(thread_id)` renders it ahead of a turn. Its +beliefs and learnings are read concurrently. + The live prelude and compaction summarizer call the underlying work directly from the scoped prefetch workers. Their background deadlines bound engine I/O without a second manual timeout wrapper. diff --git a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs index 36c4480386e..2c8e7e1bb4f 100644 --- a/crates/openhuman-core/src/memory/lifecycle/memory_block.rs +++ b/crates/openhuman-core/src/memory/lifecycle/memory_block.rs @@ -14,6 +14,9 @@ //! known renders no block at all, and memory switched off reads as nothing //! known; an engine failure is an error the caller logs and survives. +use std::future::Future; +use std::time::Instant; + use tinymemory_api::{BeliefsRequest, Error, Hit, ListRequest, Reach, Result, BELIEF_TAG}; use tinymemory_tools::layout::identity::ResolvedIdentity; use tinymemory_tools::recall::estimate_tokens; @@ -80,6 +83,7 @@ pub(crate) async fn read( identity: &ResolvedIdentity, max_tokens: u32, ) -> Result> { + let started = Instant::now(); let memory = match super::agent_memory(config, identity).await { Ok(memory) => memory, Err(Error::Off(reason)) => { @@ -88,21 +92,41 @@ pub(crate) async fn read( } Err(error) => return Err(error), }; + let resolve_ms = elapsed_ms(started); let engine = memory.engine(); - let beliefs = engine - .beliefs(BeliefsRequest::new( + // Two independent round trips: overlapped, a hosted engine's latency is + // paid once. + let (beliefs, facts) = futures::try_join!( + timed(engine.beliefs(BeliefsRequest::new( Reach::subtree(identity.root().clone()), BELIEFS_LIMIT, - )) - .await?; - let facts = engine - .list(ListRequest::new( + ))), + timed(engine.list(ListRequest::new( identity.layout.learnings_filter(), FACTS_LIMIT, - )) - .await? - .items; - Ok(render(&beliefs, &facts, max_tokens)) + ))), + )?; + tracing::debug!( + resolve_ms, + beliefs_ms = beliefs.1, + list_ms = facts.1, + beliefs = beliefs.0.len(), + facts = facts.0.items.len(), + "[memory_block] read" + ); + Ok(render(&beliefs.0, &facts.0.items, max_tokens)) +} + +/// Whole milliseconds since `started`. +fn elapsed_ms(started: Instant) -> u64 { + u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +/// `read`'s answer with the milliseconds it took. +async fn timed(read: impl Future>) -> Result<(T, u64)> { + let started = Instant::now(); + let answer = read.await?; + Ok((answer, elapsed_ms(started))) } #[cfg(test)] diff --git a/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs b/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs index f207fe54ea5..ac9cf78200d 100644 --- a/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs +++ b/crates/openhuman-core/src/memory/lifecycle/memory_block_tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine}; +use crate::memory::test_fixtures::{bind_reference, config_in, RefusingEngine, SlowEngine}; use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem}; fn hit(text: &str, tags: &[&str]) -> Hit { @@ -140,3 +140,22 @@ async fn an_engine_failure_is_an_error() { let identity = identity(&config, "block-refused"); assert!(read(&config, &identity, 500).await.is_err()); } + +#[tokio::test(start_paused = true)] +async fn the_beliefs_and_learnings_are_read_together() { + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_secs(3)); + SlowEngine::bind(&engine, &config); + let identity = identity(&config, "block-parallel"); + + let started = tokio::time::Instant::now(); + read(&config, &identity, 500).await.expect("a read"); + + assert_eq!(engine.reads(), 2); + assert_eq!( + started.elapsed(), + std::time::Duration::from_secs(3), + "two reads of 3 s overlap instead of adding up to 6 s" + ); +} diff --git a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs index 855b3a06d16..6653b847cc2 100644 --- a/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs +++ b/crates/openhuman-core/src/memory/lifecycle/session_hooks.rs @@ -147,6 +147,23 @@ impl OpenHumanTurnPrelude { ) } + /// Spawns `work` under the context this session's memory work runs in, so + /// it can outlive the turn that started it. Work of a retired profile is + /// dropped, like a deferred commit. + pub(super) fn spawn_memory_work( + &self, + work: impl std::future::Future + Send + 'static, + ) { + let profile_context = capture_profile_context( + &self.dispatch_ctx(), + crate::profiles::host::host().as_deref(), + ); + drop( + self.dispatch_ctx() + .spawn(deferred_memory_work(profile_context, work)), + ); + } + /// Takes completed memory and queues a user-authored turn's log and recall. /// Remembers the turn so the reply is logged under the same identity and /// index, and returns its memory for the run context without engine I/O. diff --git a/crates/openhuman-core/src/memory/test_fixtures.rs b/crates/openhuman-core/src/memory/test_fixtures.rs index 6f8a9574486..0a78b6ef497 100644 --- a/crates/openhuman-core/src/memory/test_fixtures.rs +++ b/crates/openhuman-core/src/memory/test_fixtures.rs @@ -308,3 +308,106 @@ impl MemoryEngine for RecordingEngine { self.inner.erase(req).await } } + +/// The reference engine with every memory-block read (`beliefs` and `list`) +/// taking `delay` first, the way the hosted engine's round trips do. It counts +/// the reads it served, so a test can tell a render from a reused block. +pub(crate) struct SlowEngine { + inner: Arc, + delay: std::time::Duration, + reads: std::sync::atomic::AtomicUsize, +} + +impl SlowEngine { + /// A slow engine over a fresh reference engine. + pub(crate) fn new(delay: std::time::Duration) -> Arc { + Arc::new(Self { + inner: Arc::new(ReferenceEngine::new()), + delay, + reads: std::sync::atomic::AtomicUsize::new(0), + }) + } + + /// The engine underneath, to store through without the delay. + pub(crate) fn inner(&self) -> &Arc { + &self.inner + } + + /// Binds the engine to `config`'s workspace. + pub(crate) fn bind(engine: &Arc, config: &Config) { + crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone()); + } + + /// How many `beliefs` and `list` reads were served. + pub(crate) fn reads(&self) -> usize { + self.reads.load(std::sync::atomic::Ordering::SeqCst) + } + + async fn slow(&self) { + self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + tokio::time::sleep(self.delay).await; + } +} + +#[async_trait::async_trait] +impl MemoryEngine for SlowEngine { + fn descriptor(&self) -> &tinymemory_api::EngineDescriptor { + self.inner.descriptor() + } + + async fn health(&self) -> tinymemory_api::EngineHealth { + self.inner.health().await + } + + async fn recall( + &self, + req: tinymemory_api::RecallRequest, + ) -> tinymemory_api::Result { + self.inner.recall(req).await + } + + async fn fetch( + &self, + req: tinymemory_api::FetchRequest, + ) -> tinymemory_api::Result { + self.inner.fetch(req).await + } + + async fn store( + &self, + item: tinymemory_api::StoreItem, + ) -> tinymemory_api::Result { + self.inner.store(item).await + } + + async fn forget( + &self, + target: tinymemory_api::ForgetTarget, + ) -> tinymemory_api::Result { + self.inner.forget(target).await + } + + async fn list(&self, req: ListRequest) -> tinymemory_api::Result { + self.slow().await; + self.inner.list(req).await + } + + async fn export(&self, req: ListRequest) -> tinymemory_api::Result { + self.inner.export(req).await + } + + async fn consolidate( + &self, + req: tinymemory_api::ConsolidateRequest, + ) -> tinymemory_api::Result { + self.inner.consolidate(req).await + } + + async fn beliefs( + &self, + req: tinymemory_api::BeliefsRequest, + ) -> tinymemory_api::Result> { + self.slow().await; + self.inner.beliefs(req).await + } +} diff --git a/crates/openhuman-embed/src/agent/README.md b/crates/openhuman-embed/src/agent/README.md index 99faa3354a7..5a1869342fd 100644 --- a/crates/openhuman-embed/src/agent/README.md +++ b/crates/openhuman-embed/src/agent/README.md @@ -31,7 +31,7 @@ with the same id cannot both pass the duplicate check), then calls 5. provider model route stays per turn, never written to config 6. MCP servers appended to mcp_client.servers (mcp feature) 7. Composio credential pinned for this agent only - 8. memory binding memory.agent_id, memory.root, memory.recall_each_turn_ms + 8. memory binding memory.agent_id, memory.root, memory.recall_each_turn_ms, memory.memory_block_deadline_ms 9. config escape hatch then config_path is reset to the runtime's 10. create dirs action_dir, agents//, agents//skills/ 11. copy skills (skills feature) diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs index e5d26078664..0b88ff74e0d 100644 --- a/crates/openhuman-embed/src/agent/build.rs +++ b/crates/openhuman-embed/src/agent/build.rs @@ -178,6 +178,9 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result Result { + let inner = Arc::clone(&self.inner); + if !inner.ctx.domains().inference { + return Err(CoreError::Unavailable { + method: PREWARM_MEMORY_BLOCK, + } + .into()); + } + let ctx = inner.ctx.clone(); + let runtime = inner.runtime.clone(); + let thread_id = thread_id.to_owned(); + let agent = Arc::clone(&inner); + let prewarm = Box::pin(async move { + use openhuman_core::inference::host_runtime::ops::AgentChatTarget; + let host = agent.composed_host_tools(); + let target = AgentChatTarget::Definition { + definition: &agent.definition, + host: host.as_ref(), + seed: None, + usage: None, + host_only: agent.host_only, + untrusted_input: false, + shape: None, + observer: None, + attachments: &[], + }; + let mut config = agent.config.clone(); + openhuman_core::agent_runs::agent_chat::prewarm_memory_block_for( + &mut config, + target, + &thread_id, + ) + .await + .map_err(|error| CoreError::Rpc { + method: PREWARM_MEMORY_BLOCK, + message: error.to_string(), + }) + }); + inner + .lifecycle + .admit( + &inner.id, + PREWARM_MEMORY_BLOCK, + runtime.run_in(ctx, prewarm), + ) + .await + .map_err(Into::into) + } } diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs index cf2a77cd1e9..9aac01ed4ed 100644 --- a/crates/openhuman-embed/src/agent/mod.rs +++ b/crates/openhuman-embed/src/agent/mod.rs @@ -19,7 +19,7 @@ mod approvals; pub use approval_handler::{ApprovalHandler, ApprovalSubscription}; mod attachments; mod compact; -pub use compact::{CompactOptions, CompactOutcome}; +pub use compact::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; pub(crate) mod lifecycle; pub(crate) mod mcp_cleanup; pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval}; diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs index bd89209daf2..755dbae604f 100644 --- a/crates/openhuman-embed/src/agent/spec.rs +++ b/crates/openhuman-embed/src/agent/spec.rs @@ -79,6 +79,7 @@ pub struct MemoryBinding { agent_id: String, root: Option, recall_each_turn: Option, + memory_block_deadline: Option, } impl MemoryBinding { @@ -88,6 +89,7 @@ impl MemoryBinding { agent_id: agent_id.into(), root: None, recall_each_turn: None, + memory_block_deadline: None, } } @@ -115,6 +117,21 @@ impl MemoryBinding { self } + /// Wait at most `deadline` for the memory block + /// ([`AgentDefinitionSpec::memory_block`]) a new transcript generation + /// renders before the turn's first model call. + /// + /// When it lapses, the turn goes on with the block its thread recorded (a + /// new thread with none), and the render finishes in the background for + /// the next generation start. Without this, a generation start waits for + /// the render however long the memory engine takes. + /// [`Agent::prewarm_memory_block`] renders it ahead of a turn instead. + #[must_use] + pub fn memory_block_deadline(mut self, deadline: std::time::Duration) -> Self { + self.memory_block_deadline = Some(deadline); + self + } + /// The memory agent id. pub fn agent_id(&self) -> &str { &self.agent_id @@ -125,6 +142,12 @@ impl MemoryBinding { self.root.as_deref() } + /// How long a generation start waits for its memory block, when + /// [`memory_block_deadline`](Self::memory_block_deadline) is set. + pub fn memory_block_deadline_timeout(&self) -> Option { + self.memory_block_deadline + } + /// How long a turn waits for its own recall, when /// [`recall_each_turn`](Self::recall_each_turn) is set. pub fn recall_each_turn_timeout(&self) -> Option { diff --git a/crates/openhuman-embed/src/agent/spec_tests.rs b/crates/openhuman-embed/src/agent/spec_tests.rs index 88a3493e0e8..e82fe429c39 100644 --- a/crates/openhuman-embed/src/agent/spec_tests.rs +++ b/crates/openhuman-embed/src/agent/spec_tests.rs @@ -70,3 +70,14 @@ fn a_memory_binding_recalls_each_turn_only_when_asked() { ); assert_eq!(binding.root_namespace(), Some("team:acme")); } + +#[test] +fn a_memory_binding_bounds_the_memory_block_only_when_asked() { + let binding = MemoryBinding::new("writer"); + assert_eq!(binding.memory_block_deadline_timeout(), None); + let binding = binding.memory_block_deadline(std::time::Duration::from_millis(300)); + assert_eq!( + binding.memory_block_deadline_timeout(), + Some(std::time::Duration::from_millis(300)) + ); +} diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs index 8a757f23c27..008c61c8798 100644 --- a/crates/openhuman-embed/src/lib.rs +++ b/crates/openhuman-embed/src/lib.rs @@ -177,8 +177,8 @@ pub use openhuman_core::voice::VOICE_COMPILED_IN; pub use agent::ToolAttachmentError; pub use agent::{ Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals, - ApprovalsError, CompactOptions, CompactOutcome, DefinitionBase, MemoryBinding, MemoryBlockSpec, - PendingApproval, SandboxModeSpec, ToolScopeSpec, + ApprovalsError, CompactOptions, CompactOutcome, DefinitionBase, MemoryBinding, + MemoryBlockPrewarm, MemoryBlockSpec, PendingApproval, SandboxModeSpec, ToolScopeSpec, }; pub use auth::{Auth, AuthState, Session}; #[cfg(feature = "channels")] diff --git a/crates/openhuman-embed/tests/runtime_agents.rs b/crates/openhuman-embed/tests/runtime_agents.rs index 1d8025ac1fc..8dff86b44d5 100644 --- a/crates/openhuman-embed/tests/runtime_agents.rs +++ b/crates/openhuman-embed/tests/runtime_agents.rs @@ -560,10 +560,14 @@ fn one_runtime_hosts_independently_configured_agents() { // unbound agent keeps the runtime's defaults. let bound = runtime .agent( - AgentSpec::new("employee") - .memory(MemoryBinding::new("employee-7").root("team:acme")), + AgentSpec::new("employee").memory( + MemoryBinding::new("employee-7") + .root("team:acme") + .memory_block_deadline(std::time::Duration::from_millis(300)), + ), ) .expect("a bound agent instantiates"); + assert_eq!(bound.config().memory.memory_block_deadline_ms, Some(300)); assert_eq!( bound.config().memory.agent_id.as_deref(), Some("employee-7")