Skip to content

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

fix: bind core ownership and index publication

Steven Enamakel18abe0df8f71
diff --git a/src/embed/harness/builder.rs b/src/embed/harness/builder.rs
index 96992bf8a0..68612ccb7c 100644
--- a/src/embed/harness/builder.rs
+++ b/src/embed/harness/builder.rs
@@ -315,7 +315,7 @@ impl HarnessBuilder {
// applicator. Host policy must follow that effective behavior rather
// than the syntactic presence of endpoint credentials, or an ignored
// route could exempt an inherited installed provider from login.
- let routed_provider_effective = self.provider.is_routed()
+ let routed_provider_effective = self.provider.has_usable_route()
&& config
.as_ref()
.and_then(|config| config.default_model.as_deref())
diff --git a/src/embed/harness/mod.rs b/src/embed/harness/mod.rs
index a7c52e897b..a7d9b42b3f 100644
--- a/src/embed/harness/mod.rs
+++ b/src/embed/harness/mod.rs
@@ -123,6 +123,40 @@ pub struct Harness {
_workspace: ResolvedWorkspace,
}
+/// Borrowed access to the core owned by a [`Harness`].
+///
+/// Unlike [`Core`], this facade is deliberately not cloneable and does not
+/// expose the runtime `Arc`: a retained runtime could outlive the harness's
+/// process-slot and workspace ownership. Share an `Arc<Harness>` when several
+/// agents need concurrent access.
+pub struct HarnessCore<'a> {
+ core: &'a Core,
+}
+
+impl HarnessCore<'_> {
+ pub fn config(&self) -> crate::embed::Config<'_> {
+ self.core.config()
+ }
+
+ pub fn auth(&self) -> crate::embed::Auth<'_> {
+ self.core.auth()
+ }
+
+ pub fn agent(&self) -> crate::embed::Agent<'_> {
+ self.core.agent()
+ }
+
+ #[cfg(feature = "medulla")]
+ pub fn medulla(&self) -> crate::embed::Medulla<'_> {
+ self.core.medulla()
+ }
+
+ /// Borrow the underlying runtime without exposing its owning `Arc`.
+ pub fn raw(&self) -> &crate::core::runtime::CoreRuntime {
+ self.core.raw().as_ref()
+ }
+}
+
impl Harness {
/// Start configuring a harness.
pub fn builder() -> HarnessBuilder {
@@ -143,7 +177,12 @@ 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
+ .as_ref()
+ .expect("harness core is present until drop")
+ .agent()
+ .turn(message);
if let Some(route) = self.provider.route() {
turn = turn.route(route.clone());
}
@@ -158,10 +197,13 @@ 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
- .as_ref()
- .expect("harness core is present until drop")
+ pub fn core(&self) -> HarnessCore<'_> {
+ HarnessCore {
+ core: self
+ .core
+ .as_ref()
+ .expect("harness core is present until drop"),
+ }
}
/// The workspace this harness is rooted at.
diff --git a/src/embed/harness/provider.rs b/src/embed/harness/provider.rs
index 44812a776a..f9772c2b75 100644
--- a/src/embed/harness/provider.rs
+++ b/src/embed/harness/provider.rs
@@ -79,6 +79,15 @@ impl Provider {
pub fn is_routed(&self) -> bool {
self.route.is_some()
}
+
+ /// Whether the route would survive [`EphemeralRoute::from_params`]'s
+ /// normalization. Kept separate from [`Self::is_routed`], which describes
+ /// the caller's syntactic choice for diagnostics.
+ pub(super) fn has_usable_route(&self) -> bool {
+ self.route.as_ref().is_some_and(|route| {
+ !route.base_url.trim().is_empty() && !route.api_key.trim().is_empty()
+ })
+ }
}
#[cfg(test)]
diff --git a/src/embed/harness/provider_tests.rs b/src/embed/harness/provider_tests.rs
index 92f65b4219..c6011a616e 100644
--- a/src/embed/harness/provider_tests.rs
+++ b/src/embed/harness/provider_tests.rs
@@ -17,6 +17,13 @@ fn inherit_states_no_route() {
assert!(provider.model_id().is_none());
}
+#[test]
+fn usable_routes_require_nonblank_endpoint_and_credential() {
+ assert!(Provider::openai_compatible("https://api.example/v1", "sk").has_usable_route());
+ assert!(!Provider::openai_compatible(" ", "sk").has_usable_route());
+ assert!(!Provider::openai_compatible("https://api.example/v1", " ").has_usable_route());
+}
+
#[test]
fn a_blank_model_is_not_a_model() {
// The core treats a blank `model_override` as absent, and a route with no
diff --git a/src/embed/mod.rs b/src/embed/mod.rs
index 04274de81b..0bed29c602 100644
--- a/src/embed/mod.rs
+++ b/src/embed/mod.rs
@@ -63,7 +63,9 @@ pub use agent::{absolute, Agent, Route, Turn, TurnOutcome, TurnRequest};
pub use auth::{Auth, AuthState, Session};
pub use config::{Config, RuntimeFlags};
pub use error::CoreError;
-pub use harness::{Access, Harness, HarnessBuilder, HarnessError, Provider, Workspace};
+pub use harness::{
+ Access, Harness, HarnessBuilder, HarnessCore, HarnessError, Provider, Workspace,
+};
#[cfg(feature = "mcp")]
pub use harness::{HttpHeader, McpAuthConfig, McpServer};
#[cfg(feature = "medulla")]
diff --git a/src/openhuman/memory/conversations/store/store_index.rs b/src/openhuman/memory/conversations/store/store_index.rs
index 70dd445aba..698bedcc92 100644
--- a/src/openhuman/memory/conversations/store/store_index.rs
+++ b/src/openhuman/memory/conversations/store/store_index.rs
@@ -38,58 +38,79 @@ impl ConversationStore {
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. 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.
+ let mut hook_pending = true;
+ for attempt in 0..3 {
+ // 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;
+ // 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, 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.mutation_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();
}
- if let Ok(messages) = read_jsonl::<ConversationMessage>(&path) {
- for msg in messages {
- idx.insert(thread_id, msg);
+ // Append records its generation and updates an already-warm cache
+ // under this same metadata guard. It therefore either wins first
+ // and forces a retry, or follows publication and inserts itself.
+ let _metadata = self.locks.metadata.lock();
+ if self.locks.mutation_generation() != generation {
+ if attempt == 2 {
+ return Err(
+ "conversation index changed during three build attempts; retry search"
+ .to_string(),
+ );
}
+ continue;
}
+ let mut cache = CONVERSATION_INDEX_CACHE.lock();
+ cache.entry(key.clone()).or_insert(idx);
+ return Ok(());
}
- 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(())
+ unreachable!("bounded prime loop returns on every path")
}
/// 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 e96ee23138..318e05c481 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<()>>>>,
+ mutation_generation: AtomicU64,
}
impl StoreLocks {
@@ -30,6 +32,14 @@ impl StoreLocks {
)
}
+ pub(super) fn mutation_generation(&self) -> u64 {
+ self.mutation_generation.load(Ordering::Acquire)
+ }
+
+ pub(super) fn record_mutation(&self) {
+ self.mutation_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 aca8537e86..680d1806ab 100644
--- a/src/openhuman/memory/conversations/store/store_ops.rs
+++ b/src/openhuman/memory/conversations/store/store_ops.rs
@@ -176,12 +176,10 @@ impl ConversationStore {
last_message_at: message.created_at.clone(),
},
)?;
- }
- // Keep the inverted index in sync. We only update if the index has
- // already been materialized for this workspace — otherwise the next
- // search will lazily rebuild and pick up this message anyway, and we
- // avoid paying the rebuild cost on a write path.
- {
+ self.locks.record_mutation();
+ // Keep publication and warm-cache insertion in the same metadata
+ // critical section. A concurrent cold build either observes this
+ // generation or publishes first and receives this insertion.
let mut cache = CONVERSATION_INDEX_CACHE.lock();
if let Some(idx) = cache.get_mut(&self.root_dir()) {
idx.insert(thread_id, message.clone());
diff --git a/src/openhuman/memory/conversations/store/store_tests_late.rs b/src/openhuman/memory/conversations/store/store_tests_late.rs
index a156f2511c..e84c10abe2 100644
--- a/src/openhuman/memory/conversations/store/store_tests_late.rs
+++ b/src/openhuman/memory/conversations/store/store_tests_late.rs
@@ -361,6 +361,15 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {
"search failed: {:?}",
search_result.err()
);
+ let appended = store
+ .search_cross_thread_messages("written during cold rebuild", 10, None)
+ .unwrap();
+ assert!(
+ appended
+ .iter()
+ .any(|hit| hit.message_id == "concurrent-append"),
+ "completed append was omitted from index: {appended:?}"
+ );
}
#[test]