Skip to content

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

chore: files changed crates/openhuman-core/src/memory/backfill.rs,crates/openhuman-core/src/memory/m

Steven Enamakel68fd97561bdd
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index 19a90b41d5..efa865138c 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -1,212 +1,122 @@
//! Storing past chats: conversations from before turns were logged.
//!
-//! The lifecycle logs each turn as it happens (`lifecycle::hooks`). This walks
-//! the thread store instead and stores every earlier message of every thread
-//! the same way — one conversation item per message, user message `2n` and
-//! its reply `2n + 1`, at the main agent's node (`agent:<id>` under the
-//! layout root) — plus a [`BACKFILL_TAG`] so they can be told apart.
-//!
-//! The turn builder is `tinymemory_tools::backfill`; this file keeps the thread-store
-//! reading, the state file, consent and the run.
-//!
-//! - **Turns.** A thread's messages become turns the way the chat shows them:
-//! each user message opens a turn and the replies after it, up to the next
-//! user message, are its answer. Replies before any user message form a turn
-//! with no user side.
-//! - **No overlap with live logging.** A thread's turns from the first one the
-//! lifecycle logged on are already in memory; the backfill stops short of
-//! them (it asks the engine where logging began).
-//! - **Resumable and repeatable.** How far each thread has been stored is kept
-//! in `<workspace>/memory/conversations_backfill.json`, so an interrupted run
-//! resumes and a later run sends only what is new. A re-sent item is a
-//! replay (its id is a content digest), never a duplicate.
-//! - **Accepted, then visible.** Every batch but the last goes in with
-//! accepted writes: the engine returns once it holds them durably, and
-//! indexes them after. The last waits until it is visible, and the scope's
-//! log is ordered, so a `done` run is searchable. An engine without
-//! accepted writes stores every batch as before.
-//! - **Consent.** It uploads chat history to the selected engine, so
-//! [`start`] refuses without `consent`.
+//! The TinyMemory backfill driver owns planning, progress, batching and
+//! idempotent writes. This host adapter supplies the conversation thread
+//! source, the existing state-file path, consent, engine binding and task
+//! lifetime.
-use crate::core::runtime::DispatchCtx;
-use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
-use std::sync::{LazyLock, Mutex};
-
-use chrono::{DateTime, Utc};
-use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use async_trait::async_trait;
+use crate::core::runtime::DispatchCtx;
use crate::config::Config;
-use crate::memory::engine::{self, BoundEngine};
+use crate::memory::engine;
+use crate::memory::run_slots::{self, BACKFILL, IMPORT, MIGRATION};
use crate::threads::store::blocking as threads;
use tinymemory_api::{Error, Result};
-use tinymemory_integrations::import::ImportPhase;
-use tinymemory_tools::layout::identity::ResolvedIdentity;
-
-use tinymemory_tools::backfill::{first_live_turn, group_items, turn_groups, ThreadMessage};
-pub use tinymemory_tools::backfill::{pending_range, turns_of, PastTurn, BACKFILL_TAG, MAIN_AGENT};
+use tinymemory_tools::backfill::{BackfillFile, Backfiller, CounterStore, ThreadMessage, ThreadSource};
+use tinymemory_tools::layout::identity::Identity;
-/// Backfills running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// Progress of the last (or current) backfill.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
-pub struct BackfillState {
- /// Idle, running, done, or stopped on an error.
- pub phase: ImportPhase,
- /// Threads with turns to store when the run started.
- pub threads_total: u64,
- /// Of those, threads finished.
- pub threads_done: u64,
- /// Turns stored by the run.
- pub turns_stored: u64,
- /// Conversation items stored by the run.
- pub items_stored: u64,
- /// Why it stopped, when it failed.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- /// When the last run finished.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub finished_at: Option<DateTime<Utc>>,
-}
-
-/// `memory_conversations_backfill_status` / `_start` result.
-#[derive(Debug, Clone, Serialize)]
-pub struct BackfillView {
- /// The run's progress.
- pub state: BackfillState,
- /// Threads that still have earlier turns to store.
- pub pending_threads: u64,
- /// Turns still to store across them.
- pub pending_turns: u64,
-}
+pub use tinymemory_tools::backfill::{
+ BackfillPhase, BackfillState, BackfillView, BACKFILL_TAG, MAIN_AGENT, PastTurn, pending_range,
+ turns_of,
+};
/// `memory_conversations_backfill_start` params.
-#[derive(Debug, Clone, Default, Deserialize)]
+#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct BackfillStartParams {
/// The caller agrees to upload past chats to the engine.
#[serde(default)]
pub consent: bool,
}
-#[derive(Debug, Default, Serialize, Deserialize)]
-struct BackfillFile {
- #[serde(default)]
- state: BackfillState,
- /// Turns stored so far, per thread.
- #[serde(default)]
- stored: BTreeMap<String, u32>,
+struct HostThreadSource {
+ ctx: DispatchCtx,
+ workspace_dir: PathBuf,
}
-fn file_path(workspace_dir: &Path) -> PathBuf {
- workspace_dir
- .join("memory")
- .join("conversations_backfill.json")
+#[async_trait]
+impl ThreadSource for HostThreadSource {
+ async fn list_threads(&self) -> std::result::Result<Vec<String>, String> {
+ threads::list_threads(self.ctx.clone(), self.workspace_dir.clone())
+ .await
+ .map(|threads| threads.into_iter().map(|thread| thread.id).collect())
+ .map_err(|error| error.to_string())
+ }
+
+ async fn messages(&self, thread_id: &str) -> std::result::Result<Vec<ThreadMessage>, String> {
+ threads::get_messages(
+ self.ctx.clone(),
+ self.workspace_dir.clone(),
+ thread_id.to_string(),
+ )
+ .await
+ .map(|messages| {
+ messages
+ .into_iter()
+ .map(|message| {
+ ThreadMessage::new(message.sender, message.content, message.created_at)
+ })
+ .collect()
+ })
+ .map_err(|error| error.to_string())
+ }
}
-fn read_file(workspace_dir: &Path) -> BackfillFile {
- std::fs::read_to_string(file_path(workspace_dir))
- .ok()
- .and_then(|text| serde_json::from_str(&text).ok())
- .unwrap_or_default()
+struct FileCounterStore {
+ workspace_dir: PathBuf,
}
-/// Persists `file` atomically (staged, synced, renamed), so a crash
-/// mid-write keeps the previous progress instead of losing it.
-fn write_file(workspace_dir: &Path, file: &BackfillFile) {
- let result = serde_json::to_vec_pretty(file)
- .map_err(|error| error.to_string())
- .and_then(|json| {
- crate::security::secret_storage::file_store::write_atomic(
- &file_path(workspace_dir),
- &json,
- )
- .map_err(|error| error.to_string())
- });
- if let Err(error) = result {
- tracing::warn!(error = %error, "[memory:backfill] writing state failed");
+impl FileCounterStore {
+ fn path(&self) -> PathBuf {
+ self.workspace_dir
+ .join("memory")
+ .join("conversations_backfill.json")
}
}
-/// One thread's plan: its turns and the range still to store.
-struct ThreadPlan {
- thread_id: String,
- turns: Vec<PastTurn>,
- range: std::ops::Range<usize>,
-}
+impl CounterStore for FileCounterStore {
+ fn load(&self) -> BackfillFile {
+ std::fs::read_to_string(self.path())
+ .ok()
+ .and_then(|text| serde_json::from_str(&text).ok())
+ .unwrap_or_default()
+ }
-async fn plan(
- ctx: &DispatchCtx,
- workspace_dir: &Path,
- bound: Option<&BoundEngine>,
- stored: &BTreeMap<String, u32>,
-) -> Result<Vec<ThreadPlan>> {
- let listed = threads::list_threads(ctx.clone(), workspace_dir.to_path_buf())
- .await
- .map_err(|error| Error::Engine(format!("reading chat threads failed: {error}")))?;
- let mut plans = Vec::new();
- for thread in listed {
- let messages = match threads::get_messages(
- ctx.clone(),
- workspace_dir.to_path_buf(),
- thread.id.clone(),
- )
- .await
- {
- Ok(messages) => messages,
- Err(error) => {
- tracing::warn!(error = %error, "[memory:backfill] a thread was unreadable; skipped");
- continue;
- }
- };
- let messages: Vec<ThreadMessage> = messages
- .into_iter()
- .map(|m| ThreadMessage::new(m.sender, m.content, m.created_at))
- .collect();
- let turns = turns_of(&messages);
- let first_live = match bound {
- Some(bound) => first_live_turn(bound.engine.as_ref(), &thread.id).await,
- None => None,
- };
- let range = pending_range(
- turns.len(),
- first_live,
- stored.get(&thread.id).copied().unwrap_or(0),
- );
- if !range.is_empty() {
- plans.push(ThreadPlan {
- thread_id: thread.id,
- turns,
- range,
- });
- }
+ fn save(&self, file: &BackfillFile) -> std::result::Result<(), String> {
+ let bytes = serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?;
+ crate::security::secret_storage::file_store::write_atomic(&self.path(), &bytes)
+ .map_err(|error| error.to_string())
}
- Ok(plans)
}
-fn is_running(workspace_dir: &Path) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(workspace_dir)
+fn driver(
+ ctx: DispatchCtx,
+ config: &Config,
+ engine: Arc<dyn tinymemory_api::MemoryEngine>,
+) -> Result<Backfiller> {
+ let identity = Identity::agent(MAIN_AGENT).resolve(&crate::memory::scope::identity_pins(config));
+ Ok(Backfiller::new(
+ engine,
+ identity.layout,
+ identity.agent_id,
+ Arc::new(HostThreadSource {
+ ctx,
+ workspace_dir: config.workspace_dir.clone(),
+ }),
+ Arc::new(FileCounterStore {
+ workspace_dir: config.workspace_dir.clone(),
+ }),
+ ))
}
/// `memory_conversations_backfill_status`.
pub async fn status(ctx: &DispatchCtx, config: &Config) -> Result<BackfillView> {
- let workspace_dir = &config.workspace_dir;
- let file = read_file(workspace_dir);
- let mut state = file.state;
- if state.phase == ImportPhase::Running && !is_running(workspace_dir) {
- state.phase = ImportPhase::Error;
- state.error = Some("the sync was interrupted; start it again to resume".to_string());
- }
- let bound = engine::resolve(config).engine().ok();
- let plans = plan(ctx, workspace_dir, bound.as_ref(), &file.stored).await?;
- Ok(BackfillView {
- state,
- pending_threads: plans.len() as u64,
- pending_turns: plans.iter().map(|p| p.range.len() as u64).sum(),
- })
+ let bound = engine::resolve(config).engine()?;
+ driver(ctx.clone(), config, bound.engine)?
+ .status(BACKFILL.is_running(&config.workspace_dir))
+ .await
}
/// `memory_conversations_backfill_start`: requires `consent` and memory on.
@@ -217,146 +127,32 @@ pub async fn start(
) -> Result<BackfillView> {
if !params.consent {
return Err(Error::InvalidRequest(
- ("storing past chats uploads them to the selected engine; pass consent: true").into(),
+ "storing past chats uploads them to the selected engine; pass consent: true".into(),
));
}
let bound = engine::resolve(config).engine()?;
- let workspace_dir = config.workspace_dir.clone();
- let claimed = RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(workspace_dir.clone());
- if !claimed {
+ let workspace = config.workspace_dir.clone();
+ let Some(guard) = run_slots::reserve(&BACKFILL, &workspace, &[&IMPORT, &MIGRATION]) else {
return status(ctx, config).await;
- }
- let mut file = read_file(&workspace_dir);
- let plans = match plan(ctx, &workspace_dir, Some(&bound), &file.stored).await {
- Ok(plans) => plans,
- Err(error) => {
- release(&workspace_dir);
- return Err(error);
- }
- };
- let pending_turns: u64 = plans.iter().map(|p| p.range.len() as u64).sum();
- file.state = BackfillState {
- phase: ImportPhase::Running,
- threads_total: plans.len() as u64,
- ..BackfillState::default()
};
- write_file(&workspace_dir, &file);
- let view = BackfillView {
- state: file.state.clone(),
- pending_threads: plans.len() as u64,
- pending_turns,
+ let backfiller = driver(ctx.clone(), config, bound.engine)?;
+ let run = match backfiller.begin().await {
+ Ok(run) => run,
+ Err(error) => return Err(error),
};
- tracing::info!(
- threads = plans.len(),
- turns = pending_turns,
- "[memory:backfill] started"
- );
- let identity = tinymemory_tools::layout::identity::Identity::agent(MAIN_AGENT)
- .resolve(&crate::memory::scope::identity_pins(config));
- tokio::spawn(async move {
- run(&workspace_dir, &bound, &identity, file, plans).await;
- release(&workspace_dir);
+ let view = backfiller.status(true).await?;
+ let task_ctx = ctx.clone();
+ task_ctx.spawn(async move {
+ let _guard = guard;
+ let state = backfiller.run(run).await;
+ if state.phase == BackfillPhase::Done {
+ tracing::info!(items = state.items_stored, turns = state.turns_stored, "[memory:backfill] done");
+ }
});
Ok(view)
}
-fn release(workspace_dir: &Path) {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(workspace_dir);
+/// Whether a backfill task currently owns this workspace.
+pub(crate) fn is_running(workspace_dir: &Path) -> bool {
+ BACKFILL.is_running(&workspace_dir.to_path_buf())
}
-
-async fn run(
- workspace_dir: &Path,
- bound: &BoundEngine,
- identity: &ResolvedIdentity,
- mut file: BackfillFile,
- plans: Vec<ThreadPlan>,
-) {
- let last = last_batch(identity, &plans);
- for (thread, plan) in plans.into_iter().enumerate() {
- // Groups of whole turns, so the stored counter never splits a turn.
- for (index, group) in turn_groups(plan.range.clone()).into_iter().enumerate() {
- let items = group_items(
- &identity.layout,
- &identity.agent_id,
- &plan.thread_id,
- &plan.turns,
- &group,
- );
- let count = items.len() as u64;
- if count > 0 {
- // Accepted, not indexed: waiting on the engine to index every
- // batch made a few thousand messages take hours on CortexDB.
- // The last batch waits until it is visible: the scope's log
- // is ordered, so everything stored before it is then too, and
- // `done` still means searchable.
- let options = if last == Some((thread, index)) {
- tinymemory_api::WriteOptions::visible()
- } else {
- tinymemory_api::WriteOptions::accepted()
- };
- let stored = bound.engine.store_many_with(items, options).await;
- if let Err(error) = stored {
- tracing::warn!(
- code = error.code(),
- "[memory:backfill] storing a batch failed; stopping"
- );
- file.state.phase = ImportPhase::Error;
- file.state.error = Some(error.to_string());
- file.state.finished_at = Some(Utc::now());
- write_file(workspace_dir, &file);
- return;
- }
- }
- let end = group.last().map_or(0, |last| last + 1);
- file.stored.insert(
- plan.thread_id.clone(),
- u32::try_from(end).unwrap_or(u32::MAX),
- );
- file.state.turns_stored += group.len() as u64;
- file.state.items_stored += count;
- write_file(workspace_dir, &file);
- }
- file.state.threads_done += 1;
- write_file(workspace_dir, &file);
- }
- file.state.phase = ImportPhase::Done;
- file.state.finished_at = Some(Utc::now());
- write_file(workspace_dir, &file);
- tracing::info!(
- items = file.state.items_stored,
- turns = file.state.turns_stored,
- "[memory:backfill] done"
- );
-}
-
-/// The last batch of the run that stores anything, as (thread, group): the
-/// one the run waits on until it is visible.
-fn last_batch(identity: &ResolvedIdentity, plans: &[ThreadPlan]) -> Option<(usize, usize)> {
- plans.iter().enumerate().rev().find_map(|(thread, plan)| {
- turn_groups(plan.range.clone())
- .iter()
- .enumerate()
- .rev()
- .find(|(_, group)| {
- !group_items(
- &identity.layout,
- &identity.agent_id,
- &plan.thread_id,
- &plan.turns,
- group,
- )
- .is_empty()
- })
- .map(|(index, _)| (thread, index))
- })
-}
-
-#[cfg(test)]
-#[path = "backfill_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index 2421689b65..d387b25db7 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -35,6 +35,7 @@ pub mod layout_migration;
pub mod lifecycle;
pub mod local_root;
pub mod ops;
+pub(crate) mod run_slots;
pub mod schemas;
pub mod scope;
pub mod sources;
diff --git a/crates/openhuman-core/src/memory/run_slots.rs b/crates/openhuman-core/src/memory/run_slots.rs
new file mode 100644
index 0000000000..741f43ee79
--- /dev/null
+++ b/crates/openhuman-core/src/memory/run_slots.rs
@@ -0,0 +1,36 @@
+//! Live task reservations shared by the three memory background drivers.
+//!
+//! The start gate makes checking peer activity and reserving a driver's own
+//! slot one synchronous decision. Each driver keeps a distinct registry so a
+//! migration never appears as a live import or backfill (and vice versa).
+
+use std::path::{Path, PathBuf};
+use std::sync::LazyLock;
+
+use tinymemory_tools::run_slots::{RunGuard, RunSlots, RunStartGate};
+
+pub(crate) static START_GATE: LazyLock<RunStartGate> = LazyLock::new(RunStartGate::new);
+pub(crate) static BACKFILL: LazyLock<RunSlots<PathBuf>> = LazyLock::new(RunSlots::new);
+pub(crate) static IMPORT: LazyLock<RunSlots<PathBuf>> = LazyLock::new(RunSlots::new);
+pub(crate) static MIGRATION: LazyLock<RunSlots<PathBuf>> = LazyLock::new(RunSlots::new);
+
+/// Reserves `key` for `slots` only when no peer owns it.
+///
+/// The gate is held across every peer check and the reservation. The returned
+/// guard belongs to this driver only and must live inside its task future.
+pub(crate) fn reserve(
+ slots: &RunSlots<PathBuf>,
+ key: &Path,
+ peers: &[&RunSlots<PathBuf>],
+) -> Option<RunGuard<PathBuf>> {
+ let key = key.to_path_buf();
+ let mut guard = None;
+ let reserved = START_GATE.with_gate(&mut || {
+ if peers.iter().any(|peer| peer.is_running(&key)) {
+ return false;
+ }
+ guard = slots.try_acquire(key.clone());
+ guard.is_some()
+ });
+ reserved.then_some(guard).flatten()
+}