use std::collections::VecDeque;
use chrono::{DateTime, TimeDelta, Utc};
use serde::{Deserialize, Serialize};
use crate::error::{Result, VisionError};
const SAM_VIDEO_MIN_FRAMES: u64 = 50;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FrameBudget {
pub local_fps: f32,
pub min_local_fps: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub local_frames_per_period: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalations_per_minute: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalated_frames_per_period: Option<u64>,
pub min_frames_per_escalation: u64,
pub period_secs: u64,
}
impl FrameBudget {
pub fn new(local_fps: f32) -> Self {
Self {
local_fps,
min_local_fps: local_fps / 10.0,
local_frames_per_period: None,
escalations_per_minute: None,
escalated_frames_per_period: None,
min_frames_per_escalation: SAM_VIDEO_MIN_FRAMES,
period_secs: 86_400,
}
}
pub fn with_min_local_fps(mut self, fps: f32) -> Self {
self.min_local_fps = fps;
self
}
pub fn with_local_quota(mut self, frames: u64) -> Self {
self.local_frames_per_period = Some(frames);
self
}
pub fn with_escalations_per_minute(mut self, requests: u32) -> Self {
self.escalations_per_minute = Some(requests);
self
}
pub fn with_escalation_quota(mut self, frames: u64) -> Self {
self.escalated_frames_per_period = Some(frames);
self
}
pub fn with_min_frames_per_escalation(mut self, frames: u64) -> Self {
self.min_frames_per_escalation = frames;
self
}
pub fn with_period_secs(mut self, secs: u64) -> Self {
self.period_secs = secs;
self
}
pub fn validate(&self) -> Result<()> {
let positive = |v: f32| v.is_finite() && v > 0.0;
if !positive(self.local_fps) || !positive(self.min_local_fps) {
return Err(VisionError::InvalidInput(format!(
"frame budget rates must be positive numbers; got local_fps {} and min_local_fps {}",
self.local_fps, self.min_local_fps
)));
}
if self.min_local_fps > self.local_fps {
return Err(VisionError::InvalidInput(format!(
"min_local_fps {} is above local_fps {}; the floor must not exceed the rate",
self.min_local_fps, self.local_fps
)));
}
if self.period_secs == 0 {
return Err(VisionError::InvalidInput(
"a frame budget period must be at least 1 second".into(),
));
}
if self.min_frames_per_escalation == 0 {
return Err(VisionError::InvalidInput(
"min_frames_per_escalation must be at least 1; sam-3.1 video bills 50".into(),
));
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum StopReason {
LocalQuotaPressure,
LocalQuotaReached,
EscalationQuotaReached,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum GovernorChange {
RateLowered {
from_fps: f32,
to_fps: f32,
},
EscalationStopped {
reason: StopReason,
},
Paused {
reason: StopReason,
},
Resumed,
RateRestored {
from_fps: f32,
to_fps: f32,
},
EscalationResumed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernorState {
pub period: u64,
pub period_ends_at: DateTime<Utc>,
pub local_frames: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub local_quota: Option<u64>,
pub escalated_frames: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalation_quota: Option<u64>,
pub fps: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub escalation_stopped: Option<StopReason>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub paused: Option<StopReason>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernorStep {
pub at: DateTime<Utc>,
pub change: GovernorChange,
pub state: GovernorState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FrameVerdict {
Process,
Thinned,
Paused,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Admission {
pub verdict: FrameVerdict,
pub steps: Vec<GovernorStep>,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum EscalationRefusal {
SourcePaused,
Stopped {
reason: StopReason,
},
PerMinute {
limit: u32,
},
OverRemaining {
remaining: u64,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum EscalationVerdict {
Granted {
billed_frames: u64,
},
Refused {
refusal: EscalationRefusal,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct EscalationDecision {
pub verdict: EscalationVerdict,
pub steps: Vec<GovernorStep>,
}
#[derive(Clone, Debug)]
pub struct FrameGovernor {
budget: FrameBudget,
period: Option<u64>,
local_frames: u64,
escalated_frames: u64,
fps: f32,
escalation_stopped: Option<StopReason>,
paused: Option<StopReason>,
last_admitted: Option<DateTime<Utc>>,
grants: VecDeque<DateTime<Utc>>,
}
impl FrameGovernor {
pub fn new(budget: FrameBudget) -> Result<Self> {
budget.validate()?;
Ok(Self {
fps: budget.local_fps,
budget,
period: None,
local_frames: 0,
escalated_frames: 0,
escalation_stopped: None,
paused: None,
last_admitted: None,
grants: VecDeque::new(),
})
}
pub fn budget(&self) -> &FrameBudget {
&self.budget
}
pub fn state(&self) -> GovernorState {
let period = self.period.unwrap_or(0);
GovernorState {
period,
period_ends_at: self.period_end(period),
local_frames: self.local_frames,
local_quota: self.budget.local_frames_per_period,
escalated_frames: self.escalated_frames,
escalation_quota: self.budget.escalated_frames_per_period,
fps: self.fps,
escalation_stopped: self.escalation_stopped,
paused: self.paused,
}
}
pub fn offer(&mut self, at: DateTime<Utc>) -> Admission {
let mut steps = Vec::new();
self.evaluate(at, &mut steps);
if self.paused.is_some() {
return Admission { verdict: FrameVerdict::Paused, steps };
}
if let Some(last) = self.last_admitted.filter(|last| at >= *last) {
let interval = 1.0 / f64::from(self.fps);
let since = (at - last).as_seconds_f64();
if since + interval / 8.0 < interval {
return Admission { verdict: FrameVerdict::Thinned, steps };
}
}
self.local_frames += 1;
self.last_admitted = Some(at);
self.pressure(at, &mut steps);
Admission { verdict: FrameVerdict::Process, steps }
}
pub fn request_escalation(&mut self, at: DateTime<Utc>, frames: u64) -> EscalationDecision {
let mut steps = Vec::new();
self.evaluate(at, &mut steps);
let refuse = |refusal, steps| EscalationDecision {
verdict: EscalationVerdict::Refused { refusal },
steps,
};
if self.paused.is_some() {
return refuse(EscalationRefusal::SourcePaused, steps);
}
if let Some(reason) = self.escalation_stopped {
return refuse(EscalationRefusal::Stopped { reason }, steps);
}
if let Some(limit) = self.budget.escalations_per_minute {
let window_start = at - TimeDelta::seconds(60);
while self.grants.front().is_some_and(|granted| *granted <= window_start) {
self.grants.pop_front();
}
if self.grants.len() >= limit as usize {
return refuse(EscalationRefusal::PerMinute { limit }, steps);
}
}
let billed = frames.max(self.budget.min_frames_per_escalation);
if let Some(quota) = self.budget.escalated_frames_per_period {
let remaining = quota.saturating_sub(self.escalated_frames);
if billed > remaining {
if self.budget.min_frames_per_escalation > remaining {
self.stop_escalation(at, StopReason::EscalationQuotaReached, &mut steps);
return refuse(
EscalationRefusal::Stopped { reason: StopReason::EscalationQuotaReached },
steps,
);
}
return refuse(EscalationRefusal::OverRemaining { remaining }, steps);
}
}
self.escalated_frames += billed;
self.grants.push_back(at);
self.pressure(at, &mut steps);
EscalationDecision { verdict: EscalationVerdict::Granted { billed_frames: billed }, steps }
}
fn period_ms(&self) -> i64 {
i64::try_from(self.budget.period_secs.saturating_mul(1_000)).unwrap_or(i64::MAX)
}
fn period_of(&self, at: DateTime<Utc>) -> u64 {
u64::try_from(at.timestamp_millis().div_euclid(self.period_ms())).unwrap_or(0)
}
fn period_end(&self, period: u64) -> DateTime<Utc> {
let end = i64::try_from(period.saturating_add(1))
.unwrap_or(i64::MAX)
.saturating_mul(self.period_ms());
DateTime::from_timestamp_millis(end).unwrap_or(DateTime::<Utc>::MAX_UTC)
}
fn step(&self, at: DateTime<Utc>, change: GovernorChange, steps: &mut Vec<GovernorStep>) {
steps.push(GovernorStep { at, change, state: self.state() });
}
fn evaluate(&mut self, at: DateTime<Utc>, steps: &mut Vec<GovernorStep>) {
let period = self.period_of(at);
match self.period {
None => self.period = Some(period),
Some(current) if period > current => {
self.period = Some(period);
self.local_frames = 0;
self.escalated_frames = 0;
if self.paused.take().is_some() {
self.step(at, GovernorChange::Resumed, steps);
}
if self.fps < self.budget.local_fps {
let from_fps = self.fps;
self.fps = self.budget.local_fps;
self.step(
at,
GovernorChange::RateRestored { from_fps, to_fps: self.fps },
steps,
);
}
if self.escalation_stopped.take().is_some() {
self.step(at, GovernorChange::EscalationResumed, steps);
}
}
Some(_) => {}
}
self.pressure(at, steps);
}
fn lower_rate(&mut self, at: DateTime<Utc>, to_fps: f32, steps: &mut Vec<GovernorStep>) {
if to_fps < self.fps {
let from_fps = self.fps;
self.fps = to_fps;
self.step(at, GovernorChange::RateLowered { from_fps, to_fps }, steps);
}
}
fn stop_escalation(
&mut self,
at: DateTime<Utc>,
reason: StopReason,
steps: &mut Vec<GovernorStep>,
) {
if self.escalation_stopped.is_none() {
self.escalation_stopped = Some(reason);
self.step(at, GovernorChange::EscalationStopped { reason }, steps);
}
}
fn pressure(&mut self, at: DateTime<Utc>, steps: &mut Vec<GovernorStep>) {
if self.paused.is_some() {
return;
}
let floor = self.budget.min_local_fps;
if let Some(quota) = self.budget.local_frames_per_period {
if self.local_frames >= quota {
self.lower_rate(at, floor, steps);
self.stop_escalation(at, StopReason::LocalQuotaReached, steps);
self.paused = Some(StopReason::LocalQuotaReached);
self.step(
at,
GovernorChange::Paused { reason: StopReason::LocalQuotaReached },
steps,
);
return;
}
let period = self.period.unwrap_or_else(|| self.period_of(at));
let remaining = (self.period_end(period) - at).as_seconds_f64().max(0.0);
let taken = if self.last_admitted == Some(at) { 1.0 } else { 0.0 };
let used = self.local_frames as f64;
let projected = |fps: f32| used + (f64::from(fps) * remaining - taken).max(0.0);
let mut target = self.fps;
while projected(target) > quota as f64 && target > floor {
target = (target / 2.0).max(floor);
}
self.lower_rate(at, target, steps);
if projected(self.fps) > quota as f64 {
self.stop_escalation(at, StopReason::LocalQuotaPressure, steps);
}
}
if let Some(quota) = self.budget.escalated_frames_per_period
&& self.escalated_frames + self.budget.min_frames_per_escalation > quota
{
self.stop_escalation(at, StopReason::EscalationQuotaReached, steps);
}
}
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use super::*;
fn t0() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 21, 0, 0, 0).unwrap()
}
fn kinds(steps: &[GovernorStep]) -> Vec<&'static str> {
steps
.iter()
.map(|s| match s.change {
GovernorChange::RateLowered { .. } => "lowered",
GovernorChange::EscalationStopped { .. } => "escalation-stopped",
GovernorChange::Paused { .. } => "paused",
GovernorChange::Resumed => "resumed",
GovernorChange::RateRestored { .. } => "restored",
GovernorChange::EscalationResumed => "escalation-resumed",
})
.collect()
}
#[test]
fn invalid_budgets_are_refused() {
assert!(FrameGovernor::new(FrameBudget::new(0.0)).is_err());
assert!(FrameGovernor::new(FrameBudget::new(5.0).with_min_local_fps(6.0)).is_err());
assert!(FrameGovernor::new(FrameBudget::new(5.0).with_period_secs(0)).is_err());
assert!(
FrameGovernor::new(FrameBudget::new(5.0).with_min_frames_per_escalation(0)).is_err()
);
}
#[test]
fn an_unlimited_budget_only_thins() {
let mut g = FrameGovernor::new(FrameBudget::new(5.0)).unwrap();
let verdicts: Vec<_> =
(0..10).map(|i| g.offer(t0() + TimeDelta::milliseconds(i * 100)).verdict).collect();
assert_eq!(verdicts.iter().filter(|v| **v == FrameVerdict::Process).count(), 5);
assert!(!verdicts.contains(&FrameVerdict::Paused));
}
#[test]
fn pressure_lowers_the_rate_then_stops_escalation_then_pauses() {
let budget = FrameBudget::new(4.0)
.with_min_local_fps(1.0)
.with_local_quota(1_000)
.with_period_secs(1_000);
let mut g = FrameGovernor::new(budget).unwrap();
let start = DateTime::from_timestamp(1_000_000, 0).unwrap();
let first = g.offer(start);
assert_eq!(kinds(&first.steps), ["lowered"]);
assert_eq!(g.state().fps, 1.0);
let mut all = first.steps;
for s in 1..2_000 {
all.extend(g.offer(start + TimeDelta::seconds(s) / 2).steps);
}
assert_eq!(g.state().local_frames, 1_000);
assert_eq!(kinds(&all), ["lowered", "escalation-stopped", "paused"]);
let next = g.offer(start + TimeDelta::seconds(1_000));
assert_eq!(kinds(&next.steps), ["resumed", "restored", "escalation-resumed", "lowered"]);
assert_eq!(next.verdict, FrameVerdict::Process);
}
#[test]
fn the_escalation_quota_stops_escalation_and_the_next_period_resumes_it() {
let budget = FrameBudget::new(5.0).with_escalation_quota(120).with_period_secs(3_600);
let mut g = FrameGovernor::new(budget).unwrap();
let at = t0();
assert_eq!(
g.request_escalation(at, 10).verdict,
EscalationVerdict::Granted { billed_frames: 50 }
);
let over = g.request_escalation(at, 80);
assert_eq!(
over.verdict,
EscalationVerdict::Refused {
refusal: EscalationRefusal::OverRemaining { remaining: 70 }
}
);
let second = g.request_escalation(at, 50);
assert_eq!(second.verdict, EscalationVerdict::Granted { billed_frames: 50 });
assert_eq!(kinds(&second.steps), ["escalation-stopped"]);
assert!(matches!(
g.request_escalation(at, 1).verdict,
EscalationVerdict::Refused { refusal: EscalationRefusal::Stopped { .. } }
));
let next = g.request_escalation(at + TimeDelta::hours(1), 1);
assert_eq!(kinds(&next.steps), ["escalation-resumed"]);
assert_eq!(next.verdict, EscalationVerdict::Granted { billed_frames: 50 });
}
#[test]
fn escalations_per_minute_are_capped_in_a_sliding_window() {
let mut g =
FrameGovernor::new(FrameBudget::new(5.0).with_escalations_per_minute(2)).unwrap();
let at = t0();
assert!(matches!(g.request_escalation(at, 50).verdict, EscalationVerdict::Granted { .. }));
assert!(matches!(
g.request_escalation(at + TimeDelta::seconds(10), 50).verdict,
EscalationVerdict::Granted { .. }
));
assert_eq!(
g.request_escalation(at + TimeDelta::seconds(59), 50).verdict,
EscalationVerdict::Refused { refusal: EscalationRefusal::PerMinute { limit: 2 } }
);
assert!(matches!(
g.request_escalation(at + TimeDelta::seconds(61), 50).verdict,
EscalationVerdict::Granted { .. }
));
}
}