Skip to main content

codewhale_runtime/
retry_status.rs

1//! Process-wide retry-state surface (#499).
2//!
3//! Read-side caveat (0.9.4): the renderer this module was written for was
4//! the legacy footer's retry banner, which went with `FooterWidget`. The
5//! *producer* — `client::send_with_retry` — is still live and still records
6//! every retry, and `client`'s own tests read it back through `snapshot`.
7//! The read surface (`snapshot`, the countdown, the banner fields) is
8//! therefore test-gated (`cfg(any(test, feature = "test-support"))` where
9//! possible, so the TUI's tests reach it through the `test-support`
10//! feature; `cfg_attr(not(test))` allows where prod constructs); a renderer
11//! restores it by dropping the gates. Give the banner a renderer, or
12//! delete the producer too — but not half of it.
13//!
14//! The HTTP retry path in `client::send_with_retry` already times its
15//! waits and knows the error category. This module gives the TUI a way
16//! to observe that state — `start`, `succeeded`, and `failed` flip a
17//! global `RetryState` that the footer / status panel reads each frame.
18//!
19//! Why a process-wide global: the user-facing TUI runs as one engine
20//! per process, and the only retry state we want to surface is the one
21//! the user is staring at. Sub-agent retries in background tasks
22//! deliberately do **not** light up the foreground banner — they're
23//! supposed to be invisible. If a future feature ever needs per-engine
24//! retry surfaces, swap this for an `Arc<RwLock<...>>` carried on the
25//! `EngineHandle`; the public API stays the same.
26//!
27//! The `Retry-After` pause is process-wide too, but keyed by provider scope:
28//! every request to the rate-limited route waits it out, and requests to any
29//! other route (another provider, a local runtime) do not.
30
31use std::collections::HashMap;
32use std::sync::{Mutex, OnceLock};
33use std::time::{Duration, Instant};
34
35/// Rate-limit pause deadlines, one per provider scope (see
36/// [`note_rate_limit`]). A 429 from one provider must not stall requests to
37/// another provider, a local runtime, or a sub-agent on a different route.
38type RateLimitPauses = HashMap<String, Instant>;
39
40/// One in-flight retry attempt. `deadline` is the wall-clock time the
41/// next request will fire — the UI subtracts `Instant::now()` from it
42/// to render a live countdown.
43#[derive(Debug, Clone)]
44pub struct RetryBanner {
45    /// 1-indexed retry attempt number (the first retry is attempt 1).
46    pub attempt: u32,
47    /// Time at which the next request will be sent.
48    pub deadline: Instant,
49    /// Short human-readable reason ("rate limited", "server error", …).
50    pub reason: String,
51}
52
53/// Snapshot of the retry surface for the UI to render.
54#[derive(Debug, Clone, Default)]
55pub enum RetryState {
56    /// No retry in flight. Banner hidden.
57    #[default]
58    Idle,
59    /// A request is sleeping before retrying. Show countdown banner.
60    Active(RetryBanner),
61    /// All retries exhausted; show failure row until the next turn
62    /// starts. `since` records when the row was set so a future polish
63    /// pass can age it out automatically; today the engine clears it on
64    /// `TurnStarted`.
65    Failed { reason: String, since: Instant },
66}
67
68impl RetryState {
69    /// Wall-clock seconds remaining on the active banner, or `None` if
70    /// not active. Saturates at zero — the renderer should treat any
71    /// negative remaining as "firing now".
72    #[cfg(any(test, feature = "test-support"))]
73    #[must_use]
74    pub fn seconds_remaining(&self) -> Option<u64> {
75        match self {
76            Self::Active(banner) => Some(
77                banner
78                    .deadline
79                    .saturating_duration_since(Instant::now())
80                    .as_secs(),
81            ),
82            _ => None,
83        }
84    }
85
86    /// Whether the failure row should still be shown. Mirrors the
87    /// "until next turn" rule in the issue spec; the engine clears it
88    /// explicitly via [`clear`] on `TurnStarted`.
89    #[cfg(any(test, feature = "test-support"))]
90    #[must_use]
91    pub fn is_failed(&self) -> bool {
92        matches!(self, Self::Failed { .. })
93    }
94}
95
96/// Lazy-init the cell on first read so callers don't have to initialize
97/// process-wide state at boot.
98#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
99fn with_state<R>(f: impl FnOnce(&mut RetryState) -> R) -> R {
100    static STATE: OnceLock<Mutex<RetryState>> = OnceLock::new();
101    let mut state = STATE
102        .get_or_init(|| Mutex::new(RetryState::Idle))
103        .lock()
104        .unwrap_or_else(|error| error.into_inner());
105    f(&mut state)
106}
107
108#[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
109fn with_rate_limit<R>(f: impl FnOnce(&mut RateLimitPauses) -> R) -> R {
110    static STATE: OnceLock<Mutex<RateLimitPauses>> = OnceLock::new();
111    let mut state = STATE
112        .get_or_init(|| Mutex::new(HashMap::new()))
113        .lock()
114        .unwrap_or_else(|error| error.into_inner());
115    f(&mut state)
116}
117
118/// Under test, this state is per-thread.
119///
120/// Production has exactly one foreground engine per process, so a global is the
121/// right model there. The test harness does not: retry state is written as a
122/// side effect of *any* client request, by production code that has no test
123/// guard to take, so a real request in one test could publish a banner or a
124/// provider pause into another test's assertions. Scoping by thread removes the
125/// race at its source rather than asking every future test that happens to
126/// perform HTTP to remember a lock.
127///
128/// This changes behavior (a `Retry-After` pause no longer holds across tokio
129/// worker threads), so it is *not* part of `test-support`, which only adds
130/// helpers. The TUI's tests opt in with `test-thread-scoped-state`, and even
131/// then only a build with debug assertions gets it: an optimized build, e.g.
132/// `cargo build --release --workspace --all-features`, keeps the process-wide
133/// pause. Cargo unifies features across one build, so under
134/// `cargo test --workspace` (or a debug `--all-features` build) the debug
135/// `codewhale` binary that integration tests spawn gets the per-thread pause
136/// too; release and optimized binaries never do.
137#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
138fn with_state<R>(f: impl FnOnce(&mut RetryState) -> R) -> R {
139    #[allow(clippy::type_complexity)]
140    static STATE: OnceLock<Mutex<std::collections::HashMap<std::thread::ThreadId, RetryState>>> =
141        OnceLock::new();
142    let mut by_thread = STATE
143        .get_or_init(|| Mutex::new(std::collections::HashMap::new()))
144        .lock()
145        .unwrap_or_else(|error| error.into_inner());
146    f(by_thread
147        .entry(std::thread::current().id())
148        .or_insert(RetryState::Idle))
149}
150
151#[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
152fn with_rate_limit<R>(f: impl FnOnce(&mut RateLimitPauses) -> R) -> R {
153    static STATE: OnceLock<Mutex<HashMap<std::thread::ThreadId, RateLimitPauses>>> =
154        OnceLock::new();
155    let mut by_thread = STATE
156        .get_or_init(|| Mutex::new(HashMap::new()))
157        .lock()
158        .unwrap_or_else(|error| error.into_inner());
159    f(by_thread.entry(std::thread::current().id()).or_default())
160}
161
162/// Read snapshot for renderers. No production renderer exists since the
163/// legacy footer went away; `client` retry tests are the only readers.
164#[cfg(any(test, feature = "test-support"))]
165#[must_use]
166pub fn snapshot() -> RetryState {
167    with_state(|state| state.clone())
168}
169
170/// Extend the rate-limit pause window for one provider `scope` (the caller's
171/// route identity and host). This is separate from the footer banner so one
172/// successful concurrent request cannot clear another request's active
173/// `Retry-After` window, and it is keyed so a 429 from one provider never
174/// pauses requests to another. Expired scopes are dropped here, so the map
175/// holds at most the providers currently rate limited.
176pub fn note_rate_limit(scope: &str, delay: Duration) {
177    let now = Instant::now();
178    let deadline = now + delay;
179    with_rate_limit(|pauses| {
180        pauses.retain(|_, existing| *existing > now);
181        let current = pauses.entry(scope.to_string()).or_insert(deadline);
182        if *current < deadline {
183            *current = deadline;
184        }
185    });
186}
187
188/// Remaining rate-limit pause for `scope`, if any.
189#[must_use]
190pub fn rate_limit_remaining(scope: &str) -> Option<Duration> {
191    let now = Instant::now();
192    with_rate_limit(|pauses| match pauses.get(scope).copied() {
193        Some(deadline) if deadline > now => Some(deadline.duration_since(now)),
194        Some(_) => {
195            pauses.remove(scope);
196            None
197        }
198        None => None,
199    })
200}
201
202/// Mark an in-flight retry. `attempt` is the number of the *upcoming*
203/// retry (1 for the first); `delay` is how long the client will sleep
204/// before firing.
205pub fn start(attempt: u32, delay: Duration, reason: impl Into<String>) {
206    let banner = RetryBanner {
207        attempt,
208        deadline: Instant::now() + delay,
209        reason: reason.into(),
210    };
211    with_state(|state| *state = RetryState::Active(banner));
212}
213
214/// Mark the retry chain as having succeeded. Hides the banner.
215pub fn succeeded() {
216    with_state(|state| *state = RetryState::Idle);
217}
218
219/// Mark the retry chain as having exhausted retries. The renderer keeps
220/// the failure row until [`clear`] (typically called on `TurnStarted`).
221pub fn failed(reason: impl Into<String>) {
222    with_state(|state| {
223        *state = RetryState::Failed {
224            reason: reason.into(),
225            since: Instant::now(),
226        };
227    });
228}
229
230/// Reset to idle. Called on `TurnStarted` so the previous turn's
231/// failure row doesn't bleed into the next turn.
232pub fn clear() {
233    with_state(|state| *state = RetryState::Idle);
234}
235
236/// Drop every scope's rate-limit pause.
237#[cfg(any(test, feature = "test-support"))]
238pub fn clear_rate_limit() {
239    with_rate_limit(HashMap::clear);
240}
241
242/// Test helper: serialize tests that touch the global state so cargo's
243/// parallel runner can't observe a torn read. The guard is exported so
244/// tests in *other* modules (e.g. footer rendering tests) can hold the
245/// same lock as the ones in `retry_status::tests`.
246#[cfg(any(test, feature = "test-support"))]
247pub fn test_guard() -> std::sync::MutexGuard<'static, ()> {
248    static GUARD: Mutex<()> = Mutex::new(());
249    GUARD.lock().unwrap_or_else(|e| e.into_inner())
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    /// Acquire the cross-module test guard from [`super::test_guard`] and
257    /// reset state to `Idle` before yielding to the test body.
258    fn setup() -> std::sync::MutexGuard<'static, ()> {
259        let g = test_guard();
260        clear();
261        clear_rate_limit();
262        g
263    }
264
265    #[test]
266    fn idle_by_default_after_clear() {
267        let _g = setup();
268        assert!(matches!(snapshot(), RetryState::Idle));
269        assert_eq!(snapshot().seconds_remaining(), None);
270    }
271
272    #[test]
273    fn start_then_succeeded_returns_to_idle() {
274        let _g = setup();
275        start(1, Duration::from_secs(5), "rate limited");
276        let s = snapshot();
277        assert!(matches!(s, RetryState::Active(_)));
278        let remaining = s.seconds_remaining().unwrap();
279        assert!(remaining <= 5, "{remaining}");
280        succeeded();
281        assert!(matches!(snapshot(), RetryState::Idle));
282    }
283
284    #[test]
285    fn failed_persists_until_clear() {
286        let _g = setup();
287        failed("upstream 500");
288        let s = snapshot();
289        assert!(s.is_failed());
290        if let RetryState::Failed { reason, .. } = s {
291            assert_eq!(reason, "upstream 500");
292        } else {
293            panic!("expected Failed");
294        }
295        clear();
296        assert!(matches!(snapshot(), RetryState::Idle));
297    }
298
299    #[test]
300    fn deadline_in_past_yields_zero_remaining() {
301        let _g = setup();
302        // Bypass `start` so we can plant a deadline already in the past.
303        with_state(|state| {
304            *state = RetryState::Active(RetryBanner {
305                attempt: 2,
306                deadline: Instant::now() - Duration::from_secs(1),
307                reason: "test".into(),
308            });
309        });
310        assert_eq!(snapshot().seconds_remaining(), Some(0));
311        clear();
312    }
313
314    #[test]
315    fn rate_limit_deadline_survives_banner_clear() {
316        let _g = setup();
317        note_rate_limit("provider-a", Duration::from_secs(5));
318        start(1, Duration::from_secs(5), "rate limited");
319        succeeded();
320        assert!(
321            rate_limit_remaining("provider-a").is_some(),
322            "provider rate limit pause must not be cleared by an unrelated success"
323        );
324        clear_rate_limit();
325    }
326
327    #[test]
328    fn one_providers_rate_limit_does_not_pause_another() {
329        let _g = setup();
330        note_rate_limit("provider-a@api.a.example", Duration::from_secs(30));
331        assert!(rate_limit_remaining("provider-a@api.a.example").is_some());
332        assert_eq!(rate_limit_remaining("ollama@127.0.0.1:11434"), None);
333
334        // A shorter Retry-After never shortens an existing window.
335        note_rate_limit("provider-a@api.a.example", Duration::from_secs(1));
336        assert!(
337            rate_limit_remaining("provider-a@api.a.example").unwrap() > Duration::from_secs(20)
338        );
339        clear_rate_limit();
340        assert_eq!(rate_limit_remaining("provider-a@api.a.example"), None);
341    }
342}