diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs index d9adde5cf54..581dbbabbab 100644 --- a/crates/openhuman-core/src/agent/session_host/mod.rs +++ b/crates/openhuman-core/src/agent/session_host/mod.rs @@ -56,6 +56,7 @@ pub(crate) mod test_support; pub use codec::OpenHumanTranscriptCodec; pub type OpenHumanSessionHooks = tinyagents_runtime::FnSessionHooks; +pub(crate) use runtime_session::invalidate_ready_memory_blocks; pub use runtime_session::{CompactOptions, CompactOutcome, MemoryBlockPrewarm}; pub use types::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides}; 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 0e9269b742b..0f7fe361399 100644 --- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs +++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs @@ -10,6 +10,7 @@ pub use compact::{CompactOptions, CompactOutcome}; mod enrichment; pub(super) mod memory_block; mod memory_block_ready; +pub(crate) use memory_block_ready::invalidate as invalidate_ready_memory_blocks; pub use memory_block_ready::MemoryBlockPrewarm; mod permanent; mod post_commit; diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_invalidation_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_invalidation_tests.rs new file mode 100644 index 00000000000..02560cf6a1a --- /dev/null +++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_invalidation_tests.rs @@ -0,0 +1,491 @@ +//! A memory block read before memory changed does not reach a later prompt. + +use super::*; +use crate::agent::session_host::runtime_session::memory_block_ready::MAX_BACKGROUND_RENDERS; + +/// The text of the memory block a new session's first turn is sent, if any. +async fn first_turn_block(config: &Config) -> Option { + let prelude = prelude(config, PROMPT, false); + let empty = PrefixSnapshot::default(); + let (prepared, _) = prepare(&prelude, true, &view(&empty, &[], None)).await; + sent(&prepared, &empty) + .iter() + .find(|m| is_memory_block(m)) + .map(Message::text) +} + +#[tokio::test(start_paused = true)] +async fn a_forgotten_fact_is_not_in_the_next_turns_block_after_a_prewarm() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_millis(10)); + SlowEngine::bind(&engine, &config); + let id = learn(engine.inner(), &config, "The user lives in Lisbon").await; + assert_eq!( + host(&config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Ready + ); + + crate::memory::ops::forget( + &config, + crate::memory::types::ForgetParams { + ids: vec![id], + reach: None, + }, + ) + .await + .expect("forgotten"); + + let block = first_turn_block(&config).await; + assert!( + !block.unwrap_or_default().contains("Lisbon"), + "the block read before the erase must not reach a new prompt" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_fact_learned_after_a_prewarm_is_in_the_next_turns_block() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_millis(10)); + SlowEngine::bind(&engine, &config); + assert_eq!( + host(&config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Ready, + "nothing known yet: an empty block waits" + ); + + crate::memory::ops::learn( + &config, + crate::memory::types::LearnParams { + text: "The user lives in Lisbon".into(), + kind: None, + confidence: None, + meta: None, + }, + None, + ) + .await + .expect("learned"); + + let block = first_turn_block(&config).await; + assert!( + block.unwrap_or_default().contains("Lisbon"), + "the empty block read before the write must not hide it" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_changed_memory_engine_drops_the_waiting_block() { + 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 reads = engine.reads(); + + // What a CortexDB endpoint or key change runs. + crate::memory::engine::invalidate(); + + first_turn_block(&config).await; + assert!( + engine.reads() > reads, + "the turn read memory itself instead of taking the old block" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_render_in_flight_across_an_erase_is_not_kept_for_the_next_turn() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(SLOW); + SlowEngine::bind(&engine, &config); + let id = learn(engine.inner(), &config, "The user lives in Lisbon").await; + let prelude = prelude(&config, "You are blocky, v2.", true); + let (recorded, history) = generation_start(); + + // The render lapses its deadline and goes on in the background... + prepare(&prelude, false, &view(&recorded, &history, None)).await; + // ...and the fact is erased while it reads. + crate::memory::ops::forget( + &config, + crate::memory::types::ForgetParams { + ids: vec![id], + reach: None, + }, + ) + .await + .expect("forgotten"); + tokio::time::sleep(SLOW).await; + + let reads = engine.reads(); + let (next, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let next = next.prefix.expect("a refreshed prefix"); + assert!( + !next.messages().iter().any(|m| m.text().contains("Lisbon")), + "{next:?}" + ); + assert!(engine.reads() > reads, "the stale render was not taken"); +} + +#[tokio::test(start_paused = true)] +async fn a_background_render_is_abandoned_at_its_deadline() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 300); + let engine = SlowEngine::new(std::time::Duration::from_secs(70)); + 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(); + + prepare(&prelude, false, &view(&recorded, &history, None)).await; + tokio::time::sleep(std::time::Duration::from_secs(300)).await; + + let reads = engine.reads(); + let (next, _) = prepare(&prelude, false, &view(&recorded, &history, None)).await; + let next = next.prefix.expect("a refreshed prefix"); + assert!( + !next.messages().iter().any(|m| m.text().contains("Lisbon")), + "a render past its deadline stored nothing" + ); + assert!(engine.reads() > reads, "so the next start rendered again"); +} + +/// Whether a block is waiting for this session's next generation start: a +/// prewarm reads nothing when one is. +async fn a_block_waits(config: &Config) -> bool { + host(config, PROMPT, false).prewarm_memory_block().await == MemoryBlockPrewarm::AlreadyReady +} + +/// What tests that store credentials run under. The security module those go +/// through admits one secret scope per process, so they share one config +/// directory and run one at a time (CI runs each test in its own process). +/// They run in real time too: that module times out under a paused clock. +async fn credential_config() -> (tokio::sync::MutexGuard<'static, ()>, Config) { + static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); + let serial = SERIAL.lock().await; + let config = config_in(DIR.get_or_init(|| tempfile::tempdir().expect("config dir"))); + // Nothing a test before this one left waiting. + crate::memory::lifecycle::prefetch::invalidate(&config); + (serial, config) +} + +/// A bound engine holding one fact, with a block prewarmed from it. +async fn prewarmed(config: &Config) -> Arc { + let engine = SlowEngine::new(std::time::Duration::from_millis(10)); + SlowEngine::bind(&engine, config); + learn(engine.inner(), config, "The user lives in Lisbon").await; + assert_eq!( + host(config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Ready + ); + assert!(a_block_waits(config).await); + engine +} + +#[tokio::test(start_paused = true)] +async fn a_render_inside_the_foreground_deadline_is_not_cut_at_the_background_limit() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = with_deadline(config_in(&tmp), 120_000); + let engine = SlowEngine::new(std::time::Duration::from_secs(90)); + SlowEngine::bind(&engine, &config); + learn(engine.inner(), &config, "The user lives in Lisbon").await; + + let block = first_turn_block(&config).await; + + assert!( + block.unwrap_or_default().contains("Lisbon"), + "a render the turn is still waiting for is not a background one" + ); +} + +#[tokio::test] +async fn storing_the_memory_credential_drops_the_waiting_block() { + let (_serial, config) = credential_config().await; + let _stable = undisturbed(); + prewarmed(&config).await; + + crate::credentials::ops::store_provider_credentials( + &config, + crate::config::schema::MEMORY_CORTEXDB_KEY_NAME, + None, + Some("cdb-key".into()), + None, + None, + ) + .await + .expect("stored"); + + assert!(!a_block_waits(&config).await); +} + +#[tokio::test] +async fn removing_the_memory_credential_drops_the_waiting_block() { + let (_serial, config) = credential_config().await; + let _stable = undisturbed(); + prewarmed(&config).await; + + crate::credentials::ops::remove_provider_credentials( + &config, + crate::config::schema::MEMORY_CORTEXDB_KEY_NAME, + None, + ) + .await + .expect("removed"); + + assert!(!a_block_waits(&config).await); +} + +#[tokio::test] +async fn another_providers_credential_keeps_the_waiting_block() { + let (_serial, config) = credential_config().await; + let _stable = undisturbed(); + prewarmed(&config).await; + + crate::credentials::ops::store_provider_credentials( + &config, + "openai", + None, + Some("sk-other".into()), + None, + None, + ) + .await + .expect("stored"); + + assert!(a_block_waits(&config).await); +} + +#[tokio::test] +async fn storing_the_cortexdb_key_drops_the_waiting_block() { + let (_serial, config) = credential_config().await; + let _stable = undisturbed(); + prewarmed(&config).await; + + crate::memory::engine::store_cortexdb_key(&config, "cdb-key") + .await + .expect("stored"); + + assert!(!a_block_waits(&config).await); +} + +#[tokio::test] +async fn clearing_the_cortexdb_key_drops_the_waiting_block() { + let (_serial, config) = credential_config().await; + let _stable = undisturbed(); + crate::memory::engine::store_cortexdb_key(&config, "cdb-key") + .await + .expect("stored"); + prewarmed(&config).await; + + crate::memory::engine::clear_cortexdb_key(&config) + .await + .expect("cleared"); + + assert!(!a_block_waits(&config).await); +} + +/// Clears the host engine a test installed, even when it fails. +struct ClearHostEngine; + +impl Drop for ClearHostEngine { + fn drop(&mut self) { + crate::memory::engine::clear_host_engine(); + } +} + +#[tokio::test(start_paused = true)] +async fn replacing_the_host_engine_drops_the_waiting_block() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + prewarmed(&config).await; + + let _clear = ClearHostEngine; + crate::memory::engine::install_host_engine(Arc::new( + tinymemory_api::conformance::ReferenceEngine::new(), + )); + + assert!(!a_block_waits(&config).await); +} + +#[tokio::test(start_paused = true)] +async fn clearing_the_host_engine_drops_the_waiting_block() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + prewarmed(&config).await; + + crate::memory::engine::clear_host_engine(); + + assert!(!a_block_waits(&config).await); +} + +#[tokio::test(start_paused = true)] +async fn prewarms_beyond_the_render_limit_are_not_started() { + let _stable = undisturbed(); + let tmps = (0..=MAX_BACKGROUND_RENDERS) + .map(|_| tempfile::tempdir().unwrap()) + .collect::>(); + let configs = tmps.iter().map(config_in).collect::>(); + for config in &configs { + SlowEngine::bind(&SlowEngine::new(SLOW), config); + } + let hosts = configs + .iter() + .map(|config| host(config, PROMPT, false)) + .collect::>(); + + let results = futures::future::join_all(hosts.iter().map(|h| h.prewarm_memory_block())).await; + + let ready = results + .iter() + .filter(|r| **r == MemoryBlockPrewarm::Ready) + .count(); + assert_eq!(ready, MAX_BACKGROUND_RENDERS, "{results:?}"); + assert_eq!( + results + .iter() + .filter(|r| **r == MemoryBlockPrewarm::Failed) + .count(), + 1, + "{results:?}" + ); + + // A finished prewarm freed its slot. + let last = host(&configs[MAX_BACKGROUND_RENDERS], PROMPT, false); + let again = last.prewarm_memory_block().await; + assert!( + matches!( + again, + MemoryBlockPrewarm::Ready | MemoryBlockPrewarm::AlreadyReady + ), + "{again:?}" + ); +} + +#[tokio::test(start_paused = true)] +async fn a_prewarm_is_abandoned_at_the_background_deadline() { + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let config = config_in(&tmp); + let engine = SlowEngine::new(std::time::Duration::from_secs(70)); + SlowEngine::bind(&engine, &config); + + assert_eq!( + host(&config, PROMPT, false).prewarm_memory_block().await, + MemoryBlockPrewarm::Failed + ); + assert!(!a_block_waits(&config).await, "nothing was stored"); +} + +#[tokio::test(start_paused = true)] +async fn generation_starts_beyond_the_render_limit_keep_no_background_render() { + let _stable = undisturbed(); + let tmps = (0..=MAX_BACKGROUND_RENDERS) + .map(|_| tempfile::tempdir().unwrap()) + .collect::>(); + let configs = tmps + .iter() + .map(|tmp| with_deadline(config_in(tmp), 300)) + .collect::>(); + for config in &configs { + SlowEngine::bind(&SlowEngine::new(SLOW), config); + } + let preludes = configs + .iter() + .map(|config| prelude(config, "You are blocky, v2.", true)) + .collect::>(); + let (recorded, history) = generation_start(); + + // Every start lapses its deadline and its render goes on in the + // background, but only eight are admitted there. + let (recorded, history) = (&recorded, &history); + futures::future::join_all(preludes.iter().map(|p| async move { + prepare(p, false, &view(recorded, history, None)).await; + })) + .await; + tokio::time::sleep(SLOW * 2).await; + + let mut waiting = 0; + for config in &configs { + waiting += usize::from(a_block_waits(config).await); + } + assert_eq!(waiting, MAX_BACKGROUND_RENDERS); +} + +#[tokio::test(start_paused = true)] +async fn the_host_engine_is_shared_so_a_write_drops_every_workspaces_block() { + let _stable = undisturbed(); + let one = tempfile::tempdir().unwrap(); + let two = tempfile::tempdir().unwrap(); + let (config_one, config_two) = (config_in(&one), config_in(&two)); + prewarmed(&config_one).await; + prewarmed(&config_two).await; + + let _clear = ClearHostEngine; + crate::memory::engine::install_host_engine(Arc::new( + tinymemory_api::conformance::ReferenceEngine::new(), + )); + host(&config_one, PROMPT, false) + .prewarm_memory_block() + .await; + host(&config_two, PROMPT, false) + .prewarm_memory_block() + .await; + assert!(a_block_waits(&config_two).await); + + crate::memory::lifecycle::prefetch::invalidate(&config_one); + + assert!(!a_block_waits(&config_two).await); +} + +#[tokio::test(start_paused = true)] +async fn another_workspaces_write_keeps_a_block_when_engines_are_not_shared() { + let _stable = undisturbed(); + let one = tempfile::tempdir().unwrap(); + let two = tempfile::tempdir().unwrap(); + let (config_one, config_two) = (config_in(&one), config_in(&two)); + prewarmed(&config_one).await; + prewarmed(&config_two).await; + + crate::memory::lifecycle::prefetch::invalidate(&config_one); + + assert!(!a_block_waits(&config_one).await); + assert!(a_block_waits(&config_two).await); +} + +#[tokio::test(start_paused = true)] +async fn a_background_memory_job_run_drops_the_waiting_block() { + use crate::memory::lifecycle::jobs; + use tinymemory_api::{ConsolidateRequest, ItemKind, Namespace, Reach}; + use tinymemory_tools::queue::Selection; + use tinymemory_tools::BackgroundJob; + + let _stable = undisturbed(); + let tmp = tempfile::tempdir().unwrap(); + let mut config = config_in(&tmp); + config.memory.recall.build_delay_secs = 0; + prewarmed(&config).await; + jobs::enqueue( + &config, + &Namespace::ROOT, + vec![BackgroundJob::BuildBeliefs { + request: ConsolidateRequest::new(Reach::exact(Namespace::agent("a"))) + .kinds([ItemKind::Conversation]), + }], + ) + .await; + + let runs = jobs::run(&config, Selection::Due).await.expect("ran"); + + assert!(!runs.is_empty()); + assert!(!a_block_waits(&config).await); +} 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 index f25ef78db2b..e0f55e95bf5 100644 --- 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 @@ -8,13 +8,17 @@ //! 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 +//! generation in flight keeps the prefix it was sent. A write to memory, its +//! erasure, or a change of its engine or credentials drops the waiting blocks +//! and voids the renders in flight, so nothing read before reaches a later +//! generation; a render never stores over one that started after it. 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::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex}; use std::time::{Duration, Instant}; use tinymemory_tools::layout::identity::ResolvedIdentity; @@ -50,16 +54,38 @@ impl OpenHumanSessionHost { let Some(max_tokens) = prelude.memory_block_budget() else { return MemoryBlockPrewarm::Unavailable; }; - let Some(scope) = prelude.memory_scope("prewarm").await else { + let Some((scope, ticket)) = prelude.scope_and_ticket("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), + // A prewarm is background work like a render past its deadline: a + // slow engine must not pile up callers' renders, so it takes a slot + // and is bounded by the same deadline. + let Some(_slot) = BACKGROUND_RENDERS.acquire() else { + tracing::warn!( + thread_id = prelude.thread_id.as_deref().unwrap_or(""), + agent_id = prelude.agent_definition_id.as_str(), + limit = MAX_BACKGROUND_RENDERS, + "[memory_block] too many renders in the background, skipping this prewarm" + ); + return MemoryBlockPrewarm::Failed; + }; + let render = prelude.render_in(&scope, max_tokens, "prewarm"); + let Ok(rendered) = tokio::time::timeout(BACKGROUND_RENDER_DEADLINE, render).await else { + tracing::warn!( + thread_id = prelude.thread_id.as_deref().unwrap_or(""), + agent_id = prelude.agent_definition_id.as_str(), + limit_secs = BACKGROUND_RENDER_DEADLINE.as_secs(), + "[memory_block] prewarm abandoned at its deadline" + ); + return MemoryBlockPrewarm::Failed; + }; + match rendered { + RenderedBlock::Block(block) => put(key, Some(block.text()), ticket), + RenderedBlock::Empty => put(key, None, ticket), _ => return MemoryBlockPrewarm::Failed, } MemoryBlockPrewarm::Ready @@ -76,7 +102,7 @@ impl OpenHumanTurnPrelude { max_tokens: u32, reason: &str, ) -> RenderedBlock { - let Some(scope) = self.memory_scope(reason).await else { + let Some((scope, ticket)) = self.scope_and_ticket(reason).await else { return RenderedBlock::Empty; }; let key = ready_key(&scope, max_tokens); @@ -100,19 +126,67 @@ impl OpenHumanTurnPrelude { else { return self.render_in(&scope, max_tokens, reason).await; }; - let (sender, mut receiver) = tokio::sync::oneshot::channel(); + let (mut sender, mut receiver) = tokio::sync::oneshot::channel(); let prelude = self.clone(); let reason_owned = reason.to_string(); let scope_owned = scope.clone(); + let thread_id = self.thread_id.clone().unwrap_or_default(); + let agent_id = self.agent_definition_id.clone(); self.spawn_memory_work(async move { - let rendered = prelude - .render_in(&scope_owned, max_tokens, &reason_owned) - .await; + let mut render = Box::pin(prelude.render_in(&scope_owned, max_tokens, &reason_owned)); + // The turn waits for the render up to its deadline. + let rendered = match tokio::time::timeout(deadline, &mut render).await { + Ok(rendered) => rendered, + Err(_) => { + // Past it the render is background work, which a slow + // engine must not pile up: at the limit it is dropped, + // and the next generation start renders for itself. + let Some(_slot) = BACKGROUND_RENDERS.acquire() else { + tracing::warn!( + thread_id = thread_id.as_str(), + agent_id = agent_id.as_str(), + reason = reason_owned.as_str(), + limit = MAX_BACKGROUND_RENDERS, + "[memory_block] too many renders in the background, dropping this one" + ); + // Held until the turn has moved on, so it reads a + // deferred render, not a dropped one. + sender.closed().await; + return; + }; + let Ok(rendered) = + tokio::time::timeout(BACKGROUND_RENDER_DEADLINE, &mut render).await + else { + tracing::warn!( + thread_id = thread_id.as_str(), + agent_id = agent_id.as_str(), + reason = reason_owned.as_str(), + limit_secs = BACKGROUND_RENDER_DEADLINE.as_secs(), + "[memory_block] background render abandoned at its deadline" + ); + return; + }; + rendered + } + }; + // A change of memory while it read voided it: the waiting + // generation gets no block rather than the one read before. + let rendered = if ticket.is_live() { + rendered + } else { + tracing::info!( + thread_id = thread_id.as_str(), + agent_id = agent_id.as_str(), + reason = reason_owned.as_str(), + "[memory_block] render voided by a memory change, dropping it" + ); + RenderedBlock::Failed + }; // 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), + RenderedBlock::Block(block) => put(key, Some(block.text()), ticket), + RenderedBlock::Empty => put(key, None, ticket), _ => {} } } @@ -141,6 +215,24 @@ impl OpenHumanTurnPrelude { } } +impl OpenHumanTurnPrelude { + /// The scope a read is made in, with the ticket for it. The ticket is + /// taken before the (possibly slow) config load, so a change of memory + /// while the scope resolves voids the render instead of slipping between + /// the two. + async fn scope_and_ticket(&self, reason: &str) -> Option<(MemoryScope, Ticket)> { + let early = ticket(&self.workspace_dir); + let scope = self.memory_scope(reason).await?; + if scope.config.workspace_dir == self.workspace_dir { + return Some((scope, early)); + } + // The config names another workspace: that is the one to watch. + drop(early); + let ticket = ticket(&scope.config.workspace_dir); + Some((scope, ticket)) + } +} + /// What a block read in `scope` with `max_tokens` is stored under. fn ready_key(scope: &MemoryScope, max_tokens: u32) -> ReadyKey { ReadyKey { @@ -164,46 +256,212 @@ pub(super) struct ReadyKey { pub(super) max_tokens: u32, } -/// Blocks waiting for a generation start. `None` is a render that found -/// nothing known. +/// Most renders left running in the background past their deadline at once. +pub(super) const MAX_BACKGROUND_RENDERS: usize = 8; + +/// How long a render may go on in the background, past the deadline the turn +/// waited for it, before it is abandoned. +pub(super) const BACKGROUND_RENDER_DEADLINE: Duration = Duration::from_secs(60); + +static BACKGROUND_RENDERS: RenderSlots = RenderSlots::new(MAX_BACKGROUND_RENDERS); + +/// A fixed number of places for background renders. +pub(super) struct RenderSlots { + limit: usize, + taken: AtomicUsize, +} + +impl RenderSlots { + pub(super) const fn new(limit: usize) -> Self { + Self { + limit, + taken: AtomicUsize::new(0), + } + } + + /// A place for one more render; `None` when all are taken. The place is + /// freed when the returned guard drops. + pub(super) fn acquire(&'static self) -> Option { + let mut taken = self.taken.load(Ordering::Acquire); + while taken < self.limit { + match self.taken.compare_exchange_weak( + taken, + taken + 1, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return Some(RenderSlot(self)), + Err(now) => taken = now, + } + } + None + } +} + +/// One admitted background render, released on drop. +pub(super) struct RenderSlot(&'static RenderSlots); + +impl Drop for RenderSlot { + fn drop(&mut self) { + self.0.taken.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Held by a render from its start. Its block may be stored only while no +/// invalidation of its workspace (or of everything) has run since, and never +/// over a block from a render that started after it (`seq`). Dropped +/// without storing, it is forgotten. +pub(super) struct Ticket { + state: Arc>, + seq: u64, + /// Whether the store still tracks this ticket. + tracked: bool, +} + +impl Ticket { + /// Whether no invalidation has voided this render since it started. + pub(super) fn is_live(&self) -> bool { + lock(&self.state).in_flight.contains_key(&self.seq) + } +} + +impl Drop for Ticket { + fn drop(&mut self) { + if self.tracked { + lock(&self.state).in_flight.remove(&self.seq); + } + } +} + +/// A stored block: `None` once taken, its sequence staying behind so an older +/// render cannot store its own afterwards; then the block, which is itself +/// `None` for a render that found nothing known. +struct Entry { + block: Option>, + at: Instant, + seq: u64, +} + +#[derive(Default)] +struct State { + entries: HashMap, + /// The renders in flight, by sequence, and the workspace each reads. + in_flight: HashMap, + /// Counts renders started. + seq: u64, +} + +fn lock(state: &Mutex) -> std::sync::MutexGuard<'_, State> { + state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Blocks waiting for a generation start. #[derive(Default)] pub(super) struct ReadyBlocks { - entries: Mutex, Instant)>>, + state: Arc>, } 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)); + /// A ticket for a render about to start for `workspace`. + pub(super) fn ticket(&self, workspace: &Path) -> Ticket { + let mut state = self.lock(); + state.seq += 1; + let seq = state.seq; + state.in_flight.insert(seq, workspace.to_path_buf()); + Ticket { + state: Arc::clone(&self.state), + seq, + tracked: true, + } + } + + /// Drops every block (those of `workspace` only when given) and voids the + /// ticket of every render in flight for it (for all, when none is given), + /// so none of them can store a block read before the change that called + /// this. + pub(super) fn invalidate(&self, workspace: Option<&Path>) { + let mut state = self.lock(); + match workspace { + Some(workspace) => { + state.entries.retain(|key, _| key.workspace != workspace); + state.in_flight.retain(|_, reads| reads != workspace); + } + None => { + state.entries.clear(); + state.in_flight.clear(); + } + } + } + + /// Holds `block` for `key`, replacing an earlier one, unless `ticket` is + /// void or older than the block already there, taken or not. + pub(super) fn put_ticketed_at( + &self, + key: ReadyKey, + block: Option, + mut ticket: Ticket, + now: Instant, + ) { + let mut state = self.lock(); + ticket.tracked = false; + if state.in_flight.remove(&ticket.seq).is_none() { + return; + } + let entries = &mut state.entries; + entries.retain(|_, entry| fresh(entry.at, now)); + if entries.get(&key).is_some_and(|held| held.seq > ticket.seq) { + return; + } if entries.len() >= READY_CAPACITY && !entries.contains_key(&key) { let oldest = entries .iter() - .min_by_key(|(_, (_, at))| *at) + .min_by_key(|(_, entry)| entry.at) .map(|(key, _)| key.clone()); if let Some(oldest) = oldest { entries.remove(&oldest); } } - entries.insert(key, (block, now)); + entries.insert( + key, + Entry { + block: Some(block), + at: now, + seq: ticket.seq, + }, + ); + } + + /// Holds `block` for `key`, replacing an earlier one. + #[cfg(test)] + pub(super) fn put_at(&self, key: ReadyKey, block: Option, now: Instant) { + let ticket = self.ticket(&key.workspace); + self.put_ticketed_at(key, block, ticket, now); } - /// The block ready for `key`, removed; `None` when there is none or it is + /// The block ready for `key`, taken; `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) + let mut state = self.lock(); + let entry = state.entries.get_mut(key)?; + if !fresh(entry.at, now) { + state.entries.remove(key); + return None; + } + entry.block.take() } /// 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)) + self.lock() + .entries + .get(key) + .is_some_and(|entry| entry.block.is_some() && fresh(entry.at, now)) } - fn lock(&self) -> std::sync::MutexGuard<'_, HashMap, Instant)>> { - self.entries - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + lock(&self.state) } } @@ -214,9 +472,22 @@ fn fresh(at: Instant, now: Instant) -> bool { static READY: LazyLock = LazyLock::new(ReadyBlocks::default); +/// A ticket for a render about to start for `workspace`; see [`Ticket`]. +pub(super) fn ticket(workspace: &Path) -> Ticket { + READY.ticket(workspace) +} + /// Holds `block` for `key` in the process-wide store. -pub(super) fn put(key: ReadyKey, block: Option) { - READY.put_at(key, block, Instant::now()); +pub(super) fn put(key: ReadyKey, block: Option, ticket: Ticket) { + READY.put_ticketed_at(key, block, ticket, Instant::now()); +} + +/// Drops the waiting blocks (of one workspace, or all) and voids renders in +/// flight. Called when memory is written to, erased, or its engine or +/// credentials change, so a block read before cannot reach a later +/// generation. +pub(crate) fn invalidate(workspace: Option<&Path>) { + READY.invalidate(workspace); } /// Takes the block ready for `key` from the process-wide store. 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 index 33fa19acb2d..d74a30ebc38 100644 --- 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 @@ -1,10 +1,16 @@ use super::*; +use std::path::Path; + use crate::config::Config; fn key(agent: &str, max_tokens: u32) -> ReadyKey { + key_in("/workspace", agent, max_tokens) +} + +fn key_in(workspace: &str, agent: &str, max_tokens: u32) -> ReadyKey { ReadyKey { - workspace: PathBuf::from("/workspace"), + workspace: PathBuf::from(workspace), identity: tinymemory_tools::layout::identity::Identity::agent(agent) .resolve(&crate::memory::scope::identity_pins(&Config::default())), max_tokens, @@ -83,3 +89,179 @@ fn the_oldest_block_makes_room_at_capacity() { assert!(ready.contains_at(&key("agent-1", 500), now)); assert!(ready.contains_at(&key(&format!("agent-{READY_CAPACITY}"), 500), now)); } + +#[test] +fn an_older_render_finishing_later_does_not_replace_a_newer_block() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let older = ready.ticket(Path::new("/workspace")); + let newer = ready.ticket(Path::new("/workspace")); + ready.put_ticketed_at(key("a", 500), Some("new".into()), newer, now); + ready.put_ticketed_at(key("a", 500), Some("old".into()), older, now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(Some("new".into()))); +} + +#[test] +fn a_newer_render_replaces_the_block_of_an_older_one() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let older = ready.ticket(Path::new("/workspace")); + let newer = ready.ticket(Path::new("/workspace")); + ready.put_ticketed_at(key("a", 500), Some("old".into()), older, now); + ready.put_ticketed_at(key("a", 500), Some("new".into()), newer, now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(Some("new".into()))); +} + +#[test] +fn an_invalidation_drops_every_waiting_block() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key_in("/one", "a", 500), Some("block".into()), now); + ready.put_at(key_in("/two", "a", 500), None, now); + ready.invalidate(None); + assert!(!ready.contains_at(&key_in("/one", "a", 500), now)); + assert!(!ready.contains_at(&key_in("/two", "a", 500), now)); +} + +#[test] +fn an_invalidation_of_one_workspace_keeps_the_blocks_of_others() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.put_at(key_in("/one", "a", 500), Some("block".into()), now); + ready.put_at(key_in("/two", "a", 500), Some("block".into()), now); + ready.invalidate(Some(std::path::Path::new("/one"))); + assert!(!ready.contains_at(&key_in("/one", "a", 500), now)); + assert!(ready.contains_at(&key_in("/two", "a", 500), now)); +} + +#[test] +fn an_invalidation_of_one_workspace_does_not_void_renders_in_flight_for_others() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let in_flight = ready.ticket(Path::new("/two")); + ready.invalidate(Some(Path::new("/one"))); + ready.put_ticketed_at( + key_in("/two", "a", 500), + Some("block".into()), + in_flight, + now, + ); + assert!(ready.contains_at(&key_in("/two", "a", 500), now)); +} + +#[test] +fn an_invalidation_of_one_workspace_voids_renders_in_flight_for_it() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let in_flight = ready.ticket(Path::new("/one")); + ready.invalidate(Some(Path::new("/one"))); + ready.put_ticketed_at( + key_in("/one", "a", 500), + Some("block".into()), + in_flight, + now, + ); + assert!(!ready.contains_at(&key_in("/one", "a", 500), now)); +} + +#[test] +fn an_invalidation_voids_a_render_already_in_flight() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let in_flight = ready.ticket(Path::new("/workspace")); + ready.invalidate(None); + ready.put_ticketed_at(key("a", 500), Some("read before".into()), in_flight, now); + assert!(!ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn a_render_started_after_an_invalidation_may_store_its_block() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + ready.invalidate(None); + let after = ready.ticket(Path::new("/workspace")); + ready.put_ticketed_at(key("a", 500), Some("block".into()), after, now); + assert!(ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn background_renders_are_admitted_up_to_the_limit_and_freed_when_done() { + static SLOTS: RenderSlots = RenderSlots::new(2); + let first = SLOTS.acquire().expect("first"); + let _second = SLOTS.acquire().expect("second"); + assert!(SLOTS.acquire().is_none(), "the limit holds"); + drop(first); + assert!( + SLOTS.acquire().is_some(), + "a finished render frees its slot" + ); +} + +#[test] +fn background_renders_run_at_most_eight_at_once_for_at_most_a_minute() { + assert_eq!(MAX_BACKGROUND_RENDERS, 8); + assert_eq!(BACKGROUND_RENDER_DEADLINE, Duration::from_secs(60)); +} + +#[test] +fn a_render_older_than_a_block_already_taken_does_not_store_its_own() { + let ready = ReadyBlocks::default(); + let now = Instant::now(); + let older = ready.ticket(Path::new("/workspace")); + let newer = ready.ticket(Path::new("/workspace")); + ready.put_ticketed_at(key("a", 500), Some("new".into()), newer, now); + assert_eq!(ready.take_at(&key("a", 500), now), Some(Some("new".into()))); + ready.put_ticketed_at(key("a", 500), Some("old".into()), older, now); + assert!(!ready.contains_at(&key("a", 500), now)); +} + +#[test] +fn invalidating_idle_workspaces_leaves_nothing_behind() { + let ready = ReadyBlocks::default(); + for n in 0..100 { + ready.invalidate(Some(Path::new(&format!("/workspace-{n}")))); + } + ready.invalidate(None); + let state = ready.lock(); + assert!(state.entries.is_empty()); + assert!(state.in_flight.is_empty()); +} + +#[test] +fn a_render_that_ends_without_a_block_is_forgotten() { + let ready = ReadyBlocks::default(); + drop(ready.ticket(Path::new("/workspace"))); + assert!(ready.lock().in_flight.is_empty()); +} + +#[test] +fn a_render_that_stored_its_block_is_forgotten() { + let ready = ReadyBlocks::default(); + let ticket = ready.ticket(Path::new("/workspace")); + ready.put_ticketed_at(key("a", 500), None, ticket, Instant::now()); + assert!(ready.lock().in_flight.is_empty()); +} + +#[test] +fn a_voided_render_that_ends_is_forgotten_without_harm() { + let ready = ReadyBlocks::default(); + let voided = ready.ticket(Path::new("/workspace")); + let live = ready.ticket(Path::new("/workspace")); + ready.invalidate(Some(Path::new("/workspace"))); + drop(voided); + assert!(ready.lock().in_flight.is_empty()); + drop(live); +} + +#[test] +fn a_ticket_is_live_until_an_invalidation_voids_it() { + let ready = ReadyBlocks::default(); + let one = ready.ticket(Path::new("/one")); + let two = ready.ticket(Path::new("/two")); + assert!(one.is_live() && two.is_live()); + ready.invalidate(Some(Path::new("/one"))); + assert!(!one.is_live(), "voided by an invalidation of its workspace"); + assert!(two.is_live(), "another workspace's render is untouched"); + ready.invalidate(None); + assert!(!two.is_live()); +} 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 62bcdfd713c..fb98ae9ce60 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 @@ -56,8 +56,13 @@ fn prelude(config: &Config, prompt: &str, refresh: bool) -> OpenHumanTurnPrelude state.prelude.clone().expect("prelude") } -/// Files `text` as a learning every agent under the config's root sees. -async fn learn(engine: &tinymemory_api::conformance::ReferenceEngine, config: &Config, text: &str) { +/// Files `text` as a learning every agent under the config's root sees, +/// returning its id. +async fn learn( + engine: &tinymemory_api::conformance::ReferenceEngine, + config: &Config, + text: &str, +) -> String { let (_, identity) = crate::memory::lifecycle::current_agent_memory( config, &tinymemory_tools::layout::identity::Identity::root(), @@ -75,7 +80,9 @@ async fn learn(engine: &tinymemory_api::conformance::ReferenceEngine, config: &C }, )) .await - .expect("stored"); + .expect("stored") + .id + .0 } fn block(text: &str) -> Message { @@ -433,6 +440,14 @@ fn with_deadline(mut config: Config, ms: u64) -> Config { config } +/// Held by a test whose render is in flight across awaits, so another test's +/// engine invalidation (which voids every render in flight) cannot reach it. +fn undisturbed() -> std::sync::RwLockWriteGuard<'static, ()> { + crate::memory::engine::CACHE_STABLE + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + const SLOW: std::time::Duration = std::time::Duration::from_secs(5); /// A resumed thread whose recorded prefix carries a block and whose prompt is @@ -492,6 +507,7 @@ async fn a_cold_thread_sends_no_block_when_the_render_lapses() { #[tokio::test(start_paused = true)] async fn deferred_memory_block_is_used_next_generation() { + let _stable = undisturbed(); let tmp = tempfile::tempdir().unwrap(); let config = with_deadline(config_in(&tmp), 300); let engine = SlowEngine::new(SLOW); @@ -531,6 +547,7 @@ async fn deferred_memory_block_is_used_next_generation() { #[tokio::test(start_paused = true)] async fn a_render_inside_the_deadline_is_used_and_not_kept_for_later() { + let _stable = undisturbed(); let tmp = tempfile::tempdir().unwrap(); let config = with_deadline(config_in(&tmp), 300); let engine = SlowEngine::new(std::time::Duration::from_millis(100)); @@ -551,6 +568,7 @@ async fn a_render_inside_the_deadline_is_used_and_not_kept_for_later() { #[tokio::test(start_paused = true)] async fn prewarmed_memory_block_skips_render_on_turn() { + let _stable = undisturbed(); let tmp = tempfile::tempdir().unwrap(); // No deadline: the turn must not render at all. let config = config_in(&tmp); @@ -584,6 +602,7 @@ async fn prewarmed_memory_block_skips_render_on_turn() { #[tokio::test(start_paused = true)] async fn a_prewarm_is_taken_by_one_generation_start_only() { + let _stable = undisturbed(); let tmp = tempfile::tempdir().unwrap(); let config = config_in(&tmp); let engine = SlowEngine::new(std::time::Duration::from_millis(10)); @@ -636,3 +655,6 @@ async fn an_agent_without_a_memory_block_has_nothing_to_prewarm() { MemoryBlockPrewarm::Unavailable ); } + +#[path = "memory_block_invalidation_tests.rs"] +mod invalidation; diff --git a/crates/openhuman-core/src/credentials/ops/provider_credentials.rs b/crates/openhuman-core/src/credentials/ops/provider_credentials.rs index cfda6260cb2..1f81da146a8 100644 --- a/crates/openhuman-core/src/credentials/ops/provider_credentials.rs +++ b/crates/openhuman-core/src/credentials/ops/provider_credentials.rs @@ -2,6 +2,7 @@ use serde_json::json; +use crate::config::schema::MEMORY_CORTEXDB_KEY_NAME; use crate::config::Config; use crate::core::Outcome; use crate::credentials::session_state::{ @@ -53,6 +54,7 @@ pub async fn store_provider_credentials( // notify again). Credentials are keyed `provider:`; the auth-error // registry is keyed by the bare provider slug used by the chat factory. clear_provider_auth_error(&provider); + drop_memory_read_with(&provider); Ok(Outcome::single_log( summarize_auth_profile(&stored), "provider credentials stored", @@ -67,6 +69,17 @@ fn clear_provider_auth_error(provider: &str) { crate::inference::auth_error_registry::clear(slug); } +/// A change to the memory engine's API key leaves what memory was read with +/// the old one behind, so it is dropped. +fn drop_memory_read_with(provider: &str) { + if provider + .trim() + .eq_ignore_ascii_case(MEMORY_CORTEXDB_KEY_NAME) + { + crate::memory::lifecycle::prefetch::invalidate_all(); + } +} + pub async fn remove_provider_credentials( config: &Config, provider: &str, @@ -81,6 +94,7 @@ pub async fn remove_provider_credentials( // Removing the key clears any recorded BYO auth error for this provider — // there is no longer a key to be "rejected", so the stale notice must go. clear_provider_auth_error(provider); + drop_memory_read_with(provider); Ok(Outcome::single_log( json!({ "removed": removed, diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs index 16a50ea4c3b..c3283ad429f 100644 --- a/crates/openhuman-core/src/memory/engine.rs +++ b/crates/openhuman-core/src/memory/engine.rs @@ -140,12 +140,23 @@ pub fn install_host_engine(engine: Arc) { let id = engine.descriptor().id.to_string(); tracing::info!(engine = %id, "[memory:engine] host engine installed"); ENGINE_BINDER.install_host_engine(engine, crate::memory::host_policy::host_policy()); + // What was read from the engine before is not what this one holds. + super::lifecycle::prefetch::invalidate_all(); +} + +/// Whether the process-wide host engine is serving every workspace: one is +/// installed and this process admits it (never in SaaS). +pub(crate) fn host_engine_is_shared() -> bool { + ENGINE_BINDER.host_engine().is_some() + && admits_host_engine_with(crate::core::runtime::is_saas()) } /// Removes a host-installed engine; the configured engine applies again. /// Returns whether one was installed. pub fn clear_host_engine() -> bool { - ENGINE_BINDER.clear_host_engine() + let cleared = ENGINE_BINDER.clear_host_engine(); + super::lifecycle::prefetch::invalidate_all(); + cleared } /// Resolves the configured engine. @@ -577,15 +588,19 @@ pub async fn store_cortexdb_key(config: &Config, key: &str) -> Result<()> { .await .map_err(|error| Error::Engine(format!("storing the API key failed: {error}")))?; tracing::debug!("[memory:engine] cortexdb key stored"); + // Memory read under the old key is not the new key's account's. + super::lifecycle::prefetch::invalidate_all(); Ok(()) } /// Removes the stored CortexDB API key. pub async fn clear_cortexdb_key(config: &Config) -> Result { - AuthService::from_config(config) + let removed = AuthService::from_config(config) .remove_profile(MEMORY_CORTEXDB_KEY_NAME, DEFAULT_AUTH_PROFILE_NAME) .await - .map_err(|error| Error::Engine(format!("removing the API key failed: {error}"))) + .map_err(|error| Error::Engine(format!("removing the API key failed: {error}")))?; + super::lifecycle::prefetch::invalidate_all(); + Ok(removed) } /// Whether the engine `id` has a credential available. diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rs index 2fc312c777f..375a66ec70f 100644 --- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs +++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs @@ -110,7 +110,7 @@ pub async fn snapshot(config: &Config) -> QueueState { /// recorded; see `tinymemory_tools::queue::JobQueue::run` for the retry rules. pub async fn run(config: &Config, selection: Selection) -> Result> { let bound = engine::resolve(config).await.engine()?; - queue_of(&config.workspace_dir) + let runs = queue_of(&config.workspace_dir) .run( bound.engine, selection, @@ -119,7 +119,14 @@ pub async fn run(config: &Config, selection: Selection) -> Result> { .await .map_err(|error| match error { QueueError::NoSuchJob(_) => Error::InvalidRequest(error.to_string()), - }) + })?; + if !runs.is_empty() { + // A job that ran, even one that failed part way, may have changed + // what memory holds (beliefs built, say): a block read before it, or + // a read still in flight, must not reach a later prompt. + super::prefetch::invalidate(config); + } + Ok(runs) } /// The cron entry point: runs due jobs unless background work is paused. diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs index f000b7fda67..588a33a7d86 100644 --- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs +++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs @@ -125,12 +125,21 @@ fn cache(ctx: &DispatchCtx) -> Arc { /// successful memory writes and erasure; no engine work runs here. pub(crate) fn invalidate(config: &Config) { CACHES.invalidate_where(|key| key.workspace == config.workspace_dir); + // A memory block rendered ahead of a generation holds what was just + // written over or erased; it must not reach a later prompt. + // The host engine is one store for every workspace in the process, so a + // change through one workspace reaches the blocks of all of them. + let shared = crate::memory::engine::host_engine_is_shared(); + crate::agent::session_host::invalidate_ready_memory_blocks( + (!shared).then_some(config.workspace_dir.as_path()), + ); } /// Clears all automatic packs after engine or credential invalidation. Old /// in-flight completions cannot recreate entries they no longer own. pub(crate) fn invalidate_all() { CACHES.invalidate_all(); + crate::agent::session_host::invalidate_ready_memory_blocks(None); } fn completed(cache: &Cache, key: &Key) -> Option { diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs index ab10397a360..bb65dc12588 100644 --- a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs +++ b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs @@ -264,6 +264,9 @@ async fn expiration_failure_and_oversized_packs_are_not_reused() { #[tokio::test] async fn credential_invalidation_removes_ready_and_rejects_late_inflight_results() { + let _stable = crate::memory::engine::CACHE_STABLE + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); let _guard = TEST_LOCK.lock().await; let tmp = tempfile::tempdir().unwrap(); let config = config_in(&tmp); diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 9f49bd19247..edfbd350977 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -756,7 +756,17 @@ "type": "LazyLock", "count": 1, "category": "B", - "reason": "Rendered memory blocks wait here for the next generation start. Every key combines the session's workspace directory, its resolved memory identity (profile and agent) and the token budget, so a block is only ever taken by the identity it was read for; the store holds at most READY_CAPACITY entries, each dropped after READY_MAX_AGE.", - "verification": "agent/session_host/runtime_session/memory_block_ready_tests.rs: a_block_is_not_taken_for_another_identity_or_budget" + "reason": "Rendered memory blocks wait here for the next generation start. Every key combines the session's workspace directory, its resolved memory identity (profile and agent) and the token budget, so a block is only ever taken by the identity it was read for; the store holds at most READY_CAPACITY entries, each dropped after READY_MAX_AGE. A write to or erasure of memory, or a change of its engine or credentials, drops the blocks of the workspace (all of them for an engine or credential change) and voids the renders then in flight, so a block read before cannot be stored or taken afterwards.", + "verification": "agent/session_host/runtime_session/memory_block_ready_tests.rs: an_invalidation_of_one_workspace_keeps_the_blocks_of_others" + }, + { + "file": "crates/openhuman-core/src/agent/session_host/runtime_session/memory_block_ready.rs", + "scope": "", + "name": "BACKGROUND_RENDERS", + "type": "RenderSlots", + "count": 1, + "category": "A", + "reason": "A counter of memory-block renders left running in the background past their deadline, capped at MAX_BACKGROUND_RENDERS so a slow memory engine cannot pile up tasks and requests. It holds a number only and carries no tenant data.", + "verification": "agent/session_host/runtime_session/memory_block_ready_tests.rs: background_renders_are_admitted_up_to_the_limit_and_freed_when_done" } ]