Skip to content

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

fix(app_state): scope staleness to the identity and skip rejected sessions

Shanu6b435fff3b23
diff --git a/.env.example b/.env.example
index e9527cd996..f58b734df9 100644
--- a/.env.example
+++ b/.env.example
@@ -104,6 +104,13 @@ OPENHUMAN_TEMPERATURE=0.7
# in-app "Action timeout" setting (Settings -> Agent OS access), which persists
# to [agent].agent_timeout_secs. Leave unset to let the UI control it.
# OPENHUMAN_TOOL_TIMEOUT_SECS=
+# [optional] Operator override for how long the desktop app waits on the
+# backend's current-user (auth_get_me) refresh, in seconds (default 5, range
+# 2-12). Raise it if a slow-but-healthy backend keeps falling back to the
+# stored snapshot. The ceiling is deliberate: this budget is spent inside the
+# app_state_snapshot RPC, and the retry backoff is derived from it so a wider
+# timeout cannot re-open the poll treadmill. Leave unset to use the default.
+# OPENHUMAN_AUTH_FETCH_TIMEOUT_SECS=
# [optional] Operator override for the inference HTTP request timeout, in
# seconds (default 120, range 1-3600). Raise this when long reasoning/research
# turns get cut off at the two-minute mark. Leave unset to use the default.
diff --git a/src/openhuman/desktop/app_state/ops.rs b/src/openhuman/desktop/app_state/ops.rs
index f3d55b1717..07a5fa0863 100644
--- a/src/openhuman/desktop/app_state/ops.rs
+++ b/src/openhuman/desktop/app_state/ops.rs
@@ -1,6 +1,11 @@
#[cfg(test)]
+#[path = "ops_current_user_backoff_tests.rs"]
+mod current_user_backoff_tests;
+#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
+include!("ops_auth_timeout.rs");
include!("ops_part_01.rs");
+include!("ops_staleness.rs");
include!("ops_part_02.rs");
include!("ops_part_03.rs");
diff --git a/src/openhuman/desktop/app_state/ops_auth_timeout.rs b/src/openhuman/desktop/app_state/ops_auth_timeout.rs
new file mode 100644
index 0000000000..bd7a4d6031
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_auth_timeout.rs
@@ -0,0 +1,94 @@
+// How long the current-user refresh may take, and how long a failed run of
+// them suppresses the next attempt.
+//
+// Split out of `ops_part_01.rs` because the two values are one decision: the
+// backoff step is *derived* from the fetch timeout so that widening the
+// timeout cannot re-open #5624's poll treadmill. Keeping them adjacent is
+// what makes that relationship reviewable.
+//
+// `include!`d into `ops.rs`, so everything here shares that module's scope.
+
+/// 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`.
+///
+/// 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())
+}
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
new file mode 100644
index 0000000000..3e03efbf7b
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_current_user_backoff_tests.rs
@@ -0,0 +1,490 @@
+//! The current-user failure backoff, its replay, and the staleness it reports.
+//!
+//! Split out of `ops_tests.rs` for the layout gate. Kept as one file because
+//! the three subjects are one mechanism: a failure is recorded, replayed while
+//! its window is open (#5930), and surfaced as snapshot staleness — and the
+//! helpers that seed an outage are shared across all three.
+
+use super::*;
+use once_cell::sync::Lazy as TestLazy;
+use serde_json::json;
+
+// ── 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() {
+ 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), 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"
+ );
+}
+
+// ── 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(api_base, "token-a");
+
+ 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);
+}
+
+#[test]
+fn one_identitys_success_is_never_reported_as_anothers_age() {
+ // The stale flag was keyed on `(api_base, token)` from the start but the
+ // age was read from a bare global, so identity A succeeding and identity B
+ // then failing reported A's freshness against B's outage. The ordinary
+ // `credentials::clear_session` logout does not run the deferred-rejection
+ // cleanup either, so the same leak survived a logout and re-login in one
+ // process. Keying the stamp closes both.
+ 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";
+ note_current_user_success(api_base, "token-a");
+
+ let (_, age_a) = current_user_staleness(api_base, "token-a");
+ assert!(
+ age_a.is_some(),
+ "the identity that succeeded knows its own age"
+ );
+
+ let (_, age_b) = current_user_staleness(api_base, "token-b");
+ assert_eq!(
+ age_b, None,
+ "a different token must not inherit another identity's freshness"
+ );
+
+ let (_, age_other_env) = current_user_staleness("https://other.example.test", "token-a");
+ assert_eq!(
+ age_other_env, None,
+ "a different backend must not inherit another environment's freshness"
+ );
+
+ // The pairing that actually shipped the bug: B is stale, and must not be
+ // handed A's age alongside that.
+ record_current_user_failure(
+ api_base,
+ "token-b",
+ CurrentUserFetchError::FetchFailed("boom".to_string()),
+ );
+ let (stale_b, age_b) = current_user_staleness(api_base, "token-b");
+ assert!(stale_b, "B's outage is B's");
+ assert_eq!(
+ age_b, None,
+ "B has no success of its own, so its age is unknown"
+ );
+}
diff --git a/src/openhuman/desktop/app_state/ops_part_01.rs b/src/openhuman/desktop/app_state/ops_part_01.rs
index c1348dd354..3a93c87cdf 100644
--- a/src/openhuman/desktop/app_state/ops_part_01.rs
+++ b/src/openhuman/desktop/app_state/ops_part_01.rs
@@ -43,90 +43,6 @@ 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);
-/// 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`.
-///
-/// 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
@@ -148,15 +64,6 @@ 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
@@ -345,41 +252,6 @@ 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
diff --git a/src/openhuman/desktop/app_state/ops_part_02.rs b/src/openhuman/desktop/app_state/ops_part_02.rs
index 0f49507adf..e9140fdf0f 100644
--- a/src/openhuman/desktop/app_state/ops_part_02.rs
+++ b/src/openhuman/desktop/app_state/ops_part_02.rs
@@ -236,7 +236,7 @@ async fn fetch_current_user_cached(
}
};
clear_current_user_failure();
- note_current_user_success();
+ note_current_user_success(&api_base, token);
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.rs
index d698a8854c..0de1ebc307 100644
--- a/src/openhuman/desktop/app_state/ops_part_03.rs
+++ b/src/openhuman/desktop/app_state/ops_part_03.rs
@@ -160,8 +160,8 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
// 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: {}",
+ "{LOG_PREFIX} current user refresh suppressed; backend unavailable or unhealthy \
+ {consecutive}x, next live attempt in {}s, using stored snapshot fallback: {}",
retry_in.as_secs(),
inner.message()
);
@@ -216,17 +216,27 @@ pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
// 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.
+ //
+ // A rejected session is excluded outright: that arm is about to clear
+ // `auth`, `session_token` and `current_user`, and a signed-out snapshot
+ // carrying `currentUserStale: true` would describe a user it no longer
+ // reports.
+ //
+ // The token is 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 session_rejected = matches!(current_user, SnapshotCurrentUser::DeferredSessionRejected);
let (current_user_stale, current_user_stale_seconds) = match session_token
.as_deref()
+ .filter(|_| !session_rejected)
.filter(|&token| !token.trim().is_empty() && !is_local_session_token(token))
{
Some(token) => current_user_staleness(&current_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.
+ // Signed out, rejected, 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();
diff --git a/src/openhuman/desktop/app_state/ops_staleness.rs b/src/openhuman/desktop/app_state/ops_staleness.rs
new file mode 100644
index 0000000000..47562b7ec3
--- /dev/null
+++ b/src/openhuman/desktop/app_state/ops_staleness.rs
@@ -0,0 +1,76 @@
+// How stale the `current_user` the snapshot is serving has become.
+//
+// Split out of `ops_part_01.rs` (layout gate) and kept together because the
+// three pieces are one contract: the stamp is written on every successful
+// `auth_get_me`, cleared when the identity goes away, and read back keyed on
+// the same `(api_base, token)` both caches use — so one identity's freshness
+// is never reported as another's (#5930).
+//
+// `include!`d into `ops.rs`, so everything here shares that module's scope.
+
+/// 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).
+///
+/// Keyed on `(api_base, token)` like both caches. An unkeyed timestamp would
+/// outlive the identity that earned it: the ordinary
+/// `credentials::clear_session` logout does not run the deferred-rejection
+/// cleanup, so a logout and re-login in the same process — or simply a second
+/// identity failing after a first succeeded — would report the previous
+/// session's age as this one's.
+static LAST_CURRENT_USER_SUCCESS: Lazy<Mutex<Option<CurrentUserSuccess>>> =
+ Lazy::new(|| Mutex::new(None));
+
+/// The last successful `auth_get_me`, with the identity it belongs to.
+#[derive(Debug, Clone)]
+struct CurrentUserSuccess {
+ api_base: String,
+ token: String,
+ at: Instant,
+}
+
+/// Stamp a successful backend answer, so the snapshot can report how old the
+/// data it is serving has become.
+fn note_current_user_success(api_base: &str, token: &str) {
+ *LAST_CURRENT_USER_SUCCESS.lock() = Some(CurrentUserSuccess {
+ api_base: api_base.to_string(),
+ token: token.to_string(),
+ at: 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 *this identity's* 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. A success recorded against a different `(api_base,
+/// token)` is somebody else's freshness and is not reported as this one's.
+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()
+ .filter(|entry| entry.api_base == api_base && entry.token == token)
+ .map(|entry| entry.at.elapsed().as_secs());
+ (stale, age)
+}
diff --git a/src/openhuman/desktop/app_state/ops_tests.rs b/src/openhuman/desktop/app_state/ops_tests.rs
index d657fe8cbc..b25772469d 100644
--- a/src/openhuman/desktop/app_state/ops_tests.rs
+++ b/src/openhuman/desktop/app_state/ops_tests.rs
@@ -486,434 +486,3 @@ 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() {
- 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), 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"
- );
-}
-
-// ── 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);
-}
diff --git a/tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs b/tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs
index 3e3eaa1ec4..dcfbcad98b 100644
--- a/tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/app_state_credentials_raw_coverage_e2e.rs
@@ -934,6 +934,19 @@ async fn snapshot_clears_pending_session_when_backend_revalidation_is_rejected()
assert!(snap.auth.user.is_none());
assert!(snap.current_user.is_none());
assert!(snap.session_token.is_none());
+ // A signed-out snapshot must not also describe a user it no longer
+ // reports. The staleness fields are read from the pre-rejection
+ // `session_token`, so without an explicit guard this arm published
+ // `currentUserStale` metadata for the identity it had just cleared
+ // (#5930).
+ assert!(
+ !snap.current_user_stale,
+ "a rejected session must not be reported as a stale user"
+ );
+ assert_eq!(
+ snap.current_user_stale_seconds, None,
+ "a rejected session must not carry a stale-user age"
+ );
let profile = AuthService::from_config(&config)
.get_profile(APP_SESSION_PROVIDER, None)
.expect("read profile after rejection");