Skip to main content

grafeo_core/execution/operators/
leapfrog_join.rs

1//! Leapfrog TrieJoin operator for worst-case optimal joins.
2//!
3//! This operator wraps the `LeapfrogJoin` algorithm from the trie index module
4//! to provide efficient multi-way joins for cyclic patterns like triangles.
5//!
6//! Traditional binary hash joins cascade O(N²) for triangle patterns; leapfrog
7//! achieves O(N^1.5) by processing all relations simultaneously.
8
9use grafeo_common::types::{EdgeId, LogicalType, NodeId, Value};
10
11use super::{Operator, OperatorError, OperatorResult};
12use crate::execution::DataChunk;
13use crate::execution::chunk::DataChunkBuilder;
14use crate::index::trie::{LeapfrogJoin, TrieIndex};
15
16/// Row identifier for reconstructing output: (input_index, chunk_index, row_index).
17type RowId = (usize, usize, usize);
18
19/// A multi-way join intersection result.
20struct JoinResult {
21    /// Row identifiers from each input that participated in this match.
22    row_ids: Vec<Vec<RowId>>,
23}
24
25/// Leapfrog TrieJoin operator for worst-case optimal multi-way joins.
26///
27/// Uses the leapfrog algorithm to efficiently find intersections across
28/// multiple sorted inputs without materializing intermediate Cartesian products.
29pub struct LeapfrogJoinOperator {
30    /// Input operators (one per relation in the join).
31    inputs: Vec<Box<dyn Operator>>,
32
33    /// Column indices for join keys in each input.
34    /// Each inner Vec maps to one join variable.
35    join_key_indices: Vec<Vec<usize>>,
36
37    /// Output schema (combined columns from all inputs).
38    output_schema: Vec<LogicalType>,
39
40    /// Mapping from output column index to (input_idx, column_idx).
41    output_column_mapping: Vec<(usize, usize)>,
42
43    // === Materialization state ===
44    /// Materialized input chunks (built once during first next() call).
45    materialized_inputs: Vec<Vec<DataChunk>>,
46
47    /// TrieIndex structures built from materialized inputs.
48    tries: Vec<TrieIndex>,
49
50    /// Whether materialization is complete.
51    materialized: bool,
52
53    // === Iteration state ===
54    /// Pre-computed join results.
55    results: Vec<JoinResult>,
56
57    /// Current position in results.
58    result_position: usize,
59
60    /// Current expansion position within current result's cross product.
61    expansion_indices: Vec<usize>,
62
63    /// Whether iteration is exhausted.
64    exhausted: bool,
65}
66
67impl LeapfrogJoinOperator {
68    /// Creates a new leapfrog join operator.
69    ///
70    /// # Arguments
71    /// * `inputs` - Input operators (one per relation).
72    /// * `join_key_indices` - Column indices for join keys in each input.
73    /// * `output_schema` - Schema of the output columns.
74    /// * `output_column_mapping` - Maps output columns to (input_idx, column_idx).
75    #[must_use]
76    pub fn new(
77        inputs: Vec<Box<dyn Operator>>,
78        join_key_indices: Vec<Vec<usize>>,
79        output_schema: Vec<LogicalType>,
80        output_column_mapping: Vec<(usize, usize)>,
81    ) -> Self {
82        Self {
83            inputs,
84            join_key_indices,
85            output_schema,
86            output_column_mapping,
87            materialized_inputs: Vec::new(),
88            tries: Vec::new(),
89            materialized: false,
90            results: Vec::new(),
91            result_position: 0,
92            expansion_indices: Vec::new(),
93            exhausted: false,
94        }
95    }
96
97    /// Materializes all inputs and builds trie indexes.
98    fn materialize_inputs(&mut self) -> Result<(), OperatorError> {
99        // Phase 1: Collect all chunks from each input
100        for input in &mut self.inputs {
101            let mut chunks = Vec::new();
102            while let Some(chunk) = input.next()? {
103                chunks.push(chunk);
104            }
105            self.materialized_inputs.push(chunks);
106        }
107
108        // Phase 2: Build TrieIndex for each input
109        for (input_idx, chunks) in self.materialized_inputs.iter().enumerate() {
110            let mut trie = TrieIndex::new();
111            let key_indices = &self.join_key_indices[input_idx];
112
113            for (chunk_idx, chunk) in chunks.iter().enumerate() {
114                for row in 0..chunk.row_count() {
115                    // Extract join key values and convert to path
116                    if let Some(path) = self.extract_join_keys(chunk, row, key_indices) {
117                        // Encode row location as EdgeId for trie storage
118                        let row_id = Self::encode_row_id(input_idx, chunk_idx, row);
119                        trie.insert(&path, row_id);
120                    }
121                }
122            }
123            self.tries.push(trie);
124        }
125
126        self.materialized = true;
127        Ok(())
128    }
129
130    /// Extracts join key values from a row and converts to NodeId path.
131    fn extract_join_keys(
132        &self,
133        chunk: &DataChunk,
134        row: usize,
135        key_indices: &[usize],
136    ) -> Option<Vec<NodeId>> {
137        let mut path = Vec::with_capacity(key_indices.len());
138
139        for &col_idx in key_indices {
140            let col = chunk.column(col_idx)?;
141            let node_id = match col.data_type() {
142                LogicalType::Node => col.get_node_id(row),
143                LogicalType::Edge => col.get_edge_id(row).map(|e| NodeId::new(e.as_u64())),
144                // reason: ID encoding: i64 <-> u64 round-trip
145                LogicalType::Int64 => col.get_int64(row).map(|i| {
146                    // reason: ID encoding: i64 to u64 round-trip, negative IDs do not occur
147                    #[allow(clippy::cast_sign_loss)]
148                    NodeId::new(i as u64)
149                }),
150                _ => return None, // Unsupported join key type
151            }?;
152            path.push(node_id);
153        }
154
155        Some(path)
156    }
157
158    /// Encodes a row location as an EdgeId for trie storage.
159    fn encode_row_id(input_idx: usize, chunk_idx: usize, row: usize) -> EdgeId {
160        // Pack: input (8 bits) | chunk (24 bits) | row (32 bits)
161        let encoded = ((input_idx as u64) << 56)
162            | ((chunk_idx as u64 & 0xFFFFFF) << 32)
163            | (row as u64 & 0xFFFFFFFF);
164        EdgeId::new(encoded)
165    }
166
167    /// Decodes a row location from an EdgeId.
168    fn decode_row_id(edge_id: EdgeId) -> RowId {
169        let encoded = edge_id.as_u64();
170        let input_idx = (encoded >> 56) as usize;
171        let chunk_idx = ((encoded >> 32) & 0xFFFFFF) as usize;
172        let row = (encoded & 0xFFFFFFFF) as usize;
173        (input_idx, chunk_idx, row)
174    }
175
176    /// Executes the leapfrog join to find all intersections.
177    fn execute_leapfrog(&mut self) -> Result<(), OperatorError> {
178        if self.tries.is_empty() {
179            return Ok(());
180        }
181
182        // Create iterators for each trie at the first level
183        let iters: Vec<_> = self.tries.iter().map(|t| t.iter()).collect();
184
185        // Create leapfrog join
186        let mut join = LeapfrogJoin::new(iters);
187
188        // Find all intersections at the first level
189        while let Some(key) = join.key() {
190            // Collect all row IDs from each input that match this key
191            let mut row_ids_per_input: Vec<Vec<RowId>> = vec![Vec::new(); self.tries.len()];
192
193            // For each trie, collect all row IDs at this key
194            if let Some(child_iters) = join.open() {
195                for (input_idx, _child_iter) in child_iters.into_iter().enumerate() {
196                    // The child iterator points to the second level of the trie
197                    // We need to collect the edge IDs (our encoded row IDs) at this position
198                    self.collect_row_ids_at_key(
199                        &self.tries[input_idx],
200                        key,
201                        input_idx,
202                        &mut row_ids_per_input[input_idx],
203                    );
204                }
205            }
206
207            // Only add result if all inputs have matching rows
208            if row_ids_per_input.iter().all(|ids| !ids.is_empty()) {
209                self.results.push(JoinResult {
210                    row_ids: row_ids_per_input,
211                });
212            }
213
214            if !join.next() {
215                break;
216            }
217        }
218
219        // Initialize expansion indices if we have results
220        if !self.results.is_empty() {
221            self.expansion_indices = vec![0; self.inputs.len()];
222        }
223
224        Ok(())
225    }
226
227    /// Collects all row IDs from a trie at a specific key.
228    fn collect_row_ids_at_key(
229        &self,
230        trie: &TrieIndex,
231        key: NodeId,
232        input_idx: usize,
233        row_ids: &mut Vec<RowId>,
234    ) {
235        // Get iterator at the key's path
236        if let Some(edges) = trie.get(&[key]) {
237            for &edge_id in edges {
238                let decoded = Self::decode_row_id(edge_id);
239                // Verify input index matches (should always match)
240                if decoded.0 == input_idx {
241                    row_ids.push(decoded);
242                }
243            }
244        }
245
246        // Also check children (for multi-level tries)
247        if let Some(iter) = trie.iter_at(&[key]) {
248            let mut iter = iter;
249            loop {
250                if let Some(child_key) = iter.key()
251                    && let Some(edges) = trie.get(&[key, child_key])
252                {
253                    for &edge_id in edges {
254                        row_ids.push(Self::decode_row_id(edge_id));
255                    }
256                }
257                if !iter.next() {
258                    break;
259                }
260            }
261        }
262    }
263
264    /// Advances to the next combination in the current result's cross product.
265    fn advance_expansion(&mut self) -> bool {
266        if self.result_position >= self.results.len() {
267            return false;
268        }
269
270        let result = &self.results[self.result_position];
271
272        // Try to advance from the rightmost input
273        for i in (0..self.expansion_indices.len()).rev() {
274            self.expansion_indices[i] += 1;
275            if self.expansion_indices[i] < result.row_ids[i].len() {
276                return true;
277            }
278            self.expansion_indices[i] = 0;
279        }
280
281        // All combinations exhausted for this result, move to next
282        self.result_position += 1;
283        if self.result_position < self.results.len() {
284            self.expansion_indices = vec![0; self.inputs.len()];
285            true
286        } else {
287            false
288        }
289    }
290
291    /// Builds an output row from the current expansion position.
292    fn build_output_row(&self, builder: &mut DataChunkBuilder) -> Result<(), OperatorError> {
293        let result = &self.results[self.result_position];
294
295        for (out_col, &(input_idx, in_col)) in self.output_column_mapping.iter().enumerate() {
296            let expansion_idx = self.expansion_indices[input_idx];
297            let (_, chunk_idx, row) = result.row_ids[input_idx][expansion_idx];
298
299            let chunk = &self.materialized_inputs[input_idx][chunk_idx];
300            let col = chunk
301                .column(in_col)
302                .ok_or_else(|| OperatorError::ColumnNotFound(in_col.to_string()))?;
303
304            let out_col_vec = builder
305                .column_mut(out_col)
306                .ok_or_else(|| OperatorError::ColumnNotFound(out_col.to_string()))?;
307
308            // Copy value from input to output
309            if let Some(value) = col.get_value(row) {
310                out_col_vec.push_value(value);
311            } else {
312                out_col_vec.push_value(Value::Null);
313            }
314        }
315
316        builder.advance_row();
317        Ok(())
318    }
319}
320
321impl Operator for LeapfrogJoinOperator {
322    fn next(&mut self) -> OperatorResult {
323        // First call: materialize inputs and execute leapfrog
324        if !self.materialized {
325            self.materialize_inputs()?;
326            self.execute_leapfrog()?;
327        }
328
329        if self.exhausted || self.results.is_empty() {
330            return Ok(None);
331        }
332
333        // Check if we've exhausted all results
334        if self.result_position >= self.results.len() {
335            self.exhausted = true;
336            return Ok(None);
337        }
338
339        let mut builder = DataChunkBuilder::with_capacity(&self.output_schema, 2048);
340
341        while !builder.is_full() {
342            self.build_output_row(&mut builder)?;
343
344            if !self.advance_expansion() {
345                self.exhausted = true;
346                break;
347            }
348        }
349
350        if builder.row_count() > 0 {
351            Ok(Some(builder.finish()))
352        } else {
353            Ok(None)
354        }
355    }
356
357    fn reset(&mut self) {
358        for input in &mut self.inputs {
359            input.reset();
360        }
361        self.materialized_inputs.clear();
362        self.tries.clear();
363        self.materialized = false;
364        self.results.clear();
365        self.result_position = 0;
366        self.expansion_indices.clear();
367        self.exhausted = false;
368    }
369
370    fn name(&self) -> &'static str {
371        "LeapfrogJoin"
372    }
373
374    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
375        self
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use crate::execution::vector::ValueVector;
383
384    /// Creates a simple scan operator that returns a single chunk.
385    struct MockScanOperator {
386        chunk: Option<DataChunk>,
387        returned: bool,
388    }
389
390    impl MockScanOperator {
391        fn new(chunk: DataChunk) -> Self {
392            Self {
393                chunk: Some(chunk),
394                returned: false,
395            }
396        }
397    }
398
399    impl Operator for MockScanOperator {
400        fn next(&mut self) -> OperatorResult {
401            if self.returned {
402                Ok(None)
403            } else {
404                self.returned = true;
405                Ok(self.chunk.take())
406            }
407        }
408
409        fn reset(&mut self) {
410            self.returned = false;
411        }
412
413        fn name(&self) -> &'static str {
414            "MockScan"
415        }
416
417        fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
418            self
419        }
420    }
421
422    fn create_node_chunk(node_ids: &[i64]) -> DataChunk {
423        let mut col = ValueVector::with_type(LogicalType::Int64);
424        for &id in node_ids {
425            col.push_int64(id);
426        }
427        DataChunk::new(vec![col])
428    }
429
430    #[test]
431    fn test_leapfrog_binary_intersection() {
432        // Input 1: nodes [1, 2, 3, 5]
433        // Input 2: nodes [2, 3, 4, 5]
434        // Expected intersection: [2, 3, 5]
435
436        let chunk1 = create_node_chunk(&[1, 2, 3, 5]);
437        let chunk2 = create_node_chunk(&[2, 3, 4, 5]);
438
439        let op1: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk1));
440        let op2: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk2));
441
442        let mut leapfrog = LeapfrogJoinOperator::new(
443            vec![op1, op2],
444            vec![vec![0], vec![0]], // Join on first column of each
445            vec![LogicalType::Int64, LogicalType::Int64],
446            vec![(0, 0), (1, 0)], // Output both columns
447        );
448
449        let mut all_results = Vec::new();
450        while let Some(chunk) = leapfrog.next().unwrap() {
451            for row in 0..chunk.row_count() {
452                let val1 = chunk.column(0).unwrap().get_int64(row).unwrap();
453                let val2 = chunk.column(1).unwrap().get_int64(row).unwrap();
454                all_results.push((val1, val2));
455            }
456        }
457
458        // Should find 3 matches: (2,2), (3,3), (5,5)
459        assert_eq!(all_results.len(), 3);
460        assert!(all_results.contains(&(2, 2)));
461        assert!(all_results.contains(&(3, 3)));
462        assert!(all_results.contains(&(5, 5)));
463    }
464
465    #[test]
466    fn test_leapfrog_empty_intersection() {
467        // Input 1: nodes [1, 2, 3]
468        // Input 2: nodes [4, 5, 6]
469        // Expected: empty
470
471        let chunk1 = create_node_chunk(&[1, 2, 3]);
472        let chunk2 = create_node_chunk(&[4, 5, 6]);
473
474        let op1: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk1));
475        let op2: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk2));
476
477        let mut leapfrog = LeapfrogJoinOperator::new(
478            vec![op1, op2],
479            vec![vec![0], vec![0]],
480            vec![LogicalType::Int64, LogicalType::Int64],
481            vec![(0, 0), (1, 0)],
482        );
483
484        let result = leapfrog.next().unwrap();
485        assert!(result.is_none());
486    }
487
488    #[test]
489    fn test_leapfrog_reset() {
490        let chunk1 = create_node_chunk(&[1, 2, 3]);
491        let chunk2 = create_node_chunk(&[2, 3, 4]);
492
493        let op1: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk1.clone()));
494        let op2: Box<dyn Operator> = Box::new(MockScanOperator::new(chunk2.clone()));
495
496        let mut leapfrog = LeapfrogJoinOperator::new(
497            vec![op1, op2],
498            vec![vec![0], vec![0]],
499            vec![LogicalType::Int64, LogicalType::Int64],
500            vec![(0, 0), (1, 0)],
501        );
502
503        // First iteration - consume all results
504        let mut _count = 0;
505        while leapfrog.next().unwrap().is_some() {
506            _count += 1;
507        }
508
509        // Reset won't work with MockScanOperator since the chunk is taken
510        // but the reset logic itself should work
511        leapfrog.reset();
512        assert!(!leapfrog.materialized);
513        assert!(leapfrog.results.is_empty());
514    }
515
516    #[test]
517    fn test_encode_decode_row_id() {
518        let test_cases = [
519            (0, 0, 0),
520            (1, 2, 3),
521            (255, 16777215, 4294967295), // Max values for each field
522        ];
523
524        for (input_idx, chunk_idx, row) in test_cases {
525            let encoded = LeapfrogJoinOperator::encode_row_id(input_idx, chunk_idx, row);
526            let decoded = LeapfrogJoinOperator::decode_row_id(encoded);
527            assert_eq!(decoded, (input_idx, chunk_idx, row));
528        }
529    }
530}