Skip to main content

datumesh_engine/
engine.rs

1//! [`Engine`], [`EngineBuilder`] and [`Answer`].
2
3use std::borrow::Cow;
4use std::collections::{BTreeSet, HashMap};
5use std::fmt;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8
9use datumesh_core::{
10    lexical, Cell, CellRef, Evaluation, Fault, FunctionDescriptor, KeyDoc, Resolver, Scalar, SigningKey,
11};
12use datumesh_store::Store;
13
14use crate::cache::{Cache, Parsed};
15use crate::check::{check_args, check_no_slice};
16use crate::clock::{Clock, SystemClock};
17use crate::error::{ConfigError, EngineError, EvalError, StoreError};
18use crate::eval::{is_instant, parse_stored, Done, Req, Use};
19use crate::memo::Memo;
20use crate::runtime::Runtime;
21
22/// The default depth limit: frames on the evaluation stack.
23pub const DEFAULT_DEPTH_LIMIT: usize = 10_000;
24/// The default fuel of a request: runtime steps plus input reads.
25pub const DEFAULT_FUEL: u64 = 10_000_000;
26/// The default work limit of a request, as a multiple of its fuel.
27pub const DEFAULT_WORK_FACTOR: u64 = 16;
28/// The default memo capacity, in entries.
29pub const DEFAULT_MEMO_CAPACITY: usize = 1_000_000;
30
31/// The answer to "the value of this cell as of A".
32#[non_exhaustive]
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum Answer {
35    /// The receipt that answers, canonical JSON text: for a stored cell the publisher's
36    /// receipt as the store holds it; for a computed cell one signed by the engine.
37    Receipt(Vec<u8>),
38    /// Nothing answers as of A, and no receipt is given.
39    ///
40    /// `fault: None`: the function is unknown then, a stored cell has no version answering
41    /// then, or a computed cell reads such an input. `fault: Some(code)`: the cell is a
42    /// computed cell whose evaluation faulted (SPEC 15.12): it has no value, deterministically
43    /// (the envelope's `fault`, SPEC 5.5). Since 0.3.0 the variant carries `fault`.
44    NotCovered {
45        /// The evaluation fault, if the cell has no value because of one.
46        fault: Option<Fault>,
47    },
48    /// The cell is withdrawn as of A (SPEC 8.1, store 0.6.0): a stored cell whose latest
49    /// version as of A is a withdrawal. It has no value, and no receipt of one: `receipt` is
50    /// the withdrawal's canonical bytes (as `Resolver::receipt` gives them for its hash) and
51    /// `reason` its `withdrawn` text. Since 0.6.0. A formula reading the cell alone has no
52    /// value of it ([`NotCovered`](Answer::NotCovered)), and nothing is stored for the read.
53    Withdrawn {
54        /// The withdrawal's canonical bytes.
55        receipt: Vec<u8>,
56        /// The reason: the withdrawal's `withdrawn` member.
57        reason: String,
58    },
59}
60
61impl Answer {
62    /// `NotCovered` without a fault.
63    pub const NOT_COVERED: Answer = Answer::NotCovered { fault: None };
64}
65
66/// The function computing a computed receipt's `summary`.
67pub type SummaryFn = dyn Fn(&Cell) -> String + Send + Sync;
68
69/// Builds an [`Engine`]: [`Engine::builder`].
70pub struct EngineBuilder {
71    pub(crate) store: Arc<dyn Store + Send + Sync>,
72    pub(crate) host: String,
73    pub(crate) key: Option<SigningKey>,
74    pub(crate) key_file: Option<PathBuf>,
75    pub(crate) runtimes: Vec<Arc<dyn Runtime>>,
76    pub(crate) depth_limit: usize,
77    pub(crate) fuel: u64,
78    pub(crate) work_limit: Option<u64>,
79    pub(crate) memo_capacity: usize,
80    pub(crate) licence: String,
81    pub(crate) summary: Option<Arc<SummaryFn>>,
82    pub(crate) clock: Arc<dyn Clock>,
83}
84
85impl EngineBuilder {
86    /// The mesh's signing key.
87    pub fn signing_key(mut self, key: SigningKey) -> Self {
88        self.key = Some(key);
89        self.key_file = None;
90        self
91    }
92
93    /// The mesh's signing key, from a file holding its 32-byte seed: the 32 bytes, or 64 hex
94    /// digits (an optional final newline). The only file the engine reads.
95    pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
96        self.key_file = Some(path.into());
97        self.key = None;
98        self
99    }
100
101    /// Adds a runtime, for the language its [`Runtime::lang`] names.
102    pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
103        self.runtimes.push(runtime);
104        self
105    }
106
107    /// The depth limit: frames on the evaluation stack (default 10,000).
108    pub fn depth_limit(mut self, limit: usize) -> Self {
109        self.depth_limit = limit;
110        self
111    }
112
113    /// The fuel of each request: runtime steps plus input reads (default 10,000,000).
114    pub fn fuel(mut self, fuel: u64) -> Self {
115        self.fuel = fuel;
116        self
117    }
118
119    /// The work limit of each request: every evaluation attempt (those discarded by a restart
120    /// included) and the engine's validation reads, in fuel units (default 16 times the
121    /// fuel). It bounds the total cost of a request beyond its normative fuel
122    /// ([`EngineError::WorkExceeded`](crate::EngineError::WorkExceeded)). Since 0.3.0.
123    pub fn work_limit(mut self, units: u64) -> Self {
124        self.work_limit = Some(units);
125        self
126    }
127
128    /// How many answers the memo keeps (default 1,000,000); when full it starts afresh. 0
129    /// turns the memo off: every request then validates through the store.
130    pub fn memo_capacity(mut self, entries: usize) -> Self {
131        self.memo_capacity = entries;
132        self
133    }
134
135    /// The mesh's own licence: an SPDX identifier or an https URL (default `CC-BY-4.0`).
136    ///
137    /// Since 0.4.1 (spec-0.4.3, SPEC 8.5) it is the `licence` of computed receipts with no
138    /// input receipt (a constant, or only empty slices); a receipt with inputs inherits its
139    /// licence from theirs (see the crate documentation, "Licence inheritance").
140    pub fn licence(mut self, licence: impl Into<String>) -> Self {
141        self.licence = licence.into();
142        self
143    }
144
145    /// The `summary` of a computed receipt, from its cell. The default says which function
146    /// the mesh computed: `"<namespace>/<function> computed by <mesh host>."`.
147    pub fn summary(mut self, f: impl Fn(&Cell) -> String + Send + Sync + 'static) -> Self {
148        self.summary = Some(Arc::new(f));
149        self
150    }
151
152    /// The clock (default [`SystemClock`]).
153    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
154        self.clock = clock;
155        self
156    }
157
158    /// Checks the configuration and builds the engine.
159    pub fn build(self) -> Result<Engine, ConfigError> {
160        lexical::check_dns_name(&self.host, "$.host").map_err(ConfigError::Host)?;
161        let key = match (self.key, &self.key_file) {
162            (Some(k), _) => k,
163            (None, Some(path)) => read_seed(path)?,
164            (None, None) => return Err(ConfigError::NoSigningKey),
165        };
166        lexical::check_licence(&self.licence, "$.licence").map_err(ConfigError::Licence)?;
167        let mut runtimes: HashMap<String, Arc<dyn Runtime>> = HashMap::new();
168        for rt in self.runtimes {
169            let lang = rt.lang().to_string();
170            if lang == STORED {
171                return Err(ConfigError::Runtime("stored is answered by the engine, not a runtime".into()));
172            }
173            if runtimes.insert(lang.clone(), rt).is_some() {
174                return Err(ConfigError::Runtime(format!("two runtimes for {lang}")));
175            }
176        }
177        let published = match self.store.namespace(&self.host) {
178            Ok(Some(ns)) => KeyDoc::from_json(&self.host, &ns.keydoc)
179                .ok()
180                .and_then(|doc| doc.key(key.key_id()).map(|k| k.public == key.public_key()))
181                .unwrap_or(false),
182            Ok(None) => false,
183            Err(e) => return Err(ConfigError::Store(StoreError::new("namespace", e))),
184        };
185        if !published {
186            return Err(ConfigError::KeyNotPublished { host: self.host, key_id: key.key_id().to_string() });
187        }
188        Ok(Engine {
189            store: self.store,
190            host: self.host,
191            key,
192            runtimes,
193            depth_limit: self.depth_limit,
194            fuel: self.fuel,
195            work_limit: self.work_limit.unwrap_or(self.fuel.saturating_mul(DEFAULT_WORK_FACTOR)),
196            licence: self.licence,
197            summary: self.summary,
198            clock: self.clock,
199            memo: Memo::new(self.memo_capacity),
200            descriptors: Cache::new(DESCRIPTOR_CACHE),
201            receipts: Cache::new(RECEIPT_CACHE),
202            asof_dependent: Cache::new(DESCRIPTOR_CACHE),
203            evaluator: Mutex::new(()),
204        })
205    }
206}
207
208impl fmt::Debug for EngineBuilder {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("EngineBuilder").field("host", &self.host).finish_non_exhaustive()
211    }
212}
213
214/// The engine: answers the value of a cell as of a time. See the crate documentation.
215pub struct Engine {
216    pub(crate) store: Arc<dyn Store + Send + Sync>,
217    pub(crate) host: String,
218    pub(crate) key: SigningKey,
219    pub(crate) runtimes: HashMap<String, Arc<dyn Runtime>>,
220    pub(crate) depth_limit: usize,
221    pub(crate) fuel: u64,
222    pub(crate) work_limit: u64,
223    pub(crate) licence: String,
224    pub(crate) summary: Option<Arc<SummaryFn>>,
225    pub(crate) clock: Arc<dyn Clock>,
226    pub(crate) memo: Memo,
227    /// Parsed descriptors by function hash (immutable: content-addressed).
228    pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
229    /// Parsed receipts by hash (immutable: content-addressed).
230    pub(crate) receipts: Cache<Arc<Parsed>>,
231    /// Whether a function is asof-dependent, by function hash: a pure function of the
232    /// descriptor, which a runtime may take long to derive (it is asked on every frame).
233    pub(crate) asof_dependent: Cache<bool>,
234    /// Evaluations run one at a time (single-flight); answers from the memo do not wait.
235    pub(crate) evaluator: Mutex<()>,
236}
237
238/// The language of stored functions, answered by the engine itself.
239pub(crate) const STORED: &str = "stored";
240const DESCRIPTOR_CACHE: usize = 10_000;
241const RECEIPT_CACHE: usize = 100_000;
242
243/// The seed in a key file: 32 bytes, or 64 lowercase hex digits and an optional newline.
244fn read_seed(path: &std::path::Path) -> Result<SigningKey, ConfigError> {
245    let bytes = std::fs::read(path).map_err(|e| ConfigError::KeyFile(format!("{}: {e}", path.display())))?;
246    if let Ok(seed) = <[u8; 32]>::try_from(bytes.as_slice()) {
247        return Ok(SigningKey::from_seed(&seed));
248    }
249    let text = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
250    let hex = |c: u8| match c {
251        b'0'..=b'9' => Some(c - b'0'),
252        b'a'..=b'f' => Some(c - b'a' + 10),
253        _ => None,
254    };
255    if text.len() == 64 {
256        let mut seed = [0u8; 32];
257        let mut ok = true;
258        for (i, pair) in text.chunks(2).enumerate() {
259            match (hex(pair[0]), hex(pair[1])) {
260                (Some(h), Some(l)) => seed[i] = h << 4 | l,
261                _ => ok = false,
262            }
263        }
264        if ok {
265            return Ok(SigningKey::from_seed(&seed));
266        }
267    }
268    Err(ConfigError::KeyFile(format!("{}: not a seed (32 bytes, or 64 lowercase hex digits)", path.display())))
269}
270
271impl fmt::Debug for Engine {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        f.debug_struct("Engine").finish_non_exhaustive()
274    }
275}
276
277/// Sizes of the memo and of the dirty set ([`Engine::memo_stats`]).
278#[non_exhaustive]
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub struct MemoStats {
281    /// Answers held.
282    pub entries: usize,
283    /// Cells with at least one answer held.
284    pub cells: usize,
285    /// Edges of the in-memory dependents index (input cell to reading cell).
286    pub dependent_edges: usize,
287    /// Cells marked dirty and kept to refuse answers of evaluations already running.
288    pub dirty: usize,
289    /// Answers dropped because a stored version they rested on changed, kept to be rechecked
290    /// from memory (early cutoff without store queries for the unchanged part of a graph).
291    pub stale: usize,
292    /// Slices over stored functions read by answers held (matched by pattern against new
293    /// stored versions). Since 0.3.0.
294    pub slice_patterns: usize,
295    /// An estimate of the bytes these take.
296    pub approx_bytes: usize,
297}
298
299impl Engine {
300    /// A builder for an engine on `store`, signing as the mesh `host`.
301    pub fn builder(store: Arc<dyn Store + Send + Sync>, host: impl Into<String>) -> EngineBuilder {
302        EngineBuilder {
303            store,
304            host: host.into(),
305            key: None,
306            key_file: None,
307            runtimes: Vec::new(),
308            depth_limit: DEFAULT_DEPTH_LIMIT,
309            fuel: DEFAULT_FUEL,
310            work_limit: None,
311            memo_capacity: DEFAULT_MEMO_CAPACITY,
312            licence: "CC-BY-4.0".into(),
313            summary: None,
314            clock: Arc::new(SystemClock),
315        }
316    }
317
318    /// The value of the cell `cell` denotes, as of `asof` (else `cell.asof`, else now).
319    ///
320    /// The function name resolves as of the asof; with no binding then, the answer is
321    /// [`Answer::NotCovered`]. See the crate documentation for the answers and errors.
322    pub fn get(&self, cell: &CellRef, asof: Option<&str>) -> Result<Answer, EngineError> {
323        let now = self.clock.now();
324        let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
325        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
326        check_no_slice(&cell.args)?;
327        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
328        let Some(fn_hash) = self.store.resolve_name(&fn_name, &a).map_err(|e| StoreError::new("resolve_name", e))?
329        else {
330            return Ok(Answer::NOT_COVERED);
331        };
332        let resolved = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
333        self.answer(&resolved, &a, &now)
334    }
335
336    /// The cell `cell` denotes, its function name resolved as of `asof` (else `cell.asof`,
337    /// else now), as [`get`](Engine::get) resolves it; `None` when the name has no binding
338    /// then (SPEC 5.5 `E_NAME_UNBOUND`: it may be bound later), where `get` answers
339    /// [`Answer::NotCovered`]. With the cell, [`get_cell`](Engine::get_cell) answers as `get`
340    /// would. Malformed requests are the errors `get` gives. Since 0.3.2.
341    pub fn resolve(&self, cell: &CellRef, asof: Option<&str>) -> Result<Option<Cell>, EngineError> {
342        let now;
343        let a = match asof.or(cell.asof.as_deref()) {
344            Some(a) => a,
345            None => {
346                now = self.clock.now();
347                &now
348            }
349        };
350        lexical::check_instant(a, "$.asof").map_err(EngineError::Invalid)?;
351        check_no_slice(&cell.args)?;
352        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
353        let Some(fn_hash) = self.store.resolve_name(&fn_name, a).map_err(|e| StoreError::new("resolve_name", e))?
354        else {
355            return Ok(None);
356        };
357        cell.resolve(&fn_hash).map(Some).map_err(EngineError::Invalid)
358    }
359
360    /// The value of `cell` (its function pinned by `fn_hash`), as of `asof` (else now). The
361    /// form for a reference that already carries the function hash. An unknown function
362    /// hash is [`Answer::NotCovered`].
363    pub fn get_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Answer, EngineError> {
364        let now = self.clock.now();
365        let a = asof.unwrap_or(&now).to_string();
366        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
367        check_no_slice(&cell.args)?;
368        self.answer(cell, &a, &now)
369    }
370
371    /// The answer for a resolved cell as of `a`; `now` is the request's clock reading.
372    fn answer(&self, cell: &Cell, a: &str, now: &str) -> Result<Answer, EngineError> {
373        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else {
374            return Ok(Answer::NOT_COVERED);
375        };
376        check_args(cell, &desc).map_err(EngineError::Invalid)?;
377        let id = cell.id();
378        let store_err = |e: EvalError| match e {
379            EvalError::Store(e) => e.into(),
380            other => EngineError::Runtime { cell_id: id.clone(), message: other.to_string() },
381        };
382        // From the memo (a value or a fault), without waiting for the evaluator.
383        let done = match Req::new(self, a, now).memo_done(&id, a).map_err(store_err)? {
384            Some(d) => d,
385            None if desc.lang == STORED => {
386                let start = self.memo.begin();
387                let mut req = Req::new(self, a, now);
388                match req.stored(cell, &id, a) {
389                    Ok(d) => {
390                        self.memo.end(start, &req.learned);
391                        d
392                    }
393                    Err(e) => {
394                        self.memo.abort(start);
395                        return Err(store_err(e));
396                    }
397                }
398            }
399            None => {
400                let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
401                self.evaluate_cell(cell, desc, a, now, false)?
402            }
403        };
404        Ok(match done {
405            Done::Value(ans) => Answer::Receipt(ans.bytes.to_vec()),
406            Done::Fault(fa) => Answer::NotCovered { fault: Some(fa.fault) },
407            Done::Withdrawn(w) => Answer::Withdrawn { receipt: w.bytes.to_vec(), reason: w.reason.clone() },
408            Done::NotCovered | Done::Unsigned(..) => Answer::NOT_COVERED,
409        })
410    }
411
412    /// Evaluates a computed cell in a request of its own (the caller holds the evaluator):
413    /// memo first, then the store's version validated, else the function; writes what is new
414    /// and keeps the answers in the memo.
415    fn evaluate_cell(
416        &self,
417        cell: &Cell,
418        desc: Arc<FunctionDescriptor>,
419        a: &str,
420        now: &str,
421        unsigned: bool,
422    ) -> Result<Done, EngineError> {
423        let start = self.memo.begin();
424        let mut req = Req::new(self, a, now);
425        let result = (|| {
426            if !unsigned {
427                if let Some(done) =
428                    req.memo_done(&cell.id(), &req.asof()).map_err(|e| crate::eval::engine_error(e, &cell.id()))?
429                {
430                    return Ok(done);
431                }
432            }
433            let done = req.run(cell.clone(), desc, unsigned)?;
434            req.flush()?;
435            Ok(done)
436        })();
437        match &result {
438            Ok(_) => self.memo.end(start, &req.learned),
439            Err(_) => self.memo.abort(start),
440        }
441        result
442    }
443
444    /// A receipt the store returned, parsed (cached by hash).
445    pub(crate) fn parsed(&self, hash: &str, bytes: &[u8]) -> Result<Arc<Parsed>, StoreError> {
446        if let Some(p) = self.receipts.get(hash) {
447            return Ok(p);
448        }
449        let p = Arc::new(parse_stored(hash, bytes)?);
450        self.receipts.insert(hash.to_string(), p.clone());
451        Ok(p)
452    }
453
454    /// The value of `cell` as of `asof`, evaluated (a computed cell's function is run, not
455    /// looked up); for `Resolver::evaluate`.
456    fn evaluate_value(&self, cell: &Cell, asof: &str) -> Result<Option<Evaluation>, EngineError> {
457        if !is_instant(asof) || cell.is_slice() {
458            return Ok(None);
459        }
460        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else { return Ok(None) };
461        if check_args(cell, &desc).is_err() {
462            return Ok(None);
463        }
464        let now = self.clock.now();
465        let done = if desc.lang == STORED {
466            Req::new(self, asof, &now)
467                .stored(cell, &cell.id(), asof)
468                .map_err(|e| EngineError::Runtime { cell_id: cell.id(), message: e.to_string() })?
469        } else {
470            let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
471            // Under a suspended mesh namespace (SPEC 9.9) nothing is signed: the cell is
472            // evaluated as `get` would, so a value needing a new receipt is none, and a
473            // receipt already signed (or one the store validates) gives its value.
474            let suspended = self.store.namespace(&self.host).map_err(|e| StoreError::new("namespace", e))?;
475            if suspended.is_some_and(|n| n.suspended_at.is_some()) {
476                match self.evaluate_cell(cell, desc, asof, &now, false)? {
477                    Done::Value(ans) => {
478                        let lineage: BTreeSet<String> = ans
479                            .inputs
480                            .iter()
481                            .map(|u| match u {
482                                Use::Cell { hash, .. } => hash.clone(),
483                                Use::Slice(s) => s.entry.clone(),
484                            })
485                            .collect();
486                        return Ok(Some(Evaluation::with_lineage(ans.value.clone(), lineage.into_iter().collect())));
487                    }
488                    _ => return Ok(None),
489                }
490            }
491            self.evaluate_cell(cell, desc, asof, &now, true)?
492        };
493        Ok(match done {
494            Done::Value(ans) => Some(Evaluation::new(ans.value.clone())),
495            Done::Unsigned(v, lineage) => Some(Evaluation::with_lineage(v, lineage)),
496            Done::NotCovered | Done::Fault(_) | Done::Withdrawn(_) => None,
497        })
498    }
499
500    /// Whether the function `fn_hash` (descriptor `desc`) is declared asof-dependent by its
501    /// runtime, cached by hash.
502    pub(crate) fn asof_dependent(&self, fn_hash: &str, desc: &FunctionDescriptor) -> bool {
503        if let Some(b) = self.asof_dependent.get(fn_hash) {
504            return b;
505        }
506        let b = self.runtimes.get(&desc.lang).is_some_and(|rt| rt.asof_dependent(desc));
507        self.asof_dependent.insert(fn_hash.to_string(), b);
508        b
509    }
510
511    /// The parsed descriptor of `fn_hash`, cached.
512    pub(crate) fn descriptor_of(&self, fn_hash: &str) -> Result<Option<Arc<FunctionDescriptor>>, EngineError> {
513        if let Some(d) = self.descriptors.get(fn_hash) {
514            return Ok(Some(d));
515        }
516        let Some(bytes) = self.store.descriptor(fn_hash) else { return Ok(None) };
517        let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(EngineError::Invalid)?);
518        self.descriptors.insert(fn_hash.to_string(), d.clone());
519        Ok(Some(d))
520    }
521
522    /// Tells the engine that a stored version of `cell_id` was added: the memoised answers
523    /// that depend on the cell are dropped.
524    ///
525    /// Since 0.3.0 also the answers that read a slice the cell falls into (a late sample, a
526    /// correction, a new member), and nothing else: when some memoised answer read a slice
527    /// over a stored function (or an evaluation is running), the engine reads the cell's
528    /// latest receipt from the store to match it against their patterns. If that read fails,
529    /// every answer that read such a slice is dropped.
530    pub fn stored_version_added(&self, cell_id: &str) {
531        let receipt = if self.memo.wants_receipts() {
532            self.store
533                .latest(cell_id)
534                .ok()
535                .flatten()
536                // A withdrawal is no `Receipt` (it has no value): none is read for it, and
537                // every slice reader is dropped.
538                .filter(|v| !v.withdrawn)
539                .and_then(|v| self.store.receipt(&v.receipt_hash).map(|b| b.into_owned()))
540                .and_then(|b| datumesh_core::Receipt::from_json(&b).ok())
541                .map(Arc::new)
542        } else {
543            None
544        };
545        self.memo.invalidate(cell_id, receipt);
546    }
547
548    /// Drops every memoised answer.
549    pub fn clear_memo(&self) {
550        self.memo.clear();
551    }
552
553    /// Sizes of the memo and of the dirty set.
554    pub fn memo_stats(&self) -> MemoStats {
555        self.memo.stats()
556    }
557}
558
559impl Resolver for Engine {
560    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
561        self.store.descriptor(fn_hash)
562    }
563
564    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
565        self.store.receipt(hash)
566    }
567
568    /// The manifest of a slice entry, from the store (the engine stores the manifest of every
569    /// slice its receipts and evaluations read).
570    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
571        self.store.manifest(entry)
572    }
573
574    /// The value of `cell` as of `asof` by the engine's answering rule (a receipt answers at
575    /// A when its tx and its asof are both at or before A): a stored cell's is looked up; a
576    /// computed cell's function is evaluated (its inputs answered as for `get`, and stored
577    /// when new), never read back from its own receipts. `None` when there is none or the
578    /// evaluation fails (logged with `tracing`, target `datumesh_engine`).
579    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
580        self.evaluation(cell, asof).map(|e| e.value)
581    }
582
583    /// [`evaluate`](Resolver::evaluate)'s value with, for a computed cell, its lineage: the
584    /// `inputs` entries the evaluation read (receipt hashes and slice entries, whose receipts
585    /// and manifests the engine serves), so that a verifier can report `E_INPUT_SUPERSEDED`
586    /// (SPEC 10.1 step 7.6). A stored cell's has none.
587    fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
588        match self.evaluate_value(cell, asof) {
589            Ok(v) => v,
590            Err(e) => {
591                tracing::debug!(target: "datumesh_engine", cell_id = %cell.id(), asof, error = %e, "evaluate failed");
592                None
593            }
594        }
595    }
596}