The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(app_state): back off the current-user fetch when the backend is unreachable\n\n`fetch_current_user_cached` cached successes and nothing else. The `?` on the\nfetch returned early, so the cache write below it never ran on failure, and on a\ntimeout the whole future was dropped mid-flight before it could run at all. The\nclient therefore kept no memory that the backend had just failed.\n\nThe cost of that is arithmetic rather than bad luck. The frontend polls\n`app_state_snapshot` about every 5s, the caller wraps each attempt in a 5s\n`AUTH_FETCH_TIMEOUT`, and the positive-cache TTL is also 5s — equal to the\ntimeout, so an attempt that times out can never be deduped by the cache that\nfollows it. While the backend is unreachable essentially every poll re-attempts\nthe fetch and re-pays the full five seconds, which is what 51 timeouts in one\nsession looks like.\n\nAdd a negative counterpart to `CURRENT_USER_CACHE`: the last availability\nfailure, keyed on `(api_base, token)` exactly as the positive cache is, with a\nwindow that doubles from 10s and saturates at 60s. Inside that window the fetch\nreplays the recorded error instead of going to the network, so the caller\nreaches its existing stored-snapshot fallback in microseconds rather than five\nseconds. The caller itself is unchanged.\n\nThree details are load-bearing:\n\n- The timeout is applied by the caller, around the whole of\n `fetch_current_user_cached`, so recording only on that function's error path\n would miss the case this issue is actually about. The two timeout arms record\n too.\n- An auth rejection is never recorded. It is the backend answering, in time,\n that the token is no good; it drives the deferred-session cleanup at the\n snapshot caller, and replaying it from a cache would delay that cleanup or\n hand the caller a variant the backend never produced.\n- The record is cleared on every success and on sign-out. A record outliving\n its cause is the failure mode that matters here — it would strand the app on\n the stored snapshot after the backend had already recovered.\n\nThe first backoff step is deliberately larger than both the fetch timeout and\nthe poll interval; a shorter one would let the next poll find the window already\nclosed and pay the timeout again, which is the bug rather than the fix. A test\npins that relationship.\n\nEight tests cover the window, the key, the rejection carve-out, the clear, and\nthe widening. One of them drives `fetch_current_user_cached` itself against a\nclosed loopback port: with the probe removed it returns\n`request failed: error sending request for url (http://127.0.0.1:9/auth/me)`\ninstead of the seeded marker, which is the same error string this issue reports.\n
M3gA-Mind0f72eb9eef06
diff --git a/src/openhuman/desktop/app_state/ops.rs b/src/openhuman/desktop/app_state/ops.rsindex d1b9626b35..f90c39bade 100644--- a/src/openhuman/desktop/app_state/ops.rs+++ b/src/openhuman/desktop/app_state/ops.rs@@ -44,12 +44,35 @@ const CURRENT_USER_REFRESH_TTL: Duration = Duration::from_secs(5);// calls even though inference itself was idle).const RUNTIME_SNAPSHOT_TTL: Duration = Duration::from_secs(10);const AUTH_FETCH_TIMEOUT: Duration = Duration::from_secs(5);+/// First backoff step after the backend fails to answer `auth_get_me`.+///+/// Deliberately larger than both [`AUTH_FETCH_TIMEOUT`] and the frontend's+/// ~5s `app_state_snapshot` poll. That relationship is the whole point of the+/// backoff: with a shorter step, the next poll would find the window already+/// expired and pay the full timeout again, which is exactly the treadmill this+/// exists to stop (#5624 — 51 timeouts in one session, ~5s each).+const CURRENT_USER_BACKOFF_BASE: Duration = Duration::from_secs(10);+/// Ceiling on that backoff. Modest on purpose: this window is time during which+/// a recovered backend still will not be noticed, so it trades a bounded amount+/// of staleness for not stalling every poll. At the cap a 5s poll loop attempts+/// roughly one live fetch per twelve polls instead of one per poll.+const CURRENT_USER_BACKOFF_MAX: Duration = Duration::from_secs(60);const RUNTIME_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);const SNAPSHOT_SUB_OP_TIMEOUT: Duration = Duration::from_secs(5);const PENDING_BACKEND_VALIDATION_FIELD: &str = "pendingBackendValidation";const AUTH_ME_REVALIDATION_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];static APP_STATE_FILE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));static CURRENT_USER_CACHE: Lazy<Mutex<Option<CachedCurrentUser>>> = Lazy::new(|| Mutex::new(None));+/// Negative counterpart to [`CURRENT_USER_CACHE`]: the last *availability*+/// failure against `auth_get_me`, so a client whose backend is unreachable stops+/// re-paying [`AUTH_FETCH_TIMEOUT`] on every snapshot poll.+///+/// Kept separate from the positive cache rather than folded into it because the+/// two have different lifetimes and different readers —+/// [`peek_cached_current_user_identity`] must keep serving the last known+/// identity throughout an outage, and it reads only the positive cache.+static CURRENT_USER_FAILURE: Lazy<Mutex<Option<CurrentUserFailure>>> =+ Lazy::new(|| Mutex::new(None));static RUNTIME_SNAPSHOT_CACHE: Lazy<Mutex<Option<CachedRuntimeSnapshot>>> =Lazy::new(|| Mutex::new(None));/// Single-flight gate for the runtime-snapshot rebuild. Concurrent callers whose@@ -117,6 +140,131 @@ impl CurrentUserFetchError {}}+impl CurrentUserFetchError {+ /// Whether this failure says the *backend was not reachable or not healthy*,+ /// as opposed to saying something about our credentials.+ ///+ /// Only these are worth backing off. A [`Rejected`](Self::Rejected) is the+ /// backend answering, in time, that the token is no good — it drives the+ /// deferred-session cleanup at the snapshot caller, and replaying it from a+ /// cache would either delay that cleanup or, worse, hand the caller a+ /// different variant than the one the backend actually produced.+ fn is_availability_failure(&self) -> bool {+ match self {+ CurrentUserFetchError::TransientResponse(_) | CurrentUserFetchError::FetchFailed(_) => {+ true+ }+ CurrentUserFetchError::Rejected(_) => false,+ }+ }+}++/// The last availability failure against `auth_get_me`, keyed the same way the+/// positive cache is so that changing environment or signing in as someone else+/// bypasses it rather than inheriting someone else's outage.+#[derive(Debug, Clone)]+struct CurrentUserFailure {+ api_base: String,+ token: String,+ failed_at: Instant,+ /// Failures in an unbroken run, counted from 1. Drives the backoff width.+ consecutive: u32,+ /// Replayed verbatim while the window is open, so a caller that matches on+ /// the variant sees what the backend really produced.+ error: CurrentUserFetchError,+}++/// How long a run of `consecutive` failures suppresses the next live attempt.+///+/// Doubles from [`CURRENT_USER_BACKOFF_BASE`] and saturates at+/// [`CURRENT_USER_BACKOFF_MAX`]. `consecutive` is 1-based; 0 is treated as 1 so+/// the function has no surprising zero-length window.+fn current_user_backoff(consecutive: u32) -> Duration {+ let steps = consecutive.saturating_sub(1).min(16);+ CURRENT_USER_BACKOFF_BASE+ .saturating_mul(2u32.saturating_pow(steps))+ .min(CURRENT_USER_BACKOFF_MAX)+}++/// The recorded failure for `(api_base, token)` if its backoff window is still+/// open, in which case the caller should return it instead of going to the+/// network.+fn suppressed_current_user_failure(+ api_base: &str,+ token: &str,+) -> Option<(CurrentUserFetchError, u32, Duration)> {+ let failure = CURRENT_USER_FAILURE.lock();+ let entry = failure.as_ref()?;+ if entry.api_base != api_base || entry.token != token {+ return None;+ }+ let window = current_user_backoff(entry.consecutive);+ let elapsed = entry.failed_at.elapsed();+ (elapsed < window).then(|| (entry.error.clone(), entry.consecutive, window - elapsed))+}++/// Record an availability failure, extending the run when it is the same+/// `(api_base, token)` and starting a new one when it is not.+///+/// A [`CurrentUserFetchError::Rejected`] is ignored — see+/// [`CurrentUserFetchError::is_availability_failure`].+fn record_current_user_failure(api_base: &str, token: &str, error: CurrentUserFetchError) {+ if !error.is_availability_failure() {+ return;+ }+ let mut failure = CURRENT_USER_FAILURE.lock();+ let consecutive = match failure.as_ref() {+ Some(entry) if entry.api_base == api_base && entry.token == token => {+ entry.consecutive.saturating_add(1)+ }+ _ => 1,+ };+ *failure = Some(CurrentUserFailure {+ api_base: api_base.to_string(),+ token: token.to_string(),+ failed_at: Instant::now(),+ consecutive,+ error,+ });+}++/// Forget any recorded failure, so the next poll goes straight to the network.+///+/// Called on every success and on sign-out. Missing either one is the failure+/// mode that matters here: a stale record outliving its cause keeps the app on+/// the stored snapshot after the backend has already come back.+fn clear_current_user_failure() {+ *CURRENT_USER_FAILURE.lock() = None;+}++/// Record the timeout path's failure.+///+/// The timeout is applied by the snapshot caller, wrapping the whole of+/// `fetch_current_user_cached`, so when it fires that future is **dropped+/// mid-flight** and nothing inside it runs — including the failure recording on+/// its error path. Without this call the backoff would never engage for the one+/// case #5624 is actually about, which is timeouts rather than returned errors.+fn note_current_user_timeout(config: &Config, token: &str) {+ record_current_user_failure(+ ¤t_user_api_base(config),+ token,+ CurrentUserFetchError::FetchFailed(format!(+ "request timed out after {}s",+ AUTH_FETCH_TIMEOUT.as_secs()+ )),+ );+}++/// The cache key both the positive and negative current-user caches are keyed+/// on. Factored out so the snapshot caller, which records the timeout path, and+/// the fetch itself cannot drift apart on how the base URL is normalised.+fn current_user_api_base(config: &Config) -> String {+ effective_backend_api_url(&config.api_url)+ .trim()+ .trim_end_matches('/')+ .to_string()+}+#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "camelCase")]pub struct StoredOnboardingTasks {@@ -650,6 +798,7 @@ async fn clear_deferred_session_after_backend_rejection(});*CURRENT_USER_CACHE.lock() = None;+ clear_current_user_failure();crate::openhuman::cron::scheduler_gate::set_signed_out(true);match crate::openhuman::config::default_root_openhuman_dir() {@@ -690,28 +839,53 @@ async fn fetch_current_user_cached(token: &str,allow_cache: bool,) -> Result<Option<Value>, CurrentUserFetchError> {- let api_base = effective_backend_api_url(&config.api_url)- .trim()- .trim_end_matches('/')- .to_string();+ 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()));+ {+ 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()));+ }}}++ // Nothing fresh to serve, so this poll would normally go to the network+ // — and if the backend is unreachable it would sit there for the full+ // `AUTH_FETCH_TIMEOUT` before the caller gives up and uses the stored+ // snapshot anyway. Replay the recorded failure instead while its window+ // is open. The caller's behaviour is unchanged (it already falls back on+ // `Err`); it just does so in microseconds. Gated on `allow_cache` for+ // the same reason the positive cache is: a pending-backend-validation+ // pass is explicitly asking for a live answer.+ if let Some((error, consecutive, remaining)) =+ suppressed_current_user_failure(&api_base, token)+ {+ debug!(+ "{LOG_PREFIX} skipping current user refresh; backend failed {consecutive}x, \+ retrying in {}ms",+ remaining.as_millis()+ );+ return Err(error);+ }}- let fetched = sanitize_snapshot_user(fetch_current_user(config, token).await?);+ let fetched = match fetch_current_user(config, token).await {+ Ok(user) => sanitize_snapshot_user(user),+ Err(error) => {+ record_current_user_failure(&api_base, token, error.clone());+ return Err(error);+ }+ };+ clear_current_user_failure();let mut cache = CURRENT_USER_CACHE.lock();match fetched.clone() {@@ -1071,6 +1245,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {"{LOG_PREFIX} pending current user fetch timed out after {}s; keeping stored pending session for retry",AUTH_FETCH_TIMEOUT.as_secs());+ note_current_user_timeout(&config, &token);snapshot_current_user_result(stored_user.clone())}Err(_) => {@@ -1078,6 +1253,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {"{LOG_PREFIX} current user fetch timed out after {}s; using stored snapshot fallback",AUTH_FETCH_TIMEOUT.as_secs());+ note_current_user_timeout(&config, &token);snapshot_current_user_result(stored_user.clone())}}diff --git a/src/openhuman/desktop/app_state/ops_tests.rs b/src/openhuman/desktop/app_state/ops_tests.rsindex 4042e79172..37ee5cba1b 100644--- a/src/openhuman/desktop/app_state/ops_tests.rs+++ b/src/openhuman/desktop/app_state/ops_tests.rs@@ -401,3 +401,274 @@ async fn current_user_fetch_carries_the_product_identity() {crate::api::product::reset_product_identity_for_test();}++// ── Current-user failure backoff (#5624) ────────────────────────────────────+//+// While the backend is unreachable, every `app_state_snapshot` poll used to+// re-attempt `auth_get_me` and re-pay the full `AUTH_FETCH_TIMEOUT`, because a+// failure was never recorded anywhere: `fetch_current_user_cached` cached only+// successes, and on a timeout its future was dropped before it could cache+// anything at all. 51 timeouts in one session is what that costs at a 5s poll+// cadence. These cover the record, the window, and the fact that the fetch+// actually consults it.++/// Serializes the tests that seed `CURRENT_USER_FAILURE`.+///+/// Async-aware rather than the `parking_lot` guard the positive-cache tests+/// use, because one of these tests has to hold it across an `.await` — the+/// 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<()>> =+ TestLazy::new(|| tokio::sync::Mutex::new(()));++/// Drops the seeded outage on the way out, so one test cannot leak into the next.+struct CurrentUserFailureResetGuard;++impl Drop for CurrentUserFailureResetGuard {+ fn drop(&mut self) {+ clear_current_user_failure();+ }+}++/// Overwrite the failure record with one that failed `age` ago, so a test can+/// sit either side of a backoff window without sleeping.+fn seed_current_user_failure(+ api_base: &str,+ token: &str,+ consecutive: u32,+ age: Duration,+ error: CurrentUserFetchError,+) {+ *CURRENT_USER_FAILURE.lock() = Some(CurrentUserFailure {+ api_base: api_base.to_string(),+ token: token.to_string(),+ failed_at: Instant::now()+ .checked_sub(age)+ .expect("test ages are far smaller than process uptime"),+ consecutive,+ error,+ });+}++#[test]+fn current_user_backoff_doubles_and_saturates_at_the_cap() {+ assert_eq!(current_user_backoff(1), CURRENT_USER_BACKOFF_BASE);+ assert_eq!(current_user_backoff(2), CURRENT_USER_BACKOFF_BASE * 2);+ assert_eq!(current_user_backoff(3), CURRENT_USER_BACKOFF_BASE * 4);+ assert_eq!(current_user_backoff(u32::MAX), CURRENT_USER_BACKOFF_MAX);+ // 0 is not a state the recorder can produce, but the function must not+ // answer it with a zero-length window.+ assert_eq!(current_user_backoff(0), CURRENT_USER_BACKOFF_BASE);++ let mut previous = Duration::ZERO;+ for consecutive in 1..=12 {+ let window = current_user_backoff(consecutive);+ assert!(+ window >= previous,+ "backoff must never narrow as failures accumulate: {consecutive} gave {window:?} after {previous:?}"+ );+ assert!(+ window <= CURRENT_USER_BACKOFF_MAX,+ "backoff must stay under the cap: {consecutive} gave {window:?}"+ );+ previous = window;+ }+}++#[test]+fn the_first_backoff_step_outlasts_both_the_fetch_timeout_and_the_poll() {+ // This is the property that actually stops the treadmill, and the one a+ // future constant change could silently break. A first step shorter than+ // the fetch timeout means the next poll finds the window already closed and+ // pays the full 5s again — which is the bug, not the fix. It must also+ // outlast the positive-cache TTL, because that TTL is what governs how soon+ // a poll asks for a live fetch at all.+ assert!(+ current_user_backoff(1) > AUTH_FETCH_TIMEOUT,+ "first backoff step {:?} must exceed the fetch timeout {:?}",+ current_user_backoff(1),+ AUTH_FETCH_TIMEOUT+ );+ assert!(+ current_user_backoff(1) > CURRENT_USER_REFRESH_TTL,+ "first backoff step {:?} must exceed the current-user cache TTL {:?}",+ current_user_backoff(1),+ CURRENT_USER_REFRESH_TTL+ );+}++#[test]+fn a_recorded_failure_suppresses_a_retry_inside_its_window() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ record_current_user_failure(+ "https://api.example.test",+ "token-a",+ CurrentUserFetchError::FetchFailed("request timed out after 5s".to_string()),+ );++ let (error, consecutive, remaining) =+ suppressed_current_user_failure("https://api.example.test", "token-a")+ .expect("a just-recorded failure must suppress the next attempt");+ assert_eq!(consecutive, 1);+ assert_eq!(error.message(), "request timed out after 5s");+ assert!(remaining <= CURRENT_USER_BACKOFF_BASE && !remaining.is_zero());+}++#[test]+fn a_recorded_failure_stops_suppressing_once_its_window_closes() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ seed_current_user_failure(+ "https://api.example.test",+ "token-a",+ 1,+ CURRENT_USER_BACKOFF_BASE + Duration::from_millis(1),+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );++ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),+ "a failure older than its window must let the next attempt through"+ );+}++#[test]+fn consecutive_failures_widen_the_window() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ for _ in 0..3 {+ record_current_user_failure(+ "https://api.example.test",+ "token-a",+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );+ }++ let (_, consecutive, _) =+ suppressed_current_user_failure("https://api.example.test", "token-a")+ .expect("still inside the widened window");+ assert_eq!(consecutive, 3);++ // Three failures in, an attempt that would have been let through at the+ // first window is still suppressed.+ seed_current_user_failure(+ "https://api.example.test",+ "token-a",+ 3,+ CURRENT_USER_BACKOFF_BASE + Duration::from_millis(1),+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );+ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-a").is_some(),+ "the third failure's window must outlast the first failure's"+ );+}++#[test]+fn a_rejected_credential_is_never_recorded() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ record_current_user_failure(+ "https://api.example.test",+ "token-a",+ CurrentUserFetchError::Rejected("401 Unauthorized".to_string()),+ );++ // Replaying a rejection from a cache would either delay the deferred-session+ // cleanup the snapshot caller drives off that variant, or hand it a+ // different variant than the backend produced.+ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),+ "an auth rejection must not be backed off"+ );+}++#[test]+fn a_different_token_or_backend_bypasses_the_record() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ record_current_user_failure(+ "https://api.example.test",+ "token-a",+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );++ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-b").is_none(),+ "signing in as someone else must not inherit the previous session's outage"+ );+ assert!(+ suppressed_current_user_failure("https://other.example.test", "token-a").is_none(),+ "switching environment must not inherit the previous backend's outage"+ );+ // …and the run it was recorded against is untouched by those probes.+ assert!(suppressed_current_user_failure("https://api.example.test", "token-a").is_some());+}++#[test]+fn clearing_the_record_lets_the_next_attempt_through() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ record_current_user_failure(+ "https://api.example.test",+ "token-a",+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );+ assert!(suppressed_current_user_failure("https://api.example.test", "token-a").is_some());++ // What sign-out and every success both call. Missing either is the failure+ // mode that matters: a record outliving its cause strands the app on the+ // stored snapshot after the backend is back.+ clear_current_user_failure();++ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),+ "a cleared record must not keep suppressing"+ );+}++#[tokio::test]+async fn fetch_current_user_cached_replays_a_recorded_failure_without_calling_the_backend() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;+ let _reset = CurrentUserFailureResetGuard;++ let mut config = Config::default();+ // A closed loopback port. Nothing here should reach it — the point of the+ // test is that the recorded failure short-circuits first — but if the probe+ // is removed the call fails locally with a connection error instead of+ // reaching out to the real backend.+ config.api_url = Some("http://127.0.0.1:9/".to_string());+ let api_base = current_user_api_base(&config);+ assert!(+ api_base.starts_with("http://127.0.0.1:9"),+ "precondition: the override must survive backend-url resolution, got {api_base}; \+ otherwise this test would talk to a real backend"+ );++ let token = "token-a";+ seed_current_user_failure(+ &api_base,+ token,+ 1,+ Duration::from_millis(1),+ CurrentUserFetchError::FetchFailed("seeded outage marker".to_string()),+ );++ let error = fetch_current_user_cached(&config, token, true)+ .await+ .expect_err("a recorded failure inside its window must be replayed");++ assert_eq!(+ error.message(),+ "seeded outage marker",+ "the fetch must replay the recorded failure rather than issue a request"+ );+}