1use std::collections::BTreeMap;
14use std::fmt;
15use std::str::FromStr;
16use std::time::Duration;
17
18use adk_core::{UsageUnit, UsageVector};
19
20use chrono::{DateTime, FixedOffset, Local, NaiveTime, TimeZone, Utc};
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22
23use crate::error::KernelError;
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47#[non_exhaustive]
48pub enum QueueClass {
49 Interactive,
51 Background,
53 Maintenance,
55 Named(String),
57}
58
59impl QueueClass {
60 pub const INTERACTIVE: &'static str = "interactive";
62 pub const BACKGROUND: &'static str = "background";
64 pub const MAINTENANCE: &'static str = "maintenance";
66
67 pub fn from_name(name: &str) -> Self {
70 match name {
71 Self::INTERACTIVE => Self::Interactive,
72 Self::BACKGROUND => Self::Background,
73 Self::MAINTENANCE => Self::Maintenance,
74 other => Self::Named(other.to_string()),
75 }
76 }
77
78 pub fn as_str(&self) -> &str {
80 match self {
81 Self::Interactive => Self::INTERACTIVE,
82 Self::Background => Self::BACKGROUND,
83 Self::Maintenance => Self::MAINTENANCE,
84 Self::Named(name) => name,
85 }
86 }
87
88 pub fn poll_interval(&self) -> Duration {
91 match self {
92 Self::Interactive => Duration::from_millis(500),
93 Self::Background | Self::Named(_) => Duration::from_secs(2),
94 Self::Maintenance => Duration::from_secs(5),
95 }
96 }
97
98 pub fn defaults() -> Vec<Self> {
100 vec![Self::Interactive, Self::Background, Self::Maintenance]
101 }
102}
103
104impl fmt::Display for QueueClass {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.write_str(self.as_str())
107 }
108}
109
110impl FromStr for QueueClass {
111 type Err = KernelError;
112
113 fn from_str(name: &str) -> Result<Self, Self::Err> {
114 let name = name.trim();
115 if name.is_empty() {
116 return Err(KernelError::Config {
117 reason: "a queue name must not be empty; use interactive, background, \
118 maintenance or a queue the kernel configures"
119 .to_string(),
120 });
121 }
122 Ok(Self::from_name(name))
123 }
124}
125
126impl Serialize for QueueClass {
127 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
128 serializer.serialize_str(self.as_str())
129 }
130}
131
132impl<'de> Deserialize<'de> for QueueClass {
133 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
134 let name = String::deserialize(deserializer)?;
135 name.parse().map_err(serde::de::Error::custom)
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169#[non_exhaustive]
170pub struct QuietHours {
171 #[serde(with = "hh_mm")]
173 pub start: NaiveTime,
174 #[serde(with = "hh_mm")]
176 pub end: NaiveTime,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub utc_offset_minutes: Option<i32>,
180 #[serde(default, skip_serializing_if = "Option::is_none", with = "zone")]
184 pub time_zone: Option<chrono_tz::Tz>,
185}
186
187impl QuietHours {
188 pub fn new(start: NaiveTime, end: NaiveTime) -> Self {
190 Self { start, end, utc_offset_minutes: None, time_zone: None }
191 }
192
193 #[must_use]
195 pub fn with_utc_offset_minutes(mut self, minutes: i32) -> Self {
196 self.utc_offset_minutes = Some(minutes);
197 self
198 }
199
200 #[must_use]
216 pub fn with_time_zone(mut self, zone: chrono_tz::Tz) -> Self {
217 self.time_zone = Some(zone);
218 self
219 }
220
221 fn offset(&self) -> Option<FixedOffset> {
222 self.utc_offset_minutes.and_then(|minutes| FixedOffset::east_opt(minutes * 60))
223 }
224
225 fn local_time(&self, at: DateTime<Utc>) -> NaiveTime {
226 if let Some(zone) = self.time_zone {
227 return at.with_timezone(&zone).time();
228 }
229 match self.offset() {
230 Some(offset) => at.with_timezone(&offset).time(),
231 None => at.with_timezone(&Local).time(),
232 }
233 }
234
235 fn inside(&self, time: NaiveTime) -> bool {
236 match self.start.cmp(&self.end) {
237 std::cmp::Ordering::Less => time >= self.start && time < self.end,
238 std::cmp::Ordering::Greater => time >= self.start || time < self.end,
239 std::cmp::Ordering::Equal => false,
240 }
241 }
242
243 pub fn contains(&self, at: DateTime<Utc>) -> bool {
245 self.inside(self.local_time(at))
246 }
247
248 pub fn release_at(&self, at: DateTime<Utc>) -> DateTime<Utc> {
251 if !self.contains(at) {
252 return at;
253 }
254 let local_date = match (self.time_zone, self.offset()) {
255 (Some(zone), _) => at.with_timezone(&zone).date_naive(),
256 (None, Some(offset)) => at.with_timezone(&offset).date_naive(),
257 (None, None) => at.with_timezone(&Local).date_naive(),
258 };
259 for days in 0..=2 {
261 let Some(date) = local_date.checked_add_days(chrono::Days::new(days)) else {
262 break;
263 };
264 let naive = date.and_time(self.end);
265 let end = match (self.time_zone, self.offset()) {
266 (Some(zone), _) => zone.from_local_datetime(&naive).earliest().map(|t| t.to_utc()),
267 (None, Some(offset)) => {
268 offset.from_local_datetime(&naive).earliest().map(|t| t.to_utc())
269 }
270 (None, None) => Local.from_local_datetime(&naive).earliest().map(|t| t.to_utc()),
271 };
272 if let Some(end) = end
273 && end > at
274 {
275 return end;
276 }
277 }
278 at + chrono::Duration::days(1)
279 }
280}
281
282impl FromStr for QuietHours {
283 type Err = KernelError;
284
285 fn from_str(text: &str) -> Result<Self, Self::Err> {
287 let invalid = || KernelError::Config {
288 reason: format!(
289 "invalid quiet hours `{text}`; write them as HH:MM-HH:MM, e.g. 22:00-07:00"
290 ),
291 };
292 let (start, end) = text.trim().split_once('-').ok_or_else(invalid)?;
293 let start = hh_mm::parse(start.trim()).ok_or_else(invalid)?;
294 let end = hh_mm::parse(end.trim()).ok_or_else(invalid)?;
295 Ok(Self::new(start, end))
296 }
297}
298
299mod zone {
301 use chrono_tz::Tz;
302 use serde::{Deserialize, Deserializer, Serializer};
303
304 pub(super) fn serialize<S: Serializer>(
305 zone: &Option<Tz>,
306 serializer: S,
307 ) -> Result<S::Ok, S::Error> {
308 match zone {
309 Some(zone) => serializer.serialize_str(zone.name()),
310 None => serializer.serialize_none(),
311 }
312 }
313
314 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
315 deserializer: D,
316 ) -> Result<Option<Tz>, D::Error> {
317 let Some(name) = Option::<String>::deserialize(deserializer)? else { return Ok(None) };
318 name.parse::<Tz>().map(Some).map_err(|_| {
319 serde::de::Error::custom(format!(
320 "`{name}` is not an IANA time zone; name one such as `Europe/London`"
321 ))
322 })
323 }
324}
325
326mod hh_mm {
328 use chrono::NaiveTime;
329 use serde::{Deserialize, Deserializer, Serializer};
330
331 pub(super) fn parse(text: &str) -> Option<NaiveTime> {
332 NaiveTime::parse_from_str(text, "%H:%M")
333 .or_else(|_| NaiveTime::parse_from_str(text, "%H:%M:%S"))
334 .ok()
335 }
336
337 pub(super) fn serialize<S: Serializer>(
338 time: &NaiveTime,
339 serializer: S,
340 ) -> Result<S::Ok, S::Error> {
341 serializer.serialize_str(&time.format("%H:%M").to_string())
342 }
343
344 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
345 deserializer: D,
346 ) -> Result<NaiveTime, D::Error> {
347 let text = String::deserialize(deserializer)?;
348 parse(&text)
349 .ok_or_else(|| serde::de::Error::custom(format!("`{text}` is not an HH:MM time")))
350 }
351}
352
353#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
386#[serde(rename_all = "camelCase")]
387#[non_exhaustive]
388pub struct Quotas {
389 #[serde(default, skip_serializing_if = "Option::is_none")]
391 pub max_running: Option<usize>,
392 #[serde(default, skip_serializing_if = "Option::is_none")]
394 pub max_queued: Option<usize>,
395 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub daily_spend_cap: Option<u64>,
398 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
400 pub daily_caps: BTreeMap<UsageUnit, u64>,
401}
402
403impl Quotas {
404 pub fn new() -> Self {
406 Self::default()
407 }
408
409 #[must_use]
411 pub fn with_max_running(mut self, max: usize) -> Self {
412 self.max_running = Some(max);
413 self
414 }
415
416 #[must_use]
418 pub fn with_max_queued(mut self, max: usize) -> Self {
419 self.max_queued = Some(max);
420 self
421 }
422
423 #[must_use]
425 pub fn with_daily_spend_cap(mut self, micro_usd: u64) -> Self {
426 self.daily_spend_cap = Some(micro_usd);
427 self
428 }
429
430 #[must_use]
432 pub fn with_daily_cap(mut self, unit: UsageUnit, max: u64) -> Self {
433 self.daily_caps.insert(unit, max);
434 self
435 }
436
437 pub(crate) fn stricter(&self, other: &Self) -> Self {
439 fn lower<T: Ord + Copy>(a: Option<T>, b: Option<T>) -> Option<T> {
440 match (a, b) {
441 (Some(a), Some(b)) => Some(a.min(b)),
442 (a, b) => a.or(b),
443 }
444 }
445 let mut daily_caps = self.daily_caps.clone();
446 for (unit, max) in &other.daily_caps {
447 let cap = daily_caps.entry(*unit).or_insert(*max);
448 *cap = (*cap).min(*max);
449 }
450 Self {
451 max_running: lower(self.max_running, other.max_running),
452 max_queued: lower(self.max_queued, other.max_queued),
453 daily_spend_cap: lower(self.daily_spend_cap, other.daily_spend_cap),
454 daily_caps,
455 }
456 }
457
458 pub(crate) fn caps_daily_usage(&self) -> bool {
460 self.daily_spend_cap.is_some() || !self.daily_caps.is_empty()
461 }
462}
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466pub(crate) enum ProcessClass {
467 Interactive,
470 Background,
472 Proactive,
475}
476
477#[derive(Debug, Clone)]
479pub(crate) struct AdmissionInput<'a> {
480 pub(crate) class: ProcessClass,
481 pub(crate) approval_woken: bool,
483 pub(crate) now: DateTime<Utc>,
484 pub(crate) quiet_hours: &'a [QuietHours],
485 pub(crate) quotas: &'a Quotas,
486 pub(crate) running: usize,
488 pub(crate) preemptible: bool,
490 pub(crate) partition_spent: u64,
492 pub(crate) partition_units: UsageVector,
494 pub(crate) proactive_spent: u64,
496 pub(crate) proactive_calls_and_tokens: (u64, u64),
498 pub(crate) daily_budget: Option<u64>,
500 pub(crate) daily_calls_and_tokens: (Option<u64>, Option<u64>),
502 pub(crate) need: u64,
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub(crate) enum Admission {
509 Admit,
511 QuietHours { until: DateTime<Utc> },
513 Budget,
515 Quota { preempt: bool },
519}
520
521impl Admission {
522 pub(crate) fn reason(self) -> Option<&'static str> {
524 match self {
525 Self::Admit => None,
526 Self::QuietHours { .. } => Some("quiet_hours"),
527 Self::Budget => Some("budget"),
528 Self::Quota { .. } => Some("quota"),
529 }
530 }
531}
532
533fn covers(cap: Option<u64>, spent: u64, need: u64) -> bool {
536 cap.is_none_or(|cap| spent.saturating_add(need.max(1)) <= cap)
537}
538
539pub(crate) fn admit(input: &AdmissionInput<'_>) -> Admission {
542 if input.class == ProcessClass::Proactive && !input.approval_woken {
543 let mut until = input.now;
544 for _ in 0..=input.quiet_hours.len() {
546 let next = input
547 .quiet_hours
548 .iter()
549 .map(|quiet| quiet.release_at(until))
550 .max()
551 .unwrap_or(until);
552 if next == until {
553 break;
554 }
555 until = next;
556 }
557 if until > input.now {
558 return Admission::QuietHours { until };
559 }
560 }
561 if input.class != ProcessClass::Interactive {
562 let within_cap = covers(input.quotas.daily_spend_cap, input.partition_spent, input.need)
563 && input
564 .quotas
565 .daily_caps
566 .iter()
567 .all(|(unit, max)| input.partition_units.get(*unit) < *max);
568 let (calls, tokens) = input.proactive_calls_and_tokens;
569 let (max_calls, max_tokens) = input.daily_calls_and_tokens;
570 let within_budget = input.class != ProcessClass::Proactive
571 || (covers(input.daily_budget, input.proactive_spent, input.need)
572 && max_calls.is_none_or(|max| calls < max)
573 && max_tokens.is_none_or(|max| tokens < max));
574 if !within_cap || !within_budget {
575 return Admission::Budget;
576 }
577 }
578 if input.quotas.max_running.is_some_and(|max| input.running >= max) {
579 return Admission::Quota {
580 preempt: input.class == ProcessClass::Interactive && input.preemptible,
581 };
582 }
583 Admission::Admit
584}
585
586pub(crate) fn youngest_background<'a>(
589 candidates: impl IntoIterator<Item = (&'a str, DateTime<Utc>)>,
590) -> Option<&'a str> {
591 candidates
592 .into_iter()
593 .max_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(b.0)))
594 .map(|(pid, _)| pid)
595}
596
597#[cfg(test)]
598mod admission_tests {
599 use chrono::TimeZone;
600 use proptest::prelude::*;
601
602 use super::*;
603
604 fn at(hour: u32, minute: u32) -> DateTime<Utc> {
605 Utc.with_ymd_and_hms(2026, 10, 23, hour, minute, 0).unwrap()
606 }
607
608 fn input<'a>(
609 class: ProcessClass,
610 quiet: &'a [QuietHours],
611 quotas: &'a Quotas,
612 ) -> AdmissionInput<'a> {
613 AdmissionInput {
614 class,
615 approval_woken: false,
616 now: at(12, 0),
617 quiet_hours: quiet,
618 quotas,
619 running: 0,
620 preemptible: false,
621 partition_spent: 0,
622 partition_units: UsageVector::new(),
623 proactive_spent: 0,
624 proactive_calls_and_tokens: (0, 0),
625 daily_budget: None,
626 daily_calls_and_tokens: (None, None),
627 need: 0,
628 }
629 }
630
631 #[test]
632 fn daily_unit_caps_hold_background_and_proactive_work() {
633 let quotas = Quotas::new().with_daily_cap(UsageUnit::Images, 3);
634 for class in [ProcessClass::Background, ProcessClass::Proactive] {
635 let mut room = input(class, &[], "as);
636 room.partition_units = UsageVector::new().with(UsageUnit::Images, 2);
637 assert_eq!(admit(&room), Admission::Admit, "{class:?}");
638 room.partition_units = UsageVector::new().with(UsageUnit::Images, 3);
639 assert_eq!(admit(&room), Admission::Budget, "{class:?} at the cap");
640 }
641 let mut human = input(ProcessClass::Interactive, &[], "as);
642 human.partition_units = UsageVector::new().with(UsageUnit::Images, 30);
643 assert_eq!(admit(&human), Admission::Admit, "a human turn is never held");
644 let mut other = input(ProcessClass::Background, &[], "as);
646 other.partition_units = UsageVector::new().with(UsageUnit::AudioMillis, 1 << 40);
647 assert_eq!(admit(&other), Admission::Admit);
648 }
649
650 #[test]
651 fn the_daily_proactive_budget_caps_model_calls_and_tokens() {
652 let quotas = Quotas::new();
653 let mut proactive = input(ProcessClass::Proactive, &[], "as);
654 proactive.daily_calls_and_tokens = (Some(10), Some(50_000));
655 proactive.proactive_calls_and_tokens = (9, 49_999);
656 assert_eq!(admit(&proactive), Admission::Admit);
657 proactive.proactive_calls_and_tokens = (10, 0);
658 assert_eq!(admit(&proactive), Admission::Budget, "model calls reached");
659 proactive.proactive_calls_and_tokens = (0, 50_000);
660 assert_eq!(admit(&proactive), Admission::Budget, "tokens reached");
661 let mut background = input(ProcessClass::Background, &[], "as);
662 background.daily_calls_and_tokens = (Some(10), Some(50_000));
663 background.proactive_calls_and_tokens = (10, 50_000);
664 assert_eq!(admit(&background), Admission::Admit, "the proactive budget is not the cap");
665 }
666
667 #[test]
668 fn stricter_quotas_take_the_lower_cap_per_unit() {
669 let kernel =
670 Quotas::new().with_daily_cap(UsageUnit::Images, 10).with_daily_cap(UsageUnit::Pages, 5);
671 let partition = Quotas::new()
672 .with_daily_cap(UsageUnit::Images, 3)
673 .with_daily_cap(UsageUnit::AudioMillis, 60_000);
674 assert_eq!(
675 kernel.stricter(&partition).daily_caps,
676 BTreeMap::from([
677 (UsageUnit::Images, 3),
678 (UsageUnit::AudioMillis, 60_000),
679 (UsageUnit::Pages, 5),
680 ])
681 );
682 let json = serde_json::json!({ "dailyCaps": { "images": 3 } });
683 assert_eq!(
684 serde_json::from_value::<Quotas>(json).unwrap(),
685 Quotas::new().with_daily_cap(UsageUnit::Images, 3)
686 );
687 }
688
689 fn night() -> QuietHours {
690 "22:00-07:00".parse::<QuietHours>().unwrap().with_utc_offset_minutes(0)
691 }
692
693 #[test]
694 fn the_admission_table() {
695 let quiet = [night()];
696 let quotas = Quotas::new().with_max_running(3).with_daily_spend_cap(1_000);
697 let base = |class| input(class, &quiet, "as);
698
699 for class in [ProcessClass::Interactive, ProcessClass::Background, ProcessClass::Proactive]
701 {
702 assert_eq!(admit(&base(class)), Admission::Admit, "{class:?}");
703 }
704 let mut late = base(ProcessClass::Proactive);
706 late.now = at(23, 0);
707 assert_eq!(
708 admit(&late),
709 Admission::QuietHours { until: Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap() }
710 );
711 late.approval_woken = true;
712 assert_eq!(admit(&late), Admission::Admit);
713 for class in [ProcessClass::Interactive, ProcessClass::Background] {
714 let mut late = base(class);
715 late.now = at(23, 0);
716 assert_eq!(admit(&late), Admission::Admit, "{class:?}");
717 }
718 for class in [ProcessClass::Background, ProcessClass::Proactive] {
720 let mut full = base(class);
721 full.running = 3;
722 full.preemptible = true;
723 assert_eq!(admit(&full), Admission::Quota { preempt: false }, "{class:?}");
724 }
725 let mut full = base(ProcessClass::Interactive);
726 full.running = 3;
727 assert_eq!(admit(&full), Admission::Quota { preempt: false }, "nothing to preempt");
728 full.preemptible = true;
729 assert_eq!(admit(&full), Admission::Quota { preempt: true });
730 let mut spent = base(ProcessClass::Background);
732 spent.partition_spent = 900;
733 spent.need = 100;
734 assert_eq!(admit(&spent), Admission::Admit, "exactly covered");
735 spent.need = 101;
736 assert_eq!(admit(&spent), Admission::Budget);
737 spent.need = 0;
738 spent.partition_spent = 1_000;
739 assert_eq!(admit(&spent), Admission::Budget, "budget exhausted");
740 let mut human = base(ProcessClass::Interactive);
741 human.partition_spent = 5_000;
742 assert_eq!(admit(&human), Admission::Admit, "a human turn is never held by spend");
743 let mut proactive = base(ProcessClass::Proactive);
745 proactive.daily_budget = Some(500);
746 proactive.proactive_spent = 450;
747 proactive.need = 60;
748 assert_eq!(admit(&proactive), Admission::Budget);
749 let mut background = base(ProcessClass::Background);
750 background.daily_budget = Some(500);
751 background.proactive_spent = 450;
752 background.need = 60;
753 assert_eq!(admit(&background), Admission::Admit, "the proactive budget is not the cap");
754 }
755
756 #[test]
757 fn overlapping_windows_release_outside_both() {
758 let quiet = [
759 "22:00-02:00".parse::<QuietHours>().unwrap().with_utc_offset_minutes(0),
760 "01:00-06:30".parse::<QuietHours>().unwrap().with_utc_offset_minutes(0),
761 ];
762 let quotas = Quotas::new();
763 let mut late = input(ProcessClass::Proactive, &quiet, "as);
764 late.now = at(23, 0);
765 assert_eq!(
766 admit(&late),
767 Admission::QuietHours { until: Utc.with_ymd_and_hms(2026, 10, 24, 6, 30, 0).unwrap() }
768 );
769 }
770
771 #[test]
772 fn preemption_takes_the_youngest_background_run() {
773 let runs =
774 [("run-a", at(9, 0)), ("run-c", at(11, 0)), ("run-b", at(11, 0)), ("run-d", at(8, 0))];
775 assert_eq!(youngest_background(runs), Some("run-c"));
776 assert_eq!(youngest_background(std::iter::empty()), None);
777 }
778
779 #[test]
780 fn quiet_hours_boundaries() {
781 let quiet = night();
782 assert!(quiet.contains(at(22, 0)), "the start is inside");
783 assert!(
784 !quiet.contains(Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap()),
785 "the end is outside"
786 );
787 assert!(!quiet.contains(at(21, 59)));
788 let empty = "09:00-09:00".parse::<QuietHours>().unwrap().with_utc_offset_minutes(0);
789 assert!(!empty.contains(at(9, 0)), "equal times make no window");
790 let east = "22:00-07:00".parse::<QuietHours>().unwrap().with_utc_offset_minutes(180);
791 assert!(east.contains(at(20, 0)), "23:00 at UTC+3");
792 assert_eq!(
793 east.release_at(at(20, 0)),
794 Utc.with_ymd_and_hms(2026, 10, 24, 4, 0, 0).unwrap()
795 );
796 assert!("22-07".parse::<QuietHours>().is_err());
797 }
798
799 fn class() -> impl Strategy<Value = ProcessClass> {
800 prop_oneof![
801 Just(ProcessClass::Interactive),
802 Just(ProcessClass::Background),
803 Just(ProcessClass::Proactive)
804 ]
805 }
806
807 #[derive(Debug, Clone)]
808 enum Step {
809 Claim { class: ProcessClass, need: u64 },
810 Finish(usize),
811 NextDay,
812 }
813
814 fn step() -> impl Strategy<Value = Step> {
815 prop_oneof![
816 4 => (class(), 0u64..400).prop_map(|(class, need)| Step::Claim { class, need }),
817 2 => (0usize..8).prop_map(Step::Finish),
818 1 => Just(Step::NextDay),
819 ]
820 }
821
822 proptest! {
823 #![proptest_config(ProptestConfig::with_cases(256))]
824
825 #[test]
829 fn admission_never_exceeds_quota_or_budget(
830 max_running in 1usize..5,
831 cap in 0u64..2_000,
832 budget in 0u64..1_500,
833 steps in proptest::collection::vec(step(), 1..80),
834 ) {
835 let quotas = Quotas::new().with_max_running(max_running).with_daily_spend_cap(cap);
836 let mut running: Vec<ProcessClass> = Vec::new();
837 let (mut background_spent, mut proactive_spent) = (0u64, 0u64);
838 for step in steps {
839 match step {
840 Step::Claim { class, need } => {
841 let decision = admit(&AdmissionInput {
842 class,
843 approval_woken: false,
844 now: at(12, 0),
845 quiet_hours: &[],
846 quotas: "as,
847 running: running.len(),
848 preemptible: running.contains(&ProcessClass::Background),
849 partition_spent: background_spent + proactive_spent,
850 partition_units: UsageVector::new(),
851 proactive_spent,
852 proactive_calls_and_tokens: (0, 0),
853 daily_budget: Some(budget),
854 daily_calls_and_tokens: (None, None),
855 need,
856 });
857 match decision {
858 Admission::Admit => {
859 running.push(class);
860 match class {
861 ProcessClass::Background => background_spent += need,
862 ProcessClass::Proactive => proactive_spent += need,
863 ProcessClass::Interactive => {}
864 }
865 }
866 Admission::Quota { preempt: true } => {
867 let victim = running.iter().rposition(|c| *c == ProcessClass::Background);
870 prop_assert!(victim.is_some());
871 running.remove(victim.unwrap());
872 running.push(class);
873 }
874 Admission::Quota { preempt: false } | Admission::Budget => {}
875 Admission::QuietHours { .. } => prop_assert!(false, "no quiet hours set"),
876 }
877 }
878 Step::Finish(index) => {
879 if !running.is_empty() {
880 running.remove(index % running.len());
881 }
882 }
883 Step::NextDay => {
884 background_spent = 0;
885 proactive_spent = 0;
886 }
887 }
888 prop_assert!(running.len() <= max_running, "{} running of {max_running}", running.len());
889 prop_assert!(background_spent + proactive_spent <= cap);
890 prop_assert!(proactive_spent <= budget);
891 }
892 }
893
894 #[test]
897 fn no_proactive_process_starts_inside_quiet_hours(
898 start in 0u32..24 * 60,
899 end in 0u32..24 * 60,
900 offset in -12i32 * 60..14 * 60,
901 minute in 0i64..3 * 24 * 60,
902 class in class(),
903 approval_woken in any::<bool>(),
904 ) {
905 let time = |m: u32| NaiveTime::from_hms_opt(m / 60, m % 60, 0).unwrap();
906 let quiet = [QuietHours::new(time(start), time(end)).with_utc_offset_minutes(offset)];
907 let quotas = Quotas::new();
908 let now = at(0, 0) + chrono::Duration::minutes(minute);
909 let mut probe = input(class, &quiet, "as);
910 probe.now = now;
911 probe.approval_woken = approval_woken;
912 let decision = admit(&probe);
913 let held = class == ProcessClass::Proactive && !approval_woken && quiet[0].contains(now);
914 match decision {
915 Admission::Admit => prop_assert!(!held),
916 Admission::QuietHours { until } => {
917 prop_assert!(held);
918 prop_assert!(until > now);
919 prop_assert!(!quiet[0].contains(until));
920 prop_assert!(until - now <= chrono::Duration::days(1));
921 }
922 other => prop_assert!(false, "unexpected {other:?}"),
923 }
924 }
925 }
926}