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: harden concurrent store lifecycle
Steven Enamakel0bd3c8a97662
diff --git a/src/embed/harness/mod.rs b/src/embed/harness/mod.rsindex f7c8f4ae6f..c63f29e962 100644--- a/src/embed/harness/mod.rs+++ b/src/embed/harness/mod.rs@@ -190,12 +190,14 @@ impl Drop for Harness {// `keep()` hands back the path without removing the directory so// we can do the retried removal ourselves.let root = temp.keep();+ // Keep clearing through the whole bounded settling window. A+ // successful first removal is not sufficient: a detached session+ // writer can recreate the directory immediately afterward.for _ in 0..20 {- if std::fs::remove_dir_all(&root).is_ok() {- break;- }+ let _ = std::fs::remove_dir_all(&root);std::thread::sleep(std::time::Duration::from_millis(50));}+ let _ = std::fs::remove_dir_all(&root);}log::debug!("[embed][harness] released");}diff --git a/src/openhuman/inference/provider/factory_part_03.rs b/src/openhuman/inference/provider/factory_part_03.rsindex 3f1cc786af..74a5a28caa 100644--- a/src/openhuman/inference/provider/factory_part_03.rs+++ b/src/openhuman/inference/provider/factory_part_03.rs@@ -529,6 +529,13 @@ pub(crate) fn verify_session_active(config: &Config) -> anyhow::Result<()> {return Ok(());}+ verify_backend_session_active(config)+}++/// Managed `OpenhumanJwt` inference always needs the backend bearer, including+/// in a Library host. Library mode exempts caller-owned provider credentials;+/// it cannot manufacture a TinyHumans account credential.+pub(crate) fn verify_backend_session_active(config: &Config) -> anyhow::Result<()> {// Fast path: the scheduler gate already knows the session is dead.if crate::openhuman::cron::scheduler_gate::is_signed_out() {anyhow::bail!(diff --git a/src/openhuman/inference/provider/factory_part_04.rs b/src/openhuman/inference/provider/factory_part_04.rsindex fce5b3b690..fac969c7af 100644--- a/src/openhuman/inference/provider/factory_part_04.rs+++ b/src/openhuman/inference/provider/factory_part_04.rs@@ -393,6 +393,10 @@ fn try_create_cloud_slug_chat_model_from_string_with_native_tools(AuthStyle::Anthropic => CompatAuthStyle::Anthropic,AuthStyle::None => CompatAuthStyle::None,AuthStyle::OpenhumanJwt => {+ #[cfg(not(test))]+ if let Err(error) = verify_backend_session_active(config) {+ return Some(Err(error));+ }let model_override =(!effective_model.trim().is_empty()).then_some(effective_model.as_str());let (backend, pinned_model) =diff --git a/src/openhuman/memory/conversations/store/store.rs b/src/openhuman/memory/conversations/store/store.rsindex c8ddb2dc89..ec394cb723 100644--- a/src/openhuman/memory/conversations/store/store.rs+++ b/src/openhuman/memory/conversations/store/store.rs@@ -113,7 +113,7 @@ pub struct ConversationPurgeStats {/// Workspace-rooted handle that reads and writes the JSONL conversation log.#[derive(Debug, Clone)]pub struct ConversationStore {- workspace_dir: PathBuf,+ root_dir: PathBuf,locks: std::sync::Arc<locks::StoreLocks>,}@@ -125,10 +125,10 @@ impl ConversationStore {/// `root_dir` in `store_index.rs`), so the caller's workspace is the whole/// input and there is nothing for a config type to add.pub fn new(workspace_dir: PathBuf) -> Self {- let root = workspace_dir.join("memory").join("conversations");+ let root = locks::normalized_root(&workspace_dir.join("memory").join("conversations"));let locks = locks::for_root(&root);Self {- workspace_dir,+ root_dir: root,locks,}}@@ -142,6 +142,11 @@ impl ConversationStore {pub(super) fn thread_lock_identity_for_test(&self, thread_id: &str) -> usize {std::sync::Arc::as_ptr(&self.locks.thread(thread_id)) as usize}++ #[cfg(test)]+ pub(super) fn thread_lock_count_for_test(&self) -> usize {+ self.locks.thread_count()+ }}/// One line in `threads.jsonl`. The append-only log is folded into the currentdiff --git a/src/openhuman/memory/conversations/store/store_index.rs b/src/openhuman/memory/conversations/store/store_index.rsindex 91e863b912..c0163359a7 100644--- a/src/openhuman/memory/conversations/store/store_index.rs+++ b/src/openhuman/memory/conversations/store/store_index.rs@@ -27,57 +27,81 @@ impl ConversationStore {/// After this call returns, `with_index` will always find a warm entry and/// will not re-enter `populate_index_unlocked`.pub(super) fn prime_index_if_cold(&self) -> Result<(), String> {+ self.prime_index_if_cold_with_hook(|| {})+ }++ /// `after_scan` is a deterministic test seam for mutations that land+ /// after file reads but before publication. Production always passes a+ /// no-op closure through [`Self::prime_index_if_cold`].+ pub(super) fn prime_index_if_cold_with_hook(+ &self,+ mut after_scan: impl FnMut(),+ ) -> Result<(), String> {let key = self.root_dir();- // Fast path: already warm — one tiny lock acquisition and out.- if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {- return Ok(());- }- // Snapshot live thread IDs while holding the metadata lock.- // `thread_index_unlocked` reads only `threads.jsonl` (header-only,- // O(threads), no per-thread file I/O) — metadata is released- // immediately after, so the slow content reads below never block- // concurrent writers.- //- // Do NOT call `list_threads_unlocked` here. For workspaces where any- // thread has no `MessageAppended`/`Stats` history (common before the- // Stats log was introduced), `list_threads_unlocked` triggers- // `measure_messages_unlocked` + a `Stats` append per thread — all under- // the metadata lock — reintroducing the multi-second stall this- // function is designed to avoid.- let thread_ids: Vec<String> = {- let _metadata = self.locks.metadata.lock();- // Re-check after acquiring: a concurrent prime may have just- // finished while we waited for metadata.+ let mut hook_pending = true;+ loop {+ // Fast path: already warm — one tiny lock acquisition and out.if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {return Ok(());}- self.thread_index_unlocked()?.into_keys().collect()- };- // Build the index with no shared metadata lock held. Each JSONL file is- // read under its own thread lock. A message- // appended during this window stays absent from the in-memory index- // until the next cold rebuild — the accepted tradeoff for issue #2849.- let mut idx = InvertedIndex::new();- for thread_id in &thread_ids {- let thread_lock = self.locks.thread(thread_id);- let _thread = thread_lock.lock();- let path = self.thread_messages_path(thread_id);- if !path.exists() {- continue;- }- if let Ok(messages) = read_jsonl::<ConversationMessage>(&path) {- for msg in messages {- idx.insert(thread_id, msg);+ // Snapshot live thread IDs and the deletion generation while+ // holding the metadata lock.+ // `thread_index_unlocked` reads only `threads.jsonl` (header-only,+ // O(threads), no per-thread file I/O) — metadata is released+ // immediately after, so the slow content reads below never block+ // concurrent writers.+ //+ // Do NOT call `list_threads_unlocked` here. For workspaces where any+ // thread has no `MessageAppended`/`Stats` history (common before the+ // Stats log was introduced), `list_threads_unlocked` triggers+ // `measure_messages_unlocked` + a `Stats` append per thread — all under+ // the metadata lock — reintroducing the multi-second stall this+ // function is designed to avoid.+ let (thread_ids, deletion_generation): (Vec<String>, u64) = {+ let _metadata = self.locks.metadata.lock();+ // Re-check after acquiring: a concurrent prime may have just+ // finished while we waited for metadata.+ if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {+ return Ok(());+ }+ (+ self.thread_index_unlocked()?.into_keys().collect(),+ self.locks.deletion_generation(),+ )+ };+ // Build the index with no shared metadata lock held. Each JSONL file is+ // read under its own thread lock. A message+ // appended during this window stays absent from the in-memory index+ // until the next cold rebuild — the accepted tradeoff for issue #2849.+ let mut idx = InvertedIndex::new();+ for thread_id in &thread_ids {+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ let path = self.thread_messages_path(thread_id);+ if !path.exists() {+ continue;+ }+ if let Ok(messages) = read_jsonl::<ConversationMessage>(&path) {+ for msg in messages {+ idx.insert(thread_id, msg);+ }}}- }- // Insert only if the key is still absent — a concurrent prime that- // finished first wins; ours is discarded.- {+ if hook_pending {+ hook_pending = false;+ after_scan();+ }+ // Hold metadata across generation validation and publication. A+ // delete either wins first and forces a rebuild, or runs after+ // publication and removes its documents from the warm index.+ let _metadata = self.locks.metadata.lock();+ if self.locks.deletion_generation() != deletion_generation {+ continue;+ }let mut cache = CONVERSATION_INDEX_CACHE.lock();- cache.entry(key).or_insert(idx);+ cache.entry(key.clone()).or_insert(idx);+ return Ok(());}- Ok(())}/// Acquire the cached inverted index for this workspace and run `f` against@@ -112,7 +136,7 @@ impl ConversationStore {/// Absolute path to this workspace's `memory/conversations` root.pub(super) fn root_dir(&self) -> PathBuf {- self.workspace_dir.join("memory").join("conversations")+ self.root_dir.clone()}/// Absolute path to a thread's per-thread messages JSONL file. The threaddiff --git a/src/openhuman/memory/conversations/store/store_locks.rs b/src/openhuman/memory/conversations/store/store_locks.rsindex 9222107d68..a7965dd640 100644--- a/src/openhuman/memory/conversations/store/store_locks.rs+++ b/src/openhuman/memory/conversations/store/store_locks.rs@@ -7,6 +7,7 @@use std::collections::HashMap;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, LazyLock, Weak};use parking_lot::{Mutex, RwLock};@@ -18,6 +19,7 @@ pub(super) struct StoreLocks {/// Serializes reads and appends of the root's shared `threads.jsonl`.pub(super) metadata: Mutex<()>,threads: Mutex<HashMap<String, Arc<Mutex<()>>>>,+ deletion_generation: AtomicU64,}impl StoreLocks {@@ -29,6 +31,29 @@ impl StoreLocks {.or_insert_with(|| Arc::new(Mutex::new(()))),)}++ pub(super) fn deletion_generation(&self) -> u64 {+ self.deletion_generation.load(Ordering::Acquire)+ }++ pub(super) fn record_deletion(&self) {+ self.deletion_generation.fetch_add(1, Ordering::AcqRel);+ }++ /// Call only while holding the lifecycle write guard.+ pub(super) fn remove_thread(&self, thread_id: &str) {+ self.threads.lock().remove(thread_id);+ }++ /// Call only while holding the lifecycle write guard.+ pub(super) fn clear_threads(&self) {+ self.threads.lock().clear();+ }++ #[cfg(test)]+ pub(super) fn thread_count(&self) -> usize {+ self.threads.lock().len()+ }}/// Separate `ConversationStore::new` calls for the same root must coordinate.@@ -38,7 +63,7 @@ static ROOTS: LazyLock<Mutex<HashMap<PathBuf, Weak<StoreLocks>>>> =LazyLock::new(|| Mutex::new(HashMap::new()));pub(super) fn for_root(root: &Path) -> Arc<StoreLocks> {- let root = stable_root_key(root);+ let root = normalized_root(root);let mut roots = ROOTS.lock();if let Some(existing) = roots.get(&root).and_then(Weak::upgrade) {return existing;@@ -51,7 +76,7 @@ pub(super) fn for_root(root: &Path) -> Arc<StoreLocks> {/// Resolve aliases even before the conversation directory itself exists./// Canonicalizing the nearest existing ancestor handles symlinks and `..`;/// the missing suffix is then appended without touching the filesystem.-fn stable_root_key(root: &Path) -> PathBuf {+pub(super) fn normalized_root(root: &Path) -> PathBuf {if let Ok(canonical) = root.canonicalize() {return canonical;}diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rsindex 306460fe7b..e086571415 100644--- a/src/openhuman/memory/conversations/store/store_ops.rs+++ b/src/openhuman/memory/conversations/store/store_ops.rs@@ -286,12 +286,16 @@ impl ConversationStore {/// Append a `Delete` entry and remove the thread's messages file. Returns/// `false` if the thread did not exist.pub fn delete_thread(&self, thread_id: &str, deleted_at: &str) -> Result<bool, String> {- let _lifecycle = self.locks.lifecycle.read();+ // Deletion also evicts the thread's lock entry. Exclusive lifecycle+ // ownership prevents a new operation from retaining the old lock+ // while the registry entry is replaced.+ let _lifecycle = self.locks.lifecycle.write();let thread_lock = self.locks.thread(thread_id);let _thread = thread_lock.lock();{let _metadata = self.locks.metadata.lock();if !self.thread_exists_unlocked(thread_id)? {+ self.locks.remove_thread(thread_id);return Ok(false);}let root = self.ensure_root()?;@@ -303,6 +307,7 @@ impl ConversationStore {deleted_at: deleted_at.to_string(),},)?;+ self.locks.record_deletion();}let messages_path = self.thread_messages_path(thread_id);match fs::remove_file(&messages_path) {@@ -323,6 +328,7 @@ impl ConversationStore {idx.remove_thread(thread_id);}}+ self.locks.remove_thread(thread_id);Ok(true)}@@ -343,6 +349,8 @@ impl ConversationStore {let mut cache = CONVERSATION_INDEX_CACHE.lock();cache.remove(&root);}+ self.locks.record_deletion();+ self.locks.clear_threads();Ok(stats)}}diff --git a/src/openhuman/memory/conversations/store/store_tests_late.rs b/src/openhuman/memory/conversations/store/store_tests_late.rsindex a86f706f61..53adff3d26 100644--- a/src/openhuman/memory/conversations/store/store_tests_late.rs+++ b/src/openhuman/memory/conversations/store/store_tests_late.rs@@ -205,6 +205,7 @@ fn equivalent_workspace_paths_share_the_same_lock_registry_entry() {direct.lock_identity_for_test(),dotted.lock_identity_for_test());+ assert_eq!(direct.root_dir(), dotted.root_dir());}#[cfg(unix)]@@ -223,6 +224,7 @@ fn symlinked_workspace_paths_share_the_same_lock_registry_entry() {direct.lock_identity_for_test(),linked.lock_identity_for_test());+ assert_eq!(direct.root_dir(), linked.root_dir());}// ── concurrency: search cold rebuild must not block concurrent append ────────@@ -242,7 +244,7 @@ fn symlinked_workspace_paths_share_the_same_lock_registry_entry() {/// serialized through one shared lock.#[test]fn search_cold_rebuild_does_not_block_concurrent_append() {- use std::sync::{mpsc, Arc, Barrier};+ use std::sync::mpsc;use std::thread;use std::time::Duration;@@ -264,6 +266,16 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {personality_id: None,}).unwrap();+ store+ .ensure_thread(CreateConversationThread {+ parent_thread_id: None,+ id: "t2".to_string(),+ title: "Concurrent append target".to_string(),+ created_at: ts.clone(),+ labels: None,+ personality_id: None,+ })+ .unwrap();// Seed enough messages to give the rebuild real work.for i in 0..200_usize {@@ -285,21 +297,24 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {let store_search = store.clone();let store_append = store.clone();- // Both threads start at the same time.- let barrier = Arc::new(Barrier::new(2));- let b_search = Arc::clone(&barrier);- let b_append = Arc::clone(&barrier);-+ let (scanned_tx, scanned_rx) = mpsc::channel();+ let (release_tx, release_rx) = mpsc::channel();let search_handle = thread::spawn(move || {- b_search.wait();- store_search.search_cross_thread_messages("seed message", 5, None)+ let _lifecycle = store_search.locks.lifecycle.read();+ store_search.prime_index_if_cold_with_hook(|| {+ scanned_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ })?;+ store_search.with_index(|idx| idx.search("seed message", 5, None))});+ scanned_rx+ .recv_timeout(Duration::from_secs(5))+ .expect("cold rebuild did not reach the post-scan test seam");let (tx, rx) = mpsc::channel();thread::spawn(move || {- b_append.wait();let result = store_append.append_message(- "t1",+ "t2",ConversationMessage {id: "concurrent-append".to_string(),content: "written during cold rebuild".to_string(),@@ -312,18 +327,18 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {let _ = tx.send(result);});- // append_message must complete even if the rebuild is in progress. On the- // old code this blocked for the full rebuild duration; on fixed code the- // two operations proceed concurrently. The 30 s budget tolerates a slow CI- // runner — a genuine deadlock never completes, so a regression still fails.+ // The unrelated append must finish while publication is deliberately+ // paused. Releasing the rebuild first would let root-wide serialization+ // pass this test eventually and prove nothing about overlap.let append_result = rx- .recv_timeout(Duration::from_secs(30))- .expect("append_message did not complete within 30 s — likely blocked by cold rebuild");+ .recv_timeout(Duration::from_secs(5))+ .expect("unrelated append blocked behind a cold rebuild");assert!(append_result.is_ok(),"append failed: {:?}",append_result.err());+ release_tx.send(()).unwrap();let search_result = search_handle.join().expect("search thread panicked");assert!(@@ -333,6 +348,103 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {);}+#[test]+fn delete_during_cold_prime_cannot_republish_stale_messages() {+ use std::sync::mpsc;+ use std::thread;+ use std::time::Duration;++ let (temp, store) = make_store();+ store+ .ensure_thread(CreateConversationThread {+ parent_thread_id: None,+ id: "t1".to_string(),+ title: "Delete race".to_string(),+ created_at: "2026-04-10T12:00:00Z".to_string(),+ labels: None,+ personality_id: None,+ })+ .unwrap();+ store+ .append_message(+ "t1",+ ConversationMessage {+ id: "m1".to_string(),+ content: "hello from a soon-deleted thread".to_string(),+ message_type: "text".to_string(),+ extra_metadata: serde_json::json!({}),+ sender: "user".to_string(),+ created_at: "2026-04-10T12:01:00Z".to_string(),+ },+ )+ .unwrap();+ let store_prime = store.clone();+ let store_delete = store.clone();+ let root = store.root_dir();+ CONVERSATION_INDEX_CACHE.lock().remove(&root);++ let (scanned_tx, scanned_rx) = mpsc::channel();+ let (release_tx, release_rx) = mpsc::channel();+ let prime = thread::spawn(move || {+ let _lifecycle = store_prime.locks.lifecycle.read();+ store_prime.prime_index_if_cold_with_hook(|| {+ scanned_tx.send(()).unwrap();+ release_rx.recv().unwrap();+ })+ });+ scanned_rx+ .recv_timeout(Duration::from_secs(5))+ .expect("prime did not reach post-scan seam");++ let (delete_tx, delete_rx) = mpsc::channel();+ thread::spawn(move || {+ let result = store_delete.delete_thread("t1", "2026-04-10T12:02:00Z");+ delete_tx.send(result).unwrap();+ });+ assert!(+ delete_rx.recv_timeout(Duration::from_millis(100)).is_err(),+ "delete must wait for the cold prime's lifecycle read guard"+ );+ release_tx.send(()).unwrap();+ prime.join().unwrap().unwrap();+ assert!(delete_rx+ .recv_timeout(Duration::from_secs(5))+ .unwrap()+ .unwrap());++ let hits = store+ .search_cross_thread_messages("hello", 10, None)+ .unwrap();+ assert!(hits.is_empty(), "deleted content was republished: {hits:?}");+ drop(temp);+}++#[test]+fn delete_and_purge_evict_historical_thread_locks() {+ let (_temp, store) = make_store();+ store+ .ensure_thread(CreateConversationThread {+ parent_thread_id: None,+ id: "t1".to_string(),+ title: "Eviction".to_string(),+ created_at: "2026-04-10T12:00:00Z".to_string(),+ labels: None,+ personality_id: None,+ })+ .unwrap();+ let _ = store.thread_lock_identity_for_test("t1");+ assert_eq!(store.thread_lock_count_for_test(), 1);+ assert!(store.delete_thread("t1", "2026-04-10T12:02:00Z").unwrap());+ assert_eq!(store.thread_lock_count_for_test(), 0);++ for index in 0..100 {+ let _ = store.thread_lock_identity_for_test(&format!("historical-{index}"));+ }+ assert_eq!(store.thread_lock_count_for_test(), 100);+ store.purge_threads().unwrap();+ assert_eq!(store.thread_lock_count_for_test(), 0);+}+// ── legacy workspace (pre-Stats backfill path) ───────────────────────────────/// Regression test for issue #2849 (backfill path).diff --git a/tests/harness_embed.rs b/tests/harness_embed.rsindex 38758e0911..b8fb07713b 100644--- a/tests/harness_embed.rs+++ b/tests/harness_embed.rs@@ -188,10 +188,15 @@ fn a_harness_runs_a_turn_against_the_provider_it_was_given() {.await});}- let mut outcomes = Vec::with_capacity(100);- while let Some(outcome) = turns.join_next().await {- outcomes.push(outcome.expect("concurrent turn task did not panic"));- }+ let outcomes = tokio::time::timeout(std::time::Duration::from_secs(20), async {+ let mut outcomes = Vec::with_capacity(100);+ while let Some(outcome) = turns.join_next().await {+ outcomes.push(outcome.expect("concurrent turn task did not panic"));+ }+ outcomes+ })+ .await+ .expect("100 concurrent turns did not settle within 20 seconds");let elapsed = started.elapsed();eprintln!("100 concurrent library turns completed in {elapsed:?}");assert!(