Skip to content

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

feat(memory): add source sync backfill for memory ingestion

Steven Enamakel9c5f97e275f1
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index c1c59c6a58..3fe607d7b6 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -6,6 +6,9 @@
//! 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
@@ -26,10 +29,6 @@ use std::sync::{LazyLock, Mutex};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
-use tinymemory_api::{
- ItemKind, ListRequest, MemoryMeta, MetaFilter, Role, SourceKind, SourceRef, StoreItem, Turn,
- TurnRange,
-};
use crate::config::Config;
use crate::memory::engine::{self, BoundEngine};
@@ -38,19 +37,11 @@ use crate::memory::ops::store_many_on;
use crate::memory::scope::{MemoryIdentity, ResolvedIdentity};
use crate::memory::types::ImportPhase;
use crate::threads::store::blocking as threads;
-use crate::threads::store::ConversationMessage;
-
-/// The tag every backfilled conversation item carries.
-pub const BACKFILL_TAG: &str = "backfill";
-
-/// The agent definition past chats belong to: the main chat agent.
-pub const MAIN_AGENT: &str = "orchestrator";
-
-/// Conversation items per bulk store (`MemoryEngine::store_many`).
-const STORE_GROUP: usize = 50;
-/// Items a thread lookup lists to find where live logging began.
-const LIVE_SCAN_LIMIT: usize = 200;
+pub use tinymemory_tools::backfill::{
+ pending_range, turns_of, PastTurn, BACKFILL_TAG, MAIN_AGENT,
+};
+use tinymemory_tools::backfill::{first_live_turn, group_items, turn_groups, ThreadMessage};
/// Backfills running now, per workspace.
static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
@@ -134,144 +125,6 @@ fn write_file(workspace_dir: &Path, file: &BackfillFile) {
}
}
-fn parse_time(raw: &str) -> Option<DateTime<Utc>> {
- DateTime::parse_from_rfc3339(raw)
- .ok()
- .map(|at| at.with_timezone(&Utc))
-}
-
-/// One past turn: what the user said and what came back.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct PastTurn {
- /// The user's message; empty for replies before any user message.
- pub user: String,
- /// The replies, joined.
- pub assistant: String,
- /// When the turn last changed.
- pub at: DateTime<Utc>,
-}
-
-/// A thread's messages as turns, oldest first.
-#[must_use]
-pub fn turns_of(messages: &[ConversationMessage]) -> Vec<PastTurn> {
- let mut turns: Vec<PastTurn> = Vec::new();
- for message in messages {
- let text = message.content.trim();
- if text.is_empty() {
- continue;
- }
- let at = parse_time(&message.created_at);
- if message.sender.eq_ignore_ascii_case("user") {
- turns.push(PastTurn {
- user: text.to_string(),
- assistant: String::new(),
- at: at.unwrap_or_else(Utc::now),
- });
- continue;
- }
- if turns.is_empty() {
- turns.push(PastTurn {
- user: String::new(),
- assistant: String::new(),
- at: at.unwrap_or_else(Utc::now),
- });
- }
- if let Some(turn) = turns.last_mut() {
- if !turn.assistant.is_empty() {
- turn.assistant.push_str("\n\n");
- }
- turn.assistant.push_str(text);
- if let Some(at) = at {
- turn.at = at;
- }
- }
- }
- turns
-}
-
-/// Which turns of a thread with `total` turns the backfill should store:
-/// from what it already stored up to (not including) the first turn live
-/// logging took, if any.
-#[must_use]
-pub fn pending_range(
- total: usize,
- first_live: Option<usize>,
- already_stored: u32,
-) -> std::ops::Range<usize> {
- let end = first_live.map_or(total, |first| first.min(total));
- let start = (already_stored as usize).min(end);
- start..end
-}
-
-/// The conversation items for turn `index` of `thread_id`, shaped as the
-/// lifecycle logs them (one per message), tagged [`BACKFILL_TAG`].
-#[must_use]
-pub fn turn_items(
- identity: &ResolvedIdentity,
- thread_id: &str,
- index: usize,
- turn: &PastTurn,
-) -> Vec<StoreItem> {
- let Ok(node) = identity.layout.conversations(&identity.agent_id) else {
- return Vec::new();
- };
- let base = u32::try_from(index.saturating_mul(2)).unwrap_or(u32::MAX - 1);
- [
- (Role::User, &turn.user, base),
- (Role::Assistant, &turn.assistant, base + 1),
- ]
- .into_iter()
- .filter(|(_, text, _)| !text.trim().is_empty())
- .map(|(role, text, at_index)| StoreItem::Conversation {
- meta: MemoryMeta {
- namespace: node.clone(),
- thread_id: Some(thread_id.to_string()),
- turns: Some(TurnRange {
- first: at_index,
- last: at_index,
- }),
- agent_id: Some(identity.agent_id.clone()),
- source: SourceRef {
- kind: SourceKind::Conversation,
- id: Some(thread_id.to_string()),
- },
- observed_at: Some(turn.at),
- tags: vec![BACKFILL_TAG.to_string()],
- ..MemoryMeta::default()
- },
- turns: vec![Turn {
- at: Some(turn.at),
- ..Turn::new(role, text.as_str())
- }],
- })
- .collect()
-}
-
-/// The first turn of `thread_id` the lifecycle logged (not a backfill), as a
-/// turn number; `None` when none was.
-async fn first_live_turn(bound: &BoundEngine, thread_id: &str) -> Option<usize> {
- let page = bound
- .engine
- .list(ListRequest {
- filter: MetaFilter {
- thread_id: Some(thread_id.to_string()),
- ..MetaFilter::kinds([ItemKind::Conversation])
- },
- limit: LIVE_SCAN_LIMIT,
- cursor: None,
- })
- .await
- .map_err(|error| {
- tracing::debug!(%error, "[memory:backfill] live turn lookup failed");
- })
- .ok()?;
- page.items
- .iter()
- .filter(|hit| !hit.meta.tags.iter().any(|tag| tag == BACKFILL_TAG))
- .filter_map(|hit| hit.meta.turns.map(|turns| turns.first as usize / 2))
- .min()
-}
-
/// One thread's plan: its turns and the range still to store.
struct ThreadPlan {
thread_id: String,
@@ -298,9 +151,13 @@ async fn plan(
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, &thread.id).await,
+ Some(bound) => first_live_turn(bound.engine.as_ref(), &thread.id).await,
None => None,
};
let range = pending_range(
@@ -408,13 +265,15 @@ async fn run(
plans: Vec<ThreadPlan>,
) {
for plan in plans {
- let indices: Vec<usize> = plan.range.clone().collect();
// Groups of whole turns, so the stored counter never splits a turn.
- for group in indices.chunks(STORE_GROUP / 2) {
- let items: Vec<StoreItem> = group
- .iter()
- .flat_map(|&index| turn_items(identity, &plan.thread_id, index, &plan.turns[index]))
- .collect();
+ for group in turn_groups(plan.range.clone()) {
+ let items = group_items(
+ &identity.layout,
+ &identity.agent_id,
+ &plan.thread_id,
+ &plan.turns,
+ &group,
+ );
let count = items.len() as u64;
if count > 0 {
if let Err(error) = store_many_on(bound, items).await {
diff --git a/crates/openhuman-core/src/memory/backfill_tests.rs b/crates/openhuman-core/src/memory/backfill_tests.rs
index e7640cafd4..564d075897 100644
--- a/crates/openhuman-core/src/memory/backfill_tests.rs
+++ b/crates/openhuman-core/src/memory/backfill_tests.rs
@@ -6,7 +6,7 @@ use tinymemory_api::{ItemKind, MetaFilter};
use crate::memory::error::{INVALID_REQUEST, MEMORY_OFF};
use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use crate::threads::store::CreateConversationThread;
+use crate::threads::store::{ConversationMessage, CreateConversationThread};
fn message(id: &str, sender: &str, content: &str, at: &str) -> ConversationMessage {
ConversationMessage {
@@ -61,58 +61,6 @@ async fn wait_done(config: &Config) -> BackfillView {
panic!("the backfill did not finish");
}
-#[test]
-fn messages_become_turns_like_the_chat_shows_them() {
- let messages = [
- message("0", "agent", "Welcome!", "2026-09-01T09:59:00Z"),
- message("1", "user", "Plan a trip", "2026-09-01T10:00:00Z"),
- message("2", "agent", "Where to?", "2026-09-01T10:01:00Z"),
- message("3", "agent", "Also, when?", "2026-09-01T10:02:00Z"),
- message("4", "user", " ", "2026-09-01T10:03:00Z"),
- message("5", "user", "Bali in October", "not a time"),
- ];
- let turns = turns_of(&messages);
- assert_eq!(turns.len(), 3);
- assert_eq!(turns[0].user, "");
- assert_eq!(turns[0].assistant, "Welcome!");
- assert_eq!(turns[1].user, "Plan a trip");
- assert_eq!(turns[1].assistant, "Where to?\n\nAlso, when?");
- assert_eq!(turns[1].at.to_rfc3339(), "2026-09-01T10:02:00+00:00");
- assert_eq!(turns[2].user, "Bali in October");
- assert!(turns[2].assistant.is_empty());
-}
-
-#[test]
-fn the_range_stops_where_live_logging_began() {
- assert_eq!(pending_range(10, None, 0), 0..10);
- assert_eq!(pending_range(10, Some(7), 0), 0..7, "turns 7.. are live's");
- assert_eq!(pending_range(10, Some(7), 4), 4..7);
- assert_eq!(pending_range(10, Some(7), 9), 7..7, "nothing left");
- assert_eq!(pending_range(2, Some(5), 0), 0..2);
-}
-
-#[test]
-fn a_turn_is_one_item_per_message_at_the_agents_node() {
- let config = Config::default();
- let identity = MemoryIdentity::agent(MAIN_AGENT).resolve(&config);
- let turn = PastTurn {
- user: "q".into(),
- assistant: "a".into(),
- at: Utc::now(),
- };
- let items = turn_items(&identity, "t", 3, &turn);
- assert_eq!(items.len(), 2);
- let meta = items[1].meta();
- assert_eq!(meta.turns.map(|range| range.first), Some(7));
- assert_eq!(meta.namespace.to_string(), "agent:orchestrator");
- assert!(meta.tags.iter().any(|tag| tag == BACKFILL_TAG));
- let reply_only = PastTurn {
- user: String::new(),
- ..turn
- };
- assert_eq!(turn_items(&identity, "t", 0, &reply_only).len(), 1);
-}
-
#[tokio::test]
async fn refuses_without_consent_and_with_memory_off() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rs
index 61939ecf9d..b843d17d4e 100644
--- a/crates/openhuman-core/src/memory/sources/mod.rs
+++ b/crates/openhuman-core/src/memory/sources/mod.rs
@@ -10,7 +10,6 @@
pub mod state;
mod sync;
-use chrono::{DateTime, Utc};
use tinymemory_api::{ForgetTarget, MetaFilter};
use crate::config::schema::{MemorySourceConfig, MemorySourceKind};
@@ -18,7 +17,7 @@ use crate::config::Config;
use super::engine;
use super::error::{MemoryError, MemoryResult};
-use super::types::{SourceStatus, SourceView, SourcesAddParams};
+use super::types::{SourceView, SourcesAddParams};
pub use sync::{start_sync, sync_due, sync_one};
diff --git a/crates/openhuman-core/src/memory/sources/mod_tests.rs b/crates/openhuman-core/src/memory/sources/mod_tests.rs
index ee90ce270f..0797724d28 100644
--- a/crates/openhuman-core/src/memory/sources/mod_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/mod_tests.rs
@@ -188,56 +188,6 @@ fn view_overlays_the_sync_state() {
assert_eq!(super::view(&src, None).status, SourceStatus::Idle);
}
-#[test]
-fn is_due_follows_schedule_and_status() {
- let now = Utc::now();
- let scheduled = source("s", Some(60));
- assert!(
- !is_due(&source("manual", None), None, now),
- "on demand only"
- );
- assert!(is_due(&scheduled, None, now), "never synced");
-
- let synced = |ago_mins: i64, status| state::SourceState {
- last_sync_at: Some(now - Duration::minutes(ago_mins)),
- status,
- ..state::SourceState::default()
- };
- assert!(!is_due(
- &scheduled,
- Some(&synced(59, SourceStatus::Idle)),
- now
- ));
- assert!(is_due(
- &scheduled,
- Some(&synced(60, SourceStatus::Idle)),
- now
- ));
- assert!(
- is_due(&scheduled, Some(&synced(500, SourceStatus::Error)), now),
- "errors retry"
- );
- assert!(!is_due(
- &scheduled,
- Some(&synced(500, SourceStatus::Syncing)),
- now
- ));
- let no_last_sync = state::SourceState::default();
- assert!(is_due(&scheduled, Some(&no_last_sync), now));
-}
-
-#[test]
-fn is_due_never_schedules_faster_than_the_minimum() {
- let now = Utc::now();
- let mut eager = source("s", Some(1));
- eager.schedule_mins = Some(1);
- let state = state::SourceState {
- last_sync_at: Some(now - Duration::minutes(5)),
- ..state::SourceState::default()
- };
- assert!(!is_due(&eager, Some(&state), now));
-}
-
#[tokio::test]
async fn forget_items_removes_only_that_sources_documents() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/openhuman-core/src/memory/sources/sync_tests.rs b/crates/openhuman-core/src/memory/sources/sync_tests.rs
index d042665e0a..f2fa96cfa6 100644
--- a/crates/openhuman-core/src/memory/sources/sync_tests.rs
+++ b/crates/openhuman-core/src/memory/sources/sync_tests.rs
@@ -42,7 +42,7 @@ async fn wait_for_idle(config: &Config, id: &str) -> state::SourceState {
}
#[test]
-fn reader_entry_maps_every_kind() {
+fn validate_accepts_every_kind_and_refuses_a_bad_url() {
let mk = |kind, target: &str| MemorySourceConfig {
id: "s".into(),
kind,
@@ -51,18 +51,21 @@ fn reader_entry_maps_every_kind() {
schedule_mins: None,
namespace: None,
};
- let folder = reader_entry(&mk(MemorySourceKind::Folder, "/p")).unwrap();
- assert_eq!(folder.path.as_deref(), Some("/p"));
- let file = reader_entry(&mk(MemorySourceKind::File, "/p/a.md")).unwrap();
- assert_eq!(file.path.as_deref(), Some("/p/a.md"));
for (kind, target) in [
+ (MemorySourceKind::Folder, "/p"),
+ (MemorySourceKind::File, "/p/a.md"),
(MemorySourceKind::Link, "https://example.com/"),
(MemorySourceKind::Github, "https://github.com/o/r"),
(MemorySourceKind::Rss, "https://example.com/feed"),
] {
- let entry = reader_entry(&mk(kind, target)).unwrap();
- assert_eq!(entry.url.as_deref(), Some(target));
+ validate(&mk(kind, target)).unwrap();
}
+ assert_eq!(
+ validate(&mk(MemorySourceKind::Link, "not a url"))
+ .unwrap_err()
+ .code(),
+ INVALID_REQUEST
+ );
}
#[tokio::test]
@@ -176,10 +179,11 @@ async fn a_source_already_syncing_is_not_started_twice() {
.memory
.sources
.push(folder_source("src-once", &dir, None));
- let key = (config.workspace_dir.clone(), "src-once".to_string());
- RUNNING.lock().unwrap().insert(key.clone());
+ // Hold a claim as a running sync would: a second request starts nothing.
+ let held = syncer_for(&config).start(Some("src-once")).unwrap();
+ assert_eq!(held.len(), 1);
assert!(start_sync(&config, Some("src-once")).unwrap().is_empty());
- RUNNING.lock().unwrap().remove(&key);
+ drop(held);
assert_eq!(start_sync(&config, Some("src-once")).unwrap().len(), 1);
wait_for_idle(&config, "src-once").await;
}
@@ -231,118 +235,6 @@ fn sync_due_with_memory_off_starts_nothing() {
assert!(sync_due(&config, Utc::now()).is_empty());
}
-#[tokio::test]
-async fn store_all_skips_a_bad_item_but_fails_when_nothing_stored() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- bind_reference(&config);
- let bound = engine::resolve(&config).engine().unwrap();
- let good = tinymemory_api::StoreItem::learning(
- "a good one",
- tinymemory_api::LearningKind::Fact,
- 0.8,
- tinymemory_api::MemoryMeta::default(),
- );
- let bad = tinymemory_api::StoreItem::learning(
- " ",
- tinymemory_api::LearningKind::Fact,
- 0.8,
- tinymemory_api::MemoryMeta::default(),
- );
- assert_eq!(
- store_all(
- &config,
- &bound,
- vec![bad.clone(), good],
- (MemorySourceKind::Folder, "src"),
- &tinymemory_tools::MemoryLayout::default()
- )
- .await
- .unwrap(),
- 1
- );
- assert!(store_all(
- &config,
- &bound,
- vec![bad],
- (MemorySourceKind::Folder, "src"),
- &tinymemory_tools::MemoryLayout::default()
- )
- .await
- .is_err());
- assert_eq!(
- store_all(
- &config,
- &bound,
- Vec::new(),
- (MemorySourceKind::Folder, "src"),
- &tinymemory_tools::MemoryLayout::default()
- )
- .await
- .unwrap(),
- 0
- );
-}
-
-/// More items than one request may carry (`MAX_STORE_MANY`), so the store
-/// spans several batches. Pins that nothing is dropped or double-counted at a
-/// chunk boundary, and that a bad item in the middle still only costs itself.
-#[tokio::test]
-async fn store_all_spans_chunk_boundaries_without_losing_items() {
- let tmp = tempfile::tempdir().unwrap();
- let config = config_in(&tmp);
- bind_reference(&config);
- let bound = engine::resolve(&config).engine().unwrap();
-
- let good = |n: usize| {
- tinymemory_api::StoreItem::learning(
- format!("fact {n}"),
- tinymemory_api::LearningKind::Fact,
- 0.8,
- tinymemory_api::MemoryMeta::default(),
- )
- };
- // Two and a half requests' worth.
- let total = tinymemory_api::MAX_STORE_MANY * 2 + 50;
- let items: Vec<_> = (0..total).map(good).collect();
- assert_eq!(
- store_all(
- &config,
- &bound,
- items,
- (MemorySourceKind::Folder, "src"),
- &tinymemory_tools::MemoryLayout::default()
- )
- .await
- .unwrap(),
- total as u64,
- "every item across every chunk must be counted exactly once"
- );
-
- // A blank item in the second chunk: that chunk falls back to one request
- // per item, and only the blank one is lost.
- let mut items: Vec<_> = (0..total).map(good).collect();
- items[tinymemory_api::MAX_STORE_MANY + 10] = tinymemory_api::StoreItem::learning(
- " ",
- tinymemory_api::LearningKind::Fact,
- 0.8,
- tinymemory_api::MemoryMeta::default(),
- );
- assert_eq!(
- store_all(
- &config,
- &bound,
- items,
- (MemorySourceKind::Folder, "src"),
- &tinymemory_tools::MemoryLayout::default()
- )
- .await
- .unwrap(),
- total as u64 - 1,
- "a bad item must cost only itself, not its chunk"
- );
-}
-
#[test]
fn reset_interrupted_marks_syncing_sources_idle() {
let tmp = tempfile::tempdir().unwrap();