datumesh-engine 0.7.0

The Datumesh engine: the value of a cell as of a time, from stored receipts or by evaluating functions; memoised, and signed for computed cells.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! [`Engine`], [`EngineBuilder`] and [`Answer`].

use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};

use datumesh_core::{
    lexical, Cell, CellRef, Error as CoreError, ErrorCode, Evaluation, Fault, FunctionDescriptor, KeyDoc, Manifest,
    Resolver, Scalar, SigningKey, Slice,
};
use datumesh_store::Store;

use crate::cache::{Cache, Parsed};
use crate::check::{check_args, check_no_slice};
use crate::clock::{Clock, SystemClock};
use crate::error::{ConfigError, EngineError, EvalError, StoreError};
use crate::eval::{exhausted, is_instant, parse_stored, Done, Req, Use};
use crate::memo::Memo;
use crate::runtime::{Budget, Runtime};
use crate::slice::{extent_cells, spec_of, Spec};

/// How the engine stores the manifests of the slices its receipts read (CONTRACT-guard-patch G1).
/// A member-set row (G2) is written for every slice read, whatever the policy.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ManifestPolicy {
    /// The manifest is stored, as today (datumesh-local keeps this one).
    #[default]
    Store,
    /// No manifest is stored: the member-set row only; the members are rebuilt on demand.
    MemberSetOnly,
    /// The manifest is stored when the slice has at most this many members; a longer one is not.
    StoreUpTo(usize),
}

/// The default depth limit: frames on the evaluation stack.
pub const DEFAULT_DEPTH_LIMIT: usize = 10_000;
/// The default fuel of a request: runtime steps plus input reads.
pub const DEFAULT_FUEL: u64 = 10_000_000;
/// The default work limit of a request, as a multiple of its fuel.
pub const DEFAULT_WORK_FACTOR: u64 = 16;
/// The default memo capacity, in entries.
pub const DEFAULT_MEMO_CAPACITY: usize = 1_000_000;

/// The answer to "the value of this cell as of A".
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Answer {
    /// The receipt that answers, canonical JSON text: for a stored cell the publisher's
    /// receipt as the store holds it; for a computed cell one signed by the engine.
    Receipt(Vec<u8>),
    /// Nothing answers as of A, and no receipt is given.
    ///
    /// `fault: None`: the function is unknown then, a stored cell has no version answering
    /// then, or a computed cell reads such an input. `fault: Some(code)`: the cell is a
    /// computed cell whose evaluation faulted (SPEC 15.12): it has no value, deterministically
    /// (the envelope's `fault`, SPEC 5.5). Since 0.3.0 the variant carries `fault`.
    NotCovered {
        /// The evaluation fault, if the cell has no value because of one.
        fault: Option<Fault>,
    },
    /// The cell is withdrawn as of A (SPEC 8.1, store 0.6.0): a stored cell whose latest
    /// version as of A is a withdrawal. It has no value, and no receipt of one: `receipt` is
    /// the withdrawal's canonical bytes (as `Resolver::receipt` gives them for its hash) and
    /// `reason` its `withdrawn` text. Since 0.6.0. A formula reading the cell alone has no
    /// value of it ([`NotCovered`](Answer::NotCovered)), and nothing is stored for the read.
    Withdrawn {
        /// The withdrawal's canonical bytes.
        receipt: Vec<u8>,
        /// The reason: the withdrawal's `withdrawn` member.
        reason: String,
    },
}

impl Answer {
    /// `NotCovered` without a fault.
    pub const NOT_COVERED: Answer = Answer::NotCovered { fault: None };
}

/// The function computing a computed receipt's `summary`.
pub type SummaryFn = dyn Fn(&Cell) -> String + Send + Sync;

/// Builds an [`Engine`]: [`Engine::builder`].
pub struct EngineBuilder {
    pub(crate) store: Arc<dyn Store + Send + Sync>,
    pub(crate) host: String,
    pub(crate) key: Option<SigningKey>,
    pub(crate) key_file: Option<PathBuf>,
    pub(crate) runtimes: Vec<Arc<dyn Runtime>>,
    pub(crate) depth_limit: usize,
    pub(crate) fuel: u64,
    pub(crate) work_limit: Option<u64>,
    pub(crate) memo_capacity: usize,
    pub(crate) licence: String,
    pub(crate) summary: Option<Arc<SummaryFn>>,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) accepted: BTreeSet<String>,
    pub(crate) manifests: ManifestPolicy,
    pub(crate) store_past_reads: bool,
}

impl EngineBuilder {
    /// How the manifests of the slices read are stored (default [`ManifestPolicy::Store`]).
    pub fn manifests(mut self, policy: ManifestPolicy) -> Self {
        self.manifests = policy;
        self
    }

    /// Whether a read as of a time before the clock's now stores what it makes: its receipt,
    /// computed version, member-set row and manifest (default true, as today). Off, such a read
    /// stores only the slice definitions (once per slice) (CONTRACT-guard-patch G10).
    pub fn store_past_reads(mut self, store: bool) -> Self {
        self.store_past_reads = store;
        self
    }

    /// The mesh's signing key.
    pub fn signing_key(mut self, key: SigningKey) -> Self {
        self.key = Some(key);
        self.key_file = None;
        self
    }

    /// The mesh's signing key, from a file holding its 32-byte seed: the 32 bytes, or 64 hex
    /// digits (an optional final newline). The only file the engine reads.
    pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.key_file = Some(path.into());
        self.key = None;
        self
    }

    /// Adds a runtime, for the language its [`Runtime::lang`] names.
    pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
        self.runtimes.push(runtime);
        self
    }

    /// The depth limit: frames on the evaluation stack (default 10,000).
    pub fn depth_limit(mut self, limit: usize) -> Self {
        self.depth_limit = limit;
        self
    }

    /// The fuel of each request: runtime steps plus input reads (default 10,000,000).
    pub fn fuel(mut self, fuel: u64) -> Self {
        self.fuel = fuel;
        self
    }

    /// The work limit of each request: every evaluation attempt (those discarded by a restart
    /// included) and the engine's validation reads, in fuel units (default 16 times the
    /// fuel). It bounds the total cost of a request beyond its normative fuel
    /// ([`EngineError::WorkExceeded`](crate::EngineError::WorkExceeded)). Since 0.3.0.
    pub fn work_limit(mut self, units: u64) -> Self {
        self.work_limit = Some(units);
        self
    }

    /// How many answers the memo keeps (default 1,000,000); when full it starts afresh. 0
    /// turns the memo off: every request then validates through the store.
    pub fn memo_capacity(mut self, entries: usize) -> Self {
        self.memo_capacity = entries;
        self
    }

    /// The mesh's own licence: an SPDX identifier or an https URL (default `CC-BY-4.0`).
    ///
    /// Since 0.4.1 (spec-0.4.3, SPEC 8.5) it is the `licence` of computed receipts with no
    /// input receipt (a constant, or only empty slices); a receipt with inputs inherits its
    /// licence from theirs (see the crate documentation, "Licence inheritance").
    pub fn licence(mut self, licence: impl Into<String>) -> Self {
        self.licence = licence.into();
        self
    }

    /// The `summary` of a computed receipt, from its cell. The default says which function
    /// the mesh computed: `"<namespace>/<function> computed by <mesh host>."`.
    pub fn summary(mut self, f: impl Fn(&Cell) -> String + Send + Sync + 'static) -> Self {
        self.summary = Some(Arc::new(f));
        self
    }

    /// The clock (default [`SystemClock`]).
    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
        self.clock = clock;
        self
    }

    /// The restricted licences this engine's operator has accepted (engine 0.6.1, E1). Used only
    /// on an unrooted host (`*.invalid`): when SPEC 8.5 refuses a computation over restricted
    /// input licences and every one of them is accepted, the result is computed (see the crate
    /// documentation, "Local acceptance"). On a rooted host the set is ignored. Replaces the
    /// set given before; [`Engine::set_accepted_licences`] changes it later.
    pub fn accepted_licences(mut self, licences: impl IntoIterator<Item = String>) -> Self {
        self.accepted = licences.into_iter().collect();
        self
    }

    /// Checks the configuration and builds the engine.
    pub fn build(self) -> Result<Engine, ConfigError> {
        lexical::check_dns_name(&self.host, "$.host").map_err(ConfigError::Host)?;
        let key = match (self.key, &self.key_file) {
            (Some(k), _) => k,
            (None, Some(path)) => read_seed(path)?,
            (None, None) => return Err(ConfigError::NoSigningKey),
        };
        lexical::check_licence(&self.licence, "$.licence").map_err(ConfigError::Licence)?;
        let mut runtimes: HashMap<String, Arc<dyn Runtime>> = HashMap::new();
        for rt in self.runtimes {
            let lang = rt.lang().to_string();
            if lang == STORED {
                return Err(ConfigError::Runtime("stored is answered by the engine, not a runtime".into()));
            }
            if runtimes.insert(lang.clone(), rt).is_some() {
                return Err(ConfigError::Runtime(format!("two runtimes for {lang}")));
            }
        }
        let published = match self.store.namespace(&self.host) {
            Ok(Some(ns)) => KeyDoc::from_json(&self.host, &ns.keydoc)
                .ok()
                .and_then(|doc| doc.key(key.key_id()).map(|k| k.public == key.public_key()))
                .unwrap_or(false),
            Ok(None) => false,
            Err(e) => return Err(ConfigError::Store(StoreError::new("namespace", e))),
        };
        if !published {
            return Err(ConfigError::KeyNotPublished { host: self.host, key_id: key.key_id().to_string() });
        }
        Ok(Engine {
            store: self.store,
            host: self.host,
            key,
            runtimes,
            depth_limit: self.depth_limit,
            fuel: self.fuel,
            work_limit: self.work_limit.unwrap_or(self.fuel.saturating_mul(DEFAULT_WORK_FACTOR)),
            licence: self.licence,
            summary: self.summary,
            clock: self.clock,
            manifests: self.manifests,
            store_past_reads: self.store_past_reads,
            accepted: RwLock::new(self.accepted),
            memo: Memo::new(self.memo_capacity),
            descriptors: Cache::new(DESCRIPTOR_CACHE),
            receipts: Cache::new(RECEIPT_CACHE),
            asof_dependent: Cache::new(DESCRIPTOR_CACHE),
            evaluator: Mutex::new(()),
        })
    }
}

impl fmt::Debug for EngineBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EngineBuilder").field("host", &self.host).finish_non_exhaustive()
    }
}

/// The engine: answers the value of a cell as of a time. See the crate documentation.
pub struct Engine {
    pub(crate) store: Arc<dyn Store + Send + Sync>,
    pub(crate) host: String,
    pub(crate) key: SigningKey,
    pub(crate) runtimes: HashMap<String, Arc<dyn Runtime>>,
    pub(crate) depth_limit: usize,
    pub(crate) fuel: u64,
    pub(crate) work_limit: u64,
    pub(crate) licence: String,
    pub(crate) summary: Option<Arc<SummaryFn>>,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) manifests: ManifestPolicy,
    pub(crate) store_past_reads: bool,
    /// The accepted restricted licences (E1), read by every licence decision and replaced by
    /// [`Engine::set_accepted_licences`].
    pub(crate) accepted: RwLock<BTreeSet<String>>,
    pub(crate) memo: Memo,
    /// Parsed descriptors by function hash (immutable: content-addressed).
    pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
    /// Parsed receipts by hash (immutable: content-addressed).
    pub(crate) receipts: Cache<Arc<Parsed>>,
    /// Whether a function is asof-dependent, by function hash: a pure function of the
    /// descriptor, which a runtime may take long to derive (it is asked on every frame).
    pub(crate) asof_dependent: Cache<bool>,
    /// Evaluations run one at a time (single-flight); answers from the memo do not wait.
    pub(crate) evaluator: Mutex<()>,
}

/// The language of stored functions, answered by the engine itself.
pub(crate) const STORED: &str = "stored";
const DESCRIPTOR_CACHE: usize = 10_000;
const RECEIPT_CACHE: usize = 100_000;

/// The seed in a key file: 32 bytes, or 64 lowercase hex digits and an optional newline.
fn read_seed(path: &std::path::Path) -> Result<SigningKey, ConfigError> {
    let bytes = std::fs::read(path).map_err(|e| ConfigError::KeyFile(format!("{}: {e}", path.display())))?;
    if let Ok(seed) = <[u8; 32]>::try_from(bytes.as_slice()) {
        return Ok(SigningKey::from_seed(&seed));
    }
    let text = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
    let hex = |c: u8| match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        _ => None,
    };
    if text.len() == 64 {
        let mut seed = [0u8; 32];
        let mut ok = true;
        for (i, pair) in text.chunks(2).enumerate() {
            match (hex(pair[0]), hex(pair[1])) {
                (Some(h), Some(l)) => seed[i] = h << 4 | l,
                _ => ok = false,
            }
        }
        if ok {
            return Ok(SigningKey::from_seed(&seed));
        }
    }
    Err(ConfigError::KeyFile(format!("{}: not a seed (32 bytes, or 64 lowercase hex digits)", path.display())))
}

impl fmt::Debug for Engine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Engine").finish_non_exhaustive()
    }
}

/// Sizes of the memo and of the dirty set ([`Engine::memo_stats`]).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MemoStats {
    /// Answers held.
    pub entries: usize,
    /// Cells with at least one answer held.
    pub cells: usize,
    /// Edges of the in-memory dependents index (input cell to reading cell).
    pub dependent_edges: usize,
    /// Cells marked dirty and kept to refuse answers of evaluations already running.
    pub dirty: usize,
    /// Answers dropped because a stored version they rested on changed, kept to be rechecked
    /// from memory (early cutoff without store queries for the unchanged part of a graph).
    pub stale: usize,
    /// Slices over stored functions read by answers held (matched by pattern against new
    /// stored versions). Since 0.3.0.
    pub slice_patterns: usize,
    /// An estimate of the bytes these take.
    pub approx_bytes: usize,
}

impl Engine {
    /// A builder for an engine on `store`, signing as the mesh `host`.
    pub fn builder(store: Arc<dyn Store + Send + Sync>, host: impl Into<String>) -> EngineBuilder {
        EngineBuilder {
            store,
            host: host.into(),
            key: None,
            key_file: None,
            runtimes: Vec::new(),
            depth_limit: DEFAULT_DEPTH_LIMIT,
            fuel: DEFAULT_FUEL,
            work_limit: None,
            memo_capacity: DEFAULT_MEMO_CAPACITY,
            licence: "CC-BY-4.0".into(),
            summary: None,
            clock: Arc::new(SystemClock),
            accepted: BTreeSet::new(),
            manifests: ManifestPolicy::Store,
            store_past_reads: true,
        }
    }

    /// Replaces the set of accepted restricted licences (engine 0.6.1, E1), for the next
    /// request: a long-running `serve` or `mcp` picks up an acceptance made by another process
    /// this way. Safe to call from any thread. It waits for a running evaluation to finish, then
    /// drops the memo (its answers were judged under the old set), so a memoised answer whose
    /// licence the new set no longer gives is refused, not answered (see
    /// [`EngineBuilder::accepted_licences`]).
    pub fn set_accepted_licences(&self, licences: BTreeSet<String>) {
        let _evaluating = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
        let mut accepted = self.accepted.write().unwrap_or_else(|p| p.into_inner());
        if *accepted != licences {
            *accepted = licences;
            self.memo.clear();
        }
    }

    /// The value of the cell `cell` denotes, as of `asof` (else `cell.asof`, else now).
    ///
    /// The function name resolves as of the asof; with no binding then, the answer is
    /// [`Answer::NotCovered`]. See the crate documentation for the answers and errors.
    ///
    /// Past or current (CONTRACT-guard-patch G10): a read with no asof is current; a named asof
    /// earlier than the clock at the call's start is a past read, which stores nothing but slice
    /// definitions (when `store_past_reads` is off). For a request fixed before it is evaluated, see
    /// [`get_cell_current`](Engine::get_cell_current).
    pub fn get(&self, cell: &CellRef, asof: Option<&str>) -> Result<Answer, EngineError> {
        let now = self.clock.now();
        let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
        check_no_slice(&cell.args)?;
        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
        self.barrier()?;
        let Some(fn_hash) = self.store.resolve_name(&fn_name, &a).map_err(|e| StoreError::new("resolve_name", e))?
        else {
            return Ok(Answer::NOT_COVERED);
        };
        let resolved = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
        // Current only when no asof is named (decided 27 Nov, B1): a named asof, past or future, stores
        // nothing but the slice definition.
        self.answer(&resolved, &a, &now, asof.is_none() && cell.asof.is_none())
    }

    /// The cell `cell` denotes, its function name resolved as of `asof` (else `cell.asof`,
    /// else now), as [`get`](Engine::get) resolves it; `None` when the name has no binding
    /// then (SPEC 5.5 `E_NAME_UNBOUND`: it may be bound later), where `get` answers
    /// [`Answer::NotCovered`]. With the cell, [`get_cell`](Engine::get_cell) answers as `get`
    /// would. Malformed requests are the errors `get` gives. Since 0.3.2.
    pub fn resolve(&self, cell: &CellRef, asof: Option<&str>) -> Result<Option<Cell>, EngineError> {
        let now;
        let a = match asof.or(cell.asof.as_deref()) {
            Some(a) => a,
            None => {
                now = self.clock.now();
                &now
            }
        };
        lexical::check_instant(a, "$.asof").map_err(EngineError::Invalid)?;
        check_no_slice(&cell.args)?;
        let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
        let Some(fn_hash) = self.store.resolve_name(&fn_name, a).map_err(|e| StoreError::new("resolve_name", e))?
        else {
            return Ok(None);
        };
        cell.resolve(&fn_hash).map(Some).map_err(EngineError::Invalid)
    }

    /// The value of `cell` (its function pinned by `fn_hash`), as of `asof` (else now). The
    /// form for a reference that already carries the function hash. An unknown function
    /// hash is [`Answer::NotCovered`].
    pub fn get_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Answer, EngineError> {
        let now = self.clock.now();
        let a = asof.unwrap_or(&now).to_string();
        lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
        check_no_slice(&cell.args)?;
        self.barrier()?;
        self.answer(cell, &a, &now, asof.is_none())
    }

    /// The value of `cell` as of `arrival`, a current read whatever the clock reads when it is
    /// evaluated: it stores as a current read does (its version and its member-set row, as of the
    /// arrival), though the clock has moved on (CONTRACT-guard-patch G10; the mesh's requests pin
    /// their arrival). `get_cell` with a named asof before the clock is a past read instead.
    pub fn get_cell_current(&self, cell: &Cell, arrival: &str) -> Result<Answer, EngineError> {
        let now = self.clock.now();
        lexical::check_instant(arrival, "$.arrival").map_err(EngineError::Invalid)?;
        check_no_slice(&cell.args)?;
        self.barrier()?;
        self.answer(cell, arrival, &now, true)
    }

    /// The answer for a resolved cell as of `a`; `now` is the request's clock reading.
    fn answer(&self, cell: &Cell, a: &str, now: &str, current: bool) -> Result<Answer, EngineError> {
        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else {
            return Ok(Answer::NOT_COVERED);
        };
        check_args(cell, &desc).map_err(EngineError::Invalid)?;
        let id = cell.id();
        let store_err = |e: EvalError| match e {
            EvalError::Store(e) => e.into(),
            other => EngineError::Runtime { cell_id: id.clone(), message: other.to_string() },
        };
        // From the memo (a value or a fault), without waiting for the evaluator.
        let done = match Req::new(self, a, now).with_current(current).memo_done(&id, a).map_err(store_err)? {
            Some(d) => d,
            None if desc.lang == STORED => {
                let start = self.memo.begin();
                let mut req = Req::new(self, a, now).with_current(current);
                match req.stored(cell, &id, a) {
                    Ok(d) => {
                        self.memo.end(start, &req.learned);
                        d
                    }
                    Err(e) => {
                        self.memo.abort(start);
                        return Err(store_err(e));
                    }
                }
            }
            None => {
                let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
                self.evaluate_cell(cell, desc, a, now, false, current)?
            }
        };
        Ok(match done {
            Done::Value(ans) => Answer::Receipt(ans.bytes.to_vec()),
            Done::Fault(fa) => Answer::NotCovered { fault: Some(fa.fault) },
            Done::Withdrawn(w) => Answer::Withdrawn { receipt: w.bytes.to_vec(), reason: w.reason.clone() },
            Done::NotCovered | Done::Unsigned(..) => Answer::NOT_COVERED,
        })
    }

    /// Evaluates a computed cell in a request of its own (the caller holds the evaluator):
    /// memo first, then the store's version validated, else the function; writes what is new
    /// and keeps the answers in the memo.
    fn evaluate_cell(
        &self,
        cell: &Cell,
        desc: Arc<FunctionDescriptor>,
        a: &str,
        now: &str,
        unsigned: bool,
        current: bool,
    ) -> Result<Done, EngineError> {
        let start = self.memo.begin();
        let mut req = Req::new(self, a, now).with_current(current);
        let result = (|| {
            if !unsigned {
                if let Some(done) =
                    req.memo_done(&cell.id(), &req.asof()).map_err(|e| crate::eval::engine_error(e, &cell.id()))?
                {
                    return Ok(done);
                }
            }
            let done = req.run(cell.clone(), desc, unsigned)?;
            req.flush()?;
            Ok(done)
        })();
        // An answer a past read made and did not store is not memoised: a later read must make
        // and store its own (CONTRACT-guard-patch G10).
        match &result {
            Ok(_) if !req.stores_nothing() => self.memo.end(start, &req.learned),
            _ => self.memo.abort(start),
        }
        result
    }

    /// A receipt the store returned, parsed (cached by hash).
    pub(crate) fn parsed(&self, hash: &str, bytes: &[u8]) -> Result<Arc<Parsed>, StoreError> {
        if let Some(p) = self.receipts.get(hash) {
            return Ok(p);
        }
        let p = Arc::new(parse_stored(hash, bytes)?);
        self.receipts.insert(hash.to_string(), p.clone());
        Ok(p)
    }

    /// The value of `cell` as of `asof`, evaluated (a computed cell's function is run, not
    /// looked up); for `Resolver::evaluate`.
    fn evaluate_value(&self, cell: &Cell, asof: &str) -> Result<Option<Evaluation>, EngineError> {
        if !is_instant(asof) || cell.is_slice() {
            return Ok(None);
        }
        let Some(desc) = self.descriptor_of(&cell.fn_hash)? else { return Ok(None) };
        if check_args(cell, &desc).is_err() {
            return Ok(None);
        }
        let now = self.clock.now();
        let done = if desc.lang == STORED {
            Req::new(self, asof, &now)
                .stored(cell, &cell.id(), asof)
                .map_err(|e| EngineError::Runtime { cell_id: cell.id(), message: e.to_string() })?
        } else {
            let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
            // Under a suspended mesh namespace (SPEC 9.9) nothing is signed: the cell is
            // evaluated as `get` would, so a value needing a new receipt is none, and a
            // receipt already signed (or one the store validates) gives its value.
            let suspended = self.store.namespace(&self.host).map_err(|e| StoreError::new("namespace", e))?;
            if suspended.is_some_and(|n| n.suspended_at.is_some()) {
                match self.evaluate_cell(cell, desc, asof, &now, false, false)? {
                    Done::Value(ans) => {
                        let lineage: BTreeSet<String> = ans
                            .inputs
                            .iter()
                            .map(|u| match u {
                                Use::Cell { hash, .. } => hash.clone(),
                                Use::Slice(s) => s.entry.clone(),
                            })
                            .collect();
                        return Ok(Some(Evaluation::with_lineage(ans.value.clone(), lineage.into_iter().collect())));
                    }
                    _ => return Ok(None),
                }
            }
            self.evaluate_cell(cell, desc, asof, &now, true, false)?
        };
        Ok(match done {
            Done::Value(ans) => Some(Evaluation::new(ans.value.clone())),
            Done::Unsigned(v, lineage) => Some(Evaluation::with_lineage(v, lineage)),
            Done::NotCovered | Done::Fault(_) | Done::Withdrawn(_) => None,
        })
    }

    /// Whether the function `fn_hash` (descriptor `desc`) is declared asof-dependent by its
    /// runtime, cached by hash.
    pub(crate) fn asof_dependent(&self, fn_hash: &str, desc: &FunctionDescriptor) -> bool {
        if let Some(b) = self.asof_dependent.get(fn_hash) {
            return b;
        }
        let b = self.runtimes.get(&desc.lang).is_some_and(|rt| rt.asof_dependent(desc));
        self.asof_dependent.insert(fn_hash.to_string(), b);
        b
    }

    /// The parsed descriptor of `fn_hash`, cached.
    pub(crate) fn descriptor_of(&self, fn_hash: &str) -> Result<Option<Arc<FunctionDescriptor>>, EngineError> {
        if let Some(d) = self.descriptors.get(fn_hash) {
            return Ok(Some(d));
        }
        let Some(bytes) = self.store.descriptor(fn_hash) else { return Ok(None) };
        let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(EngineError::Invalid)?);
        self.descriptors.insert(fn_hash.to_string(), d.clone());
        Ok(Some(d))
    }

    /// Tells the engine that a stored version of `cell_id` was added: the memoised answers
    /// that depend on the cell are dropped.
    ///
    /// Since 0.3.0 also the answers that read a slice the cell falls into (a late sample, a
    /// correction, a new member), and nothing else: when some memoised answer read a slice
    /// over a stored function (or an evaluation is running), the engine reads the cell's
    /// latest receipt from the store to match it against their patterns. If that read fails,
    /// every answer that read such a slice is dropped.
    pub fn stored_version_added(&self, cell_id: &str) {
        let receipt = if self.memo.wants_receipts() {
            self.store
                .latest(cell_id)
                .ok()
                .flatten()
                // A withdrawal is no `Receipt` (it has no value): none is read for it, and
                // every slice reader is dropped.
                .filter(|v| !v.withdrawn)
                .and_then(|v| self.store.receipt(&v.receipt_hash).map(|b| b.into_owned()))
                .and_then(|b| datumesh_core::Receipt::from_json(&b).ok())
                .map(Arc::new)
        } else {
            None
        };
        self.memo.invalidate(cell_id, receipt);
    }

    /// The manifest of the slice entry `entry` as of `asof` (CONTRACT-guard-patch G5, G10): the held
    /// bytes when a manifest is stored, else the members rebuilt from the slice's definition as of
    /// `asof` (the canonical bytes a stored manifest holds). Nothing is stored. `Ok(None)` when no
    /// manifest is held and the mesh has no definition of the slice (or the entry is malformed).
    /// Errors: `BudgetExceeded` over the fuel; `Invalid` when the members do not hash to the
    /// entry's members hash, or a member cannot be listed (a false `asof` is refused, not guessed).
    pub fn manifest_asof(&self, entry: &str, asof: &str) -> Result<Option<Vec<u8>>, EngineError> {
        self.barrier()?;
        self.manifest_asof_inner(entry, asof, None)
    }

    /// [`manifest_asof`](Engine::manifest_asof) with a deadline (CONTRACT-guard-patch, the time budget of
    /// a request, `DATUMESH_BUDGET_MS`): `BudgetExceeded` once `deadline` has passed, checked before and
    /// after the listing and while listing or hashing the members. Nothing is stored.
    pub fn manifest_asof_until(
        &self,
        entry: &str,
        asof: &str,
        deadline: std::time::Instant,
    ) -> Result<Option<Vec<u8>>, EngineError> {
        self.barrier()?;
        self.manifest_asof_inner(entry, asof, Some(deadline))
    }

    /// The store's barrier (CONTRACT-guard-patch review item 2): called once per request, before its
    /// first store read, so that a version recorded at or before the request's asof is seen.
    fn barrier(&self) -> Result<(), EngineError> {
        self.store.barrier().map_err(|e| StoreError::new("barrier", e).into())
    }

    /// [`manifest_asof`](Engine::manifest_asof) within a request that has passed the barrier.
    fn manifest_asof_inner(
        &self,
        entry: &str,
        asof: &str,
        deadline: Option<std::time::Instant>,
    ) -> Result<Option<Vec<u8>>, EngineError> {
        let late = || deadline.is_some_and(|d| std::time::Instant::now() >= d);
        if late() {
            return Err(EngineError::BudgetExceeded { fuel: self.fuel });
        }
        if let Some(b) = self.store.manifest(entry) {
            return Ok(Some(b.into_owned()));
        }
        let Some((slice_id, members_hash)) = entry.strip_prefix("slice:").and_then(|r| r.split_once(':')) else {
            return Ok(None);
        };
        // The slice's definition, kept once per slice; else the member-set row's copy of it (R3).
        let slice = match self.store.slice_definition(slice_id).map_err(|e| StoreError::new("slice_definition", e))? {
            Some(s) => s,
            None => match self.store.member_set(entry).map_err(|e| StoreError::new("member_set", e))? {
                Some(row) => Slice::from_json(&row.slice).map_err(EngineError::Invalid)?,
                None => return Ok(None),
            },
        };
        let Some(desc) = self.descriptor_of(slice.fn_hash())? else { return Ok(None) };
        let mut budget = Budget::with_work(self.fuel, self.work_limit);
        let mut hashes: Vec<String> = Vec::new();
        // Over the fuel is refused as the listing goes: only receipt hashes are read, bounded at
        // fuel + 1 (review item 5); no member's value is loaded.
        let over = || EngineError::BudgetExceeded { fuel: self.fuel };
        if desc.lang == STORED {
            let limit = usize::try_from(self.fuel.saturating_add(1)).unwrap_or(usize::MAX);
            // Under the deadline the listing runs within the time left (decided 27 Nov, B6); a store
            // timeout is the budget's, and so is a deadline already passed.
            let listed = match deadline {
                None => self.store.slice_member_hashes(&slice, asof, limit),
                Some(d) => {
                    let left = d.saturating_duration_since(std::time::Instant::now());
                    if left.is_zero() {
                        return Err(over());
                    }
                    self.store.slice_member_hashes_within(&slice, asof, limit, left)
                }
            };
            let found = listed.map_err(|e| match e {
                datumesh_store::Error::Timeout(_) => over(),
                other => StoreError::new("slice_member_hashes", other).into(),
            })?;
            if found.len() as u64 > self.fuel || late() {
                return Err(over());
            }
            hashes.extend(found);
        } else {
            let not_listed = || {
                EngineError::Invalid(CoreError::new(
                    ErrorCode::Slice,
                    "$",
                    "a member of the slice has no computed version as of the asof",
                ))
            };
            let Some(Spec::Cells { pattern }) = spec_of(&slice) else { return Err(not_listed()) };
            let cells =
                extent_cells(&slice.function_name(), slice.fn_hash(), &desc, &pattern).map_err(EngineError::Invalid)?;
            for cell in cells {
                let v = self.store.computed_asof(&cell.id(), asof).map_err(|e| StoreError::new("computed_asof", e))?;
                hashes.push(v.ok_or_else(not_listed)?.receipt_hash);
                if hashes.len() as u64 > self.fuel || late() {
                    return Err(over());
                }
            }
        }
        if budget.charge(1 + hashes.len() as u64).is_err() {
            return Err(exhausted(&budget));
        }
        if late() {
            return Err(over());
        }
        hashes.sort();
        hashes.dedup();
        let m = Manifest::new(slice, hashes).map_err(EngineError::Invalid)?;
        if m.members_hash() != members_hash || m.entry() != entry {
            return Err(EngineError::Invalid(CoreError::new(
                ErrorCode::Slice,
                "$",
                "the members do not hash to the entry's members hash",
            )));
        }
        Ok(Some(m.canonical()))
    }

    /// The manifest of `entry` as the engine serves it: the held bytes, else the rebuild as of
    /// the member-set row's `asof` (G6). `Ok(None)` when neither is there.
    pub(crate) fn manifest_bytes(&self, entry: &str) -> Result<Option<Vec<u8>>, EngineError> {
        if let Some(b) = self.store.manifest(entry) {
            return Ok(Some(b.into_owned()));
        }
        let Some(row) = self.store.member_set(entry).map_err(|e| StoreError::new("member_set", e))? else {
            return Ok(None);
        };
        self.manifest_asof_inner(entry, &row.asof, None)
    }

    /// The resolver for one receipt being verified, whose `asof` is the receipt's (R2): the public
    /// [`Resolver`] of the engine, with a manifest held, else the rebuild from the member-set row,
    /// else the rebuild as of this `asof` (so a receipt with no row, such as a past read's, verifies).
    /// Nothing is stored. The engine's own `Resolver` keeps its row-only answer.
    pub fn resolver_for(&self, asof: &str) -> ReceiptResolver<'_> {
        ReceiptResolver { eng: self, asof: asof.to_string(), ready: std::sync::OnceLock::new() }
    }

    /// Drops every memoised answer.
    pub fn clear_memo(&self) {
        self.memo.clear();
    }

    /// Sizes of the memo and of the dirty set.
    pub fn memo_stats(&self) -> MemoStats {
        self.memo.stats()
    }
}

/// The resolver of one receipt, from [`Engine::resolver_for`]: the engine's, with the manifest as of
/// the receipt's `asof` when none is held and there is no member-set row. Its first call passes the
/// store's barrier (review item 2), so the reads that follow see every version recorded at or before
/// the asof; a barrier that fails answers nothing.
pub struct ReceiptResolver<'e> {
    eng: &'e Engine,
    asof: String,
    ready: std::sync::OnceLock<bool>,
}

impl ReceiptResolver<'_> {
    fn ready(&self) -> bool {
        *self.ready.get_or_init(|| self.eng.barrier().is_ok())
    }
}

impl Resolver for ReceiptResolver<'_> {
    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
        if !self.ready() {
            return None;
        }
        self.eng.descriptor(fn_hash)
    }

    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
        if !self.ready() {
            return None;
        }
        self.eng.receipt(hash)
    }

    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
        if !self.ready() {
            return None;
        }
        if let Some(b) = self.eng.store.manifest(entry) {
            return Some(b);
        }
        if let Ok(Some(b)) = self.eng.manifest_bytes(entry) {
            return Some(Cow::Owned(b));
        }
        self.eng.manifest_asof_inner(entry, &self.asof, None).ok().flatten().map(Cow::Owned)
    }

    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
        if !self.ready() {
            return None;
        }
        self.eng.evaluate(cell, asof)
    }

    fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
        if !self.ready() {
            return None;
        }
        self.eng.evaluation(cell, asof)
    }
}

impl Resolver for Engine {
    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
        self.store.descriptor(fn_hash)
    }

    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
        self.store.receipt(hash)
    }

    /// The manifest of a slice entry, from the store (the engine stores the manifest of every
    /// slice its receipts and evaluations read).
    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
        if let Some(b) = self.store.manifest(entry) {
            return Some(b);
        }
        // With none held, the list rebuilt as of the member-set row's asof (G6).
        self.manifest_bytes(entry).ok().flatten().map(Cow::Owned)
    }

    /// The value of `cell` as of `asof` by the engine's answering rule (a receipt answers at
    /// A when its tx and its asof are both at or before A): a stored cell's is looked up; a
    /// computed cell's function is evaluated (its inputs answered as for `get`, and stored
    /// when new), never read back from its own receipts. `None` when there is none or the
    /// evaluation fails (logged with `tracing`, target `datumesh_engine`).
    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
        self.evaluation(cell, asof).map(|e| e.value)
    }

    /// [`evaluate`](Resolver::evaluate)'s value with, for a computed cell, its lineage: the
    /// `inputs` entries the evaluation read (receipt hashes and slice entries, whose receipts
    /// and manifests the engine serves), so that a verifier can report `E_INPUT_SUPERSEDED`
    /// (SPEC 10.1 step 7.6). A stored cell's has none.
    fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
        match self.evaluate_value(cell, asof) {
            Ok(v) => v,
            Err(e) => {
                tracing::debug!(target: "datumesh_engine", cell_id = %cell.id(), asof, error = %e, "evaluate failed");
                None
            }
        }
    }
}