1use 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#[non_exhaustive]
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum ManifestPolicy {
29 #[default]
31 Store,
32 MemberSetOnly,
34 StoreUpTo(usize),
36}
37
38pub const DEFAULT_DEPTH_LIMIT: usize = 10_000;
40pub const DEFAULT_FUEL: u64 = 10_000_000;
42pub const DEFAULT_WORK_FACTOR: u64 = 16;
44pub const DEFAULT_MEMO_CAPACITY: usize = 1_000_000;
46
47#[non_exhaustive]
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub enum Answer {
51 Receipt(Vec<u8>),
54 NotCovered {
61 fault: Option<Fault>,
63 },
64 Withdrawn {
70 receipt: Vec<u8>,
72 reason: String,
74 },
75}
76
77impl Answer {
78 pub const NOT_COVERED: Answer = Answer::NotCovered { fault: None };
80}
81
82pub type SummaryFn = dyn Fn(&Cell) -> String + Send + Sync;
84
85pub 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 pub fn manifests(mut self, policy: ManifestPolicy) -> Self {
107 self.manifests = policy;
108 self
109 }
110
111 pub fn store_past_reads(mut self, store: bool) -> Self {
115 self.store_past_reads = store;
116 self
117 }
118
119 pub fn signing_key(mut self, key: SigningKey) -> Self {
121 self.key = Some(key);
122 self.key_file = None;
123 self
124 }
125
126 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 pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
136 self.runtimes.push(runtime);
137 self
138 }
139
140 pub fn depth_limit(mut self, limit: usize) -> Self {
142 self.depth_limit = limit;
143 self
144 }
145
146 pub fn fuel(mut self, fuel: u64) -> Self {
148 self.fuel = fuel;
149 self
150 }
151
152 pub fn work_limit(mut self, units: u64) -> Self {
157 self.work_limit = Some(units);
158 self
159 }
160
161 pub fn memo_capacity(mut self, entries: usize) -> Self {
164 self.memo_capacity = entries;
165 self
166 }
167
168 pub fn licence(mut self, licence: impl Into<String>) -> Self {
174 self.licence = licence.into();
175 self
176 }
177
178 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 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
187 self.clock = clock;
188 self
189 }
190
191 pub fn accepted_licences(mut self, licences: impl IntoIterator<Item = String>) -> Self {
197 self.accepted = licences.into_iter().collect();
198 self
199 }
200
201 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
260pub 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 pub(crate) accepted: RwLock<BTreeSet<String>>,
277 pub(crate) memo: Memo,
278 pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
280 pub(crate) receipts: Cache<Arc<Parsed>>,
282 pub(crate) asof_dependent: Cache<bool>,
285 pub(crate) evaluator: Mutex<()>,
287}
288
289pub(crate) const STORED: &str = "stored";
291const DESCRIPTOR_CACHE: usize = 10_000;
292const RECEIPT_CACHE: usize = 100_000;
293
294fn 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#[non_exhaustive]
330#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
331pub struct MemoStats {
332 pub entries: usize,
334 pub cells: usize,
336 pub dependent_edges: usize,
338 pub dirty: usize,
340 pub stale: usize,
343 pub slice_patterns: usize,
346 pub approx_bytes: usize,
348}
349
350impl Engine {
351 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 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 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 self.answer(&resolved, &a, &now, asof.is_none() && cell.asof.is_none())
411 }
412
413 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 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 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 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 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 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 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 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 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 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 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 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 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 .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 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 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 fn barrier(&self) -> Result<(), EngineError> {
668 self.store.barrier().map_err(|e| StoreError::new("barrier", e).into())
669 }
670
671 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 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 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 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 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 pub fn resolver_for(&self, asof: &str) -> ReceiptResolver<'_> {
779 ReceiptResolver { eng: self, asof: asof.to_string(), ready: std::sync::OnceLock::new() }
780 }
781
782 pub fn clear_memo(&self) {
784 self.memo.clear();
785 }
786
787 pub fn memo_stats(&self) -> MemoStats {
789 self.memo.stats()
790 }
791}
792
793pub 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 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
864 if let Some(b) = self.store.manifest(entry) {
865 return Some(b);
866 }
867 self.manifest_bytes(entry).ok().flatten().map(Cow::Owned)
869 }
870
871 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
877 self.evaluation(cell, asof).map(|e| e.value)
878 }
879
880 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}