Skip to content

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

fix(memory): move the thread window on every fold, counting by position

sanil-236ce3299025df
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
index 6c0b163d47..4e2be39d70 100644
--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
@@ -33,14 +33,16 @@ pub(crate) struct MemoryRecallSummarizer {
impl MemoryRecallSummarizer {
/// Wraps `inner` for `turn`; without a turn binding the summarizer is
- /// returned as is.
+ /// returned as is. With recall off the wrapper adds no recall, but still
+ /// moves the turn's memory window past what the fold took: the agent's
+ /// `memory` tool reads by it either way.
pub(crate) fn wrap(
inner: Box<dyn Summarizer>,
turn: Option<Arc<MemoryTurn>>,
) -> Box<dyn Summarizer> {
match turn {
- Some(turn) if turn.identity.recall => Box::new(Self { inner, turn }),
- _ => inner,
+ Some(turn) => Box::new(Self { inner, turn }),
+ None => inner,
}
}
@@ -49,13 +51,17 @@ impl MemoryRecallSummarizer {
messages: &[Message],
summary: impl std::future::Future<Output = Result<SummaryRecord>>,
) -> Result<SummaryRecord> {
- let pack = crate::memory::lifecycle::prefetch::compaction(
- &self.turn.dispatch_ctx(),
- self.turn.config.clone(),
- self.turn.identity.clone(),
- self.turn.thread_id.clone(),
- dropped_turns(messages),
- );
+ let pack = if self.turn.identity.recall {
+ crate::memory::lifecycle::prefetch::compaction(
+ &self.turn.dispatch_ctx(),
+ self.turn.config.clone(),
+ self.turn.identity.clone(),
+ self.turn.thread_id.clone(),
+ dropped_turns(messages),
+ )
+ } else {
+ None
+ };
let mut record = summary.await?;
// The folded user turns are out of the prompt now, so the turn's next
// memory read may return them.
@@ -65,6 +71,9 @@ impl MemoryRecallSummarizer {
.filter(|message| matches!(message, Message::User(_)) && !is_checkpoint(message))
.map(Message::text),
);
+ if !self.turn.identity.recall {
+ return Ok(record);
+ }
// A later compaction folds the previous checkpoint, recall included;
// keep one recall section, the current one.
strip_recalled(&mut record.summary);
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
index 583047df05..1c4f7be095 100644
--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs
@@ -125,6 +125,28 @@ async fn without_recall_the_summarizer_is_unchanged_and_its_failure_is_its_own()
assert!(failing.summarize(&dropped()).await.is_err());
}
+#[tokio::test]
+async fn with_recall_off_a_compaction_still_moves_the_memory_window() {
+ let tmp = tempfile::tempdir().unwrap();
+ let turn = bound_turn(&tmp).await;
+ let mut quiet = (*turn).clone();
+ quiet.identity.recall = false;
+ let quiet = Arc::new(quiet);
+ let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(quiet.clone()));
+ let text = summarizer
+ .summarize(&dropped())
+ .await
+ .unwrap()
+ .summary
+ .text();
+ assert!(!text.contains(RECALLED_HEADING), "no recall when it is off");
+ assert_eq!(
+ quiet.in_prompt().from_turn,
+ 2,
+ "the agent's memory tool still reads by the window"
+ );
+}
+
#[test]
fn an_earlier_recall_section_is_dropped_before_the_new_one() {
let mut summary = Message::user(format!(
diff --git a/crates/openhuman-core/src/memory/lifecycle/window.rs b/crates/openhuman-core/src/memory/lifecycle/window.rs
index 9b9057863d..bbcf2d7720 100644
--- a/crates/openhuman-core/src/memory/lifecycle/window.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/window.rs
@@ -14,21 +14,47 @@ use std::sync::Mutex;
/// advances it past the user turns it folded, so the turn's next memory read
/// can return them. It never passes the turn's own index: the message being
/// answered, and the reply being written, stay out.
+///
+/// Folded messages are counted by position, not by text, so two identical
+/// messages are two turns. The same slice folded again moves nothing, and a
+/// slice that starts where the turn's first one did (the transcript folded
+/// again from the start) is counted from the turn's starting point rather
+/// than on top of what was already counted. Both rules can only count too
+/// little, never too much: the window may stay short, never pass a turn still
+/// in the prompt.
#[derive(Debug)]
pub struct InPromptFrom {
from: AtomicU32,
+ start: u32,
ceiling: u32,
- folded: Mutex<HashSet<u64>>,
+ folds: Mutex<Folds>,
+}
+
+/// The slices a turn's compactions folded, by fingerprint.
+#[derive(Debug, Default)]
+struct Folds {
+ seen: HashSet<u64>,
+ first_head: Option<u64>,
+}
+
+fn fingerprint<'a>(texts: impl IntoIterator<Item = &'a str>) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ for text in texts {
+ text.hash(&mut hasher);
+ }
+ hasher.finish()
}
impl InPromptFrom {
/// Starts at `from`, never past `ceiling`: the turn's own user-turn index.
#[must_use]
pub fn new(from: u32, ceiling: u32) -> Self {
+ let start = from.min(ceiling);
Self {
- from: AtomicU32::new(from.min(ceiling)),
+ from: AtomicU32::new(start),
+ start,
ceiling,
- folded: Mutex::default(),
+ folds: Mutex::default(),
}
}
@@ -38,37 +64,48 @@ impl InPromptFrom {
self.from.load(Ordering::Acquire)
}
- /// Moves past the user messages a compaction folded: two memory turns (the
- /// message and its reply) for each one not folded before, so a span folded
- /// again does not count twice. Returns the new value.
+ /// Moves past the user messages one compaction folded, in transcript
+ /// order: two memory turns (the message and its reply) for each. Returns
+ /// the new value.
pub fn advance_past<I>(&self, folded_user_texts: I) -> u32
where
I: IntoIterator,
I::Item: AsRef<str>,
{
- let mut seen = self
- .folded
+ let texts: Vec<I::Item> = folded_user_texts.into_iter().collect();
+ let from = self.get();
+ let Some(first) = texts.first() else {
+ return from;
+ };
+ let mut folds = self
+ .folds
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- let fresh = folded_user_texts
- .into_iter()
- .filter(|text| {
- let mut hasher = DefaultHasher::new();
- text.as_ref().hash(&mut hasher);
- seen.insert(hasher.finish())
- })
- .count();
- let from = self.get();
- if fresh == 0 {
+ if !folds
+ .seen
+ .insert(fingerprint(texts.iter().map(AsRef::as_ref)))
+ {
return from;
}
- let step = u32::try_from(fresh).unwrap_or(u32::MAX).saturating_mul(2);
- let next = from.saturating_add(step).min(self.ceiling);
+ let head = fingerprint([first.as_ref()]);
+ let step = u32::try_from(texts.len())
+ .unwrap_or(u32::MAX)
+ .saturating_mul(2);
+ let next = match folds.first_head {
+ None => {
+ folds.first_head = Some(head);
+ from.saturating_add(step)
+ }
+ // The transcript folded again from the start of the turn.
+ Some(first_head) if first_head == head => from.max(self.start.saturating_add(step)),
+ Some(_) => from.saturating_add(step),
+ }
+ .min(self.ceiling);
self.from.store(next, Ordering::Release);
tracing::debug!(
from,
next,
- folded = fresh,
+ folded = texts.len(),
"[memory:window] compaction moved the in-prompt window"
);
next
diff --git a/crates/openhuman-core/src/memory/lifecycle/window_tests.rs b/crates/openhuman-core/src/memory/lifecycle/window_tests.rs
index f75009f3a2..8dd95fb52c 100644
--- a/crates/openhuman-core/src/memory/lifecycle/window_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/window_tests.rs
@@ -7,18 +7,40 @@ fn starts_where_the_pre_turn_step_put_it_and_never_past_the_turn() {
}
#[test]
-fn a_fold_moves_it_two_turns_per_new_user_message() {
+fn a_fold_moves_it_two_turns_per_folded_user_message() {
let window = InPromptFrom::new(6, 20);
assert_eq!(
window.advance_past(["first question", "second question"]),
10
);
assert_eq!(window.get(), 10);
- // Folding the same messages again (a retried or extended compaction)
- // moves nothing.
- assert_eq!(window.advance_past(["second question"]), 10);
- assert_eq!(window.advance_past(Vec::<String>::new()), 10);
assert_eq!(window.advance_past(["third question"]), 12);
+ assert_eq!(window.advance_past(Vec::<String>::new()), 12);
+}
+
+#[test]
+fn identical_messages_are_separate_turns() {
+ let window = InPromptFrom::new(0, 40);
+ assert_eq!(window.advance_past(["yes", "yes"]), 4);
+ // A later fold holding the same text is new turns too.
+ assert_eq!(window.advance_past(["ok", "yes"]), 8);
+}
+
+#[test]
+fn the_same_slice_folded_again_moves_nothing() {
+ let window = InPromptFrom::new(0, 40);
+ assert_eq!(window.advance_past(["a", "b"]), 4);
+ assert_eq!(window.advance_past(["c"]), 6);
+ assert_eq!(window.advance_past(["c"]), 6);
+}
+
+#[test]
+fn a_fold_from_the_start_of_the_turn_is_counted_from_there() {
+ let window = InPromptFrom::new(2, 40);
+ assert_eq!(window.advance_past(["a", "b"]), 6);
+ // The transcript folded again from its start, one message further:
+ // three messages past the turn's start, not five past the last value.
+ assert_eq!(window.advance_past(["a", "b", "c"]), 8);
}
#[test]