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, Error as CoreError, ErrorCode, Evaluation, Fault, FunctionDescriptor, KeyDoc, Manifest,
11    Resolver, Scalar, SigningKey, Slice,
12};
13use datumesh_store::Store;
14
15use crate::cache::{Cache, Parsed};
16use crate::check::{check_args, check_no_slice};
17use crate::clock::{Clock, SystemClock};
18use crate::error::{ConfigError, EngineError, EvalError, StoreError};
19use crate::eval::{exhausted, is_instant, parse_stored, Done, Req, Use};
20use crate::memo::Memo;
21use crate::runtime::{Budget, Runtime};
22use crate::slice::{extent_cells, spec_of, Spec};
23
24/// How the engine stores the manifests of the slices its receipts read (CONTRACT-guard-patch G1).
25/// A member-set row (G2) is written for every slice read, whatever the policy.
26#[non_exhaustive]
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum ManifestPolicy {
29    /// The manifest is stored, as today (datumesh-local keeps this one).
30    #[default]
31    Store,
32    /// No manifest is stored: the member-set row only; the members are rebuilt on demand.
33    MemberSetOnly,
34    /// The manifest is stored when the slice has at most this many members; a longer one is not.
35    StoreUpTo(usize),
36}
37
38/// The default depth limit: frames on the evaluation stack.
39pub const DEFAULT_DEPTH_LIMIT: usize = 10_000;
40/// The default fuel of a request: runtime steps plus input reads.
41pub const DEFAULT_FUEL: u64 = 10_000_000;
42/// The default work limit of a request, as a multiple of its fuel.
43pub const DEFAULT_WORK_FACTOR: u64 = 16;
44/// The default memo capacity, in entries.
45pub const DEFAULT_MEMO_CAPACITY: usize = 1_000_000;
46
47/// The answer to "the value of this cell as of A".
48#[non_exhaustive]
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub enum Answer {
51    /// The receipt that answers, canonical JSON text: for a stored cell the publisher's
52    /// receipt as the store holds it; for a computed cell one signed by the engine.
53    Receipt(Vec<u8>),
54    /// Nothing answers as of A, and no receipt is given.
55    ///
56    /// `fault: None`: the function is unknown then, a stored cell has no version answering
57    /// then, or a computed cell reads such an input. `fault: Some(code)`: the cell is a
58    /// computed cell whose evaluation faulted (SPEC 15.12): it has no value, deterministically
59    /// (the envelope's `fault`, SPEC 5.5). Since 0.3.0 the variant carries `fault`.
60    NotCovered {
61        /// The evaluation fault, if the cell has no value because of one.
62        fault: Option<Fault>,
63    },
64    /// The cell is withdrawn as of A (SPEC 8.1, store 0.6.0): a stored cell whose latest
65    /// version as of A is a withdrawal. It has no value, and no receipt of one: `receipt` is
66    /// the withdrawal's canonical bytes (as `Resolver::receipt` gives them for its hash) and
67    /// `reason` its `withdrawn` text. Since 0.6.0. A formula reading the cell alone has no
68    /// value of it ([`NotCovered`](Answer::NotCovered)), and nothing is stored for the read.
69    Withdrawn {
70        /// The withdrawal's canonical bytes.
71        receipt: Vec<u8>,
72        /// The reason: the withdrawal's `withdrawn` member.
73        reason: String,
74    },
75}
76
77impl Answer {
78    /// `NotCovered` without a fault.
79    pub const NOT_COVERED: Answer = Answer::NotCovered { fault: None };
80}
81
82/// The function computing a computed receipt's `summary`.
83pub type SummaryFn = dyn Fn(&Cell) -> String + Send + Sync;
84
85/// Builds an [`Engine`]: [`Engine::builder`].
86pub struct EngineBuilder {
87    pub(crate) store: Arc<dyn Store + Send + Sync>,
88    pub(crate) host: String,
89    pub(crate) key: Option<SigningKey>,
90    pub(crate) key_file: Option<PathBuf>,
91    pub(crate) runtimes: Vec<Arc<dyn Runtime>>,
92    pub(crate) depth_limit: usize,
93    pub(crate) fuel: u64,
94    pub(crate) work_limit: Option<u64>,
95    pub(crate) memo_capacity: usize,
96    pub(crate) licence: String,
97    pub(crate) summary: Option<Arc<SummaryFn>>,
98    pub(crate) clock: Arc<dyn Clock>,
99    pub(crate) accepted: BTreeSet<String>,
100    pub(crate) manifests: ManifestPolicy,
101    pub(crate) store_past_reads: bool,
102}
103
104impl EngineBuilder {
105    /// How the manifests of the slices read are stored (default [`ManifestPolicy::Store`]).
106    pub fn manifests(mut self, policy: ManifestPolicy) -> Self {
107        self.manifests = policy;
108        self
109    }
110
111    /// Whether a read as of a time before the clock's now stores what it makes: its receipt,
112    /// computed version, member-set row and manifest (default true, as today). Off, such a read
113    /// stores only the slice definitions (once per slice) (CONTRACT-guard-patch G10).
114    pub fn store_past_reads(mut self, store: bool) -> Self {
115        self.store_past_reads = store;
116        self
117    }
118
119    /// The mesh's signing key.
120    pub fn signing_key(mut self, key: SigningKey) -> Self {
121        self.key = Some(key);
122        self.key_file = None;
123        self
124    }
125
126    /// The mesh's signing key, from a file holding its 32-byte seed: the 32 bytes, or 64 hex
127    /// digits (an optional final newline). The only file the engine reads.
128    pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
129        self.key_file = Some(path.into());
130        self.key = None;
131        self
132    }
133
134    /// Adds a runtime, for the language its [`Runtime::lang`] names.
135    pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
136        self.runtimes.push(runtime);
137        self
138    }
139
140    /// The depth limit: frames on the evaluation stack (default 10,000).
141    pub fn depth_limit(mut self, limit: usize) -> Self {
142        self.depth_limit = limit;
143        self
144    }
145
146    /// The fuel of each request: runtime steps plus input reads (default 10,000,000).
147    pub fn fuel(mut self, fuel: u64) -> Self {
148        self.fuel = fuel;
149        self
150    }
151
152    /// The work limit of each request: every evaluation attempt (those discarded by a restart
153    /// included) and the engine's validation reads, in fuel units (default 16 times the
154    /// fuel). It bounds the total cost of a request beyond its normative fuel
155    /// ([`EngineError::WorkExceeded`](crate::EngineError::WorkExceeded)). Since 0.3.0.
156    pub fn work_limit(mut self, units: u64) -> Self {
157        self.work_limit = Some(units);
158        self
159    }
160
161    /// How many answers the memo keeps (default 1,000,000); when full it starts afresh. 0
162    /// turns the memo off: every request then validates through the store.
163    pub fn memo_capacity(mut self, entries: usize) -> Self {
164        self.memo_capacity = entries;
165        self
166    }
167
168    /// The mesh's own licence: an SPDX identifier or an https URL (default `CC-BY-4.0`).
169    ///
170    /// Since 0.4.1 (spec-0.4.3, SPEC 8.5) it is the `licence` of computed receipts with no
171    /// input receipt (a constant, or only empty slices); a receipt with inputs inherits its
172    /// licence from theirs (see the crate documentation, "Licence inheritance").
173    pub fn licence(mut self, licence: impl Into<String>) -> Self {
174        self.licence = licence.into();
175        self
176    }
177
178    /// The `summary` of a computed receipt, from its cell. The default says which function
179    /// the mesh computed: `"<namespace>/<function> computed by <mesh host>."`.
180    pub fn summary(mut self, f: impl Fn(&Cell) -> String + Send + Sync + 'static) -> Self {
181        self.summary = Some(Arc::new(f));
182        self
183    }
184
185    /// The clock (default [`SystemClock`]).
186    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
187        self.clock = clock;
188        self
189    }
190
191    /// The restricted licences this engine's operator has accepted (engine 0.6.1, E1). Used only
192    /// on an unrooted host (`*.invalid`): when SPEC 8.5 refuses a computation over restricted
193    /// input licences and every one of them is accepted, the result is computed (see the crate
194    /// documentation, "Local acceptance"). On a rooted host the set is ignored. Replaces the
195    /// set given before; [`Engine::set_accepted_licences`] changes it later.
196    pub fn accepted_licences(mut self, licences: impl IntoIterator<Item = String>) -> Self {
197        self.accepted = licences.into_iter().collect();
198        self
199    }
200
201    /// Checks the configuration and builds the engine.
202    pub fn build(self) -> Result<Engine, ConfigError> {
203        lexical::check_dns_name(&self.host, "$.host").map_err(ConfigError::Host)?;
204        let key = match (self.key, &self.key_file) {
205            (Some(k), _) => k,
206            (None, Some(path)) => read_seed(path)?,
207            (None, None) => return Err(ConfigError::NoSigningKey),
208        };
209        lexical::check_licence(&self.licence, "$.licence").map_err(ConfigError::Licence)?;
210        let mut runtimes: HashMap<String, Arc<dyn Runtime>> = HashMap::new();
211        for rt in self.runtimes {
212            let lang = rt.lang().to_string();
213            if lang == STORED {
214                return Err(ConfigError::Runtime("stored is answered by the engine, not a runtime".into()));
215            }
216            if runtimes.insert(lang.clone(), rt).is_some() {
217                return Err(ConfigError::Runtime(format!("two runtimes for {lang}")));
218            }
219        }
220        let published = match self.store.namespace(&self.host) {
221            Ok(Some(ns)) => KeyDoc::from_json(&self.host, &ns.keydoc)
222                .ok()
223                .and_then(|doc| doc.key(key.key_id()).map(|k| k.public == key.public_key()))
224                .unwrap_or(false),
225            Ok(None) => false,
226            Err(e) => return Err(ConfigError::Store(StoreError::new("namespace", e))),
227        };
228        if !published {
229            return Err(ConfigError::KeyNotPublished { host: self.host, key_id: key.key_id().to_string() });
230        }
231        Ok(Engine {
232            store: self.store,
233            host: self.host,
234            key,
235            runtimes,
236            depth_limit: self.depth_limit,
237            fuel: self.fuel,
238            work_limit: self.work_limit.unwrap_or(self.fuel.saturating_mul(DEFAULT_WORK_FACTOR)),
239            licence: self.licence,
240            summary: self.summary,
241            clock: self.clock,
242            manifests: self.manifests,
243            store_past_reads: self.store_past_reads,
244            accepted: RwLock::new(self.accepted),
245            memo: Memo::new(self.memo_capacity),
246            descriptors: Cache::new(DESCRIPTOR_CACHE),
247            receipts: Cache::new(RECEIPT_CACHE),
248            asof_dependent: Cache::new(DESCRIPTOR_CACHE),
249            evaluator: Mutex::new(()),
250        })
251    }
252}
253
254impl fmt::Debug for EngineBuilder {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        f.debug_struct("EngineBuilder").field("host", &self.host).finish_non_exhaustive()
257    }
258}
259
260/// The engine: answers the value of a cell as of a time. See the crate documentation.
261pub struct Engine {
262    pub(crate) store: Arc<dyn Store + Send + Sync>,
263    pub(crate) host: String,
264    pub(crate) key: SigningKey,
265    pub(crate) runtimes: HashMap<String, Arc<dyn Runtime>>,
266    pub(crate) depth_limit: usize,
267    pub(crate) fuel: u64,
268    pub(crate) work_limit: u64,
269    pub(crate) licence: String,
270    pub(crate) summary: Option<Arc<SummaryFn>>,
271    pub(crate) clock: Arc<dyn Clock>,
272    pub(crate) manifests: ManifestPolicy,
273    pub(crate) store_past_reads: bool,
274    /// The accepted restricted licences (E1), read by every licence decision and replaced by
275    /// [`Engine::set_accepted_licences`].
276    pub(crate) accepted: RwLock<BTreeSet<String>>,
277    pub(crate) memo: Memo,
278    /// Parsed descriptors by function hash (immutable: content-addressed).
279    pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
280    /// Parsed receipts by hash (immutable: content-addressed).
281    pub(crate) receipts: Cache<Arc<Parsed>>,
282    /// Whether a function is asof-dependent, by function hash: a pure function of the
283    /// descriptor, which a runtime may take long to derive (it is asked on every frame).
284    pub(crate) asof_dependent: Cache<bool>,
285    /// Evaluations run one at a time (single-flight); answers from the memo do not wait.
286    pub(crate) evaluator: Mutex<()>,
287}
288
289/// The language of stored functions, answered by the engine itself.
290pub(crate) const STORED: &str = "stored";
291const DESCRIPTOR_CACHE: usize = 10_000;
292const RECEIPT_CACHE: usize = 100_000;
293
294/// The seed in a key file: 32 bytes, or 64 lowercase hex digits and an optional newline.
295fn read_seed(path: &std::path::Path) -> Result<SigningKey, ConfigError> {
296    let bytes = std::fs::read(path).map_err(|e| ConfigError::KeyFile(format!("{}: {e}", path.display())))?;
297    if let Ok(seed) = <[u8; 32]>::try_from(bytes.as_slice()) {
298        return Ok(SigningKey::from_seed(&seed));
299    }
300    let text = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
301    let hex = |c: u8| match c {
302        b'0'..=b'9' => Some(c - b'0'),
303        b'a'..=b'f' => Some(c - b'a' + 10),
304        _ => None,
305    };
306    if text.len() == 64 {
307        let mut seed = [0u8; 32];
308        let mut ok = true;
309        for (i, pair) in text.chunks(2).enumerate() {
310            match (hex(pair[0]), hex(pair[1])) {
311                (Some(h), Some(l)) => seed[i] = h << 4 | l,
312                _ => ok = false,
313            }
314        }
315        if ok {
316            return Ok(SigningKey::from_seed(&seed));
317        }
318    }
319    Err(ConfigError::KeyFile(format!("{}: not a seed (32 bytes, or 64 lowercase hex digits)", path.display())))
320}
321
322impl fmt::Debug for Engine {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        f.debug_struct("Engine").finish_non_exhaustive()
325    }
326}
327
328/// Sizes of the memo and of the dirty set ([`Engine::memo_stats`]).
329#[non_exhaustive]
330#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
331pub struct MemoStats {
332    /// Answers held.
333    pub entries: usize,
334    /// Cells with at least one answer held.
335    pub cells: usize,
336    /// Edges of the in-memory dependents index (input cell to reading cell).
337    pub dependent_edges: usize,
338    /// Cells marked dirty and kept to refuse answers of evaluations already running.
339    pub dirty: usize,
340    /// Answers dropped because a stored version they rested on changed, kept to be rechecked
341    /// from memory (early cutoff without store queries for the unchanged part of a graph).
342    pub stale: usize,
343    /// Slices over stored functions read by answers held (matched by pattern against new
344    /// stored versions). Since 0.3.0.
345    pub slice_patterns: usize,
346    /// An estimate of the bytes these take.
347    pub approx_bytes: usize,
348}
349
350impl Engine {
351    /// A builder for an engine on `store`, signing as the mesh `host`.
352    pub fn builder(store: Arc<dyn Store + Send + Sync>, host: impl Into<String>) -> EngineBuilder {
353        EngineBuilder {
354            store,
355            host: host.into(),
356            key: None,
357            key_file: None,
358            runtimes: Vec::new(),
359            depth_limit: DEFAULT_DEPTH_LIMIT,
360            fuel: DEFAULT_FUEL,
361            work_limit: None,
362            memo_capacity: DEFAULT_MEMO_CAPACITY,
363            licence: "CC-BY-4.0".into(),
364            summary: None,
365            clock: Arc::new(SystemClock),
366            accepted: BTreeSet::new(),
367            manifests: ManifestPolicy::Store,
368            store_past_reads: true,
369        }
370    }
371
372    /// Replaces the set of accepted restricted licences (engine 0.6.1, E1), for the next
373    /// request: a long-running `serve` or `mcp` picks up an acceptance made by another process
374    /// this way. Safe to call from any thread. It waits for a running evaluation to finish, then
375    /// drops the memo (its answers were judged under the old set), so a memoised answer whose
376    /// licence the new set no longer gives is refused, not answered (see
377    /// [`EngineBuilder::accepted_licences`]).
378    pub fn set_accepted_licences(&self, licences: BTreeSet<String>) {
379        let _evaluating = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
380        let mut accepted = self.accepted.write().unwrap_or_else(|p| p.into_inner());
381        if *accepted != licences {
382            *accepted = licences;
383            self.memo.clear();
384        }
385    }
386
387    /// The value of the cell `cell` denotes, as of `asof` (else `cell.asof`, else now).
388    ///
389    /// The function name resolves as of the asof; with no binding then, the answer is
390    /// [`Answer::NotCovered`]. See the crate documentation for the answers and errors.
391    ///
392    /// Past or current (CONTRACT-guard-patch G10): a read with no asof is current; a named asof
393    /// earlier than the clock at the call's start is a past read, which stores nothing but slice
394    /// definitions (when `store_past_reads` is off). For a request fixed before it is evaluated, see
395    /// [`get_cell_current`](Engine::get_cell_current).
396    pub fn get(&self, cell: &CellRef, asof: Option<&str>) -> Result<Answer, EngineError> {
397        let now = self.clock.now();
398        let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
399        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
400        check_no_slice(&cell.args)?;
401        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
402        self.barrier()?;
403        let Some(fn_hash) = self.store.resolve_name(&fn_name, &a).map_err(|e| StoreError::new("resolve_name", e))?
404        else {
405            return Ok(Answer::NOT_COVERED);
406        };
407        let resolved = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
408        // Current only when no asof is named (decided 27 Nov, B1): a named asof, past or future, stores
409        // nothing but the slice definition.
410        self.answer(&resolved, &a, &now, asof.is_none() && cell.asof.is_none())
411    }
412
413    /// The cell `cell` denotes, its function name resolved as of `asof` (else `cell.asof`,
414    /// else now), as [`get`](Engine::get) resolves it; `None` when the name has no binding
415    /// then (SPEC 5.5 `E_NAME_UNBOUND`: it may be bound later), where `get` answers
416    /// [`Answer::NotCovered`]. With the cell, [`get_cell`](Engine::get_cell) answers as `get`
417    /// would. Malformed requests are the errors `get` gives. Since 0.3.2.
418    pub fn resolve(&self, cell: &CellRef, asof: Option<&str>) -> Result<Option<Cell>, EngineError> {
419        let now;
420        let a = match asof.or(cell.asof.as_deref()) {
421            Some(a) => a,
422            None => {
423                now = self.clock.now();
424                &now
425            }
426        };
427        lexical::check_instant(a, "$.asof").map_err(EngineError::Invalid)?;
428        check_no_slice(&cell.args)?;
429        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
430        let Some(fn_hash) = self.store.resolve_name(&fn_name, a).map_err(|e| StoreError::new("resolve_name", e))?
431        else {
432            return Ok(None);
433        };
434        cell.resolve(&fn_hash).map(Some).map_err(EngineError::Invalid)
435    }
436
437    /// The value of `cell` (its function pinned by `fn_hash`), as of `asof` (else now). The
438    /// form for a reference that already carries the function hash. An unknown function
439    /// hash is [`Answer::NotCovered`].
440    pub fn get_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Answer, EngineError> {
441        let now = self.clock.now();
442        let a = asof.unwrap_or(&now).to_string();
443        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
444        check_no_slice(&cell.args)?;
445        self.barrier()?;
446        self.answer(cell, &a, &now, asof.is_none())
447    }
448
449    /// The value of `cell` as of `arrival`, a current read whatever the clock reads when it is
450    /// evaluated: it stores as a current read does (its version and its member-set row, as of the
451    /// arrival), though the clock has moved on (CONTRACT-guard-patch G10; the mesh's requests pin
452    /// their arrival). `get_cell` with a named asof before the clock is a past read instead.
453    pub fn get_cell_current(&self, cell: &Cell, arrival: &str) -> Result<Answer, EngineError> {
454        let now = self.clock.now();
455        lexical::check_instant(arrival, "$.arrival").map_err(EngineError::Invalid)?;
456        check_no_slice(&cell.args)?;
457        self.barrier()?;
458        self.answer(cell, arrival, &now, true)
459    }
460
461    /// The answer for a resolved cell as of `a`; `now` is the request's clock reading.
462    fn answer(&self, cell: &Cell, a: &str, now: &str, current: bool) -> Result<Answer, EngineError> {
463        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else {
464            return Ok(Answer::NOT_COVERED);
465        };
466        check_args(cell, &desc).map_err(EngineError::Invalid)?;
467        let id = cell.id();
468        let store_err = |e: EvalError| match e {
469            EvalError::Store(e) => e.into(),
470            other => EngineError::Runtime { cell_id: id.clone(), message: other.to_string() },
471        };
472        // From the memo (a value or a fault), without waiting for the evaluator.
473        let done = match Req::new(self, a, now).with_current(current).memo_done(&id, a).map_err(store_err)? {
474            Some(d) => d,
475            None if desc.lang == STORED => {
476                let start = self.memo.begin();
477                let mut req = Req::new(self, a, now).with_current(current);
478                match req.stored(cell, &id, a) {
479                    Ok(d) => {
480                        self.memo.end(start, &req.learned);
481                        d
482                    }
483                    Err(e) => {
484                        self.memo.abort(start);
485                        return Err(store_err(e));
486                    }
487                }
488            }
489            None => {
490                let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
491                self.evaluate_cell(cell, desc, a, now, false, current)?
492            }
493        };
494        Ok(match done {
495            Done::Value(ans) => Answer::Receipt(ans.bytes.to_vec()),
496            Done::Fault(fa) => Answer::NotCovered { fault: Some(fa.fault) },
497            Done::Withdrawn(w) => Answer::Withdrawn { receipt: w.bytes.to_vec(), reason: w.reason.clone() },
498            Done::NotCovered | Done::Unsigned(..) => Answer::NOT_COVERED,
499        })
500    }
501
502    /// Evaluates a computed cell in a request of its own (the caller holds the evaluator):
503    /// memo first, then the store's version validated, else the function; writes what is new
504    /// and keeps the answers in the memo.
505    fn evaluate_cell(
506        &self,
507        cell: &Cell,
508        desc: Arc<FunctionDescriptor>,
509        a: &str,
510        now: &str,
511        unsigned: bool,
512        current: bool,
513    ) -> Result<Done, EngineError> {
514        let start = self.memo.begin();
515        let mut req = Req::new(self, a, now).with_current(current);
516        let result = (|| {
517            if !unsigned {
518                if let Some(done) =
519                    req.memo_done(&cell.id(), &req.asof()).map_err(|e| crate::eval::engine_error(e, &cell.id()))?
520                {
521                    return Ok(done);
522                }
523            }
524            let done = req.run(cell.clone(), desc, unsigned)?;
525            req.flush()?;
526            Ok(done)
527        })();
528        // An answer a past read made and did not store is not memoised: a later read must make
529        // and store its own (CONTRACT-guard-patch G10).
530        match &result {
531            Ok(_) if !req.stores_nothing() => self.memo.end(start, &req.learned),
532            _ => self.memo.abort(start),
533        }
534        result
535    }
536
537    /// A receipt the store returned, parsed (cached by hash).
538    pub(crate) fn parsed(&self, hash: &str, bytes: &[u8]) -> Result<Arc<Parsed>, StoreError> {
539        if let Some(p) = self.receipts.get(hash) {
540            return Ok(p);
541        }
542        let p = Arc::new(parse_stored(hash, bytes)?);
543        self.receipts.insert(hash.to_string(), p.clone());
544        Ok(p)
545    }
546
547    /// The value of `cell` as of `asof`, evaluated (a computed cell's function is run, not
548    /// looked up); for `Resolver::evaluate`.
549    fn evaluate_value(&self, cell: &Cell, asof: &str) -> Result<Option<Evaluation>, EngineError> {
550        if !is_instant(asof) || cell.is_slice() {
551            return Ok(None);
552        }
553        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else { return Ok(None) };
554        if check_args(cell, &desc).is_err() {
555            return Ok(None);
556        }
557        let now = self.clock.now();
558        let done = if desc.lang == STORED {
559            Req::new(self, asof, &now)
560                .stored(cell, &cell.id(), asof)
561                .map_err(|e| EngineError::Runtime { cell_id: cell.id(), message: e.to_string() })?
562        } else {
563            let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
564            // Under a suspended mesh namespace (SPEC 9.9) nothing is signed: the cell is
565            // evaluated as `get` would, so a value needing a new receipt is none, and a
566            // receipt already signed (or one the store validates) gives its value.
567            let suspended = self.store.namespace(&self.host).map_err(|e| StoreError::new("namespace", e))?;
568            if suspended.is_some_and(|n| n.suspended_at.is_some()) {
569                match self.evaluate_cell(cell, desc, asof, &now, false, false)? {
570                    Done::Value(ans) => {
571                        let lineage: BTreeSet<String> = ans
572                            .inputs
573                            .iter()
574                            .map(|u| match u {
575                                Use::Cell { hash, .. } => hash.clone(),
576                                Use::Slice(s) => s.entry.clone(),
577                            })
578                            .collect();
579                        return Ok(Some(Evaluation::with_lineage(ans.value.clone(), lineage.into_iter().collect())));
580                    }
581                    _ => return Ok(None),
582                }
583            }
584            self.evaluate_cell(cell, desc, asof, &now, true, false)?
585        };
586        Ok(match done {
587            Done::Value(ans) => Some(Evaluation::new(ans.value.clone())),
588            Done::Unsigned(v, lineage) => Some(Evaluation::with_lineage(v, lineage)),
589            Done::NotCovered | Done::Fault(_) | Done::Withdrawn(_) => None,
590        })
591    }
592
593    /// Whether the function `fn_hash` (descriptor `desc`) is declared asof-dependent by its
594    /// runtime, cached by hash.
595    pub(crate) fn asof_dependent(&self, fn_hash: &str, desc: &FunctionDescriptor) -> bool {
596        if let Some(b) = self.asof_dependent.get(fn_hash) {
597            return b;
598        }
599        let b = self.runtimes.get(&desc.lang).is_some_and(|rt| rt.asof_dependent(desc));
600        self.asof_dependent.insert(fn_hash.to_string(), b);
601        b
602    }
603
604    /// The parsed descriptor of `fn_hash`, cached.
605    pub(crate) fn descriptor_of(&self, fn_hash: &str) -> Result<Option<Arc<FunctionDescriptor>>, EngineError> {
606        if let Some(d) = self.descriptors.get(fn_hash) {
607            return Ok(Some(d));
608        }
609        let Some(bytes) = self.store.descriptor(fn_hash) else { return Ok(None) };
610        let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(EngineError::Invalid)?);
611        self.descriptors.insert(fn_hash.to_string(), d.clone());
612        Ok(Some(d))
613    }
614
615    /// Tells the engine that a stored version of `cell_id` was added: the memoised answers
616    /// that depend on the cell are dropped.
617    ///
618    /// Since 0.3.0 also the answers that read a slice the cell falls into (a late sample, a
619    /// correction, a new member), and nothing else: when some memoised answer read a slice
620    /// over a stored function (or an evaluation is running), the engine reads the cell's
621    /// latest receipt from the store to match it against their patterns. If that read fails,
622    /// every answer that read such a slice is dropped.
623    pub fn stored_version_added(&self, cell_id: &str) {
624        let receipt = if self.memo.wants_receipts() {
625            self.store
626                .latest(cell_id)
627                .ok()
628                .flatten()
629                // A withdrawal is no `Receipt` (it has no value): none is read for it, and
630                // every slice reader is dropped.
631                .filter(|v| !v.withdrawn)
632                .and_then(|v| self.store.receipt(&v.receipt_hash).map(|b| b.into_owned()))
633                .and_then(|b| datumesh_core::Receipt::from_json(&b).ok())
634                .map(Arc::new)
635        } else {
636            None
637        };
638        self.memo.invalidate(cell_id, receipt);
639    }
640
641    /// The manifest of the slice entry `entry` as of `asof` (CONTRACT-guard-patch G5, G10): the held
642    /// bytes when a manifest is stored, else the members rebuilt from the slice's definition as of
643    /// `asof` (the canonical bytes a stored manifest holds). Nothing is stored. `Ok(None)` when no
644    /// manifest is held and the mesh has no definition of the slice (or the entry is malformed).
645    /// Errors: `BudgetExceeded` over the fuel; `Invalid` when the members do not hash to the
646    /// entry's members hash, or a member cannot be listed (a false `asof` is refused, not guessed).
647    pub fn manifest_asof(&self, entry: &str, asof: &str) -> Result<Option<Vec<u8>>, EngineError> {
648        self.barrier()?;
649        self.manifest_asof_inner(entry, asof, None)
650    }
651
652    /// [`manifest_asof`](Engine::manifest_asof) with a deadline (CONTRACT-guard-patch, the time budget of
653    /// a request, `DATUMESH_BUDGET_MS`): `BudgetExceeded` once `deadline` has passed, checked before and
654    /// after the listing and while listing or hashing the members. Nothing is stored.
655    pub fn manifest_asof_until(
656        &self,
657        entry: &str,
658        asof: &str,
659        deadline: std::time::Instant,
660    ) -> Result<Option<Vec<u8>>, EngineError> {
661        self.barrier()?;
662        self.manifest_asof_inner(entry, asof, Some(deadline))
663    }
664
665    /// The store's barrier (CONTRACT-guard-patch review item 2): called once per request, before its
666    /// first store read, so that a version recorded at or before the request's asof is seen.
667    fn barrier(&self) -> Result<(), EngineError> {
668        self.store.barrier().map_err(|e| StoreError::new("barrier", e).into())
669    }
670
671    /// [`manifest_asof`](Engine::manifest_asof) within a request that has passed the barrier.
672    fn manifest_asof_inner(
673        &self,
674        entry: &str,
675        asof: &str,
676        deadline: Option<std::time::Instant>,
677    ) -> Result<Option<Vec<u8>>, EngineError> {
678        let late = || deadline.is_some_and(|d| std::time::Instant::now() >= d);
679        if late() {
680            return Err(EngineError::BudgetExceeded { fuel: self.fuel });
681        }
682        if let Some(b) = self.store.manifest(entry) {
683            return Ok(Some(b.into_owned()));
684        }
685        let Some((slice_id, members_hash)) = entry.strip_prefix("slice:").and_then(|r| r.split_once(':')) else {
686            return Ok(None);
687        };
688        // The slice's definition, kept once per slice; else the member-set row's copy of it (R3).
689        let slice = match self.store.slice_definition(slice_id).map_err(|e| StoreError::new("slice_definition", e))? {
690            Some(s) => s,
691            None => match self.store.member_set(entry).map_err(|e| StoreError::new("member_set", e))? {
692                Some(row) => Slice::from_json(&row.slice).map_err(EngineError::Invalid)?,
693                None => return Ok(None),
694            },
695        };
696        let Some(desc) = self.descriptor_of(slice.fn_hash())? else { return Ok(None) };
697        let mut budget = Budget::with_work(self.fuel, self.work_limit);
698        let mut hashes: Vec<String> = Vec::new();
699        // Over the fuel is refused as the listing goes: only receipt hashes are read, bounded at
700        // fuel + 1 (review item 5); no member's value is loaded.
701        let over = || EngineError::BudgetExceeded { fuel: self.fuel };
702        if desc.lang == STORED {
703            let limit = usize::try_from(self.fuel.saturating_add(1)).unwrap_or(usize::MAX);
704            // Under the deadline the listing runs within the time left (decided 27 Nov, B6); a store
705            // timeout is the budget's, and so is a deadline already passed.
706            let listed = match deadline {
707                None => self.store.slice_member_hashes(&slice, asof, limit),
708                Some(d) => {
709                    let left = d.saturating_duration_since(std::time::Instant::now());
710                    if left.is_zero() {
711                        return Err(over());
712                    }
713                    self.store.slice_member_hashes_within(&slice, asof, limit, left)
714                }
715            };
716            let found = listed.map_err(|e| match e {
717                datumesh_store::Error::Timeout(_) => over(),
718                other => StoreError::new("slice_member_hashes", other).into(),
719            })?;
720            if found.len() as u64 > self.fuel || late() {
721                return Err(over());
722            }
723            hashes.extend(found);
724        } else {
725            let not_listed = || {
726                EngineError::Invalid(CoreError::new(
727                    ErrorCode::Slice,
728                    "$",
729                    "a member of the slice has no computed version as of the asof",
730                ))
731            };
732            let Some(Spec::Cells { pattern }) = spec_of(&slice) else { return Err(not_listed()) };
733            let cells =
734                extent_cells(&slice.function_name(), slice.fn_hash(), &desc, &pattern).map_err(EngineError::Invalid)?;
735            for cell in cells {
736                let v = self.store.computed_asof(&cell.id(), asof).map_err(|e| StoreError::new("computed_asof", e))?;
737                hashes.push(v.ok_or_else(not_listed)?.receipt_hash);
738                if hashes.len() as u64 > self.fuel || late() {
739                    return Err(over());
740                }
741            }
742        }
743        if budget.charge(1 + hashes.len() as u64).is_err() {
744            return Err(exhausted(&budget));
745        }
746        if late() {
747            return Err(over());
748        }
749        hashes.sort();
750        hashes.dedup();
751        let m = Manifest::new(slice, hashes).map_err(EngineError::Invalid)?;
752        if m.members_hash() != members_hash || m.entry() != entry {
753            return Err(EngineError::Invalid(CoreError::new(
754                ErrorCode::Slice,
755                "$",
756                "the members do not hash to the entry's members hash",
757            )));
758        }
759        Ok(Some(m.canonical()))
760    }
761
762    /// The manifest of `entry` as the engine serves it: the held bytes, else the rebuild as of
763    /// the member-set row's `asof` (G6). `Ok(None)` when neither is there.
764    pub(crate) fn manifest_bytes(&self, entry: &str) -> Result<Option<Vec<u8>>, EngineError> {
765        if let Some(b) = self.store.manifest(entry) {
766            return Ok(Some(b.into_owned()));
767        }
768        let Some(row) = self.store.member_set(entry).map_err(|e| StoreError::new("member_set", e))? else {
769            return Ok(None);
770        };
771        self.manifest_asof_inner(entry, &row.asof, None)
772    }
773
774    /// The resolver for one receipt being verified, whose `asof` is the receipt's (R2): the public
775    /// [`Resolver`] of the engine, with a manifest held, else the rebuild from the member-set row,
776    /// else the rebuild as of this `asof` (so a receipt with no row, such as a past read's, verifies).
777    /// Nothing is stored. The engine's own `Resolver` keeps its row-only answer.
778    pub fn resolver_for(&self, asof: &str) -> ReceiptResolver<'_> {
779        ReceiptResolver { eng: self, asof: asof.to_string(), ready: std::sync::OnceLock::new() }
780    }
781
782    /// Drops every memoised answer.
783    pub fn clear_memo(&self) {
784        self.memo.clear();
785    }
786
787    /// Sizes of the memo and of the dirty set.
788    pub fn memo_stats(&self) -> MemoStats {
789        self.memo.stats()
790    }
791}
792
793/// The resolver of one receipt, from [`Engine::resolver_for`]: the engine's, with the manifest as of
794/// the receipt's `asof` when none is held and there is no member-set row. Its first call passes the
795/// store's barrier (review item 2), so the reads that follow see every version recorded at or before
796/// the asof; a barrier that fails answers nothing.
797pub struct ReceiptResolver<'e> {
798    eng: &'e Engine,
799    asof: String,
800    ready: std::sync::OnceLock<bool>,
801}
802
803impl ReceiptResolver<'_> {
804    fn ready(&self) -> bool {
805        *self.ready.get_or_init(|| self.eng.barrier().is_ok())
806    }
807}
808
809impl Resolver for ReceiptResolver<'_> {
810    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
811        if !self.ready() {
812            return None;
813        }
814        self.eng.descriptor(fn_hash)
815    }
816
817    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
818        if !self.ready() {
819            return None;
820        }
821        self.eng.receipt(hash)
822    }
823
824    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
825        if !self.ready() {
826            return None;
827        }
828        if let Some(b) = self.eng.store.manifest(entry) {
829            return Some(b);
830        }
831        if let Ok(Some(b)) = self.eng.manifest_bytes(entry) {
832            return Some(Cow::Owned(b));
833        }
834        self.eng.manifest_asof_inner(entry, &self.asof, None).ok().flatten().map(Cow::Owned)
835    }
836
837    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
838        if !self.ready() {
839            return None;
840        }
841        self.eng.evaluate(cell, asof)
842    }
843
844    fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
845        if !self.ready() {
846            return None;
847        }
848        self.eng.evaluation(cell, asof)
849    }
850}
851
852impl Resolver for Engine {
853    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
854        self.store.descriptor(fn_hash)
855    }
856
857    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
858        self.store.receipt(hash)
859    }
860
861    /// The manifest of a slice entry, from the store (the engine stores the manifest of every
862    /// slice its receipts and evaluations read).
863    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
864        if let Some(b) = self.store.manifest(entry) {
865            return Some(b);
866        }
867        // With none held, the list rebuilt as of the member-set row's asof (G6).
868        self.manifest_bytes(entry).ok().flatten().map(Cow::Owned)
869    }
870
871    /// The value of `cell` as of `asof` by the engine's answering rule (a receipt answers at
872    /// A when its tx and its asof are both at or before A): a stored cell's is looked up; a
873    /// computed cell's function is evaluated (its inputs answered as for `get`, and stored
874    /// when new), never read back from its own receipts. `None` when there is none or the
875    /// evaluation fails (logged with `tracing`, target `datumesh_engine`).
876    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
877        self.evaluation(cell, asof).map(|e| e.value)
878    }
879
880    /// [`evaluate`](Resolver::evaluate)'s value with, for a computed cell, its lineage: the
881    /// `inputs` entries the evaluation read (receipt hashes and slice entries, whose receipts
882    /// and manifests the engine serves), so that a verifier can report `E_INPUT_SUPERSEDED`
883    /// (SPEC 10.1 step 7.6). A stored cell's has none.
884    fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
885        match self.evaluate_value(cell, asof) {
886            Ok(v) => v,
887            Err(e) => {
888                tracing::debug!(target: "datumesh_engine", cell_id = %cell.id(), asof, error = %e, "evaluate failed");
889                None
890            }
891        }
892    }
893}