Skip to content

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

refactor(memory): extract prefetch lifecycle into its own module

Steven Enamakel859f95bfdca7
diff --git a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
index 84231e0c75..87afcacdda 100644
--- a/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/prefetch.rs
@@ -2,14 +2,13 @@
//! 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 std::time::Duration;
use futures::future::BoxFuture;
-use tokio::sync::Semaphore;
+use tinymemory_tools::prefetch::{Limits, PrefetchRuntime, Prefetcher, WorkerPool};
use crate::config::Config;
use crate::core::runtime::{current_slot, spawn_scoped};
@@ -17,16 +16,33 @@ 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 WORKERS: LazyLock<WorkerPool> = LazyLock::new(|| WorkerPool::new(8));
static CACHES: LazyLock<Mutex<Vec<Weak<Cache>>>> = LazyLock::new(Mutex::default);
type Work = BoxFuture<'static, Option<TurnPack>>;
+/// The host executor the prefetcher's workers run on: the caller's core
+/// context and memory identity ride along with every spawned task.
+struct HostRuntime;
+
+impl PrefetchRuntime for HostRuntime {
+ fn spawn(&self, task: BoxFuture<'static, ()>) {
+ drop(spawn_scoped(task));
+ }
+
+ fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
+ Box::pin(tokio::time::sleep(duration))
+ }
+}
+
+fn pack_fits(pack: &TurnPack) -> bool {
+ 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)
+}
+
#[derive(Clone, Hash, PartialEq, Eq)]
struct Key {
workspace: PathBuf,
@@ -57,24 +73,19 @@ impl Key {
}
}
-struct Entry {
- ticket: u64,
- revision: u64,
- pack: Option<(Instant, TurnPack)>,
- pending: VecDeque<Work>,
- active: bool,
- touched: Instant,
-}
+struct Cache(Prefetcher<Key, TurnPack>);
-#[derive(Default)]
-struct State {
- entries: HashMap<Key, Entry>,
- next_ticket: u64,
+impl Default for Cache {
+ fn default() -> Self {
+ Self(
+ Prefetcher::new(Arc::new(HostRuntime))
+ .with_limits(Limits::default())
+ .with_workers(WORKERS.clone())
+ .with_filter(pack_fits),
+ )
+ }
}
-#[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);
@@ -100,15 +111,7 @@ pub(crate) fn invalidate(config: &Config) {
};
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);
- });
+ .invalidate_where(|key| key.workspace == config.workspace_dir);
true
});
}
@@ -121,28 +124,18 @@ pub(crate) fn invalidate_all() {
let Some(cache) = known.upgrade() else {
return false;
};
- cache
- .0
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .entries
- .clear();
+ cache.0.invalidate_all();
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())
+ cache.0.completed(key)
+}
+
+fn enqueue(cache: Arc<Cache>, key: Key, work: Work) {
+ tracing::debug!(thread_id = %key.thread, agent_id = %key.identity.agent_id, compaction = key.compaction, "[memory:prefetch] enqueue refresh");
+ cache.0.enqueue(key, work);
}
/// Returns the last completed pack immediately, then logs this user turn and
@@ -224,141 +217,6 @@ pub(crate) fn compaction(
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,
@@ -369,17 +227,7 @@ pub(crate) async fn settle_for_test(
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;
- }
+ while !cache.0.is_idle(&key) {
tokio::task::yield_now().await;
}
})