Skip to main content

agentmux_srv_core/broker/
state.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pure reducer for the Credential Broker's per-credential coordination
5//! state — fresh / refreshing / failed / needs-reauth. Same shape as every
6//! other reducer in this codebase (`crates/launcher/src/reducer/`,
7//! `crates/srv-core/src/reducer.rs`, `crates/cef/src/reducer/mod.rs`):
8//! `update(&mut State, Command) -> Vec<Event>`, no I/O, no async,
9//! sub-millisecond lock hold when called from `scheduler.rs`'s orchestrator.
10//!
11//! Internal-only, like the CEF host reducer — this never crosses IPC, so it
12//! does not reuse `agentmux_common::ipc::{Command, Event}` (the
13//! srv<->launcher<->host wire protocol); it defines its own local types.
14//!
15//! This module never holds a credential's actual secret/value — only enough
16//! coordination state to decide WHEN `scheduler.rs`'s caller-supplied
17//! `is_fresh`/`refresh` closures should run, and to make that decision
18//! observable. Events are mapped 1:1 to `auth.broker.*`-prefixed `tracing`
19//! calls by the orchestrator — that prefix lands in `muxlog auth`'s existing
20//! filter regex (`\bauth\.\w+|...`) with zero changes needed there.
21
22use std::collections::HashMap;
23
24/// After this many consecutive TRANSIENT refresh failures the server answered
25/// (5xx, rate limits, unparseable replies), a credential moves to
26/// `NeedsReauth { rejected: false }`. An unreachable server never counts
27/// (`RefreshErrorKind::Unreachable`). The sweep keeps retrying a credential
28/// that wasn't refused; `ensure_fresh` (on-demand, e.g. right before a
29/// reconnect attempt) re-checks freshness from any `NeedsReauth`: if an
30/// external login has since succeeded, `is_fresh()` will report true and state
31/// naturally moves back to `Fresh`. No explicit "clear" API needed.
32pub const NEEDS_REAUTH_THRESHOLD: u32 = 5;
33
34/// Coordination state for one registered credential.
35#[derive(Debug, Clone, PartialEq)]
36pub enum CredentialState {
37    /// Registered; last check (if any) said fresh, or never checked yet.
38    Fresh,
39    /// A freshness check or refresh attempt is currently in flight — this
40    /// IS the single-flight guard: a second `CheckRequested` while already
41    /// `Refreshing` gets `Event::AlreadyInFlight`, never a second
42    /// `RunFreshnessCheck`/`RunRefresh`. Carries forward the failure count
43    /// from whatever `Failed` state (if any) preceded this attempt — the
44    /// only place that count lives, since transitioning through
45    /// `Refreshing` would otherwise lose it before `RefreshFailed` can read
46    /// it back out to increment. `prior_reauth` keeps the `NeedsReauth` an
47    /// on-demand check started from, so a refusal is put back after any
48    /// refresh that doesn't succeed instead of being forgotten. `offline`
49    /// carries `Failed { offline }` through the attempt: still offline until
50    /// an answer says otherwise.
51    Refreshing {
52        prior_failures: u32,
53        prior_reauth: Option<Box<CredentialState>>,
54        offline: bool,
55    },
56    /// Last refresh attempt failed with a transient error (no answer from the
57    /// server, a 5xx, a parse failure) — will be retried on the next
58    /// `ensure_fresh`/sweep tick. An unreachable server leaves
59    /// `consecutive_failures` where it was: being offline never counts toward
60    /// `NEEDS_REAUTH_THRESHOLD`.
61    Failed {
62        consecutive_failures: u32,
63        last_error: String,
64        /// The last attempt got no answer at all (`RefreshErrorKind::Unreachable`).
65        offline: bool,
66    },
67    /// Either `consecutive_failures` crossed `NEEDS_REAUTH_THRESHOLD`, or a
68    /// refresh closure explicitly reported
69    /// `RefreshErrorKind::PermanentAuthFailure` (no need to accumulate
70    /// failures for an error already known permanent). `rejected` tells the
71    /// two apart: true when the credential itself was refused (only a human
72    /// login helps; the sweep stops retrying it), false when answered
73    /// transient failures merely piled up (the sweep and on-demand checks keep
74    /// retrying, and a recovering server cures it).
75    NeedsReauth {
76        since_unix: u64,
77        reason: String,
78        rejected: bool,
79    },
80}
81
82/// What a registered refresh closure's failure means for scheduling.
83#[derive(Debug, Clone, PartialEq)]
84pub enum RefreshErrorKind {
85    /// The server answered with a transient error, or the answer couldn't be
86    /// parsed — worth retrying.
87    Transient(String),
88    /// The server couldn't be reached at all: no HTTP response (DNS, connect,
89    /// reset, timeout). Says nothing about the credential, so it never counts
90    /// toward `NEEDS_REAUTH_THRESHOLD`; the sweep keeps retrying until the
91    /// network is back.
92    Unreachable(String),
93    /// The credential itself is rejected (e.g. an OAuth server's
94    /// `invalid_grant` for a revoked/expired refresh_token) — retrying with
95    /// the SAME credential will never succeed; only a fresh login fixes it.
96    PermanentAuthFailure(String),
97}
98
99impl RefreshErrorKind {
100    fn message(&self) -> &str {
101        match self {
102            RefreshErrorKind::Transient(m)
103            | RefreshErrorKind::Unreachable(m)
104            | RefreshErrorKind::PermanentAuthFailure(m) => m,
105        }
106    }
107}
108
109#[derive(Debug, Clone, PartialEq)]
110pub enum Command {
111    Register { id: String },
112    #[cfg(any(test, feature = "test-support"))]
113    Unregister { id: String },
114    /// `ensure_fresh` or a sweep tick wants to know/ensure this credential
115    /// is fresh.
116    CheckRequested { id: String },
117    /// The orchestrator ran `is_fresh()` and is reporting the result.
118    /// `generation` is the value from the `RunFreshnessCheck` event that
119    /// triggered this call — see `Event::RunFreshnessCheck`'s doc comment.
120    FreshnessChecked {
121        id: String,
122        is_fresh: bool,
123        generation: u64,
124    },
125    /// `generation` carried forward from the `RunRefresh` event that
126    /// triggered this call.
127    RefreshSucceeded { id: String, generation: u64 },
128    RefreshFailed {
129        id: String,
130        error: RefreshErrorKind,
131        generation: u64,
132    },
133}
134
135#[derive(Debug, Clone, PartialEq)]
136pub enum Event {
137    /// Orchestrator should call the registered `is_fresh()` closure now.
138    /// `generation` is this id's registration epoch at dispatch time — the
139    /// orchestrator must echo it back unchanged in the resulting
140    /// `Command::FreshnessChecked` (and, if a refresh follows, in
141    /// `RefreshSucceeded`/`RefreshFailed` too). This lets the reducer detect
142    /// a stale completion: if `register()` replaces this id's closures
143    /// (bumping its generation) while `is_fresh()`/`refresh()` is still
144    /// awaiting, the eventual result would otherwise silently clobber the
145    /// freshly re-registered credential's state with a verdict about
146    /// closures that no longer apply (reagent re-review on #2275).
147    RunFreshnessCheck { id: String, generation: u64 },
148    /// Orchestrator should call the registered `refresh()` closure now.
149    /// `generation` carries the same epoch forward from `RunFreshnessCheck`.
150    RunRefresh { id: String, generation: u64 },
151    /// Another caller is already checking/refreshing this id — the
152    /// orchestrator should wait on the id's `Notify` and re-dispatch
153    /// `CheckRequested` once woken.
154    AlreadyInFlight { id: String },
155    /// `id` was never registered (or was just unregistered).
156    Unregistered { id: String },
157    /// Diagnostics-only — mapped 1:1 to `tracing` by the orchestrator.
158    BecameFresh { id: String },
159    BecameFailed {
160        id: String,
161        consecutive_failures: u32,
162        error: String,
163    },
164    /// The server couldn't be reached; the failure count is unchanged.
165    BecameUnreachable { id: String, error: String },
166    BecameNeedsReauth { id: String, reason: String, rejected: bool },
167}
168
169fn now_unix() -> u64 {
170    agentmux_common::time::now_secs_u64()
171}
172
173/// `states` is the orchestrator's whole coordination table; `generations`
174/// tracks each id's CURRENT registration epoch so a completion from a
175/// superseded registration can be told apart from a current one (see
176/// `Event::RunFreshnessCheck`'s doc comment); `next_generation` is a single
177/// counter shared across ALL ids, strictly increasing, never reused —
178/// deliberately NOT a per-id counter restarted at 0 on each `Register`,
179/// because an unregister-then-re-register sequence would then hand the new
180/// registration the SAME generation number the old one had, and a stale
181/// completion from the old registration (still in flight when the
182/// unregister/re-register raced in) would wrongly pass the staleness check
183/// instead of being discarded (reagent re-review on #2275). One reducer
184/// call per dispatched command, sub-millisecond, never awaits.
185pub fn update(
186    states: &mut HashMap<String, CredentialState>,
187    generations: &mut HashMap<String, u64>,
188    next_generation: &mut u64,
189    cmd: Command,
190) -> Vec<Event> {
191    match cmd {
192        Command::Register { id } => {
193            // Replacing an already-registered id is safe here specifically
194            // because single-flight is guarded by THIS reducer's own state,
195            // not by an external lock a caller could be left blocked on
196            // (the pre-refactor design's latent race). A caller currently
197            // waiting via AlreadyInFlight re-dispatches CheckRequested once
198            // woken and just sees the fresh entry's is_fresh() result.
199            let generation = *next_generation;
200            *next_generation += 1;
201            generations.insert(id.clone(), generation);
202            states.insert(id, CredentialState::Fresh);
203            Vec::new()
204        }
205        #[cfg(any(test, feature = "test-support"))]
206        Command::Unregister { id } => {
207            // Removing the entry here is just memory hygiene, not a
208            // correctness requirement — next_generation never reuses a
209            // number, so a future re-registration can't collide with a
210            // stale completion's captured generation either way.
211            generations.remove(&id);
212            states.remove(&id);
213            vec![Event::Unregistered { id }]
214        }
215        Command::CheckRequested { id } => match states.get(&id) {
216            None => vec![Event::Unregistered { id }],
217            Some(CredentialState::Refreshing { .. }) => vec![Event::AlreadyInFlight { id }],
218            Some(state) => {
219                // Carry the failure count forward through the Refreshing
220                // transition — it's the only place it lives, so overwriting
221                // it with a bare Refreshing here would otherwise strand
222                // RefreshFailed with no way to read the prior count back
223                // out and every failure would reset to 1.
224                let (prior_failures, prior_reauth, offline) = match state {
225                    CredentialState::Failed {
226                        consecutive_failures,
227                        offline,
228                        ..
229                    } => (*consecutive_failures, None, *offline),
230                    CredentialState::Fresh => (0, None, false),
231                    CredentialState::NeedsReauth { .. } => (0, Some(Box::new(state.clone())), false),
232                    CredentialState::Refreshing { .. } => unreachable!("matched above"),
233                };
234                states.insert(id.clone(), CredentialState::Refreshing { prior_failures, prior_reauth, offline });
235                let generation = *generations.get(&id).unwrap_or(&0);
236                vec![Event::RunFreshnessCheck { id, generation }]
237            }
238        },
239        Command::FreshnessChecked {
240            id,
241            is_fresh,
242            generation,
243        } => {
244            if generations.get(&id).copied() != Some(generation) {
245                // Stale completion: id was unregistered (generation gone)
246                // or re-registered (generation bumped) while is_fresh() was
247                // still awaiting. Either way this result is about closures
248                // that no longer apply — discard it rather than clobber the
249                // current epoch's state (reagent re-review on #2275).
250                return Vec::new();
251            }
252            if is_fresh {
253                let became_fresh = !matches!(states.get(&id), Some(CredentialState::Fresh));
254                states.insert(id.clone(), CredentialState::Fresh);
255                if became_fresh {
256                    vec![Event::BecameFresh { id }]
257                } else {
258                    Vec::new()
259                }
260            } else {
261                // Stays Refreshing — orchestrator now runs the actual refresh.
262                vec![Event::RunRefresh { id, generation }]
263            }
264        }
265        Command::RefreshSucceeded { id, generation } => {
266            if generations.get(&id).copied() != Some(generation) {
267                // Same stale-epoch hazard as FreshnessChecked above.
268                return Vec::new();
269            }
270            states.insert(id.clone(), CredentialState::Fresh);
271            vec![Event::BecameFresh { id }]
272        }
273        Command::RefreshFailed {
274            id,
275            error,
276            generation,
277        } => {
278            if generations.get(&id).copied() != Some(generation) {
279                // Same stale-epoch hazard as FreshnessChecked above.
280                return Vec::new();
281            }
282            let reason = error.message().to_string();
283            let permanent = matches!(error, RefreshErrorKind::PermanentAuthFailure(_));
284            let (prior_failures, prior_reauth) = match states.get(&id) {
285                Some(CredentialState::Refreshing { prior_failures, prior_reauth, .. }) => {
286                    (*prior_failures, prior_reauth.clone())
287                }
288                _ => (0, None),
289            };
290            let unreachable = matches!(error, RefreshErrorKind::Unreachable(_));
291            // A refusal stands until a refresh succeeds: neither silence nor a
292            // transient answer says the refused credential works.
293            if !permanent {
294                if let Some(prior) = prior_reauth.filter(|p| matches!(**p, CredentialState::NeedsReauth { rejected: true, .. })) {
295                    states.insert(id.clone(), *prior);
296                    return if unreachable { vec![Event::BecameUnreachable { id, error: reason }] } else { Vec::new() };
297                }
298            }
299            if unreachable {
300                states.insert(
301                    id.clone(),
302                    CredentialState::Failed {
303                        consecutive_failures: prior_failures,
304                        last_error: reason.clone(),
305                        offline: true,
306                    },
307                );
308                return vec![Event::BecameUnreachable { id, error: reason }];
309            }
310            let consecutive_failures = prior_failures + 1;
311            if permanent || consecutive_failures >= NEEDS_REAUTH_THRESHOLD {
312                states.insert(
313                    id.clone(),
314                    CredentialState::NeedsReauth {
315                        since_unix: now_unix(),
316                        reason: reason.clone(),
317                        rejected: permanent,
318                    },
319                );
320                vec![Event::BecameNeedsReauth { id, reason, rejected: permanent }]
321            } else {
322                states.insert(
323                    id.clone(),
324                    CredentialState::Failed {
325                        consecutive_failures,
326                        last_error: reason.clone(),
327                        offline: false,
328                    },
329                );
330                vec![Event::BecameFailed {
331                    id,
332                    consecutive_failures,
333                    error: reason,
334                }]
335            }
336        }
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    /// Bundles `states` + `generations` + `next_generation` so tests can
345    /// dispatch commands without threading three pieces of state through
346    /// every call site by hand.
347    #[derive(Default)]
348    struct Harness {
349        states: HashMap<String, CredentialState>,
350        generations: HashMap<String, u64>,
351        next_generation: u64,
352    }
353
354    impl Harness {
355        fn dispatch(&mut self, cmd: Command) -> Vec<Event> {
356            update(
357                &mut self.states,
358                &mut self.generations,
359                &mut self.next_generation,
360                cmd,
361            )
362        }
363
364        fn get(&self, id: &str) -> Option<&CredentialState> {
365            self.states.get(id)
366        }
367
368        fn contains_key(&self, id: &str) -> bool {
369            self.states.contains_key(id)
370        }
371
372        fn generation_of(&self, id: &str) -> u64 {
373            *self.generations.get(id).expect("id should be registered")
374        }
375    }
376
377    fn registered() -> Harness {
378        let mut h = Harness::default();
379        h.dispatch(Command::Register { id: "cred".into() });
380        h
381    }
382
383    #[test]
384    fn register_starts_fresh() {
385        let m = registered();
386        assert_eq!(m.get("cred"), Some(&CredentialState::Fresh));
387    }
388
389    #[test]
390    fn check_on_fresh_transitions_to_refreshing_and_requests_a_check() {
391        let mut m = registered();
392        let gen = m.generation_of("cred");
393        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
394        assert_eq!(
395            events,
396            vec![Event::RunFreshnessCheck {
397                id: "cred".into(),
398                generation: gen
399            }]
400        );
401        assert_eq!(
402            m.get("cred"),
403            Some(&CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
404        );
405    }
406
407    #[test]
408    fn a_second_check_while_refreshing_gets_already_in_flight_not_a_second_run() {
409        let mut m = registered();
410        m.dispatch(Command::CheckRequested { id: "cred".into() });
411        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
412        assert_eq!(events, vec![Event::AlreadyInFlight { id: "cred".into() }]);
413        // Still just one credential, still Refreshing — the second dispatch
414        // did not disturb the in-flight state.
415        assert_eq!(
416            m.get("cred"),
417            Some(&CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
418        );
419    }
420
421    #[test]
422    fn freshness_checked_true_returns_to_fresh_and_reports_became_fresh() {
423        let mut m = registered();
424        let gen = m.generation_of("cred");
425        m.dispatch(Command::CheckRequested { id: "cred".into() });
426        let events = m.dispatch(Command::FreshnessChecked {
427            id: "cred".into(),
428            is_fresh: true,
429            generation: gen,
430        });
431        assert_eq!(m.get("cred"), Some(&CredentialState::Fresh));
432        assert_eq!(events, vec![Event::BecameFresh { id: "cred".into() }]);
433    }
434
435    #[test]
436    fn freshness_checked_false_requests_a_refresh_and_stays_refreshing() {
437        let mut m = registered();
438        let gen = m.generation_of("cred");
439        m.dispatch(Command::CheckRequested { id: "cred".into() });
440        let events = m.dispatch(Command::FreshnessChecked {
441            id: "cred".into(),
442            is_fresh: false,
443            generation: gen,
444        });
445        assert_eq!(
446            events,
447            vec![Event::RunRefresh {
448                id: "cred".into(),
449                generation: gen
450            }]
451        );
452        assert_eq!(
453            m.get("cred"),
454            Some(&CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
455        );
456    }
457
458    #[test]
459    fn refresh_succeeded_returns_to_fresh_and_resets_any_failure_count() {
460        let mut m = registered();
461        let gen = m.generation_of("cred");
462        m.dispatch(Command::CheckRequested { id: "cred".into() });
463        m.dispatch(Command::RefreshFailed {
464            id: "cred".into(),
465            error: RefreshErrorKind::Transient("boom".into()),
466            generation: gen,
467        });
468        m.dispatch(Command::CheckRequested { id: "cred".into() });
469        let events = m.dispatch(Command::RefreshSucceeded {
470            id: "cred".into(),
471            generation: gen,
472        });
473        assert_eq!(events, vec![Event::BecameFresh { id: "cred".into() }]);
474        assert_eq!(m.get("cred"), Some(&CredentialState::Fresh));
475    }
476
477    #[test]
478    fn refresh_failed_transient_moves_to_failed_with_count_one() {
479        let mut m = registered();
480        let gen = m.generation_of("cred");
481        m.dispatch(Command::CheckRequested { id: "cred".into() });
482        let events = m.dispatch(Command::RefreshFailed {
483            id: "cred".into(),
484            error: RefreshErrorKind::Transient("network blip".into()),
485            generation: gen,
486        });
487        assert_eq!(
488            events,
489            vec![Event::BecameFailed {
490                id: "cred".into(),
491                consecutive_failures: 1,
492                error: "network blip".into(),
493            }]
494        );
495        assert_eq!(
496            m.get("cred"),
497            Some(&CredentialState::Failed {
498                consecutive_failures: 1,
499                last_error: "network blip".into(),
500                offline: false,
501            })
502        );
503    }
504
505    #[test]
506    fn a_failed_refresh_does_not_mark_the_credential_fresh() {
507        // Port of the pre-refactor scheduler test — a second check after a
508        // failure must retry (not treat the failed attempt as success).
509        let mut m = registered();
510        let gen = m.generation_of("cred");
511        m.dispatch(Command::CheckRequested { id: "cred".into() });
512        m.dispatch(Command::RefreshFailed {
513            id: "cred".into(),
514            error: RefreshErrorKind::Transient("nope".into()),
515            generation: gen,
516        });
517        assert!(!matches!(m.get("cred"), Some(CredentialState::Fresh)));
518        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
519        assert_eq!(
520            events,
521            vec![Event::RunFreshnessCheck {
522                id: "cred".into(),
523                generation: gen
524            }]
525        );
526    }
527
528    #[test]
529    fn permanent_auth_failure_skips_straight_to_needs_reauth_on_the_first_failure() {
530        let mut m = registered();
531        let gen = m.generation_of("cred");
532        m.dispatch(Command::CheckRequested { id: "cred".into() });
533        let events = m.dispatch(Command::RefreshFailed {
534            id: "cred".into(),
535            error: RefreshErrorKind::PermanentAuthFailure("invalid_grant".into()),
536            generation: gen,
537        });
538        assert!(matches!(
539            events.as_slice(),
540            [Event::BecameNeedsReauth { .. }]
541        ));
542        assert!(matches!(
543            m.get("cred"),
544            Some(CredentialState::NeedsReauth { rejected: true, .. })
545        ));
546    }
547
548    #[test]
549    fn five_consecutive_transient_failures_escalate_to_needs_reauth() {
550        let mut m = registered();
551        let gen = m.generation_of("cred");
552        for i in 1..=(NEEDS_REAUTH_THRESHOLD - 1) {
553            m.dispatch(Command::CheckRequested { id: "cred".into() });
554            let events = m.dispatch(Command::RefreshFailed {
555                id: "cred".into(),
556                error: RefreshErrorKind::Transient(format!("attempt {i}")),
557                generation: gen,
558            });
559            assert!(
560                matches!(events.as_slice(), [Event::BecameFailed { .. }]),
561                "attempt {i} should still be a transient Failed, not NeedsReauth yet"
562            );
563        }
564        m.dispatch(Command::CheckRequested { id: "cred".into() });
565        let events = m.dispatch(Command::RefreshFailed {
566            id: "cred".into(),
567            error: RefreshErrorKind::Transient("final straw".into()),
568            generation: gen,
569        });
570        assert!(matches!(
571            events.as_slice(),
572            [Event::BecameNeedsReauth { .. }]
573        ));
574        // Nothing refused the credential itself: an offline stretch must not
575        // read as a dead sign-in.
576        assert!(matches!(
577            m.get("cred"),
578            Some(CredentialState::NeedsReauth { rejected: false, .. })
579        ));
580    }
581
582    /// A long offline stretch is many unreachable refreshes; none of them is
583    /// evidence against the credential.
584    #[test]
585    fn an_unreachable_server_never_escalates_to_needs_reauth() {
586        let mut m = registered();
587        let gen = m.generation_of("cred");
588        for i in 1..=(NEEDS_REAUTH_THRESHOLD * 4) {
589            m.dispatch(Command::CheckRequested { id: "cred".into() });
590            let events = m.dispatch(Command::RefreshFailed {
591                id: "cred".into(),
592                error: RefreshErrorKind::Unreachable(format!("connect error {i}")),
593                generation: gen,
594            });
595            assert_eq!(
596                events,
597                vec![Event::BecameUnreachable {
598                    id: "cred".into(),
599                    error: format!("connect error {i}"),
600                }]
601            );
602        }
603        assert_eq!(
604            m.get("cred"),
605            Some(&CredentialState::Failed {
606                consecutive_failures: 0,
607                last_error: format!("connect error {}", NEEDS_REAUTH_THRESHOLD * 4),
608                offline: true,
609            })
610        );
611    }
612
613    /// Offline neither adds to nor clears the count of failures the server
614    /// itself answered with.
615    #[test]
616    fn unreachable_refreshes_keep_the_count_of_answered_failures() {
617        let mut m = registered();
618        let gen = m.generation_of("cred");
619        let mut fail = |m: &mut Harness, error: RefreshErrorKind| {
620            m.dispatch(Command::CheckRequested { id: "cred".into() });
621            m.dispatch(Command::RefreshFailed { id: "cred".into(), error, generation: gen })
622        };
623        fail(&mut m, RefreshErrorKind::Transient("503".into()));
624        fail(&mut m, RefreshErrorKind::Transient("503".into()));
625        for _ in 0..10 {
626            fail(&mut m, RefreshErrorKind::Unreachable("offline".into()));
627        }
628        let events = fail(&mut m, RefreshErrorKind::Transient("503".into()));
629        assert_eq!(
630            events,
631            vec![Event::BecameFailed {
632                id: "cred".into(),
633                consecutive_failures: 3,
634                error: "503".into(),
635            }]
636        );
637    }
638
639    /// An on-demand check of a refused credential that can't reach the
640    /// server must not forget the refusal: offline is no news about it.
641    #[test]
642    fn an_unreachable_refresh_keeps_a_refusal() {
643        let mut m = registered();
644        let gen = m.generation_of("cred");
645        m.dispatch(Command::CheckRequested { id: "cred".into() });
646        m.dispatch(Command::RefreshFailed {
647            id: "cred".into(),
648            error: RefreshErrorKind::PermanentAuthFailure("invalid_grant".into()),
649            generation: gen,
650        });
651        let refused = m.get("cred").cloned();
652        m.dispatch(Command::CheckRequested { id: "cred".into() });
653        let events = m.dispatch(Command::RefreshFailed {
654            id: "cred".into(),
655            error: RefreshErrorKind::Unreachable("offline".into()),
656            generation: gen,
657        });
658        assert_eq!(events, vec![Event::BecameUnreachable { id: "cred".into(), error: "offline".into() }]);
659        assert_eq!(m.get("cred").cloned(), refused);
660        assert!(matches!(m.get("cred"), Some(CredentialState::NeedsReauth { rejected: true, .. })));
661    }
662
663    /// A transient answer doesn't say a refused credential works either.
664    #[test]
665    fn a_transient_answer_keeps_a_refusal() {
666        let mut m = registered();
667        let gen = m.generation_of("cred");
668        m.dispatch(Command::CheckRequested { id: "cred".into() });
669        m.dispatch(Command::RefreshFailed {
670            id: "cred".into(),
671            error: RefreshErrorKind::PermanentAuthFailure("invalid_grant".into()),
672            generation: gen,
673        });
674        m.dispatch(Command::CheckRequested { id: "cred".into() });
675        m.dispatch(Command::RefreshFailed {
676            id: "cred".into(),
677            error: RefreshErrorKind::Transient("503".into()),
678            generation: gen,
679        });
680        assert!(matches!(m.get("cred"), Some(CredentialState::NeedsReauth { rejected: true, .. })));
681    }
682
683    /// Answered failures that piled up are no refusal; going offline after
684    /// them is recorded as offline.
685    #[test]
686    fn an_unreachable_refresh_after_piled_up_failures_is_offline() {
687        let mut m = registered();
688        let gen = m.generation_of("cred");
689        for _ in 0..NEEDS_REAUTH_THRESHOLD {
690            m.dispatch(Command::CheckRequested { id: "cred".into() });
691            m.dispatch(Command::RefreshFailed {
692                id: "cred".into(),
693                error: RefreshErrorKind::Transient("503".into()),
694                generation: gen,
695            });
696        }
697        assert!(matches!(m.get("cred"), Some(CredentialState::NeedsReauth { rejected: false, .. })));
698        m.dispatch(Command::CheckRequested { id: "cred".into() });
699        m.dispatch(Command::RefreshFailed {
700            id: "cred".into(),
701            error: RefreshErrorKind::Unreachable("connect".into()),
702            generation: gen,
703        });
704        assert!(matches!(m.get("cred"), Some(CredentialState::Failed { offline: true, .. })));
705    }
706
707    #[test]
708    fn check_requested_on_needs_reauth_still_runs_a_fresh_check_on_demand() {
709        // A human may have logged in again out-of-band (e.g. muxbus.login)
710        // since the credential was marked NeedsReauth — on-demand checks
711        // (unlike the sweep loop) must not just give up permanently.
712        let mut m = registered();
713        let gen = m.generation_of("cred");
714        m.dispatch(Command::CheckRequested { id: "cred".into() });
715        m.dispatch(Command::RefreshFailed {
716            id: "cred".into(),
717            error: RefreshErrorKind::PermanentAuthFailure("dead".into()),
718            generation: gen,
719        });
720        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
721        assert_eq!(
722            events,
723            vec![Event::RunFreshnessCheck {
724                id: "cred".into(),
725                generation: gen
726            }]
727        );
728    }
729
730    #[test]
731    fn check_requested_on_an_unregistered_id_reports_unregistered() {
732        let mut m = Harness::default();
733        let events = m.dispatch(Command::CheckRequested { id: "nope".into() });
734        assert_eq!(events, vec![Event::Unregistered { id: "nope".into() }]);
735    }
736
737    #[test]
738    fn unregister_then_check_reports_unregistered() {
739        let mut m = registered();
740        m.dispatch(Command::Unregister { id: "cred".into() });
741        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
742        assert_eq!(events, vec![Event::Unregistered { id: "cred".into() }]);
743    }
744
745    #[test]
746    fn re_registering_an_id_that_is_mid_refresh_does_not_leave_anything_orphaned() {
747        // The pre-refactor design's latent race: register() on an
748        // already-registered id replaced the Entry (including its lock), so
749        // a caller already blocked on the OLD entry's lock waited forever.
750        // Here there's no separate lock to orphan — Register always resets
751        // cleanly to Fresh, and the next CheckRequested from any caller
752        // (old or new) just sees that fresh state.
753        let mut m = registered();
754        m.dispatch(Command::CheckRequested { id: "cred".into() });
755        assert_eq!(
756            m.get("cred"),
757            Some(&CredentialState::Refreshing { prior_failures: 0, prior_reauth: None, offline: false })
758        );
759        m.dispatch(Command::Register { id: "cred".into() });
760        assert_eq!(m.get("cred"), Some(&CredentialState::Fresh));
761        let new_gen = m.generation_of("cred");
762        let events = m.dispatch(Command::CheckRequested { id: "cred".into() });
763        assert_eq!(
764            events,
765            vec![Event::RunFreshnessCheck {
766                id: "cred".into(),
767                generation: new_gen
768            }]
769        );
770    }
771
772    #[test]
773    fn a_stale_completion_after_unregister_does_not_resurrect_a_phantom_entry() {
774        // reagent re-review on #2275: an in-flight check/refresh that loses
775        // a race with a concurrent unregister() must not reinsert an entry
776        // for an id nothing owns anymore — the sweep loop only walks
777        // registered closures, so a resurrected entry would leak forever
778        // and scheduler.state(id) would misreport it as still registered.
779        fn mid_check_then_unregistered() -> (Harness, u64) {
780            let mut m = registered();
781            let gen = m.generation_of("cred");
782            m.dispatch(Command::CheckRequested { id: "cred".into() });
783            m.dispatch(Command::Unregister { id: "cred".into() });
784            assert!(!m.contains_key("cred"));
785            (m, gen)
786        }
787
788        let stale_completion_builders: [fn(u64) -> Command; 4] = [
789            |gen| Command::FreshnessChecked {
790                id: "cred".into(),
791                is_fresh: true,
792                generation: gen,
793            },
794            |gen| Command::FreshnessChecked {
795                id: "cred".into(),
796                is_fresh: false,
797                generation: gen,
798            },
799            |gen| Command::RefreshSucceeded {
800                id: "cred".into(),
801                generation: gen,
802            },
803            |gen| Command::RefreshFailed {
804                id: "cred".into(),
805                error: RefreshErrorKind::Transient("late".into()),
806                generation: gen,
807            },
808        ];
809        for build_stale_completion in stale_completion_builders {
810            let (mut m, gen) = mid_check_then_unregistered();
811            let events = m.dispatch(build_stale_completion(gen));
812            assert_eq!(events, Vec::new());
813            assert!(
814                !m.contains_key("cred"),
815                "a stale completion must not resurrect the entry"
816            );
817        }
818    }
819
820    #[test]
821    fn a_stale_completion_after_re_register_does_not_clobber_the_new_epoch() {
822        // reagent re-review on #2275: if register() is called again for an
823        // id while an OLD in-flight check/refresh for that same id is still
824        // awaiting, the stale completion (belonging to the pre-registration
825        // closures) must not overwrite the freshly re-registered
826        // credential's Fresh state — it belongs to a superseded epoch and
827        // has nothing meaningful to say about the current one.
828        let mut m = registered();
829        let old_gen = m.generation_of("cred");
830        m.dispatch(Command::CheckRequested { id: "cred".into() });
831
832        // Re-register while the "old" check/refresh is still in flight —
833        // bumps the generation and resets to Fresh.
834        m.dispatch(Command::Register { id: "cred".into() });
835        assert_eq!(m.get("cred"), Some(&CredentialState::Fresh));
836        let new_gen = m.generation_of("cred");
837        assert_ne!(old_gen, new_gen);
838
839        // The old attempt's belated failure must not land.
840        let events = m.dispatch(Command::RefreshFailed {
841            id: "cred".into(),
842            error: RefreshErrorKind::PermanentAuthFailure("stale invalid_grant".into()),
843            generation: old_gen,
844        });
845        assert_eq!(events, Vec::new());
846        assert_eq!(
847            m.get("cred"),
848            Some(&CredentialState::Fresh),
849            "a stale completion from a superseded registration must not mask the new one"
850        );
851    }
852
853    #[test]
854    fn a_stale_completion_survives_an_unregister_then_re_register_of_the_same_id() {
855        // reagent re-review on #2275, second round: a PER-ID counter that
856        // restarts at 0 on each Register would hand an unregister-then-
857        // re-register sequence the SAME generation number the original
858        // registration had, so a stale completion from before the
859        // unregister would wrongly pass the staleness check after the
860        // re-register instead of being discarded. next_generation is a
861        // single counter shared across every id specifically so this can't
862        // happen — assert the two registrations never collide even across
863        // an intervening unregister.
864        let mut m = registered();
865        let old_gen = m.generation_of("cred");
866        m.dispatch(Command::CheckRequested { id: "cred".into() });
867
868        m.dispatch(Command::Unregister { id: "cred".into() });
869        m.dispatch(Command::Register { id: "cred".into() });
870        let new_gen = m.generation_of("cred");
871        assert_ne!(
872            old_gen, new_gen,
873            "unregister-then-register must never reissue a prior generation number"
874        );
875
876        let events = m.dispatch(Command::RefreshFailed {
877            id: "cred".into(),
878            error: RefreshErrorKind::PermanentAuthFailure("stale invalid_grant".into()),
879            generation: old_gen,
880        });
881        assert_eq!(events, Vec::new());
882        assert_eq!(
883            m.get("cred"),
884            Some(&CredentialState::Fresh),
885            "a stale completion from before the unregister must not mask the re-registered credential"
886        );
887    }
888}