Skip to content

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

Write import state atomically and keep a resumed import's total

M3gA-Mind2169ffa9d8d3
diff --git a/crates/openhuman-core/src/memory/backfill.rs b/crates/openhuman-core/src/memory/backfill.rs
index 851dd78b3e..e1f348306c 100644
--- a/crates/openhuman-core/src/memory/backfill.rs
+++ b/crates/openhuman-core/src/memory/backfill.rs
@@ -117,14 +117,14 @@ fn read_file(workspace_dir: &Path) -> BackfillFile {
.unwrap_or_default()
}
+/// 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 path = file_path(workspace_dir);
- let result = path
- .parent()
- .map_or(Ok(()), std::fs::create_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(file).map_err(std::io::Error::other)?;
- std::fs::write(&path, json)
+ let result = serde_json::to_vec_pretty(file)
+ .map_err(|error| error.to_string())
+ .and_then(|json| {
+ crate::security::keyring::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");
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index 8ca67607e3..64ea87cbbf 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -152,14 +152,15 @@ fn read_file(workspace_dir: &Path) -> ImportFile {
.unwrap_or_default()
}
+/// Persists `file` atomically (staged, synced, renamed): a crash mid-write
+/// leaves the previous state, never a torn file that reads back as a fresh
+/// start and re-sends everything.
fn write_file(workspace_dir: &Path, file: &ImportFile) {
- let path = file_path(workspace_dir);
- let result = path
- .parent()
- .map_or(Ok(()), std::fs::create_dir_all)
- .and_then(|()| {
- let json = serde_json::to_vec_pretty(file).map_err(std::io::Error::other)?;
- std::fs::write(&path, json)
+ let result = serde_json::to_vec_pretty(file)
+ .map_err(|error| error.to_string())
+ .and_then(|json| {
+ crate::security::keyring::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:import] writing import state failed");
@@ -324,24 +325,37 @@ async fn start_with(
if !claimed {
return Ok(status(config));
}
+ let mut file = read_file(&workspace_dir);
+ if file.state.phase == ImportPhase::Done {
+ file = ImportFile::default();
+ }
+ // A resumed import already knows its total: only check the store is
+ // still there, instead of reading all of it again before the run reads
+ // it once more.
+ let resuming = !file.checkpoint.is_start() && file.state.total > 0;
let scan_dir = workspace_dir.clone();
- let counts = tokio::task::spawn_blocking(move || count_legacy(&scan_dir))
- .await
- .ok()
- .flatten();
- let Some(counts) = counts else {
+ let total = tokio::task::spawn_blocking(move || {
+ if resuming {
+ LegacyWorkspace::open(&scan_dir).ok().map(|_| None)
+ } else {
+ count_legacy(&scan_dir)
+ .map(|counts| Some(counts.documents + counts.conversations + counts.learnings))
+ }
+ })
+ .await
+ .ok()
+ .flatten();
+ let Some(total) = total else {
RUNNING
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(&workspace_dir);
return Err(MemoryError::invalid("no v1 memory store to import"));
};
- let mut file = read_file(&workspace_dir);
- if file.state.phase == ImportPhase::Done {
- file = ImportFile::default();
- }
file.state.phase = ImportPhase::Running;
- file.state.total = counts.documents + counts.conversations + counts.learnings;
+ if let Some(total) = total {
+ file.state.total = total;
+ }
file.state.error = None;
write_file(&workspace_dir, &file);
let state = file.state.clone();
diff --git a/crates/openhuman-core/src/memory/import_tests.rs b/crates/openhuman-core/src/memory/import_tests.rs
index a575536708..2e137fdff8 100644
--- a/crates/openhuman-core/src/memory/import_tests.rs
+++ b/crates/openhuman-core/src/memory/import_tests.rs
@@ -593,3 +593,61 @@ async fn an_automatic_resume_that_cannot_start_is_stopped_not_retried() {
"d1 is not re-sent"
);
}
+
+#[tokio::test]
+async fn a_resumed_import_keeps_its_total_instead_of_rescanning() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ legacy_workspace(&config.workspace_dir);
+ bind_reference(&config);
+ // A total no scan of this store would produce: a resume must keep it.
+ write_file(
+ &config.workspace_dir,
+ &ImportFile {
+ state: ImportState {
+ phase: ImportPhase::Error,
+ imported: 1,
+ total: 99,
+ error: Some("unavailable".into()),
+ },
+ checkpoint: Checkpoint {
+ documents: Some("d1".into()),
+ ..Checkpoint::default()
+ },
+ },
+ );
+ let started = start(&config, true).await.unwrap();
+ assert_eq!(started.total, 99);
+ let done = wait_until_settled(&config).await;
+ assert_eq!(
+ (done.phase, done.total),
+ (ImportPhase::Done, 99),
+ "{done:?}"
+ );
+}
+
+#[test]
+fn the_import_state_is_written_whole_and_leaves_no_staging_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let file = ImportFile {
+ state: ImportState {
+ phase: ImportPhase::Running,
+ imported: 3,
+ total: 7,
+ error: None,
+ },
+ checkpoint: Checkpoint {
+ documents: Some("d9".into()),
+ ..Checkpoint::default()
+ },
+ };
+ write_file(tmp.path(), &file);
+ write_file(tmp.path(), &file);
+ let read = read_file(tmp.path());
+ assert_eq!((read.state, read.checkpoint), (file.state, file.checkpoint));
+ let names: Vec<String> = std::fs::read_dir(tmp.path().join("memory"))
+ .unwrap()
+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, ["import_state.json"]);
+}