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
chore: files changed crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents
Steven Enamakel89661bacdf45
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rsindex 73d0407c51..2a643e6bc0 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs@@ -112,26 +112,31 @@ impl Docs {sessions: &[DurableSubagentSession],) -> Result<()> {let id = marker_id(source);- let claimed = crate::storage::import_claim::with_claim(&self.0, IMPORTED, &id.clone(), || {- self.save(sessions)?;- self.0.run(|docs| async move {- match docs- .put(- IMPORTED,- &id,- serde_json::json!({ "imported": true }),- Precondition::Absent,- )- .await- {- Ok(_) => Ok(()),- Err(error) if error.kind() == tinystoragedrivers::ErrorKind::Conflict => Ok(()),- Err(error) => Err(error),- }- })- })?;+ let claimed =+ crate::storage::import_claim::with_claim(&self.0, IMPORTED, &id.clone(), || {+ self.save(sessions)?;+ self.0.run(|docs| async move {+ match docs+ .put(+ IMPORTED,+ &id,+ serde_json::json!({ "imported": true }),+ Precondition::Absent,+ )+ .await+ {+ Ok(_) => Ok(()),+ Err(error) if error.kind() == tinystoragedrivers::ErrorKind::Conflict => {+ Ok(())+ }+ Err(error) => Err(error),+ }+ })+ })?;if claimed.is_none() {- log::debug!("[subagent_sessions] another process is importing the legacy file; skipped");+ log::debug!(+ "[subagent_sessions] another process is importing the legacy file; skipped"+ );}Ok(())}diff --git a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs b/crates/openhuman-core/src/integrations/composio/file_store_documents.rsindex ed5c5b883b..a2af40bf4e 100644--- a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs+++ b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs@@ -141,30 +141,31 @@ impl Docs {let id = name.to_string();let doc = json!({ "value": value });log::debug!("[composio:store] document import id={id}");- let claimed = crate::storage::import_claim::with_claim(&self.0, IMPORTED, &id.clone(), || {- self.0.run(|docs| async move {- let wrote = match docs.put(STATE, &id, doc, Precondition::Absent).await {- Ok(_) => true,- Err(error) if error.kind() == ErrorKind::Conflict => false,- Err(error) => return Err(error),- };- match docs- .put(- IMPORTED,- &id,- json!({ "imported": true }),- Precondition::Absent,- )- .await- {- Ok(_) => {}- // Another core finished first.- Err(error) if error.kind() == ErrorKind::Conflict => {}- Err(error) => return Err(error),- }- Ok(wrote)- })- })?;+ let claimed =+ crate::storage::import_claim::with_claim(&self.0, IMPORTED, &id.clone(), || {+ self.0.run(|docs| async move {+ let wrote = match docs.put(STATE, &id, doc, Precondition::Absent).await {+ Ok(_) => true,+ Err(error) if error.kind() == ErrorKind::Conflict => false,+ Err(error) => return Err(error),+ };+ match docs+ .put(+ IMPORTED,+ &id,+ json!({ "imported": true }),+ Precondition::Absent,+ )+ .await+ {+ Ok(_) => {}+ // Another core finished first.+ Err(error) if error.kind() == ErrorKind::Conflict => {}+ Err(error) => return Err(error),+ }+ Ok(wrote)+ })+ })?;Ok(claimed.unwrap_or(false))}diff --git a/crates/openhuman-core/src/storage/import/mod.rs b/crates/openhuman-core/src/storage/import/mod.rsindex 4368be45d8..25708689d8 100644--- a/crates/openhuman-core/src/storage/import/mod.rs+++ b/crates/openhuman-core/src/storage/import/mod.rs@@ -295,81 +295,82 @@ fn import_one(return Ok(Outcome::NoSource);}- let claimed = super::import_claim::with_claim(&markers, MARKER_COLLECTION, &marker.clone(), || {- // Another process may have finished between our check and the claim.- let again = marker.clone();- let done = markers- .run(move |docs| async move { docs.get(MARKER_COLLECTION, &again).await })?- .is_some();- if done {- return Ok(Outcome::AlreadyDone);- }- let snapshot = Snapshot::of(&legacy, source.db)- .with_context(|| format!("[{domain}] copy the legacy file for reading"))?;- let scratch = Config {- workspace_dir: snapshot.workspace().to_path_buf(),- ..config.clone()- };+ let claimed =+ super::import_claim::with_claim(&markers, MARKER_COLLECTION, &marker.clone(), || {+ // Another process may have finished between our check and the claim.+ let again = marker.clone();+ let done = markers+ .run(move |docs| async move { docs.get(MARKER_COLLECTION, &again).await })?+ .is_some();+ if done {+ return Ok(Outcome::AlreadyDone);+ }+ let snapshot = Snapshot::of(&legacy, source.db)+ .with_context(|| format!("[{domain}] copy the legacy file for reading"))?;+ let scratch = Config {+ workspace_dir: snapshot.workspace().to_path_buf(),+ ..config.clone()+ };- // Driver document records first: they are the newer copy of a row whose- // legacy table was retired, so they win an id clash.- let mut found: Vec<Record> = snapshot- .driver_docs(source.collections)- .with_context(|| format!("[{domain}] read the document tables"))?- .into_iter()- .map(|doc| (source.rekey)(doc, config))- .collect();- found.extend(- (source.read_legacy)(&scratch, config)- .with_context(|| format!("[{domain}] read the legacy tables"))?- .into_iter()- .map(Record::from),- );+ // Driver document records first: they are the newer copy of a row whose+ // legacy table was retired, so they win an id clash.+ let mut found: Vec<Record> = snapshot+ .driver_docs(source.collections)+ .with_context(|| format!("[{domain}] read the document tables"))?+ .into_iter()+ .map(|doc| (source.rekey)(doc, config))+ .collect();+ found.extend(+ (source.read_legacy)(&scratch, config)+ .with_context(|| format!("[{domain}] read the legacy tables"))?+ .into_iter()+ .map(Record::from),+ );- let total = found.len();- let written = repo.run(move |docs| async move {- let mut written = 0usize;- for record in found {- match docs- .put(- &record.collection,- &record.id,- record.doc,- Precondition::Absent,- )- .await- {- Ok(_) => written += 1,- Err(error) if error.kind() == ErrorKind::Conflict => {}- Err(error) => return Err(error),- }- }- Ok(written)- })?;+ let total = found.len();+ let written = repo.run(move |docs| async move {+ let mut written = 0usize;+ for record in found {+ match docs+ .put(+ &record.collection,+ &record.id,+ record.doc,+ Precondition::Absent,+ )+ .await+ {+ Ok(_) => written += 1,+ Err(error) if error.kind() == ErrorKind::Conflict => {}+ Err(error) => return Err(error),+ }+ }+ Ok(written)+ })?;- let body = json!({- "version": MARKER_VERSION,- "domain": domain,- "found": total,- "written": written,- "at": chrono::Utc::now().to_rfc3339(),- });- markers.run(move |docs| async move {- match docs- .put(MARKER_COLLECTION, &marker, body, Precondition::Absent)- .await- {- Ok(_) => Ok(()),- // Another process finished first.- Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),- Err(error) => Err(error),- }- })?;- Ok(Outcome::Imported {- found: total,- written,- })- })?;+ let body = json!({+ "version": MARKER_VERSION,+ "domain": domain,+ "found": total,+ "written": written,+ "at": chrono::Utc::now().to_rfc3339(),+ });+ markers.run(move |docs| async move {+ match docs+ .put(MARKER_COLLECTION, &marker, body, Precondition::Absent)+ .await+ {+ Ok(_) => Ok(()),+ // Another process finished first.+ Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),+ Err(error) => Err(error),+ }+ })?;+ Ok(Outcome::Imported {+ found: total,+ written,+ })+ })?;Ok(claimed.unwrap_or(Outcome::InProgress))}diff --git a/crates/openhuman-core/src/storage/import/mod_tests.rs b/crates/openhuman-core/src/storage/import/mod_tests.rsindex bde1098f86..ac61944149 100644--- a/crates/openhuman-core/src/storage/import/mod_tests.rs+++ b/crates/openhuman-core/src/storage/import/mod_tests.rs@@ -152,6 +152,78 @@ fn a_finished_import_does_not_run_again_or_resurrect_deleted_records() {assert!(!dump(&backend, &source, "paired_devices").contains_key("chan-b"));}+#[test]+fn an_import_claimed_by_another_process_is_skipped_and_leaves_no_marker() {+ let (_dir, config) = workspace();+ legacy_device(&config, "chan-a", "Phone", false);+ let backend = backend();+ let source = devices();++ // Another process holds the claim for this domain and workspace.+ let markers = Repo::on(&backend, &Scope::local(), "storage::import", marker_spec).unwrap();+ let claim =+ crate::storage::import_claim::claim_id(&marker_id(source.domain, &config.workspace_dir));+ markers+ .run(move |docs| async move {+ docs.put(+ MARKER_COLLECTION,+ &claim,+ json!({ "claimed_at_ms": chrono::Utc::now().timestamp_millis() }),+ Precondition::Absent,+ )+ .await+ .map(|_| ())+ })+ .unwrap();++ assert_eq!(+ outcome(run_with(&backend, &config, &[source])),+ Outcome::InProgress+ );+ assert!(!is_done(&backend, &config, &source).unwrap());+ assert!(dump(&backend, &source, "paired_devices").is_empty());+}++#[test]+fn processes_importing_one_workspace_at_once_import_it_once() {+ let (_dir, config) = workspace();+ for n in 0..20 {+ legacy_device(&config, &format!("chan-{n}"), "Phone", false);+ }+ let backend = backend();+ let source = devices();+ let barrier = Arc::new(std::sync::Barrier::new(6));+ let handles: Vec<_> = (0..6)+ .map(|_| {+ let (backend, config, barrier) =+ (Arc::clone(&backend), config.clone(), Arc::clone(&barrier));+ std::thread::spawn(move || {+ barrier.wait();+ outcome(run_with(&backend, &config, &[source]))+ })+ })+ .collect();+ let outcomes: Vec<Outcome> = handles.into_iter().map(|h| h.join().unwrap()).collect();++ let imports = outcomes+ .iter()+ .filter(|o| matches!(o, Outcome::Imported { .. }))+ .count();+ assert_eq!(imports, 1, "exactly one process imports: {outcomes:?}");+ assert!(outcomes+ .iter()+ .all(|o| !matches!(o, Outcome::Imported { .. })+ || matches!(+ o,+ Outcome::Imported {+ found: 20,+ written: 20+ }+ )));+ assert!(is_done(&backend, &config, &source).unwrap());+ assert_eq!(dump(&backend, &source, "paired_devices").len(), 20);+}+#[test]fn an_existing_record_is_never_overwritten() {let (_dir, config) = workspace();diff --git a/crates/openhuman-core/src/storage/import/tinyflows.rs b/crates/openhuman-core/src/storage/import/tinyflows.rsindex 653f167d68..83cef4d68c 100644--- a/crates/openhuman-core/src/storage/import/tinyflows.rs+++ b/crates/openhuman-core/src/storage/import/tinyflows.rs@@ -67,46 +67,51 @@ pub(super) fn marked(if done {return Ok(Outcome::AlreadyDone);}- let claimed = super::super::import_claim::with_claim(&markers, MARKER_COLLECTION, &marker.clone(), || {- let again = marker.clone();- let done = markers- .run(move |docs| async move { docs.get(MARKER_COLLECTION, &again).await })?- .is_some();- if done {- return Ok(Outcome::AlreadyDone);- }- let Some((found, written, skipped)) = body()? else {- return Ok(Outcome::NoSource);- };- if skipped > 0 {- tracing::warn!(- target: "openhuman::storage_import",- domain,- skipped,- "[storage::import] legacy records were skipped; the import stays open for retry"- );- return Ok(Outcome::Imported { found, written });- }- let body = json!({- "version": MARKER_VERSION,- "domain": domain,- "found": found,- "written": written,- "at": chrono::Utc::now().to_rfc3339(),- });- markers.run(move |docs| async move {- match docs- .put(MARKER_COLLECTION, &marker, body, Precondition::Absent)- .await- {- Ok(_) => Ok(()),- // Another process finished first.- Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),- Err(error) => Err(error),- }- })?;- Ok(Outcome::Imported { found, written })- })?;+ let claimed = super::super::import_claim::with_claim(+ &markers,+ MARKER_COLLECTION,+ &marker.clone(),+ || {+ let again = marker.clone();+ let done = markers+ .run(move |docs| async move { docs.get(MARKER_COLLECTION, &again).await })?+ .is_some();+ if done {+ return Ok(Outcome::AlreadyDone);+ }+ let Some((found, written, skipped)) = body()? else {+ return Ok(Outcome::NoSource);+ };+ if skipped > 0 {+ tracing::warn!(+ target: "openhuman::storage_import",+ domain,+ skipped,+ "[storage::import] legacy records were skipped; the import stays open for retry"+ );+ return Ok(Outcome::Imported { found, written });+ }+ let body = json!({+ "version": MARKER_VERSION,+ "domain": domain,+ "found": found,+ "written": written,+ "at": chrono::Utc::now().to_rfc3339(),+ });+ markers.run(move |docs| async move {+ match docs+ .put(MARKER_COLLECTION, &marker, body, Precondition::Absent)+ .await+ {+ Ok(_) => Ok(()),+ // Another process finished first.+ Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),+ Err(error) => Err(error),+ }+ })?;+ Ok(Outcome::Imported { found, written })+ },+ )?;Ok(claimed.unwrap_or(Outcome::InProgress))}diff --git a/crates/openhuman-core/src/threads/store/legacy_import.rs b/crates/openhuman-core/src/threads/store/legacy_import.rsindex 317f0619d6..b047e39961 100644--- a/crates/openhuman-core/src/threads/store/legacy_import.rs+++ b/crates/openhuman-core/src/threads/store/legacy_import.rs@@ -166,42 +166,44 @@ pub(super) fn import_once(log::debug!("{LOG_PREFIX} already imported");return Ok(());}- let claimed = crate::storage::import_claim::with_claim(repo, MARKERS, &marker_id.clone(), || {- let marked = repo.run(|docs| {- let marker_id = marker_id.clone();- async move { docs.get(MARKERS, &marker_id).await }- })?;- if marked.is_some() {- return Ok(());- }- let threads = fold_threads(&root)?;- let mut messages = Vec::with_capacity(threads.len());- for thread in &threads {- messages.push(read_jsonl::<ThreadMessage>(&messages_path(- &root, &thread.id,- ))?);- }- let store = store.clone();- let (threads_n, messages_n) =- crate::storage::block_on_anyhow(async move { copy(&store, threads, messages).await })?;- repo.run(|docs| async move {- match docs- .put(- MARKERS,- &marker_id,- serde_json::json!({ "threads": threads_n, "messages": messages_n }),- Precondition::Absent,- )- .await- {- Ok(_) => Ok(()),- Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),- Err(error) => Err(error),+ let claimed =+ crate::storage::import_claim::with_claim(repo, MARKERS, &marker_id.clone(), || {+ let marked = repo.run(|docs| {+ let marker_id = marker_id.clone();+ async move { docs.get(MARKERS, &marker_id).await }+ })?;+ if marked.is_some() {+ return Ok(());}+ let threads = fold_threads(&root)?;+ let mut messages = Vec::with_capacity(threads.len());+ for thread in &threads {+ messages.push(read_jsonl::<ThreadMessage>(&messages_path(+ &root, &thread.id,+ ))?);+ }+ let store = store.clone();+ let (threads_n, messages_n) = crate::storage::block_on_anyhow(async move {+ copy(&store, threads, messages).await+ })?;+ repo.run(|docs| async move {+ match docs+ .put(+ MARKERS,+ &marker_id,+ serde_json::json!({ "threads": threads_n, "messages": messages_n }),+ Precondition::Absent,+ )+ .await+ {+ Ok(_) => Ok(()),+ Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),+ Err(error) => Err(error),+ }+ })?;+ log::info!("{LOG_PREFIX} imported threads={threads_n} messages={messages_n}");+ Ok(())})?;- log::info!("{LOG_PREFIX} imported threads={threads_n} messages={messages_n}");- Ok(())- })?;if claimed.is_none() {log::debug!("{LOG_PREFIX} another process is importing; skipped");}