Skip to content

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

fix: serialize core and store teardown

Steven Enamakel5e8c4412fd45
diff --git a/src/embed/harness/builder.rs b/src/embed/harness/builder.rs
index 5cd46fd29f..96992bf8a0 100644
--- a/src/embed/harness/builder.rs
+++ b/src/embed/harness/builder.rs
@@ -377,7 +377,7 @@ impl HarnessBuilder {
}
Ok(Harness {
- core,
+ core: Some(core),
provider: self.provider,
access: self.access,
_workspace: resolved,
diff --git a/src/embed/harness/mod.rs b/src/embed/harness/mod.rs
index c63f29e962..f153e9e904 100644
--- a/src/embed/harness/mod.rs
+++ b/src/embed/harness/mod.rs
@@ -115,7 +115,7 @@ static HARNESS_LIVE: AtomicBool = AtomicBool::new(false);
/// Dropping it releases the process slot and, for
/// [`Workspace::Ephemeral`], removes the workspace.
pub struct Harness {
- core: Core,
+ core: Option<Core>,
provider: Provider,
access: Access,
/// Held for its `Drop`: an ephemeral workspace lives exactly as long as the
@@ -143,7 +143,7 @@ impl Harness {
/// The harness's provider route and access origin are pre-applied; anything
/// set on the returned [`Turn`] overrides them for that turn alone.
pub fn turn(&self, message: impl Into<String>) -> Turn<'_> {
- let mut turn = self.core.agent().turn(message);
+ let mut turn = self.core().agent().turn(message);
if let Some(route) = self.provider.route() {
turn = turn.route(route.clone());
}
@@ -159,7 +159,9 @@ impl Harness {
/// The typed core facade beneath this harness — config, memory, and the
/// [`raw`](Core::raw) escape hatch for anything not yet modelled.
pub fn core(&self) -> &Core {
- &self.core
+ self.core
+ .as_ref()
+ .expect("harness core is present until drop")
}
/// The workspace this harness is rooted at.
@@ -178,7 +180,10 @@ impl Harness {
impl Drop for Harness {
fn drop(&mut self) {
- HARNESS_LIVE.store(false, std::sync::atomic::Ordering::Release);
+ // Drop the old core while the process slot is still claimed. Releasing
+ // it first lets another builder initialize process-scoped state while
+ // this runtime's keyring, bearer, event bus and subscribers are live.
+ drop(self.core.take());
// For an ephemeral workspace, take ownership of the temp path and
// remove it with a short retry. The core's memory/session writers keep
// running a moment after the harness returns from a turn and can
@@ -199,6 +204,7 @@ impl Drop for Harness {
}
let _ = std::fs::remove_dir_all(&root);
}
+ HARNESS_LIVE.store(false, std::sync::atomic::Ordering::Release);
log::debug!("[embed][harness] released");
}
}
diff --git a/src/openhuman/memory/conversations/store/store_index.rs b/src/openhuman/memory/conversations/store/store_index.rs
index c0163359a7..70dd445aba 100644
--- a/src/openhuman/memory/conversations/store/store_index.rs
+++ b/src/openhuman/memory/conversations/store/store_index.rs
@@ -38,70 +38,58 @@ impl ConversationStore {
mut after_scan: impl FnMut(),
) -> Result<(), String> {
let key = self.root_dir();
- let mut hook_pending = true;
- loop {
- // Fast path: already warm — one tiny lock acquisition and out.
+ // 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. A delete
+ // takes the lifecycle write guard, while every production caller of
+ // this method holds its read guard, so deletion cannot interleave with
+ // this scan or publication.
+ // `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.
if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {
return Ok(());
}
- // 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);
- }
- }
- }
- 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 {
+ 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;
}
- let mut cache = CONVERSATION_INDEX_CACHE.lock();
- cache.entry(key.clone()).or_insert(idx);
- return Ok(());
+ if let Ok(messages) = read_jsonl::<ConversationMessage>(&path) {
+ for msg in messages {
+ idx.insert(thread_id, msg);
+ }
+ }
}
+ after_scan();
+ // Insert only if the key is still absent — a concurrent prime that
+ // finished first wins; ours is discarded.
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ cache.entry(key).or_insert(idx);
+ Ok(())
}
/// Acquire the cached inverted index for this workspace and run `f` against
diff --git a/src/openhuman/memory/conversations/store/store_locks.rs b/src/openhuman/memory/conversations/store/store_locks.rs
index d0fdbcef1e..e96ee23138 100644
--- a/src/openhuman/memory/conversations/store/store_locks.rs
+++ b/src/openhuman/memory/conversations/store/store_locks.rs
@@ -7,7 +7,6 @@
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};
@@ -19,7 +18,6 @@ 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 {
@@ -32,14 +30,6 @@ impl StoreLocks {
)
}
- 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);
diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rs
index e086571415..b6e77e3907 100644
--- a/src/openhuman/memory/conversations/store/store_ops.rs
+++ b/src/openhuman/memory/conversations/store/store_ops.rs
@@ -307,7 +307,6 @@ 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) {
@@ -349,7 +348,6 @@ impl ConversationStore {
let mut cache = CONVERSATION_INDEX_CACHE.lock();
cache.remove(&root);
}
- self.locks.record_deletion();
self.locks.clear_threads();
Ok(stats)
}