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 document `id`, if this layer holds one.
136    pub(crate) fn doc(&self, id: &str) -> Option<&Document> {
137        self.docs.get(id)
138    }
139
140    /// The live documents, borrowed, in no particular order, but the same
141    /// order on every call while the layer is unchanged. The compute pool
142    /// relies on that: it scores `docs()` in one pass and the caller pairs the
143    /// scores with a second pass. Keep it true if the storage
144    /// changes.
145    pub(crate) fn docs(&self) -> impl Iterator<Item = &Document> {
146        self.docs.values()
147    }
148
149    /// Number of live documents.
150    pub fn doc_count(&self) -> usize {
151        self.docs.len()
152    }
153
154    /// Number of tombstones.
155    pub fn tombstone_count(&self) -> usize {
156        self.tombstones.len()
157    }
158
159    /// Live documents in ascending id order. Sorting is what makes an
160    /// encoded segment a pure function of the layer's contents.
161    pub fn sorted_docs(&self) -> Vec<&Document> {
162        let mut docs: Vec<&Document> = self.docs.values().collect();
163        docs.sort_unstable_by(|a, b| a.id.cmp(&b.id));
164        docs
165    }
166
167    /// Tombstoned ids in ascending order.
168    pub fn sorted_tombstones(&self) -> Vec<&str> {
169        let mut ids: Vec<&str> = self.tombstones.iter().map(String::as_str).collect();
170        ids.sort_unstable();
171        ids
172    }
173
174    /// Consume the layer, yielding its live documents in no particular order.
175    pub fn into_docs(self) -> impl Iterator<Item = Document> {
176        self.docs.into_values()
177    }
178
179    /// Live documents and tombstones, each in ascending id order, owned: what
180    /// a streaming merge reads a whole input as.
181    pub(crate) fn into_sorted_parts(self) -> (Vec<Document>, Vec<String>) {
182        let mut docs: Vec<Document> = self.docs.into_values().collect();
183        docs.sort_unstable_by(|a, b| a.id.cmp(&b.id));
184        let mut tombstones: Vec<String> = self.tombstones.into_iter().collect();
185        tombstones.sort_unstable();
186        (docs, tombstones)
187    }
188
189    /// Build a layer from decoded parts. The caller has checked that the two
190    /// lists are disjoint.
191    pub(crate) fn from_parts(docs: Vec<Document>, tombstones: Vec<String>) -> Self {
192        Self {
193            docs: docs.into_iter().map(|d| (d.id.clone(), d)).collect(),
194            tombstones: tombstones.into_iter().collect(),
195        }
196    }
197}
198
199/// Fold a stream of log entries, in order, into a layer of their own, one
200/// entry at a time, and return it with the seq of the last entry (`None` for
201/// an empty stream). Overlaying the result on older layers equals replaying
202/// the entries on top of them (see [`Layer::overlay`]).
203pub(crate) async fn fold_log(
204    mut log: BoxStream<'_, Result<(u64, WalEntry)>>,
205) -> Result<(Layer, Option<u64>)> {
206    let mut layer = Layer::new();
207    let mut last = None;
208    while let Some((seq, entry)) = log.try_next().await? {
209        layer.apply_entry(entry);
210        last = Some(seq);
211    }
212    Ok((layer, last))
213}
214
215/// The heads of several sources sorted by id, sources numbered oldest first,
216/// ordered so the smallest id comes out first and, for one id, the newest
217/// source holding it. The one form of [`Layer::overlay`]'s rule for sorted
218/// data: compaction's streaming merge and the flat source's survivors drive it.
219/// The caller pushes each source's next id after taking
220/// one, and checks that a source's ids rise.
221pub(crate) struct NewestWins<K> {
222    heap: BinaryHeap<Reverse<(K, Reverse<usize>)>>,
223}
224
225impl<K: Ord> NewestWins<K> {
226    pub(crate) fn with_capacity(sources: usize) -> Self {
227        Self {
228            heap: BinaryHeap::with_capacity(sources),
229        }
230    }
231
232    /// `source`'s next id.
233    pub(crate) fn push(&mut self, source: usize, id: K) {
234        self.heap.push(Reverse((id, Reverse(source))));
235    }
236
237    /// The smallest id any source holds, and the newest source holding it:
238    /// the one that decides the id.
239    pub(crate) fn pop(&mut self) -> Option<(K, usize)> {
240        self.heap
241            .pop()
242            .map(|Reverse((id, Reverse(source)))| (id, source))
243    }
244
245    /// Another source whose head is also `id`, newest first: one the id's
246    /// winner shadows. `None` once no source's head is `id`.
247    pub(crate) fn pop_older(&mut self, id: &K) -> Option<usize> {
248        match self.heap.peek() {
249            Some(Reverse((next, _))) if next == id => {
250                self.heap.pop().map(|Reverse((_, Reverse(source)))| source)
251            }
252            _ => None,
253        }
254    }
255}
256
257/// One sorted source of [`survivors`]: its document ids and its tombstones,
258/// each strictly ascending, the two disjoint.
259pub(crate) struct SortedIds<'a> {
260    pub(crate) docs: &'a IdColumn,
261    pub(crate) tombstones: &'a IdColumn,
262}
263
264impl<'a> SortedIds<'a> {
265    /// The smaller of the next document and the next tombstone at `at`, and
266    /// whether it is a document.
267    fn head(&self, (doc, tombstone): (usize, usize)) -> Option<(&'a str, bool)> {
268        let docs: &'a IdColumn = self.docs;
269        let tombstones: &'a IdColumn = self.tombstones;
270        let d = (doc < docs.len()).then(|| docs.get(doc));
271        let t = (tombstone < tombstones.len()).then(|| tombstones.get(tombstone));
272        match (d, t) {
273            (Some(d), Some(t)) if t < d => Some((t, false)),
274            (Some(d), _) => Some((d, true)),
275            (None, Some(t)) => Some((t, false)),
276            (None, None) => None,
277        }
278    }
279}
280
281/// For sources sorted by id, oldest first, which document rows survive: one
282/// bitmap per source, a row set when no newer source holds its id as a
283/// document or a tombstone. [`Layer::overlay`]'s answer without building the
284/// map.
285pub(crate) fn survivors(sources: &[SortedIds<'_>]) -> Vec<Bitmap> {
286    let mut live: Vec<Bitmap> = sources.iter().map(|s| Bitmap::new(s.docs.len())).collect();
287    let mut at = vec![(0usize, 0usize); sources.len()];
288    let mut wins = NewestWins::with_capacity(sources.len());
289    for (s, source) in sources.iter().enumerate() {
290        if let Some((id, _)) = source.head(at[s]) {
291            wins.push(s, id);
292        }
293    }
294    while let Some((id, winner)) = wins.pop() {
295        if let Some((_, true)) = sources[winner].head(at[winner]) {
296            live[winner].set(at[winner].0);
297        }
298        step(sources, winner, &mut at, &mut wins);
299        while let Some(older) = wins.pop_older(&id) {
300            step(sources, older, &mut at, &mut wins);
301        }
302    }
303    live
304}
305
306/// Move source `s` past its head and push its next id.
307fn step<'a>(
308    sources: &[SortedIds<'a>],
309    s: usize,
310    at: &mut [(usize, usize)],
311    wins: &mut NewestWins<&'a str>,
312) {
313    match sources[s].head(at[s]) {
314        Some((_, true)) => at[s].0 += 1,
315        Some((_, false)) => at[s].1 += 1,
316        None => return,
317    }
318    if let Some((id, _)) = sources[s].head(at[s]) {
319        wins.push(s, id);
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn docs_come_in_the_same_order_on_every_call() {
329        let mut layer = Layer::new();
330        for i in 0..5_000 {
331            layer.apply(WalOp::Upsert(Document {
332                id: format!("d{i}"),
333                vector: vec![i as f32],
334                attrs: None,
335                sparse: None,
336            }));
337        }
338        let first: Vec<&str> = layer.docs().map(|d| d.id.as_str()).collect();
339        let shared = std::sync::Arc::new(layer.clone());
340        let second: Vec<&str> = shared.docs().map(|d| d.id.as_str()).collect();
341        let again: Vec<&str> = shared.docs().map(|d| d.id.as_str()).collect();
342        assert_eq!(first.len(), 5_000);
343        assert_eq!(second, again);
344        assert_eq!(
345            layer.docs().map(|d| d.id.as_str()).collect::<Vec<_>>(),
346            first
347        );
348    }
349    use crate::document::{Document, WalOp};
350
351    fn up(id: &str, v: f32) -> WalOp {
352        WalOp::Upsert(Document {
353            id: id.into(),
354            vector: vec![v],
355            attrs: None,
356            sparse: None,
357        })
358    }
359
360    fn del(id: &str) -> WalOp {
361        WalOp::Delete(id.into())
362    }
363
364    fn replay(ops: impl IntoIterator<Item = WalOp>) -> Layer {
365        let mut layer = Layer::new();
366        for op in ops {
367            layer.apply(op);
368        }
369        layer
370    }
371
372    #[test]
373    fn upsert_inserts_and_replaces() {
374        let layer = replay([up("a", 1.0), up("a", 2.0)]);
375        assert_eq!(layer.doc_count(), 1);
376        assert_eq!(layer.docs["a"].vector, vec![2.0]);
377        assert_eq!(layer.tombstone_count(), 0);
378    }
379
380    #[test]
381    fn delete_removes_the_doc_and_leaves_a_tombstone() {
382        let layer = replay([up("a", 1.0), del("a")]);
383        assert_eq!(layer.doc_count(), 0);
384        assert_eq!(layer.sorted_tombstones(), ["a"]);
385    }
386
387    #[test]
388    fn delete_of_an_unknown_id_still_leaves_a_tombstone() {
389        // It may be hiding a document in an older segment.
390        let layer = replay([del("ghost")]);
391        assert_eq!(layer.sorted_tombstones(), ["ghost"]);
392    }
393
394    #[test]
395    fn upsert_after_delete_clears_the_tombstone() {
396        let layer = replay([del("a"), up("a", 3.0)]);
397        assert_eq!(layer.doc_count(), 1);
398        assert_eq!(layer.tombstone_count(), 0);
399    }
400
401    #[test]
402    fn drop_tombstones_keeps_the_docs() {
403        let mut layer = replay([up("a", 1.0), del("b")]);
404        layer.drop_tombstones();
405        assert_eq!(layer.doc_count(), 1);
406        assert_eq!(layer.tombstone_count(), 0);
407    }
408
409    #[test]
410    fn sorted_views_are_in_id_order() {
411        let layer = replay([up("c", 1.0), up("a", 1.0), up("b", 1.0), del("z"), del("y")]);
412        let ids: Vec<&str> = layer.sorted_docs().iter().map(|d| d.id.as_str()).collect();
413        assert_eq!(ids, ["a", "b", "c"]);
414        assert_eq!(layer.sorted_tombstones(), ["y", "z"]);
415    }
416
417    #[test]
418    fn overlay_newer_delete_hides_an_older_doc() {
419        let mut older = replay([up("a", 1.0)]);
420        older.overlay(replay([del("a")]));
421        assert_eq!(older.doc_count(), 0);
422        assert_eq!(older.sorted_tombstones(), ["a"]);
423    }
424
425    #[test]
426    fn overlay_newer_upsert_beats_an_older_tombstone() {
427        let mut older = replay([del("a")]);
428        older.overlay(replay([up("a", 5.0)]));
429        assert_eq!(older.docs["a"].vector, vec![5.0]);
430        assert_eq!(older.tombstone_count(), 0);
431    }
432
433    /// Folding a range in two halves must equal replaying it whole. This is
434    /// what makes a merge of segments produce the same bytes as a fold of the
435    /// WAL, so it is checked for every op sequence up to length 5 over two ids.
436    #[test]
437    fn overlay_matches_replay_for_every_short_sequence() {
438        for len in 0..=5u32 {
439            for code in 0..4u32.pow(len) {
440                let ops: Vec<WalOp> = (0..len)
441                    .map(|i| {
442                        let v = i as f32;
443                        match (code / 4u32.pow(i)) % 4 {
444                            0 => up("a", v),
445                            1 => up("b", v),
446                            2 => del("a"),
447                            _ => del("b"),
448                        }
449                    })
450                    .collect();
451                let whole = replay(ops.clone());
452                for split in 0..=ops.len() {
453                    let mut left = replay(ops[..split].to_vec());
454                    left.overlay(replay(ops[split..].to_vec()));
455                    assert_eq!(left, whole, "ops {ops:?} split at {split}");
456                }
457            }
458        }
459    }
460
461    #[test]
462    fn newest_wins_pops_the_smallest_id_and_the_newest_source_first() {
463        let mut wins = NewestWins::with_capacity(3);
464        wins.push(0, "b");
465        wins.push(1, "a");
466        wins.push(2, "b");
467        assert_eq!(wins.pop(), Some(("a", 1)));
468        assert_eq!(wins.pop_older(&"a"), None);
469        assert_eq!(wins.pop(), Some(("b", 2)));
470        assert_eq!(wins.pop_older(&"b"), Some(0));
471        assert_eq!(wins.pop_older(&"b"), None);
472        assert_eq!(wins.pop(), None);
473    }
474
475    #[test]
476    fn pop_older_takes_every_older_holder_newest_first() {
477        let mut wins = NewestWins::with_capacity(4);
478        for source in [0, 3, 1, 2] {
479            wins.push(source, "x");
480        }
481        wins.push(1, "y");
482        assert_eq!(wins.pop(), Some(("x", 3)));
483        assert_eq!(wins.pop_older(&"x"), Some(2));
484        assert_eq!(wins.pop_older(&"x"), Some(1));
485        assert_eq!(wins.pop_older(&"x"), Some(0));
486        assert_eq!(wins.pop_older(&"x"), None);
487        assert_eq!(wins.pop(), Some(("y", 1)));
488    }
489
490    /// `survivors` over sorted runs gives what `Layer::overlay` gives: a row
491    /// survives exactly when its source is the newest holding the id, and the
492    /// overlay's documents are exactly the surviving rows.
493    #[test]
494    fn survivors_equal_overlay_on_random_runs() {
495        use crate::columnar::IdColumn;
496        let mut state = 0x5eed_0043_u64;
497        let mut next = move |n: u64| {
498            state ^= state << 13;
499            state ^= state >> 7;
500            state ^= state << 17;
501            state % n
502        };
503        for case in 0..300 {
504            let sources = 1 + next(5) as usize;
505            // Up to 600 ids, so sources span several 256-row blocks.
506            let ids = 1 + next(600);
507            let layers: Vec<Layer> = (0..sources)
508                .map(|s| {
509                    // Some sources empty.
510                    let ops = next(700) as usize;
511                    replay(
512                        (0..ops)
513                            .map(|i| {
514                                let id = format!("i{:04}", next(ids));
515                                match next(4) {
516                                    0 => del(&id),
517                                    _ => up(&id, (s * 1000 + i) as f32),
518                                }
519                            })
520                            .collect::<Vec<_>>(),
521                    )
522                })
523                .collect();
524            let docs: Vec<IdColumn> = layers
525                .iter()
526                .map(|l| IdColumn::from_sorted(l.sorted_docs().iter().map(|d| d.id.as_str())))
527                .collect();
528            let tombstones: Vec<IdColumn> = layers
529                .iter()
530                .map(|l| IdColumn::from_sorted(l.sorted_tombstones()))
531                .collect();
532            let sorted: Vec<SortedIds<'_>> = docs
533                .iter()
534                .zip(&tombstones)
535                .map(|(docs, tombstones)| SortedIds { docs, tombstones })
536                .collect();
537
538            let live = survivors(&sorted);
539
540            let mut overlaid = Layer::new();
541            for layer in layers.iter().cloned() {
542                overlaid.overlay(layer);
543            }
544            let mut from_bitmaps: Vec<(String, f32)> = Vec::new();
545            for (s, layer) in layers.iter().enumerate() {
546                assert_eq!(live[s].len(), layer.doc_count(), "case {case}");
547                for (row, doc) in layer.sorted_docs().into_iter().enumerate() {
548                    if live[s].get(row) {
549                        from_bitmaps.push((doc.id.clone(), doc.vector[0]));
550                    }
551                }
552            }
553            from_bitmaps.sort_by(|a, b| a.0.cmp(&b.0));
554            let expected: Vec<(String, f32)> = overlaid
555                .sorted_docs()
556                .into_iter()
557                .map(|d| (d.id.clone(), d.vector[0]))
558                .collect();
559            assert_eq!(from_bitmaps, expected, "case {case}");
560        }
561    }
562
563    #[test]
564    fn survivors_of_no_sources_and_of_empty_sources_are_empty() {
565        use crate::columnar::IdColumn;
566        assert!(survivors(&[]).is_empty());
567        let empty = IdColumn::default();
568        let live = survivors(&[SortedIds {
569            docs: &empty,
570            tombstones: &empty,
571        }]);
572        assert_eq!(live.len(), 1);
573        assert_eq!(live[0].len(), 0);
574    }
575
576    /// The same property over longer logs and more ids, which is what an
577    /// incremental tail leans on: it folds a tail in two steps,
578    /// split wherever the last query happened to stop.
579    #[test]
580    fn folding_long_logs_in_two_steps_equals_folding_in_one() {
581        let mut state = 0x9e37_79b9_u64;
582        let mut next = move || {
583            state ^= state << 13;
584            state ^= state >> 7;
585            state ^= state << 17;
586            state
587        };
588        for _ in 0..200 {
589            let ops: Vec<WalOp> = (0..12)
590                .map(|i| {
591                    let id = ["a", "b", "c", "d"][(next() % 4) as usize];
592                    if next() % 3 == 0 {
593                        del(id)
594                    } else {
595                        up(id, i as f32)
596                    }
597                })
598                .collect();
599            let whole = replay(ops.clone());
600            for split in 0..=ops.len() {
601                let mut left = replay(ops[..split].to_vec());
602                left.overlay(replay(ops[split..].to_vec()));
603                assert_eq!(left, whole, "ops {ops:?} split at {split}");
604            }
605        }
606    }
607}