byteflow-actors 0.9.24

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Resource quotas — Phase 3.
//!
//! Three independent budgets per flow:
//! - `cpu_budget` — remaining reductions/instructions before the flow is
//!   stopped pending an ADMIN top-up. Distinct from the scheduler *quantum*
//!   (fairness / preemption, not an absolute consumption cap).
//! - `mem_used` / `mem_limit` — bytes currently charged to this flow's heap.
//! - `spawn_bucket` / `send_bucket` — token buckets drained on SPAWN / SEND,
//!   refilled by time. Covers the spawn-bomb and mailbox-flood DoS the
//!   threat model already admits.
//!
//! All three fail *closed*: exhausting a budget aborts the instruction
//! (error / trap), never degrades silently into unlimited behaviour.

use std::sync::atomic::{AtomicI64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use super::error::RuntimeError;
use super::sync_lock;

/// Tunables copied onto every newly spawned flow.
#[derive(Clone, Copy, Debug)]
pub struct QuotaConfig {
    pub cpu_budget: i64,
    pub mem_limit: usize,
    pub spawn_burst: i64,
    pub spawn_per_sec: i64,
    pub send_burst: i64,
    pub send_per_sec: i64,
}

impl QuotaConfig {
    /// Current defaults: generous so samples and tests keep passing.
    pub fn permissive() -> Self {
        Self {
            cpu_budget: 1_000_000_000,
            mem_limit: 64 * 1024 * 1024,
            spawn_burst: 10_000,
            spawn_per_sec: 10_000,
            send_burst: 50_000,
            send_per_sec: 50_000,
        }
    }

    /// Starting point for untrusted modules. Tune under real load before
    /// using as a production default. Pair with
    /// [`crate::RuntimeConfig::sandbox`] for process-wide `max_flows` /
    /// `max_ask_waits` ceilings.
    pub fn sandbox() -> Self {
        Self {
            cpu_budget: 50_000,
            mem_limit: 16 * 1024 * 1024,
            spawn_burst: 32,
            spawn_per_sec: 32,
            send_burst: 256,
            send_per_sec: 64,
        }
    }
}

impl Default for QuotaConfig {
    fn default() -> Self {
        Self::permissive()
    }
}

pub struct TokenBucket {
    capacity: i64,
    tokens: AtomicI64,
    refill_per_sec: i64,
    last_refill: Mutex<Instant>,
}

impl TokenBucket {
    pub fn new(capacity: i64, refill_per_sec: i64) -> Self {
        Self {
            capacity,
            tokens: AtomicI64::new(capacity),
            refill_per_sec,
            last_refill: Mutex::new(Instant::now()),
        }
    }

    /// Refill or fail closed on lock poison (no tokens granted).
    fn refill(&self) -> Result<(), RuntimeError> {
        let mut last = sync_lock::lock(&self.last_refill, "TokenBucket::refill")?;
        let elapsed = last.elapsed();
        if elapsed >= Duration::from_millis(50) {
            let add = tokens_for_elapsed(elapsed, self.refill_per_sec);
            if add > 0 {
                loop {
                    let cur = self.tokens.load(Ordering::Acquire);
                    let new = cur.saturating_add(add).min(self.capacity);
                    if self
                        .tokens
                        .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
                        .is_ok()
                    {
                        break;
                    }
                }
                *last = Instant::now();
            }
        }
        Ok(())
    }

    /// True and consume one token iff one was available.
    pub fn try_consume(&self) -> bool {
        if self.refill().is_err() {
            return false;
        }
        loop {
            let cur = self.tokens.load(Ordering::Acquire);
            if cur <= 0 {
                return false;
            }
            if self
                .tokens
                .compare_exchange_weak(cur, cur - 1, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return true;
            }
        }
    }

    /// ADMIN credit. May exceed capacity until the next refill caps it.
    ///
    /// A credit that does not fit stays at `i64::MAX`. Wrapping would make
    /// the bucket look empty and refuse every later spawn or send.
    pub fn credit(&self, extra: i64) {
        if extra <= 0 {
            return;
        }
        loop {
            let cur = self.tokens.load(Ordering::Acquire);
            let new = cur.saturating_add(extra);
            if self
                .tokens
                .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return;
            }
        }
    }
}

/// How many tokens `per_sec` earns over `elapsed`, without a float cast.
///
/// `as i64` on an out-of-range float is a saturating conversion, and the
/// old `cur + add` then overflowed `i64` (panic in debug, wrap in release).
fn tokens_for_elapsed(elapsed: Duration, per_sec: i64) -> i64 {
    if per_sec <= 0 {
        return 0;
    }
    let add = (per_sec as u128).saturating_mul(elapsed.as_nanos()) / 1_000_000_000;
    match i64::try_from(add) {
        Ok(n) => n,
        Err(_) => i64::MAX,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuotaError {
    CpuExhausted,
    /// `charge_cpu` rejected `cost <= 0` (would grow the budget or overflow).
    InvalidCost,
    MemoryExhausted { requested: usize, limit: usize },
    SpawnRateExceeded,
    SendRateExceeded,
}

impl QuotaError {
    /// Stable tag for [`crate::SecurityEvent::QuotaExceeded`].
    pub fn audit_kind(self) -> &'static str {
        match self {
            QuotaError::CpuExhausted => "cpu",
            QuotaError::InvalidCost => "invalid_cost",
            QuotaError::MemoryExhausted { .. } => "memory",
            QuotaError::SpawnRateExceeded => "spawn_rate",
            QuotaError::SendRateExceeded => "send_rate",
        }
    }
}

impl std::fmt::Display for QuotaError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            QuotaError::CpuExhausted => f.write_str("flow CPU budget exhausted"),
            QuotaError::InvalidCost => f.write_str("CPU charge must be positive"),
            QuotaError::MemoryExhausted { requested, limit } => {
                write!(
                    f,
                    "flow memory exhausted (requested {requested}, limit {limit})"
                )
            }
            QuotaError::SpawnRateExceeded => f.write_str("spawn rate exceeded"),
            QuotaError::SendRateExceeded => f.write_str("send rate exceeded"),
        }
    }
}

impl std::error::Error for QuotaError {}

pub struct FlowQuota {
    cpu_budget: AtomicI64,
    mem_limit: AtomicUsize,
    mem_used: AtomicUsize,
    spawn_bucket: TokenBucket,
    send_bucket: TokenBucket,
}

impl FlowQuota {
    pub fn from_config(cfg: QuotaConfig) -> Self {
        Self::new(
            cfg.cpu_budget,
            cfg.mem_limit,
            cfg.spawn_burst,
            cfg.spawn_per_sec,
            cfg.send_burst,
            cfg.send_per_sec,
        )
    }

    pub fn new(
        cpu_budget: i64,
        mem_limit: usize,
        spawn_burst: i64,
        spawn_per_sec: i64,
        send_burst: i64,
        send_per_sec: i64,
    ) -> Self {
        Self {
            cpu_budget: AtomicI64::new(cpu_budget),
            mem_limit: AtomicUsize::new(mem_limit),
            mem_used: AtomicUsize::new(0),
            spawn_bucket: TokenBucket::new(spawn_burst, spawn_per_sec),
            send_bucket: TokenBucket::new(send_burst, send_per_sec),
        }
    }

    pub fn remaining_cpu(&self) -> i64 {
        self.cpu_budget.load(Ordering::Relaxed).max(0)
    }

    /// Call once per executed instruction (or every N, in a batch — the
    /// batch only thickens trap latency, it does not change the limit).
    ///
    /// `cost` must be **strictly positive**. Zero or negative values used to
    /// increase the budget (`cur - (-n)`) and `i64::MIN` could overflow the
    /// subtraction; both now fail closed as [`QuotaError::InvalidCost`].
    pub fn charge_cpu(&self, cost: i64) -> Result<(), QuotaError> {
        if cost <= 0 {
            return Err(QuotaError::InvalidCost);
        }
        loop {
            let cur = self.cpu_budget.load(Ordering::Acquire);
            if cur < cost {
                return Err(QuotaError::CpuExhausted);
            }
            let new = cur - cost;
            if self
                .cpu_budget
                .compare_exchange_weak(cur, new, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return Ok(());
            }
        }
    }

    pub fn alloc(&self, bytes: usize) -> Result<(), QuotaError> {
        loop {
            let cur = self.mem_used.load(Ordering::Relaxed);
            let limit = self.mem_limit.load(Ordering::Relaxed);
            // `saturating_add` would record a smaller charge than `bytes`
            // when the sum overflows, and then accept it if the limit is
            // `usize::MAX`. Fail closed: the bytes were not accounted for.
            let Some(next) = cur.checked_add(bytes) else {
                return Err(QuotaError::MemoryExhausted {
                    requested: bytes,
                    limit,
                });
            };
            if next > limit {
                return Err(QuotaError::MemoryExhausted {
                    requested: bytes,
                    limit,
                });
            }
            if self
                .mem_used
                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return Ok(());
            }
        }
    }

    pub fn free(&self, bytes: usize) {
        loop {
            let cur = self.mem_used.load(Ordering::Relaxed);
            let next = cur.saturating_sub(bytes);
            if self
                .mem_used
                .compare_exchange_weak(cur, next, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return;
            }
        }
    }

    pub fn check_spawn(&self) -> Result<(), QuotaError> {
        if self.spawn_bucket.try_consume() {
            Ok(())
        } else {
            Err(QuotaError::SpawnRateExceeded)
        }
    }

    pub fn check_send(&self) -> Result<(), QuotaError> {
        if self.send_bucket.try_consume() {
            Ok(())
        } else {
            Err(QuotaError::SendRateExceeded)
        }
    }

    /// Reachable only after `check_admin` against `CapTarget::Scheduler`.
    ///
    /// A non-positive credit is ignored. A credit that does not fit stops at
    /// `i64::MAX`: wrapping would make `remaining_cpu` look exhausted and
    /// kill the flow the admin just tried to extend.
    pub fn top_up_cpu(&self, extra: i64) {
        if extra <= 0 {
            return;
        }
        loop {
            let cur = self.cpu_budget.load(Ordering::Relaxed);
            let new = cur.saturating_add(extra);
            if self
                .cpu_budget
                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return;
            }
        }
    }

    /// Raise the heap ceiling. A sum that does not fit stops at `usize::MAX`
    /// instead of wrapping the limit down to a handful of bytes.
    pub fn top_up_mem(&self, extra: usize) {
        loop {
            let cur = self.mem_limit.load(Ordering::Relaxed);
            let new = cur.saturating_add(extra);
            if self
                .mem_limit
                .compare_exchange_weak(cur, new, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                return;
            }
        }
    }

    pub fn top_up_send(&self, extra: i64) {
        self.send_bucket.credit(extra);
    }

    pub fn mem_used(&self) -> usize {
        self.mem_used.load(Ordering::Relaxed)
    }
}

/// Live-flow quota directory so ADMIN top-up can find a running flow.
pub struct QuotaTable {
    inner: Mutex<std::collections::HashMap<u64, Arc<FlowQuota>>>,
}

impl QuotaTable {
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(std::collections::HashMap::new()),
        }
    }

    pub fn insert(
        &self,
        id: super::process::FlowId,
        quota: Arc<FlowQuota>,
    ) -> Result<(), RuntimeError> {
        sync_lock::lock(&self.inner, "QuotaTable::insert")?.insert(id.as_u64(), quota);
        Ok(())
    }

    pub fn get(&self, id: super::process::FlowId) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
        Ok(sync_lock::lock(&self.inner, "QuotaTable::get")?
            .get(&id.as_u64())
            .cloned())
    }

    pub fn remove(
        &self,
        id: super::process::FlowId,
    ) -> Result<Option<Arc<FlowQuota>>, RuntimeError> {
        Ok(sync_lock::lock(&self.inner, "QuotaTable::remove")?.remove(&id.as_u64()))
    }
}

impl Default for QuotaTable {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cpu_budget_fails_closed() {
        let q = FlowQuota::new(10, 1024, 1, 1, 1, 1);
        assert!(q.charge_cpu(7).is_ok());
        assert!(q.charge_cpu(4).is_err());
        assert!(q.charge_cpu(3).is_ok());
    }

    #[test]
    fn charge_cpu_rejects_non_positive_cost() {
        let q = FlowQuota::new(10, 1024, 1, 1, 1, 1);
        assert_eq!(q.charge_cpu(0), Err(QuotaError::InvalidCost));
        assert_eq!(q.charge_cpu(-1), Err(QuotaError::InvalidCost));
        assert_eq!(q.charge_cpu(i64::MIN), Err(QuotaError::InvalidCost));
        assert_eq!(q.remaining_cpu(), 10);
    }

    #[test]
    fn memory_never_exceeds_limit() {
        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
        assert!(q.alloc(60).is_ok());
        assert!(q.alloc(60).is_err());
        q.free(60);
        assert!(q.alloc(60).is_ok());
    }

    #[test]
    fn alloc_rejects_a_charge_that_would_overflow_the_counter() {
        let q = FlowQuota::new(1000, usize::MAX, 1, 1, 1, 1);
        assert!(q.alloc(usize::MAX - 10).is_ok());
        assert!(q.alloc(20).is_err());
        assert_eq!(q.mem_used(), usize::MAX - 10);
    }

    #[test]
    fn sandbox_is_tighter_than_permissive() {
        let p = QuotaConfig::permissive();
        let s = QuotaConfig::sandbox();
        assert!(s.cpu_budget < p.cpu_budget);
        assert!(s.mem_limit < p.mem_limit);
        assert!(s.send_burst < p.send_burst);
        assert_eq!(QuotaConfig::default().cpu_budget, p.cpu_budget);
    }

    #[test]
    fn top_up_does_not_wrap_a_budget_that_is_already_at_the_top() {
        let q = FlowQuota::new(i64::MAX, usize::MAX, 1, 1, 1, 1);
        q.top_up_cpu(5);
        q.top_up_cpu(-5);
        q.top_up_mem(1);
        assert_eq!(q.remaining_cpu(), i64::MAX);
        assert!(q.alloc(1).is_ok());
    }

    #[test]
    fn top_up_mem_raises_limit() {
        let q = FlowQuota::new(1000, 100, 1, 1, 1, 1);
        assert!(q.alloc(60).is_ok());
        assert!(q.alloc(60).is_err());
        q.top_up_mem(50);
        assert!(q.alloc(60).is_ok());
    }

    #[test]
    fn credit_at_the_top_of_i64_does_not_wrap_the_bucket_negative() {
        let bucket = TokenBucket::new(i64::MAX, 0);
        bucket.credit(8);
        assert!(
            bucket.try_consume(),
            "a wrapped bucket would refuse the token"
        );
    }

    #[test]
    fn tokens_for_a_long_interval_saturate_instead_of_overflowing() {
        let add = tokens_for_elapsed(Duration::from_secs(u64::MAX), i64::MAX);
        assert_eq!(add, i64::MAX);
        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), 32), 1);
        assert_eq!(tokens_for_elapsed(Duration::from_millis(50), -1), 0);
    }

    #[test]
    fn spawn_bucket_does_not_over_issue() {
        let q = FlowQuota::new(1000, 100, 3, 0, 1, 1);
        assert!(q.check_spawn().is_ok());
        assert!(q.check_spawn().is_ok());
        assert!(q.check_spawn().is_ok());
        assert!(q.check_spawn().is_err());
    }

    #[test]
    fn concurrent_try_consume_never_over_issues() -> Result<(), String> {
        use std::sync::Arc;
        use std::thread;

        const CAP: i64 = 128;
        const WORKERS: usize = 16;
        const ROUNDS: usize = 512;
        let bucket = Arc::new(TokenBucket::new(CAP, 0));
        let successes = Arc::new(AtomicUsize::new(0));
        let handles: Vec<_> = (0..WORKERS)
            .map(|_| {
                let bucket = Arc::clone(&bucket);
                let successes = Arc::clone(&successes);
                thread::spawn(move || {
                    for _ in 0..ROUNDS {
                        if bucket.try_consume() {
                            successes.fetch_add(1, Ordering::Relaxed);
                        }
                    }
                })
            })
            .collect();
        for handle in handles {
            handle.join().map_err(|_| "worker panicked".to_string())?;
        }
        if successes.load(Ordering::Relaxed) != CAP as usize {
            return Err(format!(
                "issued {} tokens, capacity {CAP}",
                successes.load(Ordering::Relaxed)
            ));
        }
        if bucket.try_consume() {
            return Err("bucket should be empty".into());
        }
        Ok(())
    }

    #[test]
    fn concurrent_credit_accumulates_without_loss() -> Result<(), String> {
        use std::sync::Arc;
        use std::thread;

        const WORKERS: usize = 12;
        const PER_WORKER: i64 = 25;
        let bucket = Arc::new(TokenBucket::new(0, 0));
        let handles: Vec<_> = (0..WORKERS)
            .map(|_| {
                let bucket = Arc::clone(&bucket);
                thread::spawn(move || {
                    for _ in 0..PER_WORKER {
                        bucket.credit(1);
                    }
                })
            })
            .collect();
        for handle in handles {
            handle.join().map_err(|_| "worker panicked".to_string())?;
        }
        let expected = (WORKERS as i64) * PER_WORKER;
        let mut consumed = 0i64;
        while bucket.try_consume() {
            consumed += 1;
        }
        if consumed != expected {
            return Err(format!("consumed {consumed}, expected {expected}"));
        }
        Ok(())
    }

    #[test]
    fn concurrent_charge_cpu_respects_budget() -> Result<(), String> {
        use std::sync::Arc;
        use std::thread;

        const BUDGET: i64 = 200;
        const WORKERS: usize = 8;
        const CHARGE: i64 = 1;
        const ROUNDS: usize = 100;
        let quota = Arc::new(FlowQuota::new(BUDGET, 1024, 1, 1, 1, 1));
        let ok = Arc::new(AtomicUsize::new(0));
        let handles: Vec<_> = (0..WORKERS)
            .map(|_| {
                let quota = Arc::clone(&quota);
                let ok = Arc::clone(&ok);
                thread::spawn(move || {
                    for _ in 0..ROUNDS {
                        if quota.charge_cpu(CHARGE).is_ok() {
                            ok.fetch_add(1, Ordering::Relaxed);
                        }
                    }
                })
            })
            .collect();
        for handle in handles {
            handle.join().map_err(|_| "worker panicked".to_string())?;
        }
        if ok.load(Ordering::Relaxed) != BUDGET as usize {
            return Err(format!(
                "charged {} times, budget {BUDGET}",
                ok.load(Ordering::Relaxed)
            ));
        }
        if quota.charge_cpu(1).is_ok() {
            return Err("budget should be exhausted".into());
        }
        if quota.remaining_cpu() != 0 {
            return Err(format!("remaining {}", quota.remaining_cpu()));
        }
        Ok(())
    }
}