Skip to content

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

feat: queue memory writes and prefetch context off live turns

Steven Enamakel95c7af81b6af
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
index ce423d758b..d96f0e70fb 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
@@ -1,8 +1,8 @@
//! The session host's memory hooks: the pre-turn pack and the post-turn log.
//!
//! Before the model runs, [`OpenHumanTurnPrelude::memory_pre_turn`] logs the
-//! user turn and recalls the pack the turn is given
-//! (`memory::lifecycle::hooks::pre_turn`); `MemoryPackMiddleware` then adds the
+//! user turn and refreshes memory in the background, taking a completed cached
+//! pack immediately (`memory::lifecycle::prefetch::pre_turn`); `MemoryPackMiddleware` then adds the
//! pack to the turn's requests without persisting it. After the durable
//! commit, [`OpenHumanTurnPrelude::memory_post_turn`] logs the reply with its
//! tool calls. Both run under the session's own config, so a host binding set
@@ -71,9 +71,9 @@ impl OpenHumanTurnPrelude {
.ok()
}
- /// Logs a user-authored turn and recalls its pack. Remembers the turn so
- /// the reply is logged under the same identity and index, and returns
- /// the turn's memory for the run context.
+ /// 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.
/// `origin` is the turn's origin as the run context carries it (the
/// session host never reads the task-local one); a channel turn is
/// logged as observed from its sender
@@ -97,9 +97,6 @@ impl OpenHumanTurnPrelude {
if self.omit_memory_context {
identity.recall = false;
}
- if config.memory.conversations.enabled {
- crate::memory::channels::record(&config.workspace_dir, &self.event_channel, &thread_id);
- }
let user_index = hooks::user_turn_index(committed_turns);
let (in_prompt_from, compacted) = in_prompt_window(history, committed_turns, current);
self.mutable
@@ -109,9 +106,9 @@ impl OpenHumanTurnPrelude {
identity: identity.clone(),
user_index,
});
- let pack = hooks::pre_turn(
- &config,
- &identity,
+ let pack = crate::memory::lifecycle::prefetch::pre_turn(
+ config.clone(),
+ identity.clone(),
PreTurnInput {
thread_id: thread_id.clone(),
turn_index: user_index,
@@ -123,8 +120,8 @@ impl OpenHumanTurnPrelude {
.as_ref()
.and_then(crate::memory::lifecycle::sender::channel_actor),
},
- )
- .await;
+ Some(self.event_channel.clone()),
+ );
Some(Arc::new(MemoryTurn {
config,
identity,
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
index 33608ed2bb..54efefd95b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
@@ -2,11 +2,10 @@
//! folds away rides into the checkpoint that replaces them.
//!
//! [`MemoryRecallSummarizer`] wraps the turn's summarizer. While the inner
-//! summarizer folds the dropped messages, it asks memory for the same span
-//! (`memory::lifecycle::hooks::compaction` → TinyMemory's
-//! `recall_for_compaction`: an answered summary of the thread plus the
-//! standard sections), concurrently and under its own timeout. A non-empty
-//! pack is appended to the summary under "Recalled from memory". The
+//! summarizer folds the dropped messages, it queues memory's refresh of that
+//! span and takes only completed cached context. A non-empty cached pack is
+//! appended under "Recalled from memory"; engine I/O never delays the inner
+//! summarizer. The
//! checkpoint is a fresh user-role message after a compaction, which already
//! resets the provider's cache from that point, so it costs no warm prefix.
//!
@@ -21,7 +20,7 @@ use tinyagents_harness::summarization::{Summarizer, SummaryRecord, SummaryReques
use tinyinference_llm::message::{ContentBlock, Message};
use tinymemory_api::{Role, Turn};
-use crate::memory::lifecycle::hooks::{self, MemoryTurn};
+use crate::memory::lifecycle::hooks::MemoryTurn;
/// Heading of the recalled section in a checkpoint.
pub(crate) const RECALLED_HEADING: &str = "## Recalled from memory";
@@ -50,14 +49,13 @@ impl MemoryRecallSummarizer {
messages: &[Message],
summary: impl std::future::Future<Output = Result<SummaryRecord>>,
) -> Result<SummaryRecord> {
- let recall = hooks::compaction(
- &self.turn.config,
- &self.turn.identity,
- &self.turn.thread_id,
+ let pack = crate::memory::lifecycle::prefetch::compaction(
+ self.turn.config.clone(),
+ self.turn.identity.clone(),
+ self.turn.thread_id.clone(),
dropped_turns(messages),
);
- let (record, pack) = futures::join!(summary, recall);
- let mut record = record?;
+ let mut record = summary.await?;
// A later compaction folds the previous checkpoint, recall included;
// keep one recall section, the current one.
strip_recalled(&mut record.summary);
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
index 668b3cfd50..051ff42c8f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
@@ -74,10 +74,19 @@ fn only_user_and_assistant_text_become_turns() {
}
#[tokio::test]
-async fn the_checkpoint_carries_what_memory_recalls() {
+async fn the_checkpoint_uses_completed_memory_without_waiting_for_refresh() {
let tmp = tempfile::tempdir().unwrap();
let turn = bound_turn(&tmp).await;
- let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn));
+ let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn.clone()));
+ let cold = summarizer.summarize(&dropped()).await.unwrap();
+ assert!(!cold.summary.text().contains(RECALLED_HEADING));
+ crate::memory::lifecycle::prefetch::settle_for_test(
+ &turn.config,
+ &turn.identity,
+ &turn.thread_id,
+ true,
+ )
+ .await;
let record = summarizer.summarize(&dropped()).await.unwrap();
let text = record.summary.text();
assert!(text.contains(RECALLED_HEADING), "{text}");
@@ -129,10 +138,109 @@ fn an_earlier_recall_section_is_dropped_before_the_new_one() {
async fn a_second_compaction_keeps_one_recall_section() {
let tmp = tempfile::tempdir().unwrap();
let turn = bound_turn(&tmp).await;
- let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn));
+ let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn.clone()));
+ summarizer.summarize(&dropped()).await.unwrap();
+ crate::memory::lifecycle::prefetch::settle_for_test(
+ &turn.config,
+ &turn.identity,
+ &turn.thread_id,
+ true,
+ )
+ .await;
let first = summarizer.summarize(&dropped()).await.unwrap();
let mut again = dropped();
again.insert(0, first.summary.clone());
let second = summarizer.summarize(&again).await.unwrap();
assert_eq!(second.summary.text().matches(RECALLED_HEADING).count(), 1);
}
+
+struct HeldRecall {
+ inner: tinymemory_api::conformance::ReferenceEngine,
+}
+#[async_trait::async_trait]
+impl tinymemory_api::MemoryEngine for HeldRecall {
+ 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<tinymemory_api::RecallAnswer> {
+ std::future::pending().await
+ }
+
+ async fn fetch(
+ &self,
+ _req: tinymemory_api::FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ std::future::pending().await
+ }
+
+ async fn store(
+ &self,
+ _item: tinymemory_api::StoreItem,
+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
+ std::future::pending().await
+ }
+
+ async fn forget(
+ &self,
+ _target: tinymemory_api::ForgetTarget,
+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
+ std::future::pending().await
+ }
+
+ async fn list(
+ &self,
+ _req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ std::future::pending().await
+ }
+
+ async fn export(
+ &self,
+ _req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ExportPage> {
+ std::future::pending().await
+ }
+
+ async fn consolidate(
+ &self,
+ _req: tinymemory_api::ConsolidateRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ConsolidateReceipt> {
+ std::future::pending().await
+ }
+}
+
+#[tokio::test]
+async fn a_held_memory_engine_does_not_delay_transcript_compaction() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ crate::memory::engine::install_test_engine(
+ &config.workspace_dir,
+ Arc::new(HeldRecall {
+ inner: tinymemory_api::conformance::ReferenceEngine::new(),
+ }),
+ );
+ let identity = MemoryIdentity::agent("orchestrator").resolve(&config);
+ let turn = Arc::new(MemoryTurn {
+ config: Arc::new(config),
+ identity,
+ thread_id: "held".into(),
+ pack: None,
+ });
+ let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn));
+ let record = tokio::time::timeout(
+ std::time::Duration::from_millis(100),
+ summarizer.summarize(&dropped()),
+ )
+ .await
+ .expect("memory must not hold the inner summarizer")
+ .unwrap();
+ assert!(record.summary.text().contains("March 3rd"));
+}
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index 2adcb3b6ab..c1b686210d 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -71,6 +71,7 @@ impl EventHandler<DomainEvent> for PendingDeletionsSubscriber {
/// Runs the deletions queued while memory was off, after a credential of
/// `kind` was stored.
pub(crate) async fn drain_pending_deletions(config: &crate::config::Config, kind: &str) -> usize {
+ super::tool_writes::schedule_all(Arc::new(config.clone()));
let settled = super::deletion::drain(config).await;
tracing::debug!(kind = %kind, settled, "[memory:bus] pending deletions drained after sign-in");
settled
@@ -139,6 +140,7 @@ pub async fn run_system_job(config: &crate::config::Config, job: &str) {
);
}
BACKGROUND_JOB => {
+ super::tool_writes::schedule_all(Arc::new(config.clone()));
super::import::resume_interrupted(config).await;
super::layout_migration::tick(
config,
diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs
index 2ce4c8c7d6..257f8e0f9f 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -575,6 +575,7 @@ pub fn invalidate() {
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
+ super::lifecycle::prefetch::invalidate_all();
}
/// The stored CortexDB API key, if any.
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
index 9b43203e3c..c39144d6d4 100644
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@ -191,6 +191,40 @@ pub async fn pre_turn(
config: &Config,
identity: &ResolvedIdentity,
input: PreTurnInput,
+) -> Option<TurnPack> {
+ let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));
+ let started = std::time::Instant::now();
+ let agent_id = identity.agent_id.clone();
+ let config = config.clone();
+ let identity = identity.clone();
+ let thread = input.thread_id.clone();
+ let task = crate::core::runtime::spawn_scoped(async move {
+ pre_turn_work(&config, &identity, input).await
+ });
+ let pack = match tokio::time::timeout(timeout, task).await {
+ Ok(Ok(pack)) => pack,
+ Ok(Err(error)) => {
+ tracing::warn!(thread_id = %thread, %error, "[memory:hooks] pre_turn task failed");
+ None
+ }
+ Err(_) => {
+ tracing::warn!(thread_id = %thread, timeout_ms = timeout.as_millis() as u64, "[memory:hooks] pre_turn timed out; the turn runs without a pack");
+ None
+ }
+ };
+ if let Some(pack) = &pack {
+ crate::memory::tools::record_pack_citations(&thread, pack.citations.clone());
+ }
+ tracing::debug!(thread_id = %thread, %agent_id, injected = pack.is_some(), tokens = pack.as_ref().map_or(0, |pack| pack.tokens), refs = pack.as_ref().map_or(0, |pack| pack.refs.len()), elapsed_ms = started.elapsed().as_millis() as u64, "[memory:hooks] pre_turn");
+ pack
+}
+
+/// The direct lifecycle operation for bounded background workers. Unlike the
+/// manual timeout wrapper, its future owns all I/O and can be cancelled.
+pub(crate) async fn pre_turn_work(
+ config: &Config,
+ identity: &ResolvedIdentity,
+ input: PreTurnInput,
) -> Option<TurnPack> {
let logging = config.memory.conversations.enabled;
if !logging && !identity.recall {
@@ -218,9 +252,6 @@ pub async fn pre_turn(
memory.with_policy(quiet)
};
let recall = identity.recall;
- let thread_id = input.thread_id.clone();
- let agent_id = identity.agent_id.clone();
- let started = std::time::Instant::now();
let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));
// Runs beside the turn log and the reads (tinymemory joins all three) and
// answers by the turn's own deadline less a margin, counted from now, so
@@ -238,7 +269,7 @@ pub async fn pre_turn(
.flatten()
}
});
- let task = tokio::spawn(async move {
+ let pack = async move {
// The first turn after a compaction gets one pack that leads with the
// thread's earlier turns, under the turn's own budget and dedupe.
let resumed = recall && input.resumed_after_compaction;
@@ -302,34 +333,8 @@ pub async fn pre_turn(
);
TurnPack::refused(&error, engine_id)
})
- });
- let pack = match tokio::time::timeout(timeout, task).await {
- Ok(Ok(pack)) => pack,
- Ok(Err(error)) => {
- tracing::warn!(%error, "[memory:hooks] pre_turn task failed");
- None
- }
- Err(_) => {
- tracing::warn!(
- thread_id = %thread_id,
- timeout_ms = timeout.as_millis() as u64,
- "[memory:hooks] pre_turn timed out; the turn runs without a pack"
- );
- None
- }
- };
- if let Some(pack) = &pack {
- crate::memory::tools::record_pack_citations(&thread_id, pack.citations.clone());
}
- tracing::debug!(
- thread_id = %thread_id,
- agent_id = %agent_id,
- injected = pack.is_some(),
- tokens = pack.as_ref().map_or(0, |pack| pack.tokens),
- refs = pack.as_ref().map_or(0, |pack| pack.refs.len()),
- elapsed_ms = started.elapsed().as_millis() as u64,
- "[memory:hooks] pre_turn"
- );
+ .await;
pack
}
@@ -470,6 +475,28 @@ pub async fn compaction(
identity: &ResolvedIdentity,
thread_id: &str,
dropped: Vec<Turn>,
+) -> Option<TurnPack> {
+ let timeout = Duration::from_millis(config.memory.recall.compaction_timeout_ms.max(1));
+ match tokio::time::timeout(
+ timeout,
+ compaction_work(config, identity, thread_id, dropped),
+ )
+ .await
+ {
+ Ok(pack) => pack,
+ Err(_) => {
+ tracing::warn!(thread_id, "[memory:hooks] compaction recall timed out");
+ None
+ }
+ }
+}
+
+/// Direct compaction recall, owned and cancelled by the background worker.
+pub(crate) async fn compaction_work(
+ config: &Config,
+ identity: &ResolvedIdentity,
+ thread_id: &str,
+ dropped: Vec<Turn>,
) -> Option<TurnPack> {
if !identity.recall || dropped.is_empty() || thread_id.trim().is_empty() {
return None;
@@ -482,17 +509,12 @@ pub async fn compaction(
dropped,
focus: None,
};
- let timeout = Duration::from_millis(config.memory.recall.compaction_timeout_ms.max(1));
- let pack = match tokio::time::timeout(timeout, memory.recall_for_compaction(request)).await {
- Ok(Ok(pack)) => TurnPack::from_packs([pack]),
- Ok(Err(error)) => {
+ let pack = match memory.recall_for_compaction(request).await {
+ Ok(pack) => TurnPack::from_packs([pack]),
+ Err(error) => {
tracing::warn!(%error, "[memory:hooks] compaction recall failed");
None
}
- Err(_) => {
- tracing::warn!(thread_id, "[memory:hooks] compaction recall timed out");
- None
- }
};
tracing::debug!(
thread_id,
diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rs
index 8859ad00e2..f9757f03cd 100644
--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs
@@ -7,17 +7,19 @@
//!
//! | Hook | When | Call |
//! | --- | --- | --- |
-//! | [`hooks::pre_turn`] | before the model runs, once per turn | logs the user turn and recalls the pack the turn is given |
+//! | [`prefetch`] | before the model runs, once per turn | takes completed cached memory and queues user logging and refresh |
//! | [`hooks::post_turn`] | after the turn is committed | logs the reply and queues the belief builds it hands back |
-//! | [`hooks::compaction`] | when the transcript is compacted | recalls what the compacted turns carried |
+//! | [`prefetch`] | when the transcript is compacted | enriches from completed memory and queues recall of the folded span |
//! | [`jobs`] | the `memory_background` cron job | runs queued belief builds and deferred ingests |
//!
-//! Every hook is bounded by a timeout and never fails a turn: an engine
-//! outage degrades memory, it does not block the agent.
+//! Automatic hooks never await engine I/O. The explicit/manual hook primitives
+//! remain timeout-bounded; an engine outage degrades memory without blocking
+//! the live agent.
pub mod date_hint;
pub mod hooks;
pub mod jobs;
+pub(crate) mod prefetch;
pub mod sender;
pub mod views;
diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
new file mode 100644
index 0000000000..7e46d37294
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
@@ -0,0 +1,384 @@
+//! Best-effort, scoped automatic memory refresh. Turns only read completed
+//! packs; all engine work and date extraction run in bounded background workers.
+//! Packs live in memory for one minute and are never persisted by this adapter.
+
+use std::collections::{HashMap, VecDeque};
+use std::hash::{Hash, Hasher};
+use std::path::PathBuf;
+use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
+use std::time::{Duration, Instant};
+
+use futures::future::BoxFuture;
+use tokio::sync::Semaphore;
+
+use crate::config::Config;
+use crate::core::runtime::{current_slot, spawn_scoped};
+use crate::memory::scope::ResolvedIdentity;
+
+use super::hooks::{self, PreTurnInput, TurnPack};
+
+const TTL: Duration = Duration::from_secs(60);
+const WORK_TIMEOUT: Duration = Duration::from_secs(120);
+const MAX_ENTRIES: usize = 64;
+const MAX_PENDING: usize = 16;
+const MAX_PACK_BYTES: usize = 64 * 1024;
+static WORKERS: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(8)));
+static CACHES: LazyLock<Mutex<Vec<Weak<Cache>>>> = LazyLock::new(Mutex::default);
+
+type Work = BoxFuture<'static, Option<TurnPack>>;
+
+#[derive(Clone, Hash, PartialEq, Eq)]
+struct Key {
+ workspace: PathBuf,
+ config: u64,
+ identity: ResolvedIdentity,
+ thread: String,
+ compaction: bool,
+}
+
+impl Key {
+ fn new(config: &Config, identity: &ResolvedIdentity, thread: &str, compaction: bool) -> Self {
+ let mut fingerprint = std::collections::hash_map::DefaultHasher::new();
+ // Keep only the digest, never serialized settings or credentials.
+ serde_json::to_value(config)
+ .ok()
+ .and_then(|value| serde_json::to_vec(&value).ok())
+ .unwrap_or_default()
+ .hash(&mut fingerprint);
+ config.config_path.hash(&mut fingerprint);
+ config.action_dir.hash(&mut fingerprint);
+ Self {
+ workspace: config.workspace_dir.clone(),
+ config: fingerprint.finish(),
+ identity: identity.clone(),
+ thread: thread.to_owned(),
+ compaction,
+ }
+ }
+}
+
+struct Entry {
+ ticket: u64,
+ revision: u64,
+ pack: Option<(Instant, TurnPack)>,
+ pending: VecDeque<Work>,
+ active: bool,
+ touched: Instant,
+}
+
+#[derive(Default)]
+struct State {
+ entries: HashMap<Key, Entry>,
+ next_ticket: u64,
+}
+
+#[derive(Default)]
+struct Cache(Mutex<State>);
+
+fn cache() -> Arc<Cache> {
+ let cache = current_slot::<Cache>();
+ let mut caches = CACHES.lock().unwrap_or_else(PoisonError::into_inner);
+ caches.retain(|known| known.strong_count() > 0);
+ if !caches
+ .iter()
+ .any(|known| known.ptr_eq(&Arc::downgrade(&cache)))
+ {
+ caches.push(Arc::downgrade(&cache));
+ }
+ cache
+}
+
+/// Discards completed packs for this workspace, across its agent contexts.
+/// Pending conversation logs are preserved; results of reads already in flight
+/// cannot republish after invalidation. Call after
+/// successful memory writes and erasure; no engine work runs here.
+pub(crate) fn invalidate(config: &Config) {
+ let mut caches = CACHES.lock().unwrap_or_else(PoisonError::into_inner);
+ caches.retain(|known| {
+ let Some(cache) = known.upgrade() else {
+ return false;
+ };
+ cache
+ .0
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entries
+ .iter_mut()
+ .filter(|(key, _)| key.workspace == config.workspace_dir)
+ .for_each(|(_, entry)| {
+ entry.pack = None;
+ entry.revision = entry.revision.wrapping_add(1);
+ });
+ true
+ });
+}
+
+/// 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() {
+ let mut caches = CACHES.lock().unwrap_or_else(PoisonError::into_inner);
+ caches.retain(|known| {
+ let Some(cache) = known.upgrade() else {
+ return false;
+ };
+ cache
+ .0
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entries
+ .clear();
+ true
+ });
+}
+
+fn completed(cache: &Cache, key: &Key) -> Option<TurnPack> {
+ let mut state = cache.0.lock().unwrap_or_else(PoisonError::into_inner);
+ let entry = state.entries.get_mut(key)?;
+ entry.touched = Instant::now();
+ if entry
+ .pack
+ .as_ref()
+ .is_some_and(|(at, _)| at.elapsed() >= TTL)
+ {
+ entry.pack = None;
+ }
+ entry.pack.as_ref().map(|(_, pack)| pack.clone())
+}
+
+/// Returns the last completed pack immediately, then logs this user turn and
+/// refreshes its context in the background. A cold cache returns `None`.
+/// Omitted recall still logs, but cannot consume another identity's pack.
+pub(crate) fn pre_turn(
+ config: Arc<Config>,
+ identity: ResolvedIdentity,
+ input: PreTurnInput,
+ channel: Option<String>,
+) -> Option<TurnPack> {
+ if !config.memory.conversations.enabled && !identity.recall {
+ return None;
+ }
+ let cache = cache();
+ let key = Key::new(&config, &identity, &input.thread_id, false);
+ let pack = identity.recall.then(|| completed(&cache, &key)).flatten();
+ tracing::debug!(thread_id = %key.thread, agent_id = %key.identity.agent_id, cache_hit = pack.is_some(), "[memory:prefetch] pre_turn cache");
+ if let Some(pack) = &pack {
+ crate::memory::tools::record_pack_citations(&input.thread_id, pack.citations.clone());
+ }
+ enqueue(
+ cache,
+ key,
+ Box::pin(crate::core::runtime::spawn::scoped(async move {
+ if config.memory.conversations.enabled {
+ if let Some(channel) = channel {
+ let workspace = config.workspace_dir.clone();
+ let thread = input.thread_id.clone();
+ let _ = crate::core::runtime::spawn_blocking_scoped(move || {
+ crate::memory::channels::record(&workspace, &channel, &thread)
+ })
+ .await;
+ }
+ }
+ hooks::pre_turn_work(&config, &identity, input).await
+ })),
+ );
+ pack.map(cached_notice)
+}
+
+fn cached_notice(mut pack: TurnPack) -> TurnPack {
+ let notice = "This is cached memory from a completed background lookup for an earlier turn. It may be incomplete or unrelated to the current question; use explicit memory recall or fetch when you need a current answer.\n\n";
+ pack.markdown.insert_str(0, notice);
+ pack.tokens += tinymemory_tools::recall::estimate_tokens(notice);
+ pack
+}
+
+/// Uses only completed context while queuing recall of the folded span. The
+/// authoritative summarizer never waits for this refresh.
+pub(crate) fn compaction(
+ config: Arc<Config>,
+ identity: ResolvedIdentity,
+ thread: String,
+ dropped: Vec<tinymemory_api::Turn>,
+) -> Option<TurnPack> {
+ if !identity.recall || dropped.is_empty() {
+ return None;
+ }
+ let cache = cache();
+ let key = Key::new(&config, &identity, &thread, true);
+ let pack = completed(&cache, &key)
+ .or_else(|| completed(&cache, &Key::new(&config, &identity, &thread, false)));
+ enqueue(
+ cache,
+ key,
+ Box::pin(crate::core::runtime::spawn::scoped(async move {
+ hooks::compaction_work(&config, &identity, &thread, dropped).await
+ })),
+ );
+ pack.map(cached_notice)
+}
+
+fn enqueue(cache: Arc<Cache>, key: Key, work: Work) {
+ let mut state = cache.0.lock().unwrap_or_else(PoisonError::into_inner);
+ if !state.entries.contains_key(&key) {
+ if state.entries.len() >= MAX_ENTRIES {
+ let oldest = state
+ .entries
+ .iter()
+ .filter(|(_, entry)| !entry.active)
+ .min_by_key(|(_, entry)| entry.touched)
+ .map(|(key, _)| key.clone());
+ let Some(oldest) = oldest else {
+ tracing::warn!("[memory:prefetch] cache busy; automatic refresh skipped");
+ return;
+ };
+ state.entries.remove(&oldest);
+ }
+ state.next_ticket = state.next_ticket.wrapping_add(1);
+ let ticket = state.next_ticket;
+ state.entries.insert(
+ key.clone(),
+ Entry {
+ ticket,
+ revision: 0,
+ pack: None,
+ pending: VecDeque::new(),
+ active: false,
+ touched: Instant::now(),
+ },
+ );
+ }
+ let entry = state.entries.get_mut(&key).expect("inserted");
+ if entry.pending.len() >= MAX_PENDING {
+ tracing::warn!("[memory:prefetch] queue full; automatic refresh skipped");
+ return;
+ }
+ // No waiting task is created when capacity is exhausted.
+ let permit = if entry.active {
+ None
+ } else {
+ let Ok(permit) = WORKERS.clone().try_acquire_owned() else {
+ tracing::warn!("[memory:prefetch] workers busy; automatic refresh skipped");
+ return;
+ };
+ Some(permit)
+ };
+ entry.pending.push_back(work);
+ entry.touched = Instant::now();
+ let ticket = entry.ticket;
+ tracing::debug!(thread_id = %key.thread, agent_id = %key.identity.agent_id, compaction = key.compaction, ticket, pending = entry.pending.len(), "[memory:prefetch] refresh queued");
+ if entry.active {
+ return;
+ }
+ entry.active = true;
+ drop(state);
+ let cleanup = Worker {
+ cache: cache.clone(),
+ key: key.clone(),
+ ticket,
+ armed: true,
+ };
+ spawn_scoped(async move {
+ let _permit = permit;
+ let mut cleanup = cleanup;
+ loop {
+ let (work, revision) = {
+ let mut state = cache.0.lock().unwrap_or_else(PoisonError::into_inner);
+ let Some(entry) = state
+ .entries
+ .get_mut(&key)
+ .filter(|entry| entry.ticket == ticket)
+ else {
+ return;
+ };
+ let Some(work) = entry.pending.pop_front() else {
+ entry.active = false;
+ cleanup.armed = false;
+ return;
+ };
+ (work, entry.revision)
+ };
+ let started = Instant::now();
+ let pack = match tokio::time::timeout(WORK_TIMEOUT, work).await {
+ Ok(pack) => pack.filter(|pack| {
+ serde_json::to_vec(pack)
+ .ok()
+ .zip(serde_json::to_vec(&pack.citations).ok())
+ .is_some_and(|(pack, citations)| {
+ pack.len().saturating_add(citations.len()) <= MAX_PACK_BYTES
+ })
+ }),
+ Err(_) => {
+ tracing::warn!(thread_id = %key.thread, agent_id = %key.identity.agent_id, compaction = key.compaction, ticket, "[memory:prefetch] automatic refresh timed out");
+ None
+ }
+ };
+ tracing::debug!(thread_id = %key.thread, agent_id = %key.identity.agent_id, compaction = key.compaction, ticket, completed = pack.is_some(), elapsed_ms = started.elapsed().as_millis() as u64, "[memory:prefetch] refresh completed");
+ let mut state = cache.0.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(entry) = state
+ .entries
+ .get_mut(&key)
+ .filter(|entry| entry.ticket == ticket)
+ {
+ if entry.revision == revision {
+ entry.pack = pack.map(|pack| (Instant::now(), pack));
+ }
+ }
+ }
+ });
+}
+
+// Cancellation/runtime shutdown and panics must release the active flag as
+// well as the semaphore permit; a subsequent turn can retry normally.
+struct Worker {
+ cache: Arc<Cache>,
+ key: Key,
+ ticket: u64,
+ armed: bool,
+}
+impl Drop for Worker {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let mut state = self.cache.0.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(entry) = state
+ .entries
+ .get_mut(&self.key)
+ .filter(|entry| entry.ticket == self.ticket)
+ {
+ entry.active = false;
+ entry.pending.clear();
+ }
+ }
+}
+
+#[cfg(test)]
+pub(crate) async fn settle_for_test(
+ config: &Config,
+ identity: &ResolvedIdentity,
+ thread: &str,
+ compaction: bool,
+) {
+ let cache = cache();
+ let key = Key::new(config, identity, thread, compaction);
+ tokio::time::timeout(Duration::from_secs(2), async {
+ loop {
+ if cache
+ .0
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entries
+ .get(&key)
+ .is_some_and(|entry| !entry.active)
+ {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("automatic memory refresh completed");
+}
+
+#[cfg(test)]
+#[path = "prefetch_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
new file mode 100644
index 0000000000..57e582ebc1
--- /dev/null
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch_tests.rs
@@ -0,0 +1,433 @@
+use super::*;
+
+use crate::memory::scope::MemoryIdentity;
+use crate::memory::test_fixtures::config_in;
+
+static TEST_LOCK: LazyLock<tokio::sync::Mutex<()>> = LazyLock::new(|| tokio::sync::Mutex::new(()));
+
+fn pack(text: &str) -> TurnPack {
+ TurnPack {
+ markdown: text.into(),
+ tokens: 1,
+ refs: vec![],
+ engine: "test".into(),
+ citations: vec![],
+ refusal: None,
+ }
+}
+
+async fn drain(cache: &Cache, key: &Key) {
+ tokio::time::timeout(Duration::from_secs(1), async {
+ loop {
+ if cache
+ .0
+ .lock()
+ .unwrap()
+ .entries
+ .get(key)
+ .is_some_and(|entry| !entry.active)
+ {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("worker completed");
+}
+
+#[tokio::test]
+async fn held_refresh_returns_immediately_and_later_turn_reads_completed_context() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ let release = Arc::new(tokio::sync::Notify::new());
+ let held = release.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async move {
+ held.notified().await;
+ Some(pack("later result"))
+ }),
+ );
+ assert!(
+ completed(&cache, &key).is_none(),
+ "cold refresh never waits"
+ );
+ release.notify_one();
+ drain(&cache, &key).await;
+ assert_eq!(completed(&cache, &key).unwrap().markdown, "later result");
+}
+
+#[tokio::test]
+async fn identity_config_thread_workspace_and_context_are_isolated() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("private")) }),
+ );
+ drain(&cache, &key).await;
+ let mut changed = config.clone();
+ changed.memory.recall.brain_limit += 1;
+ let mut omitted = identity.clone();
+ omitted.recall = false;
+ let mut other_root = identity.clone();
+ other_root.layout = tinymemory_tools::MemoryLayout::new("team:other".parse().unwrap()).unwrap();
+ let mut workspace = config.clone();
+ workspace.workspace_dir = tmp.path().join("other");
+ for other in [
+ Key::new(&changed, &identity, "t", false),
+ Key::new(&config, &omitted, "t", false),
+ Key::new(&config, &other_root, "t", false),
+ Key::new(&config, &identity, "other", false),
+ Key::new(&workspace, &identity, "t", false),
+ ] {
+ assert!(completed(&cache, &other).is_none());
+ }
+ assert!(completed(&Cache::default(), &key).is_none());
+}
+
+#[tokio::test]
+async fn invalidation_rejects_late_results_and_preserves_bounded_pending_logs() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ CACHES.lock().unwrap().push(Arc::downgrade(&cache));
+ let release = Arc::new(tokio::sync::Notify::new());
+ let started = Arc::new(tokio::sync::Notify::new());
+ let held = release.clone();
+ let starting = started.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async move {
+ starting.notify_one();
+ held.notified().await;
+ Some(pack("forgotten"))
+ }),
+ );
+ started.notified().await;
+ let logs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ for _ in 0..MAX_PENDING + 10 {
+ let logs = logs.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async move {
+ logs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ None
+ }),
+ );
+ }
+ assert_eq!(
+ cache.0.lock().unwrap().entries[&key].pending.len(),
+ MAX_PENDING
+ );
+ invalidate(&config);
+ assert_eq!(
+ cache.0.lock().unwrap().entries[&key].pending.len(),
+ MAX_PENDING
+ );
+ release.notify_one();
+ drain(&cache, &key).await;
+ assert!(completed(&cache, &key).is_none());
+ assert_eq!(logs.load(std::sync::atomic::Ordering::SeqCst), MAX_PENDING);
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("fresh")) }),
+ );
+ drain(&cache, &key).await;
+ assert_eq!(completed(&cache, &key).unwrap().markdown, "fresh");
+}
+
+#[tokio::test]
+async fn expiration_failure_and_oversized_packs_are_not_reused() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("good")) }),
+ );
+ drain(&cache, &key).await;
+ cache
+ .0
+ .lock()
+ .unwrap()
+ .entries
+ .get_mut(&key)
+ .unwrap()
+ .pack
+ .as_mut()
+ .unwrap()
+ .0 = Instant::now() - TTL;
+ assert!(completed(&cache, &key).is_none());
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack(&"x".repeat(MAX_PACK_BYTES + 1))) }),
+ );
+ drain(&cache, &key).await;
+ assert!(completed(&cache, &key).is_none());
+ enqueue(cache.clone(), key.clone(), Box::pin(async { None }));
+ drain(&cache, &key).await;
+ assert!(completed(&cache, &key).is_none());
+}
+
+#[tokio::test]
+async fn credential_invalidation_removes_ready_and_rejects_late_inflight_results() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ CACHES.lock().unwrap().push(Arc::downgrade(&cache));
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("private")) }),
+ );
+ drain(&cache, &key).await;
+ let started = Arc::new(tokio::sync::Notify::new());
+ let release = Arc::new(tokio::sync::Notify::new());
+ let starting = started.clone();
+ let held = release.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async move {
+ starting.notify_one();
+ held.notified().await;
+ Some(pack("old credentials"))
+ }),
+ );
+ started.notified().await;
+ assert_eq!(completed(&cache, &key).unwrap().markdown, "private");
+ invalidate_all();
+ assert!(completed(&cache, &key).is_none());
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("new credentials")) }),
+ );
+ drain(&cache, &key).await;
+ release.notify_one();
+ tokio::task::yield_now().await;
+ assert_eq!(completed(&cache, &key).unwrap().markdown, "new credentials");
+}
+
+struct HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine,
+ release: Arc<tokio::sync::Semaphore>,
+}
+#[async_trait::async_trait]
+impl tinymemory_api::MemoryEngine for HeldEngine {
+ 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<tinymemory_api::RecallAnswer> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.recall(req).await
+ }
+
+ async fn fetch(
+ &self,
+ req: tinymemory_api::FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.fetch(req).await
+ }
+
+ async fn store(
+ &self,
+ item: tinymemory_api::StoreItem,
+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.store(item).await
+ }
+
+ async fn forget(
+ &self,
+ target: tinymemory_api::ForgetTarget,
+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.forget(target).await
+ }
+
+ async fn list(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.list(req).await
+ }
+
+ async fn export(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ExportPage> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.export(req).await
+ }
+
+ async fn consolidate(
+ &self,
+ req: tinymemory_api::ConsolidateRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ConsolidateReceipt> {
+ let _permit = self.release.acquire().await.unwrap();
+ self.inner.consolidate(req).await
+ }
+}
+
+#[tokio::test]
+async fn slow_engine_results_survive_the_manual_pre_turn_cutoff() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ config.memory.recall.pre_turn_timeout_ms = 1;
+ let release = Arc::new(tokio::sync::Semaphore::new(0));
+ let engine = Arc::new(HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine::new(),
+ release: release.clone(),
+ });
+ use tinymemory_api::MemoryEngine;
+ engine
+ .inner
+ .store(tinymemory_api::StoreItem::learning(
+ "Favourite colour is teal",
+ tinymemory_api::LearningKind::Preference,
+ 0.9,
+ tinymemory_api::MemoryMeta::default(),
+ ))
+ .await
+ .unwrap();
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let input = |index| PreTurnInput {
+ thread_id: "slow".into(),
+ turn_index: index,
+ user_text: "what is my favourite colour?".into(),
+ in_prompt_from: 0,
+ at: chrono::Utc::now(),
+ resumed_after_compaction: false,
+ observed_actor: None,
+ };
+ let config = Arc::new(config);
+ assert!(pre_turn(config.clone(), identity.clone(), input(0), None).is_none());
+ // Even after the old one-millisecond cutoff, the pack remains owned by
+ // the background worker instead of being discarded by the live turn.
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ let cache = cache();
+ let key = Key::new(&config, &identity, "slow", false);
+ assert!(completed(&cache, &key).is_none());
+ release.add_permits(100);
+ drain(&cache, &key).await;
+ let pack = pre_turn(config.clone(), identity.clone(), input(2), None)
+ .expect("next turn uses completed slow lookup");
+ assert!(pack.markdown.contains("teal"));
+ assert!(pack.markdown.contains("earlier turn"));
+ drain(&cache, &key).await;
+ let mut omitted = identity;
+ omitted.recall = false;
+ assert!(pre_turn(config.clone(), omitted.clone(), input(4), None).is_none());
+ drain(&cache, &Key::new(&config, &omitted, "slow", false)).await;
+ let turns = crate::memory::test_fixtures::stored(
+ &engine.inner,
+ tinymemory_api::MetaFilter::kinds([tinymemory_api::ItemKind::Conversation]),
+ )
+ .await;
+ assert_eq!(turns.len(), 3, "omitted recall still logs its user turn");
+}
+
+#[tokio::test]
+async fn queued_work_keeps_the_callers_core_and_memory_identity() {
+ let _guard = TEST_LOCK.lock().await;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let ctx = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ Some(config.workspace_dir.clone()),
+ );
+ crate::core::runtime::CoreContext::scope(
+ ctx.clone(),
+ crate::memory::scope::within(MemoryIdentity::agent("scoped-agent"), async {
+ let identity = MemoryIdentity::agent("scoped-agent").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = cache();
+ let expected = ctx.clone();
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(crate::core::runtime::spawn::scoped(async move {
+ assert!(Arc::ptr_eq(
+ &crate::core::runtime::CoreContext::scoped().unwrap(),
+ &expected
+ ));
+ assert_eq!(
+ crate::memory::scope::current().unwrap().agent_id.as_deref(),
+ Some("scoped-agent")
+ );
+ Some(pack("scoped"))
+ })),
+ );
+ drain(&cache, &key).await;
+ assert_eq!(completed(&cache, &key).unwrap().markdown, "scoped");
+ }),
+ )
+ .await;
+}
+
+#[test]
+fn runtime_shutdown_releases_worker_and_pending_work() {
+ let _guard = TEST_LOCK.blocking_lock();
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let identity = MemoryIdentity::agent("a").resolve(&config);
+ let key = Key::new(&config, &identity, "t", false);
+ let cache = Arc::new(Cache::default());
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ enqueue(cache.clone(), key.clone(), Box::pin(std::future::pending()));
+ enqueue(
+ cache.clone(),
+ key.clone(),
+ Box::pin(async { Some(pack("queued")) }),
+ );
+ tokio::task::yield_now().await;
+ assert!(cache.0.lock().unwrap().entries[&key].active);
+ });
+ drop(runtime);
+ let state = cache.0.lock().unwrap();
+ assert!(!state.entries[&key].active);
+ assert!(state.entries[&key].pending.is_empty());
+}
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index e3d6183c64..5542d3bbc6 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -43,6 +43,7 @@ pub mod sources;
pub mod status;
mod tool_budget;
pub mod tools;
+pub(crate) mod tool_writes;
pub mod types;
pub mod user_scope;
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index 3f028355c9..dba2a222a3 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -401,6 +401,7 @@ pub async fn forget(config: &Config, params: ForgetParams) -> MemoryResult<Forge
None => bound.engine.forget(ForgetTarget::Ids(ids)).await?,
};
tracing::debug!(engine = %bound.id, forgotten = report.forgotten, "[memory:ops] forget");
+ super::lifecycle::prefetch::invalidate(config);
Ok(ForgetView {
forgotten: report.forgotten,
})
@@ -423,6 +424,10 @@ pub async fn erase_all(config: &Config, params: EraseAllParams) -> MemoryResult<
));
}
let bound = bound(config)?;
+ // Earlier durable tool writes must finish or be discarded before the
+ // remote wipe; hold the owner barrier until the erase has completed.
+ let _writes = super::tool_writes::fence_and_clear(config).await?;
+ super::lifecycle::prefetch::invalidate(config);
let mut request = EraseRequest::new(tinymemory_api::Reach::subtree(
tinymemory_api::Namespace::ROOT,
));
@@ -437,6 +442,7 @@ pub async fn erase_all(config: &Config, params: EraseAllParams) -> MemoryResult<
erased_scopes = report.erased_scopes,
"[memory:ops] erase_all: done"
);
+ super::lifecycle::prefetch::invalidate(config);
Ok(EraseAllView {
erased_scopes: report.erased_scopes,
})
diff --git a/crates/openhuman-core/src/memory/ops_tests.rs b/crates/openhuman-core/src/memory/ops_tests.rs
index 8dcf7a94f8..15ed8523e8 100644
--- a/crates/openhuman-core/src/memory/ops_tests.rs
+++ b/crates/openhuman-core/src/memory/ops_tests.rs
@@ -465,6 +465,27 @@ async fn erase_all_reports_memory_off_without_an_engine() {
assert_eq!(error.code(), MEMORY_OFF);
}
+#[tokio::test]
+async fn erasing_memory_cancels_queued_learning_so_restart_cannot_restore_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let facts = crate::memory::tools::CallFacts::of(
+ &config,
+ &crate::memory::scope::MemoryIdentity::agent("orchestrator"),
+ );
+ let queued = crate::memory::tool_writes::enqueue(
+ &config,
+ &serde_json::json!({"action":"learn","text":"Prefers tea"}),
+ &facts,
+ ).unwrap();
+ assert!(queued["status"].as_str().unwrap().starts_with("queued"));
+ erase_all(&config, EraseAllParams { confirm: true }).await.unwrap();
+ let restarted = config.clone();
+ crate::memory::tool_writes::drain(&restarted).await;
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+}
+
/// With a reach, forget by id goes to the engine's `forget_within` (through
/// the scrubbing wrapper every bound engine sits in), so the engine never
/// sweeps the tree for the ids; without one it stays a plain forget by id.
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
new file mode 100644
index 0000000000..249378dbaf
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -0,0 +1,596 @@
+//! Durable, bounded FIFO for the agent tool's optional memory writes.
+//! Only scrubbed items and trusted scope are persisted; credentials are resolved
+//! at drain time. Enqueue never waits on the remote engine.
+
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use tinymemory_api::{Namespace, Reach, StoreItem, WriteOptions};
+
+use super::error::{MemoryError, MemoryResult};
+use super::tools::CallFacts;
+use super::types::{ForgetParams, LearnParams};
+use crate::config::Config;
+
+const MAX_PENDING: usize = 256;
+const MAX_BYTES: usize = 2 * 1024 * 1024;
+const WRITE_TIMEOUT: Duration = Duration::from_secs(120);
+static PROCESS_EPOCH: LazyLock<String> = LazyLock::new(|| uuid::Uuid::new_v4().to_string());
+const QUEUED: &str = "queued; not yet saved to memory";
+static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
+#[derive(Default)]
+struct DrainState {
+ barrier: Arc<tokio::sync::Mutex<()>>,
+}
+
+#[derive(Default)]
+struct OwnerState {
+ admission: Mutex<()>,
+ barrier: Arc<tokio::sync::RwLock<()>>,
+ generation: AtomicU64,
+ fences: AtomicU64,
+}
+
+static OWNERS: LazyLock<Mutex<HashMap<PathBuf, Weak<OwnerState>>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+type DrainLocks = HashMap<PathBuf, Weak<DrainState>>;
+static DRAINS: LazyLock<Mutex<DrainLocks>> = LazyLock::new(|| Mutex::new(HashMap::new()));
+
+#[derive(Clone, Serialize, Deserialize)]
+struct Entry {
+ ticket: String,
+ root: Option<String>,
+ layout_v3: bool,
+ scope_root: Namespace,
+ #[serde(default)]
+ epoch: Option<(String, u64)>,
+ operation: Operation,
+ // Stable, content-free last outcome; never an engine message.
+ status: Option<String>,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(tag = "action", rename_all = "snake_case")]
+enum Operation {
+ Learn { item: StoreItem },
+ Forget { ids: Vec<String>, reach: Reach },
+}
+
+#[cfg(test)]
+fn path(workspace: &Path) -> PathBuf {
+ let config = Config {
+ workspace_dir: workspace.to_path_buf(),
+ config_path: workspace
+ .parent()
+ .expect("fixture root")
+ .join("config.toml"),
+ ..Config::default()
+ };
+ queue_path(&config, &Namespace::ROOT)
+}
+
+fn owner_prefix(config: &Config) -> String {
+ let root = super::scope::user_root(config);
+ let fallback = root
+ .is_none()
+ .then(|| config.config_path.to_string_lossy().to_string());
+ let owner = serde_json::to_vec(&(root, fallback)).expect("owner fields serialize");
+ format!("tool_writes-{:x}", Sha256::digest(owner))
+}
+
+fn queue_path(config: &Config, root: &Namespace) -> PathBuf {
+ let partition = serde_json::to_vec(&(
+ &config.memory.root,
+ super::scope::layout_is_v3(config),
+ root,
+ ))
+ .expect("partition fields serialize");
+ config.workspace_dir.join("memory").join(format!(
+ "{}-{:x}.json",
+ owner_prefix(config),
+ Sha256::digest(partition)
+ ))
+}
+
+fn unavailable() -> MemoryError {
+ MemoryError::Unavailable(
+ "memory write queue unavailable; durable queueing was not confirmed".into(),
+ )
+}
+
+fn read_at(path: &Path) -> MemoryResult<Vec<Entry>> {
+ let file = match std::fs::File::open(path) {
+ Ok(file) => file,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(_) => return Err(unavailable()),
+ };
+ let mut bytes = Vec::new();
+ file.take((MAX_BYTES + 1) as u64)
+ .read_to_end(&mut bytes)
+ .map_err(|_| unavailable())?;
+ if bytes.len() > MAX_BYTES {
+ return Err(unavailable());
+ }
+ let entries: Vec<Entry> = serde_json::from_slice(&bytes).map_err(|_| unavailable())?;
+ if entries.len() > MAX_PENDING {
+ return Err(unavailable());
+ }
+ Ok(entries)
+}
+
+fn write_at(file: &Path, entries: &[Entry]) -> MemoryResult<()> {
+ let bytes = serde_json::to_vec(entries).map_err(|_| unavailable())?;
+ if bytes.len() > MAX_BYTES {
+ return Err(unavailable());
+ }
+ let temp = file.with_extension("json.tmp");
+ let result = (|| -> std::io::Result<()> {
+ super::files::create_private_dir_all(file.parent().expect("memory directory"))?;
+ let mut output = super::files::create_private(&temp)?;
+ output.write_all(&bytes)?;
+ output.sync_all()?;
+ std::fs::rename(&temp, file)?;
+ #[cfg(unix)]
+ std::fs::File::open(file.parent().expect("memory directory"))?.sync_all()?;
+ Ok(())
+ })();
+ result.map_err(|_| unavailable())
+}
+
+#[cfg(test)]
+fn read(workspace: &Path) -> MemoryResult<Vec<Entry>> {
+ read_at(&path(workspace))
+}
+#[cfg(test)]
+fn write(workspace: &Path, entries: &[Entry]) -> MemoryResult<()> {
+ write_at(&path(workspace), entries)
+}
+
+/// Accepts a validated, scrubbed write locally. The acknowledgement means only
+/// that it is durable in the local outbox, not accepted by the remote engine.
+pub(super) fn enqueue(
+ config: &Config,
+ args: &serde_json::Value,
+ facts: &CallFacts,
+) -> MemoryResult<serde_json::Value> {
+ if config.memory.engine == super::engine::DISABLED_ENGINE {
+ return Err(MemoryError::Off("memory is disabled".into()));
+ }
+ let confinement = super::user_scope::confinement(config)?;
+ let reach = match confinement {
+ Some(ref root) => super::user_scope::clamp_reach(Some(facts.reach.clone()), root),
+ None => facts.reach.clone(),
+ };
+ let scope_root = reach.at.clone();
+ let file = queue_path(config, &scope_root);
+ let operation = match args.get("action").and_then(serde_json::Value::as_str) {
+ Some("learn") => {
+ let mut params: LearnParams = serde_json::from_value(args.clone())
+ .map_err(|_| MemoryError::invalid("invalid learning arguments"))?;
+ params.meta = None;
+ let mut item = super::ops::learning_item(params, Some(facts.learn_meta()))?;
+ if let Some(root) = confinement {
+ super::user_scope::clamp_item(&mut item, &root);
+ }
+ if !super::user_scope::within(&item.meta().namespace, &reach.at) || reach.inherit {
+ return Err(MemoryError::invalid(
+ "learning namespace is outside the trusted reach",
+ ));
+ }
+ Operation::Learn {
+ item: super::guard::scrub(item),
+ }
+ }
+ Some("forget") => {
+ let params: ForgetParams = serde_json::from_value(args.clone())
+ .map_err(|_| MemoryError::invalid("invalid forgetting arguments"))?;
+ let mut ids: Vec<_> = params
+ .ids
+ .into_iter()
+ .map(|id| id.trim().to_string())
+ .filter(|id| !id.is_empty())
+ .collect();
+ ids.sort();
+ ids.dedup();
+ if ids.is_empty() {
+ return Err(MemoryError::invalid("forget needs at least one id"));
+ }
+ Operation::Forget { ids, reach }
+ }
+ _ => return Err(MemoryError::invalid("expected a memory write")),
+ };
+ let acknowledgement = match &operation {
+ Operation::Learn { item } => serde_json::json!({"id":item.fingerprint(), "status":QUEUED}),
+ Operation::Forget { ids, .. } => {
+ serde_json::json!({"queued":ids.len(), "status":"queued; not yet removed from memory"})
+ }
+ };
+ let root = super::scope::user_root(config);
+ let layout_v3 = super::scope::layout_is_v3(config);
+ let _guard = LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !file.exists() && partitions(config)?.len() >= MAX_PENDING {
+ return Err(MemoryError::Unavailable(
+ "memory write queue full; nothing was queued".into(),
+ ));
+ }
+ let mut entries = read_at(&file)?;
+ let owner = owner_state(config);
+ let (fencing, epoch) = {
+ let _admission = owner
+ .admission
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ (
+ owner.fences.load(Ordering::SeqCst) > 0,
+ Some((
+ PROCESS_EPOCH.clone(),
+ owner.generation.load(Ordering::SeqCst),
+ )),
+ )
+ };
+ // Adjacent retries are coalesced; never coalesce across a forget/relearn.
+ if !fencing
+ && entries.last().is_some_and(|last| {
+ last.root == root
+ && last.layout_v3 == layout_v3
+ && match (&last.operation, &operation) {
+ (Operation::Learn { item: a }, Operation::Learn { item: b }) => {
+ a.fingerprint() == b.fingerprint()
+ }
+ (
+ Operation::Forget { ids: a, reach: ar },
+ Operation::Forget { ids: b, reach: br },
+ ) => a == b && ar == br,
+ _ => false,
+ }
+ })
+ {
+ return Ok(acknowledgement);
+ }
+ if entries.len() >= MAX_PENDING {
+ return Err(MemoryError::Unavailable(
+ "memory write queue full; nothing was queued".into(),
+ ));
+ }
+ entries.push(Entry {
+ ticket: uuid::Uuid::new_v4().to_string(),
+ root,
+ layout_v3,
+ scope_root,
+ epoch,
+ operation,
+ status: None,
+ });
+ write_at(&file, &entries)?;
+ Ok(acknowledgement)
+}
+
+fn drain_state(workspace: &Path) -> Arc<DrainState> {
+ let mut locks = DRAINS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ locks.retain(|_, value| value.strong_count() > 0);
+ if let Some(lock) = locks.get(workspace).and_then(Weak::upgrade) {
+ return lock;
+ }
+ let lock = Arc::new(DrainState::default());
+ locks.insert(workspace.to_path_buf(), Arc::downgrade(&lock));
+ lock
+}
+
+fn owner_state(config: &Config) -> Arc<OwnerState> {
+ let key = config
+ .workspace_dir
+ .join("memory")
+ .join(owner_prefix(config));
+ let mut owners = OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ owners.retain(|_, value| value.strong_count() > 0);
+ if let Some(state) = owners.get(&key).and_then(Weak::upgrade) {
+ return state;
+ }
+ let state = Arc::new(OwnerState::default());
+ owners.insert(key, Arc::downgrade(&state));
+ state
+}
+
+fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {
+ let prefix = format!("{}-", owner_prefix(config));
+ let entries = match std::fs::read_dir(config.workspace_dir.join("memory")) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(_) => return Err(unavailable()),
+ };
+ let mut files = Vec::new();
+ for entry in entries {
+ let file = entry.map_err(|_| unavailable())?.path();
+ if file
+ .file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".json"))
+ {
+ files.push(file);
+ if files.len() > MAX_PENDING {
+ return Err(unavailable());
+ }
+ }
+ }
+ Ok(files)
+}
+
+/// Holds the owner's mutation barrier through explicit engine erasure.
+/// Subsequent queued writes resume only after the outer erasure finishes.
+pub(crate) struct WriteFence {
+ guard: Option<tokio::sync::OwnedRwLockWriteGuard<()>>,
+ state: Arc<OwnerState>,
+ config: Arc<Config>,
+}
+
+impl Drop for WriteFence {
+ fn drop(&mut self) {
+ let last = {
+ let _admission = self
+ .state
+ .admission
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ self.state.fences.fetch_sub(1, Ordering::SeqCst) == 1
+ };
+ drop(self.guard.take());
+ if last && tokio::runtime::Handle::try_current().is_ok() {
+ schedule_all(self.config.clone());
+ }
+ }
+}
+
+/// Stops each owner partition after its current mutation, durably clears
+/// earlier pending writes, and fences subsequent writes through explicit erase.
+/// Other owners sharing a workspace keep independent queues and barriers.
+pub(crate) async fn fence_and_clear(config: &Config) -> MemoryResult<WriteFence> {
+ let state = owner_state(config);
+ let fencing_generation = {
+ let _admission = state
+ .admission
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ state.fences.fetch_add(1, Ordering::SeqCst);
+ state.generation.fetch_add(1, Ordering::SeqCst) + 1
+ };
+ let mut fence = WriteFence {
+ guard: None,
+ state: state.clone(),
+ config: Arc::new(config.clone()),
+ };
+ let snapshot_config = config.clone();
+ let prior = crate::core::runtime::spawn_blocking_scoped(move || {
+ let _guard = LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ partitions(&snapshot_config)?
+ .into_iter()
+ .map(|file| {
+ let tickets = read_at(&file)?
+ .into_iter()
+ .filter(|entry| {
+ entry.epoch.as_ref().is_none_or(|(process, generation)| {
+ process != &*PROCESS_EPOCH || *generation < fencing_generation
+ })
+ })
+ .map(|entry| entry.ticket)
+ .collect::<HashSet<_>>();
+ Ok::<_, MemoryError>((file, tickets))
+ })
+ .collect::<MemoryResult<Vec<_>>>()
+ })
+ .await
+ .map_err(|_| unavailable())??;
+ fence.guard = Some(state.barrier.clone().write_owned().await);
+ crate::core::runtime::spawn_blocking_scoped(move || {
+ let _guard = LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ for (file, tickets) in prior {
+ let mut entries = read_at(&file)?;
+ entries.retain(|entry| !tickets.contains(&entry.ticket));
+ write_at(&file, &entries)?;
+ }
+ Ok::<_, MemoryError>(())
+ })
+ .await
+ .map_err(|_| unavailable())??;
+ Ok(fence)
+}
+
+/// Starts a scoped background drain, retaining config only in memory.
+pub(super) fn schedule(config: Arc<Config>) {
+ let file = queue_path(&config, super::scope::resolve_current(&config).root());
+ schedule_partition(config, file);
+}
+
+/// Retries all durable partitions belonging to this owner on auth/cron ticks.
+pub(super) fn schedule_all(config: Arc<Config>) {
+ if config.memory.engine == super::engine::DISABLED_ENGINE {
+ return;
+ }
+ crate::core::runtime::spawn_scoped(async move {
+ let scan_config = config.clone();
+ let files =
+ match crate::core::runtime::spawn_blocking_scoped(move || partitions(&scan_config))
+ .await
+ {
+ Ok(Ok(files)) => files,
+ _ => {
+ tracing::debug!(
+ code = "QUEUE_UNAVAILABLE",
+ "[memory:tool_writes] retry discovery deferred"
+ );
+ return;
+ }
+ };
+ for file in files {
+ schedule_partition(config.clone(), file);
+ }
+ });
+}
+
+fn schedule_partition(config: Arc<Config>, file: PathBuf) {
+ let owner = owner_state(&config);
+ let (generation, owner_guard) = {
+ let _admission = owner
+ .admission
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if owner.fences.load(Ordering::SeqCst) > 0 {
+ return;
+ }
+ let generation = owner.generation.load(Ordering::SeqCst);
+ let Ok(guard) = owner.barrier.clone().try_read_owned() else {
+ return;
+ };
+ (generation, guard)
+ };
+ let state = drain_state(&file);
+ let Ok(guard) = state.barrier.clone().try_lock_owned() else {
+ return;
+ };
+ crate::core::runtime::spawn_scoped(async move {
+ let _guard = guard;
+ let _owner_guard = owner_guard;
+ let _state = state;
+ drain_locked(&config, &file, &owner, generation).await;
+ });
+}
+
+/// Retries oldest first, retaining a failed write and all later writes.
+/// Producers hold no queue lock during remote I/O. Also used by auth/cron
+/// after restart; the persisted owner root must still match the active user.
+#[cfg(test)]
+pub(crate) async fn drain(config: &Config) -> usize {
+ let file = queue_path(config, super::scope::resolve_current(config).root());
+ let owner = owner_state(config);
+ let _owner = owner.barrier.read().await;
+ let state = drain_state(&file);
+ let _draining = state.barrier.lock().await;
+ let generation = owner.generation.load(Ordering::SeqCst);
+ drain_locked(config, &file, &owner, generation).await
+}
+
+async fn drain_locked(config: &Config, file: &Path, state: &OwnerState, generation: u64) -> usize {
+ if config.memory.engine == super::engine::DISABLED_ENGINE {
+ return 0;
+ }
+ let mut settled = 0;
+ // Bounded even if a producer continually adds new work.
+ for _ in 0..MAX_PENDING {
+ if state.generation.load(Ordering::SeqCst) != generation {
+ break;
+ }
+ let snapshot_file = file.to_path_buf();
+ let entry = crate::core::runtime::spawn_blocking_scoped(move || {
+ let _guard = LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ match read_at(&snapshot_file) {
+ Ok(entries) => entries.into_iter().next(),
+ Err(_) => None,
+ }
+ })
+ .await
+ .ok()
+ .flatten();
+ let Some(entry) = entry else {
+ break;
+ };
+ if state.generation.load(Ordering::SeqCst) != generation {
+ break;
+ }
+ if entry.root != super::scope::user_root(config)
+ || entry.layout_v3 != super::scope::layout_is_v3(config)
+ || queue_path(config, &entry.scope_root) != file
+ {
+ break;
+ }
+ let operation = async {
+ match &entry.operation {
+ Operation::Learn { item } => {
+ let bound = super::engine::resolve(config).engine()?;
+ let receipt =
+ super::ops::store_on_with(&bound, item.clone(), WriteOptions::accepted())
+ .await?;
+ let category = match item {
+ StoreItem::Learning { kind, .. } => kind.as_str(),
+ _ => "learning",
+ };
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::MemoryStored {
+ key: receipt.id.0,
+ category: category.to_string(),
+ namespace: "learnings".to_string(),
+ });
+ Ok(())
+ }
+ Operation::Forget { ids, reach } => super::ops::forget(
+ config,
+ ForgetParams {
+ ids: ids.clone(),
+ reach: Some(reach.clone()),
+ },
+ )
+ .await
+ .map(|_| ()),
+ }
+ };
+ let result = tokio::time::timeout(WRITE_TIMEOUT, operation).await;
+ let status = match result {
+ Ok(Ok(())) => None,
+ Ok(Err(error)) => Some(error.code().to_string()),
+ Err(_) => Some("TIMEOUT".to_string()),
+ };
+ let settlement_file = file.to_path_buf();
+ let ticket = entry.ticket.clone();
+ let last_status = status.clone();
+ let saved = crate::core::runtime::spawn_blocking_scoped(move || {
+ let _guard = LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let Ok(mut entries) = read_at(&settlement_file) else {
+ return false;
+ };
+ if entries.first().is_none_or(|first| first.ticket != ticket) {
+ return false;
+ }
+ if let Some(code) = last_status {
+ entries[0].status = Some(code);
+ } else {
+ entries.remove(0);
+ }
+ write_at(&settlement_file, &entries).is_ok()
+ })
+ .await
+ .unwrap_or(false);
+ if let Some(code) = status {
+ tracing::debug!(code, ticket = %entry.ticket, "[memory:tool_writes] pending write retained");
+ break;
+ }
+ if !saved {
+ break;
+ }
+ settled += 1;
+ super::lifecycle::prefetch::invalidate(config);
+ }
+ settled
+}
+
+#[cfg(test)]
+#[path = "tool_writes_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/tool_writes_tests.rs b/crates/openhuman-core/src/memory/tool_writes_tests.rs
new file mode 100644
index 0000000000..19e1cf5d67
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs
@@ -0,0 +1,538 @@
+use super::*;
+use crate::memory::scope::MemoryIdentity;
+use crate::memory::test_fixtures::{bind_reference, config_in, stored, RefusingEngine};
+use serde_json::json;
+use tinymemory_api::{MetaFilter, Namespace};
+
+fn facts(config: &Config) -> CallFacts {
+ CallFacts::of(config, &MemoryIdentity::agent("outbox-agent"))
+}
+
+#[tokio::test]
+async fn restart_drains_scrubbed_learnings_and_ordered_forgetting() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let facts = facts(&config);
+ let ack = enqueue(
+ &config,
+ &json!({"action":"learn","text":"Prefers tea"}),
+ &facts,
+ )
+ .unwrap();
+ let id = ack["id"].as_str().unwrap();
+ enqueue(
+ &config,
+ &json!({"action":"forget","ids":[id],"reach":{"at":"root"}}),
+ &facts,
+ )
+ .unwrap();
+ // A fresh config and engine sees only the durable file from before restart.
+ let restarted = config_in(&tmp);
+ let engine = bind_reference(&restarted);
+ assert_eq!(drain(&restarted).await, 2);
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+ assert!(read(&config.workspace_dir).unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn backend_failure_retains_the_head_and_blocks_later_writes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let facts = facts(&config);
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Prefers tea"}),
+ &facts,
+ )
+ .unwrap();
+ enqueue(&config, &json!({"action":"forget","ids":["later"]}), &facts).unwrap();
+ RefusingEngine::out_of_credits().bind(&config);
+ assert_eq!(drain(&config).await, 0);
+ let pending = read(&config.workspace_dir).unwrap();
+ assert_eq!(pending.len(), 2);
+ assert_eq!(pending[0].status.as_deref(), Some("INSUFFICIENT_CREDITS"));
+ assert!(pending[1].status.is_none());
+ bind_reference(&config);
+ assert_eq!(drain(&config).await, 2);
+}
+
+#[test]
+fn retries_ignore_provider_invocation_ids_but_relearning_after_forget_is_ordered() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let mut facts = facts(&config);
+ let args = json!({"action":"learn","text":"Prefers tea"});
+ facts.tool_call_id = Some("first-provider-id".into());
+ let first = enqueue(&config, &args, &facts).unwrap();
+ facts.tool_call_id = Some("second-provider-id".into());
+ let second = enqueue(&config, &args, &facts).unwrap();
+ assert_eq!(first, second);
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);
+ enqueue(
+ &config,
+ &json!({"action":"forget","ids":[first["id"]]}),
+ &facts,
+ )
+ .unwrap();
+ enqueue(&config, &args, &facts).unwrap();
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 3);
+}
+
+#[test]
+fn persistence_failure_and_invalid_scope_never_acknowledge_a_write() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let mut facts = facts(&config);
+ facts.namespace = "user:someone-else".parse::<Namespace>().unwrap();
+ facts.reach = Reach::subtree("user:trusted".parse().unwrap());
+ let args = json!({"action":"learn","text":"Prefers tea"});
+ assert!(enqueue(&config, &args, &facts).is_err());
+ assert!(!path(&config.workspace_dir).exists());
+ std::fs::write(config.workspace_dir.join("memory"), "blocks directory").unwrap();
+ assert!(enqueue(&config, &args, &self::facts(&config)).is_err());
+}
+
+#[test]
+fn private_outbox_is_scrubbed_before_persistence_and_has_a_size_limit() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let secret = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+ let text = format!("The API token is {secret}");
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":text}),
+ &facts(&config),
+ )
+ .unwrap();
+ let file = path(&config.workspace_dir);
+ let persisted = std::fs::read_to_string(&file).unwrap();
+ assert!(!persisted.contains(secret));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(
+ std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ assert_eq!(
+ std::fs::metadata(file.parent().unwrap())
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777,
+ 0o700
+ );
+ }
+ let huge = "x".repeat(MAX_BYTES);
+ assert!(enqueue(
+ &config,
+ &json!({"action":"learn","text":huge}),
+ &facts(&config)
+ )
+ .is_err());
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);
+}
+
+struct HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine,
+ entered: tokio::sync::Notify,
+ release: tokio::sync::Notify,
+ held: std::sync::atomic::AtomicBool,
+}
+
+#[async_trait::async_trait]
+impl tinymemory_api::MemoryEngine for HeldEngine {
+ 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<tinymemory_api::RecallAnswer> {
+ self.inner.recall(req).await
+ }
+ async fn fetch(
+ &self,
+ req: tinymemory_api::FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ self.inner.fetch(req).await
+ }
+ async fn store(&self, item: StoreItem) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
+ if self.held.load(std::sync::atomic::Ordering::SeqCst) {
+ self.entered.notify_one();
+ self.release.notified().await;
+ }
+ self.inner.store(item).await
+ }
+ async fn forget(
+ &self,
+ target: tinymemory_api::ForgetTarget,
+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
+ self.inner.forget(target).await
+ }
+ async fn list(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ self.inner.list(req).await
+ }
+ async fn export(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ExportPage> {
+ self.inner.export(req).await
+ }
+ async fn consolidate(
+ &self,
+ req: tinymemory_api::ConsolidateRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ConsolidateReceipt> {
+ self.inner.consolidate(req).await
+ }
+}
+
+#[tokio::test]
+async fn held_engine_writes_do_not_delay_acknowledgements_or_hold_the_producer_lock() {
+ use tinytools::Tool;
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = Arc::new(HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine::new(),
+ entered: tokio::sync::Notify::new(),
+ release: tokio::sync::Notify::new(),
+ held: std::sync::atomic::AtomicBool::new(true),
+ });
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+ let tool = crate::memory::MemoryTool::new(Arc::new(config.clone()));
+ let first = tokio::time::timeout(
+ Duration::from_secs(2),
+ tool.execute(json!({"action":"learn","text":"First fact"})),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!first.is_error);
+ tokio::time::timeout(Duration::from_secs(2), engine.entered.notified())
+ .await
+ .unwrap();
+ let second = tokio::time::timeout(
+ Duration::from_secs(2),
+ tool.execute(json!({"action":"learn","text":"Second fact"})),
+ )
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!second.is_error);
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 2);
+ engine
+ .held
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ engine.release.notify_one();
+ drain(&config).await;
+ assert_eq!(stored(&engine.inner, MetaFilter::default()).await.len(), 2);
+}
+
+#[test]
+fn corrupt_existing_outbox_is_preserved_and_refuses_new_writes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let file = path(&config.workspace_dir);
+ super::super::files::write_private(&file, b"corrupt existing state").unwrap();
+ assert!(enqueue(
+ &config,
+ &json!({"action":"learn","text":"Prefers tea"}),
+ &facts(&config)
+ )
+ .is_err());
+ assert_eq!(std::fs::read(&file).unwrap(), b"corrupt existing state");
+}
+
+#[tokio::test]
+async fn a_different_owner_cannot_replay_the_original_owners_queue() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Prefers tea"}),
+ &facts(&config),
+ )
+ .unwrap();
+ {
+ let _guard = LOCK.lock().unwrap();
+ let mut entries = read(&config.workspace_dir).unwrap();
+ entries[0].root = Some("org:another-user".into());
+ write(&config.workspace_dir, &entries).unwrap();
+ }
+ let engine = bind_reference(&config);
+ assert_eq!(drain(&config).await, 0);
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);
+}
+
+#[tokio::test(start_paused = true)]
+async fn background_writes_can_complete_after_the_foreground_fifteen_second_budget() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = Arc::new(HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine::new(),
+ entered: tokio::sync::Notify::new(),
+ release: tokio::sync::Notify::new(),
+ held: std::sync::atomic::AtomicBool::new(true),
+ });
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+ let ack = enqueue(
+ &config,
+ &json!({"action":"learn","text":"Slow but accepted learning"}),
+ &facts(&config),
+ )
+ .unwrap();
+ assert_eq!(ack["status"], QUEUED);
+ let drain_config = config.clone();
+ let draining = tokio::spawn(async move { drain(&drain_config).await });
+ engine.entered.notified().await;
+ tokio::time::advance(Duration::from_secs(56)).await;
+ engine
+ .held
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ engine.release.notify_one();
+ assert_eq!(draining.await.unwrap(), 1);
+ assert_eq!(stored(&engine.inner, MetaFilter::default()).await.len(), 1);
+}
+
+#[test]
+fn a_full_outbox_keeps_existing_writes_and_refuses_a_new_one() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"first"}),
+ &facts(&config),
+ )
+ .unwrap();
+ let mut entries = read(&config.workspace_dir).unwrap();
+ entries.resize(MAX_PENDING, entries[0].clone());
+ write(&config.workspace_dir, &entries).unwrap();
+ assert!(enqueue(
+ &config,
+ &json!({"action":"learn","text":"new"}),
+ &facts(&config)
+ )
+ .is_err());
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), MAX_PENDING);
+}
+
+#[tokio::test]
+async fn model_supplied_forget_reach_cannot_remove_another_identitys_item() {
+ use tinymemory_api::{LearningKind, MemoryEngine, MemoryMeta};
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let other_facts = CallFacts::of(&config, &MemoryIdentity::agent("different-agent"));
+ let item = StoreItem::learning(
+ "Other identity's learning",
+ LearningKind::Fact,
+ 0.8,
+ MemoryMeta {
+ namespace: other_facts.namespace,
+ ..MemoryMeta::default()
+ },
+ );
+ let id = engine.store(item).await.unwrap().id.0;
+ // All agents under one identity share their root by design. Choose an
+ // unrelated root explicitly to exercise a foreign identity boundary.
+ let mut confined = facts(&config);
+ confined.reach = Reach::subtree("user:isolated".parse().unwrap());
+ let mut config = config;
+ config.memory.root = Some("user:isolated".into());
+ enqueue(
+ &config,
+ &json!({"action":"forget","ids":[id],"reach":{"at":"","inherit":true,"descendants":true}}),
+ &confined,
+ )
+ .unwrap();
+ assert_eq!(drain(&config).await, 1);
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
+}
+
+#[tokio::test]
+async fn explicit_memory_disable_refuses_new_writes_and_keeps_old_writes_pending() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let call_facts = facts(&config);
+ let args = json!({"action":"learn","text":"An earlier accepted learning"});
+ enqueue(&config, &args, &call_facts).unwrap();
+ config.memory.engine = super::super::engine::DISABLED_ENGINE.to_string();
+ assert!(matches!(
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Must not persist"}),
+ &call_facts
+ ),
+ Err(MemoryError::Off(_))
+ ));
+ assert_eq!(drain(&config).await, 0);
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 1);
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+ config.memory.engine = super::super::engine::TINYHUMANS_ENGINE.to_string();
+ assert_eq!(drain(&config).await, 1);
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
+}
+
+#[tokio::test]
+async fn an_erase_fence_clears_prior_pending_learnings_across_restart() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Remove this pending learning"}),
+ &facts(&config),
+ )
+ .unwrap();
+ let fence = fence_and_clear(&config).await.unwrap();
+ assert!(read(&config.workspace_dir).unwrap().is_empty());
+ drop(fence);
+ let restarted = config_in(&tmp);
+ let engine = bind_reference(&restarted);
+ assert_eq!(drain(&restarted).await, 0);
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+}
+
+#[tokio::test]
+async fn an_erase_fence_waits_for_only_the_current_write_and_preserves_later_enqueues() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = Arc::new(HeldEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine::new(),
+ entered: tokio::sync::Notify::new(),
+ release: tokio::sync::Notify::new(),
+ held: std::sync::atomic::AtomicBool::new(true),
+ });
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Current write"}),
+ &facts(&config),
+ )
+ .unwrap();
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Earlier pending write"}),
+ &facts(&config),
+ )
+ .unwrap();
+ schedule(Arc::new(config.clone()));
+ engine.entered.notified().await;
+ let fence_config = config.clone();
+ let fencing = tokio::spawn(async move { fence_and_clear(&fence_config).await });
+ let state = owner_state(&config);
+ while state.fences.load(Ordering::SeqCst) == 0 {
+ tokio::task::yield_now().await;
+ }
+ assert!(
+ !fencing.is_finished(),
+ "fence must wait for the held mutation"
+ );
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"Current write"}),
+ &facts(&config),
+ )
+ .unwrap();
+ engine
+ .held
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ engine.release.notify_one();
+ let fence = fencing.await.unwrap().unwrap();
+ assert_eq!(
+ stored(&engine.inner, MetaFilter::default()).await.len(),
+ 1,
+ "the earlier pending write must not be sent"
+ );
+ enqueue(
+ &config,
+ &json!({"action":"learn","text":"After erase was requested"}),
+ &facts(&config),
+ )
+ .unwrap();
+ schedule(Arc::new(config.clone()));
+ assert_eq!(read(&config.workspace_dir).unwrap().len(), 2);
+ drop(fence);
+ drain(&config).await;
+ assert_eq!(stored(&engine.inner, MetaFilter::default()).await.len(), 2);
+}
+
+#[tokio::test]
+async fn separate_owner_roots_share_a_workspace_without_blocking_or_erasing_each_other() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut first = config_in(&tmp);
+ first.memory.root = Some("user:first".into());
+ first.config_path = tmp
+ .path()
+ .join("users/111111111111111111111111/config.toml");
+ let mut second = first.clone();
+ second.memory.root = Some("user:second".into());
+ second.config_path = tmp
+ .path()
+ .join("users/222222222222222222222222/config.toml");
+ let engine = bind_reference(&first);
+ enqueue(
+ &first,
+ &json!({"action":"learn","text":"First owner pending"}),
+ &facts(&first),
+ )
+ .unwrap();
+ enqueue(
+ &second,
+ &json!({"action":"learn","text":"Second owner pending"}),
+ &facts(&second),
+ )
+ .unwrap();
+ let fence = fence_and_clear(&first).await.unwrap();
+ assert_eq!(
+ drain(&second).await,
+ 1,
+ "another owner's fence cannot block this owner"
+ );
+ let second_items = stored(&engine, MetaFilter::default()).await;
+ assert_eq!(second_items.len(), 1);
+ assert!(second_items[0].text.contains("Second owner"));
+ assert_eq!(drain(&second).await, 0);
+ drop(fence);
+ assert_eq!(drain(&first).await, 0);
+}
+
+#[tokio::test]
+async fn erasing_one_owner_fences_pending_writes_from_every_team_root() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut first = config_in(&tmp);
+ first.memory.root = Some("team:first".into());
+ let mut second = first.clone();
+ second.memory.root = Some("team:second".into());
+ enqueue(
+ &first,
+ &json!({"action":"learn","text":"First team pending"}),
+ &facts(&first),
+ )
+ .unwrap();
+ enqueue(
+ &second,
+ &json!({"action":"learn","text":"Second team pending"}),
+ &facts(&second),
+ )
+ .unwrap();
+ let fence = fence_and_clear(&first).await.unwrap();
+ assert!(read_at(&queue_path(&first, &facts(&first).reach.at))
+ .unwrap()
+ .is_empty());
+ assert!(read_at(&queue_path(&second, &facts(&second).reach.at))
+ .unwrap()
+ .is_empty());
+ drop(fence);
+ let engine = bind_reference(&first);
+ assert_eq!(drain(&first).await, 0);
+ assert_eq!(drain(&second).await, 0);
+ assert!(stored(&engine, MetaFilter::default()).await.is_empty());
+}
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index 1ce03faccf..5f547ba871 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -362,7 +362,32 @@ impl Tool for MemoryTool {
.or_else(crate::agent::turn_origin::current_request_id);
Ok(self
.budget
- .run(run_id, run_action(&self.config, &args, &facts))
+ .run(run_id, async {
+ if matches!(
+ args.get("action").and_then(Value::as_str),
+ Some("learn" | "forget")
+ ) {
+ let config = self.config.clone();
+ let write_args = args.clone();
+ let queued = crate::core::runtime::spawn_blocking_scoped(move || {
+ super::tool_writes::enqueue(&config, &write_args, &facts)
+ })
+ .await;
+ match queued.unwrap_or_else(|_| {
+ Err(MemoryError::Unavailable(
+ "memory write queue unavailable".into(),
+ ))
+ }) {
+ Ok(value) => {
+ super::tool_writes::schedule(self.config.clone());
+ ToolResult::success(value.to_string())
+ }
+ Err(error) => ToolResult::error(render_error(error)),
+ }
+ } else {
+ run_action(&self.config, &args, &facts).await
+ }
+ })
.await)
}
}
diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rs
index 09f1fce501..70729b03dc 100644
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@ -47,7 +47,7 @@ async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn()
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let engine = bind_reference(&config);
- let tool = MemoryTool::new(Arc::new(config));
+ let tool = MemoryTool::new(Arc::new(config.clone()));
let origin = |request: &str| AgentTurnOrigin::WebChat {
thread_id: "thread-budget".into(),
client_id: "client-budget".into(),
@@ -63,6 +63,7 @@ async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn()
}
})
.await;
+ super::super::tool_writes::drain(&config).await;
assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 8);
let result = with_origin(
origin("next"),
@@ -71,18 +72,19 @@ async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn()
.await
.unwrap();
assert!(!result.is_error);
+ super::super::tool_writes::drain(&config).await;
assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
}
#[tokio::test]
-async fn harness_runs_have_independent_budgets_and_learning_retries_replay() {
+async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplicate() {
use tinyagents_harness::context::{RunConfig, RunContext};
use tinyagents_harness::ids::CallId;
use tinyagents_harness::tool::ToolExecutionContext;
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let engine = bind_reference(&config);
- let tool = MemoryTool::new(Arc::new(config));
+ let tool = MemoryTool::new(Arc::new(config.clone()));
let first: RunContext = RunContext::new(RunConfig::new("first-harness-run"), ());
let next: RunContext = RunContext::new(RunConfig::new("next-harness-run"), ());
let args = json!({"action":"learn","text":"Prefers tea"});
@@ -111,6 +113,7 @@ async fn harness_runs_have_independent_budgets_and_learning_retries_replay() {
.await
.unwrap();
assert!(!result.is_error, "a new harness run gets a fresh budget");
+ super::super::tool_writes::drain(&config).await;
assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
}
@@ -365,7 +368,7 @@ async fn execute_gathers_facts_from_the_run_context() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let engine = bind_reference(&config);
- let tool = MemoryTool::new(Arc::new(config));
+ let tool = MemoryTool::new(Arc::new(config.clone()));
let ctx = Ctx {
root: tmp.path().join("isolated"),
thread: "thread-ctx",
@@ -379,6 +382,7 @@ async fn execute_gathers_facts_from_the_run_context() {
.await
.unwrap();
assert!(!result.is_error, "{}", text(&result));
+ super::super::tool_writes::drain(&config).await;
let items = stored(&engine, MetaFilter::default()).await;
assert_eq!(items.len(), 1);
assert_eq!(items[0].meta.thread_id.as_deref(), Some("thread-ctx"));
@@ -393,6 +397,7 @@ async fn execute_gathers_facts_from_the_run_context() {
.await
.unwrap();
assert!(!plain.is_error);
+ super::super::tool_writes::drain(&config).await;
}
#[test]
@@ -723,3 +728,19 @@ async fn refers_to_reaches_the_engine_in_the_users_time_zone() {
]
);
}
+
+#[tokio::test]
+async fn learning_is_durably_queued_even_when_the_backend_refuses_writes() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);
+ let tool = MemoryTool::new(Arc::new(config.clone()));
+ let result = tool
+ .execute(json!({"action":"learn","text":"Prefers tea"}))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{}", result.text());
+ let value: Value = serde_json::from_str(&result.text()).unwrap();
+ assert_eq!(value["status"], "queued; not yet saved to memory");
+ assert_eq!(super::super::tool_writes::drain(&config).await, 0);
+}