Skip to content

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

fix(memory): hold the refusal block to the recall budget and anchor the 403 check

Shanueeb9ad6acc66
diff --git a/crates/openhuman-core/src/memory/auto_recall/mod.rs b/crates/openhuman-core/src/memory/auto_recall/mod.rs
index b48fb4c39d..a5eb889afb 100644
--- a/crates/openhuman-core/src/memory/auto_recall/mod.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/mod.rs
@@ -257,7 +257,8 @@ impl AutoRecall {
);
// 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);
+ return refusal
+ .and_then(|refusal| refusal::render_refusal_block(refusal, self.recall_max_chars));
}
let block = render_block(&notes.hits, &tree.hits, self.recall_max_chars);
log::info!(
diff --git a/crates/openhuman-core/src/memory/auto_recall/refusal.rs b/crates/openhuman-core/src/memory/auto_recall/refusal.rs
index 411d1bfa67..6f83423487 100644
--- a/crates/openhuman-core/src/memory/auto_recall/refusal.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/refusal.rs
@@ -14,7 +14,7 @@ use crate::memory::ops::engine::{
MEMORY_UNREACHABLE_PREFIX, SESSION_EXPIRED_PREFIX,
};
-use super::AUTO_RECALL_BANNER;
+use super::{fits_within, AUTO_RECALL_BANNER};
/// Why memory could not be searched for a message.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -77,13 +77,30 @@ impl MemoryRefusal {
/// 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!(
+///
+/// It is held to `recall_max_chars` like any recall block. The reason is one
+/// sentence, so a cap it does not fit whole leaves the block out rather than
+/// cutting it.
+pub(crate) fn render_refusal_block(
+ refusal: MemoryRefusal,
+ recall_max_chars: Option<usize>,
+) -> Option<String> {
+ let block = 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()
- )
+ );
+ let chars = block.chars().count();
+ if !fits_within(0, chars, recall_max_chars) {
+ log::debug!(
+ "[auto_recall] refusal block omitted: {chars} chars would exceed \
+ recall_max_chars={recall_max_chars:?} refusal={}",
+ refusal.label()
+ );
+ return None;
+ }
+ Some(block)
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs b/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs
index 45b3f9a3ff..b4ab1ebae5 100644
--- a/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/refusal_tests.rs
@@ -62,7 +62,7 @@ fn an_ordinary_failure_is_not_a_refusal() {
#[test]
fn the_refusal_block_heads_the_reason_with_the_usual_banner() {
- let block = render_refusal_block(MemoryRefusal::OutOfCredits);
+ let block = render_refusal_block(MemoryRefusal::OutOfCredits, None).expect("no cap");
assert!(block.starts_with(AUTO_RECALL_BANNER), "{block}");
assert!(block.contains("out of credits"), "{block}");
assert!(
@@ -70,3 +70,24 @@ fn the_refusal_block_heads_the_reason_with_the_usual_banner() {
"{block}"
);
}
+
+#[test]
+fn the_refusal_block_is_held_to_the_recall_budget() {
+ for refusal in [
+ MemoryRefusal::OutOfCredits,
+ MemoryRefusal::SessionExpired,
+ MemoryRefusal::Forbidden,
+ MemoryRefusal::Unavailable,
+ ] {
+ let whole = render_refusal_block(refusal, None).expect("no cap");
+ let chars = whole.chars().count();
+ // A cap the block fits exactly keeps it whole.
+ assert_eq!(
+ render_refusal_block(refusal, Some(chars)).as_deref(),
+ Some(whole.as_str())
+ );
+ // One character short leaves it out: a cut reason would mislead.
+ assert_eq!(render_refusal_block(refusal, Some(chars - 1)), None);
+ assert_eq!(render_refusal_block(refusal, Some(0)), None);
+ }
+}
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
index 9b38b4902f..1aad6e7f3c 100644
--- a/crates/openhuman-core/src/memory/auto_recall/unscored_lane_tests.rs
+++ b/crates/openhuman-core/src/memory/auto_recall/unscored_lane_tests.rs
@@ -73,6 +73,26 @@ async fn a_credit_refusal_tells_the_model_why_memory_is_empty() {
assert!(block.contains("out of credits"), "{block}");
}
+#[tokio::test]
+async fn a_refusal_block_stays_within_the_guards_recall_budget() {
+ let tight = AutoRecall::new(
+ Scripted::hits(vec![]).with_refused_notes(out_of_credits),
+ true,
+ Some(40),
+ );
+ assert!(tight.block_for(TEA_QUESTION).await.is_none());
+ let roomy = AutoRecall::new(
+ Scripted::hits(vec![]).with_refused_notes(out_of_credits),
+ true,
+ Some(4_000),
+ );
+ let block = roomy
+ .block_for(TEA_QUESTION)
+ .await
+ .expect("a refusal 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);
diff --git a/crates/openhuman-core/src/memory/ops/engine.rs b/crates/openhuman-core/src/memory/ops/engine.rs
index b72d34c437..09d0f98759 100644
--- a/crates/openhuman-core/src/memory/ops/engine.rs
+++ b/crates/openhuman-core/src/memory/ops/engine.rs
@@ -236,10 +236,28 @@ pub fn classify_memory_error(error: &crate::memory::api::error::MemoryError) ->
}
/// Whether an `Unauthorized` message is a 403: the credential was valid and
-/// refused, as opposed to missing or lapsed. The remote adapters render the
-/// status into the message (`(HTTP 403 Forbidden)`).
+/// refused, as opposed to missing or lapsed. Both remote adapters render the
+/// status they received ahead of any body text, as `(HTTP 403 Forbidden)`, so
+/// only the message's first status counts: a 401 whose body quotes an
+/// upstream 403 is still a lapsed session.
fn is_forbidden(message: &str) -> bool {
- message.contains("(HTTP 403")
+ message
+ .find("(HTTP ")
+ .is_some_and(|at| message[at..].starts_with("(HTTP 403 Forbidden)"))
+}
+
+/// The `MemoryError::Unauthorized` rendering inside `message`, from after its
+/// `unauthorized: ` class tag: at the start, or after a caller's `context: `
+/// wrapper. The string path reads a 403 only here, the way the typed path
+/// reads it only in `Unauthorized`.
+fn unauthorized_clause(message: &str) -> Option<&str> {
+ const CLASS: &str = "unauthorized: ";
+ const WRAPPED: &str = ": unauthorized: ";
+ message.strip_prefix(CLASS).or_else(|| {
+ message
+ .find(WRAPPED)
+ .map(|at| &message[at + WRAPPED.len()..])
+ })
}
/// [`classify_engine_error`] for a failure that is already a string.
@@ -256,7 +274,7 @@ pub fn classify_engine_message(message: &str) -> String {
if message.contains("USER_INSUFFICIENT_CREDITS") {
return format!("{INSUFFICIENT_CREDITS_PREFIX} the memory engine is out of credits");
}
- if is_forbidden(message) {
+ if unauthorized_clause(message).is_some_and(is_forbidden) {
return format!("{MEMORY_FORBIDDEN_PREFIX} the memory engine refused this credential");
}
if message.contains(SESSION_EXPIRED_PREFIX)
diff --git a/crates/openhuman-core/src/memory/ops/engine_tests.rs b/crates/openhuman-core/src/memory/ops/engine_tests.rs
index aeb302ea31..33f7b6d0ac 100644
--- a/crates/openhuman-core/src/memory/ops/engine_tests.rs
+++ b/crates/openhuman-core/src/memory/ops/engine_tests.rs
@@ -170,6 +170,50 @@ fn a_403_is_a_refused_credential_not_an_expired_session() {
assert!(!text.contains(SESSION_EXPIRED_PREFIX), "{text}");
}
+#[test]
+fn a_403_counts_only_as_the_unauthorized_errors_own_status() {
+ // Each adapter's rendering of a 403: hosted with the backend's code,
+ // hosted without one (its default code for a 403 is `UNAUTHORIZED`), and
+ // the direct wire. Typed, as text, and behind a caller's context.
+ for refused in [
+ "[FORBIDDEN] memory API memory/recall on host (HTTP 403 Forbidden): API key is \
+ missing the required scope: memory",
+ "[UNAUTHORIZED] memory API memory/recall on host (HTTP 403 Forbidden): Forbidden — \
+ the session expired or the API key was rejected; re-authenticate",
+ "memory API memory/recall on host: the configured credential was rejected (HTTP 403 \
+ Forbidden) — check the API key",
+ ] {
+ let typed = classify_engine_error(&anyhow::Error::new(MemoryError::Unauthorized(
+ refused.into(),
+ )));
+ assert!(typed.starts_with(MEMORY_FORBIDDEN_PREFIX), "{typed}");
+ for text in [
+ format!("unauthorized: {refused}"),
+ format!("memory recall failed: unauthorized: {refused}"),
+ ] {
+ let classified = classify_engine_message(&text);
+ assert!(
+ classified.starts_with(MEMORY_FORBIDDEN_PREFIX),
+ "{text} -> {classified}"
+ );
+ }
+ }
+ // A lapsed session whose body quotes an upstream 403 is still lapsed: the
+ // adapter's own status comes first.
+ let lapsed = "[UNAUTHORIZED] memory API memory/recall on host (HTTP 401 Unauthorized): \
+ upstream answered (HTTP 403 Forbidden) — the session expired or the API \
+ key was rejected; re-authenticate";
+ let typed = classify_engine_error(&anyhow::Error::new(MemoryError::Unauthorized(
+ lapsed.into(),
+ )));
+ assert!(typed.starts_with(SESSION_EXPIRED_PREFIX), "{typed}");
+ let text = classify_engine_message(&format!("unauthorized: {lapsed}"));
+ assert!(text.starts_with(SESSION_EXPIRED_PREFIX), "{text}");
+ // Another error class that quotes a 403 is not a refused credential.
+ let other = "invalid input: the upstream answered (HTTP 403 Forbidden)";
+ assert_eq!(classify_engine_message(other), other);
+}
+
#[test]
fn an_engine_that_cannot_serve_now_is_unreachable() {
for error in [
diff --git a/tests/memory_hosted_surface_e2e.rs b/tests/memory_hosted_surface_e2e.rs
index a097346809..978aadab0f 100644
--- a/tests/memory_hosted_surface_e2e.rs
+++ b/tests/memory_hosted_surface_e2e.rs
@@ -119,6 +119,12 @@ fn a_refused_credential_and_an_outage_have_their_own_names() {
});
}
+/// The handler answers from the host log when the driver keeps no run log
+/// (`SourceSync` is absent), for a driver that serves the `Sources` sink
+/// without owning pipelines. This fixture builds no `CoreContext`, so the
+/// registry's capability gate stays open and the handler is reachable here.
+/// In the app, an engine without `Sources` (hosted among them) has no
+/// `memory_sources.*` methods at all, and Brain gates the panel on that.
#[test]
fn sync_history_answers_from_the_host_log_on_an_engine_without_one() {
run_on_big_stack("hosted-sync-history", || async {