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