Skip to content

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

Keep the items an import skipped, and retry them

M3gA-Mind188d02fdd9cc
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 5c434d25ca..fb21347d44 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -71,6 +71,32 @@ struct BatchOutcome {
/// Whether `fatal` is the account's credits running out: the run is
/// paused until automatic runs are allowed again ([`BillingCheck`]).
credits: bool,
+ /// Items the engine refused, skipped so the rest could go on.
+ failed: Vec<FailedItem>,
+}
+
+/// One legacy item the engine refused, kept with the reason so a user can
+/// see it and retry it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+struct FailedItem {
+ /// The item's legacy id (`memory_docs:<id>`, `episodic_log:<session>`, …).
+ id: String,
+ /// Why the engine refused it.
+ reason: String,
+}
+
+impl FailedItem {
+ fn new(item: &tinymemory_api::StoreItem, error: tinymemory_api::Error) -> Self {
+ Self {
+ id: legacy_id(item),
+ reason: MemoryError::from(error).to_string(),
+ }
+ }
+}
+
+/// The legacy id the importer gave `item` (its `source.id`).
+fn legacy_id(item: &tinymemory_api::StoreItem) -> String {
+ item.meta().source.id.clone().unwrap_or_default()
}
/// Runs `call` again after each of [`RETRY_DELAYS`] while it fails with a
@@ -178,9 +204,10 @@ async fn store_batch(bound: &BoundEngine, batch: Vec<ImportedItem>) -> BatchOutc
}
Err(error) => {
tracing::debug!(
- code = MemoryError::from(error).code(),
+ code = MemoryError::from(error.clone()).code(),
"[memory:import] item skipped"
);
+ outcome.failed.push(FailedItem::new(&imported.item, error));
}
}
outcome.checkpoint = Some(imported.checkpoint);
@@ -199,6 +226,9 @@ struct ImportFile {
/// background job resumes it once automatic runs are allowed.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
paused_for_credits: bool,
+ /// Items the engine refused, for `retry_failed`.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ failed: Vec<FailedItem>,
#[serde(default)]
checkpoint: Checkpoint,
}
@@ -465,6 +495,102 @@ async fn start_with(
Ok(state)
}
+/// `memory_import_retry_failed`: stores again the items a finished import
+/// skipped because the engine refused them. Items that now store leave the
+/// list; ones refused again stay, with the new reason.
+pub async fn retry_failed(config: &Config) -> MemoryResult<ImportState> {
+ let bound = engine::resolve(config).engine()?;
+ let workspace_dir = config.workspace_dir.clone();
+ let mut file = read_file(&workspace_dir);
+ if file.state.phase != ImportPhase::Done || file.failed.is_empty() {
+ return Err(MemoryError::invalid(
+ "no failed items to retry: the import has not finished or skipped nothing",
+ ));
+ }
+ let claimed = RUNNING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(workspace_dir.clone());
+ if !claimed {
+ return Ok(status(config));
+ }
+ file.state.phase = ImportPhase::Running;
+ file.state.error = None;
+ write_file(&workspace_dir, &file);
+ let state = file.state.clone();
+ tracing::info!(
+ failed = file.failed.len(),
+ "[memory:import] retrying failed items"
+ );
+ tokio::spawn(async move {
+ retry_run(&workspace_dir, &bound, file).await;
+ RUNNING
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(&workspace_dir);
+ });
+ Ok(state)
+}
+
+async fn retry_run(workspace_dir: &Path, bound: &BoundEngine, mut file: ImportFile) {
+ let wanted: HashSet<String> = file.failed.iter().map(|failed| failed.id.clone()).collect();
+ let reader_dir = workspace_dir.to_path_buf();
+ let items = tokio::task::spawn_blocking(move || {
+ let workspace = LegacyWorkspace::open(&reader_dir).map_err(|error| error.to_string())?;
+ workspace
+ .items()
+ .filter_map(|imported| match imported {
+ Ok(imported) if wanted.contains(&legacy_id(&imported.item)) => {
+ Some(Ok(imported.item))
+ }
+ Ok(_) => None,
+ Err(error) => Some(Err(error.to_string())),
+ })
+ .collect::<Result<Vec<_>, String>>()
+ })
+ .await
+ .map_err(|error| error.to_string())
+ .and_then(|items| items);
+ let mut failure = None;
+ match items {
+ Err(error) => failure = Some(format!("reading the legacy store failed: {error}")),
+ Ok(items) => {
+ for item in items {
+ let id = legacy_id(&item);
+ match with_retries(|| bound.engine.store(item.clone())).await {
+ Ok(_) => {
+ file.failed.retain(|failed| failed.id != id);
+ file.state.imported += 1;
+ }
+ Err(error) if skips_item(&error) => {
+ let again = FailedItem::new(&item, error);
+ if let Some(failed) = file.failed.iter_mut().find(|f| f.id == id) {
+ *failed = again;
+ }
+ }
+ Err(error) => {
+ failure = Some(fatal_message(error));
+ break;
+ }
+ }
+ }
+ }
+ }
+ file.state.failed = file.failed.len() as u64;
+ // The import itself is finished either way; a stopped retry says why.
+ file.state.phase = if failure.is_some() {
+ ImportPhase::Error
+ } else {
+ ImportPhase::Done
+ };
+ file.state.error = failure;
+ tracing::info!(
+ still_failed = file.failed.len(),
+ "[memory:import] retry of failed items finished"
+ );
+ write_file(workspace_dir, &file);
+}
+
async fn run(
workspace_dir: &Path,
bound: &BoundEngine,
@@ -519,6 +645,8 @@ async fn run(
}
let outcome = store_batch(bound, std::mem::take(&mut batch)).await;
file.state.imported += outcome.stored;
+ file.failed.extend(outcome.failed);
+ file.state.failed = file.failed.len() as u64;
if let Some(checkpoint) = outcome.checkpoint {
file.checkpoint = checkpoint;
}
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index f5aafc3e4a..78081b7e91 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -165,11 +165,13 @@ async fn an_interrupted_import_resumes_from_its_checkpoint() {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Error,
imported: 1,
total: 5,
error: Some("unauthorized: sign in".into()),
+ failed: 0,
},
checkpoint: Checkpoint {
documents: Some("d1".into()),
@@ -201,11 +203,13 @@ fn a_running_state_with_no_live_import_reads_as_interrupted() {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Running,
imported: 3,
total: 9,
error: None,
+ failed: 0,
},
checkpoint: Checkpoint::default(),
},
@@ -408,11 +412,13 @@ async fn an_import_the_app_quit_during_resumes_on_its_own() {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Running,
imported: 1,
total: 5,
error: None,
+ failed: 0,
},
checkpoint: Checkpoint {
documents: Some("d1".into()),
@@ -441,11 +447,13 @@ async fn a_stopped_or_finished_import_is_not_resumed_on_its_own() {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase,
imported: 0,
total: 5,
error: None,
+ failed: 0,
},
checkpoint: Checkpoint::default(),
},
@@ -462,11 +470,13 @@ fn quit_mid_import(config: &Config) {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Running,
imported: 1,
total: 5,
error: None,
+ failed: 0,
},
checkpoint: Checkpoint {
documents: Some("d1".into()),
@@ -614,11 +624,13 @@ async fn a_resumed_import_keeps_its_total_instead_of_rescanning() {
&config.workspace_dir,
&ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Error,
imported: 1,
total: 99,
error: Some("unavailable".into()),
+ failed: 0,
},
checkpoint: Checkpoint {
documents: Some("d1".into()),
@@ -641,11 +653,13 @@ fn the_import_state_is_written_whole_and_leaves_no_staging_file() {
let tmp = tempfile::tempdir().unwrap();
let file = ImportFile {
paused_for_credits: false,
+ failed: Vec::new(),
state: ImportState {
phase: ImportPhase::Running,
imported: 3,
total: 7,
error: None,
+ failed: 0,
},
checkpoint: Checkpoint {
documents: Some("d9".into()),
@@ -769,3 +783,74 @@ fn only_a_self_hosted_engine_runs_automatically_until_the_free_period_check_land
"unknown free period is not free"
);
}
+
+/// Whether a refusing engine still refuses the "Ideas" document.
+static REFUSE_IDEAS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
+
+fn refuse_ideas(item: &tinymemory_api::StoreItem) -> Option<tinymemory_api::Error> {
+ let ideas = matches!(item, tinymemory_api::StoreItem::Document { title: Some(title), .. } if title == "Ideas");
+ (ideas && REFUSE_IDEAS.load(std::sync::atomic::Ordering::SeqCst))
+ .then(|| tinymemory_api::Error::InvalidRequest("item too large".into()))
+}
+
+#[tokio::test]
+async fn a_refused_item_is_kept_and_a_retry_stores_it() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ REFUSE_IDEAS.store(true, std::sync::atomic::Ordering::SeqCst);
+ let engine = bind_failing(&config, refuse_ideas);
+
+ start(&config, true).await.unwrap();
+ let done = wait_until_settled(&config).await;
+ assert_eq!(
+ (done.phase, done.imported, done.failed),
+ (ImportPhase::Done, 4, 1)
+ );
+ let file = read_file(&config.workspace_dir);
+ assert_eq!(file.failed.len(), 1);
+ assert_eq!(file.failed[0].id, "memory_docs:d2");
+ assert!(
+ file.failed[0].reason.contains("item too large"),
+ "{:?}",
+ file.failed
+ );
+
+ // Still refused: kept, with the reason.
+ retry_failed(&config).await.unwrap();
+ let again = wait_until_settled(&config).await;
+ assert_eq!(
+ (again.phase, again.failed),
+ (ImportPhase::Done, 1),
+ "{again:?}"
+ );
+
+ // The engine takes it now: the list empties and the item is stored.
+ REFUSE_IDEAS.store(false, std::sync::atomic::Ordering::SeqCst);
+ retry_failed(&config).await.unwrap();
+ let fixed = wait_until_settled(&config).await;
+ assert_eq!(
+ (fixed.phase, fixed.imported, fixed.failed),
+ (ImportPhase::Done, 5, 0),
+ "{fixed:?}"
+ );
+ assert!(read_file(&config.workspace_dir).failed.is_empty());
+ let items = stored(&engine, MetaFilter::default()).await;
+ assert!(items.iter().any(|item| item.text.contains("oolong")));
+}
+
+#[tokio::test]
+async fn retrying_needs_a_finished_import_with_failed_items() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ bind_reference(&config);
+ let error = retry_failed(&config).await.unwrap_err();
+ assert_eq!(error.code(), INVALID_REQUEST);
+ start(&config, true).await.unwrap();
+ assert_eq!(wait_until_settled(&config).await.failed, 0);
+ assert_eq!(
+ retry_failed(&config).await.unwrap_err().code(),
+ INVALID_REQUEST
+ );
+}
diff --git a/crates/openhuman-core/src/memory/schemas.rs b/crates/openhuman-core/src/memory/schemas.rs
index fe25e6c330..6cce875394 100644
--- a/crates/openhuman-core/src/memory/schemas.rs
+++ b/crates/openhuman-core/src/memory/schemas.rs
@@ -56,6 +56,7 @@ fn handler_for(function: &str) -> crate::core::all::ControllerHandler {
"jobs_run" => handlers::jobs_run,
"import_scan" => handlers::import_scan,
"import_start" => handlers::import_start,
+ "import_retry_failed" => handlers::import_retry_failed,
_ => handlers::import_status,
}
}
diff --git a/crates/openhuman-core/src/memory/schemas/defs.rs b/crates/openhuman-core/src/memory/schemas/defs.rs
index ee5efeac4d..d5f7561e9e 100644
--- a/crates/openhuman-core/src/memory/schemas/defs.rs
+++ b/crates/openhuman-core/src/memory/schemas/defs.rs
@@ -4,7 +4,7 @@
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
/// Every function of the namespace, in spec order.
-pub const FUNCTIONS: [&str; 29] = [
+pub const FUNCTIONS: [&str; 30] = [
"engines_list",
"engine_get",
"engine_set",
@@ -34,6 +34,7 @@ pub const FUNCTIONS: [&str; 29] = [
"import_scan",
"import_start",
"import_status",
+ "import_retry_failed",
];
fn field(name: &'static str, ty: TypeSchema, comment: &'static str, required: bool) -> FieldSchema {
@@ -361,6 +362,13 @@ pub fn schema(function: &str) -> ControllerSchema {
inputs: vec![],
outputs: out("{state: ImportState}"),
},
+ "import_retry_failed" => ControllerSchema {
+ namespace: "memory",
+ function: "import_retry_failed",
+ description: "Store again the items a finished v1 import skipped because the engine refused them.",
+ inputs: vec![],
+ outputs: out("{state: ImportState}"),
+ },
_ => ControllerSchema {
namespace: "memory",
function: "unknown",
diff --git a/crates/openhuman-core/src/memory/schemas/handlers.rs b/crates/openhuman-core/src/memory/schemas/handlers.rs
index 7f1d4a0e63..b326ae52a6 100644
--- a/crates/openhuman-core/src/memory/schemas/handlers.rs
+++ b/crates/openhuman-core/src/memory/schemas/handlers.rs
@@ -283,3 +283,15 @@ pub(super) fn import_status(params: Map<String, Value>) -> ControllerFuture {
}))
})
}
+
+pub(super) fn import_retry_failed(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ parse::<EmptyParams>(params)?;
+ let config = load().await?;
+ finish(
+ import::retry_failed(&config)
+ .await
+ .map(|state| ImportStateView { state }),
+ )
+ })
+}
diff --git a/crates/openhuman-core/src/memory/schemas_tests.rs b/crates/openhuman-core/src/memory/schemas_tests.rs
index 7ebd3b282f..137c704796 100644
--- a/crates/openhuman-core/src/memory/schemas_tests.rs
+++ b/crates/openhuman-core/src/memory/schemas_tests.rs
@@ -6,7 +6,7 @@ use crate::memory::test_fixtures::{bind_reference, config_in};
use serde_json::{json, Map, Value};
/// Every method of the spec's RPC table (`docs/specs/memory-v2.md`), exactly.
-const SPEC_METHODS: [&str; 29] = [
+const SPEC_METHODS: [&str; 30] = [
"openhuman.memory_engines_list",
"openhuman.memory_engine_get",
"openhuman.memory_engine_set",
@@ -36,6 +36,7 @@ const SPEC_METHODS: [&str; 29] = [
"openhuman.memory_import_scan",
"openhuman.memory_import_start",
"openhuman.memory_import_status",
+ "openhuman.memory_import_retry_failed",
];
fn object(value: Value) -> Map<String, Value> {
@@ -121,6 +122,7 @@ fn required_inputs_match_the_spec() {
"sources_list",
"import_scan",
"import_status",
+ "import_retry_failed",
] {
assert!(schema(empty).inputs.is_empty(), "{empty} takes no params");
}
diff --git a/crates/openhuman-core/src/memory/types.rs b/crates/openhuman-core/src/memory/types.rs
index 7c8432c846..650bb62eeb 100644
--- a/crates/openhuman-core/src/memory/types.rs
+++ b/crates/openhuman-core/src/memory/types.rs
@@ -368,6 +368,10 @@ pub struct ImportState {
/// Why it stopped.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
+ /// Items the engine refused (malformed, too large), kept so they can be
+ /// retried (`memory_import_retry_failed`).
+ #[serde(default)]
+ pub failed: u64,
}
/// `memory_import_start` / `_status` result.
diff --git a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
index b5f264dd75..e95a3a8f2b 100644
--- a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
+++ b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs
@@ -369,7 +369,7 @@ Capability {
domain: "memory",
category: CapabilityCategory::Intelligence,
description: "Bring memory kept by an earlier OpenHuman version (documents, conversations and learnings) into the selected engine. The scan is local and read-only; the import uploads that data to the engine and only starts after explicit consent.",
- how_to: "Connections > Memory: the import banner appears when earlier memory is found. Programmatic: openhuman.memory_import_scan, memory_import_start (requires consent: true), memory_import_status (RPC).",
+ how_to: "Connections > Memory: the import banner appears when earlier memory is found. Programmatic: openhuman.memory_import_scan, memory_import_start (requires consent: true), memory_import_status, memory_import_retry_failed (RPC).",
status: CapabilityStatus::Beta,
privacy: MEMORY_TO_REMOTE_ENGINE,
},
diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.md
index 9dcee71516..61bbc7379a 100644
--- a/docs/specs/memory-v2.md
+++ b/docs/specs/memory-v2.md
@@ -233,6 +233,7 @@ memory.
| `memory_import_scan` | `{}` | `{found, counts?: {documents, conversations, learnings}}` |
| `memory_import_start` | `{consent: true}` | `{state: ImportState}` |
| `memory_import_status` | `{}` | `{state: ImportState}` |
+| `memory_import_retry_failed` | `{}` | `{state: ImportState}`; stores again the items a finished import skipped because the engine refused them (`ImportState.failed` counts them) |
`memory_context_*` and `memory_conversations_get/set` are retired.
diff --git a/tests/memory_v2_e2e.rs b/tests/memory_v2_e2e.rs
index cd9306f4f4..8e91c31f70 100644
--- a/tests/memory_v2_e2e.rs
+++ b/tests/memory_v2_e2e.rs
@@ -1776,6 +1776,7 @@ async fn memory_v2_registers_exactly_the_documented_methods() {
"import_scan",
"import_start",
"import_status",
+ "import_retry_failed",
]
.iter()
.map(|m| format!("openhuman.memory_{m}"))