datumesh-engine 0.4.2

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
//! The memo: answers known to hold over an interval of asofs, dropped when a stored version
//! they depend on is added (the dirty set).
//!
//! An answer for cell C holds for every asof in `[lo, hi)` given the store as it was read
//! and its function names resolving as recorded (checked on every use, see
//! [`Ans::names`]). Adding a stored version can change that, so
//! [`Memo::invalidate`] drops the answers of the cell and of every cell that read it,
//! transitively, through the memo's own index of who read what (the cell-level dependents
//! of the answers it holds: a dirty mark can only matter to an answer it holds).
//!
//! An evaluation that was running when an invalidation happened may have read the old
//! version: every evaluation registers the revision it started at ([`Memo::begin`]), every
//! invalidation bumps the revision and marks the cells it reached dirty at it, and
//! [`Memo::end`] refuses an answer whose cell or whose inputs were marked dirty after the
//! evaluation began (and marks it dirty in turn, for the answers that read it). Answers are
//! inserted inputs first, so the refusal propagates. Marks are kept only while an evaluation
//! that began before them is running.
//!
//! Slices over stored functions are not in that index (their members are many, and a new
//! member is in no answer yet): each answer that read one registers the slice object, and an
//! invalidation with the new version's receipt drops the readers of every registered slice
//! that contains it (`Slice::contains`); without the receipt, every such reader. Versions
//! added while evaluations run are kept with their revision, and [`Memo::end`] refuses an
//! answer one of whose slices contains one added after the evaluation began. Members of
//! slices over computed functions are in the index like single inputs.
//!
//! Correctness does not depend on the memo: a miss validates the store's computed version
//! (or computes one). The memo only saves that work, so losing it (a restart) is harmless.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex, MutexGuard};

use datumesh_core::{Receipt, Slice};

use crate::engine::MemoStats;
use crate::eval::{Ans, FaultAns, Use};

/// What a request learned and the memo may keep: a value, or a fault (SPEC 15.12, memoised as
/// a value is). Learned inputs come before the answers reading them.
#[derive(Clone, Debug)]
pub(crate) enum Entry {
    Value(Arc<Ans>),
    Fault(Arc<FaultAns>),
}

impl Entry {
    fn id(&self) -> &str {
        match self {
            Entry::Value(a) => &a.id,
            Entry::Fault(f) => &f.id,
        }
    }

    fn memo(&self) -> bool {
        match self {
            Entry::Value(a) => a.memo,
            Entry::Fault(f) => f.memo,
        }
    }

    fn deps(&self) -> Vec<&String> {
        match self {
            Entry::Value(a) => a.deps().collect(),
            Entry::Fault(f) => f.deps().collect(),
        }
    }

    fn patterns(&self) -> Vec<&Arc<Slice>> {
        match self {
            Entry::Value(a) => a.patterns().collect(),
            Entry::Fault(f) => f.patterns().collect(),
        }
    }
}

pub(crate) struct Memo {
    capacity: usize,
    state: Mutex<State>,
}

/// A slice and the cells whose answers read it.
type Readers = (Arc<Slice>, HashSet<String>);

#[derive(Default)]
struct State {
    rev: u64,
    entries: HashMap<String, Vec<Arc<Ans>>>,
    /// Faults (SPEC 15.12) held, by cell id: counted with the answers in `count`.
    faults: HashMap<String, Vec<Arc<FaultAns>>>,
    count: usize,
    /// Answers dropped by an invalidation, kept as candidates to recheck (from memory) before
    /// the store's version is looked at.
    stale: HashMap<String, Vec<Arc<Ans>>>,
    stale_count: usize,
    /// Input cell id to the cells whose answers read it.
    readers: HashMap<String, HashSet<String>>,
    edges: usize,
    /// Cell id to the revision at which it was last marked dirty.
    dirty: HashMap<String, u64>,
    /// Revisions at which running evaluations began, with how many began at each.
    active: BTreeMap<u64, usize>,
    /// The slices over stored functions that held answers read, by function hash and slice
    /// id, with the cells whose answers read them: a new stored version of a cell the slice
    /// contains drops them.
    patterns: HashMap<String, HashMap<String, Readers>>,
    pattern_count: usize,
    /// Stored versions added while evaluations ran, with the revision: their receipt (none
    /// when it could not be read), to refuse answers of slices they fall into.
    added: Vec<(u64, Option<Arc<Receipt>>)>,
}

impl Memo {
    pub(crate) fn new(capacity: usize) -> Memo {
        Memo { capacity, state: Mutex::new(State::default()) }
    }

    pub(crate) fn enabled(&self) -> bool {
        self.capacity > 0
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(|p| p.into_inner())
    }

    /// An answer for `cell_id` holding at `asof` (its names still to be checked).
    pub(crate) fn get(&self, cell_id: &str, asof: &str) -> Option<Arc<Ans>> {
        if !self.enabled() {
            return None;
        }
        let s = self.lock();
        s.entries
            .get(cell_id)?
            .iter()
            .find(|a| a.lo.as_str() <= asof && a.hi.as_deref().is_none_or(|h| asof < h))
            .cloned()
    }

    /// A fault for `cell_id` holding at `asof` (its names still to be checked).
    pub(crate) fn get_fault(&self, cell_id: &str, asof: &str) -> Option<Arc<FaultAns>> {
        if !self.enabled() {
            return None;
        }
        let s = self.lock();
        s.faults
            .get(cell_id)?
            .iter()
            .find(|f| f.lo.as_str() <= asof && f.hi.as_deref().is_none_or(|h| asof < h))
            .cloned()
    }

    /// A dropped answer for `cell_id` that held at `asof` before it was dropped.
    pub(crate) fn stale(&self, cell_id: &str, asof: &str) -> Option<Arc<Ans>> {
        if !self.enabled() {
            return None;
        }
        let s = self.lock();
        s.stale
            .get(cell_id)?
            .iter()
            .find(|a| a.lo.as_str() <= asof && a.hi.as_deref().is_none_or(|h| asof < h))
            .cloned()
    }

    /// Registers an evaluation; returns the revision it began at.
    pub(crate) fn begin(&self) -> u64 {
        let mut s = self.lock();
        let rev = s.rev;
        *s.active.entry(rev).or_default() += 1;
        rev
    }

    /// Ends an evaluation begun at `start`, keeping `learned` (inputs before their readers)
    /// unless something they depend on was marked dirty since.
    pub(crate) fn end(&self, start: u64, learned: &[Entry]) {
        let mut s = self.lock();
        if self.enabled() {
            for e in learned {
                if !e.memo() {
                    continue;
                }
                let deps = e.deps();
                let patterns = e.patterns();
                let mut mark = std::iter::once(e.id())
                    .chain(deps.iter().map(|d| d.as_str()))
                    .filter_map(|c| s.dirty.get(c))
                    .max()
                    .copied();
                // A version added since, of a cell one of its slices contains.
                for (rev, r) in s.added.iter().filter(|(rev, _)| *rev > start) {
                    let hit = patterns.iter().any(|p| match r {
                        Some(r) => p.fn_hash() == r.cell().fn_hash && p.contains(r),
                        None => true,
                    });
                    if hit {
                        mark = Some(mark.map_or(*rev, |m| m.max(*rev)));
                    }
                }
                if let Some(m) = mark.filter(|m| *m > start) {
                    let d = s.dirty.entry(e.id().to_string()).or_default();
                    *d = (*d).max(m);
                    continue;
                }
                s.insert(e.clone(), self.capacity);
            }
        }
        s.finish(start);
    }

    /// Ends an evaluation begun at `start` that keeps nothing.
    pub(crate) fn abort(&self, start: u64) {
        self.lock().finish(start);
    }

    /// Whether [`invalidate`](Memo::invalidate) needs the receipt of the version added: some
    /// answer read a slice over a stored function, or an evaluation is running.
    pub(crate) fn wants_receipts(&self) -> bool {
        let s = self.lock();
        s.pattern_count > 0 || !s.active.is_empty()
    }

    /// A stored version of `cell_id` was added (its receipt `receipt`, when known): drops its
    /// answers and those of every cell that read it, or read a slice containing it,
    /// transitively. Without the receipt, every answer that read a slice over a stored
    /// function is dropped.
    pub(crate) fn invalidate(&self, cell_id: &str, receipt: Option<Arc<Receipt>>) {
        let mut s = self.lock();
        s.rev += 1;
        let rev = s.rev;
        let track = !s.active.is_empty();
        let mut queue = vec![cell_id.to_string()];
        // The readers of slices the new version falls into.
        let mut matched = Vec::new();
        match &receipt {
            Some(r) => {
                if let Some(by_id) = s.patterns.get_mut(&r.cell().fn_hash) {
                    by_id.retain(|_, (slice, readers)| {
                        if slice.contains(r) {
                            matched.extend(readers.drain());
                            false
                        } else {
                            true
                        }
                    });
                }
            }
            None => {
                for (_, by_id) in s.patterns.drain() {
                    for (_, (_, readers)) in by_id {
                        matched.extend(readers);
                    }
                }
            }
        }
        s.pattern_count = s.patterns.values().map(HashMap::len).sum();
        queue.extend(matched);
        if track {
            s.added.push((rev, receipt));
        }
        let mut seen = HashSet::new();
        while let Some(c) = queue.pop() {
            if !seen.insert(c.clone()) {
                continue;
            }
            if track {
                s.dirty.insert(c.clone(), rev);
            }
            if let Some(list) = s.entries.remove(&c) {
                s.count -= list.len();
                s.stale_count += list.len();
                s.stale.entry(c.clone()).or_default().extend(list);
            }
            // A fault is dropped, not kept to recheck: it has no receipt to validate.
            if let Some(list) = s.faults.remove(&c) {
                s.count -= list.len();
            }
            if let Some(readers) = s.readers.remove(&c) {
                s.edges -= readers.len();
                queue.extend(readers);
            }
        }
    }

    /// Drops every answer.
    pub(crate) fn clear(&self) {
        let mut s = self.lock();
        s.rev += 1;
        s.entries.clear();
        s.faults.clear();
        s.readers.clear();
        s.stale.clear();
        s.patterns.clear();
        s.pattern_count = 0;
        s.count = 0;
        s.stale_count = 0;
        s.edges = 0;
    }

    pub(crate) fn stats(&self) -> MemoStats {
        let s = self.lock();
        let mut bytes = 0usize;
        for (id, list) in &s.faults {
            bytes += id.len() + 48;
            for f in list {
                bytes += std::mem::size_of::<FaultAns>()
                    + f.id.len()
                    + f.known.len()
                    + f.lo.len()
                    + f.hi.as_ref().map_or(0, String::len)
                    + f.faulted.iter().map(|c| c.len() + 32).sum::<usize>()
                    + f.names.len() * 64;
            }
        }
        for (id, list) in &s.entries {
            bytes += id.len() + 48;
            for a in list {
                bytes += std::mem::size_of::<Ans>()
                    + a.bytes.len()
                    + a.id.len()
                    + a.hash.len()
                    + a.tx.len()
                    + a.asof.len()
                    + a.lo.len()
                    + a.hi.as_ref().map_or(0, String::len)
                    + a.inputs
                        .iter()
                        .map(|u| match u {
                            Use::Cell { id, hash, .. } => id.len() + hash.len() + std::mem::size_of_val(u) + 160,
                            // Shared by the answers that read it: counted where it is held.
                            Use::Slice(r) => {
                                (r.entry.len() + r.manifest.len() + r.members.len() * 400 + 200)
                                    / Arc::strong_count(r).max(1)
                            }
                        })
                        .sum::<usize>()
                    + a.names
                        .iter()
                        .map(|((k, t), v)| k.len() + t.as_ref().map_or(0, String::len) + v.len() + 64)
                        .sum::<usize>()
                        / Arc::strong_count(&a.names).max(1);
            }
        }
        for (k, set) in &s.readers {
            bytes += k.len() + 48 + set.iter().map(|c| c.len() + 32).sum::<usize>();
        }
        bytes += s.dirty.keys().map(|k| k.len() + 40).sum::<usize>();
        bytes += s.stale.values().flatten().map(|a| a.bytes.len() + 400).sum::<usize>();
        bytes += s
            .patterns
            .values()
            .flat_map(HashMap::values)
            .map(|(p, r)| p.canonical().len() + r.len() * 80 + 120)
            .sum::<usize>();
        let fault_cells = s.faults.keys().filter(|k| !s.entries.contains_key(*k)).count();
        MemoStats {
            slice_patterns: s.pattern_count,
            stale: s.stale_count,
            entries: s.count,
            cells: s.entries.len() + fault_cells,
            dependent_edges: s.edges,
            dirty: s.dirty.len(),
            approx_bytes: bytes,
        }
    }
}

impl State {
    fn insert(&mut self, e: Entry, capacity: usize) {
        let held = match &e {
            Entry::Value(a) => self
                .entries
                .get(&a.id)
                .is_some_and(|list| list.iter().any(|x| x.hash == a.hash && x.lo == a.lo && x.hi == a.hi)),
            Entry::Fault(f) => self
                .faults
                .get(&f.id)
                .is_some_and(|list| list.iter().any(|x| x.fault == f.fault && x.lo == f.lo && x.hi == f.hi)),
        };
        if held {
            return;
        }
        if let Entry::Value(a) = &e {
            if let Some(old) = self.stale.remove(&a.id) {
                self.stale_count -= old.len();
            }
        }
        if self.count + self.stale_count >= capacity {
            self.entries.clear();
            self.faults.clear();
            self.readers.clear();
            self.stale.clear();
            self.patterns.clear();
            self.pattern_count = 0;
            self.count = 0;
            self.stale_count = 0;
            self.edges = 0;
        }
        let id = e.id().to_string();
        for d in e.deps() {
            if self.readers.entry(d.clone()).or_default().insert(id.clone()) {
                self.edges += 1;
            }
        }
        for p in e.patterns() {
            let by_id = self.patterns.entry(p.fn_hash().to_string()).or_default();
            if !by_id.contains_key(p.id()) {
                self.pattern_count += 1;
            }
            by_id.entry(p.id().to_string()).or_insert_with(|| (p.clone(), HashSet::new())).1.insert(id.clone());
        }
        match e {
            Entry::Value(a) => self.entries.entry(a.id.clone()).or_default().push(a),
            Entry::Fault(f) => self.faults.entry(f.id.clone()).or_default().push(f),
        }
        self.count += 1;
    }

    fn finish(&mut self, start: u64) {
        if let Some(n) = self.active.get_mut(&start) {
            *n -= 1;
            if *n == 0 {
                self.active.remove(&start);
            }
        }
        // Marks matter only to evaluations that began before them.
        match self.active.keys().next().copied() {
            None => {
                self.dirty.clear();
                self.added.clear();
            }
            Some(oldest) => {
                self.dirty.retain(|_, m| *m > oldest);
                self.added.retain(|(m, _)| *m > oldest);
            }
        }
    }
}