1use std::collections::VecDeque;
4
5use chrono::{DateTime, TimeDelta, Utc};
6use serde::{Deserialize, Serialize};
7
8use crate::error::{Result, VisionError};
9
10const SAM_VIDEO_MIN_FRAMES: u64 = 50;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41pub struct FrameBudget {
42 pub local_fps: f32,
44 pub min_local_fps: f32,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub local_frames_per_period: Option<u64>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub escalations_per_minute: Option<u32>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub escalated_frames_per_period: Option<u64>,
55 pub min_frames_per_escalation: u64,
57 pub period_secs: u64,
59}
60
61impl FrameBudget {
62 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 pub fn with_min_local_fps(mut self, fps: f32) -> Self {
78 self.min_local_fps = fps;
79 self
80 }
81
82 pub fn with_local_quota(mut self, frames: u64) -> Self {
84 self.local_frames_per_period = Some(frames);
85 self
86 }
87
88 pub fn with_escalations_per_minute(mut self, requests: u32) -> Self {
90 self.escalations_per_minute = Some(requests);
91 self
92 }
93
94 pub fn with_escalation_quota(mut self, frames: u64) -> Self {
96 self.escalated_frames_per_period = Some(frames);
97 self
98 }
99
100 pub fn with_min_frames_per_escalation(mut self, frames: u64) -> Self {
102 self.min_frames_per_escalation = frames;
103 self
104 }
105
106 pub fn with_period_secs(mut self, secs: u64) -> Self {
108 self.period_secs = secs;
109 self
110 }
111
112 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#[non_exhaustive]
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "camelCase")]
150pub enum StopReason {
151 LocalQuotaPressure,
153 LocalQuotaReached,
155 EscalationQuotaReached,
157}
158
159#[non_exhaustive]
161#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
163pub enum GovernorChange {
164 RateLowered {
166 from_fps: f32,
168 to_fps: f32,
170 },
171 EscalationStopped {
173 reason: StopReason,
175 },
176 Paused {
178 reason: StopReason,
180 },
181 Resumed,
183 RateRestored {
185 from_fps: f32,
187 to_fps: f32,
189 },
190 EscalationResumed,
192}
193
194#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
196#[serde(rename_all = "camelCase")]
197pub struct GovernorState {
198 pub period: u64,
200 pub period_ends_at: DateTime<Utc>,
202 pub local_frames: u64,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub local_quota: Option<u64>,
207 pub escalated_frames: u64,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub escalation_quota: Option<u64>,
212 pub fps: f32,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub escalation_stopped: Option<StopReason>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
219 pub paused: Option<StopReason>,
220}
221
222#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct GovernorStep {
226 pub at: DateTime<Utc>,
228 pub change: GovernorChange,
230 pub state: GovernorState,
232}
233
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "camelCase")]
237pub enum FrameVerdict {
238 Process,
240 Thinned,
242 Paused,
244}
245
246#[derive(Clone, Debug, PartialEq)]
248pub struct Admission {
249 pub verdict: FrameVerdict,
251 pub steps: Vec<GovernorStep>,
253}
254
255#[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 SourcePaused,
262 Stopped {
264 reason: StopReason,
266 },
267 PerMinute {
269 limit: u32,
271 },
272 OverRemaining {
274 remaining: u64,
276 },
277}
278
279#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
282pub enum EscalationVerdict {
283 Granted {
285 billed_frames: u64,
287 },
288 Refused {
290 refusal: EscalationRefusal,
292 },
293}
294
295#[derive(Clone, Debug, PartialEq)]
297pub struct EscalationDecision {
298 pub verdict: EscalationVerdict,
300 pub steps: Vec<GovernorStep>,
302}
303
304#[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 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 pub fn budget(&self) -> &FrameBudget {
381 &self.budget
382 }
383
384 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 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 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 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 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 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 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 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 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 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 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}