Skip to content

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

feat(memory): add deletion bus for memory removal events

Steven Enamakel51682892adcd
diff --git a/crates/openhuman-core/src/memory/bus.rs b/crates/openhuman-core/src/memory/bus.rs
index abeff2e753..8a800c1f6b 100644
--- a/crates/openhuman-core/src/memory/bus.rs
+++ b/crates/openhuman-core/src/memory/bus.rs
@@ -148,7 +148,7 @@ pub async fn run_system_job(config: &crate::config::Config, job: &str) {
std::sync::Arc::new(super::import::scheduler_paused),
);
super::lifecycle::jobs::run_due(config).await;
- super::deletion::drain(config).await;
+ super::deletion::drain_due(config).await;
}
_ => {}
}
diff --git a/crates/openhuman-core/src/memory/deletion.rs b/crates/openhuman-core/src/memory/deletion.rs
index 5660b80f8a..eef3b6997b 100644
--- a/crates/openhuman-core/src/memory/deletion.rs
+++ b/crates/openhuman-core/src/memory/deletion.rs
@@ -11,182 +11,142 @@
//! Every deletion is hard: a forget by filter removes the matched events by
//! `memory_ids` with an explicit `redact_events` cascade.
+use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex};
-use serde::{Deserialize, Serialize};
+use async_trait::async_trait;
use tinymemory_api::{ForgetTarget, ItemKind, MetaFilter};
+use tinymemory_tools::deletion::{Backoff, DeletionExecutor, DeletionQueue, Drain};
+use tinymemory_tools::list_store::{ListStore, StoreError};
+
+pub use tinymemory_tools::deletion::PendingDeletion;
use crate::config::Config;
use super::engine;
use super::error::{MemoryError, MemoryResult};
-/// One deletion still owed to the engine.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum PendingDeletion {
- /// A deleted chat thread's conversation memory.
- Thread {
- /// The thread.
- thread_id: String,
- },
- /// Every item a removed memory source stored.
- Source {
- /// The source id.
- source_id: String,
- },
-}
-
-impl PendingDeletion {
- /// A short, content-free label for logs.
- fn label(&self) -> &'static str {
- match self {
- Self::Thread { .. } => "thread",
- Self::Source { .. } => "source",
- }
- }
-}
-
-/// Serialises every read-modify-write of the file in this process.
-static LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
-
-/// Serialises drains, so two triggers never run one deletion twice at once.
-static DRAINING: LazyLock<tokio::sync::Mutex<()>> = LazyLock::new(|| tokio::sync::Mutex::new(()));
-
fn path(workspace_dir: &Path) -> PathBuf {
workspace_dir.join("memory").join("pending_deletions.json")
}
-fn locked() -> std::sync::MutexGuard<'static, ()> {
- LOCK.lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
+/// `<workspace>/memory/pending_deletions.json`: owner-only, written through a
+/// temporary file and a rename so a stop mid-write never loses the queue. An
+/// unparsable file is set aside; an empty queue removes the file.
+struct FileStore {
+ file: PathBuf,
}
-fn read(workspace_dir: &Path) -> Vec<PendingDeletion> {
- let file = path(workspace_dir);
- let Ok(text) = std::fs::read_to_string(&file) else {
- return Vec::new();
- };
- serde_json::from_str(&text).unwrap_or_else(|error| {
- tracing::warn!(%error, "[memory:deletion] pending deletions unparsable; set aside");
- if let Err(error) = std::fs::rename(&file, file.with_extension("json.corrupt")) {
- tracing::warn!(%error, "[memory:deletion] could not set the file aside");
- }
- Vec::new()
- })
-}
+impl ListStore<PendingDeletion> for FileStore {
+ fn load(&self) -> Result<Vec<PendingDeletion>, StoreError> {
+ let Ok(text) = std::fs::read_to_string(&self.file) else {
+ return Ok(Vec::new());
+ };
+ Ok(serde_json::from_str(&text).unwrap_or_else(|error| {
+ tracing::warn!(%error, "[memory:deletion] pending deletions unparsable; set aside");
+ if let Err(error) =
+ std::fs::rename(&self.file, self.file.with_extension("json.corrupt"))
+ {
+ tracing::warn!(%error, "[memory:deletion] could not set the file aside");
+ }
+ Vec::new()
+ }))
+ }
-/// Writes (owner-only, like the other memory files) through a temporary file and a rename, so a stop mid-write never
-/// leaves a partial file and loses the queue.
-fn write(workspace_dir: &Path, all: &[PendingDeletion]) {
- let file = path(workspace_dir);
- if all.is_empty() {
- match std::fs::remove_file(&file) {
- Ok(()) => {}
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
- Err(error) => tracing::warn!(%error, "[memory:deletion] clearing the queue failed"),
+ fn save(&self, all: &[PendingDeletion]) -> Result<(), StoreError> {
+ if all.is_empty() {
+ return match std::fs::remove_file(&self.file) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(StoreError(error.to_string())),
+ };
}
- return;
- }
- let temp = file.with_extension("json.tmp");
- let result = file
- .parent()
- .map_or(Ok(()), super::files::create_private_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;
- super::files::write_private(&temp, &json)?;
- std::fs::rename(&temp, &file)
- });
- if let Err(error) = result {
- tracing::warn!(%error, "[memory:deletion] writing pending deletions failed");
+ let temp = self.file.with_extension("json.tmp");
+ self.file
+ .parent()
+ .map_or(Ok(()), super::files::create_private_dir_all)
+ .and_then(|()| {
+ let json = serde_json::to_vec_pretty(all).map_err(std::io::Error::other)?;
+ super::files::write_private(&temp, &json)?;
+ std::fs::rename(&temp, &self.file)
+ })
+ .map_err(|error| StoreError(error.to_string()))
}
}
+type Queue = DeletionQueue<FileStore>;
+
+/// One queue per workspace, so the in-memory retry backoff and the drain lock
+/// are shared by every trigger.
+static QUEUES: LazyLock<Mutex<HashMap<PathBuf, Arc<Queue>>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+fn queue(workspace_dir: &Path) -> Arc<Queue> {
+ let mut queues = QUEUES
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ queues
+ .entry(workspace_dir.to_path_buf())
+ .or_insert_with(|| {
+ Arc::new(DeletionQueue::new(
+ FileStore {
+ file: path(workspace_dir),
+ },
+ Backoff::default(),
+ ))
+ })
+ .clone()
+}
+
/// Records `deletion` to run on the next [`drain`]. A deletion already
/// queued is not queued twice.
pub fn enqueue(workspace_dir: &Path, deletion: PendingDeletion) {
- let _guard = locked();
- let mut all = read(workspace_dir);
- if all.contains(&deletion) {
- return;
- }
- tracing::info!(
- kind = deletion.label(),
- "[memory:deletion] deletion queued until memory is reachable"
- );
- all.push(deletion);
- write(workspace_dir, &all);
+ queue(workspace_dir).enqueue(deletion);
}
/// Every deletion still owed, oldest first.
#[must_use]
pub fn pending(workspace_dir: &Path) -> Vec<PendingDeletion> {
- let _guard = locked();
- read(workspace_dir)
+ queue(workspace_dir).pending()
}
-fn settle(workspace_dir: &Path, deletion: &PendingDeletion) {
- let _guard = locked();
- let mut all = read(workspace_dir);
- let before = all.len();
- all.retain(|queued| queued != deletion);
- if all.len() != before {
- write(workspace_dir, &all);
- }
+/// Runs queued deletions against the engine.
+struct Executor<'a> {
+ config: &'a Config,
}
-/// Runs `deletion` now. Memory off is [`MemoryError::Off`], which the
-/// caller decides how to treat.
-async fn run(config: &Config, deletion: &PendingDeletion) -> MemoryResult<usize> {
- match deletion {
- PendingDeletion::Thread { thread_id } => forget_thread_now(config, thread_id).await,
- PendingDeletion::Source { source_id } => {
- super::sources::forget_items(config, source_id).await
- }
+#[async_trait]
+impl DeletionExecutor for Executor<'_> {
+ fn is_reachable(&self) -> bool {
+ engine::resolve(self.config).is_on()
}
-}
-/// Runs every queued deletion, settling each one that succeeds. Stops at
-/// once when memory is off (nothing can run), and keeps a deletion that
-/// fails for the next drain. Returns how many deletions settled.
-pub async fn drain(config: &Config) -> usize {
- let _draining = DRAINING.lock().await;
- let queued = pending(&config.workspace_dir);
- if queued.is_empty() {
- return 0;
- }
- if !engine::resolve(config).is_on() {
- tracing::debug!(
- queued = queued.len(),
- "[memory:deletion] memory off; pending deletions wait"
- );
- return 0;
- }
- let mut settled = 0;
- for deletion in queued {
- // Settled first: the deletion re-queues itself if it cannot finish.
- settle(&config.workspace_dir, &deletion);
- match run(config, &deletion).await {
- Ok(forgotten) => {
- settled += 1;
- tracing::info!(
- kind = deletion.label(),
- forgotten,
- "[memory:deletion] pending deletion completed"
- );
- }
- Err(error) => {
- enqueue(&config.workspace_dir, deletion.clone());
- tracing::warn!(
- kind = deletion.label(),
- code = error.code(),
- "[memory:deletion] pending deletion failed; kept for the next drain"
- );
+ async fn run(&self, deletion: &PendingDeletion) -> Result<usize, String> {
+ let result = match deletion {
+ PendingDeletion::Thread { thread_id } => forget_thread_now(self.config, thread_id).await,
+ PendingDeletion::Source { source_id } => {
+ super::sources::forget_items(self.config, source_id).await
}
- }
+ };
+ result.map_err(|error| error.code().to_string())
}
- settled
+}
+
+/// Runs every queued deletion now (a sign-in), settling each one that
+/// succeeds. Returns how many settled.
+pub async fn drain(config: &Config) -> usize {
+ queue(&config.workspace_dir)
+ .drain(&Executor { config }, Drain::Force, chrono::Utc::now())
+ .await
+}
+
+/// The background tick: like [`drain`], but a deletion that failed recently
+/// waits out its backoff.
+pub async fn drain_due(config: &Config) -> usize {
+ queue(&config.workspace_dir)
+ .drain(&Executor { config }, Drain::Due, chrono::Utc::now())
+ .await
}
/// Forgets every conversation item of `thread_id` now.