The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(storage): handle empty claim ids during import
Steven Enamakel3ab6cd56efc1
diff --git a/crates/openhuman-core/src/storage/import_claim.rs b/crates/openhuman-core/src/storage/import_claim.rsindex 960e539d6e..ffd74ef529 100644--- a/crates/openhuman-core/src/storage/import_claim.rs+++ b/crates/openhuman-core/src/storage/import_claim.rs@@ -7,10 +7,12 @@//! prevent is both of them doing the whole read-and-copy at the same time.//! [`with_claim`] puts a claim document beside the marker (`<marker>#claim`)//! with `Precondition::Absent` before the import starts; the process that-//! loses the race skips the import (the winner writes the marker) instead of-//! repeating it. A claim is released when the import ends, success or failure,+//! loses the race waits, then re-checks the marker (the winner wrote it)+//! instead of repeating the import. A claim is released when the import ends, success or failure,//! and a claim older than [`CLAIM_TTL_MS`] (its owner crashed) is taken over//! with a version-checked write, so a dead process never blocks the import.+//! The owner renews the claim while it works; a process that finds a live+//! claim waits for it instead of proceeding.use anyhow::Result;use serde_json::json;@@ -28,9 +30,20 @@ pub fn claim_id(marker: &str) -> String {format!("{marker}#claim")}+/// How often a waiting process re-tries a claim another process holds.+const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(100);+/// Runs `body` while holding the claim for `marker` in `collection`, which-/// `repo` must declare. Returns `None` without running `body` when another-/// live process holds the claim.+/// `repo` must declare.+///+/// A live claim held by another process is waited out (up to [`CLAIM_TTL_MS`]),+/// so a caller never proceeds while the winner is still copying; once the+/// claim is free `body` runs, and it must re-check its completion marker+/// because the winner has usually finished the work by then. Returns `None`+/// only when the claim stays held for the whole wait.+///+/// The claim is renewed while `body` runs, so a long import is not mistaken+/// for a crashed one.////// # Errors///@@ -40,19 +53,24 @@ pub fn with_claim<T>(repo: &Repo,collection: &'static str,marker: &str,- body: impl FnOnce() -> Result<T>,+ mut body: impl FnMut() -> Result<T>,) -> Result<Option<T>> {- with_claim_at(- repo,- collection,- marker,- chrono::Utc::now().timestamp_millis(),- CLAIM_TTL_MS,- body,- )+ let started = std::time::Instant::now();+ loop {+ let now = chrono::Utc::now().timestamp_millis();+ if let Some(ran) = with_claim_at(repo, collection, marker, now, CLAIM_TTL_MS, &mut body)? {+ return Ok(Some(ran));+ }+ if started.elapsed().as_millis() as i64 >= CLAIM_TTL_MS {+ return Ok(None);+ }+ std::thread::sleep(WAIT_POLL);+ }}-/// [`with_claim`] with an explicit clock and lease length, for tests.+/// One attempt of [`with_claim`] with an explicit clock and lease length, for+/// tests: returns `None` without running `body` or waiting when another live+/// process holds the claim.pub fn with_claim_at<T>(repo: &Repo,collection: &'static str,@@ -66,11 +84,50 @@ pub fn with_claim_at<T>(tracing::debug!(target: "openhuman::storage_import",claim = %id,- "{LOG_PREFIX} another process holds the import claim; skipping"+ "{LOG_PREFIX} another process holds the import claim");return Ok(None);};+ let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();+ let heartbeat = {+ let (repo, id) = (repo.clone(), id.clone());+ let interval = std::time::Duration::from_millis((ttl_ms / 3).max(1) as u64);+ std::thread::spawn(move || {+ let started = std::time::Instant::now();+ let mut version = held;+ while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =+ stop_rx.recv_timeout(interval)+ {+ let at = now_ms.saturating_add(started.elapsed().as_millis() as i64);+ let renew_id = id.clone();+ let renewed = repo.run(move |docs| async move {+ docs.put(+ collection,+ &renew_id,+ json!({ "claimed_at_ms": at, "pid": std::process::id() }),+ Precondition::Version(version),+ )+ .await+ });+ match renewed {+ Ok(next) => version = next,+ Err(error) => {+ tracing::warn!(+ target: "openhuman::storage_import",+ claim = %id,+ error = %format!("{error:#}"),+ "{LOG_PREFIX} could not renew the import claim"+ );+ break;+ }+ }+ }+ version+ })+ };let result = body();+ let _ = stop_tx.send(());+ let held = heartbeat.join().unwrap_or(held);let release_id = id.clone();let released = repo.run(move |docs| async move {docs.delete(collection, &release_id, Precondition::Version(held))