linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! Extract equi-join keys from a Filter above a keyless InnerJoin.
//!
//! This rule identifies the Filter -> InnerJoin pattern where the join
//! carries no hash/probe keys (a cross product with the predicate evaluated
//! per pair above it) and moves cross-side equalities into the join keys.
//!
//! # Conversion example
//!
//! Before:
//! ```text
//!   Filter(a.value = b.value)
//!           |
//!   InnerJoin (no keys)
//!   /          \
//! Left        Right
//! ```
//!
//! After:
//! ```text
//!   InnerJoin (hash_keys=[b.value], probe_keys=[a.value])
//!   /          \
//! Left        Right
//! ```
//!
//! # Applicable Conditions
//!
//! - The InnerJoin has empty hash/probe keys (existing keys are never
//!   disturbed).
//! - A top-level `AND` conjunct is an `Equal` whose two sides each reference
//!   columns from exactly one join input (left/right or right/left).
//!   Anything else (single-side predicates, literals, non-equalities,
//!   ambiguous column references) stays in a residual Filter above the join.
//!
//! # Side convention
//!
//! The executor builds the hash table from the right child with `hash_keys`
//! and probes it with the left child using `probe_keys`
//! (`BuildSide::Right` default), so the right-side expression becomes a
//! hash key and the left-side expression a probe key.

use crate::optimizer::heuristic::context::RewriteContext;
use crate::optimizer::heuristic::pattern::Pattern;
use crate::optimizer::heuristic::result::{RewriteResult, TransformResult};
use crate::optimizer::heuristic::rule::RewriteRule;
use crate::planning::plan::core::nodes::base::plan_node_traits::SingleInputNode;
use crate::planning::plan::core::nodes::operation::filter_node::FilterNode;
use crate::planning::plan::PlanNodeEnum;
use linkrs_core::types::expr::contextual::ContextualExpression;
use linkrs_core::types::expr::expression_context::ExpressionAnalysisContext;
use linkrs_core::types::expr::visitor::ExpressionVisitor;
use linkrs_core::types::expr::visitor_collectors::VariableCollector;
use linkrs_core::types::expr::ExpressionMeta;
use linkrs_core::types::operators::BinaryOperator;
use linkrs_core::Expression;
use std::sync::Arc;

/// Extract equi-join keys from a Filter above a keyless InnerJoin.
#[derive(Debug)]
pub struct ExtractEquiJoinKeysRule;

impl ExtractEquiJoinKeysRule {
    /// Create a rule instance.
    pub fn new() -> Self {
        Self
    }

    /// Flatten a top-level `AND` chain into its conjuncts.
    fn flatten_conjuncts(expr: &Expression, out: &mut Vec<Expression>) {
        match expr {
            Expression::Binary {
                op: BinaryOperator::And,
                left,
                right,
            } => {
                Self::flatten_conjuncts(left, out);
                Self::flatten_conjuncts(right, out);
            }
            _ => out.push(expr.clone()),
        }
    }

    /// Collect the variable names referenced by an expression.
    fn referenced_variables(expr: &Expression) -> Vec<String> {
        let mut collector = VariableCollector::new();
        collector.visit(expr);
        collector.variables
    }

    /// Attribute an expression to exactly one join side.
    ///
    /// Returns `Some(true)` when every referenced variable belongs to the
    /// left input (and none to the right), `Some(false)` for the mirrored
    /// right case, and `None` when the expression is ambiguous (empty,
    /// single-side-unresolvable, or shared column names).
    fn is_left_side(vars: &[String], left_cols: &[String], right_cols: &[String]) -> Option<bool> {
        if vars.is_empty() {
            return None;
        }
        let in_left = vars.iter().all(|v| left_cols.contains(v));
        let in_right = vars.iter().all(|v| right_cols.contains(v));
        match (in_left, in_right) {
            (true, false) => Some(true),
            (false, true) => Some(false),
            _ => None,
        }
    }

    /// Register a key expression in the given context.
    fn register_key(
        expr: Expression,
        ctx: &Arc<ExpressionAnalysisContext>,
    ) -> ContextualExpression {
        let id = ctx.register_expression(ExpressionMeta::new(expr));
        ContextualExpression::new(id, ctx.clone())
    }

    /// Combine residual conjuncts back into a single `AND` expression,
    /// preserving the original left-to-right order.
    fn combine_residual(conjuncts: Vec<Expression>) -> Option<Expression> {
        let mut iter = conjuncts.into_iter();
        let first = iter.next()?;
        Some(iter.fold(first, |acc, next| Expression::Binary {
            left: Box::new(acc),
            op: BinaryOperator::And,
            right: Box::new(next),
        }))
    }
}

impl Default for ExtractEquiJoinKeysRule {
    fn default() -> Self {
        Self::new()
    }
}

impl RewriteRule for ExtractEquiJoinKeysRule {
    fn name(&self) -> &'static str {
        "ExtractEquiJoinKeysRule"
    }

    fn pattern(&self) -> Pattern {
        Pattern::new_with_name("Filter").with_dependency_name("InnerJoin")
    }

    fn apply(
        &self,
        _ctx: &mut RewriteContext,
        node: &PlanNodeEnum,
    ) -> RewriteResult<Option<TransformResult>> {
        let filter_node = match node {
            PlanNodeEnum::Filter(n) => n,
            _ => return Ok(None),
        };
        let join = match filter_node.input() {
            PlanNodeEnum::InnerJoin(n) => n,
            _ => return Ok(None),
        };
        // Never disturb joins that already carry keys.
        if !join.hash_keys().is_empty() || !join.probe_keys().is_empty() {
            return Ok(None);
        }

        let condition = filter_node.condition();
        let filter_expr = match condition.expression() {
            Some(meta) => meta.inner().clone(),
            None => return Ok(None),
        };
        let expr_ctx = condition.context().clone();

        let left_cols = join.left_input().col_names().to_vec();
        let right_cols = join.right_input().col_names().to_vec();

        let mut conjuncts = Vec::new();
        Self::flatten_conjuncts(&filter_expr, &mut conjuncts);

        let mut hash_keys = Vec::new();
        let mut probe_keys = Vec::new();
        let mut residual = Vec::new();

        for conjunct in conjuncts {
            // A usable key is an equality whose sides belong to opposite
            // join inputs. The left-input expression probes, the
            // right-input expression builds (see the module docs).
            let sides = match &conjunct {
                Expression::Binary {
                    op: BinaryOperator::Equal,
                    left,
                    right,
                } => {
                    let left_is_left = Self::is_left_side(
                        &Self::referenced_variables(left),
                        &left_cols,
                        &right_cols,
                    );
                    let right_is_left = Self::is_left_side(
                        &Self::referenced_variables(right),
                        &left_cols,
                        &right_cols,
                    );
                    match (left_is_left, right_is_left) {
                        (Some(true), Some(false)) => Some((left, right)),
                        (Some(false), Some(true)) => Some((right, left)),
                        _ => None,
                    }
                }
                _ => None,
            };
            match sides {
                Some((probe_side, hash_side)) => {
                    probe_keys.push(Self::register_key((**probe_side).clone(), &expr_ctx));
                    hash_keys.push(Self::register_key((**hash_side).clone(), &expr_ctx));
                }
                None => residual.push(conjunct),
            }
        }

        if hash_keys.is_empty() {
            return Ok(None);
        }

        let mut new_join = join.clone();
        new_join.set_hash_keys(hash_keys);
        new_join.set_probe_keys(probe_keys);
        let new_join_enum = PlanNodeEnum::InnerJoin(new_join);

        let mut result = TransformResult::new();
        result.erase_curr = true;
        if residual.is_empty() {
            result.add_new_node(new_join_enum);
        } else {
            let residual_expr = match Self::combine_residual(residual) {
                Some(expr) => expr,
                None => {
                    result.add_new_node(new_join_enum);
                    return Ok(Some(result));
                }
            };
            let residual_ctx_expr = Self::register_key(residual_expr, &expr_ctx);
            let new_filter = FilterNode::new(new_join_enum, residual_ctx_expr).map_err(|e| {
                crate::optimizer::heuristic::result::RewriteError::rewrite_failed(format!(
                    "Failed to create residual FilterNode: {:?}",
                    e
                ))
            })?;
            result.add_new_node(PlanNodeEnum::Filter(new_filter));
        }
        Ok(Some(result))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::planning::plan::core::nodes::access::graph_scan_node::ScanVerticesNode;
    use crate::planning::plan::core::nodes::join::join_node::InnerJoinNode;
    use linkrs_core::types::expr::expression_context::ExpressionAnalysisContext;

    fn scan_with_cols(space: &str, cols: &[&str]) -> PlanNodeEnum {
        let mut scan = ScanVerticesNode::new(1, space);
        scan.set_col_names(cols.iter().map(|s| s.to_string()).collect());
        PlanNodeEnum::ScanVertices(scan)
    }

    fn contextual(expr: Expression, ctx: &Arc<ExpressionAnalysisContext>) -> ContextualExpression {
        let id = ctx.register_expression(ExpressionMeta::new(expr));
        ContextualExpression::new(id, ctx.clone())
    }

    fn equality_filter(
        input: PlanNodeEnum,
        left: Expression,
        right: Expression,
        ctx: &Arc<ExpressionAnalysisContext>,
    ) -> PlanNodeEnum {
        let cond = Expression::Binary {
            left: Box::new(left),
            op: BinaryOperator::Equal,
            right: Box::new(right),
        };
        let filter = FilterNode::new(input, contextual(cond, ctx)).expect("filter");
        PlanNodeEnum::Filter(filter)
    }

    fn prop(var: &str, property: &str) -> Expression {
        Expression::Property {
            object: Box::new(Expression::variable(var)),
            property: property.to_string(),
        }
    }

    #[test]
    fn test_rule_name() {
        let rule = ExtractEquiJoinKeysRule::new();
        assert_eq!(rule.name(), "ExtractEquiJoinKeysRule");
    }

    #[test]
    fn test_rule_pattern() {
        let rule = ExtractEquiJoinKeysRule::new();
        let pattern = rule.pattern();
        assert!(pattern.node.is_some());
    }

    #[test]
    fn test_skips_join_with_existing_keys() {
        let ctx = Arc::new(ExpressionAnalysisContext::new());
        let left = scan_with_cols("s", &["a"]);
        let right = scan_with_cols("s", &["b"]);
        let key = contextual(Expression::variable("a"), &ctx);
        let join =
            InnerJoinNode::new(left, right, vec![key.clone()], vec![key]).expect("join with keys");
        let node = equality_filter(
            PlanNodeEnum::InnerJoin(join),
            prop("a", "value"),
            prop("b", "value"),
            &ctx,
        );
        let rule = ExtractEquiJoinKeysRule::new();
        let mut rewrite_ctx = RewriteContext::new();
        let out = rule.apply(&mut rewrite_ctx, &node).expect("apply");
        assert!(out.is_none(), "joins with keys must be left alone");
    }

    #[test]
    fn test_extracts_cross_side_equality() {
        let ctx = Arc::new(ExpressionAnalysisContext::new());
        let left = scan_with_cols("s", &["a"]);
        let right = scan_with_cols("s", &["b"]);
        let join = InnerJoinNode::new(left, right, vec![], vec![]).expect("keyless join");
        let node = equality_filter(
            PlanNodeEnum::InnerJoin(join),
            prop("a", "value"),
            prop("b", "value"),
            &ctx,
        );
        let rule = ExtractEquiJoinKeysRule::new();
        let mut rewrite_ctx = RewriteContext::new();
        let out = rule
            .apply(&mut rewrite_ctx, &node)
            .expect("apply")
            .expect("must fire");
        assert!(out.erase_curr);
        assert_eq!(out.new_nodes.len(), 1);
        match &out.new_nodes[0] {
            PlanNodeEnum::InnerJoin(j) => {
                assert_eq!(j.hash_keys().len(), 1);
                assert_eq!(j.probe_keys().len(), 1);
                // Build side (right) key references b, probe side (left) key
                // references a.
                let hash_vars = ExtractEquiJoinKeysRule::referenced_variables(
                    j.hash_keys()[0].expression().expect("hash").inner(),
                );
                let probe_vars = ExtractEquiJoinKeysRule::referenced_variables(
                    j.probe_keys()[0].expression().expect("probe").inner(),
                );
                assert_eq!(hash_vars, vec!["b".to_string()]);
                assert_eq!(probe_vars, vec!["a".to_string()]);
            }
            other => panic!("expected keyed InnerJoin, got {:?}", other.type_name()),
        }
    }

    #[test]
    fn test_extracts_mirrored_equality() {
        let ctx = Arc::new(ExpressionAnalysisContext::new());
        let left = scan_with_cols("s", &["a"]);
        let right = scan_with_cols("s", &["b"]);
        let join = InnerJoinNode::new(left, right, vec![], vec![]).expect("keyless join");
        // Equality written right-first: b.value = a.value.
        let node = equality_filter(
            PlanNodeEnum::InnerJoin(join),
            prop("b", "value"),
            prop("a", "value"),
            &ctx,
        );
        let rule = ExtractEquiJoinKeysRule::new();
        let mut rewrite_ctx = RewriteContext::new();
        let out = rule
            .apply(&mut rewrite_ctx, &node)
            .expect("apply")
            .expect("must fire");
        match &out.new_nodes[0] {
            PlanNodeEnum::InnerJoin(j) => {
                let hash_vars = ExtractEquiJoinKeysRule::referenced_variables(
                    j.hash_keys()[0].expression().expect("hash").inner(),
                );
                let probe_vars = ExtractEquiJoinKeysRule::referenced_variables(
                    j.probe_keys()[0].expression().expect("probe").inner(),
                );
                assert_eq!(hash_vars, vec!["b".to_string()]);
                assert_eq!(probe_vars, vec!["a".to_string()]);
            }
            other => panic!("expected keyed InnerJoin, got {:?}", other.type_name()),
        }
    }

    #[test]
    fn test_keeps_residual_filter() {
        let ctx = Arc::new(ExpressionAnalysisContext::new());
        let left = scan_with_cols("s", &["a"]);
        let right = scan_with_cols("s", &["b"]);
        let join = InnerJoinNode::new(left, right, vec![], vec![]).expect("keyless join");
        let equality = Expression::Binary {
            left: Box::new(prop("a", "value")),
            op: BinaryOperator::Equal,
            right: Box::new(prop("b", "value")),
        };
        let range = Expression::Binary {
            left: Box::new(prop("a", "value")),
            op: BinaryOperator::LessThan,
            right: Box::new(Expression::int(200)),
        };
        let cond = Expression::Binary {
            left: Box::new(equality),
            op: BinaryOperator::And,
            right: Box::new(range),
        };
        let filter =
            FilterNode::new(PlanNodeEnum::InnerJoin(join), contextual(cond, &ctx)).expect("filter");
        let node = PlanNodeEnum::Filter(filter);
        let rule = ExtractEquiJoinKeysRule::new();
        let mut rewrite_ctx = RewriteContext::new();
        let out = rule
            .apply(&mut rewrite_ctx, &node)
            .expect("apply")
            .expect("must fire");
        assert_eq!(out.new_nodes.len(), 1);
        match &out.new_nodes[0] {
            PlanNodeEnum::Filter(f) => match f.input() {
                PlanNodeEnum::InnerJoin(j) => {
                    assert_eq!(j.hash_keys().len(), 1);
                    assert_eq!(j.probe_keys().len(), 1);
                }
                other => panic!(
                    "residual filter must sit above keyed join, got {:?}",
                    other.type_name()
                ),
            },
            other => panic!("expected residual Filter, got {:?}", other.type_name()),
        }
    }

    #[test]
    fn test_ignores_single_side_predicate() {
        let ctx = Arc::new(ExpressionAnalysisContext::new());
        let left = scan_with_cols("s", &["a"]);
        let right = scan_with_cols("s", &["b"]);
        let join = InnerJoinNode::new(left, right, vec![], vec![]).expect("keyless join");
        let range = Expression::Binary {
            left: Box::new(prop("a", "value")),
            op: BinaryOperator::LessThan,
            right: Box::new(Expression::int(200)),
        };
        let filter = FilterNode::new(PlanNodeEnum::InnerJoin(join), contextual(range, &ctx))
            .expect("filter");
        let node = PlanNodeEnum::Filter(filter);
        let rule = ExtractEquiJoinKeysRule::new();
        let mut rewrite_ctx = RewriteContext::new();
        let out = rule.apply(&mut rewrite_ctx, &node).expect("apply");
        assert!(out.is_none(), "single-side predicates are not join keys");
    }
}