Skip to content

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

fix(app_state): stop blocking every snapshot poll on a backend round trip

M3gA-Mind67592dd06f9d
diff --git a/src/openhuman/desktop/app_state/ops.rs b/src/openhuman/desktop/app_state/ops.rs
index 07a5fa0863..c2b59c29b9 100644
--- a/src/openhuman/desktop/app_state/ops.rs
+++ b/src/openhuman/desktop/app_state/ops.rs
@@ -2,6 +2,9 @@
#[path = "ops_current_user_backoff_tests.rs"]
mod current_user_backoff_tests;
#[cfg(test)]
+#[path = "ops_snapshot_latency_tests.rs"]
+mod snapshot_latency_tests;
+#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
include!("ops_auth_timeout.rs");
diff --git a/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs b/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
index e07f6ef1f8..82e923b322 100644
--- a/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
+++ b/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
@@ -25,7 +25,10 @@ use once_cell::sync::Lazy as TestLazy;
/// whole point of that test is that `fetch_current_user_cached` consults the
/// record. Kept distinct from `APP_STATE_CACHE_TEST_LOCK` because the two guard
/// different globals and nothing here writes the positive cache.
-static CURRENT_USER_FAILURE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =
+/// `pub(super)` because `ops_tests.rs` needs it too: a successful fetch calls
+/// `clear_current_user_failure`, which wipes this global, so a test that lets a
+/// real fetch complete has to serialise against the tests seeding outages here.
+pub(super) static CURRENT_USER_FAILURE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =
TestLazy::new(|| tokio::sync::Mutex::new(()));
/// Drops the seeded outage on the way out, so one test cannot leak into the next.
diff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rs
index 37097399c2..118b088b37 100644
--- a/src/openhuman/desktop/app_state/ops_part_01.rs
+++ b/src/openhuman/desktop/app_state/ops_part_01.rs
@@ -512,23 +512,34 @@ pub fn save_app_state(config: &Config, state: &StoredAppState) -> Result<(), Str
save_stored_app_state_unlocked(config, state)
}
-fn build_client() -> Result<Client, String> {
+/// One process-wide client for `GET /auth/me`, so its pooled TCP+TLS
+/// connection survives between snapshot polls instead of being handshaken
+/// again on every one.
+///
+/// `app_state_snapshot` polls this endpoint for the life of the session. A
+/// `Client` built per call gave each poll its own connection pool, so every one
+/// paid a fresh TCP connect *and* TLS handshake before the request could go out
+/// — two extra WAN round trips on top of the one the request itself costs.
+/// Measured against the production backend over a ~250ms RTT link: ~780-1420ms
+/// on a cold connection versus ~380-540ms on a reused one (#6180).
+///
+/// `reqwest::Client` is internally reference-counted and built to be shared;
+/// holding one is the only way to keep its pool.
+///
+/// The product-identity header moved to the request rather than
+/// `default_headers`, because this client now outlives
+/// [`crate::api::product::set_product_identity`] — baking the header in here
+/// would pin whichever identity happened to be installed when the first
+/// snapshot ran. `MedullaClient` reads it per request for the same reason.
+static CURRENT_USER_CLIENT: Lazy<Result<Client, String>> = Lazy::new(|| {
// Platform-appropriate TLS backend — see [`crate::openhuman::util::tls`].
crate::openhuman::util::tls::tls_client_builder()
.http1_only()
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(10))
- // `GET /auth/me` is backend traffic like any other, so it carries the
- // product identity. This client is hand-rolled rather than obtained
- // from `BackendOAuthClient`, so it inherits nothing from that path's
- // default headers — see [`crate::api::product`]. Set here rather than
- // at the one call site because every user of this builder is
- // backend-bound by construction (`resolve_base` resolves the backend
- // API URL and nothing else).
- .default_headers(crate::api::product::product_identity_headers())
.build()
.map_err(|e| format!("failed to build HTTP client: {e}"))
-}
+});
fn resolve_base(config: &Config) -> Result<Url, String> {
let base = effective_backend_api_url(&config.api_url);
@@ -545,13 +556,20 @@ async fn fetch_current_user(
config: &Config,
token: &str,
) -> Result<Option<Value>, CurrentUserFetchError> {
- let client = build_client().map_err(CurrentUserFetchError::FetchFailed)?;
+ let client = CURRENT_USER_CLIENT
+ .as_ref()
+ .map_err(|e| CurrentUserFetchError::FetchFailed(e.clone()))?;
let base = resolve_base(config).map_err(CurrentUserFetchError::FetchFailed)?;
let url = base
.join("auth/me")
.map_err(|e| CurrentUserFetchError::FetchFailed(format!("build URL failed: {e}")))?;
let response = client
.request(Method::GET, url.clone())
+ // `GET /auth/me` is backend traffic like any other, so it carries the
+ // product identity. This request is hand-rolled rather than issued
+ // through `BackendOAuthClient`, so it inherits nothing from that path's
+ // default headers — see [`crate::api::product`].
+ .headers(crate::api::product::product_identity_headers())
.header(AUTHORIZATION, bearer_authorization_value(token))
.send()
.await
diff --git a/src/openhuman/desktop/app_state/ops_part_02.rs b/src/openhuman/desktop/app_state/ops_part_02.rs
index ad48396c3e..8c016da56a 100644
--- a/src/openhuman/desktop/app_state/ops_part_02.rs
+++ b/src/openhuman/desktop/app_state/ops_part_02.rs
@@ -184,20 +184,36 @@ async fn fetch_current_user_cached(
let api_base = current_user_api_base(config);
if allow_cache {
- {
- let cache = CURRENT_USER_CACHE.lock();
- if let Some(entry) = cache.as_ref() {
- if entry.api_base == api_base
- && entry.token == token
- && entry.fetched_at.elapsed() < CURRENT_USER_REFRESH_TTL
- {
- debug!(
- "{LOG_PREFIX} using cached current user age_ms={}",
- entry.fetched_at.elapsed().as_millis()
- );
- return Ok(Some(entry.user.clone()));
- }
+ if let Some((user, age)) = cached_current_user(&api_base, token) {
+ if age < CURRENT_USER_REFRESH_TTL {
+ debug!(
+ "{LOG_PREFIX} using cached current user age_ms={}",
+ age.as_millis()
+ );
+ return Ok(Some(user));
}
+ // Stale-while-revalidate. The entry has expired, but we already
+ // know who this is — serve that and re-confirm it behind the poll
+ // instead of making the shell wait on a WAN round trip to be told
+ // the same thing. Blocking here is what put a floor of one round
+ // trip under every `app_state_snapshot` (#6180: 732 calls in 3.5h,
+ // not one of them under 500ms).
+ //
+ // This costs no freshness: the refresh is still triggered on the
+ // same cadence and by the same poll that would have blocked for it,
+ // so the data is exactly as new as before — it just lands one poll
+ // later instead of holding this one open. The snapshot keeps
+ // reporting the true age it is serving in `current_user_stale_seconds`.
+ //
+ // Only the expired-entry path revalidates in the background. With
+ // no entry at all the shell has no identity to render, so that
+ // first fetch after login still blocks, below.
+ spawn_current_user_refresh(config, token);
+ debug!(
+ "{LOG_PREFIX} serving expired current user age_ms={} while refreshing behind the poll",
+ age.as_millis()
+ );
+ return Ok(Some(user));
}
// Nothing fresh to serve, so this poll would normally go to the network
@@ -228,6 +244,101 @@ async fn fetch_current_user_cached(
}
}
+ refresh_current_user_now(config, token).await
+}
+
+/// The cached user for this identity and how old it is, if the cache holds one.
+///
+/// Reads under one lock and hands back an owned copy, so no caller holds
+/// `CURRENT_USER_CACHE` across a decision — the freshness test and the
+/// stale-while-revalidate branch below both need the same read.
+fn cached_current_user(api_base: &str, token: &str) -> Option<(Value, Duration)> {
+ let cache = CURRENT_USER_CACHE.lock();
+ let entry = cache.as_ref()?;
+ (entry.api_base == api_base && entry.token == token)
+ .then(|| (entry.user.clone(), entry.fetched_at.elapsed()))
+}
+
+/// Single-flight gate for the background refresh.
+///
+/// An async mutex held by the spawned task for its lifetime, taken with
+/// `try_lock` so a poll that finds a refresh already running simply declines to
+/// start a second one rather than queueing behind it. Same gate, same reason as
+/// [`RUNTIME_SNAPSHOT_REBUILD`]: without it every overlapping poll launches its
+/// own fetch. Using a guard rather than a flag means a panicking refresh
+/// releases the gate instead of wedging it shut for the life of the process.
+static CURRENT_USER_REFRESH_INFLIGHT: Lazy<tokio::sync::Mutex<()>> =
+ Lazy::new(|| tokio::sync::Mutex::new(()));
+
+/// Refresh the cached current user without making the caller wait for it.
+///
+/// Declines to start when the backoff window from an earlier failure is still
+/// open — a background refresh would re-pay exactly the timeout that window
+/// exists to avoid (#5624) — and when a previous poll's refresh is still in
+/// flight.
+fn spawn_current_user_refresh(config: &Config, token: &str) {
+ if let Some((error, consecutive, remaining)) =
+ suppressed_current_user_failure(&current_user_api_base(config), token)
+ {
+ // Logged here because the stale-while-revalidate return above means an
+ // outage no longer reaches the replay branch in
+ // `fetch_current_user_cached` — without this line a backend that has
+ // been down for minutes leaves no trace at all in the snapshot logs.
+ // `debug!`, not `warn!`: no request was made and nothing waited on it
+ // (#5930).
+ debug!(
+ "{LOG_PREFIX} not refreshing current user behind the poll; backend failed \
+ {consecutive}x, retrying in {}ms: {}",
+ remaining.as_millis(),
+ error.message()
+ );
+ return;
+ }
+ let gate: &'static tokio::sync::Mutex<()> = &CURRENT_USER_REFRESH_INFLIGHT;
+ let Ok(guard) = gate.try_lock() else {
+ return;
+ };
+
+ let config = config.clone();
+ let token = token.to_string();
+ tokio::spawn(async move {
+ let _guard = guard;
+ // Bounded by the same budget the blocking path spends, so a hung
+ // backend cannot leave the gate closed for longer than one window.
+ match tokio::time::timeout(
+ auth_fetch_timeout(),
+ refresh_current_user_now(&config, &token),
+ )
+ .await
+ {
+ Ok(Ok(_)) => {}
+ // The stale entry stands and the failure is recorded, so the next
+ // poll takes the backoff path. Not a failure of any user-visible
+ // operation — nothing was waiting on this.
+ Ok(Err(error)) => debug!(
+ "{LOG_PREFIX} background current user refresh failed; serving stale entry: {}",
+ error.message()
+ ),
+ Err(_) => {
+ debug!(
+ "{LOG_PREFIX} background current user refresh timed out after {}s; serving stale entry",
+ auth_fetch_timeout().as_secs()
+ );
+ note_current_user_timeout(&config, &token);
+ }
+ }
+ });
+}
+
+/// Go to the backend, then reconcile the caches and freshness stamps with what
+/// came back. The blocking half of [`fetch_current_user_cached`], split out so
+/// the background refresh runs exactly the same path rather than a parallel
+/// copy of it that could drift.
+async fn refresh_current_user_now(
+ config: &Config,
+ token: &str,
+) -> Result<Option<Value>, CurrentUserFetchError> {
+ let api_base = current_user_api_base(config);
let fetched = match fetch_current_user(config, token).await {
Ok(user) => sanitize_snapshot_user(user),
Err(error) => {
diff --git a/src/openhuman/desktop/app_state/ops_snapshot_latency_tests.rs b/src/openhuman/desktop/app_state/ops_snapshot_latency_tests.rs
new file mode 100644
index 0000000000..29d6d3dad8
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_snapshot_latency_tests.rs
@@ -0,0 +1,174 @@
+//! What one `app_state_snapshot` poll costs, and what the core can stop paying.
+//!
+//! Split out of `ops_tests.rs` for the layout gate. Kept as one file because
+//! both subjects are one measurement: #6180 reported 732 snapshot calls in
+//! ~3.5h with no call under 500ms and spikes to 1910ms, and the two tests here
+//! pin the two halves of that number the core controls.
+
+use super::tests::APP_STATE_CACHE_TEST_LOCK;
+use super::*;
+use serde_json::json;
+// Measured against the production backend over a ~250ms RTT link, one
+// `GET /auth/me` costs ~380-540ms on a warm connection and ~780-1420ms on a
+// cold one — and a 404 for a route that does not exist on the same host costs
+// the same as `/auth/me`, so the floor is the round trip itself, not the
+// endpoint. Neither number is something the core can shrink. What it can do is
+// stop paying them: not block the poll on the round trip, and not open a new
+// connection each time it makes one. One test each.
+
+/// Serve the identity we already have; re-confirm it behind the poll.
+///
+/// `fetch_current_user_cached` used to block on `GET /auth/me` the moment its
+/// entry aged past the TTL, which — with the frontend scheduling the next poll
+/// from the previous *response* — was every poll. That put a floor of one WAN
+/// round trip under every `app_state_snapshot`. The stub here answers slowly on
+/// purpose: an expired entry must come back immediately anyway, and the refresh
+/// must still land.
+#[tokio::test]
+async fn an_expired_current_user_is_served_while_it_refreshes() {
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;
+ // A successful refresh calls `clear_current_user_failure`, which wipes a
+ // global the backoff tests seed.
+ let _failure_lock = super::current_user_backoff_tests::CURRENT_USER_FAILURE_TEST_LOCK
+ .lock()
+ .await;
+ struct CacheResetGuard;
+ impl Drop for CacheResetGuard {
+ fn drop(&mut self) {
+ *CURRENT_USER_CACHE.lock() = None;
+ }
+ }
+ let _reset = CacheResetGuard;
+
+ const BACKEND_DELAY: Duration = Duration::from_millis(2000);
+
+ let app = axum::Router::new().route(
+ "/auth/me",
+ axum::routing::get(|| async move {
+ tokio::time::sleep(BACKEND_DELAY).await;
+ axum::Json(json!({ "success": true, "data": { "firstName": "from-backend" } }))
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let _ = axum::serve(listener, app).await;
+ });
+
+ let config = Config {
+ api_url: Some(format!("http://{addr}")),
+ ..Config::default()
+ };
+ // The failure record is keyed on `(api_base, token)` and this base carries a
+ // fresh ephemeral port, so no seeded outage can match it and none is seeded
+ // here — nothing to clean up, and no cross-test write.
+ *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {
+ api_base: current_user_api_base(&config),
+ token: "tok".into(),
+ fetched_at: Instant::now() - (CURRENT_USER_REFRESH_TTL + Duration::from_secs(1)),
+ user: json!({ "firstName": "from-cache" }),
+ });
+
+ let started = Instant::now();
+ let served = fetch_current_user_cached(&config, "tok", true)
+ .await
+ .expect("an expired entry is still an answer");
+ let waited = started.elapsed();
+
+ assert_eq!(
+ served.as_ref().and_then(|u| u.get("firstName")),
+ Some(&json!("from-cache")),
+ "the expired entry must be what the poll is handed"
+ );
+ assert!(
+ waited < Duration::from_millis(400),
+ "the poll waited {waited:?} on the backend; serving the entry it already \
+ had is the whole point — this is #6180's per-poll round trip"
+ );
+
+ // ...and the refresh must actually happen, or "fast" is just "never
+ // refreshes". Wait past the stub's delay for the cache to flip.
+ let refreshed = tokio::time::timeout(BACKEND_DELAY * 3, async {
+ loop {
+ let landed = CURRENT_USER_CACHE
+ .lock()
+ .as_ref()
+ .and_then(|entry| entry.user.get("firstName").cloned());
+ if landed == Some(json!("from-backend")) {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ })
+ .await;
+ assert!(
+ refreshed.is_ok(),
+ "the background refresh never replaced the stale entry; \
+ serving stale forever is not stale-while-revalidate"
+ );
+}
+
+/// Successive `/auth/me` fetches must share one TCP connection.
+///
+/// `fetch_current_user` built a fresh `reqwest::Client` per call, and a
+/// `Client` owns its connection pool — so every fetch opened a new connection
+/// and paid a TCP handshake plus a TLS handshake before the request could go
+/// out. Over a WAN link that is two extra round trips on top of the one the
+/// request costs, and it is the gap between #6180's ~500ms floor and its
+/// ~1900ms spikes.
+///
+/// Asserted on the wire, because `reqwest::Client` exposes no pool statistics:
+/// the server sees a distinct ephemeral source port for every new connection,
+/// so a reused connection is exactly one distinct peer address across N
+/// requests.
+#[tokio::test]
+async fn current_user_fetches_reuse_one_connection() {
+ use axum::extract::ConnectInfo;
+ use std::collections::BTreeSet;
+ use std::net::SocketAddr;
+ use std::sync::{Arc, Mutex as StdMutex};
+
+ type Peers = Arc<StdMutex<BTreeSet<SocketAddr>>>;
+ let peers: Peers = Arc::new(StdMutex::new(BTreeSet::new()));
+ let peers_for_route = peers.clone();
+
+ let app = axum::Router::new().route(
+ "/auth/me",
+ axum::routing::get(move |ConnectInfo(peer): ConnectInfo<SocketAddr>| {
+ let peers = peers_for_route.clone();
+ async move {
+ peers.lock().unwrap().insert(peer);
+ axum::Json(json!({ "success": true, "data": { "firstName": "steven" } }))
+ }
+ }),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let _ = axum::serve(
+ listener,
+ app.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await;
+ });
+
+ let config = Config {
+ api_url: Some(format!("http://{addr}")),
+ ..Config::default()
+ };
+
+ // Sequential, like the poll loop: each call must find the previous call's
+ // connection idle in the pool and reuse it.
+ for _ in 0..3 {
+ fetch_current_user(&config, "tok")
+ .await
+ .expect("the stub answers /auth/me");
+ }
+
+ let distinct = peers.lock().unwrap().len();
+ assert_eq!(
+ distinct, 1,
+ "three sequential /auth/me fetches opened {distinct} connections; each new \
+ one costs a TCP and a TLS handshake before the request goes out (#6180)"
+ );
+}
diff --git a/src/openhuman/desktop/app_state/ops_tests.rs b/src/openhuman/desktop/app_state/ops_tests.rs
index 107509733b..bf5c0ba442 100644
--- a/src/openhuman/desktop/app_state/ops_tests.rs
+++ b/src/openhuman/desktop/app_state/ops_tests.rs
@@ -4,7 +4,15 @@ use parking_lot::Mutex as TestMutex;
use serde_json::json;
use tempfile::tempdir;
-static APP_STATE_CACHE_TEST_LOCK: TestLazy<TestMutex<()>> = TestLazy::new(|| TestMutex::new(()));
+/// Serialises every test that reads or writes the process-global snapshot
+/// caches. A `tokio` mutex rather than a `parking_lot` one so async tests can
+/// hold it across an `.await` — sibling `ops_current_user_backoff_tests.rs`
+/// guards its own global the same way.
+///
+/// `pub(super)` for `ops_snapshot_latency_tests.rs`, which seeds the positive
+/// cache and so has to serialise against the readers here.
+pub(super) static APP_STATE_CACHE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =
+ TestLazy::new(|| tokio::sync::Mutex::new(()));
#[test]
fn sanitize_snapshot_user_drops_empty_payloads() {
@@ -142,7 +150,7 @@ fn save_and_reload_stored_app_state_round_trips() {
#[test]
fn peek_cached_current_user_identity_plucks_known_fields() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
struct CacheResetGuard;
impl Drop for CacheResetGuard {
fn drop(&mut self) {
@@ -170,7 +178,7 @@ fn peek_cached_current_user_identity_plucks_known_fields() {
#[test]
fn peek_cached_current_user_identity_returns_none_when_only_empty_fields_exist() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
struct CacheResetGuard;
impl Drop for CacheResetGuard {
fn drop(&mut self) {
@@ -203,7 +211,7 @@ impl Drop for SnapshotCacheResetGuard {
#[test]
fn runtime_snapshot_cache_hit_within_ttl() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
let _reset = SnapshotCacheResetGuard;
let dummy = build_dummy_runtime_snapshot();
@@ -224,7 +232,7 @@ fn runtime_snapshot_cache_hit_within_ttl() {
#[test]
fn runtime_snapshot_cache_miss_after_ttl() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
let _reset = SnapshotCacheResetGuard;
*RUNTIME_SNAPSHOT_CACHE.lock() = Some(CachedRuntimeSnapshot {
@@ -243,7 +251,7 @@ fn runtime_snapshot_cache_miss_after_ttl() {
#[test]
fn fresh_cached_runtime_snapshot_returns_entry_within_ttl() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
let _reset = SnapshotCacheResetGuard;
let dummy = build_dummy_runtime_snapshot();
@@ -260,7 +268,7 @@ fn fresh_cached_runtime_snapshot_returns_entry_within_ttl() {
#[test]
fn fresh_cached_runtime_snapshot_misses_when_stale_or_empty() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
let _reset = SnapshotCacheResetGuard;
let cfg = Config::default();
@@ -280,7 +288,7 @@ fn fresh_cached_runtime_snapshot_misses_when_stale_or_empty() {
#[test]
fn fresh_cached_runtime_snapshot_misses_on_config_key_mismatch() {
- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock();
+ let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();
let _reset = SnapshotCacheResetGuard;
// A fresh entry cached for one workspace must never be served to another