Skip to content

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

feat(memory): one check for whether memory work is free right now

M3gA-Mindd1c5dadda570
diff --git a/crates/openhuman-core/src/memory/billing.rs b/crates/openhuman-core/src/memory/billing.rs
new file mode 100644
index 0000000000..f60697f65b
--- /dev/null
+++ b/crates/openhuman-core/src/memory/billing.rs
@@ -0,0 +1,129 @@
+//! Whether memory work is free for the user right now.
+//!
+//! Background memory jobs that write a user's whole memory again (moving it
+//! into a new layout, importing a local store) start on their own only when
+//! that costs the user nothing; otherwise they wait for the user to start them.
+//! [`free_period_active`] is the one check every such job asks:
+//!
+//! - **Not the hosted engine** (self-hosted CortexDB, or a host's own engine):
+//! always free here, because no TinyHumans credit is spent.
+//! - **The hosted `tinyhumans` engine**: free only while the backend's memory
+//! free period is on (`GET /memory/free-period`, through the backend
+//! transport). The answer is cached for [`CACHE_TTL`] per backend.
+//! - **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::time::{Duration, Instant};
+
+use crate::backend::BackendClient;
+use crate::config::Config;
+
+use super::engine::{self, Binding, TINYHUMANS_ENGINE};
+
+/// How long an answer is reused. A job polls between batches; the period
+/// 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.
+struct Answer {
+ inner: RwLock<Option<(String, Instant, bool)>>,
+}
+
+impl Answer {
+ const fn new() -> Self {
+ Self {
+ inner: RwLock::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();
+
+/// Whether memory work is free for the user right now. See the module docs.
+pub async fn free_period_active(config: &Config) -> bool {
+ let engine_id = match engine::resolve(config) {
+ Binding::On(bound) => bound.id,
+ Binding::Off { .. } => return false,
+ };
+ if engine_id != TINYHUMANS_ENGINE {
+ return true;
+ }
+ let Ok(backend) = crate::backend::require_base_url(&config.api_url) else {
+ return false;
+ };
+ active_with_cache(&ANSWER, &backend, CACHE_TTL, Instant::now(), || {
+ fetch(config, &backend)
+ })
+ .await
+}
+
+/// Asks the backend whether its memory free period is on.
+async fn fetch(config: &Config, backend: &str) -> Result<bool, String> {
+ let credential =
+ crate::security::credentials::session_support::resolve_backend_credential(config)?;
+ let client = BackendClient::new(backend).map_err(|e| format!("{e:#}"))?;
+ let data = client
+ .authed_json(
+ &credential,
+ reqwest::Method::GET,
+ "/memory/free-period",
+ None,
+ )
+ .await
+ .map_err(crate::backend::flatten_authed_error)?;
+ parse_active(&data)
+}
+
+/// `active` from the route's answer; anything else is an error.
+fn parse_active(data: &serde_json::Value) -> Result<bool, String> {
+ data.get("active")
+ .and_then(serde_json::Value::as_bool)
+ .ok_or_else(|| "free-period answer has no boolean `active`".to_string())
+}
+
+/// The cached answer for `key`, else `fetch`'s, with a failure read as not
+/// free. Failures are cached too, so a backend without the route is asked
+/// once a minute, not once a batch.
+async fn active_with_cache<F, Fut>(
+ cache: &Answer,
+ key: &str,
+ ttl: Duration,
+ now: Instant,
+ fetch: F,
+) -> bool
+where
+ F: FnOnce() -> Fut,
+ Fut: std::future::Future<Output = Result<bool, String>>,
+{
+ if let Some(active) = cache.get(key, now, ttl) {
+ return active;
+ }
+ let active = match fetch().await {
+ Ok(active) => active,
+ Err(error) => {
+ tracing::debug!(%error, "[memory:billing] free period unknown; treating as not free");
+ false
+ }
+ };
+ cache.set(key, now, active);
+ active
+}
+
+#[cfg(test)]
+#[path = "billing_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/billing_tests.rs b/crates/openhuman-core/src/memory/billing_tests.rs
new file mode 100644
index 0000000000..54bb7591e3
--- /dev/null
+++ b/crates/openhuman-core/src/memory/billing_tests.rs
@@ -0,0 +1,156 @@
+use super::*;
+use serde_json::json;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+const KEY: &str = "https://backend.test";
+
+#[test]
+fn parse_active_reads_the_flag_and_refuses_anything_else() {
+ assert_eq!(
+ parse_active(&json!({"active": true, "until": "x"})),
+ Ok(true)
+ );
+ assert_eq!(
+ parse_active(&json!({"active": false, "until": null})),
+ Ok(false)
+ );
+ assert!(parse_active(&json!({"active": "yes"})).is_err());
+ assert!(parse_active(&json!({})).is_err());
+}
+
+#[tokio::test]
+async fn an_answer_is_reused_within_the_ttl_and_asked_again_after() {
+ 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, KEY, CACHE_TTL, base, || ask(true)).await);
+ assert!(
+ active_with_cache(
+ &cache,
+ KEY,
+ CACHE_TTL,
+ base + Duration::from_secs(30),
+ || ask(false)
+ )
+ .await,
+ "still the cached answer"
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert!(
+ !active_with_cache(
+ &cache,
+ KEY,
+ CACHE_TTL,
+ base + Duration::from_secs(61),
+ || ask(false)
+ )
+ .await,
+ "asked again once stale"
+ );
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+}
+
+#[tokio::test]
+async fn an_error_is_not_free_and_is_not_asked_again_at_once() {
+ let cache = Answer::new();
+ let base = Instant::now();
+ let calls = AtomicUsize::new(0);
+ let failing = || {
+ calls.fetch_add(1, Ordering::SeqCst);
+ async { Err::<bool, _>("GET /memory/free-period failed (404 Not Found)".to_string()) }
+ };
+ assert!(!active_with_cache(&cache, KEY, CACHE_TTL, base, failing).await);
+ assert!(!active_with_cache(&cache, KEY, CACHE_TTL, base, failing).await);
+ assert_eq!(calls.load(Ordering::SeqCst), 1, "a failure is cached too");
+}
+
+#[tokio::test]
+async fn an_answer_for_one_backend_is_not_reused_for_another() {
+ let cache = Answer::new();
+ let base = Instant::now();
+ assert!(active_with_cache(&cache, KEY, CACHE_TTL, base, || async { Ok(true) }).await);
+ assert!(
+ !active_with_cache(&cache, "https://other.test", CACHE_TTL, base, || async {
+ Ok(false)
+ })
+ .await
+ );
+}
+
+#[tokio::test]
+async fn memory_off_is_not_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = crate::memory::test_fixtures::config_in(&tmp);
+ config.memory.engine = String::new();
+ assert!(!free_period_active(&config).await);
+}
+
+#[tokio::test]
+async fn an_engine_other_than_the_hosted_one_is_always_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = crate::memory::test_fixtures::config_in(&tmp);
+ crate::memory::test_fixtures::bind_reference(&config);
+ assert!(free_period_active(&config).await);
+}
+
+fn keyed_config(tmp: &tempfile::TempDir) -> Config {
+ let mut config = crate::memory::test_fixtures::config_in(tmp);
+ config.secrets.encrypt = false;
+ crate::security::credentials::api_key::store_api_key(&config, "th_test_key").unwrap();
+ config
+}
+
+async fn backend_answering(status: u16, body: serde_json::Value) -> wiremock::MockServer {
+ use wiremock::matchers::{method, path};
+ let server = wiremock::MockServer::start().await;
+ wiremock::Mock::given(method("GET"))
+ .and(path("/memory/free-period"))
+ .respond_with(wiremock::ResponseTemplate::new(status).set_body_json(body))
+ .mount(&server)
+ .await;
+ server
+}
+
+#[tokio::test]
+async fn the_backend_says_the_period_is_on() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = keyed_config(&tmp);
+ let server = backend_answering(
+ 200,
+ json!({"success": true, "data": {"active": true, "until": "2026-11-06T00:00:00.000Z"}}),
+ )
+ .await;
+ assert_eq!(fetch(&config, &server.uri()).await, Ok(true));
+}
+
+#[tokio::test]
+async fn the_backend_says_the_period_is_off() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = keyed_config(&tmp);
+ let server = backend_answering(
+ 200,
+ json!({"success": true, "data": {"active": false, "until": null}}),
+ )
+ .await;
+ assert_eq!(fetch(&config, &server.uri()).await, Ok(false));
+}
+
+#[tokio::test]
+async fn a_backend_without_the_route_is_an_error_read_as_not_free() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = keyed_config(&tmp);
+ let server = backend_answering(404, json!({"success": false, "error": "Not Found"})).await;
+ assert!(fetch(&config, &server.uri()).await.is_err());
+ let cache = Answer::new();
+ let uri = server.uri();
+ assert!(
+ !active_with_cache(&cache, &uri, CACHE_TTL, Instant::now(), || fetch(
+ &config, &uri
+ ))
+ .await
+ );
+}
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index cdf7932183..0a9cad0311 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -20,6 +20,7 @@
//! Chat thread persistence is not memory: it lives in [`crate::threads::store`].
pub mod backfill;
+pub mod billing;
pub mod brain;
pub mod bus;
pub mod channels;