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): distinguish replayed backoff from live refresh failure (#5930)
Shanu851204c156ef
diff --git a/app/src/lib/coreState/store.ts b/app/src/lib/coreState/store.tsindex 2128df4685..1e27e5b1a3 100644--- a/app/src/lib/coreState/store.ts+++ b/app/src/lib/coreState/store.ts@@ -65,6 +65,24 @@ export interface CoreAppSnapshot {localState: CoreLocalState;keyringStatus: KeyringStatus;runtime: CoreRuntimeSnapshot;+ /**+ * Whether `currentUser` is being served from the core's stored snapshot+ * because the backend could not be refreshed (#5930). Plan tier, credits and+ * feature flags read off a stale `currentUser` may be wrong.+ *+ * Optional on the type, always concrete at runtime: `normalizeSnapshot`+ * defaults it and `emptySnapshot` carries it. Optional so a snapshot literal+ * — of which there are several in tests — stays valid without restating a+ * field it does not care about. Read it as `?? false`.+ */+ currentUserStale?: boolean;+ /**+ * Seconds since the backend last answered, or `null` when it has not answered+ * at all this process — the age is then genuinely unknown, not zero. A+ * surface deciding whether to warn owns its own threshold; the core does not+ * pick one.+ */+ currentUserStaleSeconds?: number | null;}export interface CoreState {@@ -91,6 +109,8 @@ const emptySnapshot: CoreAppSnapshot = {backendName: 'os',},runtime: { localAi: null, service: null },+ currentUserStale: false,+ currentUserStaleSeconds: null,};let currentState: CoreState = {diff --git a/app/src/providers/CoreStateProvider.tsx b/app/src/providers/CoreStateProvider.tsxindex d534546f6f..20feb08fae 100644--- a/app/src/providers/CoreStateProvider.tsx+++ b/app/src/providers/CoreStateProvider.tsx@@ -241,6 +241,8 @@ function normalizeSnapshot(backendName: 'os',},runtime: { localAi: result.runtime?.localAi ?? null, service: result.runtime?.service ?? null },+ currentUserStale: result.currentUserStale ?? false,+ currentUserStaleSeconds: result.currentUserStaleSeconds ?? null,};}@@ -252,6 +254,10 @@ function toSignedOutSnapshot(snapshot: CoreAppSnapshot): CoreAppSnapshot {currentUser: null,onboardingCompleted: false,chatOnboardingCompleted: false,+ // Signed out there is no backend-backed user for the stored snapshot to be+ // stale relative to.+ currentUserStale: false,+ currentUserStaleSeconds: null,};}diff --git a/app/src/services/coreStateApi.ts b/app/src/services/coreStateApi.tsindex 0eee7e91f9..91f1e984b4 100644--- a/app/src/services/coreStateApi.ts+++ b/app/src/services/coreStateApi.ts@@ -72,6 +72,20 @@ interface AppStateSnapshotResult {* degrade to "no recovery". `CoreStateProvider` raises a one-shot notice.*/configRecovered?: boolean;+ /**+ * `true` when `currentUser` came from the core's stored snapshot because the+ * backend could not be refreshed, so its plan tier, credit balance and+ * feature flags may be out of date (#5930). Optional so older cores that+ * omit it degrade to "not stale".+ */+ currentUserStale?: boolean;+ /**+ * Seconds since the core last got a successful `auth_get_me` answer this+ * process. Absent when it never has — the stored snapshot then came off+ * disk and its real age is unknown, which is a different statement from+ * "zero seconds old".+ */+ currentUserStaleSeconds?: number;}/** Raw (snake_case) health payload embedded in the app-state snapshot. */diff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rsindex a4a2845f3f..c1348dd354 100644--- a/src/openhuman/desktop/app_state/ops_part_01.rs+++ b/src/openhuman/desktop/app_state/ops_part_01.rs@@ -43,15 +43,90 @@ const CURRENT_USER_REFRESH_TTL: Duration = Duration::from_secs(5);// the agent harness runs on — the agent's turns stalled 50-100s between model// 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);+/// Wall-clock budget for one `auth_get_me` refresh when nothing overrides it.+pub const DEFAULT_AUTH_FETCH_TIMEOUT_SECS: u64 = 5;+/// Smallest accepted override. Anything shorter would time out a healthy+/// backend on a merely slow link on every poll — the #5624 treadmill inverted.+pub const MIN_AUTH_FETCH_TIMEOUT_SECS: u64 = 2;+/// Largest accepted override.+///+/// The ceiling exists because this budget is spent *inside* the snapshot RPC,+/// concurrently with [`RUNTIME_SNAPSHOT_TIMEOUT`], and the frontend gives that+/// RPC 30s total. `12 + 10 = 22` leaves headroom; a larger value would let an+/// operator turn a slow backend into a failed snapshot call.+pub const MAX_AUTH_FETCH_TIMEOUT_SECS: u64 = 12;+/// Operator override for [`auth_fetch_timeout`]. A missing, non-numeric or+/// out-of-range value leaves the default in place (and is logged once).+pub const AUTH_FETCH_TIMEOUT_ENV_VAR: &str = "OPENHUMAN_AUTH_FETCH_TIMEOUT_SECS";++/// Floor under the first backoff step, independent of the fetch timeout.+///+/// Must stay above [`CURRENT_USER_REFRESH_TTL`], which governs how soon a poll+/// asks for a live fetch at all.+const CURRENT_USER_BACKOFF_BASE_FLOOR: Duration = Duration::from_secs(10);++/// Parse a raw override into a bounded timeout in seconds.+///+/// Pure and global-free so the clamp can be tested without touching the process+/// environment. `None`, unparseable input, and out-of-range values all fall back+/// to [`DEFAULT_AUTH_FETCH_TIMEOUT_SECS`].+pub fn parse_auth_fetch_timeout_secs(raw: Option<&str>) -> u64 {+ auth_fetch_timeout_override(raw).unwrap_or(DEFAULT_AUTH_FETCH_TIMEOUT_SECS)+}++/// The override if `raw` names one inside the accepted range, else `None`.+///+/// Split from [`parse_auth_fetch_timeout_secs`] so the resolver can tell+/// "accepted" from "fell back" without re-deriving it by comparing strings —+/// which would report a valid `05` as ignored.+fn auth_fetch_timeout_override(raw: Option<&str>) -> Option<u64> {+ raw.map(str::trim)+ .and_then(|s| s.parse::<u64>().ok())+ .filter(|n| (MIN_AUTH_FETCH_TIMEOUT_SECS..=MAX_AUTH_FETCH_TIMEOUT_SECS).contains(n))+}++/// The effective `auth_get_me` timeout, resolved once per process.+///+/// Read through a function rather than held as a `const` so #5930's "5s may be+/// too tight" has an answer that does not need a rebuild. Every caller — the+/// `tokio::time::timeout` wrapper, the timeout log line, and the recorded+/// timeout error's message — reads the same value, so they cannot drift.+fn auth_fetch_timeout() -> Duration {+ static RESOLVED: Lazy<Duration> = Lazy::new(|| {+ let raw = std::env::var(AUTH_FETCH_TIMEOUT_ENV_VAR).ok();+ match (raw.as_deref(), auth_fetch_timeout_override(raw.as_deref())) {+ (Some(raw), None) => warn!(+ "{LOG_PREFIX} ignoring {AUTH_FETCH_TIMEOUT_ENV_VAR}={raw:?}: not an integer in \+ {MIN_AUTH_FETCH_TIMEOUT_SECS}..={MAX_AUTH_FETCH_TIMEOUT_SECS}; \+ using {DEFAULT_AUTH_FETCH_TIMEOUT_SECS}s"+ ),+ (Some(_), Some(secs)) => debug!(+ "{LOG_PREFIX} auth fetch timeout overridden to {secs}s by {AUTH_FETCH_TIMEOUT_ENV_VAR}"+ ),+ (None, _) => {}+ }+ Duration::from_secs(parse_auth_fetch_timeout_secs(raw.as_deref()))+ });+ *RESOLVED+}+/// 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);+/// Derived from `fetch_timeout` rather than fixed, because the property that+/// actually stops the treadmill is *relational*: the step must outlast both the+/// fetch timeout and the frontend's ~5s `app_state_snapshot` poll, or the next+/// poll finds the window already expired and pays the full timeout again+/// (#5624 — 51 timeouts in one session, ~5s each). Making the timeout+/// configurable (#5930) without deriving this would let an operator re-open+/// that bug by widening the timeout past a fixed 10s step.+fn current_user_backoff_base_for(fetch_timeout: Duration) -> Duration {+ CURRENT_USER_BACKOFF_BASE_FLOOR.max(fetch_timeout.saturating_mul(2))+}++/// [`current_user_backoff_base_for`] applied to the effective timeout.+fn current_user_backoff_base() -> Duration {+ current_user_backoff_base_for(auth_fetch_timeout())+}/// 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@@ -65,7 +140,7 @@ 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.+/// 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 —@@ -73,6 +148,15 @@ static CURRENT_USER_CACHE: Lazy<Mutex<Option<CachedCurrentUser>>> = Lazy::new(||/// identity throughout an outage, and it reads only the positive cache.static CURRENT_USER_FAILURE: Lazy<Mutex<Option<CurrentUserFailure>>> =Lazy::new(|| Mutex::new(None));+/// When the backend last answered `auth_get_me` successfully in this process.+///+/// Neither existing cache can answer "how old is the user data we are showing":+/// [`CURRENT_USER_FAILURE`] only knows about failures, and+/// [`CURRENT_USER_CACHE`] is set to `None` whenever the backend returns an+/// empty user, which erases the timestamp on a path that is not an outage.+/// `None` here means "no success yet this process" — the snapshot then reports+/// staleness with an unknown age rather than inventing one (#5930).+static LAST_CURRENT_USER_SUCCESS: Lazy<Mutex<Option<Instant>>> = 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@@ -128,6 +212,24 @@ enum CurrentUserFetchError {Rejected(String),TransientResponse(String),FetchFailed(String),+ /// A recorded availability failure replayed from the backoff window+ /// instead of going to the network (see+ /// [`suppressed_current_user_failure`]).+ ///+ /// Carries the original error so callers that only want the message behave+ /// exactly as before, plus the two numbers that distinguish "the backend+ /// just failed" from "we did not ask the backend". Without this the+ /// snapshot caller logs a replay — which costs microseconds and makes no+ /// request — with the same `WARN … refresh failed` wording as a real 5s+ /// timeout, so a healthy backoff reads in the logs like a hammering loop.+ /// That misreading is what #5930 was filed on.+ Suppressed {+ inner: Box<CurrentUserFetchError>,+ /// Length of the failure run that opened the window.+ consecutive: u32,+ /// How long until the next live attempt is allowed.+ retry_in: Duration,+ },}impl CurrentUserFetchError {@@ -136,6 +238,7 @@ impl CurrentUserFetchError {CurrentUserFetchError::Rejected(message)| CurrentUserFetchError::TransientResponse(message)| CurrentUserFetchError::FetchFailed(message) => message,+ CurrentUserFetchError::Suppressed { inner, .. } => inner.message(),}}}@@ -155,6 +258,11 @@ impl CurrentUserFetchError {true}CurrentUserFetchError::Rejected(_) => false,+ // Defensive: a replay is not a new observation, and recording it+ // would extend the window on evidence the backend never supplied.+ // `fetch_current_user_cached` returns this variant before it can+ // reach the recorder, so this arm should never actually run.+ CurrentUserFetchError::Suppressed { .. } => false,}}}@@ -176,12 +284,12 @@ struct CurrentUserFailure {/// How long a run of `consecutive` failures suppresses the next live attempt.///-/// Doubles from [`CURRENT_USER_BACKOFF_BASE`] and saturates at+/// 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+ current_user_backoff_base().saturating_mul(2u32.saturating_pow(steps)).min(CURRENT_USER_BACKOFF_MAX)}@@ -237,6 +345,41 @@ fn clear_current_user_failure() {*CURRENT_USER_FAILURE.lock() = None;}+/// Stamp a successful backend answer, so the snapshot can report how old the+/// data it is serving has become.+fn note_current_user_success() {+ *LAST_CURRENT_USER_SUCCESS.lock() = Some(Instant::now());+}++/// Forget the success stamp on sign-out, so the next account does not inherit+/// this one's freshness.+fn clear_current_user_success() {+ *LAST_CURRENT_USER_SUCCESS.lock() = None;+}++/// Whether the snapshot is being served from data the backend could not+/// refresh, and how long since it last did.+///+/// Keyed like both caches: a recorded failure only makes *this* `(api_base,+/// token)` stale. Without the key check, switching environment or signing in as+/// someone else would inherit the previous identity's outage and report the+/// fresh data it is about to fetch as stale.+///+/// The age is `None` when the backend has not answered at all in this process —+/// the stored snapshot then came off disk, and its true age is not knowable+/// from here.+fn current_user_staleness(api_base: &str, token: &str) -> (bool, Option<u64>) {+ let stale = CURRENT_USER_FAILURE+ .lock()+ .as_ref()+ .is_some_and(|entry| entry.api_base == api_base && entry.token == token);+ let age = LAST_CURRENT_USER_SUCCESS+ .lock()+ .as_ref()+ .map(|at| at.elapsed().as_secs());+ (stale, age)+}+/// Record the timeout path's failure.////// The timeout is applied by the snapshot caller, wrapping the whole of@@ -250,7 +393,7 @@ fn note_current_user_timeout(config: &Config, token: &str) {token,CurrentUserFetchError::FetchFailed(format!("request timed out after {}s",- AUTH_FETCH_TIMEOUT.as_secs()+ auth_fetch_timeout().as_secs())),);}@@ -322,6 +465,21 @@ pub struct AppStateSnapshot {/// healed; the frontend raises a one-shot "settings were reset" notice/// (#5167). Serialized as `configRecovered`.pub config_recovered: bool,+ /// `true` when `current_user` came from the stored snapshot because the+ /// backend could not be refreshed — the plan tier, credit balance and+ /// feature flags in it may be out of date (#5930).+ ///+ /// The frontend can warn on this; the core deliberately does not decide+ /// what "significantly out of date" means, because that threshold belongs+ /// to whatever surface is presenting the number.+ pub current_user_stale: bool,+ /// Seconds since the backend last answered `auth_get_me` in this process.+ ///+ /// Absent when it never has — the stored snapshot then came off disk and+ /// its real age is not knowable here, which is a different statement from+ /// "zero seconds old" and is why this is an `Option`.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub current_user_stale_seconds: Option<u64>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/src/openhuman/desktop/app_state/ops_part_02.rs b/src/openhuman/desktop/app_state/ops_part_02.rsindex d0ad6d896d..0f49507adf 100644--- a/src/openhuman/desktop/app_state/ops_part_02.rs+++ b/src/openhuman/desktop/app_state/ops_part_02.rs@@ -140,6 +140,7 @@ async fn clear_deferred_session_after_backend_rejection(*CURRENT_USER_CACHE.lock() = None;clear_current_user_failure();+ clear_current_user_success();crate::openhuman::cron::scheduler_gate::set_signed_out(true);match crate::openhuman::config::default_root_openhuman_dir() {@@ -201,7 +202,7 @@ async fn fetch_current_user_cached(// 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+ // `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@@ -215,7 +216,15 @@ async fn fetch_current_user_cached(retrying in {}ms",remaining.as_millis());- return Err(error);+ // Wrapped rather than returned bare so the caller can tell a replay+ // from a live failure. Both fall back to the stored snapshot, but+ // only one of them made a request, and logging them identically is+ // what made a working backoff read as a hammering loop (#5930).+ return Err(CurrentUserFetchError::Suppressed {+ inner: Box::new(error),+ consecutive,+ retry_in: remaining,+ });}}@@ -227,6 +236,7 @@ async fn fetch_current_user_cached(}};clear_current_user_failure();+ note_current_user_success();let mut cache = CURRENT_USER_CACHE.lock();match fetched.clone() {diff --git a/src/openhuman/desktop/app_state/ops_part_03.rs b/src/openhuman/desktop/app_state/ops_part_03.rsindex 1a3d0d4f6f..d698a8854c 100644--- a/src/openhuman/desktop/app_state/ops_part_03.rs+++ b/src/openhuman/desktop/app_state/ops_part_03.rs@@ -63,7 +63,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {return snapshot_current_user_result(stored_user.clone());}match tokio::time::timeout(- AUTH_FETCH_TIMEOUT,+ auth_fetch_timeout(),fetch_current_user_cached(&config, &token, !pending_backend_validation),).await@@ -149,6 +149,24 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {);snapshot_current_user_result(stored_user.clone())}+ Ok(Err(CurrentUserFetchError::Suppressed {+ inner,+ consecutive,+ retry_in,+ })) => {+ // Not a failure of *this* poll: the backoff window opened by an+ // earlier failure is still running, so no request was made and+ // this arm cost microseconds. Logging it at `warn` with the+ // same wording as a live failure is what made a working backoff+ // look like a hammering loop in #5930's own log evidence.+ debug!(+ "{LOG_PREFIX} current user refresh suppressed; backend unreachable {consecutive}x, \+ next live attempt in {}s, using stored snapshot fallback: {}",+ retry_in.as_secs(),+ inner.message()+ );+ snapshot_current_user_result(stored_user.clone())+ }Ok(Err(error)) => {warn!("{LOG_PREFIX} current user refresh failed; using stored snapshot fallback: {}",@@ -159,7 +177,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {Err(_) if pending_backend_validation => {warn!("{LOG_PREFIX} pending current user fetch timed out after {}s; keeping stored pending session for retry",- AUTH_FETCH_TIMEOUT.as_secs()+ auth_fetch_timeout().as_secs());note_current_user_timeout(&config, &token);snapshot_current_user_result(stored_user.clone())@@ -167,7 +185,7 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {Err(_) => {warn!("{LOG_PREFIX} current user fetch timed out after {}s; using stored snapshot fallback",- AUTH_FETCH_TIMEOUT.as_secs()+ auth_fetch_timeout().as_secs());note_current_user_timeout(&config, &token);snapshot_current_user_result(stored_user.clone())@@ -195,6 +213,22 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {let (current_user_result, runtime) = tokio::join!(current_user_future, runtime_future);let enrich_ms = t_enrich.elapsed().as_millis();let (current_user, revalidated_config) = current_user_result;+ // Read before the `DeferredSessionRejected` arm below clears+ // `session_token`, and keyed off the same `config` the fetch used so the+ // answer describes this identity's backend, not a previous one's.+ // Matched to the fetch above, which filters on the *trimmed* token being+ // non-empty but keys the failure record on the raw one. Trimming here+ // instead would look up a key that was never written, and staleness would+ // read as `false` for every token with surrounding whitespace.+ let (current_user_stale, current_user_stale_seconds) = match session_token+ .as_deref()+ .filter(|&token| !token.trim().is_empty() && !is_local_session_token(token))+ {+ Some(token) => current_user_staleness(¤t_user_api_base(&config), token),+ // Signed out, or a local-only token that never talks to the backend:+ // there is nothing for the stored snapshot to be stale relative to.+ None => (false, None),+ };let mut snapshot_config = config.clone();if let Some(revalidated_config) = revalidated_config {snapshot_config = *revalidated_config;@@ -283,6 +317,8 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {runtime,health,config_recovered: super::config_recovered_this_session(),+ current_user_stale,+ current_user_stale_seconds,},vec!["core app state snapshot fetched".to_string()],))diff --git a/src/openhuman/desktop/app_state/ops_tests.rs b/src/openhuman/desktop/app_state/ops_tests.rsindex 37ee5cba1b..d657fe8cbc 100644--- a/src/openhuman/desktop/app_state/ops_tests.rs+++ b/src/openhuman/desktop/app_state/ops_tests.rs@@ -325,9 +325,11 @@ fn degraded_runtime_snapshot_has_expected_degraded_fields() {#[test]fn auth_fetch_timeout_constant_is_below_rpc_timeout() {// The 30s RPC timeout on the frontend means auth fetch + runtime snapshot- // must fit comfortably. Verify the constants are sane.+ // must fit comfortably. Asserted across the whole configurable range+ // (#5930), not just the default, because the operator override is what+ // could push the pair past the ceiling.assert!(- AUTH_FETCH_TIMEOUT.as_secs() < 15,+ MAX_AUTH_FETCH_TIMEOUT_SECS < 15,"auth fetch timeout should be well under the 30s RPC timeout");assert!(@@ -335,11 +337,94 @@ fn auth_fetch_timeout_constant_is_below_rpc_timeout() {"runtime snapshot timeout should be well under the 30s RPC timeout");assert!(- AUTH_FETCH_TIMEOUT + RUNTIME_SNAPSHOT_TIMEOUT < Duration::from_secs(30),- "total of auth + runtime timeouts must fit within the 30s RPC timeout"+ Duration::from_secs(MAX_AUTH_FETCH_TIMEOUT_SECS) + RUNTIME_SNAPSHOT_TIMEOUT+ < Duration::from_secs(30),+ "even the widest permitted auth timeout plus the runtime timeout must fit within the 30s RPC timeout"+ );+ assert!(+ (MIN_AUTH_FETCH_TIMEOUT_SECS..=MAX_AUTH_FETCH_TIMEOUT_SECS)+ .contains(&DEFAULT_AUTH_FETCH_TIMEOUT_SECS),+ "the default must itself be an accepted override value");}+// ── Configurable auth fetch timeout (#5930) ─────────────────────────────────+//+// "5s may be too tight" is the issue's first acceptance criterion. The risk in+// answering it is that a wider timeout re-opens #5624: the backoff's first step+// was a fixed 10s, so an operator setting 20s would make every poll find the+// window already closed and pay the full 20s again. The clamp and the derived+// base are what stop that, so both are pinned here.++#[test]+fn parse_auth_fetch_timeout_secs_clamps_and_falls_back() {+ assert_eq!(+ parse_auth_fetch_timeout_secs(None),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS,+ "an unset override leaves the default in place"+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some("not-a-number")),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some("")),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some("0")),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS,+ "0 would disable the timeout entirely and is rejected"+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some(&(MIN_AUTH_FETCH_TIMEOUT_SECS - 1).to_string())),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS,+ "below the floor is rejected rather than clamped up, so a typo is visible in the logs"+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some(&(MAX_AUTH_FETCH_TIMEOUT_SECS + 1).to_string())),+ DEFAULT_AUTH_FETCH_TIMEOUT_SECS,+ "above the ceiling is rejected rather than clamped down"+ );+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some(" 7 ")),+ 7,+ "surrounding whitespace is tolerated"+ );++ for secs in MIN_AUTH_FETCH_TIMEOUT_SECS..=MAX_AUTH_FETCH_TIMEOUT_SECS {+ assert_eq!(+ parse_auth_fetch_timeout_secs(Some(&secs.to_string())),+ secs,+ "{secs}s is inside the accepted range and must pass through unchanged"+ );+ }+}++#[test]+fn the_derived_backoff_base_outlasts_every_permitted_fetch_timeout() {+ // This is #5624's invariant, restated as a property over the range #5930+ // opened up. A first step shorter than the fetch timeout means the next+ // poll finds the window already closed and pays the full timeout again —+ // which is the bug, not the fix.+ for secs in MIN_AUTH_FETCH_TIMEOUT_SECS..=MAX_AUTH_FETCH_TIMEOUT_SECS {+ let timeout = Duration::from_secs(secs);+ let base = current_user_backoff_base_for(timeout);+ assert!(+ base > timeout,+ "first backoff step {base:?} must exceed the fetch timeout {timeout:?}"+ );+ assert!(+ base > CURRENT_USER_REFRESH_TTL,+ "first backoff step {base:?} must exceed the cache TTL {CURRENT_USER_REFRESH_TTL:?}"+ );+ assert!(+ base <= CURRENT_USER_BACKOFF_MAX,+ "first backoff step {base:?} must not start at or above the cap {CURRENT_USER_BACKOFF_MAX:?}"+ );+ }+}+fn build_dummy_runtime_snapshot() -> RuntimeSnapshot {degraded_runtime_snapshot(&Config::default())}@@ -405,7 +490,7 @@ async fn current_user_fetch_carries_the_product_identity() {// ── 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+// 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@@ -453,13 +538,14 @@ fn seed_current_user_failure(#[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);+ let base = current_user_backoff_base();+ assert_eq!(current_user_backoff(1), base);+ assert_eq!(current_user_backoff(2), base * 2);+ assert_eq!(current_user_backoff(3), 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);+ assert_eq!(current_user_backoff(0), base);let mut previous = Duration::ZERO;for consecutive in 1..=12 {@@ -485,10 +571,10 @@ fn the_first_backoff_step_outlasts_both_the_fetch_timeout_and_the_poll() {// 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,+ current_user_backoff(1) > auth_fetch_timeout(),"first backoff step {:?} must exceed the fetch timeout {:?}",current_user_backoff(1),- AUTH_FETCH_TIMEOUT+ auth_fetch_timeout());assert!(current_user_backoff(1) > CURRENT_USER_REFRESH_TTL,@@ -514,7 +600,7 @@ fn a_recorded_failure_suppresses_a_retry_inside_its_window() {.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());+ assert!(remaining <= current_user_backoff_base() && !remaining.is_zero());}#[test]@@ -526,7 +612,7 @@ fn a_recorded_failure_stops_suppressing_once_its_window_closes() {"https://api.example.test","token-a",1,- CURRENT_USER_BACKOFF_BASE + Duration::from_millis(1),+ current_user_backoff_base() + Duration::from_millis(1),CurrentUserFetchError::FetchFailed("boom".to_string()),);@@ -560,7 +646,7 @@ fn consecutive_failures_widen_the_window() {"https://api.example.test","token-a",3,- CURRENT_USER_BACKOFF_BASE + Duration::from_millis(1),+ current_user_backoff_base() + Duration::from_millis(1),CurrentUserFetchError::FetchFailed("boom".to_string()),);assert!(@@ -672,3 +758,162 @@ async fn fetch_current_user_cached_replays_a_recorded_failure_without_calling_th"the fetch must replay the recorded failure rather than issue a request");}++// ── Replay is distinguishable from a live failure (#5930) ───────────────────+//+// #5930 was filed on four `WRN … current user refresh failed … request timed+// out after 5s` lines seconds apart, read as the app hammering a failing+// endpoint. They were replays of one recorded failure — microseconds each, no+// request made — because the suppression path returned the recorded error+// verbatim and the snapshot caller had no way to tell the two apart. These pin+// the distinction so the same false alarm cannot be filed twice.++#[tokio::test]+async fn a_replayed_failure_is_tagged_suppressed_and_keeps_the_original_message() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;+ let _reset = CurrentUserFailureResetGuard;++ let mut config = Config::default();+ config.api_url = Some("http://127.0.0.1:9/".to_string());+ let api_base = current_user_api_base(&config);+ let token = "token-a";++ seed_current_user_failure(+ &api_base,+ token,+ 3,+ Duration::from_millis(1),+ CurrentUserFetchError::FetchFailed("request timed out after 5s".to_string()),+ );++ let error = fetch_current_user_cached(&config, token, true)+ .await+ .expect_err("a recorded failure inside its window must be replayed");++ match &error {+ CurrentUserFetchError::Suppressed {+ inner,+ consecutive,+ retry_in,+ } => {+ assert_eq!(*consecutive, 3, "the run length must survive the replay");+ assert!(+ *retry_in > Duration::ZERO && *retry_in <= current_user_backoff(3),+ "remaining window {retry_in:?} must be inside the step for 3 failures"+ );+ assert!(+ matches!(**inner, CurrentUserFetchError::FetchFailed(_)),+ "the original variant must be preserved, not flattened"+ );+ }+ other => panic!("expected a Suppressed replay, got {other:?}"),+ }++ assert_eq!(+ error.message(),+ "request timed out after 5s",+ "callers reading only the message must be unaffected by the wrapper"+ );+}++#[test]+fn a_suppressed_replay_is_never_recorded_as_a_fresh_failure() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserFailureResetGuard;++ let suppressed = CurrentUserFetchError::Suppressed {+ inner: Box::new(CurrentUserFetchError::FetchFailed("boom".to_string())),+ consecutive: 2,+ retry_in: Duration::from_secs(7),+ };+ assert!(+ !suppressed.is_availability_failure(),+ "a replay is not a new observation; recording it would widen the window \+ on evidence the backend never supplied"+ );++ record_current_user_failure("https://api.example.test", "token-a", suppressed);+ assert!(+ suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),+ "recording a replay must be a no-op"+ );+}++// ── Stale-snapshot age (#5930) ──────────────────────────────────────────────++/// Drops both the outage and the success stamp on the way out.+struct CurrentUserStalenessResetGuard;++impl Drop for CurrentUserStalenessResetGuard {+ fn drop(&mut self) {+ clear_current_user_failure();+ clear_current_user_success();+ }+}++#[test]+fn staleness_is_reported_only_for_the_identity_that_actually_failed() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserStalenessResetGuard;+ clear_current_user_failure();+ clear_current_user_success();++ let api_base = "https://api.example.test";++ let (stale, age) = current_user_staleness(api_base, "token-a");+ assert!(!stale, "no recorded failure means nothing is stale");+ assert_eq!(+ age, None,+ "no success this process means the age is unknown"+ );++ record_current_user_failure(+ api_base,+ "token-a",+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );++ assert!(+ current_user_staleness(api_base, "token-a").0,+ "the identity that failed is serving data it could not refresh"+ );+ assert!(+ !current_user_staleness(api_base, "token-b").0,+ "a different token must not inherit this identity's outage"+ );+ assert!(+ !current_user_staleness("https://other.example.test", "token-a").0,+ "a different backend must not inherit this environment's outage"+ );+}++#[test]+fn a_success_stamps_the_age_and_clears_the_stale_flag() {+ let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();+ let _reset = CurrentUserStalenessResetGuard;+ clear_current_user_failure();+ clear_current_user_success();++ let api_base = "https://api.example.test";+ record_current_user_failure(+ api_base,+ "token-a",+ CurrentUserFetchError::FetchFailed("boom".to_string()),+ );+ assert!(current_user_staleness(api_base, "token-a").0);++ // What `fetch_current_user_cached` does on every successful answer.+ clear_current_user_failure();+ note_current_user_success();++ let (stale, age) = current_user_staleness(api_base, "token-a");+ assert!(!stale, "a success must clear the stale flag");+ assert!(+ age.is_some(),+ "once the backend has answered, the age of the data is knowable"+ );++ // Sign-out must not leave the next account inheriting this one's freshness.+ clear_current_user_success();+ assert_eq!(current_user_staleness(api_base, "token-a").1, None);+}