Skip to main content

byteflow/scheduler/
quota.rs

1//! Resource quotas — Phase 3.
2//!
3//! Three independent budgets per flow:
4//! - `cpu_budget` — remaining reductions/instructions before the flow is
5//!   stopped pending an ADMIN top-up. Distinct from the scheduler *quantum*
6//!   (fairness / preemption, not an absolute consumption cap).
7//! - `mem_used` / `mem_limit` — bytes currently charged to this flow's heap.
8//! - `spawn_bucket` / `send_bucket` — token buckets drained on SPAWN / SEND,
9//!   refilled by time. Covers the spawn-bomb and mailbox-flood DoS the
10//!   threat model already admits.
11//!
12//! All three fail *closed*: exhausting a budget aborts the instruction
13//! (error / trap), never degrades silently into unlimited behaviour.
14
15// Docs ratchet: public items here predate `missing_docs`. Delete this
16// allow once they are documented; new files get the lint by default.
17#![allow(missing_docs)]
18
19use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering};
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, Instant};
22
23use super::error::RuntimeError;
24use super::sync_lock;
25
26/// Tunables copied onto every newly spawned flow.
27#[derive(Clone, Copy, Debug)]
28pub struct QuotaConfig {
29    pub cpu_budget: i64,
30    pub mem_limit: usize,
31    pub spawn_burst: i64,
32    pub spawn_per_sec: i64,
33    pub send_burst: i64,
34    pub send_per_sec: i64,
35}
36
37impl QuotaConfig {
38    /// Current defaults: generous so samples and tests keep passing.
39    pub fn permissive() -> Self {
40        Self {
41            cpu_budget: 1_000_000_000,
42            mem_limit: 64 * 1024 * 1024,
43            spawn_burst: 10_000,
44            spawn_per_sec: 10_000,
45            send_burst: 50_000,
46            send_per_sec: 50_000,
47        }
48    }
49
50    /// Starting point for untrusted modules. Tune under real load before
51    /// using as a production default. Pair with
52    /// [`crate::RuntimeConfig::sandbox`] for process-wide `max_flows` /
53    /// `max_ask_waits` ceilings.
54    pub fn sandbox() -> Self {
55        Self {
56            cpu_budget: 50_000,
57            mem_limit: 16 * 1024 * 1024,
58            spawn_burst: 32,
59            spawn_per_sec: 32,
60            send_burst: 256,
61            send_per_sec: 64,
62        }
63    }
64}
65
66impl Default for QuotaConfig {
67    fn default() -> Self {
68        Self::permissive()
69    }
70}
71
72pub(super) struct TokenBucket {
73    capacity: i64,
74    tokens: AtomicI64,
75    refill_per_sec: i64,
76    last_refill: Mutex<Instant>,
77}
78
79impl TokenBucket {
80    pub(super) fn new(capacity: i64, refill_per_sec: i64) -> Self {
81        Self {
82            capacity,
83            tokens: AtomicI64::new(capacity),
84            refill_per_sec,
85            last_refill: Mutex::new(Instant::now()),
86        }
87    }
88
89    /// Refill or fail closed on lock poison (no tokens granted).
90    fn refill(&self) -> Result<(), RuntimeError> {
91        let mut last = sync_lock::lock(&self.last_refill, "TokenBucket::refill")?;
92        let elapsed = last.elapsed();
93        if elapsed >= Duration::from_millis(50) {
94            let add = tokens_for_elapsed(elapsed, self.refill_per_sec);
95            if add > 0 {
96                loop {
97                    let cur = self.tokens.load(Ordering::Acquire);
98                    let new = cur.saturating_add(add).min(self.capacity);
99                    if self
100                        .tokens
101                        .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
102                        .is_ok()
103                    {
104                        break;
105                    }
106                }
107                *last = Instant::now();
108            }
109        }
110        Ok(())
111    }
112
113    /// True and consume one token iff one was available.
114    pub(super) fn try_consume(&self) -> bool {
115        if self.refill().is_err() {
116            return false;
117        }
118        loop {
119            let cur = self.tokens.load(Ordering::Acquire);
120            if cur <= 0 {
121                return false;
122            }
123            if self
124                .tokens
125                .compare_exchange_weak(cur, cur - 1, Ordering::AcqRel, Ordering::Acquire)
126                .is_ok()
127            {
128                return true;
129            }
130        }
131    }
132
133    /// ADMIN credit. May exceed capacity until the next refill caps it.
134    ///
135    /// A credit that does not fit stays at `i64::MAX`. Wrapping would make
136    /// the bucket look empty and refuse every later spawn or send.
137    pub(super) fn credit(&self, extra: i64) {
138        if extra <= 0 {
139            return;
140        }
141        loop {
142            let cur = self.tokens.load(Ordering::Acquire);
143            let new = cur.saturating_add(extra);
144            if self
145                .tokens
146                .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
147                .is_ok()
148            {
149                return;
150            }
151        }
152    }
153}
154
155/// How many tokens `per_sec` earns over `elapsed`, without a float cast.
156///
157/// `as i64` on an out-of-range float is a saturating conversion, and the
158/// old `cur + add` then overflowed `i64` (panic in debug, wrap in release).
159fn tokens_for_elapsed(elapsed: Duration, per_sec: i64) -> i64 {
160    if per_sec <= 0 {
161        return 0;
162    }
163    let add = (per_sec as u128).saturating_mul(elapsed.as_nanos()) / 1_000_000_000;
164    match i64::try_from(add) {
165        Ok(n) => n,
166        Err(_) => i64::MAX,
167    }
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum QuotaError {
172    CpuExhausted,
173    /// `charge_cpu` rejected `cost <= 0` (would grow the budget or overflow).
174    InvalidCost,
175    MemoryExhausted {
176        requested: usize,
177        limit: usize,
178    },
179    SpawnRateExceeded,
180    SendRateExceeded,
181}
182
183impl QuotaError {
184    /// Stable tag for [`crate::SecurityEvent::QuotaExceeded`].
185    pub fn audit_kind(self) -> &'static str {
186        match self {
187            QuotaError::CpuExhausted => "cpu",
188            QuotaError::InvalidCost => "invalid_cost",
189            QuotaError::MemoryExhausted { .. } => "memory",
190            QuotaError::SpawnRateExceeded => "spawn_rate",
191            QuotaError::SendRateExceeded => "send_rate",
192        }
193    }
194}
195
196impl std::fmt::Display for QuotaError {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        match self {
199            QuotaError::CpuExhausted => f.write_str("flow CPU budget exhausted"),
200            QuotaError::InvalidCost => f.write_str("CPU charge must be positive"),
201            QuotaError::MemoryExhausted { requested, limit } => {
202                write!(
203                    f,
204                    "flow memory exhausted (requested {requested}, limit {limit})"
205                )
206            }
207            QuotaError::SpawnRateExceeded => f.write_str("spawn rate exceeded"),
208            QuotaError::SendRateExceeded => f.write_str("send rate exceeded"),
209        }
210    }
211}
212
213impl std::error::Error for QuotaError {}
214
215pub struct FlowQuota {
216    cpu_budget: AtomicI64,
217    mem_limit: AtomicUsize,
218    mem_used: AtomicUsize,
219    spawn_bucket: TokenBucket,
220    send_bucket: TokenBucket,
221}
222
223impl FlowQuota {
224    pub fn from_config(cfg: QuotaConfig) -> Self {
225        Self::new(
226            cfg.cpu_budget,
227            cfg.mem_limit,
228            cfg.spawn_burst,
229            cfg.spawn_per_sec,
230            cfg.send_burst,
231            cfg.send_per_sec,
232        )
233    }
234
235    pub fn new(
236        cpu_budget: i64,
237        mem_limit: usize,
238        spawn_burst: i64,
239        spawn_per_sec: i64,
240        send_burst: i64,
241        send_per_sec: i64,
242    ) -> Self {
243        Self {
244            cpu_budget: AtomicI64::new(cpu_budget),
245            mem_limit: AtomicUsize::new(mem_limit),
246            mem_used: AtomicUsize::new(0),
247            spawn_bucket: TokenBucket::new(spawn_burst, spawn_per_sec),
248            send_bucket: TokenBucket::new(send_burst, send_per_sec),
249        }
250    }
251
252    pub fn remaining_cpu(&self) -> i64 {
253        self.cpu_budget.load(Ordering::Relaxed).max(0)
254    }
255
256    /// Call once per executed instruction (or every N, in a batch — the
257    /// batch only thickens trap latency, it does not change the limit).
258    ///
259    /// `cost` must be **strictly positive**. Zero or negative values used to
260    /// increase the budget (`cur - (-n)`) and `i64::MIN` could overflow the
261    /// subtraction; both now fail closed as [`QuotaError::InvalidCost`].
262    pub fn charge_cpu(&self, cost: i64) -> Result<(), QuotaError> {
263        if cost <= 0 {
264            return Err(QuotaError::InvalidCost);
265        }
266        loop {
267            let cur = self.cpu_budget.load(Ordering::Acquire);
268            if cur < cost {
269                return Err(QuotaError::CpuExhausted);
270            }
271            let new = cur - cost;
272            if self
273                .cpu_budget
274                .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
275                .is_ok()
276            {
277                return Ok(());
278            }
279        }
280    }
281
282    pub fn alloc(&self, bytes: usize) -> Result<(), QuotaError> {
283        loop {
284            let cur = self.mem_used.load(Ordering::Relaxed);
285            let limit = self.mem_limit.load(Ordering::Relaxed);
286            // `saturating_add` would record a smaller charge than `bytes`
287            // when the sum overflows, and then accept it if the limit is
288            // `usize::MAX`. Fail closed: the bytes were not accounted for.
289            let Some(next) = cur.checked_add(bytes) else {
290                return Err(QuotaError::MemoryExhausted {
291                    requested: bytes,
292                    limit,
293                });
294            };
295            if next > limit {
296                return Err(QuotaError::MemoryExhausted {
297                    requested: bytes,
298                    limit,
299                });
300            }
301            if self
302                .mem_used
303                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
304                .is_ok()
305            {
306                return Ok(());
307            }
308        }
309    }
310
311    pub fn free(&self, bytes: usize) {
312        loop {
313            let cur = self.mem_used.load(Ordering::Relaxed);
314            let next = cur.saturating_sub(bytes);
315            if self
316                .mem_used
317                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
318                .is_ok()
319            {
320                return;
321            }
322        }
323    }
324
325    pub fn check_spawn(&self) -> Result<(), QuotaError> {
326        if self.spawn_bucket.try_consume() {
327            Ok(())
328        } else {
329            Err(QuotaError::SpawnRateExceeded)
330        }
331    }
332
333    pub fn check_send(&self) -> Result<(), QuotaError> {
334        if self.send_bucket.try_consume() {
335            Ok(())
336        } else {
337            Err(QuotaError::SendRateExceeded)
338        }
339    }
340
341    /// Reachable only after `check_admin` against `CapTarget::Scheduler`.
342    ///
343    /// A non-positive credit is ignored. A credit that does not fit stops at
344    /// `i64::MAX`: wrapping would make `remaining_cpu` look exhausted and
345    /// kill the flow the admin just tried to extend.
346    pub fn top_up_cpu(&self, extra: i64) {
347        if extra <= 0 {
348            return;
349        }
350        loop {
351            let cur = self.cpu_budget.load(Ordering::Relaxed);
352            let new = cur.saturating_add(extra);
353            if self
354                .cpu_budget
355                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
356                .is_ok()
357            {
358                return;
359            }
360        }
361    }
362
363    /// Raise the heap ceiling. A sum that does not fit stops at `usize::MAX`
364    /// instead of wrapping the limit down to a handful of bytes.
365    pub fn top_up_mem(&self, extra: usize) {
366        loop {
367            let cur = self.mem_limit.load(Ordering::Relaxed);
368            let new = cur.saturating_add(extra);
369            if self
370                .mem_limit
371                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
372                .is_ok()
373            {
374                return;
375            }
376        }
377    }
378
379    pub fn top_up_send(&self, extra: i64) {
380        self.send_bucket.credit(extra);
381    }
382
383    pub fn mem_used(&self) -> usize {
384        self.mem_used.load(Ordering::Relaxed)
385    }
386}
387
388/// Live-flow quota directory so ADMIN top-up can find a running flow.
389pub(crate) struct QuotaTable {
390    inner: Mutex<std::collections::HashMap<u64, Arc<FlowQuota>>>,
391}
392
393impl QuotaTable {
394    pub(crate) fn new() -> Self {
395        Self {
396            inner: Mutex::new(std::collections::HashMap::new()),
397        }
398    }
399
400    pub(crate) fn insert(
401        &self,
402        id: super::process::FlowId,
403        quota: Arc<FlowQuota>,
404    ) -> Result<(), RuntimeError> {
405        sync_lock::lock(&self.inner, "QuotaTable::insert")?.insert(id.as_u64(), quota);
406        Ok(())
407    }
408
409    pub(crate) fn get(
410        &self,
411        id: super::process::FlowId,
412    ) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
413        Ok(sync_lock::lock(&self.inner, "QuotaTable::get")?
414            .get(&id.as_u64())
415            .cloned())
416    }
417
418    pub(crate) fn remove(
419        &self,
420        id: super::process::FlowId,
421    ) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
422        Ok(sync_lock::lock(&self.inner, "QuotaTable::remove")?.remove(&id.as_u64()))
423    }
424}
425
426impl Default for QuotaTable {
427    fn default() -> Self {
428        Self::new()
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn cpu_budget_fails_closed() {
438        let q = FlowQuota::new(10, 1024, 1, 1, 1, 1);
439        assert!(q.charge_cpu(7).is_ok());
440        assert!(q.charge_cpu(4).is_err());
441        assert!(q.charge_cpu(3).is_ok());
442    }
443
444    #[test]
445    fn charge_cpu_rejects_non_positive_cost() {
446        let q = FlowQuota::new(10, 1024, 1, 1, 1, 1);
447        assert_eq!(q.charge_cpu(0), Err(QuotaError::InvalidCost));
448        assert_eq!(q.charge_cpu(-1), Err(QuotaError::InvalidCost));
449        assert_eq!(q.charge_cpu(i64::MIN), Err(QuotaError::InvalidCost));
450        assert_eq!(q.remaining_cpu(), 10);
451    }
452
453    #[test]
454    fn memory_never_exceeds_limit() {
455        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
456        assert!(q.alloc(60).is_ok());
457        assert!(q.alloc(60).is_err());
458        q.free(60);
459        assert!(q.alloc(60).is_ok());
460    }
461
462    #[test]
463    fn alloc_rejects_a_charge_that_would_overflow_the_counter() {
464        let q = FlowQuota::new(1000, usize::MAX, 1, 1, 1, 1);
465        assert!(q.alloc(usize::MAX - 10).is_ok());
466        assert!(q.alloc(20).is_err());
467        assert_eq!(q.mem_used(), usize::MAX - 10);
468    }
469
470    #[test]
471    fn sandbox_is_tighter_than_permissive() {
472        let p = QuotaConfig::permissive();
473        let s = QuotaConfig::sandbox();
474        assert!(s.cpu_budget < p.cpu_budget);
475        assert!(s.mem_limit < p.mem_limit);
476        assert!(s.send_burst < p.send_burst);
477        assert_eq!(QuotaConfig::default().cpu_budget, p.cpu_budget);
478    }
479
480    #[test]
481    fn top_up_does_not_wrap_a_budget_that_is_already_at_the_top() {
482        let q = FlowQuota::new(i64::MAX, usize::MAX, 1, 1, 1, 1);
483        q.top_up_cpu(5);
484        q.top_up_cpu(-5);
485        q.top_up_mem(1);
486        assert_eq!(q.remaining_cpu(), i64::MAX);
487        assert!(q.alloc(1).is_ok());
488    }
489
490    #[test]
491    fn top_up_mem_raises_limit() {
492        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
493        assert!(q.alloc(60).is_ok());
494        assert!(q.alloc(60).is_err());
495        q.top_up_mem(50);
496        assert!(q.alloc(60).is_ok());
497    }
498
499    #[test]
500    fn credit_at_the_top_of_i64_does_not_wrap_the_bucket_negative() {
501        let bucket = TokenBucket::new(i64::MAX, 0);
502        bucket.credit(8);
503        assert!(
504            bucket.try_consume(),
505            "a wrapped bucket would refuse the token"
506        );
507    }
508
509    #[test]
510    fn tokens_for_a_long_interval_saturate_instead_of_overflowing() {
511        let add = tokens_for_elapsed(Duration::from_secs(u64::MAX), i64::MAX);
512        assert_eq!(add, i64::MAX);
513        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), 32), 1);
514        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), -1), 0);
515    }
516
517    #[test]
518    fn spawn_bucket_does_not_over_issue() {
519        let q = FlowQuota::new(1000, 100, 3, 0, 1, 1);
520        assert!(q.check_spawn().is_ok());
521        assert!(q.check_spawn().is_ok());
522        assert!(q.check_spawn().is_ok());
523        assert!(q.check_spawn().is_err());
524    }
525
526    #[test]
527    fn concurrent_try_consume_never_over_issues() -> Result<(), String> {
528        use std::sync::Arc;
529        use std::thread;
530
531        const CAP: i64 = 128;
532        const WORKERS: usize = 16;
533        const ROUNDS: usize = 512;
534        let bucket = Arc::new(TokenBucket::new(CAP, 0));
535        let successes = Arc::new(AtomicUsize::new(0));
536        let handles: Vec<_> = (0..WORKERS)
537            .map(|_| {
538                let bucket = Arc::clone(&bucket);
539                let successes = Arc::clone(&successes);
540                thread::spawn(move || {
541                    for _ in 0..ROUNDS {
542                        if bucket.try_consume() {
543                            successes.fetch_add(1, Ordering::Relaxed);
544                        }
545                    }
546                })
547            })
548            .collect();
549        for handle in handles {
550            handle.join().map_err(|_| "worker panicked".to_string())?;
551        }
552        if successes.load(Ordering::Relaxed) != CAP as usize {
553            return Err(format!(
554                "issued {} tokens, capacity {CAP}",
555                successes.load(Ordering::Relaxed)
556            ));
557        }
558        if bucket.try_consume() {
559            return Err("bucket should be empty".into());
560        }
561        Ok(())
562    }
563
564    #[test]
565    fn concurrent_credit_accumulates_without_loss() -> Result<(), String> {
566        use std::sync::Arc;
567        use std::thread;
568
569        const WORKERS: usize = 12;
570        const PER_WORKER: i64 = 25;
571        let bucket = Arc::new(TokenBucket::new(0, 0));
572        let handles: Vec<_> = (0..WORKERS)
573            .map(|_| {
574                let bucket = Arc::clone(&bucket);
575                thread::spawn(move || {
576                    for _ in 0..PER_WORKER {
577                        bucket.credit(1);
578                    }
579                })
580            })
581            .collect();
582        for handle in handles {
583            handle.join().map_err(|_| "worker panicked".to_string())?;
584        }
585        let expected = (WORKERS as i64) * PER_WORKER;
586        let mut consumed = 0i64;
587        while bucket.try_consume() {
588            consumed += 1;
589        }
590        if consumed != expected {
591            return Err(format!("consumed {consumed}, expected {expected}"));
592        }
593        Ok(())
594    }
595
596    #[test]
597    fn concurrent_charge_cpu_respects_budget() -> Result<(), String> {
598        use std::sync::Arc;
599        use std::thread;
600
601        const BUDGET: i64 = 200;
602        const WORKERS: usize = 8;
603        const CHARGE: i64 = 1;
604        const ROUNDS: usize = 100;
605        let quota = Arc::new(FlowQuota::new(BUDGET, 1024, 1, 1, 1, 1));
606        let ok = Arc::new(AtomicUsize::new(0));
607        let handles: Vec<_> = (0..WORKERS)
608            .map(|_| {
609                let quota = Arc::clone(&quota);
610                let ok = Arc::clone(&ok);
611                thread::spawn(move || {
612                    for _ in 0..ROUNDS {
613                        if quota.charge_cpu(CHARGE).is_ok() {
614                            ok.fetch_add(1, Ordering::Relaxed);
615                        }
616                    }
617                })
618            })
619            .collect();
620        for handle in handles {
621            handle.join().map_err(|_| "worker panicked".to_string())?;
622        }
623        if ok.load(Ordering::Relaxed) != BUDGET as usize {
624            return Err(format!(
625                "charged {} times, budget {BUDGET}",
626                ok.load(Ordering::Relaxed)
627            ));
628        }
629        if quota.charge_cpu(1).is_ok() {
630            return Err("budget should be exhausted".into());
631        }
632        if quota.remaining_cpu() != 0 {
633            return Err(format!("remaining {}", quota.remaining_cpu()));
634        }
635        Ok(())
636    }
637}