Skip to content

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

fix(memory): ask for the namespace count, not the rows, before the Lane B recall

Shanuc2f3e057aa8f
diff --git a/src/openhuman/agent/experience/ops_tests.rs b/src/openhuman/agent/experience/ops_tests.rs
index e8e6fb7dda..d211aa4af8 100644
--- a/src/openhuman/agent/experience/ops_tests.rs
+++ b/src/openhuman/agent/experience/ops_tests.rs
@@ -198,6 +198,46 @@ async fn recall_relevant_by_vector_asks_the_driver_not_the_trait_default() {
);
}
+#[tokio::test]
+async fn recall_relevant_by_vector_forwards_namespace_and_limit_to_the_driver() {
+ use crate::openhuman::memory::guard::test_support::{namespace_hit, RecordingProvider};
+ let mut hits: Vec<_> = (0..7)
+ .map(|i| {
+ namespace_hit(
+ "user_pref_situational",
+ &format!("k{i}"),
+ &format!("pref {i}"),
+ 0.9,
+ )
+ })
+ .collect();
+ hits.push(namespace_hit(
+ "user_pref_general",
+ "other",
+ "a general preference",
+ 0.99,
+ ));
+ let provider = Arc::new(RecordingProvider::new().with_namespace_hits(hits));
+ let memory = DriverMemory::new(provider.clone() as Arc<dyn MemoryProvider>);
+
+ let out = memory
+ .recall_relevant_by_vector("user_pref_situational", "anything", 5, 0.35)
+ .await
+ .expect("a driver with retrieval answers");
+ assert_eq!(out.len(), 5, "the driver's page is the cap: {out:?}");
+ assert!(
+ out.iter().all(|(key, _)| key.starts_with('k')),
+ "a hit from another namespace must never come back: {out:?}"
+ );
+ let call = provider.only_call();
+ assert_eq!(call.method, "retrieval.recall_namespace_scored");
+ assert_eq!(
+ call.content.as_deref(),
+ Some("namespace=user_pref_situational limit=5"),
+ "the request must carry the caller's namespace and limit"
+ );
+}
+
#[tokio::test]
async fn recall_relevant_by_vector_over_a_driver_without_retrieval_answers_empty() {
// The null driver advertises nothing, so there is no retrieval family to
diff --git a/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs b/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
index 415adcfa82..1a05b9ab62 100644
--- a/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
+++ b/src/openhuman/agent/harness/session/turn_tests_part_04_tests.rs
@@ -473,7 +473,9 @@ fn skill_retraction_note_names_removed_skills_and_warns_against_run_skill() {
use crate::openhuman::agent::experience::ops::DriverMemory;
use crate::openhuman::memory::api::provider::MemoryProvider;
-use crate::openhuman::memory::guard::test_support::{entry, namespace_hit, RecordingProvider};
+use crate::openhuman::memory::guard::test_support::{
+ namespace_hit, namespace_summary, RecordingProvider,
+};
use crate::openhuman::memory::preferences::USER_PREF_SITUATIONAL_NAMESPACE;
const PREFERENCES_BANNER: &str = "## Relevant preferences for this message";
@@ -527,11 +529,11 @@ async fn first_request_user_messages(provider: &SequenceProvider) -> Vec<String>
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn situational_preference_reaches_the_model_through_driver_memory() {
- // The namespace must look populated (`list`) before Lane B pays for the
- // vector recall; then the scored hits decide what is injected.
+ // The namespace must look populated (a non-zero count) before Lane B pays
+ // for the vector recall; then the scored hits decide what is injected.
let driver = Arc::new(
RecordingProvider::new()
- .with_list_result(vec![entry("Prefers vim for editing code.")])
+ .with_namespace_summaries(vec![namespace_summary(USER_PREF_SITUATIONAL_NAMESPACE, 2)])
.with_namespace_hits(vec![
namespace_hit(
USER_PREF_SITUATIONAL_NAMESPACE,
@@ -579,8 +581,8 @@ async fn situational_preference_reaches_the_model_through_driver_memory() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn no_situational_preference_means_no_block_and_no_embed_through_driver_memory() {
// Nothing stored under the situational namespace: the lane must find that
- // out from the cheap listing and never reach the vector recall, which is
- // the call that embeds the message.
+ // out from the namespace counts and never reach the vector recall, which
+ // is the call that embeds the message.
let driver = Arc::new(RecordingProvider::new());
let provider_impl = scripted_reply("Sunny.");
let provider: Arc<dyn ChatModel<()>> = provider_impl.clone();
@@ -597,8 +599,8 @@ async fn no_situational_preference_means_no_block_and_no_embed_through_driver_me
);
let methods: Vec<String> = driver.calls().into_iter().map(|c| c.method).collect();
assert!(
- methods.iter().any(|m| m == "core.list"),
- "the lane must ask whether anything is stored: {methods:?}"
+ methods.iter().any(|m| m == "core.namespaces"),
+ "the lane must ask for the namespace counts: {methods:?}"
);
assert!(
!methods
diff --git a/src/openhuman/memory/guard/test_support_part_01.rs b/src/openhuman/memory/guard/test_support_part_01.rs
index 1415d2adcc..1f01038b67 100644
--- a/src/openhuman/memory/guard/test_support_part_01.rs
+++ b/src/openhuman/memory/guard/test_support_part_01.rs
@@ -80,9 +80,9 @@ pub struct RecordingProvider {
/// What `recall_namespace_scored` returns, so the vector-floored recall
/// paths (Lane B, the contradiction check) can be driven with known scores.
namespace_hits: Mutex<Vec<NamespaceMemoryHit>>,
- /// What `list` returns, so a namespace can look populated (Lane B asks
- /// before it pays for an embed) without wiring a real store.
- list_result: Mutex<Vec<MemoryEntry>>,
+ /// What `namespaces` returns, so a namespace can look populated (Lane B
+ /// asks for the count before it pays for an embed) without a real store.
+ namespace_summaries: Mutex<Vec<NamespaceSummary>>,
}
impl Default for RecordingProvider {
@@ -97,7 +97,7 @@ impl RecordingProvider {
calls: Mutex::new(Vec::new()),
recall_result: Mutex::new(Vec::new()),
namespace_hits: Mutex::new(Vec::new()),
- list_result: Mutex::new(Vec::new()),
+ namespace_summaries: Mutex::new(Vec::new()),
}
}
@@ -111,8 +111,8 @@ impl RecordingProvider {
self
}
- pub fn with_list_result(self, entries: Vec<MemoryEntry>) -> Self {
- *self.list_result.lock().unwrap() = entries;
+ pub fn with_namespace_summaries(self, summaries: Vec<NamespaceSummary>) -> Self {
+ *self.namespace_summaries.lock().unwrap() = summaries;
self
}
@@ -274,12 +274,12 @@ impl MemoryCore for RecordingProvider {
_session_id: Option<&str>,
) -> Result<Vec<MemoryEntry>, MemoryError> {
self.record(Call::plain("core.list"));
- Ok(self.list_result.lock().unwrap().clone())
+ Ok(vec![])
}
async fn namespaces(&self) -> Result<Vec<NamespaceSummary>, MemoryError> {
self.record(Call::plain("core.namespaces"));
- Ok(vec![])
+ Ok(self.namespace_summaries.lock().unwrap().clone())
}
}
diff --git a/src/openhuman/memory/guard/test_support_part_02.rs b/src/openhuman/memory/guard/test_support_part_02.rs
index c55598d2a6..e2390e5fe4 100644
--- a/src/openhuman/memory/guard/test_support_part_02.rs
+++ b/src/openhuman/memory/guard/test_support_part_02.rs
@@ -532,13 +532,29 @@ impl MemoryRetrieval for RecordingProvider {
async fn recall_namespace_scored(
&self,
- _namespace: &str,
+ namespace: &str,
_query: &str,
- _limit: usize,
+ limit: usize,
_exclude_session_id: Option<&str>,
) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {
- self.record(Call::plain("retrieval.recall_namespace_scored"));
- Ok(self.namespace_hits.lock().unwrap().clone())
+ // Honours the two request parameters a caller can get wrong — the
+ // namespace it asks for and the page it accepts — and records them,
+ // so a test can assert both rather than only the content it got.
+ self.record(Call {
+ method: "retrieval.recall_namespace_scored".into(),
+ content: Some(format!("namespace={namespace} limit={limit}")),
+ taint: None,
+ scoped: None,
+ });
+ Ok(self
+ .namespace_hits
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|hit| hit.namespace == namespace)
+ .take(limit)
+ .cloned()
+ .collect())
}
async fn recall_namespace_recent(
diff --git a/src/openhuman/memory/guard/test_support_part_03.rs b/src/openhuman/memory/guard/test_support_part_03.rs
index 9f009f11bf..1f4304b907 100644
--- a/src/openhuman/memory/guard/test_support_part_03.rs
+++ b/src/openhuman/memory/guard/test_support_part_03.rs
@@ -1,6 +1,15 @@
// Fixtures for the retrieval family's scored answers. Included into
// `test_support.rs` after the provider parts, so the imports there are in scope.
+/// A [`NamespaceSummary`] saying `namespace` holds `count` entries.
+pub fn namespace_summary(namespace: &str, count: usize) -> NamespaceSummary {
+ NamespaceSummary {
+ namespace: namespace.into(),
+ count,
+ last_updated: None,
+ }
+}
+
/// A [`NamespaceMemoryHit`] with only the vector component set — the signal the
/// vector-floored recall paths (Lane B, the contradiction check) filter on.
pub fn namespace_hit(
diff --git a/src/openhuman/memory/preferences/mod.rs b/src/openhuman/memory/preferences/mod.rs
index ee627ce4a6..7d8dcd8a39 100644
--- a/src/openhuman/memory/preferences/mod.rs
+++ b/src/openhuman/memory/preferences/mod.rs
@@ -232,13 +232,20 @@ pub async fn recall_situational_preferences_on(
// The vector recall embeds the message — a round trip to the embedder,
// measured at 0.8–3 s on the desktop — and it runs on every turn. Most
// users have never saved a topic-scoped preference, so ask the store the
- // cheap question first (a namespace listing, no embedding) and only pay
- // for the embed when there is something to match. A failed listing falls
- // through to the recall rather than silently disabling the lane.
+ // cheap question first and only pay for the embed when there is something
+ // to match. The question is a namespace *count*, not a listing: a user
+ // with hundreds of preferences must not ship every row over the bus on
+ // every turn just to learn that the namespace is non-empty. A failed
+ // count falls through to the recall rather than silently disabling the
+ // lane.
let has_candidates = memory
- .list(Some(USER_PREF_SITUATIONAL_NAMESPACE), None, None)
+ .namespace_summaries()
.await
- .map(|entries| !entries.is_empty())
+ .map(|summaries| {
+ summaries
+ .iter()
+ .any(|s| s.namespace == USER_PREF_SITUATIONAL_NAMESPACE && s.count > 0)
+ })
.unwrap_or(true);
if !has_candidates {
log::debug!("[pref_recall] no situational preferences stored; skipping the vector recall");