Skip to content

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

fix(memory): wait on the backfill's last batch so a done run is searchable

sanil-238bfb1319b75a
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index c76098eb6f..5a7c4c4496 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -20,10 +20,11 @@
//! 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, not indexed.** Batches go in with accepted writes: the
-//! engine returns once it holds them durably, and indexes them after. A
-//! run is `done` when every turn is stored; search catches up within
-//! minutes. An engine without accepted writes stores them as before.
+//! - **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`.
@@ -276,9 +277,10 @@ async fn run(
mut file: BackfillFile,
plans: Vec<ThreadPlan>,
) {
- for plan in plans {
+ 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 group in turn_groups(plan.range.clone()) {
+ for (index, group) in turn_groups(plan.range.clone()).into_iter().enumerate() {
let items = group_items(
&identity.layout,
&identity.agent_id,
@@ -288,13 +290,17 @@ async fn run(
);
let count = items.len() as u64;
if count > 0 {
- // Accepted, not indexed: the run reads nothing back, and
- // waiting on the engine to index every batch made a few
- // thousand messages take hours on CortexDB. They are durably
- // stored on return and searchable shortly after.
- let stored =
- store_many_on_with(bound, items, tinymemory_api::WriteOptions::accepted())
- .await;
+ // 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 = store_many_on_with(bound, items, options).await;
if let Err(error) = stored {
tracing::warn!(
code = error.code(),
@@ -329,6 +335,28 @@ async fn run(
);
}
+/// 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/backfill_tests.rs b/crates/openhuman-core/src/memory/backfill_tests.rs
index 483134733e..3f35e825b6 100644
--- a/crates/openhuman-core/src/memory/backfill_tests.rs
+++ b/crates/openhuman-core/src/memory/backfill_tests.rs
@@ -231,7 +231,7 @@ impl tinymemory_api::MemoryEngine for WaitRecorder {
}
#[tokio::test]
-async fn batches_are_stored_accepted_without_waiting_on_indexing() {
+async fn batches_are_stored_accepted_and_the_last_one_visible() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let engine = std::sync::Arc::new(WaitRecorder {
@@ -250,6 +250,15 @@ async fn batches_are_stored_accepted_without_waiting_on_indexing() {
],
)
.await;
+ seed_thread(
+ &config.workspace_dir,
+ "older-thread",
+ &[
+ ("user", "What is a lifetime?"),
+ ("agent", "How long a reference is valid."),
+ ],
+ )
+ .await;
start(
&DispatchCtx::ambient(),
@@ -260,15 +269,21 @@ async fn batches_are_stored_accepted_without_waiting_on_indexing() {
.unwrap();
let done = wait_done(&config).await;
assert_eq!(done.state.phase, ImportPhase::Done, "{:?}", done.state);
- assert_eq!(done.state.items_stored, 4);
+ assert_eq!(done.state.items_stored, 6);
let waits = engine.waits.lock().unwrap().clone();
- assert!(!waits.is_empty(), "the backfill stores in bulk");
+ assert_eq!(waits.len(), 2, "one batch per thread: {waits:?}");
+ let (last, earlier) = waits.split_last().expect("the backfill stores in bulk");
assert!(
- waits
+ earlier
.iter()
.all(|wait| *wait == tinymemory_api::WaitFor::Accepted),
- "every batch is stored accepted, not visible: {waits:?}"
+ "every batch but the last is stored accepted: {waits:?}"
+ );
+ assert_eq!(
+ *last,
+ tinymemory_api::WaitFor::Visible,
+ "the last batch waits until it is visible, so a done run is searchable"
);
let filter = MetaFilter {
kinds: vec![ItemKind::Conversation],
@@ -277,7 +292,7 @@ async fn batches_are_stored_accepted_without_waiting_on_indexing() {
};
assert_eq!(
stored(&engine.inner, filter).await.len(),
- 4,
+ 6,
"an engine without accepted writes still stores everything"
);
}
diff --git a/crates/openhuman-core/src/memory/ops.rs b/crates/openhuman-core/src/memory/ops.rs
index 84e0128093..1a2407a69c 100644
--- a/crates/openhuman-core/src/memory/ops.rs
+++ b/crates/openhuman-core/src/memory/ops.rs
@@ -361,21 +361,13 @@ pub async fn store_on_with(
Ok(receipt)
}
-/// Stores `items` on `bound` in one bulk call (`MemoryEngine::store_many`):
-/// each is listed on return, ranked recall may lag behind for all but the
-/// last.
-pub async fn store_many_on(
- bound: &BoundEngine,
- items: Vec<StoreItem>,
-) -> MemoryResult<Vec<StoreReceipt>> {
- store_many_on_with(bound, items, WriteOptions::visible()).await
-}
-
-/// [`store_many_on`], returning as soon as `options` allows. A backfill or an
-/// import that reads nothing back until it ends passes
+/// Stores `items` on `bound` in one bulk call, returning as soon as
+/// `options` allows. With [`WriteOptions::visible`] each item is listed on
+/// return, and ranked recall may lag behind for all but the last. A backfill
+/// or an import that reads nothing back until it ends passes
/// [`WriteOptions::accepted`]: an engine that supports it (CortexDB) returns
/// once the items are durably accepted, before they are indexed, and any
-/// other stores them as [`store_many_on`] does.
+/// other stores them as with `visible`.
pub async fn store_many_on_with(
bound: &BoundEngine,
items: Vec<StoreItem>,