Skip to main content

adk_vision/stream/
governor.rs

1//! The frame governor (spec 3.7 §7.9, scenario S11).
2
3use std::collections::VecDeque;
4
5use chrono::{DateTime, TimeDelta, Utc};
6use serde::{Deserialize, Serialize};
7
8use crate::error::{Result, VisionError};
9
10/// The billed minimum of one `sam-3.1` video request, in frames (spec 3.7 X5).
11const SAM_VIDEO_MIN_FRAMES: u64 = 50;
12
13/// What a stream may spend: a local sampling rate, escalations per minute and frame quotas
14/// per period (spec 3.7 §7.9).
15///
16/// | Field | Caps |
17/// |-------|------|
18/// | `local_fps`, `min_local_fps` | The local rate, and the lowest rate the governor steps down to before it pauses the source |
19/// | `local_frames_per_period` | Frames processed locally per period |
20/// | `escalations_per_minute` | Escalation requests in any 60 seconds |
21/// | `escalated_frames_per_period` | Frames billed for escalations per period, each request at least `min_frames_per_escalation` |
22/// | `period_secs` | The quota period; periods are aligned to the Unix epoch, so a day starts at 00:00 UTC |
23///
24/// # Example
25///
26/// ```
27/// use adk_vision::stream::FrameBudget;
28///
29/// // S11: local detection at 5 fps, escalations to sam-3.1 video, a daily frame quota.
30/// let budget = FrameBudget::new(5.0)
31///     .with_min_local_fps(1.0)
32///     .with_local_quota(200_000)
33///     .with_escalations_per_minute(2)
34///     .with_escalation_quota(5_000);
35/// assert_eq!(budget.min_frames_per_escalation, 50);
36/// assert_eq!(budget.period_secs, 86_400);
37/// assert!(budget.validate().is_ok());
38/// ```
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct FrameBudget {
42    /// The local sampling rate, in frames a second.
43    pub local_fps: f32,
44    /// The lowest local rate the governor steps down to before it pauses the source.
45    pub min_local_fps: f32,
46    /// Frames processed locally per period; unlimited when unset.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub local_frames_per_period: Option<u64>,
49    /// Escalation requests in any 60 seconds; unlimited when unset.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub escalations_per_minute: Option<u32>,
52    /// Frames billed for escalations per period; unlimited when unset.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub escalated_frames_per_period: Option<u64>,
55    /// The frames one escalation request is billed at least: 50 for `sam-3.1` video.
56    pub min_frames_per_escalation: u64,
57    /// The quota period in seconds: 86,400, a day, by default.
58    pub period_secs: u64,
59}
60
61impl FrameBudget {
62    /// A budget of `local_fps` with no quotas, a floor of a tenth of that rate, the
63    /// `sam-3.1` video minimum of 50 frames per escalation and a one-day period.
64    pub fn new(local_fps: f32) -> Self {
65        Self {
66            local_fps,
67            min_local_fps: local_fps / 10.0,
68            local_frames_per_period: None,
69            escalations_per_minute: None,
70            escalated_frames_per_period: None,
71            min_frames_per_escalation: SAM_VIDEO_MIN_FRAMES,
72            period_secs: 86_400,
73        }
74    }
75
76    /// Sets the lowest local rate before a pause.
77    pub fn with_min_local_fps(mut self, fps: f32) -> Self {
78        self.min_local_fps = fps;
79        self
80    }
81
82    /// Caps the frames processed locally per period.
83    pub fn with_local_quota(mut self, frames: u64) -> Self {
84        self.local_frames_per_period = Some(frames);
85        self
86    }
87
88    /// Caps escalation requests per minute.
89    pub fn with_escalations_per_minute(mut self, requests: u32) -> Self {
90        self.escalations_per_minute = Some(requests);
91        self
92    }
93
94    /// Caps the frames billed for escalations per period.
95    pub fn with_escalation_quota(mut self, frames: u64) -> Self {
96        self.escalated_frames_per_period = Some(frames);
97        self
98    }
99
100    /// Sets the billed minimum of one escalation request.
101    pub fn with_min_frames_per_escalation(mut self, frames: u64) -> Self {
102        self.min_frames_per_escalation = frames;
103        self
104    }
105
106    /// Sets the quota period.
107    pub fn with_period_secs(mut self, secs: u64) -> Self {
108        self.period_secs = secs;
109        self
110    }
111
112    /// Checks the budget.
113    ///
114    /// # Errors
115    ///
116    /// [`VisionError::InvalidInput`] when a rate is not a positive number, the floor exceeds
117    /// the rate, the period is zero, or the per-escalation minimum is zero.
118    pub fn validate(&self) -> Result<()> {
119        let positive = |v: f32| v.is_finite() && v > 0.0;
120        if !positive(self.local_fps) || !positive(self.min_local_fps) {
121            return Err(VisionError::InvalidInput(format!(
122                "frame budget rates must be positive numbers; got local_fps {} and min_local_fps {}",
123                self.local_fps, self.min_local_fps
124            )));
125        }
126        if self.min_local_fps > self.local_fps {
127            return Err(VisionError::InvalidInput(format!(
128                "min_local_fps {} is above local_fps {}; the floor must not exceed the rate",
129                self.min_local_fps, self.local_fps
130            )));
131        }
132        if self.period_secs == 0 {
133            return Err(VisionError::InvalidInput(
134                "a frame budget period must be at least 1 second".into(),
135            ));
136        }
137        if self.min_frames_per_escalation == 0 {
138            return Err(VisionError::InvalidInput(
139                "min_frames_per_escalation must be at least 1; sam-3.1 video bills 50".into(),
140            ));
141        }
142        Ok(())
143    }
144}
145
146/// Why the governor stopped escalation or paused the source.
147#[non_exhaustive]
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "camelCase")]
150pub enum StopReason {
151    /// The local quota cannot last the period even at the lowest rate.
152    LocalQuotaPressure,
153    /// The local quota is spent.
154    LocalQuotaReached,
155    /// The escalation quota cannot cover another request.
156    EscalationQuotaReached,
157}
158
159/// One change of the governor's state, each written as a `vision.governor.step` record.
160#[non_exhaustive]
161#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
163pub enum GovernorChange {
164    /// The local rate went down.
165    RateLowered {
166        /// The rate before.
167        from_fps: f32,
168        /// The rate after.
169        to_fps: f32,
170    },
171    /// Escalation stopped.
172    EscalationStopped {
173        /// Why.
174        reason: StopReason,
175    },
176    /// The source paused: no frame is processed until the next period.
177    Paused {
178        /// Why.
179        reason: StopReason,
180    },
181    /// A new period began and the paused source resumed.
182    Resumed,
183    /// A new period began and the local rate went back up.
184    RateRestored {
185        /// The rate before.
186        from_fps: f32,
187        /// The rate after.
188        to_fps: f32,
189    },
190    /// A new period began and escalation resumed.
191    EscalationResumed,
192}
193
194/// The governor's counters and settings at one moment.
195#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197pub struct GovernorState {
198    /// The period's index: whole periods since the Unix epoch.
199    pub period: u64,
200    /// When the period ends.
201    pub period_ends_at: DateTime<Utc>,
202    /// Frames processed locally this period.
203    pub local_frames: u64,
204    /// The local quota.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub local_quota: Option<u64>,
207    /// Frames billed for escalations this period.
208    pub escalated_frames: u64,
209    /// The escalation quota.
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub escalation_quota: Option<u64>,
212    /// The current local rate.
213    pub fps: f32,
214    /// Why escalation is stopped, when it is.
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub escalation_stopped: Option<StopReason>,
217    /// Why the source is paused, when it is.
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub paused: Option<StopReason>,
220}
221
222/// A change and the state it left, at the time it happened.
223#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct GovernorStep {
226    /// When.
227    pub at: DateTime<Utc>,
228    /// What changed.
229    pub change: GovernorChange,
230    /// The state after the change.
231    pub state: GovernorState,
232}
233
234/// What to do with one offered frame.
235#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "camelCase")]
237pub enum FrameVerdict {
238    /// Process it.
239    Process,
240    /// Skip it: it came sooner than the current local rate allows.
241    Thinned,
242    /// Skip it: the source is paused until the next period.
243    Paused,
244}
245
246/// A frame's verdict and the steps taken on the way.
247#[derive(Clone, Debug, PartialEq)]
248pub struct Admission {
249    /// What to do with the frame.
250    pub verdict: FrameVerdict,
251    /// The governor's changes, in order.
252    pub steps: Vec<GovernorStep>,
253}
254
255/// Why an escalation was refused.
256#[non_exhaustive]
257#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
259pub enum EscalationRefusal {
260    /// The source is paused.
261    SourcePaused,
262    /// Escalation is stopped until the next period.
263    Stopped {
264        /// Why.
265        reason: StopReason,
266    },
267    /// The per-minute limit is reached; a later request may pass.
268    PerMinute {
269        /// The limit.
270        limit: u32,
271    },
272    /// This request bills more frames than the quota has left; a smaller one may pass.
273    OverRemaining {
274        /// Frames the escalation quota has left.
275        remaining: u64,
276    },
277}
278
279/// Whether an escalation may go ahead.
280#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
282pub enum EscalationVerdict {
283    /// It may, billed at this many frames.
284    Granted {
285        /// The frames the request is billed: at least the per-request minimum.
286        billed_frames: u64,
287    },
288    /// It may not.
289    Refused {
290        /// Why.
291        refusal: EscalationRefusal,
292    },
293}
294
295/// An escalation's verdict and the steps taken on the way.
296#[derive(Clone, Debug, PartialEq)]
297pub struct EscalationDecision {
298    /// Whether it may go ahead.
299    pub verdict: EscalationVerdict,
300    /// The governor's changes, in order.
301    pub steps: Vec<GovernorStep>,
302}
303
304/// Holds a stream to its [`FrameBudget`] (spec 3.7 §7.9, S11).
305///
306/// The governor is a pure state machine over the times it is handed — frame capture times
307/// and escalation request times — so it behaves the same for a live camera and a replayed
308/// file. Under pressure it steps down in a fixed order and reports every change as a
309/// [`GovernorStep`]:
310///
311/// 1. **Lower the local rate.** When the local quota would not last the rest of the period
312///    at the current rate, the rate halves until it would, down to `min_local_fps`.
313/// 2. **Stop escalating.** At the floor with the quota still short, or when the escalation
314///    quota cannot cover another request.
315/// 3. **Pause the source.** When the local quota is spent. A source is never paused at a
316///    rate above the floor or with escalation still on: reaching the quota steps through
317///    both first, in that order.
318///
319/// Rates only go down within a period. When the next period starts the counters reset and
320/// the governor resumes the source, restores the rate and resumes escalation, each as its
321/// own step.
322///
323/// # Example
324///
325/// ```
326/// use chrono::{TimeZone, Utc};
327/// use adk_vision::stream::{FrameBudget, FrameGovernor, FrameVerdict, GovernorChange};
328///
329/// // Ten frames an hour-long period at 1 fps cannot last: the rate drops to the floor,
330/// // escalation stops, and the source pauses at the tenth frame.
331/// let budget = FrameBudget::new(1.0).with_min_local_fps(0.5).with_local_quota(10).with_period_secs(3_600);
332/// let mut governor = FrameGovernor::new(budget).unwrap();
333/// let start = Utc.with_ymd_and_hms(2026, 11, 21, 9, 0, 0).unwrap();
334/// let first = governor.offer(start);
335/// assert_eq!(first.verdict, FrameVerdict::Process);
336/// assert!(matches!(first.steps[0].change, GovernorChange::RateLowered { to_fps: 0.5, .. }));
337/// let mut paused = false;
338/// for s in 1..60 {
339///     let admission = governor.offer(start + chrono::TimeDelta::seconds(s * 2));
340///     paused |= admission.steps.iter().any(|s| matches!(s.change, GovernorChange::Paused { .. }));
341/// }
342/// assert!(paused);
343/// assert_eq!(governor.state().local_frames, 10);
344/// ```
345#[derive(Clone, Debug)]
346pub struct FrameGovernor {
347    budget: FrameBudget,
348    period: Option<u64>,
349    local_frames: u64,
350    escalated_frames: u64,
351    fps: f32,
352    escalation_stopped: Option<StopReason>,
353    paused: Option<StopReason>,
354    last_admitted: Option<DateTime<Utc>>,
355    grants: VecDeque<DateTime<Utc>>,
356}
357
358impl FrameGovernor {
359    /// A governor for `budget`, at its full local rate.
360    ///
361    /// # Errors
362    ///
363    /// As [`FrameBudget::validate`].
364    pub fn new(budget: FrameBudget) -> Result<Self> {
365        budget.validate()?;
366        Ok(Self {
367            fps: budget.local_fps,
368            budget,
369            period: None,
370            local_frames: 0,
371            escalated_frames: 0,
372            escalation_stopped: None,
373            paused: None,
374            last_admitted: None,
375            grants: VecDeque::new(),
376        })
377    }
378
379    /// The budget.
380    pub fn budget(&self) -> &FrameBudget {
381        &self.budget
382    }
383
384    /// The state now.
385    pub fn state(&self) -> GovernorState {
386        let period = self.period.unwrap_or(0);
387        GovernorState {
388            period,
389            period_ends_at: self.period_end(period),
390            local_frames: self.local_frames,
391            local_quota: self.budget.local_frames_per_period,
392            escalated_frames: self.escalated_frames,
393            escalation_quota: self.budget.escalated_frames_per_period,
394            fps: self.fps,
395            escalation_stopped: self.escalation_stopped,
396            paused: self.paused,
397        }
398    }
399
400    /// Decides what to do with a frame captured at `at`.
401    pub fn offer(&mut self, at: DateTime<Utc>) -> Admission {
402        let mut steps = Vec::new();
403        self.evaluate(at, &mut steps);
404        if self.paused.is_some() {
405            return Admission { verdict: FrameVerdict::Paused, steps };
406        }
407        if let Some(last) = self.last_admitted.filter(|last| at >= *last) {
408            let interval = 1.0 / f64::from(self.fps);
409            let since = (at - last).as_seconds_f64();
410            // The same eighth-of-an-interval slack as the sampler, for capture jitter.
411            if since + interval / 8.0 < interval {
412                return Admission { verdict: FrameVerdict::Thinned, steps };
413            }
414        }
415        self.local_frames += 1;
416        self.last_admitted = Some(at);
417        self.pressure(at, &mut steps);
418        Admission { verdict: FrameVerdict::Process, steps }
419    }
420
421    /// Decides whether an escalation of `frames` frames, requested at `at`, may go ahead,
422    /// and bills it when it may.
423    pub fn request_escalation(&mut self, at: DateTime<Utc>, frames: u64) -> EscalationDecision {
424        let mut steps = Vec::new();
425        self.evaluate(at, &mut steps);
426        let refuse = |refusal, steps| EscalationDecision {
427            verdict: EscalationVerdict::Refused { refusal },
428            steps,
429        };
430        if self.paused.is_some() {
431            return refuse(EscalationRefusal::SourcePaused, steps);
432        }
433        if let Some(reason) = self.escalation_stopped {
434            return refuse(EscalationRefusal::Stopped { reason }, steps);
435        }
436        if let Some(limit) = self.budget.escalations_per_minute {
437            let window_start = at - TimeDelta::seconds(60);
438            while self.grants.front().is_some_and(|granted| *granted <= window_start) {
439                self.grants.pop_front();
440            }
441            if self.grants.len() >= limit as usize {
442                return refuse(EscalationRefusal::PerMinute { limit }, steps);
443            }
444        }
445        let billed = frames.max(self.budget.min_frames_per_escalation);
446        if let Some(quota) = self.budget.escalated_frames_per_period {
447            let remaining = quota.saturating_sub(self.escalated_frames);
448            if billed > remaining {
449                if self.budget.min_frames_per_escalation > remaining {
450                    self.stop_escalation(at, StopReason::EscalationQuotaReached, &mut steps);
451                    return refuse(
452                        EscalationRefusal::Stopped { reason: StopReason::EscalationQuotaReached },
453                        steps,
454                    );
455                }
456                return refuse(EscalationRefusal::OverRemaining { remaining }, steps);
457            }
458        }
459        self.escalated_frames += billed;
460        self.grants.push_back(at);
461        self.pressure(at, &mut steps);
462        EscalationDecision { verdict: EscalationVerdict::Granted { billed_frames: billed }, steps }
463    }
464
465    fn period_ms(&self) -> i64 {
466        i64::try_from(self.budget.period_secs.saturating_mul(1_000)).unwrap_or(i64::MAX)
467    }
468
469    fn period_of(&self, at: DateTime<Utc>) -> u64 {
470        u64::try_from(at.timestamp_millis().div_euclid(self.period_ms())).unwrap_or(0)
471    }
472
473    fn period_end(&self, period: u64) -> DateTime<Utc> {
474        let end = i64::try_from(period.saturating_add(1))
475            .unwrap_or(i64::MAX)
476            .saturating_mul(self.period_ms());
477        DateTime::from_timestamp_millis(end).unwrap_or(DateTime::<Utc>::MAX_UTC)
478    }
479
480    fn step(&self, at: DateTime<Utc>, change: GovernorChange, steps: &mut Vec<GovernorStep>) {
481        steps.push(GovernorStep { at, change, state: self.state() });
482    }
483
484    /// Starts a new period when `at` is in one, then applies the quota pressure.
485    fn evaluate(&mut self, at: DateTime<Utc>, steps: &mut Vec<GovernorStep>) {
486        let period = self.period_of(at);
487        match self.period {
488            None => self.period = Some(period),
489            Some(current) if period > current => {
490                self.period = Some(period);
491                self.local_frames = 0;
492                self.escalated_frames = 0;
493                if self.paused.take().is_some() {
494                    self.step(at, GovernorChange::Resumed, steps);
495                }
496                if self.fps < self.budget.local_fps {
497                    let from_fps = self.fps;
498                    self.fps = self.budget.local_fps;
499                    self.step(
500                        at,
501                        GovernorChange::RateRestored { from_fps, to_fps: self.fps },
502                        steps,
503                    );
504                }
505                if self.escalation_stopped.take().is_some() {
506                    self.step(at, GovernorChange::EscalationResumed, steps);
507                }
508            }
509            // A time in the current period, or one before it (a clock stepped back): the
510            // current period's counters keep counting.
511            Some(_) => {}
512        }
513        self.pressure(at, steps);
514    }
515
516    fn lower_rate(&mut self, at: DateTime<Utc>, to_fps: f32, steps: &mut Vec<GovernorStep>) {
517        if to_fps < self.fps {
518            let from_fps = self.fps;
519            self.fps = to_fps;
520            self.step(at, GovernorChange::RateLowered { from_fps, to_fps }, steps);
521        }
522    }
523
524    fn stop_escalation(
525        &mut self,
526        at: DateTime<Utc>,
527        reason: StopReason,
528        steps: &mut Vec<GovernorStep>,
529    ) {
530        if self.escalation_stopped.is_none() {
531            self.escalation_stopped = Some(reason);
532            self.step(at, GovernorChange::EscalationStopped { reason }, steps);
533        }
534    }
535
536    /// Steps down under the quotas, in the fixed order.
537    fn pressure(&mut self, at: DateTime<Utc>, steps: &mut Vec<GovernorStep>) {
538        if self.paused.is_some() {
539            return;
540        }
541        let floor = self.budget.min_local_fps;
542        if let Some(quota) = self.budget.local_frames_per_period {
543            if self.local_frames >= quota {
544                self.lower_rate(at, floor, steps);
545                self.stop_escalation(at, StopReason::LocalQuotaReached, steps);
546                self.paused = Some(StopReason::LocalQuotaReached);
547                self.step(
548                    at,
549                    GovernorChange::Paused { reason: StopReason::LocalQuotaReached },
550                    steps,
551                );
552                return;
553            }
554            let period = self.period.unwrap_or_else(|| self.period_of(at));
555            let remaining = (self.period_end(period) - at).as_seconds_f64().max(0.0);
556            // A frame admitted at `at` holds the slot at `at`, which `used` already counts.
557            let taken = if self.last_admitted == Some(at) { 1.0 } else { 0.0 };
558            let used = self.local_frames as f64;
559            let projected = |fps: f32| used + (f64::from(fps) * remaining - taken).max(0.0);
560            let mut target = self.fps;
561            while projected(target) > quota as f64 && target > floor {
562                target = (target / 2.0).max(floor);
563            }
564            self.lower_rate(at, target, steps);
565            if projected(self.fps) > quota as f64 {
566                self.stop_escalation(at, StopReason::LocalQuotaPressure, steps);
567            }
568        }
569        if let Some(quota) = self.budget.escalated_frames_per_period
570            && self.escalated_frames + self.budget.min_frames_per_escalation > quota
571        {
572            self.stop_escalation(at, StopReason::EscalationQuotaReached, steps);
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use chrono::TimeZone;
580
581    use super::*;
582
583    fn t0() -> DateTime<Utc> {
584        Utc.with_ymd_and_hms(2026, 11, 21, 0, 0, 0).unwrap()
585    }
586
587    fn kinds(steps: &[GovernorStep]) -> Vec<&'static str> {
588        steps
589            .iter()
590            .map(|s| match s.change {
591                GovernorChange::RateLowered { .. } => "lowered",
592                GovernorChange::EscalationStopped { .. } => "escalation-stopped",
593                GovernorChange::Paused { .. } => "paused",
594                GovernorChange::Resumed => "resumed",
595                GovernorChange::RateRestored { .. } => "restored",
596                GovernorChange::EscalationResumed => "escalation-resumed",
597            })
598            .collect()
599    }
600
601    #[test]
602    fn invalid_budgets_are_refused() {
603        assert!(FrameGovernor::new(FrameBudget::new(0.0)).is_err());
604        assert!(FrameGovernor::new(FrameBudget::new(5.0).with_min_local_fps(6.0)).is_err());
605        assert!(FrameGovernor::new(FrameBudget::new(5.0).with_period_secs(0)).is_err());
606        assert!(
607            FrameGovernor::new(FrameBudget::new(5.0).with_min_frames_per_escalation(0)).is_err()
608        );
609    }
610
611    #[test]
612    fn an_unlimited_budget_only_thins() {
613        let mut g = FrameGovernor::new(FrameBudget::new(5.0)).unwrap();
614        let verdicts: Vec<_> =
615            (0..10).map(|i| g.offer(t0() + TimeDelta::milliseconds(i * 100)).verdict).collect();
616        assert_eq!(verdicts.iter().filter(|v| **v == FrameVerdict::Process).count(), 5);
617        assert!(!verdicts.contains(&FrameVerdict::Paused));
618    }
619
620    #[test]
621    fn pressure_lowers_the_rate_then_stops_escalation_then_pauses() {
622        // 1,000 frames a 1,000-second period at 4 fps cannot last: 2 fps would use 2,000,
623        // so the rate goes to the 1 fps floor (1,000 fits exactly).
624        let budget = FrameBudget::new(4.0)
625            .with_min_local_fps(1.0)
626            .with_local_quota(1_000)
627            .with_period_secs(1_000);
628        let mut g = FrameGovernor::new(budget).unwrap();
629        let start = DateTime::from_timestamp(1_000_000, 0).unwrap();
630        let first = g.offer(start);
631        assert_eq!(kinds(&first.steps), ["lowered"]);
632        assert_eq!(g.state().fps, 1.0);
633        let mut all = first.steps;
634        for s in 1..2_000 {
635            all.extend(g.offer(start + TimeDelta::seconds(s) / 2).steps);
636        }
637        assert_eq!(g.state().local_frames, 1_000);
638        assert_eq!(kinds(&all), ["lowered", "escalation-stopped", "paused"]);
639        // The next period resumes everything, each as its own step.
640        let next = g.offer(start + TimeDelta::seconds(1_000));
641        assert_eq!(kinds(&next.steps), ["resumed", "restored", "escalation-resumed", "lowered"]);
642        assert_eq!(next.verdict, FrameVerdict::Process);
643    }
644
645    #[test]
646    fn the_escalation_quota_stops_escalation_and_the_next_period_resumes_it() {
647        let budget = FrameBudget::new(5.0).with_escalation_quota(120).with_period_secs(3_600);
648        let mut g = FrameGovernor::new(budget).unwrap();
649        let at = t0();
650        assert_eq!(
651            g.request_escalation(at, 10).verdict,
652            EscalationVerdict::Granted { billed_frames: 50 }
653        );
654        // 70 left would cover a minimum request, but not the 80 asked.
655        let over = g.request_escalation(at, 80);
656        assert_eq!(
657            over.verdict,
658            EscalationVerdict::Refused {
659                refusal: EscalationRefusal::OverRemaining { remaining: 70 }
660            }
661        );
662        let second = g.request_escalation(at, 50);
663        assert_eq!(second.verdict, EscalationVerdict::Granted { billed_frames: 50 });
664        assert_eq!(kinds(&second.steps), ["escalation-stopped"]);
665        assert!(matches!(
666            g.request_escalation(at, 1).verdict,
667            EscalationVerdict::Refused { refusal: EscalationRefusal::Stopped { .. } }
668        ));
669        let next = g.request_escalation(at + TimeDelta::hours(1), 1);
670        assert_eq!(kinds(&next.steps), ["escalation-resumed"]);
671        assert_eq!(next.verdict, EscalationVerdict::Granted { billed_frames: 50 });
672    }
673
674    #[test]
675    fn escalations_per_minute_are_capped_in_a_sliding_window() {
676        let mut g =
677            FrameGovernor::new(FrameBudget::new(5.0).with_escalations_per_minute(2)).unwrap();
678        let at = t0();
679        assert!(matches!(g.request_escalation(at, 50).verdict, EscalationVerdict::Granted { .. }));
680        assert!(matches!(
681            g.request_escalation(at + TimeDelta::seconds(10), 50).verdict,
682            EscalationVerdict::Granted { .. }
683        ));
684        assert_eq!(
685            g.request_escalation(at + TimeDelta::seconds(59), 50).verdict,
686            EscalationVerdict::Refused { refusal: EscalationRefusal::PerMinute { limit: 2 } }
687        );
688        assert!(matches!(
689            g.request_escalation(at + TimeDelta::seconds(61), 50).verdict,
690            EscalationVerdict::Granted { .. }
691        ));
692    }
693}