Skip to main content

itzma_core/
layer.rs

1//! Layers: the net effect of applying operations in order.
2//!
3//! A [`Layer`] is a map of live documents plus a set of tombstones, the ids
4//! that this layer deletes. Queries build one from segments and the WAL tail,
5//! and compaction builds one to freeze into a segment. Both go through the
6//! same code, so they cannot disagree about what an upsert or a delete means.
7//!
8//! The two halves never overlap: an id is either a live document or a
9//! tombstone. A tombstone matters only when something older might hold the
10//! id, so a layer that starts at the very beginning of the log drops them
11//! (see [`Layer::drop_tombstones`]).
12
13use std::cmp::Reverse;
14use std::collections::{BinaryHeap, HashMap, HashSet};
15
16use futures::stream::{BoxStream, TryStreamExt};
17
18use crate::columnar::{Bitmap, IdColumn};
19use crate::document::{Document, WalOp};
20use crate::error::Result;
21use crate::wal::WalEntry;
22
23/// Live documents and tombstones produced by applying operations in order.
24///
25/// # Examples
26///
27/// ```
28/// use itzma_core::layer::Layer;
29/// use itzma_core::{Document, WalOp};
30///
31/// let doc = |id: &str| Document { id: id.into(), vector: vec![1.0], attrs: None, sparse: None };
32///
33/// let mut older = Layer::new();
34/// older.apply(WalOp::Upsert(doc("a")));
35///
36/// let mut newer = Layer::new();
37/// newer.apply(WalOp::Delete("a".into()));
38///
39/// older.overlay(newer);
40/// assert_eq!(older.doc_count(), 0);
41/// assert_eq!(older.sorted_tombstones(), ["a"]);
42/// ```
43#[derive(Debug, Default, Clone, PartialEq)]
44pub struct Layer {
45    docs: HashMap<String, Document>,
46    tombstones: HashSet<String>,
47}
48
49impl Layer {
50    /// An empty layer.
51    pub fn new() -> Self {
52        Self::default()
53    }
54
55    /// Apply one operation. An upsert replaces the document and clears any
56    /// tombstone for its id. A delete removes the document and records a
57    /// tombstone, even when the id is not in this layer, because it may be
58    /// hiding a document in an older one.
59    pub fn apply(&mut self, op: WalOp) {
60        match op {
61            WalOp::Upsert(doc) => {
62                self.tombstones.remove(&doc.id);
63                self.docs.insert(doc.id.clone(), doc);
64            }
65            WalOp::Delete(id) => {
66                self.docs.remove(&id);
67                self.tombstones.insert(id);
68            }
69        }
70    }
71
72    /// Apply every operation of one WAL entry, in order.
73    pub fn apply_entry(&mut self, entry: WalEntry) {
74        for op in entry.ops {
75            self.apply(op);
76        }
77    }
78
79    /// Apply every operation of every entry, in log order.
80    pub fn apply_log(&mut self, log: Vec<(u64, WalEntry)>) {
81        for (_seq, entry) in log {
82            self.apply_entry(entry);
83        }
84    }
85
86    /// Put a newer layer on top of this one: its tombstones remove documents
87    /// here, then its documents replace or add. Folding a range of operations
88    /// in two halves and overlaying the results equals replaying the whole
89    /// range.
90    pub fn overlay(&mut self, newer: Layer) {
91        for id in newer.tombstones {
92            self.docs.remove(&id);
93            self.tombstones.insert(id);
94        }
95        for (id, doc) in newer.docs {
96            self.tombstones.remove(&id);
97            self.docs.insert(id, doc);
98        }
99    }
100
101    /// Forget every tombstone. Only right for a layer with nothing older
102    /// beneath it, which is a segment that starts at WAL seq 1.
103    pub fn drop_tombstones(&mut self) {
104        self.tombstones.clear();
105    }
106
107    /// Set the sparse vector of each of `ids`' documents that this layer
108    /// still holds live, in order. Used to graft `sparse.bin`'s row-ordered
109    /// vectors onto a decoded segment's documents (`crate::sparse`) — a
110    /// document a tombstone or a later overlay already removed is silently
111    /// skipped, since a shadowed row's sparse vector is never seen.
112    pub(crate) fn set_sparse(
113        &mut self,
114        ids: &[String],
115        vectors: Vec<Option<crate::document::SparseVector>>,
116    ) {
117        for (id, sparse) in ids.iter().zip(vectors) {
118            if let Some(doc) = self.docs.get_mut(id) {
119                doc.sparse = sparse;
120            }
121        }
122    }
123
124    /// Whether the layer holds neither a document nor a tombstone.
125    pub(crate) fn is_empty(&self) -> bool {
126        self.docs.is_empty() && self.tombstones.is_empty()
127    }
128
129    /// Whether this layer decides `id`: it holds it as a document or as a
130    /// tombstone. Either one hides the id in every older layer.
131    pub(crate) fn holds(&self, id: &str) -> bool {
132        self.docs.contains_key(id) || self.tombstones.contains(id)
133    }
134
135    /// The live documents, borrowed, in no particular order, but the same
136    /// order on every call while the layer is unchanged. The compute pool
137    /// relies on that: it scores `docs()` in one pass and the caller pairs the
138    /// scores with a second pass. Keep it true if the storage
139    /// changes.
140    pub(crate) fn docs(&self) -> impl Iterator<Item = &Document> {
141        self.docs.values()
142    }
143
144    /// Number of live documents.
145    pub fn doc_count(&self) -> usize {
146        self.docs.len()
147    }
148
149    /// Number of tombstones.
150    pub fn tombstone_count(&self) -> usize {
151        self.tombstones.len()
152    }
153
154    /// Live documents in ascending id order. Sorting is what makes an
155    /// encoded segment a pure function of the layer's contents.
156    pub fn sorted_docs(&self) -> Vec<&Document> {
157        let mut docs: Vec<&Document> = self.docs.values().collect();
158        docs.sort_unstable_by(|a, b| a.id.cmp(&b.id));
159        docs
160    }
161
162    /// Tombstoned ids in ascending order.
163    pub fn sorted_tombstones(&self) -> Vec<&str> {
164        let mut ids: Vec<&str> = self.tombstones.iter().map(String::as_str).collect();
165        ids.sort_unstable();
166        ids
167    }
168
169    /// Consume the layer, yielding its live documents in no particular order.
170    pub fn into_docs(self) -> impl Iterator<Item = Document> {
171        self.docs.into_values()
172    }
173
174    /// Live documents and tombstones, each in ascending id order, owned: what
175    /// a streaming merge reads a whole input as.
176    pub(crate) fn into_sorted_parts(self) -> (Vec<Document>, Vec<String>) {
177        let mut docs: Vec<Document> = self.docs.into_values().collect();
178        docs.sort_unstable_by(|a, b| a.id.cmp(&b.id));
179        let mut tombstones: Vec<String> = self.tombstones.into_iter().collect();
180        tombstones.sort_unstable();
181        (docs, tombstones)
182    }
183
184    /// Build a layer from decoded parts. The caller has checked that the two
185    /// lists are disjoint.
186    pub(crate) fn from_parts(docs: Vec<Document>, tombstones: Vec<String>) -> Self {
187        Self {
188            docs: docs.into_iter().map(|d| (d.id.clone(), d)).collect(),
189            tombstones: tombstones.into_iter().collect(),
190        }
191    }
192}
193
194/// Fold a stream of log entries, in order, into a layer of their own, one
195/// entry at a time, and return it with the seq of the last entry (`None` for
196/// an empty stream). Overlaying the result on older layers equals replaying
197/// the entries on top of them (see [`Layer::overlay`]).
198pub(crate) async fn fold_log(
199    mut log: BoxStream<'_, Result<(u64, WalEntry)>>,
200) -> Result<(Layer, Option<u64>)> {
201    let mut layer = Layer::new();
202    let mut last = None;
203    while let Some((seq, entry)) = log.try_next().await? {
204        layer.apply_entry(entry);
205        last = Some(seq);
206    }
207    Ok((layer, last))
208}
209
210/// The heads of several sources sorted by id, sources numbered oldest first,
211/// ordered so the smallest id comes out first and, for one id, the newest
212/// source holding it. The one form of [`Layer::overlay`]'s rule for sorted
213/// data: compaction's streaming merge and the flat source's survivors drive it.
214/// The caller pushes each source's next id after taking
215/// one, and checks that a source's ids rise.
216pub(crate) struct NewestWins<K> {
217    heap: BinaryHeap<Reverse<(K, Reverse<usize>)>>,
218}
219
220impl<K: Ord> NewestWins<K> {
221    pub(crate) fn with_capacity(sources: usize) -> Self {
222        Self {
223            heap: BinaryHeap::with_capacity(sources),
224        }
225    }
226
227    /// `source`'s next id.
228    pub(crate) fn push(&mut self, source: usize, id: K) {
229        self.heap.push(Reverse((id, Reverse(source))));
230    }
231
232    /// The smallest id any source holds, and the newest source holding it:
233    /// the one that decides the id.
234    pub(crate) fn pop(&mut self) -> Option<(K, usize)> {
235        self.heap
236            .pop()
237            .map(|Reverse((id, Reverse(source)))| (id, source))
238    }
239
240    /// Another source whose head is also `id`, newest first: one the id's
241    /// winner shadows. `None` once no source's head is `id`.
242    pub(crate) fn pop_older(&mut self, id: &K) -> Option<usize> {
243        match self.heap.peek() {
244            Some(Reverse((next, _))) if next == id => {
245                self.heap.pop().map(|Reverse((_, Reverse(source)))| source)
246            }
247            _ => None,
248        }
249    }
250}
251
252/// One sorted source of [`survivors`]: its document ids and its tombstones,
253/// each strictly ascending, the two disjoint.
254pub(crate) struct SortedIds<'a> {
255    pub(crate) docs: &'a IdColumn,
256    pub(crate) tombstones: &'a IdColumn,
257}
258
259impl<'a> SortedIds<'a> {
260    /// The smaller of the next document and the next tombstone at `at`, and
261    /// whether it is a document.
262    fn head(&self, (doc, tombstone): (usize, usize)) -> Option<(&'a str, bool)> {
263        let docs: &'a IdColumn = self.docs;
264        let tombstones: &'a IdColumn = self.tombstones;
265        let d = (doc < docs.len()).then(|| docs.get(doc));
266        let t = (tombstone < tombstones.len()).then(|| tombstones.get(tombstone));
267        match (d, t) {
268            (Some(d), Some(t)) if t < d => Some((t, false)),
269            (Some(d), _) => Some((d, true)),
270            (None, Some(t)) => Some((t, false)),
271            (None, None) => None,
272        }
273    }
274}
275
276/// For sources sorted by id, oldest first, which document rows survive: one
277/// bitmap per source, a row set when no newer source holds its id as a
278/// document or a tombstone. [`Layer::overlay`]'s answer without building the
279/// map.
280pub(crate) fn survivors(sources: &[SortedIds<'_>]) -> Vec<Bitmap> {
281    let mut live: Vec<Bitmap> = sources.iter().map(|s| Bitmap::new(s.docs.len())).collect();
282    let mut at = vec![(0usize, 0usize); sources.len()];
283    let mut wins = NewestWins::with_capacity(sources.len());
284    for (s, source) in sources.iter().enumerate() {
285        if let Some((id, _)) = source.head(at[s]) {
286            wins.push(s, id);
287        }
288    }
289    while let Some((id, winner)) = wins.pop() {
290        if let Some((_, true)) = sources[winner].head(at[winner]) {
291            live[winner].set(at[winner].0);
292        }
293        step(sources, winner, &mut at, &mut wins);
294        while let Some(older) = wins.pop_older(&id) {
295            step(sources, older, &mut at, &mut wins);
296        }
297    }
298    live
299}
300
301/// Move source `s` past its head and push its next id.
302fn step<'a>(
303    sources: &[SortedIds<'a>],
304    s: usize,
305    at: &mut [(usize, usize)],
306    wins: &mut NewestWins<&'a str>,
307) {
308    match sources[s].head(at[s]) {
309        Some((_, true)) => at[s].0 += 1,
310        Some((_, false)) => at[s].1 += 1,
311        None => return,
312    }
313    if let Some((id, _)) = sources[s].head(at[s]) {
314        wins.push(s, id);
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn docs_come_in_the_same_order_on_every_call() {
324        let mut layer = Layer::new();
325        for i in 0..5_000 {
326            layer.apply(WalOp::Upsert(Document {
327                id: format!("d{i}"),
328                vector: vec![i as f32],
329                attrs: None,
330                sparse: None,
331            }));
332        }
333        let first: Vec<&str> = layer.docs().map(|d| d.id.as_str()).collect();
334        let shared = std::sync::Arc::new(layer.clone());
335        let second: Vec<&str> = shared.docs().map(|d| d.id.as_str()).collect();
336        let again: Vec<&str> = shared.docs().map(|d| d.id.as_str()).collect();
337        assert_eq!(first.len(), 5_000);
338        assert_eq!(second, again);
339        assert_eq!(
340            layer.docs().map(|d| d.id.as_str()).collect::<Vec<_>>(),
341            first
342        );
343    }
344    use crate::document::{Document, WalOp};
345
346    fn up(id: &str, v: f32) -> WalOp {
347        WalOp::Upsert(Document {
348            id: id.into(),
349            vector: vec![v],
350            attrs: None,
351            sparse: None,
352        })
353    }
354
355    fn del(id: &str) -> WalOp {
356        WalOp::Delete(id.into())
357    }
358
359    fn replay(ops: impl IntoIterator<Item = WalOp>) -> Layer {
360        let mut layer = Layer::new();
361        for op in ops {
362            layer.apply(op);
363        }
364        layer
365    }
366
367    #[test]
368    fn upsert_inserts_and_replaces() {
369        let layer = replay([up("a", 1.0), up("a", 2.0)]);
370        assert_eq!(layer.doc_count(), 1);
371        assert_eq!(layer.docs["a"].vector, vec![2.0]);
372        assert_eq!(layer.tombstone_count(), 0);
373    }
374
375    #[test]
376    fn delete_removes_the_doc_and_leaves_a_tombstone() {
377        let layer = replay([up("a", 1.0), del("a")]);
378        assert_eq!(layer.doc_count(), 0);
379        assert_eq!(layer.sorted_tombstones(), ["a"]);
380    }
381
382    #[test]
383    fn delete_of_an_unknown_id_still_leaves_a_tombstone() {
384        // It may be hiding a document in an older segment.
385        let layer = replay([del("ghost")]);
386        assert_eq!(layer.sorted_tombstones(), ["ghost"]);
387    }
388
389    #[test]
390    fn upsert_after_delete_clears_the_tombstone() {
391        let layer = replay([del("a"), up("a", 3.0)]);
392        assert_eq!(layer.doc_count(), 1);
393        assert_eq!(layer.tombstone_count(), 0);
394    }
395
396    #[test]
397    fn drop_tombstones_keeps_the_docs() {
398        let mut layer = replay([up("a", 1.0), del("b")]);
399        layer.drop_tombstones();
400        assert_eq!(layer.doc_count(), 1);
401        assert_eq!(layer.tombstone_count(), 0);
402    }
403
404    #[test]
405    fn sorted_views_are_in_id_order() {
406        let layer = replay([up("c", 1.0), up("a", 1.0), up("b", 1.0), del("z"), del("y")]);
407        let ids: Vec<&str> = layer.sorted_docs().iter().map(|d| d.id.as_str()).collect();
408        assert_eq!(ids, ["a", "b", "c"]);
409        assert_eq!(layer.sorted_tombstones(), ["y", "z"]);
410    }
411
412    #[test]
413    fn overlay_newer_delete_hides_an_older_doc() {
414        let mut older = replay([up("a", 1.0)]);
415        older.overlay(replay([del("a")]));
416        assert_eq!(older.doc_count(), 0);
417        assert_eq!(older.sorted_tombstones(), ["a"]);
418    }
419
420    #[test]
421    fn overlay_newer_upsert_beats_an_older_tombstone() {
422        let mut older = replay([del("a")]);
423        older.overlay(replay([up("a", 5.0)]));
424        assert_eq!(older.docs["a"].vector, vec![5.0]);
425        assert_eq!(older.tombstone_count(), 0);
426    }
427
428    /// Folding a range in two halves must equal replaying it whole. This is
429    /// what makes a merge of segments produce the same bytes as a fold of the
430    /// WAL, so it is checked for every op sequence up to length 5 over two ids.
431    #[test]
432    fn overlay_matches_replay_for_every_short_sequence() {
433        for len in 0..=5u32 {
434            for code in 0..4u32.pow(len) {
435                let ops: Vec<WalOp> = (0..len)
436                    .map(|i| {
437                        let v = i as f32;
438                        match (code / 4u32.pow(i)) % 4 {
439                            0 => up("a", v),
440                            1 => up("b", v),
441                            2 => del("a"),
442                            _ => del("b"),
443                        }
444                    })
445                    .collect();
446                let whole = replay(ops.clone());
447                for split in 0..=ops.len() {
448                    let mut left = replay(ops[..split].to_vec());
449                    left.overlay(replay(ops[split..].to_vec()));
450                    assert_eq!(left, whole, "ops {ops:?} split at {split}");
451                }
452            }
453        }
454    }
455
456    #[test]
457    fn newest_wins_pops_the_smallest_id_and_the_newest_source_first() {
458        let mut wins = NewestWins::with_capacity(3);
459        wins.push(0, "b");
460        wins.push(1, "a");
461        wins.push(2, "b");
462        assert_eq!(wins.pop(), Some(("a", 1)));
463        assert_eq!(wins.pop_older(&"a"), None);
464        assert_eq!(wins.pop(), Some(("b", 2)));
465        assert_eq!(wins.pop_older(&"b"), Some(0));
466        assert_eq!(wins.pop_older(&"b"), None);
467        assert_eq!(wins.pop(), None);
468    }
469
470    #[test]
471    fn pop_older_takes_every_older_holder_newest_first() {
472        let mut wins = NewestWins::with_capacity(4);
473        for source in [0, 3, 1, 2] {
474            wins.push(source, "x");
475        }
476        wins.push(1, "y");
477        assert_eq!(wins.pop(), Some(("x", 3)));
478        assert_eq!(wins.pop_older(&"x"), Some(2));
479        assert_eq!(wins.pop_older(&"x"), Some(1));
480        assert_eq!(wins.pop_older(&"x"), Some(0));
481        assert_eq!(wins.pop_older(&"x"), None);
482        assert_eq!(wins.pop(), Some(("y", 1)));
483    }
484
485    /// `survivors` over sorted runs gives what `Layer::overlay` gives: a row
486    /// survives exactly when its source is the newest holding the id, and the
487    /// overlay's documents are exactly the surviving rows.
488    #[test]
489    fn survivors_equal_overlay_on_random_runs() {
490        use crate::columnar::IdColumn;
491        let mut state = 0x5eed_0043_u64;
492        let mut next = move |n: u64| {
493            state ^= state << 13;
494            state ^= state >> 7;
495            state ^= state << 17;
496            state % n
497        };
498        for case in 0..300 {
499            let sources = 1 + next(5) as usize;
500            // Up to 600 ids, so sources span several 256-row blocks.
501            let ids = 1 + next(600);
502            let layers: Vec<Layer> = (0..sources)
503                .map(|s| {
504                    // Some sources empty.
505                    let ops = next(700) as usize;
506                    replay(
507                        (0..ops)
508                            .map(|i| {
509                                let id = format!("i{:04}", next(ids));
510                                match next(4) {
511                                    0 => del(&id),
512                                    _ => up(&id, (s * 1000 + i) as f32),
513                                }
514                            })
515                            .collect::<Vec<_>>(),
516                    )
517                })
518                .collect();
519            let docs: Vec<IdColumn> = layers
520                .iter()
521                .map(|l| IdColumn::from_sorted(l.sorted_docs().iter().map(|d| d.id.as_str())))
522                .collect();
523            let tombstones: Vec<IdColumn> = layers
524                .iter()
525                .map(|l| IdColumn::from_sorted(l.sorted_tombstones()))
526                .collect();
527            let sorted: Vec<SortedIds<'_>> = docs
528                .iter()
529                .zip(&tombstones)
530                .map(|(docs, tombstones)| SortedIds { docs, tombstones })
531                .collect();
532
533            let live = survivors(&sorted);
534
535            let mut overlaid = Layer::new();
536            for layer in layers.iter().cloned() {
537                overlaid.overlay(layer);
538            }
539            let mut from_bitmaps: Vec<(String, f32)> = Vec::new();
540            for (s, layer) in layers.iter().enumerate() {
541                assert_eq!(live[s].len(), layer.doc_count(), "case {case}");
542                for (row, doc) in layer.sorted_docs().into_iter().enumerate() {
543                    if live[s].get(row) {
544                        from_bitmaps.push((doc.id.clone(), doc.vector[0]));
545                    }
546                }
547            }
548            from_bitmaps.sort_by(|a, b| a.0.cmp(&b.0));
549            let expected: Vec<(String, f32)> = overlaid
550                .sorted_docs()
551                .into_iter()
552                .map(|d| (d.id.clone(), d.vector[0]))
553                .collect();
554            assert_eq!(from_bitmaps, expected, "case {case}");
555        }
556    }
557
558    #[test]
559    fn survivors_of_no_sources_and_of_empty_sources_are_empty() {
560        use crate::columnar::IdColumn;
561        assert!(survivors(&[]).is_empty());
562        let empty = IdColumn::default();
563        let live = survivors(&[SortedIds {
564            docs: &empty,
565            tombstones: &empty,
566        }]);
567        assert_eq!(live.len(), 1);
568        assert_eq!(live[0].len(), 0);
569    }
570
571    /// The same property over longer logs and more ids, which is what an
572    /// incremental tail leans on: it folds a tail in two steps,
573    /// split wherever the last query happened to stop.
574    #[test]
575    fn folding_long_logs_in_two_steps_equals_folding_in_one() {
576        let mut state = 0x9e37_79b9_u64;
577        let mut next = move || {
578            state ^= state << 13;
579            state ^= state >> 7;
580            state ^= state << 17;
581            state
582        };
583        for _ in 0..200 {
584            let ops: Vec<WalOp> = (0..12)
585                .map(|i| {
586                    let id = ["a", "b", "c", "d"][(next() % 4) as usize];
587                    if next() % 3 == 0 {
588                        del(id)
589                    } else {
590                        up(id, i as f32)
591                    }
592                })
593                .collect();
594            let whole = replay(ops.clone());
595            for split in 0..=ops.len() {
596                let mut left = replay(ops[..split].to_vec());
597                left.overlay(replay(ops[split..].to_vec()));
598                assert_eq!(left, whole, "ops {ops:?} split at {split}");
599            }
600        }
601    }
602}