Skip to main content

grafeo_core/execution/operators/
expand.rs

1//! Expand operator for relationship traversal.
2
3use super::{Operator, OperatorError, OperatorResult};
4use crate::execution::DataChunk;
5use crate::graph::Direction;
6use crate::graph::lpg::LpgStore;
7use grafeo_common::types::{EdgeId, EpochId, LogicalType, NodeId, TxId};
8use std::sync::Arc;
9
10/// An expand operator that traverses edges from source nodes.
11///
12/// For each input row containing a source node, this operator produces
13/// output rows for each neighbor connected via matching edges.
14pub struct ExpandOperator {
15    /// The store to traverse.
16    store: Arc<LpgStore>,
17    /// Input operator providing source nodes.
18    input: Box<dyn Operator>,
19    /// Index of the source node column in input.
20    source_column: usize,
21    /// Direction of edge traversal.
22    direction: Direction,
23    /// Optional edge type filter.
24    edge_type: Option<String>,
25    /// Chunk capacity.
26    chunk_capacity: usize,
27    /// Current input chunk being processed.
28    current_input: Option<DataChunk>,
29    /// Current row index in the input chunk.
30    current_row: usize,
31    /// Current edge iterator for the current row.
32    current_edges: Vec<(NodeId, EdgeId)>,
33    /// Current edge index.
34    current_edge_idx: usize,
35    /// Whether the operator is exhausted.
36    exhausted: bool,
37    /// Transaction ID for MVCC visibility (None = use current epoch).
38    tx_id: Option<TxId>,
39    /// Epoch for version visibility.
40    viewing_epoch: Option<EpochId>,
41}
42
43impl ExpandOperator {
44    /// Creates a new expand operator.
45    pub fn new(
46        store: Arc<LpgStore>,
47        input: Box<dyn Operator>,
48        source_column: usize,
49        direction: Direction,
50        edge_type: Option<String>,
51    ) -> Self {
52        Self {
53            store,
54            input,
55            source_column,
56            direction,
57            edge_type,
58            chunk_capacity: 2048,
59            current_input: None,
60            current_row: 0,
61            current_edges: Vec::with_capacity(16), // typical node degree
62            current_edge_idx: 0,
63            exhausted: false,
64            tx_id: None,
65            viewing_epoch: None,
66        }
67    }
68
69    /// Sets the chunk capacity.
70    pub fn with_chunk_capacity(mut self, capacity: usize) -> Self {
71        self.chunk_capacity = capacity;
72        self
73    }
74
75    /// Sets the transaction context for MVCC visibility.
76    ///
77    /// When set, the expand will only traverse visible edges and nodes.
78    pub fn with_tx_context(mut self, epoch: EpochId, tx_id: Option<TxId>) -> Self {
79        self.viewing_epoch = Some(epoch);
80        self.tx_id = tx_id;
81        self
82    }
83
84    /// Loads the next input chunk.
85    fn load_next_input(&mut self) -> Result<bool, OperatorError> {
86        match self.input.next() {
87            Ok(Some(mut chunk)) => {
88                // Flatten the chunk if it has a selection vector so we can use direct indexing
89                chunk.flatten();
90                self.current_input = Some(chunk);
91                self.current_row = 0;
92                self.current_edges.clear();
93                self.current_edge_idx = 0;
94                Ok(true)
95            }
96            Ok(None) => {
97                self.exhausted = true;
98                Ok(false)
99            }
100            Err(e) => Err(e),
101        }
102    }
103
104    /// Loads edges for the current row.
105    fn load_edges_for_current_row(&mut self) -> Result<bool, OperatorError> {
106        let chunk = match &self.current_input {
107            Some(c) => c,
108            None => return Ok(false),
109        };
110
111        if self.current_row >= chunk.row_count() {
112            return Ok(false);
113        }
114
115        let col = chunk.column(self.source_column).ok_or_else(|| {
116            OperatorError::ColumnNotFound(format!("Column {} not found", self.source_column))
117        })?;
118
119        let source_id = col
120            .get_node_id(self.current_row)
121            .ok_or_else(|| OperatorError::Execution("Expected node ID in source column".into()))?;
122
123        // Get visibility context
124        let epoch = self.viewing_epoch;
125        let tx = self.tx_id.unwrap_or(TxId::SYSTEM);
126
127        // Get edges from this node
128        let edges: Vec<(NodeId, EdgeId)> = self
129            .store
130            .edges_from(source_id, self.direction)
131            .filter(|(target_id, edge_id)| {
132                // Filter by edge type if specified
133                let type_matches = if let Some(ref filter_type) = self.edge_type {
134                    if let Some(edge_type) = self.store.edge_type(*edge_id) {
135                        edge_type
136                            .as_str()
137                            .eq_ignore_ascii_case(filter_type.as_str())
138                    } else {
139                        false
140                    }
141                } else {
142                    true
143                };
144
145                if !type_matches {
146                    return false;
147                }
148
149                // Filter by visibility if we have tx context
150                if let Some(epoch) = epoch {
151                    // Check if edge and target node are visible
152                    let edge_visible = self.store.get_edge_versioned(*edge_id, epoch, tx).is_some();
153                    let target_visible = self
154                        .store
155                        .get_node_versioned(*target_id, epoch, tx)
156                        .is_some();
157                    edge_visible && target_visible
158                } else {
159                    true
160                }
161            })
162            .collect();
163
164        self.current_edges = edges;
165        self.current_edge_idx = 0;
166        Ok(true)
167    }
168}
169
170impl Operator for ExpandOperator {
171    fn next(&mut self) -> OperatorResult {
172        if self.exhausted {
173            return Ok(None);
174        }
175
176        // Build output schema: preserve all input columns + edge + target
177        // We need to build this dynamically based on input schema
178        if self.current_input.is_none() {
179            if !self.load_next_input()? {
180                return Ok(None);
181            }
182            self.load_edges_for_current_row()?;
183        }
184        let input_chunk = self.current_input.as_ref().expect("input loaded above");
185
186        // Build schema: [input_columns..., edge, target]
187        let input_col_count = input_chunk.column_count();
188        let mut schema: Vec<LogicalType> = (0..input_col_count)
189            .map(|i| {
190                input_chunk
191                    .column(i)
192                    .map_or(LogicalType::Any, |c| c.data_type().clone())
193            })
194            .collect();
195        schema.push(LogicalType::Edge);
196        schema.push(LogicalType::Node);
197
198        let mut chunk = DataChunk::with_capacity(&schema, self.chunk_capacity);
199        let mut count = 0;
200
201        while count < self.chunk_capacity {
202            // If we need a new input chunk
203            if self.current_input.is_none() {
204                if !self.load_next_input()? {
205                    break;
206                }
207                self.load_edges_for_current_row()?;
208            }
209
210            // If we've exhausted edges for current row, move to next row
211            while self.current_edge_idx >= self.current_edges.len() {
212                self.current_row += 1;
213
214                // If we've exhausted the current input chunk, get next one
215                if self.current_row >= self.current_input.as_ref().map_or(0, |c| c.row_count()) {
216                    self.current_input = None;
217                    if !self.load_next_input()? {
218                        // No more input chunks
219                        if count > 0 {
220                            chunk.set_count(count);
221                            return Ok(Some(chunk));
222                        }
223                        return Ok(None);
224                    }
225                }
226
227                self.load_edges_for_current_row()?;
228            }
229
230            // Get the current edge
231            let (target_id, edge_id) = self.current_edges[self.current_edge_idx];
232
233            // Copy all input columns to output
234            let input = self.current_input.as_ref().unwrap();
235            for col_idx in 0..input_col_count {
236                if let Some(input_col) = input.column(col_idx) {
237                    if let Some(output_col) = chunk.column_mut(col_idx) {
238                        // Use copy_row_to which preserves NodeId/EdgeId types
239                        input_col.copy_row_to(self.current_row, output_col);
240                    }
241                }
242            }
243
244            // Add edge column
245            if let Some(col) = chunk.column_mut(input_col_count) {
246                col.push_edge_id(edge_id);
247            }
248
249            // Add target node column
250            if let Some(col) = chunk.column_mut(input_col_count + 1) {
251                col.push_node_id(target_id);
252            }
253
254            count += 1;
255            self.current_edge_idx += 1;
256        }
257
258        if count > 0 {
259            chunk.set_count(count);
260            Ok(Some(chunk))
261        } else {
262            Ok(None)
263        }
264    }
265
266    fn reset(&mut self) {
267        self.input.reset();
268        self.current_input = None;
269        self.current_row = 0;
270        self.current_edges.clear();
271        self.current_edge_idx = 0;
272        self.exhausted = false;
273    }
274
275    fn name(&self) -> &'static str {
276        "Expand"
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use crate::execution::operators::ScanOperator;
284
285    #[test]
286    fn test_expand_outgoing() {
287        let store = Arc::new(LpgStore::new());
288
289        // Create nodes
290        let alice = store.create_node(&["Person"]);
291        let bob = store.create_node(&["Person"]);
292        let charlie = store.create_node(&["Person"]);
293
294        // Create edges: Alice -> Bob, Alice -> Charlie
295        store.create_edge(alice, bob, "KNOWS");
296        store.create_edge(alice, charlie, "KNOWS");
297
298        // Scan Alice only
299        let scan = Box::new(ScanOperator::with_label(Arc::clone(&store), "Person"));
300
301        let mut expand = ExpandOperator::new(
302            Arc::clone(&store),
303            scan,
304            0, // source column
305            Direction::Outgoing,
306            None,
307        );
308
309        // Collect all results
310        let mut results = Vec::new();
311        while let Ok(Some(chunk)) = expand.next() {
312            for i in 0..chunk.row_count() {
313                let src = chunk.column(0).unwrap().get_node_id(i).unwrap();
314                let edge = chunk.column(1).unwrap().get_edge_id(i).unwrap();
315                let dst = chunk.column(2).unwrap().get_node_id(i).unwrap();
316                results.push((src, edge, dst));
317            }
318        }
319
320        // Alice -> Bob, Alice -> Charlie
321        assert_eq!(results.len(), 2);
322
323        // All source nodes should be Alice
324        for (src, _, _) in &results {
325            assert_eq!(*src, alice);
326        }
327
328        // Target nodes should be Bob and Charlie
329        let targets: Vec<NodeId> = results.iter().map(|(_, _, dst)| *dst).collect();
330        assert!(targets.contains(&bob));
331        assert!(targets.contains(&charlie));
332    }
333
334    #[test]
335    fn test_expand_with_edge_type_filter() {
336        let store = Arc::new(LpgStore::new());
337
338        let alice = store.create_node(&["Person"]);
339        let bob = store.create_node(&["Person"]);
340        let company = store.create_node(&["Company"]);
341
342        store.create_edge(alice, bob, "KNOWS");
343        store.create_edge(alice, company, "WORKS_AT");
344
345        let scan = Box::new(ScanOperator::with_label(Arc::clone(&store), "Person"));
346
347        let mut expand = ExpandOperator::new(
348            Arc::clone(&store),
349            scan,
350            0,
351            Direction::Outgoing,
352            Some("KNOWS".to_string()),
353        );
354
355        let mut results = Vec::new();
356        while let Ok(Some(chunk)) = expand.next() {
357            for i in 0..chunk.row_count() {
358                let dst = chunk.column(2).unwrap().get_node_id(i).unwrap();
359                results.push(dst);
360            }
361        }
362
363        // Only KNOWS edges should be followed
364        assert_eq!(results.len(), 1);
365        assert_eq!(results[0], bob);
366    }
367
368    #[test]
369    fn test_expand_incoming() {
370        let store = Arc::new(LpgStore::new());
371
372        let alice = store.create_node(&["Person"]);
373        let bob = store.create_node(&["Person"]);
374
375        store.create_edge(alice, bob, "KNOWS");
376
377        // Scan Bob
378        let scan = Box::new(ScanOperator::with_label(Arc::clone(&store), "Person"));
379
380        let mut expand =
381            ExpandOperator::new(Arc::clone(&store), scan, 0, Direction::Incoming, None);
382
383        let mut results = Vec::new();
384        while let Ok(Some(chunk)) = expand.next() {
385            for i in 0..chunk.row_count() {
386                let src = chunk.column(0).unwrap().get_node_id(i).unwrap();
387                let dst = chunk.column(2).unwrap().get_node_id(i).unwrap();
388                results.push((src, dst));
389            }
390        }
391
392        // Bob <- Alice (Bob's incoming edge from Alice)
393        assert_eq!(results.len(), 1);
394        assert_eq!(results[0].0, bob); // source in the expand is Bob
395        assert_eq!(results[0].1, alice); // target is Alice (who points to Bob)
396    }
397
398    #[test]
399    fn test_expand_no_edges() {
400        let store = Arc::new(LpgStore::new());
401
402        store.create_node(&["Person"]);
403
404        let scan = Box::new(ScanOperator::with_label(Arc::clone(&store), "Person"));
405
406        let mut expand =
407            ExpandOperator::new(Arc::clone(&store), scan, 0, Direction::Outgoing, None);
408
409        let result = expand.next().unwrap();
410        assert!(result.is_none());
411    }
412}