Skip to content

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

Import legacy memory in accepted batches, waiting once at the end

M3gA-Mind8acd1a92654f
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 8700c3fedd..8425c2d0e7 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -21,6 +21,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use serde::{Deserialize, Serialize};
+use tinymemory_api::{WaitFor, WriteOptions};
use tinymemory_integrations::cortex::is_insufficient_credits;
use tinymemory_integrations::import::{Checkpoint, ImportedItem, LegacyWorkspace};
@@ -111,6 +112,7 @@ where
Err(error) if error.is_transient() => {
tracing::debug!(
delay_ms = u64::try_from(delay.as_millis()).unwrap_or(u64::MAX),
+ %error,
"[memory:import] engine unavailable; retrying"
);
tokio::time::sleep(delay).await;
@@ -157,13 +159,14 @@ fn fatal_message(error: tinymemory_api::Error) -> String {
/// of an item (see [`skips_item`]), the items are stored one at a time instead
/// so only the bad ones are skipped. Any other failure stops the import
/// without advancing the checkpoint past what was stored.
-async fn store_batch(bound: &BoundEngine, batch: Vec<ImportedItem>) -> BatchOutcome {
+async fn store_batch(bound: &BoundEngine, batch: Vec<ImportedItem>, wait: WaitFor) -> BatchOutcome {
let Some(last) = batch.last() else {
return BatchOutcome::default();
};
let last_checkpoint = last.checkpoint.clone();
let items: Vec<_> = batch.iter().map(|imported| imported.item.clone()).collect();
- match with_retries(|| bound.engine.store_many(items.clone())).await {
+ let options = WriteOptions { wait };
+ match with_retries(|| bound.engine.store_many_with(items.clone(), options)).await {
Ok(receipts) => {
tracing::debug!(
engine = %bound.id,
@@ -589,6 +592,7 @@ async fn run(
let mut credits = false;
let mut pausing = false;
let mut batch: Vec<ImportedItem> = Vec::with_capacity(STORE_BATCH);
+ let mut last: Vec<ImportedItem> = Vec::new();
let mut reading = true;
while reading || !batch.is_empty() {
if reading && batch.len() < STORE_BATCH {
@@ -610,7 +614,10 @@ async fn run(
pausing = true;
break;
}
- let outcome = store_batch(bound, std::mem::take(&mut batch)).await;
+ // Accepted: nothing reads the import back until it ends, so a batch
+ // does not wait to be listed; the last one is waited for below.
+ last.clone_from(&batch);
+ let outcome = store_batch(bound, std::mem::take(&mut batch), WaitFor::Accepted).await;
file.state.imported += outcome.stored;
// One entry per legacy id; a later refusal replaces the reason.
for failed in outcome.failed {
@@ -645,6 +652,17 @@ async fn run(
}
drop(rx);
let _ = reader.await;
+ // Every batch was stored accepted. Before the import says it is done
+ // (and organizing reads it back), wait once for the last batch to be
+ // listed: storing it again visible is a replay that returns when it is.
+ if failure.is_none() && !pausing && !last.is_empty() {
+ let settled = store_batch(bound, last, WaitFor::Visible).await;
+ if let Some(error) = settled.fatal {
+ failure = Some(error);
+ transient = settled.transient;
+ credits = settled.credits;
+ }
+ }
if pausing {
// Left `Running` with its checkpoint: the next unpaused tick resumes it.
tracing::info!(
@@ -660,6 +678,7 @@ async fn run(
Some(error) if transient => {
tracing::info!(
imported = file.state.imported,
+ %error,
"[memory:import] engine unavailable; import left to resume"
);
file.state.error = Some(error);
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index 36d5d6181f..ccced67bae 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -707,3 +707,85 @@ async fn an_automatic_resume_that_cannot_start_is_stopped_not_retried() {
"d1 is not re-sent"
);
}
+
+/// A reference engine that records the wait each bulk store asks for.
+#[derive(Default)]
+struct WaitRecordingEngine {
+ inner: tinymemory_api::conformance::ReferenceEngine,
+ waits: std::sync::Mutex<Vec<tinymemory_api::WaitFor>>,
+}
+
+#[async_trait::async_trait]
+impl tinymemory_api::MemoryEngine for WaitRecordingEngine {
+ fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {
+ self.inner.descriptor()
+ }
+ async fn health(&self) -> tinymemory_api::EngineHealth {
+ self.inner.health().await
+ }
+ async fn recall(
+ &self,
+ req: tinymemory_api::RecallRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {
+ self.inner.recall(req).await
+ }
+ async fn fetch(
+ &self,
+ req: tinymemory_api::FetchRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {
+ self.inner.fetch(req).await
+ }
+ async fn store(
+ &self,
+ item: tinymemory_api::StoreItem,
+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {
+ self.inner.store(item).await
+ }
+ async fn store_many_with(
+ &self,
+ items: Vec<tinymemory_api::StoreItem>,
+ options: tinymemory_api::WriteOptions,
+ ) -> tinymemory_api::Result<Vec<tinymemory_api::StoreReceipt>> {
+ self.waits.lock().unwrap().push(options.wait);
+ self.inner.store_many(items).await
+ }
+ async fn forget(
+ &self,
+ target: tinymemory_api::ForgetTarget,
+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {
+ self.inner.forget(target).await
+ }
+ async fn list(
+ &self,
+ req: tinymemory_api::ListRequest,
+ ) -> tinymemory_api::Result<tinymemory_api::ListPage> {
+ self.inner.list(req).await
+ }
+}
+
+/// Batches are stored accepted (nothing reads them back mid-import); the
+/// last is stored again visible, once, before the import says it is done.
+#[tokio::test]
+async fn batches_are_stored_accepted_and_the_last_waited_for_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ let engine = Arc::new(WaitRecordingEngine::default());
+ crate::memory::engine::install_test_engine(&config.workspace_dir, engine.clone());
+
+ start(&config, true).await.unwrap();
+ let done = wait_until_settled(&config).await;
+ assert_eq!(done.phase, ImportPhase::Done, "{done:?}");
+ assert_eq!(
+ done.imported, 5,
+ "the final wait is a replay, not a recount"
+ );
+ assert_eq!(
+ *engine.waits.lock().unwrap(),
+ vec![
+ tinymemory_api::WaitFor::Accepted,
+ tinymemory_api::WaitFor::Visible
+ ],
+ "one accepted batch, then the visible wait for it"
+ );
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 296c16957d..b1e23a8b86 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -368,7 +368,7 @@ Spec: `docs/specs/memory-v2.md` (host) and `vendor/tinymemory/docs/specs/memory-
| 8.2.5 | Document sources: add, sync, list, remove | RU+RI+WD | `crates/openhuman-core/src/memory/sources/sync_tests.rs`, `crates/openhuman-core/src/memory/sources/composio_tests.rs`, `crates/openhuman-core/src/memory/sources/mod_tests.rs`, `tests/memory_v2_e2e.rs` (`sources_add_sync_list_and_remove`), `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | folder, file, link, github, rss, composio |
| 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts` | ✅ | |
| 8.2.7 | Pack preview (Ask tab) and brain views | RU+RI+WD | `crates/openhuman-core/src/memory/lifecycle/views_tests.rs`, `crates/openhuman-core/src/memory/brain_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | No `context.md`; pack never persisted in the transcript |
-| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`, `a stopped import resumes only after consent`), `app/src/components/memory/MemoryImportBanner.test.tsx` | ✅ | Refused without consent; stops (not skips) on exhausted credits (`exhausted_credits_stop_the_import_instead_of_skipping_everything`) and resumes on its own only while memory work is free, per `billing::free_period_active` (`an_import_out_of_credits_resumes_only_once_automatic_runs_are_allowed`); an unavailable engine is retried in-run (`a_transient_failure_is_retried_within_the_run`) and then resumed by the background job (`an_engine_that_stays_unavailable_is_resumed_by_the_background_job`); refused items are kept and retried (`a_refused_item_is_kept_and_a_retry_stores_it`); state written atomically and a resume keeps its total (`the_import_state_is_written_whole_and_leaves_no_staging_file`, `a_resumed_import_keeps_its_total_instead_of_rescanning`); the background job resumes an import the app quit during (`the_background_job_resumes_an_interrupted_import`), never while paused, including a pause mid-run (`nothing_resumes_while_background_work_is_paused`, `a_pause_that_lands_after_the_check_stops_the_run_at_the_next_batch`); a resume that cannot start is stopped, not retried (`an_automatic_resume_that_cannot_start_is_stopped_not_retried`); Resume button after an error, behind consent (`a stopped import resumes only after consent`) |
+| 8.2.8 | One-time import of previous (v1) memory | RU+RI+WD | `crates/openhuman-core/src/memory/import_tests.rs`, `tests/memory_v2_e2e.rs`, `app/test/playwright/specs/memory-v2.spec.ts` (`importing previous memory needs explicit consent`, `a stopped import resumes only after consent`), `app/src/components/memory/MemoryImportBanner.test.tsx` | ✅ | Refused without consent; stops (not skips) on exhausted credits (`exhausted_credits_stop_the_import_instead_of_skipping_everything`) and resumes on its own only while memory work is free, per `billing::free_period_active` (`an_import_out_of_credits_resumes_only_once_automatic_runs_are_allowed`); batches are stored accepted and the last waited for once before Done (`batches_are_stored_accepted_and_the_last_waited_for_once`); an unavailable engine is retried in-run (`a_transient_failure_is_retried_within_the_run`) and then resumed by the background job (`an_engine_that_stays_unavailable_is_resumed_by_the_background_job`); refused items are kept and retried (`a_refused_item_is_kept_and_a_retry_stores_it`); state written atomically and a resume keeps its total (`the_import_state_is_written_whole_and_leaves_no_staging_file`, `a_resumed_import_keeps_its_total_instead_of_rescanning`); the background job resumes an import the app quit during (`the_background_job_resumes_an_interrupted_import`), never while paused, including a pause mid-run (`nothing_resumes_while_background_work_is_paused`, `a_pause_that_lands_after_the_check_stops_the_run_at_the_next_batch`); a resume that cannot start is stopped, not retried (`an_automatic_resume_that_cannot_start_is_stopped_not_retried`); Resume button after an error, behind consent (`a stopped import resumes only after consent`) |
| 8.2.9 | MCP memory tools | RU | `crates/openhuman-core/src/mcp/server/tools/` | ✅ | `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn`, `memory.forget` |
| 8.2.10 | Memory UI chips and legacy redirects | VU+WD | `app/src/components/memory/*.test.tsx`, `app/test/playwright/specs/memory-v2.spec.ts` | ✅ | Engine, Ask, Explorer, Learnings, Conversations, Brain, Background, Settings; `/brain` and `/settings/memory-engine` redirect |
| 8.2.11 | Move into the per-user layout (v3) | RU+VU+WD | `crates/openhuman-core/src/memory/layout_migration/*_tests.rs`, `app/src/components/memory/MemoryImportBanner.test.tsx`, `app/test/playwright/specs/memory-v2.spec.ts` (`migrate now moves the legacy memory and the banner goes away`, `a tree other accounts may share is taken only after consent`) | ✅ | Items are stored again and verified, never copied as events; no switch before a full copy, then a catch-up copy; a source is removed only after its twin is verified (`an_item_without_its_twin_is_never_removed`), by kind-scope erasure or by id where the engine cannot erase; resumable after a pause or crash; runs on its own only while moving is free; a shared self-hosted tree moves only with consent and only one account may claim it (`a_tree_another_account_took_is_left_alone`, `the_first_account_takes_the_tree_and_keeps_it`); items are placed in the v3 layout before the setting switches (`places_into_the_v3_layout_before_the_switch`); signed out there is nothing to move; never starts while an import of old local memory is unfinished, counting a reserved import before its first state write (`nothing_starts_while_an_import_is_unfinished`, `an_import_counts_as_in_progress_from_its_reservation`), and starts on its own once the import is done, free period or not (`a_finished_import_starts_organizing_into_the_per_user_tree`); one banner shows import then organize (`does not organize while the import is still running`) |