Skip to main content

adk_kernel/
sched.rs

1//! Queue classes (spec 3.2 §7.9).
2//!
3//! Priority is a queue (§6 D-5): the kernel runs one `DurableWorker` per [`QueueClass`],
4//! each with its own fallback poll interval (§13 Q2). A worker sleeps until the earliest
5//! `not_before` deadline in its queue, and `enqueue` and `wake` notify it, so the poll only
6//! catches runs another process enqueued (§10 S3).
7//!
8//! Phase 2 adds attention and resources (§7.9): [`Quotas`] per partition (max running, max
9//! queued, a daily spend cap), [`QuietHours`] through the run's `not_before`, cost-aware
10//! admission against the partition's daily spend, and preemption of the youngest
11//! background run when an interactive one finds its partition at quota.
12
13use 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/// A priority class: the run-store queue a process waits in and the worker that claims it
26/// (spec 3.2 §7.9).
27///
28/// The three classes of the default configuration are [`Interactive`](Self::Interactive)
29/// (a human turn), [`Background`](Self::Background) (goals, triggered and scheduled work)
30/// and [`Maintenance`](Self::Maintenance) (the kernel's own work, `kernel.wake` runs).
31/// [`Named`](Self::Named) is any other queue. A class serializes as its queue name.
32///
33/// # Example
34///
35/// ```rust
36/// use std::time::Duration;
37/// use adk_kernel::QueueClass;
38///
39/// let class: QueueClass = "background".parse().unwrap();
40/// assert_eq!(class, QueueClass::Background);
41/// assert_eq!(class.poll_interval(), Duration::from_secs(2));
42/// assert_eq!(QueueClass::Interactive.poll_interval(), Duration::from_millis(500));
43/// assert_eq!(QueueClass::from_name("payments"), QueueClass::Named("payments".into()));
44/// assert_eq!(serde_json::to_value(QueueClass::Maintenance).unwrap(), "maintenance");
45/// ```
46#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
47#[non_exhaustive]
48pub enum QueueClass {
49    /// Human turns; claimed first-come with a 500 ms fallback poll.
50    Interactive,
51    /// Goals, triggered and scheduled processes; 2 s fallback poll.
52    Background,
53    /// The kernel's own work; 5 s fallback poll.
54    Maintenance,
55    /// Any other queue; 2 s fallback poll.
56    Named(String),
57}
58
59impl QueueClass {
60    /// The run-store queue name of [`Interactive`](Self::Interactive).
61    pub const INTERACTIVE: &'static str = "interactive";
62    /// The run-store queue name of [`Background`](Self::Background).
63    pub const BACKGROUND: &'static str = "background";
64    /// The run-store queue name of [`Maintenance`](Self::Maintenance).
65    pub const MAINTENANCE: &'static str = "maintenance";
66
67    /// The class of the run-store queue `name`; the three default names map to their
68    /// classes and anything else is [`Named`](Self::Named).
69    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    /// The run-store queue name the class's worker claims from.
79    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    /// The worker's fallback poll interval (spec 3.2 §7.9, §13 Q2): 500 ms for
89    /// `interactive`, 2 s for `background` and named queues, 5 s for `maintenance`.
90    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    /// The default queue classes: interactive, background and maintenance (spec 3.2 §7.2).
99    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/// A daily local-time window in which proactive and maintenance processes never start
140/// (spec 3.2 §7.5, §7.9, K-I11); interactive and approval-woken runs always may.
141///
142/// The window runs from `start` up to, not including, `end`. A `start` after `end` wraps
143/// midnight (`22:00`–`07:00`); equal times make an empty window. Times are local: in the
144/// IANA `time_zone` when set, following its daylight saving time; else at
145/// `utc_offset_minutes` east of UTC when set; else in the host's time zone. A process that
146/// would start inside the window gets `not_before` = [`release_at`](Self::release_at), so
147/// its worker sleeps until the window ends. Serializes as
148/// `{"start": "22:00", "end": "07:00", "utcOffsetMinutes": 180}` or
149/// `{"start": "22:00", "end": "07:00", "timeZone": "Europe/London"}`.
150///
151/// # Example
152///
153/// ```rust
154/// use chrono::{TimeZone, Utc};
155/// use adk_kernel::QuietHours;
156///
157/// let quiet: QuietHours = "22:00-07:00".parse().unwrap();
158/// let quiet = quiet.with_utc_offset_minutes(0);
159/// let night = Utc.with_ymd_and_hms(2026, 10, 23, 23, 30, 0).unwrap();
160/// assert!(quiet.contains(night));
161/// assert_eq!(quiet.release_at(night), Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap());
162/// let noon = Utc.with_ymd_and_hms(2026, 10, 23, 12, 0, 0).unwrap();
163/// assert!(!quiet.contains(noon));
164/// assert_eq!(quiet.release_at(noon), noon);
165/// assert_eq!(serde_json::to_value(&quiet).unwrap()["start"], "22:00");
166/// ```
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "camelCase")]
169#[non_exhaustive]
170pub struct QuietHours {
171    /// Local time the window starts.
172    #[serde(with = "hh_mm")]
173    pub start: NaiveTime,
174    /// Local time the window ends (exclusive).
175    #[serde(with = "hh_mm")]
176    pub end: NaiveTime,
177    /// Minutes east of UTC the times are in; `None` is the host's time zone.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub utc_offset_minutes: Option<i32>,
180    /// The IANA time zone the times are in, such as `Europe/London`, ahead of
181    /// `utc_offset_minutes`: the window keeps its local times across daylight saving time,
182    /// where a fixed offset moves them by an hour (spec 3.3 §10 K3).
183    #[serde(default, skip_serializing_if = "Option::is_none", with = "zone")]
184    pub time_zone: Option<chrono_tz::Tz>,
185}
186
187impl QuietHours {
188    /// The window from `start` to `end`, in the host's time zone.
189    pub fn new(start: NaiveTime, end: NaiveTime) -> Self {
190        Self { start, end, utc_offset_minutes: None, time_zone: None }
191    }
192
193    /// Reads the times at `minutes` east of UTC instead of the host's time zone.
194    #[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    /// Reads the times in the IANA time zone `zone`, following its daylight saving time.
201    ///
202    /// # Example
203    ///
204    /// ```rust
205    /// use chrono::{TimeZone, Utc};
206    /// use adk_kernel::QuietHours;
207    ///
208    /// let quiet: QuietHours = "22:00-07:00".parse().unwrap();
209    /// let quiet = quiet.with_time_zone(chrono_tz::Europe::London);
210    /// // 22:30 in London is 21:30 UTC in summer and 22:30 UTC in winter.
211    /// assert!(quiet.contains(Utc.with_ymd_and_hms(2026, 7, 1, 21, 30, 0).unwrap()));
212    /// assert!(quiet.contains(Utc.with_ymd_and_hms(2026, 12, 1, 22, 30, 0).unwrap()));
213    /// assert!(!quiet.contains(Utc.with_ymd_and_hms(2026, 12, 1, 21, 30, 0).unwrap()));
214    /// ```
215    #[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    /// Whether `at` falls inside the window.
244    pub fn contains(&self, at: DateTime<Utc>) -> bool {
245        self.inside(self.local_time(at))
246    }
247
248    /// The earliest instant at or after `at` outside the window: `at` itself when it is
249    /// outside, else the window's end.
250    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        // The end is today when it is still ahead of `at`, else tomorrow.
260        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    /// Parses `HH:MM-HH:MM`, in the host's time zone.
286    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
299/// An IANA time zone as its name, such as `Europe/London`.
300mod 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
326/// `NaiveTime` as `HH:MM` (seconds accepted on input).
327mod 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/// A partition's quotas (spec 3.2 §7.9): enforced at admission, they bound each partition
354/// within a queue so none starves another (§13 Q2). `None` leaves a quota unlimited.
355///
356/// | Quota | Enforced |
357/// |---|---|
358/// | `max_running` | A claimed process whose partition already runs this many waits for a slot; an interactive one preempts the youngest background run |
359/// | `max_queued` | [`ProcessTable::spawn`](crate::ProcessTable::spawn) and agenda scheduling refuse a process past it |
360/// | `daily_spend_cap` | A background process is admitted only while the partition's spend today plus its budget's cost cap stays within it; else it sleeps until `BudgetReplenished` |
361/// | `daily_caps` | Per [`UsageUnit`]: a background process is admitted only while the partition's usage of the unit today is below the cap; else it sleeps until `BudgetReplenished`, the next UTC day |
362///
363/// The `kernel.wake` runs the kernel routes wakes with are never counted or held.
364/// The proactive limits — open proposals and the daily proactive budget — are the
365/// partition's [`ProactivityPolicy`](crate::ProactivityPolicy).
366///
367/// # Example
368///
369/// ```rust
370/// use adk_kernel::Quotas;
371///
372/// use adk_core::UsageUnit;
373///
374/// let quotas = Quotas::new()
375///     .with_max_running(3)
376///     .with_max_queued(20)
377///     .with_daily_spend_cap(5_000_000)
378///     .with_daily_cap(UsageUnit::Images, 200);
379/// assert_eq!(quotas.max_running, Some(3));
380/// let json = serde_json::to_value(&quotas).unwrap();
381/// assert_eq!(json["dailySpendCap"], 5_000_000);
382/// assert_eq!(json["dailyCaps"]["images"], 200);
383/// assert_eq!(Quotas::default().max_running, None);
384/// ```
385#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
386#[serde(rename_all = "camelCase")]
387#[non_exhaustive]
388pub struct Quotas {
389    /// Most processes of the partition running at once, over every queue.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub max_running: Option<usize>,
392    /// Most processes of the partition queued at once.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub max_queued: Option<usize>,
395    /// Most micro-USD the partition spends per UTC day.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub daily_spend_cap: Option<u64>,
398    /// Most of each unit the partition uses per UTC day.
399    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
400    pub daily_caps: BTreeMap<UsageUnit, u64>,
401}
402
403impl Quotas {
404    /// No quota.
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    /// Sets the most running processes.
410    #[must_use]
411    pub fn with_max_running(mut self, max: usize) -> Self {
412        self.max_running = Some(max);
413        self
414    }
415
416    /// Sets the most queued processes.
417    #[must_use]
418    pub fn with_max_queued(mut self, max: usize) -> Self {
419        self.max_queued = Some(max);
420        self
421    }
422
423    /// Sets the daily spend cap, in micro-USD.
424    #[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    /// Caps the partition's daily usage of `unit`.
431    #[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    /// Each limit the lower of `self`'s and `other`'s; a limit only one sets applies.
438    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    /// Whether a daily limit of these quotas applies at admission.
459    pub(crate) fn caps_daily_usage(&self) -> bool {
460        self.daily_spend_cap.is_some() || !self.daily_caps.is_empty()
461    }
462}
463
464/// How admission treats a claimed process (spec 3.2 §7.9).
465#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466pub(crate) enum ProcessClass {
467    /// A human turn: never held by quiet hours or budgets; preempts background work at
468    /// quota.
469    Interactive,
470    /// Goals, triggered and scheduled work: quotas and the partition's daily spend cap.
471    Background,
472    /// Agenda follow-ups and the kernel's maintenance processes: quotas, the spend cap, the
473    /// daily proactive budget and quiet hours.
474    Proactive,
475}
476
477/// What admission reads about a claimed process and its partition (spec 3.2 §7.9).
478#[derive(Debug, Clone)]
479pub(crate) struct AdmissionInput<'a> {
480    pub(crate) class: ProcessClass,
481    /// The run resumes after a decided approval; quiet hours never hold it.
482    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    /// Admitted processes of the partition running now, this one excluded.
487    pub(crate) running: usize,
488    /// Whether one of them runs on the `background` queue and can be preempted.
489    pub(crate) preemptible: bool,
490    /// The partition's spend today, in micro-USD.
491    pub(crate) partition_spent: u64,
492    /// The partition's usage today per unit.
493    pub(crate) partition_units: UsageVector,
494    /// The partition's proactive spend today, in micro-USD.
495    pub(crate) proactive_spent: u64,
496    /// The partition's proactive model calls and total tokens today.
497    pub(crate) proactive_calls_and_tokens: (u64, u64),
498    /// The cost cap of the daily proactive budget.
499    pub(crate) daily_budget: Option<u64>,
500    /// The model-call and token caps of the daily proactive budget.
501    pub(crate) daily_calls_and_tokens: (Option<u64>, Option<u64>),
502    /// The cost cap of the process's own budget; 0 without one.
503    pub(crate) need: u64,
504}
505
506/// Admission's answer for a claimed process (spec 3.2 §7.9).
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub(crate) enum Admission {
509    /// It may run.
510    Admit,
511    /// Inside quiet hours: it sleeps until they end.
512    QuietHours { until: DateTime<Utc> },
513    /// The day's budget does not cover it: it sleeps until `BudgetReplenished`.
514    Budget,
515    /// The partition runs `max_running` processes: it waits for a slot, or, for an
516    /// interactive one when `preempt` is set, takes the slot of the youngest background
517    /// process, which parks at its next checkpoint.
518    Quota { preempt: bool },
519}
520
521impl Admission {
522    /// The label value a deferred process carries, `None` when admitted.
523    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
533/// Whether `spent` plus `need` stays within `cap`; a process with no budget of its own
534/// needs only that something is left.
535fn covers(cap: Option<u64>, spent: u64, need: u64) -> bool {
536    cap.is_none_or(|cap| spent.saturating_add(need.max(1)) <= cap)
537}
538
539/// Decides whether a claimed process starts now (spec 3.2 §7.9, K-I11): quiet hours first,
540/// then the daily budgets, then the partition's running quota.
541pub(crate) fn admit(input: &AdmissionInput<'_>) -> Admission {
542    if input.class == ProcessClass::Proactive && !input.approval_woken {
543        let mut until = input.now;
544        // A window may end inside another; settle on an instant outside every one.
545        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
586/// The process an interactive one preempts (spec 3.2 §7.9): the youngest running process on
587/// the `background` queue, by creation time and then id.
588pub(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, &[], &quotas);
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, &[], &quotas);
642        human.partition_units = UsageVector::new().with(UsageUnit::Images, 30);
643        assert_eq!(admit(&human), Admission::Admit, "a human turn is never held");
644        // A cap on one unit ignores the others.
645        let mut other = input(ProcessClass::Background, &[], &quotas);
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, &[], &quotas);
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, &[], &quotas);
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, &quotas);
698
699        // Free partition, daytime: everything runs.
700        for class in [ProcessClass::Interactive, ProcessClass::Background, ProcessClass::Proactive]
701        {
702            assert_eq!(admit(&base(class)), Admission::Admit, "{class:?}");
703        }
704        // Quiet hours hold proactive work only, and never an approval-woken run.
705        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        // Partition at quota: background and proactive wait; interactive preempts when it can.
719        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        // Spend cap: a background run whose budget the rest of the day does not cover waits.
731        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        // Daily proactive budget: proactive only.
744        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, &quotas);
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        /// Admission never lets a partition run more than `max_running` processes, nor
826        /// spend past its cap or its daily proactive budget, whatever arrives in what order;
827        /// each admitted process spends at most its budget's cost cap.
828        #[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: &quotas,
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                                // The youngest background run stops counting; the human
868                                // turn takes its slot.
869                                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        /// No proactive process is admitted inside quiet hours, and its release time lies
895        /// outside them; interactive and approval-woken runs are never held by them.
896        #[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, &quotas);
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}