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