Skip to main content

datumesh_engine/
runtime.rs

1//! What a function's language plugs into: [`Runtime`], the [`Inputs`] it reads through and
2//! the [`Budget`] it charges.
3
4use std::fmt;
5use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::sync::Arc;
7
8use datumesh_core::{Args, Cell, Descriptor, Scalar};
9
10use crate::error::EvalError;
11
12/// The evaluator of one function language (`code.lang` of a descriptor).
13///
14/// `evaluate` computes the value of `cell` (a cell of the function `descriptor` describes;
15/// `cell.fn_hash` is the descriptor's hash) from the cell's arguments and from the values of
16/// other cells, which it reads through `inputs`. It must be a pure function of those: no
17/// clock, no randomness, no I/O. It charges its work to `budget` and propagates every error
18/// `inputs` and `budget` return (see [`EvalError`]).
19///
20/// It may be called more than once for one cell in one request: when it reads an input that
21/// is not available yet, `read` returns [`EvalError::Suspended`], the engine evaluates the
22/// input, then calls `evaluate` again from the start (reads already made are then answered at
23/// once). So `evaluate` must not have side effects either.
24pub trait Runtime: Send + Sync {
25    /// The language this runtime evaluates: a name (SPEC 2.2), e.g. `expr`. `stored` is the
26    /// engine's own (a lookup) and cannot be configured.
27    fn lang(&self) -> &str;
28
29    /// The value of `cell`, whose type must be the descriptor's declared return type.
30    fn evaluate(
31        &self,
32        descriptor: &Descriptor,
33        cell: &Cell,
34        inputs: &mut dyn Inputs,
35        budget: &mut Budget,
36    ) -> Result<Scalar, EvalError>;
37}
38
39/// How a runtime reads the cells its function depends on.
40pub trait Inputs {
41    /// The value of the cell of function `fn_name` (fully qualified, `<namespace>/<name>`)
42    /// with arguments `args`, as of the evaluation's asof.
43    ///
44    /// Checks that `fn_name` is in the descriptor's `inputs` ([`EvalError::UndeclaredInput`]),
45    /// resolves it as of the evaluation's asof ([`EvalError::NameUnresolved`]), gets the cell
46    /// through the engine and records the receipt used (it becomes one of the computed
47    /// receipt's `inputs`), and returns its value. Costs one unit of fuel.
48    ///
49    /// [`EvalError::Suspended`]: the input is a computed cell not evaluated yet; return it
50    /// (with `?`): the engine evaluates the input and calls the runtime again.
51    /// [`EvalError::InputNotCovered`]: the input has no value as of the asof, so neither has
52    /// the cell being evaluated, whatever the runtime returns next (a receipt cannot list an
53    /// absence among its inputs).
54    ///
55    /// The asof itself is deliberately not offered: a value may depend on time only through
56    /// the inputs it reads, which is what makes memoised versions checkable.
57    fn read(&mut self, fn_name: &str, args: &Args) -> Result<Scalar, EvalError>;
58}
59
60/// The fuel of one request: runtime steps plus input reads, shared by every evaluation the
61/// request makes. When it runs out, the request fails with `BudgetExceeded` and stores
62/// nothing.
63pub struct Budget {
64    fuel: Arc<Fuel>,
65}
66
67struct Fuel {
68    limit: u64,
69    remaining: AtomicU64,
70    exhausted: AtomicBool,
71}
72
73impl Budget {
74    /// A budget of `fuel` units (for a runtime's own tests; the engine makes the budget of a
75    /// request from its configured fuel).
76    pub fn new(fuel: u64) -> Budget {
77        Budget {
78            fuel: Arc::new(Fuel { limit: fuel, remaining: AtomicU64::new(fuel), exhausted: AtomicBool::new(false) }),
79        }
80    }
81
82    /// Charges `steps` units of work. [`EvalError::BudgetExceeded`] when fewer remain: the
83    /// budget is then exhausted for the rest of the request.
84    pub fn charge(&mut self, steps: u64) -> Result<(), EvalError> {
85        self.charge_shared(steps)
86    }
87
88    /// The units left.
89    pub fn remaining(&self) -> u64 {
90        self.fuel.remaining.load(Ordering::Relaxed)
91    }
92
93    /// The units the request started with.
94    pub fn limit(&self) -> u64 {
95        self.fuel.limit
96    }
97
98    /// Whether a charge has failed.
99    pub fn is_exhausted(&self) -> bool {
100        self.fuel.exhausted.load(Ordering::Relaxed)
101    }
102
103    /// Another handle on the same fuel (the engine's reads charge it too).
104    pub(crate) fn share(&self) -> Budget {
105        Budget { fuel: Arc::clone(&self.fuel) }
106    }
107
108    pub(crate) fn charge_shared(&self, steps: u64) -> Result<(), EvalError> {
109        let f = &self.fuel;
110        let mut cur = f.remaining.load(Ordering::Relaxed);
111        loop {
112            if f.exhausted.load(Ordering::Relaxed) || cur < steps {
113                f.exhausted.store(true, Ordering::Relaxed);
114                f.remaining.store(0, Ordering::Relaxed);
115                return Err(EvalError::BudgetExceeded { fuel: f.limit });
116            }
117            match f.remaining.compare_exchange_weak(cur, cur - steps, Ordering::Relaxed, Ordering::Relaxed) {
118                Ok(_) => return Ok(()),
119                Err(now) => cur = now,
120            }
121        }
122    }
123}
124
125impl fmt::Debug for Budget {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.debug_struct("Budget")
128            .field("limit", &self.limit())
129            .field("remaining", &self.remaining())
130            .field("exhausted", &self.is_exhausted())
131            .finish()
132    }
133}