Skip to content

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

fix(memory): keep a free-period answer per backend, one request at a time

M3gA-Minde4224fa2f0c3
diff --git a/crates/openhuman-core/src/memory/billing.rs b/crates/openhuman-core/src/memory/billing.rs
index f60697f65b..be9bc78119 100644
--- a/crates/openhuman-core/src/memory/billing.rs
+++ b/crates/openhuman-core/src/memory/billing.rs
@@ -13,7 +13,7 @@
//! - **Anything unknown** (memory off, signed out, no transport, an error, a
//! backend without the route): not free, so nothing starts on its own.
-use std::sync::RwLock;
+use std::collections::HashMap;
use std::time::{Duration, Instant};
use crate::backend::BackendClient;
@@ -25,31 +25,19 @@ use super::engine::{self, Binding, TINYHUMANS_ENGINE};
/// changes on the order of days, so a minute keeps it to one request a minute.
pub const CACHE_TTL: Duration = Duration::from_secs(60);
-/// The last answer, per backend.
+/// The last answer for each backend. One async lock covers the lookup and the
+/// fetch on a miss, so concurrent callers (two jobs polling at once) wait for
+/// one request rather than each sending their own.
struct Answer {
- inner: RwLock<Option<(String, Instant, bool)>>,
+ inner: tokio::sync::Mutex<Option<HashMap<String, (Instant, bool)>>>,
}
impl Answer {
const fn new() -> Self {
Self {
- inner: RwLock::new(None),
+ inner: tokio::sync::Mutex::const_new(None),
}
}
-
- /// The answer for `key` when it is younger than `ttl` at `now`.
- fn get(&self, key: &str, now: Instant, ttl: Duration) -> Option<bool> {
- let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());
- guard
- .as_ref()
- .filter(|(k, at, _)| k == key && now.duration_since(*at) < ttl)
- .map(|(_, _, active)| *active)
- }
-
- fn set(&self, key: &str, now: Instant, active: bool) {
- let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
- *guard = Some((key.to_string(), now, active));
- }
}
static ANSWER: Answer = Answer::new();
@@ -110,8 +98,13 @@ where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<bool, String>>,
{
- if let Some(active) = cache.get(key, now, ttl) {
- return active;
+ let mut answers = cache.inner.lock().await;
+ let answers = answers.get_or_insert_with(HashMap::new);
+ if let Some((_, active)) = answers
+ .get(key)
+ .filter(|(at, _)| now.duration_since(*at) < ttl)
+ {
+ return *active;
}
let active = match fetch().await {
Ok(active) => active,
@@ -120,7 +113,7 @@ where
false
}
};
- cache.set(key, now, active);
+ answers.insert(key.to_string(), (now, active));
active
}
diff --git a/crates/openhuman-core/src/memory/billing_tests.rs b/crates/openhuman-core/src/memory/billing_tests.rs
index 959302b31d..b5e66067d6 100644
--- a/crates/openhuman-core/src/memory/billing_tests.rs
+++ b/crates/openhuman-core/src/memory/billing_tests.rs
@@ -68,6 +68,41 @@ async fn an_error_is_not_free_and_is_not_asked_again_at_once() {
assert_eq!(calls.load(Ordering::SeqCst), 1, "a failure is cached too");
}
+#[tokio::test]
+async fn each_backend_keeps_its_own_answer() {
+ let cache = Answer::new();
+ let base = Instant::now();
+ let calls = AtomicUsize::new(0);
+ let ask = |active: bool| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async move { Ok(active) }
+ };
+ assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, base, || ask(true)).await);
+ assert!(!active_with_cache(&cache, "https://b.test", CACHE_TTL, base, || ask(false)).await);
+ assert!(active_with_cache(&cache, "https://a.test", CACHE_TTL, base, || ask(false)).await);
+ assert_eq!(calls.load(Ordering::SeqCst), 2, "a's answer survived b's");
+}
+
+#[tokio::test]
+async fn concurrent_callers_share_one_request() {
+ let cache = Answer::new();
+ let base = Instant::now();
+ let calls = AtomicUsize::new(0);
+ let ask = || {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ Ok(true)
+ }
+ };
+ let (a, b) = tokio::join!(
+ active_with_cache(&cache, KEY, CACHE_TTL, base, ask),
+ active_with_cache(&cache, KEY, CACHE_TTL, base, ask),
+ );
+ assert!(a && b);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
#[tokio::test]
async fn an_answer_for_one_backend_is_not_reused_for_another() {
let cache = Answer::new();