Skip to content

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

fix(core): make legacy document imports and deletes crash-safe

Steven Enamakele90ae8678745
diff --git a/crates/openhuman-core/src/agent/artifacts/store_documents.rs b/crates/openhuman-core/src/agent/artifacts/store_documents.rs
index fe7a80fbb5..eff5960b63 100644
--- a/crates/openhuman-core/src/agent/artifacts/store_documents.rs
+++ b/crates/openhuman-core/src/agent/artifacts/store_documents.rs
@@ -181,7 +181,8 @@ impl Docs {
/// Imports the workspace's legacy `meta.json` / `args.json` files and
/// returns how many records it created. Only absent records are written,
- /// so a repeat is harmless. A missing folder or a folder without
+ /// so a repeat is harmless, and an interrupted import (meta in, args not)
+ /// is completed by the next one. A missing folder or a folder without
/// `meta.json` is nothing to import and a corrupt `meta.json` is skipped,
/// but any other read error fails the import, so it is retried rather than
/// recorded as done.
@@ -211,6 +212,16 @@ impl Docs {
);
continue;
};
+ // The file store keeps each record in `artifacts/<id>/`; a copy
+ // under another name is not the record, so the id is unique and
+ // the winner does not depend on directory order.
+ if dir.file_name().and_then(|name| name.to_str()) != Some(meta.id.as_str()) {
+ log::warn!(
+ "[artifacts] legacy import: skipping meta.json whose id does not match its folder {}",
+ dir.display()
+ );
+ continue;
+ }
if self.put_meta_if_absent(&meta)? {
imported += 1;
}
@@ -278,12 +289,13 @@ pub(super) async fn documents(workspace_dir: &Path) -> Result<Option<Docs>, Stri
Ok(Some(docs))
}
-/// Deletes artifact `id` in document mode: the record and its arguments,
-/// then its legacy directory (`artifact_dir`) so a later import does not bring
-/// it back. Not found when there was no record, as the file store reports.
+/// Deletes artifact `id` in document mode. The legacy directory
+/// (`artifact_dir`) goes first: it is what a later import would bring back,
+/// so if anything after it fails (or the process dies) the artifact is still
+/// listed and a retry finishes the job, rather than a gone record coming back
+/// from a leftover `meta.json`. Not found when there was no record, as the
+/// file store reports.
pub(super) async fn delete_record(docs: Docs, artifact_dir: &Path, id: &str) -> Result<(), String> {
- let owned = id.to_string();
- let existed = on_docs(docs, move |docs| docs.delete(&owned)).await?;
match tokio::fs::remove_dir_all(artifact_dir).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
@@ -293,6 +305,8 @@ pub(super) async fn delete_record(docs: Docs, artifact_dir: &Path, id: &str) ->
))
}
}
+ let owned = id.to_string();
+ let existed = on_docs(docs, move |docs| docs.delete(&owned)).await?;
if !existed {
return Err(format!(
"[artifacts] failed to delete artifact id={id}: not found"
diff --git a/crates/openhuman-core/src/platform/cost/tracker_documents.rs b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
index a099c5631b..e28c850263 100644
--- a/crates/openhuman-core/src/platform/cost/tracker_documents.rs
+++ b/crates/openhuman-core/src/platform/cost/tracker_documents.rs
@@ -91,13 +91,24 @@ impl CostDocs {
/// the import is not recorded as done, so the next call retries it (and
/// creates nothing twice).
pub(super) fn import_legacy(&self, path: &std::path::Path) -> Result<usize> {
- if !path.exists() {
- return Ok(0);
- }
- let raw = std::fs::read_to_string(path)
- .with_context(|| format!("read legacy cost ledger {}", path.display()))?;
+ let raw = match std::fs::read(path) {
+ Ok(raw) => raw,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(error) => {
+ return Err(error)
+ .with_context(|| format!("read legacy cost ledger {}", path.display()))
+ }
+ };
let mut imported = 0;
- for line in raw.lines().map(str::trim).filter(|line| !line.is_empty()) {
+ for line in raw.split(|byte| *byte == b'\n') {
+ let Ok(line) = std::str::from_utf8(line) else {
+ log::warn!("[cost::tracker] legacy import: skipping a line that is not UTF-8");
+ continue;
+ };
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
match serde_json::from_str::<CostRecord>(line) {
Ok(record) => {
if self.add_if_absent(&record)? {
@@ -107,14 +118,7 @@ impl CostDocs {
Err(error) => log::warn!("[cost::tracker] legacy import: skipping line: {error}"),
}
}
- let migrated = path.with_extension("jsonl.migrated");
- std::fs::rename(path, &migrated).with_context(|| {
- format!(
- "set aside legacy cost ledger {} as {}",
- path.display(),
- migrated.display()
- )
- })?;
+ set_aside(path)?;
log::debug!("[cost::tracker] legacy import: imported={imported}");
Ok(imported)
}
@@ -167,6 +171,34 @@ impl CostDocs {
}
}
+/// Renames the imported ledger to `costs.jsonl.migrated`, or the first free
+/// `costs.jsonl.migrated.<n>` so an earlier set-aside file is never replaced.
+/// A ledger already gone was set aside by another core importing at the same
+/// time, which is success.
+fn set_aside(path: &std::path::Path) -> Result<()> {
+ let base = path.with_extension("jsonl.migrated");
+ let mut target = base.clone();
+ let mut n = 0;
+ while target.exists() {
+ n += 1;
+ target = std::path::PathBuf::from(format!("{}.{n}", base.display()));
+ }
+ match std::fs::rename(path, &target) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound && !path.exists() => {
+ log::debug!("[cost::tracker] legacy import: ledger already set aside");
+ Ok(())
+ }
+ Err(error) => Err(error).with_context(|| {
+ format!(
+ "set aside legacy cost ledger {} as {}",
+ path.display(),
+ target.display()
+ )
+ }),
+ }
+}
+
#[cfg(test)]
#[path = "tracker_documents_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/storage/documents.rs b/crates/openhuman-core/src/storage/documents.rs
index ada3cab29c..0c9c84598b 100644
--- a/crates/openhuman-core/src/storage/documents.rs
+++ b/crates/openhuman-core/src/storage/documents.rs
@@ -160,11 +160,7 @@ impl Repo {
f()?;
done.retain(|_, weak| weak.strong_count() > 0);
done.insert(once_key, Arc::downgrade(&origin.backend));
- log::debug!(
- "[storage] {} one-time work done scope={} key={key}",
- self.domain,
- origin.scope
- );
+ log::debug!("[storage] {} one-time work done", self.domain);
Ok(())
}