Skip to main content

kermit_ds/ds/hash_trie/
implementation.rs

1//! `HashTrie`: a hash-based trie storing a relation as nested hash tables,
2//! one per attribute. Implements `Relation`, `JoinIterable`, `Projectable`,
3//! `HeapSize`, and `HashTrieIterable`.
4//!
5//! `HashTrie` is generic over a [`HashStrategy`](kermit_iters::HashStrategy)
6//! `H` (default [`SipHashStrategy`](kermit_iters::SipHashStrategy)). The
7//! strategy controls how attribute values are hashed at every level of the
8//! trie and is the layout axis emitted by
9//! [`HasOptimizationAxes`](kermit_iters::HasOptimizationAxes) under
10//! `ds_layout_hasher`.
11
12use {
13    super::node::HashTrieNode,
14    crate::relation::{Relation, RelationHeader},
15    kermit_iters::{HashStrategy, JoinIterable, SipHashStrategy},
16    std::marker::PhantomData,
17};
18
19/// A hash trie. Each path from root to leaf corresponds to one tuple's
20/// hash signature; tuples sharing a complete signature (collisions on
21/// every attribute) collect into a chain at the leaf — verification of
22/// actual key equality is deferred to the join algorithm.
23///
24/// # Invariants
25///
26/// - The depth of every root-to-leaf path equals `header.arity()`.
27/// - Inner nodes exist at depths `0..arity-1`; the leaf node at depth
28///   `arity-1`.
29/// - For arity = 0: undefined behavior (no nullary relations supported).
30///
31/// # Construction
32///
33/// Use `from_tuples` (batch) or `new` followed by `insert` (incremental).
34/// Both funnel through `insert` for a single tuple, faithful to
35/// Algorithm 2 from the paper.
36///
37/// # Layout parameter
38///
39/// `H` is a [`HashStrategy`] selecting which hash function is used to
40/// convert attribute values to `u64`. Defaults to
41/// [`SipHashStrategy`] for backwards compatibility with pre-standard code.
42pub struct HashTrie<H: HashStrategy = SipHashStrategy> {
43    header: RelationHeader,
44    root: HashTrieNode,
45    _hasher: PhantomData<H>,
46}
47
48impl<H: HashStrategy> HashTrie<H> {
49    /// Construct the root node appropriate for `arity` — Inner for arity ≥ 2,
50    /// Leaf for arity = 1.
51    fn make_root(arity: usize) -> HashTrieNode {
52        if arity <= 1 {
53            HashTrieNode::new_leaf()
54        } else {
55            HashTrieNode::new_inner()
56        }
57    }
58
59    /// Crate-visible accessor for the root node. Used by `HashTrieIter`
60    /// (in the same crate) to navigate the trie via shared references.
61    pub(crate) fn root(&self) -> &HashTrieNode { &self.root }
62
63    /// Walk the trie depth-first and return every materialized tuple.
64    ///
65    /// Used by [`crate::relation::Projectable::project`], the CLI's
66    /// `bench` machinery (which needs to recover tuples from an
67    /// already-built relation for the insertion-benchmark closure),
68    /// and tests. Allocates a fresh `Vec<Vec<usize>>`; for large
69    /// relations this is O(n · arity) in both time and space.
70    pub fn collect_tuples(&self) -> Vec<Vec<usize>> {
71        let mut out = Vec::new();
72        Self::collect_at(&self.root, &mut out);
73        out
74    }
75
76    fn collect_at(node: &HashTrieNode, out: &mut Vec<Vec<usize>>) {
77        match node {
78            | HashTrieNode::Inner(table) => {
79                for (_, child) in table.iter() {
80                    Self::collect_at(child, out);
81                }
82            },
83            | HashTrieNode::Leaf(table) => {
84                for (_, chain) in table.iter() {
85                    for tuple in chain {
86                        out.push(tuple.clone());
87                    }
88                }
89            },
90        }
91    }
92
93    /// Insert one tuple at the appropriate depth in the trie. Recursive
94    /// implementation of Algorithm 2 from the paper, line by line.
95    fn insert_at(node: &mut HashTrieNode, depth: usize, arity: usize, tuple: Vec<usize>) {
96        let key = tuple[depth];
97        let hash = H::hash(key);
98        match node {
99            | HashTrieNode::Inner(table) => {
100                let child = table.entry_or_insert_with(hash, || {
101                    if depth + 1 == arity - 1 {
102                        HashTrieNode::new_leaf()
103                    } else {
104                        HashTrieNode::new_inner()
105                    }
106                });
107                Self::insert_at(child, depth + 1, arity, tuple);
108            },
109            | HashTrieNode::Leaf(table) => {
110                let chain = table.entry_or_insert_with(hash, Vec::new);
111                chain.push(tuple);
112            },
113        }
114    }
115}
116
117impl<H: HashStrategy> JoinIterable for HashTrie<H> {}
118
119impl<H: HashStrategy> Relation for HashTrie<H> {
120    fn header(&self) -> &RelationHeader { &self.header }
121
122    fn new(header: RelationHeader) -> Self {
123        let root = Self::make_root(header.arity());
124        Self {
125            header,
126            root,
127            _hasher: PhantomData,
128        }
129    }
130
131    fn from_tuples(header: RelationHeader, tuples: Vec<Vec<usize>>) -> Self {
132        let arity = header.arity();
133        let mut trie = Self::new(header);
134        for tuple in tuples {
135            assert_eq!(
136                tuple.len(),
137                arity,
138                "from_tuples: tuple arity {} does not match header arity {}",
139                tuple.len(),
140                arity,
141            );
142            Self::insert_at(&mut trie.root, 0, arity, tuple);
143        }
144        trie
145    }
146
147    fn insert(&mut self, tuple: Vec<usize>) {
148        assert_eq!(
149            tuple.len(),
150            self.header.arity(),
151            "tuple arity {} does not match relation arity {}",
152            tuple.len(),
153            self.header.arity()
154        );
155        let arity = self.header.arity();
156        Self::insert_at(&mut self.root, 0, arity, tuple);
157    }
158
159    fn insert_all(&mut self, tuples: Vec<Vec<usize>>) {
160        for tuple in tuples {
161            self.insert(tuple);
162        }
163    }
164}
165
166impl<H: HashStrategy> crate::relation::Projectable for HashTrie<H> {
167    fn project(&self, columns: Vec<usize>) -> Self {
168        let arity = self.header.arity();
169        for &c in &columns {
170            assert!(
171                c < arity,
172                "project: column index {c} out of range for arity {arity}"
173            );
174        }
175        // Build the projected header. Match the convention used by
176        // project_via_trie_iter in `kermit-ds/src/relation.rs`.
177        let projected_attrs: Vec<String> = columns
178            .iter()
179            .filter_map(|&c| self.header.attrs().get(c).cloned())
180            .collect();
181        let new_header = if projected_attrs.is_empty() {
182            RelationHeader::new_nameless_positional(columns.len())
183        } else {
184            RelationHeader::new_nameless(projected_attrs)
185        };
186        let projected_tuples: Vec<Vec<usize>> = self
187            .collect_tuples()
188            .into_iter()
189            .map(|tuple| columns.iter().map(|&c| tuple[c]).collect())
190            .collect();
191        HashTrie::<H>::from_tuples(new_header, projected_tuples)
192    }
193}
194
195impl<H: HashStrategy> crate::heap_size::HeapSize for HashTrie<H> {
196    fn heap_size_bytes(&self) -> usize { node_heap_bytes(&self.root) }
197}
198
199impl<H: HashStrategy> kermit_iters::HashTrieIterable for HashTrie<H> {
200    fn hash_trie_iter(&self) -> impl kermit_iters::HashTrieIterator {
201        super::hash_trie_iter::HashTrieIter::<H>::new(self)
202    }
203}
204
205impl<H: HashStrategy> kermit_iters::HasOptimizationAxes for HashTrie<H> {
206    /// One layout axis: `ds_layout_hasher` carrying the strategy's
207    /// `LayoutOption::NAME` (e.g. `"sip"` / `"fxhash"`).
208    fn optimization_axes(&self) -> std::collections::BTreeMap<String, serde_json::Value> {
209        let mut axes = std::collections::BTreeMap::new();
210        axes.insert(
211            "ds_layout_hasher".to_string(),
212            serde_json::Value::String(<H as kermit_iters::LayoutOption>::NAME.to_string()),
213        );
214        axes
215    }
216}
217
218fn node_heap_bytes(node: &HashTrieNode) -> usize {
219    match node {
220        | HashTrieNode::Inner(table) => {
221            let shell = table.shell_heap_bytes();
222            let children: usize = table.iter().map(|(_, child)| node_heap_bytes(child)).sum();
223            shell + children
224        },
225        | HashTrieNode::Leaf(table) => {
226            let shell = table.shell_heap_bytes();
227            let chains: usize = table
228                .iter()
229                .map(|(_, chain)| {
230                    chain.capacity() * std::mem::size_of::<Vec<usize>>()
231                        + chain
232                            .iter()
233                            .map(|t| t.capacity() * std::mem::size_of::<usize>())
234                            .sum::<usize>()
235                })
236                .sum();
237            shell + chains
238        },
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    // Test let-bindings use `HashTrie` (the bare type), which resolves
247    // through the `<H = SipHashStrategy>` default in type position. The
248    // default cannot be selected from a path expression alone, so
249    // type-annotated bindings are necessary on nightly Rust.
250
251    #[test]
252    fn new_arity_2_creates_inner_root() {
253        let trie: HashTrie = HashTrie::new(2.into());
254        assert_eq!(trie.header().arity(), 2);
255        assert!(matches!(trie.root, HashTrieNode::Inner(_)));
256    }
257
258    #[test]
259    fn new_arity_1_creates_leaf_root() {
260        let trie: HashTrie = HashTrie::new(1.into());
261        assert_eq!(trie.header().arity(), 1);
262        assert!(matches!(trie.root, HashTrieNode::Leaf(_)));
263    }
264
265    #[test]
266    fn insert_arity_1_populates_leaf() {
267        let mut trie: HashTrie = HashTrie::new(1.into());
268        trie.insert(vec![42]);
269        // Verify by inspecting the root: should be a Leaf with one entry.
270        match &trie.root {
271            | HashTrieNode::Leaf(table) => assert_eq!(table.len(), 1),
272            | _ => panic!("expected Leaf root"),
273        }
274    }
275
276    #[test]
277    fn insert_arity_2_builds_inner_then_leaf() {
278        let mut trie: HashTrie = HashTrie::new(2.into());
279        trie.insert(vec![1, 2]);
280        match &trie.root {
281            | HashTrieNode::Inner(root_table) => {
282                assert_eq!(root_table.len(), 1);
283                // Walk one level deeper and confirm it's a Leaf.
284                let mut found_leaf = false;
285                for (_, child) in root_table.iter() {
286                    assert!(matches!(child, HashTrieNode::Leaf(_)));
287                    if let HashTrieNode::Leaf(leaf_table) = child {
288                        assert_eq!(leaf_table.len(), 1);
289                        found_leaf = true;
290                    }
291                }
292                assert!(found_leaf);
293            },
294            | _ => panic!("expected Inner root"),
295        }
296    }
297
298    #[test]
299    fn insert_two_tuples_sharing_first_attribute() {
300        let mut trie: HashTrie = HashTrie::new(2.into());
301        trie.insert(vec![1, 2]);
302        trie.insert(vec![1, 3]);
303        // Same attr-0 value => same hash at root => same child node; child has
304        // two entries.
305        match &trie.root {
306            | HashTrieNode::Inner(root_table) => {
307                assert_eq!(root_table.len(), 1);
308                for (_, child) in root_table.iter() {
309                    if let HashTrieNode::Leaf(leaf_table) = child {
310                        assert_eq!(leaf_table.len(), 2);
311                    }
312                }
313            },
314            | _ => panic!("expected Inner root"),
315        }
316    }
317
318    #[test]
319    #[should_panic(expected = "tuple arity")]
320    fn insert_wrong_arity_panics() {
321        let mut trie: HashTrie = HashTrie::new(2.into());
322        trie.insert(vec![1]);
323    }
324
325    #[test]
326    fn from_tuples_arity_2_builds_correct_shape() {
327        let trie: HashTrie =
328            HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
329        assert_eq!(trie.header().arity(), 2);
330        // Same attr-0 inserts share a child; two distinct attr-0 values =>
331        // two root-level entries.
332        match &trie.root {
333            | HashTrieNode::Inner(root_table) => assert_eq!(root_table.len(), 2),
334            | _ => panic!("expected Inner root"),
335        }
336    }
337
338    #[test]
339    fn from_tuples_empty_input() {
340        let trie: HashTrie = HashTrie::from_tuples(2.into(), vec![]);
341        match &trie.root {
342            | HashTrieNode::Inner(root_table) => assert_eq!(root_table.len(), 0),
343            | _ => panic!("expected Inner root"),
344        }
345    }
346
347    #[test]
348    fn insert_all_equivalent_to_from_tuples_for_multiset_view() {
349        let mut a: HashTrie = HashTrie::new(2.into());
350        a.insert_all(vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
351        let b: HashTrie = HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
352        // Compare via heap_size and tuple set (via Projectable when ready) —
353        // for now confirm both have populated roots with the same length.
354        let a_root_len = match &a.root {
355            | HashTrieNode::Inner(t) => t.len(),
356            | _ => unreachable!(),
357        };
358        let b_root_len = match &b.root {
359            | HashTrieNode::Inner(t) => t.len(),
360            | _ => unreachable!(),
361        };
362        assert_eq!(a_root_len, b_root_len);
363    }
364
365    #[test]
366    fn collect_tuples_recovers_input_as_multiset() {
367        let mut trie: HashTrie =
368            HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
369        let mut collected = trie.collect_tuples();
370        collected.sort();
371        assert_eq!(collected, vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
372
373        // Adding a tuple with full collision-equal hash signature: same value
374        // at each attribute => same hash path => stored on the same leaf chain.
375        trie.insert(vec![1, 2]);
376        let mut collected = trie.collect_tuples();
377        collected.sort();
378        assert_eq!(collected, vec![vec![1, 2], vec![1, 2], vec![1, 3], vec![
379            2, 4
380        ]]);
381    }
382
383    #[test]
384    fn collect_tuples_empty_trie() {
385        let trie: HashTrie = HashTrie::new(2.into());
386        assert!(trie.collect_tuples().is_empty());
387    }
388
389    #[test]
390    fn heap_size_zero_for_empty_trie() {
391        use crate::HeapSize;
392        let trie: HashTrie = HashTrie::new(2.into());
393        // Even an empty trie allocates initial 4-bucket tables, so heap size
394        // is non-zero — what we check is determinism and ordering.
395        let small = trie.heap_size_bytes();
396        let big_trie: HashTrie =
397            HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![1, 3], vec![2, 4], vec![
398                3, 5,
399            ]]);
400        let big = big_trie.heap_size_bytes();
401        assert!(big > small, "non-empty trie should be heavier than empty");
402    }
403
404    #[test]
405    fn heap_size_deterministic_across_rebuilds() {
406        use crate::HeapSize;
407        let tuples = vec![vec![1, 2], vec![1, 3], vec![2, 4], vec![3, 5]];
408        let trie_a: HashTrie = HashTrie::from_tuples(2.into(), tuples.clone());
409        let trie_b: HashTrie = HashTrie::from_tuples(2.into(), tuples);
410        assert_eq!(trie_a.heap_size_bytes(), trie_b.heap_size_bytes());
411    }
412
413    #[test]
414    fn project_drops_columns() {
415        use crate::relation::Projectable;
416        let trie: HashTrie =
417            HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![1, 3], vec![2, 4]]);
418        // π_0 (first column only)
419        let projected = trie.project(vec![0]);
420        assert_eq!(projected.header().arity(), 1);
421        let mut collected = projected.collect_tuples();
422        collected.sort();
423        // Duplicate `1`s collapse only if from_tuples deduplicates — HashTrie
424        // is a multiset, so we expect duplicates to survive.
425        assert_eq!(collected, vec![vec![1], vec![1], vec![2]]);
426    }
427
428    #[test]
429    fn project_reorders_columns() {
430        use crate::relation::Projectable;
431        let trie: HashTrie = HashTrie::from_tuples(2.into(), vec![vec![1, 2], vec![3, 4]]);
432        let projected = trie.project(vec![1, 0]);
433        let mut collected = projected.collect_tuples();
434        collected.sort();
435        assert_eq!(collected, vec![vec![2, 1], vec![4, 3]]);
436    }
437
438    #[test]
439    fn hash_trie_iter_returns_navigable_iterator() {
440        use kermit_iters::{HashTrieIterable, HashTrieIterator};
441        let trie: HashTrie = HashTrie::from_tuples(1.into(), vec![vec![1], vec![2], vec![3]]);
442        let mut it = trie.hash_trie_iter();
443        assert!(it.open());
444        let mut seen = std::collections::HashSet::new();
445        while !it.at_end() {
446            seen.insert(it.key().unwrap());
447            it.next();
448        }
449        assert_eq!(seen.len(), 3);
450    }
451
452    #[test]
453    fn optimization_axes_default_strategy_reports_sip() {
454        use kermit_iters::HasOptimizationAxes;
455        let trie: HashTrie = HashTrie::new(2.into());
456        let axes = trie.optimization_axes();
457        assert_eq!(axes.len(), 1);
458        assert_eq!(
459            axes.get("ds_layout_hasher"),
460            Some(&serde_json::Value::String("sip".to_string())),
461        );
462    }
463
464    #[test]
465    fn optimization_axes_fxhash_strategy_reports_fxhash() {
466        use kermit_iters::{FxHashStrategy, HasOptimizationAxes};
467        let trie: HashTrie<FxHashStrategy> = HashTrie::new(2.into());
468        let axes = trie.optimization_axes();
469        assert_eq!(axes.len(), 1);
470        assert_eq!(
471            axes.get("ds_layout_hasher"),
472            Some(&serde_json::Value::String("fxhash".to_string())),
473        );
474    }
475}