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