grafeo_core/execution/operators/
leapfrog_join.rs1use 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
16type RowId = (usize, usize, usize);
18
19struct JoinResult {
21 row_ids: Vec<Vec<RowId>>,
23}
24
25pub struct LeapfrogJoinOperator {
30 inputs: Vec<Box<dyn Operator>>,
32
33 join_key_indices: Vec<Vec<usize>>,
36
37 output_schema: Vec<LogicalType>,
39
40 output_column_mapping: Vec<(usize, usize)>,
42
43 materialized_inputs: Vec<Vec<DataChunk>>,
46
47 tries: Vec<TrieIndex>,
49
50 materialized: bool,
52
53 results: Vec<JoinResult>,
56
57 result_position: usize,
59
60 expansion_indices: Vec<usize>,
62
63 exhausted: bool,
65}
66
67impl LeapfrogJoinOperator {
68 #[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 fn materialize_inputs(&mut self) -> Result<(), OperatorError> {
99 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 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 if let Some(path) = self.extract_join_keys(chunk, row, key_indices) {
117 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 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 LogicalType::Int64 => col.get_int64(row).map(|i| {
146 #[allow(clippy::cast_sign_loss)]
148 NodeId::new(i as u64)
149 }),
150 _ => return None, }?;
152 path.push(node_id);
153 }
154
155 Some(path)
156 }
157
158 fn encode_row_id(input_idx: usize, chunk_idx: usize, row: usize) -> EdgeId {
160 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 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 fn execute_leapfrog(&mut self) -> Result<(), OperatorError> {
178 if self.tries.is_empty() {
179 return Ok(());
180 }
181
182 let iters: Vec<_> = self.tries.iter().map(|t| t.iter()).collect();
184
185 let mut join = LeapfrogJoin::new(iters);
187
188 while let Some(key) = join.key() {
190 let mut row_ids_per_input: Vec<Vec<RowId>> = vec![Vec::new(); self.tries.len()];
192
193 if let Some(child_iters) = join.open() {
195 for (input_idx, _child_iter) in child_iters.into_iter().enumerate() {
196 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 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 if !self.results.is_empty() {
221 self.expansion_indices = vec![0; self.inputs.len()];
222 }
223
224 Ok(())
225 }
226
227 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 if let Some(edges) = trie.get(&[key]) {
237 for &edge_id in edges {
238 let decoded = Self::decode_row_id(edge_id);
239 if decoded.0 == input_idx {
241 row_ids.push(decoded);
242 }
243 }
244 }
245
246 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 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 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 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 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 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 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 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 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 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]], vec![LogicalType::Int64, LogicalType::Int64],
446 vec![(0, 0), (1, 0)], );
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 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 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 let mut _count = 0;
505 while leapfrog.next().unwrap().is_some() {
506 _count += 1;
507 }
508
509 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), ];
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}