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                let cur = self.tokens.load(Ordering::Relaxed);
93                let new = cur.saturating_add(add).min(self.capacity);
94                self.tokens.store(new, Ordering::Relaxed);
95                *last = Instant::now();
96            }
97        }
98        Ok(())
99    }
100
101    /// True and consume one token iff one was available.
102    pub fn try_consume(&self) -> bool {
103        if self.refill().is_err() {
104            return false;
105        }
106        loop {
107            let cur = self.tokens.load(Ordering::Relaxed);
108            if cur <= 0 {
109                return false;
110            }
111            if self
112                .tokens
113                .compare_exchange_weak(cur, cur - 1, Ordering::Relaxed, Ordering::Relaxed)
114                .is_ok()
115            {
116                return true;
117            }
118        }
119    }
120
121    /// ADMIN credit. May exceed capacity until the next refill caps it.
122    ///
123    /// A credit that does not fit stays at `i64::MAX`. Wrapping would make
124    /// the bucket look empty and refuse every later spawn or send.
125    pub fn credit(&self, extra: i64) {
126        if extra <= 0 {
127            return;
128        }
129        loop {
130            let cur = self.tokens.load(Ordering::Relaxed);
131            let new = cur.saturating_add(extra);
132            if self
133                .tokens
134                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
135                .is_ok()
136            {
137                return;
138            }
139        }
140    }
141}
142
143/// How many tokens `per_sec` earns over `elapsed`, without a float cast.
144///
145/// `as i64` on an out-of-range float is a saturating conversion, and the
146/// old `cur + add` then overflowed `i64` (panic in debug, wrap in release).
147fn tokens_for_elapsed(elapsed: Duration, per_sec: i64) -> i64 {
148    if per_sec <= 0 {
149        return 0;
150    }
151    let add = (per_sec as u128).saturating_mul(elapsed.as_nanos()) / 1_000_000_000;
152    match i64::try_from(add) {
153        Ok(n) => n,
154        Err(_) => i64::MAX,
155    }
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum QuotaError {
160    CpuExhausted,
161    MemoryExhausted { requested: usize, limit: usize },
162    SpawnRateExceeded,
163    SendRateExceeded,
164}
165
166impl std::fmt::Display for QuotaError {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        match self {
169            QuotaError::CpuExhausted => f.write_str("flow CPU budget exhausted"),
170            QuotaError::MemoryExhausted { requested, limit } => {
171                write!(
172                    f,
173                    "flow memory exhausted (requested {requested}, limit {limit})"
174                )
175            }
176            QuotaError::SpawnRateExceeded => f.write_str("spawn rate exceeded"),
177            QuotaError::SendRateExceeded => f.write_str("send rate exceeded"),
178        }
179    }
180}
181
182impl std::error::Error for QuotaError {}
183
184pub struct FlowQuota {
185    cpu_budget: AtomicI64,
186    mem_limit: AtomicUsize,
187    mem_used: AtomicUsize,
188    spawn_bucket: TokenBucket,
189    send_bucket: TokenBucket,
190}
191
192impl FlowQuota {
193    pub fn from_config(cfg: QuotaConfig) -> Self {
194        Self::new(
195            cfg.cpu_budget,
196            cfg.mem_limit,
197            cfg.spawn_burst,
198            cfg.spawn_per_sec,
199            cfg.send_burst,
200            cfg.send_per_sec,
201        )
202    }
203
204    pub fn new(
205        cpu_budget: i64,
206        mem_limit: usize,
207        spawn_burst: i64,
208        spawn_per_sec: i64,
209        send_burst: i64,
210        send_per_sec: i64,
211    ) -> Self {
212        Self {
213            cpu_budget: AtomicI64::new(cpu_budget),
214            mem_limit: AtomicUsize::new(mem_limit),
215            mem_used: AtomicUsize::new(0),
216            spawn_bucket: TokenBucket::new(spawn_burst, spawn_per_sec),
217            send_bucket: TokenBucket::new(send_burst, send_per_sec),
218        }
219    }
220
221    pub fn remaining_cpu(&self) -> i64 {
222        self.cpu_budget.load(Ordering::Relaxed).max(0)
223    }
224
225    /// Call once per executed instruction (or every N, in a batch — the
226    /// batch only thickens trap latency, it does not change the limit).
227    pub fn charge_cpu(&self, cost: i64) -> Result<(), QuotaError> {
228        let remaining = self.cpu_budget.fetch_sub(cost, Ordering::Relaxed) - cost;
229        if remaining < 0 {
230            self.cpu_budget.fetch_add(cost, Ordering::Relaxed);
231            return Err(QuotaError::CpuExhausted);
232        }
233        Ok(())
234    }
235
236    pub fn alloc(&self, bytes: usize) -> Result<(), QuotaError> {
237        loop {
238            let cur = self.mem_used.load(Ordering::Relaxed);
239            let limit = self.mem_limit.load(Ordering::Relaxed);
240            // `saturating_add` would record a smaller charge than `bytes`
241            // when the sum overflows, and then accept it if the limit is
242            // `usize::MAX`. Fail closed: the bytes were not accounted for.
243            let Some(next) = cur.checked_add(bytes) else {
244                return Err(QuotaError::MemoryExhausted {
245                    requested: bytes,
246                    limit,
247                });
248            };
249            if next > limit {
250                return Err(QuotaError::MemoryExhausted {
251                    requested: bytes,
252                    limit,
253                });
254            }
255            if self
256                .mem_used
257                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
258                .is_ok()
259            {
260                return Ok(());
261            }
262        }
263    }
264
265    pub fn free(&self, bytes: usize) {
266        loop {
267            let cur = self.mem_used.load(Ordering::Relaxed);
268            let next = cur.saturating_sub(bytes);
269            if self
270                .mem_used
271                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
272                .is_ok()
273            {
274                return;
275            }
276        }
277    }
278
279    pub fn check_spawn(&self) -> Result<(), QuotaError> {
280        if self.spawn_bucket.try_consume() {
281            Ok(())
282        } else {
283            Err(QuotaError::SpawnRateExceeded)
284        }
285    }
286
287    pub fn check_send(&self) -> Result<(), QuotaError> {
288        if self.send_bucket.try_consume() {
289            Ok(())
290        } else {
291            Err(QuotaError::SendRateExceeded)
292        }
293    }
294
295    /// Reachable only after `check_admin` against `CapTarget::Scheduler`.
296    ///
297    /// A non-positive credit is ignored. A credit that does not fit stops at
298    /// `i64::MAX`: wrapping would make `remaining_cpu` look exhausted and
299    /// kill the flow the admin just tried to extend.
300    pub fn top_up_cpu(&self, extra: i64) {
301        if extra <= 0 {
302            return;
303        }
304        loop {
305            let cur = self.cpu_budget.load(Ordering::Relaxed);
306            let new = cur.saturating_add(extra);
307            if self
308                .cpu_budget
309                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
310                .is_ok()
311            {
312                return;
313            }
314        }
315    }
316
317    /// Raise the heap ceiling. A sum that does not fit stops at `usize::MAX`
318    /// instead of wrapping the limit down to a handful of bytes.
319    pub fn top_up_mem(&self, extra: usize) {
320        loop {
321            let cur = self.mem_limit.load(Ordering::Relaxed);
322            let new = cur.saturating_add(extra);
323            if self
324                .mem_limit
325                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
326                .is_ok()
327            {
328                return;
329            }
330        }
331    }
332
333    pub fn top_up_send(&self, extra: i64) {
334        self.send_bucket.credit(extra);
335    }
336
337    pub fn mem_used(&self) -> usize {
338        self.mem_used.load(Ordering::Relaxed)
339    }
340}
341
342/// Live-flow quota directory so ADMIN top-up can find a running flow.
343pub struct QuotaTable {
344    inner: Mutex<std::collections::HashMap<u64, Arc<FlowQuota>>>,
345}
346
347impl QuotaTable {
348    pub fn new() -> Self {
349        Self {
350            inner: Mutex::new(std::collections::HashMap::new()),
351        }
352    }
353
354    pub fn insert(
355        &self,
356        id: super::process::FlowId,
357        quota: Arc<FlowQuota>,
358    ) -> Result<(), RuntimeError> {
359        sync_lock::lock(&self.inner, "QuotaTable::insert")?.insert(id.as_u64(), quota);
360        Ok(())
361    }
362
363    pub fn get(&self, id: super::process::FlowId) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
364        Ok(sync_lock::lock(&self.inner, "QuotaTable::get")?
365            .get(&id.as_u64())
366            .cloned())
367    }
368
369    pub fn remove(
370        &self,
371        id: super::process::FlowId,
372    ) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
373        Ok(sync_lock::lock(&self.inner, "QuotaTable::remove")?.remove(&id.as_u64()))
374    }
375}
376
377impl Default for QuotaTable {
378    fn default() -> Self {
379        Self::new()
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn cpu_budget_fails_closed() {
389        let q = FlowQuota::new(10, 1024, 1, 1, 1, 1);
390        assert!(q.charge_cpu(7).is_ok());
391        assert!(q.charge_cpu(4).is_err());
392        assert!(q.charge_cpu(3).is_ok());
393    }
394
395    #[test]
396    fn memory_never_exceeds_limit() {
397        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
398        assert!(q.alloc(60).is_ok());
399        assert!(q.alloc(60).is_err());
400        q.free(60);
401        assert!(q.alloc(60).is_ok());
402    }
403
404    #[test]
405    fn alloc_rejects_a_charge_that_would_overflow_the_counter() {
406        let q = FlowQuota::new(1000, usize::MAX, 1, 1, 1, 1);
407        assert!(q.alloc(usize::MAX - 10).is_ok());
408        assert!(q.alloc(20).is_err());
409        assert_eq!(q.mem_used(), usize::MAX - 10);
410    }
411
412    #[test]
413    fn sandbox_is_tighter_than_permissive() {
414        let p = QuotaConfig::permissive();
415        let s = QuotaConfig::sandbox();
416        assert!(s.cpu_budget < p.cpu_budget);
417        assert!(s.mem_limit < p.mem_limit);
418        assert!(s.send_burst < p.send_burst);
419        assert_eq!(QuotaConfig::default().cpu_budget, p.cpu_budget);
420    }
421
422    #[test]
423    fn top_up_does_not_wrap_a_budget_that_is_already_at_the_top() {
424        let q = FlowQuota::new(i64::MAX, usize::MAX, 1, 1, 1, 1);
425        q.top_up_cpu(5);
426        q.top_up_cpu(-5);
427        q.top_up_mem(1);
428        assert_eq!(q.remaining_cpu(), i64::MAX);
429        assert!(q.alloc(1).is_ok());
430    }
431
432    #[test]
433    fn top_up_mem_raises_limit() {
434        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
435        assert!(q.alloc(60).is_ok());
436        assert!(q.alloc(60).is_err());
437        q.top_up_mem(50);
438        assert!(q.alloc(60).is_ok());
439    }
440
441    #[test]
442    fn credit_at_the_top_of_i64_does_not_wrap_the_bucket_negative() {
443        let bucket = TokenBucket::new(i64::MAX, 0);
444        bucket.credit(8);
445        assert!(
446            bucket.try_consume(),
447            "a wrapped bucket would refuse the token"
448        );
449    }
450
451    #[test]
452    fn tokens_for_a_long_interval_saturate_instead_of_overflowing() {
453        let add = tokens_for_elapsed(Duration::from_secs(u64::MAX), i64::MAX);
454        assert_eq!(add, i64::MAX);
455        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), 32), 1);
456        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), -1), 0);
457    }
458
459    #[test]
460    fn spawn_bucket_does_not_over_issue() {
461        let q = FlowQuota::new(1000, 100, 3, 0, 1, 1);
462        assert!(q.check_spawn().is_ok());
463        assert!(q.check_spawn().is_ok());
464        assert!(q.check_spawn().is_ok());
465        assert!(q.check_spawn().is_err());
466    }
467}