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::collections::BTreeMap;
5use std::fmt;
6use std::sync::{Arc, Mutex, MutexGuard};
7
8use datumesh_core::{Args, Cell, FunctionDescriptor, 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 (and of
17/// [`Inputs::asof`] for an asof-dependent function): no clock, no randomness, no I/O. It
18/// charges its work to `budget` and propagates every error `inputs` and `budget` return (see
19/// [`EvalError`]); it may catch an [`EvalError::Fault`] its language lets it catch.
20///
21/// It may be called more than once for one cell in one request: when it reads an input that
22/// is not available yet, the read returns [`EvalError::Suspended`], the engine evaluates the
23/// input, then calls `evaluate` again from the start (reads already made are then answered at
24/// once). So `evaluate` must not have side effects either. Each call is an attempt with a
25/// budget meter of its own: the fuel of a cell's evaluation is that of its last, completed
26/// call ([`Budget`]).
27pub trait Runtime: Send + Sync {
28    /// The language this runtime evaluates: a name (SPEC 2.2), e.g. `formula`. `stored` is
29    /// the engine's own (a lookup) and cannot be configured.
30    fn lang(&self) -> &str;
31
32    /// The value of `cell`, whose type must be the descriptor's declared return type; or
33    /// [`EvalError::Fault`]: the cell has no value (SPEC 15.12).
34    fn evaluate(
35        &self,
36        descriptor: &FunctionDescriptor,
37        cell: &Cell,
38        inputs: &mut dyn Inputs,
39        budget: &mut Budget,
40    ) -> Result<Scalar, EvalError>;
41
42    /// Whether the function is **asof-dependent** (SPEC 15.12: its body uses `asof()` or a
43    /// bounded `latest`), derived from the descriptor alone. Its receipts then have the
44    /// evaluation asof as their `asof`, one per requested asof, and the engine never reuses
45    /// one for another asof, from the memo or from the store. Provided: `false`.
46    ///
47    /// A function that reads [`Inputs::asof`] is treated as asof-dependent for that
48    /// evaluation even when this says `false`; its receipt is then not kept as a computed
49    /// version (a later request could not tell it apart), so declaring it is cheaper.
50    fn asof_dependent(&self, descriptor: &FunctionDescriptor) -> bool {
51        let _ = descriptor;
52        false
53    }
54}
55
56/// What a read gave: the value and the receipt stating it.
57#[non_exhaustive]
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct Input {
60    /// The value.
61    pub value: Scalar,
62    /// The hash of the receipt stating it (SPEC 8.3).
63    pub receipt_hash: String,
64    /// The receipt's `tx`.
65    pub tx: String,
66    /// The receipt's `asof`.
67    pub asof: String,
68}
69
70impl Input {
71    /// An input (for a runtime's own tests).
72    pub fn new(
73        value: Scalar,
74        receipt_hash: impl Into<String>,
75        tx: impl Into<String>,
76        asof: impl Into<String>,
77    ) -> Input {
78        Input { value, receipt_hash: receipt_hash.into(), tx: tx.into(), asof: asof.into() }
79    }
80}
81
82/// A member of a slice ([`Inputs::read_slice`]): the member cell's arguments and its input.
83#[non_exhaustive]
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct Member {
86    /// Every argument of the member cell.
87    pub args: Args,
88    /// Its value and receipt.
89    pub input: Input,
90}
91
92impl Member {
93    /// A member (for a runtime's own tests).
94    pub fn new(args: Args, input: Input) -> Member {
95        Member { args, input }
96    }
97}
98
99/// One argument of a slice pattern ([`Inputs::read_slice`]).
100#[non_exhaustive]
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub enum Pattern {
103    /// Bound to a value.
104    Value(Scalar),
105    /// Open (`*`): any value.
106    Open,
107    /// Within `[lo..hi]`, both ends inclusive, in the type's order (SPEC 15.13); `lo` after
108    /// `hi` is empty. Both ends are of the argument's type: `number`, `date`, `instant` or
109    /// `string`.
110    Range {
111        /// The low end.
112        lo: Scalar,
113        /// The high end.
114        hi: Scalar,
115    },
116}
117
118/// A slice pattern: every argument of the function, by name.
119pub type SlicePattern = BTreeMap<String, Pattern>;
120
121/// A function name's binding ([`Inputs::binding`]).
122#[non_exhaustive]
123#[derive(Clone, Debug)]
124pub struct FnBinding {
125    /// The function hash the name means.
126    pub fn_hash: String,
127    /// When the binding began (an instant).
128    pub start: String,
129    /// The function's descriptor.
130    pub descriptor: Arc<FunctionDescriptor>,
131}
132
133/// How a runtime reads the cells its function depends on, and the evaluation's asof.
134///
135/// Every read checks that the function read is in the descriptor's `inputs`
136/// ([`EvalError::UndeclaredInput`]) and resolves its name ([`EvalError::NameUnresolved`]),
137/// and is recorded: it becomes one of the computed receipt's `inputs` entries, and the name's
138/// binding is relied on (its start is a candidate for the receipt's `asof`, SPEC 8.2) as soon
139/// as the read is attempted. The fuel each costs is SPEC 15.12's.
140///
141/// Errors a runtime must propagate (with `?`): [`EvalError::Suspended`] (an input not
142/// evaluated yet: the engine evaluates it and calls the runtime again),
143/// [`EvalError::InputNotCovered`] (an input with no value: neither has the cell, whatever the
144/// runtime returns next), [`EvalError::BudgetExceeded`] and the engine's failures. A
145/// [`EvalError::Fault`] it may catch where its language allows (SPEC 15.12: `otherwise`
146/// catches `E_FORMULA_EMPTY` and `E_FORMULA_ABSENT`).
147pub trait Inputs {
148    /// The value of the cell of function `fn_name` (fully qualified, `<namespace>/<name>`)
149    /// with arguments `args`, as of the evaluation's asof: [`read_cell`](Inputs::read_cell)'s
150    /// value. Costs 1.
151    fn read(&mut self, fn_name: &str, args: &Args) -> Result<Scalar, EvalError>;
152
153    /// The cell of `fn_name` with `args` as of the evaluation's asof: its value and the
154    /// receipt that answers (hash, `tx`, `asof`). A computed cell is evaluated by the engine;
155    /// its fault, if it has one, is returned ([`EvalError::Fault`]). Costs 1.
156    fn read_cell(&mut self, fn_name: &str, args: &Args) -> Result<Input, EvalError>;
157
158    /// The cell of `fn_name` with `args` as of the transaction time `t` (SPEC 15.13,
159    /// `asof(cell, T)`): the name resolved as of `t`, the version answering as of `t`; an
160    /// ordinary single-cell input, and `t` a candidate for the receipt's `asof`. `t` after the
161    /// evaluation's asof is the fault `E_FORMULA_FUTURE`, before anything is read. Costs 1.
162    fn read_asof(&mut self, fn_name: &str, args: &Args, t: &str) -> Result<Input, EvalError>;
163
164    /// The members of the slice of `fn_name` with `pattern` (every declared argument; at least
165    /// one open or ranged) as of the evaluation's asof, in SPEC 15.13 key order: for a stored
166    /// function, its cells matching the pattern with a version answering then; for any other,
167    /// the cells of the declared `extent` (or, for a range over a `date` or integer `number`
168    /// argument without one, every day or integer in it) within the pattern, each evaluated
169    /// by the engine, and every one must have a value: else the read is the fault
170    /// `E_FORMULA_ABSENT`. One `inputs` entry `slice:<slice id>:<members hash>`, whose
171    /// manifest the engine stores. Costs 1 + members, charged once the members are obtained.
172    fn read_slice(&mut self, fn_name: &str, pattern: &SlicePattern) -> Result<Vec<Member>, EvalError>;
173
174    /// The versions of the stored cell of `fn_name` with `args` whose `tx` is in `[from, to]`,
175    /// as known as of the evaluation's asof, ascending by `tx` (SPEC 15.13 `versions`): a
176    /// version slice, one `inputs` entry, `to` a candidate for the receipt's `asof`. `to` after
177    /// the evaluation's asof is `E_FORMULA_FUTURE`. Costs 1 + versions.
178    fn read_versions(&mut self, fn_name: &str, args: &Args, from: &str, to: &str) -> Result<Vec<Input>, EvalError>;
179
180    /// The binding of `fn_name` as of the evaluation's asof, or as of `at`: its function hash,
181    /// when it began and the descriptor; `None` when it has none then. Relied on as a read's
182    /// name is. Free.
183    fn binding(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError>;
184
185    /// The evaluation's asof (SPEC 15.12 `asof()`). Reading it makes the evaluation
186    /// asof-dependent (see [`Runtime::asof_dependent`]). Free.
187    fn asof(&mut self) -> String;
188}
189
190/// The fuel of an evaluation attempt, on the request's meter.
191///
192/// Fuel is normative (SPEC 15.12): the fuel of a cell's evaluation is what its last,
193/// completed attempt charges ([`used`](Budget::used)), whatever number of times the engine
194/// restarted it. A request's normative fuel is the sum of the evaluations it completes, and
195/// its limit ([`limit`](Budget::limit)) is checked at every charge against a lower bound of
196/// that sum (each suspended evaluation will charge at least what its last attempt did), so a
197/// request fails with `BudgetExceeded` exactly when its normative fuel exceeds the limit.
198/// Separately the request's **work** (every attempt, those discarded by a restart included,
199/// and the engine's validation reads) has a limit of its own, which bounds the total cost.
200/// When either runs out, the request fails and stores nothing.
201pub struct Budget {
202    meter: Arc<Mutex<Meter>>,
203}
204
205#[derive(Debug)]
206pub(crate) struct Meter {
207    limit: u64,
208    work_limit: u64,
209    /// The normative fuel of the evaluations completed.
210    committed: u64,
211    /// The lower bounds of the suspended evaluations on the stack.
212    pending: u64,
213    /// The running attempt: its charges and its lower bound (its earlier attempt's charges).
214    attempt: u64,
215    floor: u64,
216    work: u64,
217    pub(crate) exhausted: Exhausted,
218}
219
220/// What ran out.
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222pub(crate) enum Exhausted {
223    No,
224    Fuel,
225    Work,
226}
227
228impl Meter {
229    fn bound(&self) -> u64 {
230        self.committed.saturating_add(self.pending).saturating_add(self.attempt.max(self.floor))
231    }
232}
233
234impl Budget {
235    /// A budget of `fuel` units, with no work limit (for a runtime's own tests; the engine
236    /// makes the budget of a request from its configuration).
237    pub fn new(fuel: u64) -> Budget {
238        Budget::with_work(fuel, u64::MAX)
239    }
240
241    pub(crate) fn with_work(fuel: u64, work_limit: u64) -> Budget {
242        Budget {
243            meter: Arc::new(Mutex::new(Meter {
244                limit: fuel,
245                work_limit,
246                committed: 0,
247                pending: 0,
248                attempt: 0,
249                floor: 0,
250                work: 0,
251                exhausted: Exhausted::No,
252            })),
253        }
254    }
255
256    fn lock(&self) -> MutexGuard<'_, Meter> {
257        self.meter.lock().unwrap_or_else(|p| p.into_inner())
258    }
259
260    /// Charges `steps` units of work to this attempt. [`EvalError::BudgetExceeded`] when the
261    /// request's fuel (or its work) runs out: the budget is then exhausted for the rest of the
262    /// request.
263    pub fn charge(&mut self, steps: u64) -> Result<(), EvalError> {
264        self.charge_shared(steps)
265    }
266
267    /// The fuel this attempt has charged so far: at the end of a completed attempt, the
268    /// normative fuel of the evaluation.
269    pub fn used(&self) -> u64 {
270        self.lock().attempt
271    }
272
273    /// The fuel left: the limit less the lower bound of the request's normative fuel.
274    pub fn remaining(&self) -> u64 {
275        let m = self.lock();
276        if m.exhausted != Exhausted::No {
277            return 0;
278        }
279        m.limit.saturating_sub(m.bound())
280    }
281
282    /// The request's fuel limit.
283    pub fn limit(&self) -> u64 {
284        self.lock().limit
285    }
286
287    /// Whether a charge has failed.
288    pub fn is_exhausted(&self) -> bool {
289        self.lock().exhausted != Exhausted::No
290    }
291
292    pub(crate) fn exhausted(&self) -> Exhausted {
293        self.lock().exhausted
294    }
295
296    pub(crate) fn work_limit(&self) -> u64 {
297        self.lock().work_limit
298    }
299
300    /// Another handle on the same meter.
301    pub(crate) fn share(&self) -> Budget {
302        Budget { meter: Arc::clone(&self.meter) }
303    }
304
305    /// A normative charge of the running attempt.
306    pub(crate) fn charge_shared(&self, steps: u64) -> Result<(), EvalError> {
307        let mut m = self.lock();
308        if m.exhausted != Exhausted::No {
309            return Err(EvalError::BudgetExceeded { fuel: m.limit });
310        }
311        m.work = m.work.saturating_add(steps);
312        if m.work > m.work_limit {
313            m.exhausted = Exhausted::Work;
314            return Err(EvalError::BudgetExceeded { fuel: m.limit });
315        }
316        m.attempt = m.attempt.saturating_add(steps);
317        if m.bound() > m.limit {
318            m.exhausted = Exhausted::Fuel;
319            return Err(EvalError::BudgetExceeded { fuel: m.limit });
320        }
321        Ok(())
322    }
323
324    /// Work that is not normative (validation reads, rechecks).
325    pub(crate) fn work(&self, steps: u64) -> Result<(), EvalError> {
326        let mut m = self.lock();
327        if m.exhausted != Exhausted::No {
328            return Err(EvalError::BudgetExceeded { fuel: m.limit });
329        }
330        m.work = m.work.saturating_add(steps);
331        if m.work > m.work_limit {
332            m.exhausted = Exhausted::Work;
333            return Err(EvalError::BudgetExceeded { fuel: m.limit });
334        }
335        Ok(())
336    }
337
338    /// Starts an attempt of a frame whose earlier attempts charged at most `floor` (0 for a
339    /// first attempt); the frame's floor is no longer pending.
340    pub(crate) fn begin_attempt(&self, floor: u64) {
341        let mut m = self.lock();
342        m.pending = m.pending.saturating_sub(floor);
343        m.attempt = 0;
344        m.floor = floor;
345    }
346
347    /// The running attempt suspended: returns the frame's new floor, now pending.
348    pub(crate) fn suspend_attempt(&self) -> u64 {
349        let mut m = self.lock();
350        let floor = m.attempt.max(m.floor);
351        m.pending = m.pending.saturating_add(floor);
352        m.attempt = 0;
353        m.floor = 0;
354        floor
355    }
356
357    /// The running attempt completed: its fuel is the evaluation's.
358    pub(crate) fn finish_attempt(&self) -> u64 {
359        let mut m = self.lock();
360        let used = m.attempt;
361        m.committed = m.committed.saturating_add(used);
362        m.attempt = 0;
363        m.floor = 0;
364        used
365    }
366}
367
368impl fmt::Debug for Budget {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        let m = self.lock();
371        f.debug_struct("Budget")
372            .field("limit", &m.limit)
373            .field("used", &m.attempt)
374            .field("committed", &m.committed)
375            .field("exhausted", &(m.exhausted != Exhausted::No))
376            .finish()
377    }
378}