Skip to content

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

fix(memory): let auto-recall reach saved notes on hosted memory

Shanu292b64365571
diff --git a/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs b/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs
index 75cfa9ce9a..143cbf2833 100644
--- a/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/auto_recall_tests.rs
@@ -54,6 +54,10 @@ fn response(hits: Vec<RetrievalHit>) -> RetrievalResponse {
struct Scripted {
outcome: Mutex<Result<RetrievalResponse, String>>,
notes: Mutex<Result<Vec<NamespaceMemoryHit>, String>>,
+ /// Whether the scripted notes carry the engine's scores.
+ notes_scored: Mutex<bool>,
+ /// A typed refusal for the notes leg, instead of a plain failure.
+ notes_refusal: Mutex<Option<fn() -> MemoryError>>,
delay: Duration,
notes_delay: Mutex<Duration>,
calls: AtomicUsize,
@@ -65,6 +69,8 @@ impl Scripted {
Arc::new(Self {
outcome: Mutex::new(outcome),
notes: Mutex::new(Ok(Vec::new())),
+ notes_scored: Mutex::new(true),
+ notes_refusal: Mutex::new(None),
delay,
notes_delay: Mutex::new(Duration::ZERO),
calls: AtomicUsize::new(0),
@@ -90,6 +96,20 @@ impl Scripted {
self
}
+ /// Scripts the notes leg's answer from an engine that ranks without
+ /// scoring: every similarity reads 0.0.
+ fn with_unscored_notes(self: Arc<Self>, notes: Vec<NamespaceMemoryHit>) -> Arc<Self> {
+ *self.notes.lock().unwrap() = Ok(notes);
+ *self.notes_scored.lock().unwrap() = false;
+ self
+ }
+
+ /// Scripts the notes leg to be refused with the error `refusal` makes.
+ fn with_refused_notes(self: Arc<Self>, refusal: fn() -> MemoryError) -> Arc<Self> {
+ *self.notes_refusal.lock().unwrap() = Some(refusal);
+ self
+ }
+
/// Scripts the notes leg to fail.
fn with_failing_notes(self: Arc<Self>, message: &str) -> Arc<Self> {
*self.notes.lock().unwrap() = Err(message.to_string());
@@ -133,7 +153,7 @@ impl AutoRecallSource for Scripted {
namespace: &str,
_query: &str,
limit: usize,
- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {
+ ) -> Result<ScoredNotes, MemoryError> {
self.notes_calls.fetch_add(1, AtomicOrdering::SeqCst);
// The lane owns both parameters; a fake that accepted anything would
// let a wrong namespace or page size pass every test.
@@ -143,8 +163,14 @@ impl AutoRecallSource for Scripted {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
+ if let Some(refusal) = *self.notes_refusal.lock().unwrap() {
+ return Err(refusal());
+ }
match &*self.notes.lock().unwrap() {
- Ok(notes) => Ok(notes.clone()),
+ Ok(notes) => Ok(ScoredNotes {
+ hits: notes.clone(),
+ scored: *self.notes_scored.lock().unwrap(),
+ }),
Err(message) => Err(MemoryError::Backend(message.clone())),
}
}
@@ -518,3 +544,6 @@ async fn from_guard_over_a_driver_without_retrieval_stays_silent() {
#[path = "notes_lane_tests.rs"]
mod notes_lane_tests;
+
+#[path = "unscored_lane_tests.rs"]
+mod unscored_lane_tests;
diff --git a/crates/openhuman-core/src/memory/auto_recall/mod.rs b/crates/openhuman-core/src/memory/auto_recall/mod.rs
index eb20b06735..b48fb4c39d 100644
--- a/crates/openhuman-core/src/memory/auto_recall/mod.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/mod.rs
@@ -77,11 +77,13 @@
//! thresholds can be tuned from real logs.
mod gate;
+mod refusal;
mod source;
pub mod warm;
pub use gate::{gate_decision, GateDecision};
-pub use source::{AutoRecallSource, GuardSource};
+pub use refusal::MemoryRefusal;
+pub use source::{AutoRecallSource, GuardSource, ScoredNotes};
use crate::agent::harness::memory_context_safety::{
is_potentially_untrusted, wrap_untrusted_for_agent,
@@ -144,6 +146,16 @@ pub const AUTO_RECALL_NOTES_NAMESPACE: &str = DEFAULT_AGENT_MEMORY_NAMESPACE;
/// The `[auto_recall]` line logs the best candidate before the floor.
pub const AUTO_RECALL_NOTE_MIN_SIMILARITY: f64 = 0.35;
+/// How many notes an engine that ranks without scoring contributes (hosted
+/// CortexDB answers no score at all).
+///
+/// With no similarity to floor on, the engine's order is the only relevance
+/// signal, and the gate has already judged the message worth a lookup. So the
+/// first few are kept: enough that a paraphrased question still reaches its
+/// note, few enough that an unrelated one costs a couple of lines rather than
+/// the whole namespace.
+pub const AUTO_RECALL_UNSCORED_NOTES: usize = 3;
+
/// The lane itself: a retrieval source, the switch, and the budgets.
pub struct AutoRecall {
source: Arc<dyn AutoRecallSource>,
@@ -225,17 +237,27 @@ impl AutoRecall {
self.tree_leg(user_message, reason),
self.notes_leg(user_message, reason)
);
- let notes_top = similarity_label(notes.top);
+ let notes_top = if notes.scored {
+ similarity_label(notes.top)
+ } else {
+ "unscored".to_string()
+ };
+ // Either leg can be refused, and both ask the same engine; the notes
+ // leg's reason is the one a user's saved facts depend on.
+ let refusal = notes.refusal.or(tree.refusal);
if tree.hits.is_empty() && notes.hits.is_empty() {
log::info!(
"[auto_recall] gate=open reason={reason} hits=0 total={} notes=0 \
- notes_top={notes_top} tree_ms={} notes_ms={} elapsed_ms={}",
+ notes_top={notes_top} refusal={} tree_ms={} notes_ms={} elapsed_ms={}",
tree.total,
+ refusal.map_or("none", MemoryRefusal::label),
tree.elapsed_ms,
notes.elapsed_ms,
started.elapsed().as_millis()
);
- return None;
+ // A refused lookup is not an empty one: say why, so the answer is
+ // "memory is unavailable" rather than "that was never stored".
+ return refusal.map(refusal::render_refusal_block);
}
let block = render_block(&notes.hits, &tree.hits, self.recall_max_chars);
log::info!(
@@ -269,11 +291,14 @@ impl AutoRecall {
leg.total = response.total;
leg.hits = select_hits(response.hits);
}
- Ok(Err(err)) => log::warn!(
- "[auto_recall] gate=open reason={reason} tree retrieval failed after {}ms; \
- continuing without tree hits: {err}",
- started.elapsed().as_millis()
- ),
+ Ok(Err(err)) => {
+ leg.refusal = MemoryRefusal::of(&err);
+ log::warn!(
+ "[auto_recall] gate=open reason={reason} tree retrieval failed after {}ms; \
+ continuing without tree hits: {err}",
+ started.elapsed().as_millis()
+ );
+ }
Err(_elapsed) => log::warn!(
"[auto_recall] gate=open reason={reason} tree retrieval exceeded {:?}; \
continuing without tree hits",
@@ -300,15 +325,22 @@ impl AutoRecall {
)
.await
{
- Ok(Ok(candidates)) => {
- leg.top = top_similarity(&candidates);
- leg.hits = select_notes(candidates);
+ Ok(Ok(notes)) if notes.scored => {
+ leg.top = top_similarity(&notes.hits);
+ leg.hits = select_notes(notes.hits);
+ }
+ Ok(Ok(notes)) => {
+ leg.scored = false;
+ leg.hits = select_unscored_notes(notes.hits);
+ }
+ Ok(Err(err)) => {
+ leg.refusal = MemoryRefusal::of(&err);
+ log::warn!(
+ "[auto_recall] gate=open reason={reason} notes recall failed after {}ms; \
+ continuing without notes: {err}",
+ started.elapsed().as_millis()
+ );
}
- Ok(Err(err)) => log::warn!(
- "[auto_recall] gate=open reason={reason} notes recall failed after {}ms; \
- continuing without notes: {err}",
- started.elapsed().as_millis()
- ),
Err(_elapsed) => log::warn!(
"[auto_recall] gate=open reason={reason} notes recall exceeded {:?}; \
continuing without notes",
@@ -327,6 +359,8 @@ struct TreeLeg {
hits: Vec<RetrievalHit>,
total: usize,
elapsed_ms: u128,
+ /// Why the engine refused the lookup, when it said why.
+ refusal: Option<MemoryRefusal>,
}
/// What the notes leg answered. `top` is the best vector similarity among the
@@ -336,6 +370,10 @@ struct NotesLeg {
hits: Vec<NamespaceMemoryHit>,
top: f64,
elapsed_ms: u128,
+ /// Whether the engine scored its hits; see [`ScoredNotes::scored`].
+ scored: bool,
+ /// Why the engine refused the lookup, when it said why.
+ refusal: Option<MemoryRefusal>,
}
impl Default for NotesLeg {
@@ -344,6 +382,8 @@ impl Default for NotesLeg {
hits: Vec::new(),
top: f64::NEG_INFINITY,
elapsed_ms: 0,
+ scored: true,
+ refusal: None,
}
}
}
@@ -413,6 +453,16 @@ pub(crate) fn select_notes(mut notes: Vec<NamespaceMemoryHit>) -> Vec<NamespaceM
notes
}
+/// The notes an engine that ranks without scoring contributes: its first
+/// [`AUTO_RECALL_UNSCORED_NOTES`] with a body, in its own order. There is no
+/// similarity to floor on — every hit reads 0.0 — so [`select_notes`] would
+/// drop them all however well the engine ranked them.
+pub(crate) fn select_unscored_notes(mut notes: Vec<NamespaceMemoryHit>) -> Vec<NamespaceMemoryHit> {
+ notes.retain(|note| !note.content.trim().is_empty());
+ notes.truncate(AUTO_RECALL_UNSCORED_NOTES);
+ notes
+}
+
/// The block the turn prepends: the banner, the hint, one line per note, one
/// line per tree hit, kept within `recall_max_chars` when the guard sets one.
///
diff --git a/crates/openhuman-core/src/memory/auto_recall/refusal.rs b/crates/openhuman-core/src/memory/auto_recall/refusal.rs
new file mode 100644
index 0000000000..411d1bfa67
--- /dev/null
+++ b/crates/openhuman-core/src/memory/auto_recall/refusal.rs
@@ -0,0 +1,91 @@
+//! Why a lookup could not run, when the engine said why.
+//!
+//! A remote engine can refuse a recall for reasons that are not "nothing
+//! relevant": the hosted account is out of credits, the session was not
+//! accepted, the credential lacks the memory scope, or the service cannot be
+//! reached. The lane used to log those and carry on as though memory were
+//! empty, so the model told the user a fact they had saved was never stored.
+//! A refused lookup now puts that reason in front of the model instead, in the
+//! block's usual place, so the answer can say what is actually wrong.
+
+use crate::memory::api::error::MemoryError;
+use crate::memory::ops::engine::{
+ classify_memory_error, INSUFFICIENT_CREDITS_PREFIX, MEMORY_FORBIDDEN_PREFIX,
+ MEMORY_UNREACHABLE_PREFIX, SESSION_EXPIRED_PREFIX,
+};
+
+use super::AUTO_RECALL_BANNER;
+
+/// Why memory could not be searched for a message.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MemoryRefusal {
+ /// The hosted engine's account has no credits left.
+ OutOfCredits,
+ /// The engine did not accept the session.
+ SessionExpired,
+ /// The engine refused the credential outright (HTTP 403).
+ Forbidden,
+ /// The engine could not be reached, or answered that it cannot serve now.
+ Unavailable,
+}
+
+impl MemoryRefusal {
+ /// The refusal `error` stands for, or `None` for an ordinary failure.
+ pub fn of(error: &MemoryError) -> Option<Self> {
+ let classified = classify_memory_error(error);
+ [
+ (INSUFFICIENT_CREDITS_PREFIX, Self::OutOfCredits),
+ (SESSION_EXPIRED_PREFIX, Self::SessionExpired),
+ (MEMORY_FORBIDDEN_PREFIX, Self::Forbidden),
+ (MEMORY_UNREACHABLE_PREFIX, Self::Unavailable),
+ ]
+ .into_iter()
+ .find_map(|(prefix, refusal)| classified.starts_with(prefix).then_some(refusal))
+ }
+
+ /// A stable label for log lines.
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::OutOfCredits => "out_of_credits",
+ Self::SessionExpired => "session_expired",
+ Self::Forbidden => "forbidden",
+ Self::Unavailable => "unavailable",
+ }
+ }
+
+ /// What the model is told, as the clause after "could not be searched".
+ fn reason(self) -> &'static str {
+ match self {
+ Self::OutOfCredits => {
+ "the OpenHuman account is out of credits, and hosted memory is billed in \
+ credits; it works again once credits are added"
+ }
+ Self::SessionExpired => {
+ "the memory service did not accept the session; it works again after the \
+ user signs in"
+ }
+ Self::Forbidden => {
+ "the memory service refused this account's credential; an API key needs \
+ the memory scope"
+ }
+ Self::Unavailable => {
+ "the memory service could not be reached; it may work again in a moment"
+ }
+ }
+ }
+}
+
+/// The block for a lookup that was refused and found nothing else: the usual
+/// banner over one line saying why memory is out of reach.
+pub(crate) fn render_refusal_block(refusal: MemoryRefusal) -> String {
+ format!(
+ "{AUTO_RECALL_BANNER}\n\nMemory could not be searched for this message: {}. \
+ If the user asks about something they saved, say that memory is unavailable \
+ and why, rather than that it was never stored.\n\n",
+ refusal.reason()
+ )
+}
+
+#[cfg(test)]
+#[path = "refusal_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs b/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs
new file mode 100644
index 0000000000..45b3f9a3ff
--- /dev/null
+++ b/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs
@@ -0,0 +1,72 @@
+use super::*;
+
+#[test]
+fn a_hosted_credit_refusal_is_out_of_credits() {
+ let error = MemoryError::BudgetExceeded(
+ "[USER_INSUFFICIENT_CREDITS] memory API memory/recall on api.example (HTTP 402 \
+ Payment Required): Insufficient credits — insufficient credits"
+ .into(),
+ );
+ assert_eq!(MemoryRefusal::of(&error), Some(MemoryRefusal::OutOfCredits));
+}
+
+#[test]
+fn a_401_is_a_session_the_engine_did_not_accept() {
+ let error = MemoryError::Unauthorized(
+ "[UNAUTHORIZED] memory API memory/recall on api.example (HTTP 401 Unauthorized): \
+ Invalid token — the session expired or the API key was rejected; re-authenticate"
+ .into(),
+ );
+ assert_eq!(
+ MemoryRefusal::of(&error),
+ Some(MemoryRefusal::SessionExpired)
+ );
+}
+
+#[test]
+fn a_403_is_a_refused_credential_not_a_lapsed_session() {
+ let error = MemoryError::Unauthorized(
+ "[FORBIDDEN] memory API memory/recall on api.example (HTTP 403 Forbidden): API key \
+ is missing the required scope: memory — the session expired or the API key was \
+ rejected; re-authenticate"
+ .into(),
+ );
+ assert_eq!(MemoryRefusal::of(&error), Some(MemoryRefusal::Forbidden));
+}
+
+#[test]
+fn an_outage_is_unavailable() {
+ for error in [
+ MemoryError::Unavailable("[RATE_LIMITED] memory API memory/recall (HTTP 429)".into()),
+ MemoryError::Unreachable("memory API request to api.example: could not connect".into()),
+ MemoryError::Timeout("memory API request to api.example: timed out".into()),
+ ] {
+ assert_eq!(
+ MemoryRefusal::of(&error),
+ Some(MemoryRefusal::Unavailable),
+ "{error}"
+ );
+ }
+}
+
+#[test]
+fn an_ordinary_failure_is_not_a_refusal() {
+ for error in [
+ MemoryError::Invalid("namespace must not be empty".into()),
+ MemoryError::Backend("engine answered 418".into()),
+ MemoryError::BudgetExceeded("the answer exceeded its token budget".into()),
+ ] {
+ assert_eq!(MemoryRefusal::of(&error), None, "{error}");
+ }
+}
+
+#[test]
+fn the_refusal_block_heads_the_reason_with_the_usual_banner() {
+ let block = render_refusal_block(MemoryRefusal::OutOfCredits);
+ assert!(block.starts_with(AUTO_RECALL_BANNER), "{block}");
+ assert!(block.contains("out of credits"), "{block}");
+ assert!(
+ block.contains("rather than that it was never stored"),
+ "{block}"
+ );
+}
diff --git a/crates/openhuman-core/src/memory/auto_recall/source.rs b/crates/openhuman-core/src/memory/auto_recall/source.rs
index d0572ab4f1..3782cfd97d 100644
--- a/crates/openhuman-core/src/memory/auto_recall/source.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/source.rs
@@ -33,13 +33,34 @@ pub trait AutoRecallSource: Send + Sync {
) -> Result<RetrievalResponse, MemoryError>;
/// The driver's scored recall over `namespace` for `query`: at most `limit`
- /// hits, each carrying the vector similarity the lane floors on.
+ /// hits, each carrying the vector similarity the lane floors on — or, for
+ /// an engine that ranks without scoring, the hits in its order with
+ /// [`ScoredNotes::scored`] false.
async fn recall_namespace_scored(
&self,
namespace: &str,
query: &str,
limit: usize,
- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError>;
+ ) -> Result<ScoredNotes, MemoryError>;
+}
+
+/// What a notes recall answered, and whether its similarities are scores.
+#[derive(Debug)]
+pub struct ScoredNotes {
+ /// The hits, most relevant first.
+ pub hits: Vec<NamespaceMemoryHit>,
+ /// Whether each hit's `vector_similarity` is the engine's own score.
+ /// `false` for an engine whose recall is ranked but carries no score
+ /// (hosted CortexDB): its hits read 0.0, and flooring on that would drop
+ /// every one of them however well the engine ranked it.
+ pub scored: bool,
+}
+
+impl ScoredNotes {
+ /// Hits whose similarities are the engine's scores.
+ pub fn scored(hits: Vec<NamespaceMemoryHit>) -> Self {
+ Self { hits, scored: true }
+ }
}
/// The production source: the session's bound driver, behind its guard.
@@ -84,21 +105,26 @@ impl AutoRecallSource for GuardSource {
namespace: &str,
query: &str,
limit: usize,
- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {
+ ) -> Result<ScoredNotes, MemoryError> {
// No retrieval family (a remote engine): the notes still come from the
- // mandatory ranked recall. Only the tree leg has no equivalent.
+ // mandatory ranked recall. Only the tree leg has no equivalent. The
+ // error stays typed so the lane can tell a credit or session refusal
+ // from an outage.
let Some(retrieval) = self.guard.as_retrieval() else {
log::debug!(
"[auto_recall] bound driver exposes no retrieval family; notes via mandatory recall"
);
- return crate::memory::ops::fallback::recall_hits(
+ let ranked = crate::memory::ops::fallback::ranked_recall(
self.guard.as_ref(),
namespace,
query,
limit,
)
- .await
- .map_err(|e| MemoryError::Other(anyhow::anyhow!(e)));
+ .await?;
+ return Ok(ScoredNotes {
+ hits: ranked.hits,
+ scored: ranked.scored,
+ });
};
// No session to exclude: the notes namespace is never auto-saved per
// session, and the lane runs before this turn is archived, so there is
@@ -106,5 +132,6 @@ impl AutoRecallSource for GuardSource {
retrieval
.recall_namespace_scored(namespace, query, limit, None)
.await
+ .map(ScoredNotes::scored)
}
}
diff --git a/crates/openhuman-core/src/memory/auto_recall/unscored_lane_tests.rs b/crates/openhuman-core/src/memory/auto_recall/unscored_lane_tests.rs
new file mode 100644
index 0000000000..9b38b4902f
--- /dev/null
+++ b/crates/openhuman-core/src/memory/auto_recall/unscored_lane_tests.rs
@@ -0,0 +1,127 @@
+use super::*;
+use crate::memory::api::types::{MemoryCategory, MemoryEntry};
+use crate::memory::guard::in_memory::FixedRecallProvider;
+
+// The lane against remote engines (openhuman#6718): an engine that ranks its
+// recall without scoring it, and an engine that refuses the lookup. Fixtures
+// (`note`, `Scripted`, the constants) live in the parent module.
+
+/// A note from an engine that does not score: its similarity reads 0.0.
+fn unscored(key: &str, content: &str) -> NamespaceMemoryHit {
+ note(key, content, 0.0)
+}
+
+fn out_of_credits() -> MemoryError {
+ MemoryError::BudgetExceeded(
+ "[USER_INSUFFICIENT_CREDITS] memory API memory/recall on api.example (HTTP 402 \
+ Payment Required): Insufficient credits — insufficient credits"
+ .into(),
+ )
+}
+
+fn unreachable() -> MemoryError {
+ MemoryError::Unreachable("memory API request to api.example: could not connect".into())
+}
+
+#[test]
+fn select_unscored_notes_keeps_the_engines_first_few_with_a_body() {
+ let kept = select_unscored_notes(vec![
+ unscored("a", "first"),
+ unscored("empty", " "),
+ unscored("b", "second"),
+ unscored("c", "third"),
+ unscored("d", "fourth"),
+ ]);
+ let keys: Vec<&str> = kept.iter().map(|n| n.key.as_str()).collect();
+ assert_eq!(keys, ["a", "b", "c"]);
+ assert_eq!(kept.len(), AUTO_RECALL_UNSCORED_NOTES);
+}
+
+#[tokio::test]
+async fn an_unscored_engines_notes_reach_the_block_in_its_order() {
+ // Every similarity reads 0.0, so the scored floor would drop them all.
+ let source = Scripted::hits(vec![]).with_unscored_notes(vec![
+ unscored("favourite_tea_oolong", TEA_NOTE),
+ unscored("rent", "Rent is due on the 5th."),
+ unscored("router", "The router is in the hallway cupboard."),
+ unscored("cat", "The cat eats salmon kibble."),
+ ]);
+ let lane = AutoRecall::new(source, true, None);
+ let block = lane.block_for(TEA_QUESTION).await.expect("a block");
+ assert!(block.contains(TEA_NOTE), "{block}");
+ assert!(
+ block.contains("hallway cupboard"),
+ "the first three: {block}"
+ );
+ assert!(!block.contains("salmon kibble"), "past the cap: {block}");
+}
+
+#[tokio::test]
+async fn a_scored_engines_zero_similarity_is_still_floored() {
+ let source =
+ Scripted::hits(vec![]).with_notes(vec![note("favourite_tea_oolong", TEA_NOTE, 0.0)]);
+ let lane = AutoRecall::new(source, true, None);
+ assert!(lane.block_for(TEA_QUESTION).await.is_none());
+}
+
+#[tokio::test]
+async fn a_credit_refusal_tells_the_model_why_memory_is_empty() {
+ let source = Scripted::hits(vec![]).with_refused_notes(out_of_credits);
+ let lane = AutoRecall::new(source, true, None);
+ let block = lane.block_for(TEA_QUESTION).await.expect("a refusal block");
+ assert!(block.starts_with(AUTO_RECALL_BANNER), "{block}");
+ assert!(block.contains("out of credits"), "{block}");
+}
+
+#[tokio::test]
+async fn an_unreachable_engine_is_named_not_mistaken_for_an_empty_one() {
+ let source = Scripted::hits(vec![]).with_refused_notes(unreachable);
+ let lane = AutoRecall::new(source, true, None);
+ let block = lane.block_for(TEA_QUESTION).await.expect("a refusal block");
+ assert!(block.contains("could not be reached"), "{block}");
+}
+
+#[tokio::test]
+async fn a_refusal_does_not_hide_what_the_other_leg_found() {
+ let source =
+ Scripted::hits(vec![hit("Idol: Virat Kohli", 0.9)]).with_refused_notes(out_of_credits);
+ let lane = AutoRecall::new(source, true, None);
+ let block = lane.block_for(QUESTION).await.expect("a block");
+ assert!(block.contains("Virat Kohli"), "{block}");
+}
+
+#[tokio::test]
+async fn an_ordinary_notes_failure_is_still_no_block() {
+ let source = Scripted::hits(vec![]).with_failing_notes("store locked");
+ let lane = AutoRecall::new(source, true, None);
+ assert!(lane.block_for(TEA_QUESTION).await.is_none());
+}
+
+/// An entry as a remote engine returns it from ranked recall: no score.
+fn remote_entry(key: &str, content: &str) -> MemoryEntry {
+ MemoryEntry {
+ id: key.to_string(),
+ key: key.to_string(),
+ content: content.to_string(),
+ namespace: Some(AUTO_RECALL_NOTES_NAMESPACE.to_string()),
+ category: MemoryCategory::Core,
+ timestamp: String::new(),
+ session_id: None,
+ score: None,
+ taint: MemoryTaint::Internal,
+ }
+}
+
+#[tokio::test]
+async fn from_guard_keeps_an_unscored_engines_notes() {
+ // No retrieval family: the notes come from the mandatory ranked recall,
+ // whose entries carry no score (hosted CortexDB).
+ let guard = FixedRecallProvider::guarded(vec![
+ remote_entry("favourite_tea_oolong", TEA_NOTE),
+ remote_entry("rent", "Rent is due on the 5th."),
+ ]);
+ let lane = AutoRecall::from_guard(guard);
+ assert!(lane.enabled());
+ let block = lane.block_for(TEA_QUESTION).await.expect("a block");
+ assert!(block.contains(TEA_NOTE), "{block}");
+}
diff --git a/crates/openhuman-core/src/memory/auto_recall/warm_tests.rs b/crates/openhuman-core/src/memory/auto_recall/warm_tests.rs
index fffb624ce9..77f3de58ad 100644
--- a/crates/openhuman-core/src/memory/auto_recall/warm_tests.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/warm_tests.rs
@@ -1,7 +1,6 @@
use super::*;
use crate::memory::api::error::MemoryError;
use crate::memory::api::provider::retrieval::RetrievalResponse;
-use crate::memory::api::types::NamespaceMemoryHit;
use async_trait::async_trait;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -61,7 +60,7 @@ impl AutoRecallSource for Scripted {
_namespace: &str,
_query: &str,
_limit: usize,
- ) -> Result<Vec<NamespaceMemoryHit>, MemoryError> {
+ ) -> Result<crate::memory::auto_recall::ScoredNotes, MemoryError> {
// The warm-up is one tree retrieval: that is what loads the NLP server
// and the embedder, and the notes leg needs only the second of those.
panic!("the warm-up must not read the notes namespace");
diff --git a/crates/openhuman-core/src/memory/ops/fallback.rs b/crates/openhuman-core/src/memory/ops/fallback.rs
index 3982b92bd3..3f21767e5b 100644
--- a/crates/openhuman-core/src/memory/ops/fallback.rs
+++ b/crates/openhuman-core/src/memory/ops/fallback.rs
@@ -128,13 +128,29 @@ pub(crate) async fn namespace_names(guard: &MemoryGuard) -> Result<Vec<String>,
Ok(summaries.into_iter().map(|s| s.namespace).collect())
}
-/// Ranked hits via `MemoryRecall::recall`, scoped to `namespace`.
-pub(crate) async fn recall_hits<P: MemoryRecall + ?Sized>(
+/// What [`ranked_recall`] answered: the hits, and whether the engine scored
+/// them.
+pub(crate) struct RankedRecall {
+ /// The engine's hits, in its order.
+ pub(crate) hits: Vec<NamespaceMemoryHit>,
+ /// Whether any hit carried the engine's own score. `false` for an engine
+ /// whose recall is ranked but unscored — hosted CortexDB answers no score
+ /// at all — whose hits [`entry_to_hit`] then reads as 0.0.
+ pub(crate) scored: bool,
+}
+
+/// Ranked hits via `MemoryRecall::recall`, scoped to `namespace`, and whether
+/// the engine scored them.
+///
+/// A caller that floors on similarity has to know the difference: an
+/// unscored engine's 0.0 means "no score", not "irrelevant", and flooring it
+/// drops every hit however well the engine ranked it.
+pub(crate) async fn ranked_recall<P: MemoryRecall + ?Sized>(
guard: &P,
namespace: &str,
query: &str,
limit: usize,
-) -> Result<Vec<NamespaceMemoryHit>, String> {
+) -> Result<RankedRecall, crate::memory::api::error::MemoryError> {
log::debug!(
"[memory:fallback] ranked recall via MemoryRecall::recall namespace={namespace} limit={limit}"
);
@@ -142,15 +158,30 @@ pub(crate) async fn recall_hits<P: MemoryRecall + ?Sized>(
namespace: Some(namespace.to_string()),
..Default::default()
};
- let entries = guard
- .recall(query, limit, &opts, None)
+ let entries = guard.recall(query, limit, &opts, None).await?;
+ let scored = entries.iter().any(|entry| entry.score.is_some());
+ Ok(RankedRecall {
+ hits: entries
+ .into_iter()
+ .take(limit)
+ .map(|entry| entry_to_hit(entry, namespace))
+ .collect(),
+ scored,
+ })
+}
+
+/// [`ranked_recall`]'s hits alone, with the error as text, for the RPCs that
+/// list them.
+pub(crate) async fn recall_hits<P: MemoryRecall + ?Sized>(
+ guard: &P,
+ namespace: &str,
+ query: &str,
+ limit: usize,
+) -> Result<Vec<NamespaceMemoryHit>, String> {
+ ranked_recall(guard, namespace, query, limit)
.await
- .map_err(|error| error.to_string())?;
- Ok(entries
- .into_iter()
- .take(limit)
- .map(|entry| entry_to_hit(entry, namespace))
- .collect())
+ .map(|ranked| ranked.hits)
+ .map_err(|error| error.to_string())
}
/// Read one export record back as an entry (the mandatory driver's payload
diff --git a/crates/openhuman-core/src/memory/preferences/mod.rs b/crates/openhuman-core/src/memory/preferences/mod.rs
index cd81258c9d..ef1f4365c6 100644
--- a/crates/openhuman-core/src/memory/preferences/mod.rs
+++ b/crates/openhuman-core/src/memory/preferences/mod.rs
@@ -98,9 +98,26 @@ pub(crate) async fn recall_by_vector_over(
}
// No retrieval family (a remote engine): the mandatory ranked recall
// answers, so Lane B still works instead of injecting nothing.
- None => crate::memory::ops::fallback::recall_hits(provider, namespace, query, limit)
- .await
- .map_err(|e| MemoryError::Other(anyhow::anyhow!(e)))?,
+ None => {
+ let ranked =
+ crate::memory::ops::fallback::ranked_recall(provider, namespace, query, limit)
+ .await?;
+ if !ranked.scored {
+ // An engine that ranks without scoring (hosted CortexDB) gives
+ // every hit 0.0, so no floor can tell a preference that fits
+ // the message from one that does not. Both callers inject into
+ // or judge every turn, where the engine's first hits would be
+ // noise, so this answers nothing — and says so, rather than
+ // reading as "no candidate came close".
+ log::debug!(
+ "[pref_recall] namespace={namespace} the engine ranks without scores; \
+ nothing clears a similarity floor elapsed_ms={}",
+ started.elapsed().as_millis()
+ );
+ return Ok(Vec::new());
+ }
+ ranked.hits
+ }
};
// The floor is "tunable against live data", and this line is that data:
// how close the best candidate came, whether or not it cleared. Keys and