aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Predicate Pushdown Optimization
//!
//! Moves filter operations as close to data sources as possible,
//! reducing the number of rows processed by expensive operations
//! like traversals and joins.
//!
//! # Theory: Filter Early
//!
//! The "Filter Early" principle is fundamental to query optimization. By applying
//! predicates (filters) as early as possible in the query pipeline, we reduce the
//! cardinality (number of rows) that subsequent operators must process.
//!
//! For example, if a `VectorRank` operation is O(N log k) (with limit k) and a filter
//! removes 90% of the rows, pushing the filter before the rank significantly reduces
//! the workload.
//!
//! # Optimization Strategy
//!
//! This rule recursively traverses the logical plan and attempts to "bubble down"
//! `Filter` operators through other unary operators where safe.
//!
//! ## Capabilities
//!
//! Currently, this rule supports pushing filters through:
//! - **VectorRank (without limit)**: Safe because ranking all items then filtering produces the same result as filtering then ranking.
//! - **Sort**: Sorting is commutative with filtering.
//!
//! ## Limitations
//!
//! - **VectorRank (with limit)**: Cannot push filter past a Top-K operation. Filtering *after* finding top-K is semantically different from finding top-K *after* filtering.
//! - **Traversals**: We conservatively do *not* push filters through traversals yet.
//! - **Scans**: Filters cannot be pushed below scans (they are the leaves).
//! - **Joins**: Filter pushdown through joins is handled by separate logic (future work).
//!
//! # Safety
//!
//! Pushdown is safe when:
//! 1. **No Side Effects**: The operator being swapped doesn't produce side effects that the filter depends on.
//! 2. **Semantic Equivalence**: The result set remains identical.
//!    - **CRITICAL**: Filters must NOT be pushed past `Limit` or `Top-K` operations, as this changes the result set.

use crate::core::error::Result;
use crate::query::plan::{LogicalOp, LogicalPlan, UnaryOp};

use super::{OptimizationRule, Statistics};

/// Predicate pushdown optimization rule.
///
/// This rule moves Filter operations below Traverse and other operations
/// when possible, reducing intermediate result sizes.
///
/// # Example Transformation
///
/// **Before**: Filter is applied *after* sorting (expensive).
/// ```text
/// Filter(name = "Alice")
///   Sort(score DESC)
///     VectorSearch(...)
/// ```
///
/// **After**: Filter is applied *before* sorting (cheaper).
/// ```text
/// Sort(score DESC)
///   Filter(name = "Alice")
///     VectorSearch(...)
/// ```
///
/// # Complex Example
///
/// Pushing through multiple layers:
///
/// ```text
/// Filter(active = true)
///   Sort(created DESC)
///     VectorRank(top_k=None)
///       Scan(...)
/// ```
///
/// Becomes:
///
/// ```text
/// Sort(created DESC)
///   VectorRank(top_k=None)
///     Filter(active = true)  <-- Pushed down
///       Scan(...)
/// ```
///
/// ## Examples
///
/// ```rust
/// use aletheiadb::query::planner::rules::{OptimizationRule, PredicatePushdown};
/// use aletheiadb::query::planner::stats::Statistics;
/// use aletheiadb::query::plan::{LogicalPlan, LogicalOp, UnaryOp, ScanOp, SortKey};
/// use aletheiadb::query::ir::{Predicate, PredicateValue};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // 1. Construct a sub-optimal plan: Filter is applied AFTER sorting
/// let scan = LogicalOp::Scan(ScanOp::NodeScan {
///     label: Some("Person".into()),
///     estimated_rows: Some(100),
/// });
/// let sort = LogicalOp::unary(
///     UnaryOp::Sort { key: SortKey::Score, descending: true },
///     scan
/// );
/// let filter = LogicalOp::unary(
///     UnaryOp::Filter(Predicate::Eq { key: "active".into(), value: PredicateValue::Bool(true) }),
///     sort
/// );
///
/// let plan = LogicalPlan::new(filter);
///
/// // 2. Apply the rule
/// let rule = PredicatePushdown;
/// let stats = Statistics::new();
/// let optimized_plan = rule.apply(&plan, &stats)?.unwrap();
///
/// // 3. The rule pushed the Filter BELOW the Sort
/// let expected_plan = LogicalPlan::new(
///     LogicalOp::unary(
///         UnaryOp::Sort { key: SortKey::Score, descending: true },
///         LogicalOp::unary(
///             UnaryOp::Filter(Predicate::Eq { key: "active".into(), value: PredicateValue::Bool(true) }),
///             LogicalOp::Scan(ScanOp::NodeScan { label: Some("Person".into()), estimated_rows: Some(100) })
///         )
///     )
/// );
/// assert_eq!(optimized_plan, expected_plan);
/// # Ok(())
/// # }
/// ```
pub struct PredicatePushdown;

impl OptimizationRule for PredicatePushdown {
    fn name(&self) -> &str {
        "predicate-pushdown"
    }

    fn apply(&self, plan: &LogicalPlan, _stats: &Statistics) -> Result<Option<LogicalPlan>> {
        let (new_root, changed) = self.push_down(&plan.root)?;

        if changed {
            Ok(Some(LogicalPlan {
                root: new_root,
                temporal_context: plan.temporal_context.clone(),
                hints: plan.hints.clone(),
            }))
        } else {
            Ok(None)
        }
    }
}

impl PredicatePushdown {
    /// Recursively push down filters where possible.
    ///
    /// This method traverses the plan tree. When it encounters a `Filter` operator,
    /// it attempts to move it below its input operator if that operator type allows it.
    fn push_down(&self, op: &LogicalOp) -> Result<(LogicalOp, bool)> {
        match op {
            // Filter operation: this is what we want to push down
            LogicalOp::Unary {
                op: UnaryOp::Filter(predicate),
                input,
            } => {
                // First, recursively optimize the input (bottom-up approach)
                let (optimized_input, input_changed) = self.push_down(input)?;

                // Check if we can push the filter below the optimized input operator
                match &optimized_input {
                    // STOP: Can't push below scans (they are the source)
                    LogicalOp::Scan(_) => Ok((
                        LogicalOp::unary(UnaryOp::Filter(predicate.clone()), optimized_input),
                        input_changed,
                    )),

                    // STOP: For traversal, we generally can't push blindly.
                    // We need to know if the predicate applies to the source or target.
                    // Current implementation is conservative and stops here.
                    LogicalOp::Unary {
                        op: UnaryOp::Traverse { .. },
                        ..
                    } => Ok((
                        LogicalOp::unary(UnaryOp::Filter(predicate.clone()), optimized_input),
                        input_changed,
                    )),

                    // PUSH: VectorRank
                    // Only safe if top_k is None (pure re-scoring).
                    // If top_k is set, pushing filter changes semantics (Top-K then Filter != Filter then Top-K).
                    LogicalOp::Unary {
                        op:
                            UnaryOp::VectorRank {
                                embedding,
                                top_k,
                                property_key,
                            },
                        input: vector_input,
                    } => {
                        if top_k.is_some() {
                            // STOP: Has limit, unsafe to push down
                            Ok((
                                LogicalOp::unary(
                                    UnaryOp::Filter(predicate.clone()),
                                    optimized_input,
                                ),
                                input_changed,
                            ))
                        } else {
                            // SAFE: No limit, just re-scoring
                            let filter_then_rank = LogicalOp::unary(
                                UnaryOp::VectorRank {
                                    embedding: embedding.clone(),
                                    top_k: *top_k,
                                    property_key: property_key.clone(),
                                },
                                LogicalOp::unary(
                                    UnaryOp::Filter(predicate.clone()),
                                    (**vector_input).clone(),
                                ),
                            );
                            Ok((filter_then_rank, true))
                        }
                    }

                    // PUSH: Sort
                    // Filter(Sort(Input)) -> Sort(Filter(Input))
                    // Safe because sorting is purely a reordering operation.
                    LogicalOp::Unary {
                        op: UnaryOp::Sort { key, descending },
                        input: sort_input,
                    } => {
                        let filter_then_sort = LogicalOp::unary(
                            UnaryOp::Sort {
                                key: key.clone(),
                                descending: *descending,
                            },
                            LogicalOp::unary(
                                UnaryOp::Filter(predicate.clone()),
                                (**sort_input).clone(),
                            ),
                        );
                        Ok((filter_then_sort, true))
                    }

                    // Default: STOP. Keep filter where it is.
                    _ => Ok((
                        LogicalOp::unary(UnaryOp::Filter(predicate.clone()), optimized_input),
                        input_changed,
                    )),
                }
            }

            // Not a filter: just recurse down (pass-through)
            LogicalOp::Unary { op, input } => {
                let (optimized_input, changed) = self.push_down(input)?;
                Ok((LogicalOp::unary(op.clone(), optimized_input), changed))
            }

            // Binary op: recurse down both branches
            LogicalOp::Binary { op, left, right } => {
                let (opt_left, left_changed) = self.push_down(left)?;
                let (opt_right, right_changed) = self.push_down(right)?;
                Ok((
                    LogicalOp::binary(op.clone(), opt_left, opt_right),
                    left_changed || right_changed,
                ))
            }

            // Leaf nodes: no change possible
            LogicalOp::Scan(_) | LogicalOp::Empty => Ok((op.clone(), false)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::NodeId;
    use crate::query::ir::Predicate;
    use crate::query::plan::{ScanOp, SortKey};
    use std::sync::Arc;

    fn test_stats() -> Statistics {
        Statistics::default()
    }

    #[test]
    fn test_no_change_on_simple_filter() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("name", "Alice")),
            LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        assert!(result.is_none()); // No change needed
    }

    #[test]
    fn test_push_filter_below_vector_rank_no_limit() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter(VectorRank(top_k=None, Scan)) -> VectorRank(Filter(Scan))
        // Should push down because no limit
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("name", "Alice")),
            LogicalOp::unary(
                UnaryOp::VectorRank {
                    embedding: Arc::from([0.1f32; 4].as_slice()),
                    top_k: None,
                    property_key: None,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();

        let expected_plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::VectorRank {
                embedding: Arc::from([0.1f32; 4].as_slice()),
                top_k: None,
                property_key: None,
            },
            LogicalOp::unary(
                UnaryOp::Filter(Predicate::eq("name", "Alice")),
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        assert_eq!(result, Some(expected_plan));
    }

    #[test]
    fn test_stop_filter_at_traverse() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter(Traverse(Scan))
        // Should NOT push down because we stop at traversals
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("name", "Alice")),
            LogicalOp::unary(
                UnaryOp::Traverse {
                    label: None,
                    direction: crate::query::ir::Direction::Outgoing,
                    depth: crate::query::ir::TraversalDepth::Exact(1),
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        // Should return None because pushdown was blocked
        assert!(result.is_none());
    }

    #[test]
    fn test_stop_filter_at_scan() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter(Scan)
        // Should NOT push down because we stop at scans
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("name", "Alice")),
            LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        // Should return None because pushdown was blocked by Scan
        assert!(result.is_none());
    }

    #[test]
    fn test_stop_filter_at_vector_rank_with_limit() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter(VectorRank(top_k=Some(10), Scan))
        // Should NOT push down because limit exists
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("name", "Alice")),
            LogicalOp::unary(
                UnaryOp::VectorRank {
                    embedding: Arc::from([0.1f32; 4].as_slice()),
                    top_k: Some(10),
                    property_key: None,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        // Should return None because pushdown was blocked
        assert!(result.is_none());
    }

    #[test]
    fn test_push_filter_below_sort() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter(Sort(Scan)) -> Sort(Filter(Scan))
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("active", true)),
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("created".to_string()),
                    descending: true,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();

        let expected_plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Sort {
                key: SortKey::Property("created".to_string()),
                descending: true,
            },
            LogicalOp::unary(
                UnaryOp::Filter(Predicate::eq("active", true)),
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        assert_eq!(result, Some(expected_plan));
    }

    #[test]
    fn test_multi_level_pushdown() {
        let rule = PredicatePushdown;
        let stats = test_stats();

        // Filter -> Sort -> VectorRank(no limit) -> Scan
        // Should become: Sort -> VectorRank -> Filter -> Scan
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("active", true)),
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("created".to_string()),
                    descending: true,
                },
                LogicalOp::unary(
                    UnaryOp::VectorRank {
                        embedding: Arc::from([0.1f32; 4].as_slice()),
                        top_k: None,
                        property_key: None,
                    },
                    LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
                ),
            ),
        ));

        // Simulate planner loop to get full pushdown
        let mut current_plan = plan;
        let mut changed = true;
        let mut iterations = 0;

        while changed && iterations < 10 {
            let result = rule.apply(&current_plan, &stats).unwrap();
            if let Some(new_plan) = result {
                current_plan = new_plan;
                changed = true;
            } else {
                changed = false;
            }
            iterations += 1;
        }

        // Now verify full pushdown: Sort -> VectorRank -> Filter -> Scan
        let expected_plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Sort {
                key: SortKey::Property("created".to_string()),
                descending: true,
            },
            LogicalOp::unary(
                UnaryOp::VectorRank {
                    embedding: Arc::from([0.1f32; 4].as_slice()),
                    top_k: None,
                    property_key: None,
                },
                LogicalOp::unary(
                    UnaryOp::Filter(Predicate::eq("active", true)),
                    LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
                ),
            ),
        ));

        assert_eq!(current_plan, expected_plan);
    }

    #[test]
    fn test_binary_op_recursion_logic() {
        use crate::query::plan::BinaryOp;

        let rule = PredicatePushdown;
        let stats = test_stats();

        // Binary(Union, Filter(Sort(Scan)), Scan)
        // Left side: Filter(Sort(Scan)) -> Sort(Filter(Scan)) (Optimized, changed=true)
        // Right side: Scan -> Scan (No change, changed=false)
        // Total change: true || false = true

        let left_op = LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("active", true)),
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("created".to_string()),
                    descending: true,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        );

        let right_op = LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(2).unwrap()]));

        let plan = LogicalPlan::new(LogicalOp::binary(BinaryOp::Union, left_op, right_op));

        // Expect optimization to occur on the left branch
        let result = rule.apply(&plan, &stats).unwrap();

        let expected_plan = LogicalPlan::new(LogicalOp::binary(
            BinaryOp::Union,
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("created".to_string()),
                    descending: true,
                },
                LogicalOp::unary(
                    UnaryOp::Filter(Predicate::eq("active", true)),
                    LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
                ),
            ),
            LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(2).unwrap()])),
        ));

        assert_eq!(
            result,
            Some(expected_plan),
            "Binary op with one changed branch should return Some"
        );
    }
}

#[cfg(test)]
mod sentry_tests {
    use super::*;

    #[test]
    fn test_apply_unchanged() {
        let rule = PredicatePushdown;
        let stats = Statistics::default();
        let plan = LogicalPlan::new(LogicalOp::Scan(ScanOp::NodeLookup(vec![
            NodeId::new(1).unwrap(),
        ])));
        let result = rule.apply(&plan, &stats).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_apply_changed() {
        let rule = PredicatePushdown;
        let stats = Statistics::default();
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("a", 1)),
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("a".to_string()),
                    descending: true,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));
        let result = rule.apply(&plan, &stats).unwrap();
        assert!(result.is_some());
    }

    #[test]
    fn test_pushdown_traverse() {
        let rule = PredicatePushdown;
        let stats = Statistics::default();

        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("a", 1)),
            LogicalOp::unary(
                UnaryOp::Traverse {
                    label: None,
                    direction: crate::query::ir::Direction::Outgoing,
                    depth: crate::query::ir::TraversalDepth::Exact(1),
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        // Filter cannot push past Traverse
        assert!(result.is_none());
    }
    #[test]
    fn test_pushdown_unsupported_unary_op() {
        let rule = PredicatePushdown;
        let stats = Statistics::default();

        // Filter inside an unsupported UnaryOp (like Limit) should be passed through
        // but limit itself cannot be pushed down into.
        let plan = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Limit(10),
            LogicalOp::unary(
                UnaryOp::Filter(Predicate::eq("a", 1)),
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result = rule.apply(&plan, &stats).unwrap();
        // Since Filter is directly above Scan, it doesn't change.
        // Limit -> Filter -> Scan
        // push_down(Limit(Filter(Scan))) -> Limit(push_down(Filter(Scan))) -> Limit(Filter(Scan))
        assert!(result.is_none());

        let plan2 = LogicalPlan::new(LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("a", 1)),
            LogicalOp::unary(
                UnaryOp::Limit(10),
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        ));

        let result2 = rule.apply(&plan2, &stats).unwrap();
        // Filter cannot push past Limit
        assert!(result2.is_none());
    }
    #[test]
    fn test_pushdown_name() {
        let rule = PredicatePushdown;
        assert_eq!(rule.name(), "predicate-pushdown");
    }

    use crate::core::NodeId;
    use crate::query::ir::Predicate;
    use crate::query::plan::{BinaryOp, ScanOp, SortKey};

    #[test]
    fn test_binary_op_partial_optimization() {
        // 🎯 Target: LogicalOp::Binary optimization logic (|| vs &&)
        // 💣 Risk: If changed logic uses &&, partial optimizations (one branch changed) would be lost.

        let rule = PredicatePushdown;
        let stats = Statistics::default();

        // Left: Filter(Sort(Scan)) -> Should change to Sort(Filter(Scan))
        let left = LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("a", 1)),
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("a".to_string()),
                    descending: true,
                },
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
            ),
        );

        // Right: Filter(Scan) -> Should NOT change
        let right = LogicalOp::unary(
            UnaryOp::Filter(Predicate::eq("b", 2)),
            LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(2).unwrap()])),
        );

        // Binary Op: Union(Left, Right)
        let root = LogicalOp::binary(BinaryOp::Union, left, right);

        let plan = LogicalPlan::new(root);

        let result = rule.apply(&plan, &stats).unwrap();

        let expected_plan = LogicalPlan::new(LogicalOp::binary(
            BinaryOp::Union,
            LogicalOp::unary(
                UnaryOp::Sort {
                    key: SortKey::Property("a".to_string()),
                    descending: true,
                },
                LogicalOp::unary(
                    UnaryOp::Filter(Predicate::eq("a", 1)),
                    LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(1).unwrap()])),
                ),
            ),
            LogicalOp::unary(
                UnaryOp::Filter(Predicate::eq("b", 2)),
                LogicalOp::Scan(ScanOp::NodeLookup(vec![NodeId::new(2).unwrap()])),
            ),
        ));

        assert_eq!(
            result,
            Some(expected_plan),
            "Partial optimization (left branch) should trigger change"
        );
    }
}