kglite 0.16.8

Pure-Rust embedded Cypher knowledge graph engine with in-memory, mmap, and disk storage, and agent-facing schema introspection
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
//! Predicate pushdown into MATCH — equality/comparison extraction and
//! application, plus the subsumption test a fused scan uses before dropping
//! the safety-net WHERE the pushdown leaves behind.

use super::super::ast::*;
use crate::datatypes::values::Value;
use crate::graph::core::pattern_matching::{PatternElement, PropertyMatcher};
use std::collections::{HashMap, HashSet};

pub(super) fn push_where_into_match(query: &mut CypherQuery, params: &HashMap<String, Value>) {
    let mut i = 0;
    while i < query.clauses.len() {
        // Scoped form first: `OPTIONAL MATCH … WHERE` carries its predicate
        // inside the clause. Pushing it into the optional pattern is
        // unconditionally legal under clause scoping — "filtered out" and
        // "never matched" are the same outcome (both leave the row
        // null-extended). Under the old post-filter reading they differed, and
        // the pushdown was quietly changing which rows survived.
        if matches!(&query.clauses[i], Clause::OptionalMatch(m) if m.where_clause.is_some()) {
            push_scoped_where(query, i, params);
            i += 1;
            continue;
        }

        if i + 1 >= query.clauses.len() {
            break;
        }
        let can_push = matches!(
            (&query.clauses[i], &query.clauses[i + 1]),
            (Clause::Match(_), Clause::Where(_)) | (Clause::OptionalMatch(_), Clause::Where(_))
        );

        if !can_push {
            i += 1;
            continue;
        }

        let where_pred = if let Clause::Where(w) = &query.clauses[i + 1] {
            w.predicate.clone()
        } else {
            i += 1;
            continue;
        };

        let match_vars: Vec<(String, Option<String>)> = match &query.clauses[i] {
            Clause::Match(m) => collect_pattern_variables(&m.patterns),
            Clause::OptionalMatch(m) => collect_pattern_variables(&m.patterns),
            _ => {
                i += 1;
                continue;
            }
        };
        let occupied_properties = match &query.clauses[i] {
            Clause::Match(m) => collect_pattern_property_keys(&m.patterns),
            Clause::OptionalMatch(m) => collect_pattern_property_keys(&m.patterns),
            _ => unreachable!("MATCH/OPTIONAL MATCH checked above"),
        };

        // Names only — runtime resolution picks the right binding map
        // (node_bindings for prior-MATCH nodes, projected values for
        // WITH/UNWIND/LOAD CSV scalars).
        let prior_node_vars = collect_prior_node_vars(&query.clauses[..i], &match_vars);
        let prior_scalar_vars = collect_prior_scalar_vars(&query.clauses[..i]);

        let PushableResult {
            pushable,
            pushable_in,
            pushable_cmp,
            pushable_var,
            pushable_nodeprop,
            pushable_text,
            remaining,
        } = extract_pushable_equalities(
            &where_pred,
            &match_vars,
            &prior_node_vars,
            &prior_scalar_vars,
            params,
            occupied_properties,
        );

        if has_pushable(
            &pushable,
            &pushable_in,
            &pushable_cmp,
            &pushable_var,
            &pushable_nodeprop,
            &pushable_text,
        ) {
            let patterns = match &mut query.clauses[i] {
                Clause::Match(ref mut m) => &mut m.patterns,
                Clause::OptionalMatch(ref mut m) => &mut m.patterns,
                _ => {
                    i += 1;
                    continue;
                }
            };
            let all_applied = apply_pushables(
                patterns,
                pushable,
                pushable_in,
                pushable_cmp,
                pushable_var,
                pushable_nodeprop,
                pushable_text,
            );

            // A fully-pushed WHERE stays in place as a safety net: consumers of
            // the rewritten clause list either ignore pattern properties or key
            // a fusion off the `(Match, Where, …)` adjacency, so dropping it
            // here would change which operator runs. It is dropped later, by
            // whichever operator can prove it enforces the predicate itself —
            // see `where_subsumed_by_pattern`.
            if !all_applied {
                query.clauses[i + 1] = Clause::Where(WhereClause {
                    predicate: where_pred,
                });
            } else if let Some(pred) = remaining {
                query.clauses[i + 1] = Clause::Where(WhereClause { predicate: pred });
            }
        }

        i += 1;
    }
}

/// Push an `OPTIONAL MATCH … WHERE`'s clause-owned predicate into its own
/// patterns. Same extraction and same safety-net rule as the adjacent-WHERE
/// form above — only the predicate's home differs.
fn push_scoped_where(query: &mut CypherQuery, i: usize, params: &HashMap<String, Value>) {
    let (where_pred, match_vars, occupied_properties) = match &query.clauses[i] {
        Clause::OptionalMatch(m) => match &m.where_clause {
            Some(wc) => (
                wc.predicate.clone(),
                collect_pattern_variables(&m.patterns),
                collect_pattern_property_keys(&m.patterns),
            ),
            None => return,
        },
        _ => return,
    };
    let prior_node_vars = collect_prior_node_vars(&query.clauses[..i], &match_vars);
    let prior_scalar_vars = collect_prior_scalar_vars(&query.clauses[..i]);

    let PushableResult {
        pushable,
        pushable_in,
        pushable_cmp,
        pushable_var,
        pushable_nodeprop,
        pushable_text,
        remaining,
    } = extract_pushable_equalities(
        &where_pred,
        &match_vars,
        &prior_node_vars,
        &prior_scalar_vars,
        params,
        occupied_properties,
    );

    if !has_pushable(
        &pushable,
        &pushable_in,
        &pushable_cmp,
        &pushable_var,
        &pushable_nodeprop,
        &pushable_text,
    ) {
        return;
    }

    let Clause::OptionalMatch(ref mut m) = query.clauses[i] else {
        return;
    };
    let all_applied = apply_pushables(
        &mut m.patterns,
        pushable,
        pushable_in,
        pushable_cmp,
        pushable_var,
        pushable_nodeprop,
        pushable_text,
    );
    // A partially-applied push leaves the original predicate untouched; a
    // fully-consumed one keeps it as the safety net (no `else` branch).
    if all_applied {
        if let Some(pred) = remaining {
            m.where_clause = Some(WhereClause { predicate: pred });
        }
    }
}

fn has_pushable(
    pushable: &[(String, String, Value)],
    pushable_in: &[(String, String, Vec<Value>)],
    pushable_cmp: &[(String, String, ComparisonOp, Value)],
    pushable_var: &[(String, String, String)],
    pushable_nodeprop: &[(String, String, String, String)],
    pushable_text: &[(String, String, PropertyMatcher)],
) -> bool {
    !pushable.is_empty()
        || !pushable_in.is_empty()
        || !pushable_cmp.is_empty()
        || !pushable_var.is_empty()
        || !pushable_nodeprop.is_empty()
        || !pushable_text.is_empty()
}

/// Apply every extracted term to `patterns`; `false` when any term found no
/// home (the caller then keeps the whole original predicate).
fn apply_pushables(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    pushable: Vec<(String, String, Value)>,
    pushable_in: Vec<(String, String, Vec<Value>)>,
    pushable_cmp: Vec<(String, String, ComparisonOp, Value)>,
    pushable_var: Vec<(String, String, String)>,
    pushable_nodeprop: Vec<(String, String, String, String)>,
    pushable_text: Vec<(String, String, PropertyMatcher)>,
) -> bool {
    let mut all_applied = true;
    for (var_name, property, value) in pushable {
        all_applied &= apply_property_to_patterns(patterns, &var_name, &property, value);
    }
    for (var_name, property, values) in pushable_in {
        all_applied &= apply_in_property_to_patterns(patterns, &var_name, &property, values);
    }
    for (var_name, property, op, value) in pushable_cmp {
        all_applied &= apply_comparison_to_patterns(patterns, &var_name, &property, op, value);
    }
    for (var_name, property, ref_name) in pushable_var {
        all_applied &= apply_var_property_to_patterns(patterns, &var_name, &property, ref_name);
    }
    for (var_name, property, ref_var, ref_prop) in pushable_nodeprop {
        all_applied &=
            apply_nodeprop_to_patterns(patterns, &var_name, &property, ref_var, ref_prop);
    }
    for (var_name, property, matcher) in pushable_text {
        all_applied &= apply_text_matcher_to_patterns(patterns, &var_name, &property, matcher);
    }
    all_applied
}

/// Collect node variable names bound by earlier MATCH/OPTIONAL MATCH clauses,
/// excluding any names also in the current MATCH's patterns (to avoid
/// self-correlation — those are normal within-pattern joins the pattern
/// executor already handles via shared bindings).
fn collect_prior_node_vars(
    prior_clauses: &[Clause],
    current_match_vars: &[(String, Option<String>)],
) -> HashSet<String> {
    let mut out = HashSet::new();
    let current: HashSet<&str> = current_match_vars.iter().map(|(v, _)| v.as_str()).collect();
    for c in prior_clauses {
        let patterns = match c {
            Clause::Match(m) => Some(&m.patterns),
            Clause::OptionalMatch(m) => Some(&m.patterns),
            _ => None,
        };
        if let Some(patterns) = patterns {
            for (v, _) in collect_pattern_variables(patterns) {
                if !current.contains(v.as_str()) {
                    out.insert(v);
                }
            }
        }
    }
    out
}

fn collect_pattern_property_keys(
    patterns: &[crate::graph::core::pattern_matching::Pattern],
) -> HashSet<(String, String)> {
    let mut keys = HashSet::new();
    for pattern in patterns {
        for element in &pattern.elements {
            let PatternElement::Node(node) = element else {
                continue;
            };
            let (Some(variable), Some(properties)) = (&node.variable, &node.properties) else {
                continue;
            };
            keys.extend(
                properties
                    .keys()
                    .map(|property| (variable.clone(), property.clone())),
            );
        }
    }
    keys
}

fn collect_prior_scalar_vars(prior_clauses: &[Clause]) -> HashSet<String> {
    let mut out = HashSet::new();
    for c in prior_clauses {
        match c {
            Clause::With(w) => {
                for item in &w.items {
                    if let Some(alias) = &item.alias {
                        out.insert(alias.clone());
                    } else if let Expression::Variable(name) = &item.expression {
                        out.insert(name.clone());
                    }
                }
            }
            Clause::Unwind(u) => {
                out.insert(u.alias.clone());
            }
            Clause::LoadCsv(l) => {
                out.insert(l.variable.clone());
            }
            _ => {}
        }
    }
    out
}

pub(super) fn collect_pattern_variables(
    patterns: &[crate::graph::core::pattern_matching::Pattern],
) -> Vec<(String, Option<String>)> {
    let mut vars = Vec::new();
    for pattern in patterns {
        for element in &pattern.elements {
            if let PatternElement::Node(np) = element {
                if let Some(ref var) = np.variable {
                    vars.push((var.clone(), np.node_type.clone()));
                }
            }
        }
    }
    vars
}

/// Result of splitting a WHERE predicate into MATCH-pushable components
/// plus whatever could not be pushed.
pub(super) struct PushableResult {
    pub pushable: Vec<(String, String, Value)>,
    pub pushable_in: Vec<(String, String, Vec<Value>)>,
    pub pushable_cmp: Vec<(String, String, ComparisonOp, Value)>,
    pub pushable_var: Vec<(String, String, String)>,
    pub pushable_nodeprop: Vec<(String, String, String, String)>,
    /// `(var, property, matcher)` for positive STARTS/CONTAINS/ENDS predicates.
    pub pushable_text: Vec<(String, String, PropertyMatcher)>,
    pub remaining: Option<Predicate>,
}

/// Extract pushable predicates from a WHERE clause into MATCH patterns.
///
/// Pushes conditions of the form:
/// - `variable.property = literal_value` / `= $param` (equality)
/// - `variable.property IN [literal, ...]` (IN list)
/// - `variable.property > literal_value` (and >=, <, <=)
/// - `variable.property STARTS WITH/CONTAINS/ENDS WITH <string>`
/// - `variable.property = other_variable` when `other_variable` is a scalar
///   from a prior WITH/UNWIND  →  EqualsVar
/// - `variable.property = other_var.other_prop` when `other_var` is a node
///   bound by a prior MATCH  →  EqualsNodeProp (correlated join pushdown)
///
/// The first variable must be defined in the current MATCH.
pub(super) fn extract_pushable_equalities(
    pred: &Predicate,
    match_vars: &[(String, Option<String>)],
    prior_node_vars: &HashSet<String>,
    prior_scalar_vars: &HashSet<String>,
    params: &HashMap<String, Value>,
    occupied_properties: HashSet<(String, String)>,
) -> PushableResult {
    let mut pushable = Vec::new();
    let mut pushable_in = Vec::new();
    let mut pushable_cmp = Vec::new();
    let mut pushable_var = Vec::new();
    let mut pushable_nodeprop = Vec::new();
    let mut pushable_text = Vec::new();
    let mut reservations: HashMap<(String, String), PropertyReservation> = occupied_properties
        .into_iter()
        .map(|key| (key, PropertyReservation::Exclusive))
        .collect();
    let remaining = extract_from_predicate(
        pred,
        match_vars,
        prior_node_vars,
        prior_scalar_vars,
        params,
        &mut pushable,
        &mut pushable_in,
        &mut pushable_cmp,
        &mut pushable_var,
        &mut pushable_nodeprop,
        &mut pushable_text,
        &mut reservations,
    );
    PushableResult {
        pushable,
        pushable_in,
        pushable_cmp,
        pushable_var,
        pushable_nodeprop,
        pushable_text,
        remaining,
    }
}

#[derive(Debug, Clone, Copy)]
enum PropertyReservation {
    Exclusive,
    RangeBounds { lower: bool, upper: bool },
}

#[derive(Debug, Clone, Copy)]
enum TextPredicateKind {
    StartsWith,
    Contains,
    EndsWith,
}

impl TextPredicateKind {
    fn into_matcher(self, needle: String) -> PropertyMatcher {
        match self {
            Self::StartsWith => PropertyMatcher::StartsWith(needle),
            Self::Contains => PropertyMatcher::Contains(needle),
            Self::EndsWith => PropertyMatcher::EndsWith(needle),
        }
    }
}

fn reserve_exclusive(
    reservations: &mut HashMap<(String, String), PropertyReservation>,
    variable: &str,
    property: &str,
) -> bool {
    use std::collections::hash_map::Entry;

    match reservations.entry((variable.to_string(), property.to_string())) {
        Entry::Vacant(entry) => {
            entry.insert(PropertyReservation::Exclusive);
            true
        }
        Entry::Occupied(_) => false,
    }
}

fn reserve_comparison(
    reservations: &mut HashMap<(String, String), PropertyReservation>,
    variable: &str,
    property: &str,
    op: ComparisonOp,
) -> bool {
    use std::collections::hash_map::Entry;

    let is_lower = matches!(op, ComparisonOp::GreaterThan | ComparisonOp::GreaterThanEq);
    match reservations.entry((variable.to_string(), property.to_string())) {
        Entry::Vacant(entry) => {
            entry.insert(PropertyReservation::RangeBounds {
                lower: is_lower,
                upper: !is_lower,
            });
            true
        }
        Entry::Occupied(mut entry) => match entry.get_mut() {
            PropertyReservation::Exclusive => false,
            PropertyReservation::RangeBounds { lower, upper } => {
                let slot = if is_lower { lower } else { upper };
                if *slot {
                    false
                } else {
                    *slot = true;
                    true
                }
            }
        },
    }
}

/// Recursively extract pushable predicates from a predicate tree.
/// Returns the remaining predicate (None if fully consumed).
#[allow(clippy::too_many_arguments)]
fn extract_from_predicate(
    pred: &Predicate,
    match_vars: &[(String, Option<String>)],
    prior_node_vars: &HashSet<String>,
    prior_scalar_vars: &HashSet<String>,
    params: &HashMap<String, Value>,
    pushable: &mut Vec<(String, String, Value)>,
    pushable_in: &mut Vec<(String, String, Vec<Value>)>,
    pushable_cmp: &mut Vec<(String, String, ComparisonOp, Value)>,
    pushable_var: &mut Vec<(String, String, String)>,
    pushable_nodeprop: &mut Vec<(String, String, String, String)>,
    pushable_text: &mut Vec<(String, String, PropertyMatcher)>,
    reservations: &mut HashMap<(String, String), PropertyReservation>,
) -> Option<Predicate> {
    match pred {
        Predicate::Comparison {
            left,
            operator: ComparisonOp::Equals,
            right,
        } => {
            if let Some((var, prop, val)) = try_extract_equality(left, right, match_vars, params) {
                if reserve_exclusive(reservations, &var, &prop) {
                    pushable.push((var, prop, val));
                    return None;
                }
                return Some(pred.clone());
            }
            if let Some((var, prop, ref_var, ref_prop)) =
                try_extract_correlated_nodeprop(left, right, match_vars, prior_node_vars)
            {
                if reserve_exclusive(reservations, &var, &prop) {
                    pushable_nodeprop.push((var, prop, ref_var, ref_prop));
                    return None;
                }
                return Some(pred.clone());
            }
            if let Some((var, prop, ref_name)) =
                try_extract_scalar_var(left, right, match_vars, prior_scalar_vars)
            {
                if reserve_exclusive(reservations, &var, &prop) {
                    pushable_var.push((var, prop, ref_name));
                    return None;
                }
                return Some(pred.clone());
            }
            Some(pred.clone())
        }
        Predicate::Comparison {
            left,
            operator:
                op @ (ComparisonOp::GreaterThan
                | ComparisonOp::GreaterThanEq
                | ComparisonOp::LessThan
                | ComparisonOp::LessThanEq),
            right,
        } => {
            if let Some((var, prop, op, val)) =
                try_extract_comparison(left, right, *op, match_vars, params)
            {
                if reserve_comparison(reservations, &var, &prop, op) {
                    pushable_cmp.push((var, prop, op, val));
                    None
                } else {
                    Some(pred.clone())
                }
            } else {
                Some(pred.clone())
            }
        }
        Predicate::In { expr, list } => {
            if let Expression::PropertyAccess { variable, property } = expr {
                if match_vars.iter().any(|(v, _)| v == variable) {
                    let all_literals: Option<Vec<Value>> = list
                        .iter()
                        .map(|item| {
                            if let Expression::Literal(val) = item {
                                Some(val.clone())
                            } else {
                                None
                            }
                        })
                        .collect();
                    if let Some(values) = all_literals {
                        if reserve_exclusive(reservations, variable, property) {
                            pushable_in.push((variable.clone(), property.clone(), values));
                            return None;
                        }
                        return Some(pred.clone());
                    }
                }
            }
            Some(pred.clone())
        }
        Predicate::InExpression { expr, list_expr } => {
            // Push `variable.property IN $param` (and any RHS that resolves to a
            // list at plan time) into the MATCH pattern. The common case is
            // `WHERE n.id IN $ids`: without this, an `id IN <param>` predicate
            // falls through to a full type scan + post-filter; with it, the
            // pattern matcher anchors on the id index (one lookup per id).
            if let Expression::PropertyAccess { variable, property } = expr {
                if match_vars.iter().any(|(v, _)| v == variable) {
                    if let Some(values) = resolve_value_list(list_expr, params) {
                        if !reserve_exclusive(reservations, variable, property) {
                            return Some(pred.clone());
                        }
                        pushable_in.push((variable.clone(), property.clone(), values.clone()));
                        // Replace the surviving WHERE with the O(1) HashSet form
                        // so the safety-net re-filter doesn't re-parse the list
                        // per row — matching the speed of a literal `IN [...]`.
                        return Some(Predicate::InLiteralSet {
                            expr: expr.clone(),
                            values: crate::graph::core::membership::MembershipSet::new(values),
                        });
                    }
                }
            }
            Some(pred.clone())
        }
        Predicate::StartsWith { expr, pattern }
        | Predicate::Contains { expr, pattern }
        | Predicate::EndsWith { expr, pattern } => {
            let kind = match pred {
                Predicate::StartsWith { .. } => TextPredicateKind::StartsWith,
                Predicate::Contains { .. } => TextPredicateKind::Contains,
                Predicate::EndsWith { .. } => TextPredicateKind::EndsWith,
                _ => unreachable!("text predicate match arm"),
            };
            if let Expression::PropertyAccess { variable, property } = expr {
                if match_vars.iter().any(|(v, _)| v == variable) {
                    if let Some(needle) = resolve_non_empty_string(pattern, params) {
                        if reserve_exclusive(reservations, variable, property) {
                            pushable_text.push((
                                variable.clone(),
                                property.clone(),
                                kind.into_matcher(needle),
                            ));
                        }
                    }
                }
            }
            // Text pushdown is an early candidate filter. Retain the original
            // WHERE predicate as a semantic safety net for every backend.
            Some(pred.clone())
        }
        Predicate::And(left, right) => {
            let left_remaining = extract_from_predicate(
                left,
                match_vars,
                prior_node_vars,
                prior_scalar_vars,
                params,
                pushable,
                pushable_in,
                pushable_cmp,
                pushable_var,
                pushable_nodeprop,
                pushable_text,
                reservations,
            );
            let right_remaining = extract_from_predicate(
                right,
                match_vars,
                prior_node_vars,
                prior_scalar_vars,
                params,
                pushable,
                pushable_in,
                pushable_cmp,
                pushable_var,
                pushable_nodeprop,
                pushable_text,
                reservations,
            );

            match (left_remaining, right_remaining) {
                (None, None) => None,
                (Some(l), None) => Some(l),
                (None, Some(r)) => Some(r),
                (Some(l), Some(r)) => Some(Predicate::And(Box::new(l), Box::new(r))),
            }
        }
        // Other predicate types can't be pushed
        _ => Some(pred.clone()),
    }
}

/// Resolve an `IN <rhs>` right-hand side to a concrete list of values at plan
/// time: the RHS must be a `$param` or an inline literal whose value is a list,
/// and anything not known at plan time (a correlated sub-expression) yields
/// `None`. Reuses the executor's `parse_list_value`, which accepts both a
/// native `Value::List` and the JSON-array `Value::String("[...]")` form the
/// Python binding uses for list params — so the *same* element parsing drives
/// the index pushdown here and the WHERE safety-net filter at run time. An
/// empty list is returned as a known-empty candidate set. (A bracket list
/// `IN [a, b]` parses to `Predicate::In`, not `InExpression`, and is handled
/// separately.)
fn resolve_value_list(expr: &Expression, params: &HashMap<String, Value>) -> Option<Vec<Value>> {
    let val = match expr {
        Expression::Parameter(name) => params.get(name.as_str())?,
        Expression::Literal(v) => v,
        _ => return None,
    };
    Some(super::super::executor::helpers::parse_list_value(val))
}

fn resolve_non_empty_string(expr: &Expression, params: &HashMap<String, Value>) -> Option<String> {
    let value = match expr {
        Expression::Literal(value) => value,
        Expression::Parameter(name) => params.get(name.as_str())?,
        _ => return None,
    };
    match value {
        Value::String(value) if !value.is_empty() => Some(value.clone()),
        _ => None,
    }
}

/// Try to extract a simple equality: variable.property = literal_or_param
pub(super) fn try_extract_equality(
    left: &Expression,
    right: &Expression,
    match_vars: &[(String, Option<String>)],
    params: &HashMap<String, Value>,
) -> Option<(String, String, Value)> {
    if let (Expression::PropertyAccess { variable, property }, Expression::Literal(val)) =
        (left, right)
    {
        if match_vars.iter().any(|(v, _)| v == variable) {
            return Some((variable.clone(), property.clone(), val.clone()));
        }
    }

    if let (Expression::Literal(val), Expression::PropertyAccess { variable, property }) =
        (left, right)
    {
        if match_vars.iter().any(|(v, _)| v == variable) {
            return Some((variable.clone(), property.clone(), val.clone()));
        }
    }

    if let (Expression::PropertyAccess { variable, property }, Expression::Parameter(name)) =
        (left, right)
    {
        if let Some(val) = params.get(name.as_str()) {
            if match_vars.iter().any(|(v, _)| v == variable) {
                return Some((variable.clone(), property.clone(), val.clone()));
            }
        }
    }

    if let (Expression::Parameter(name), Expression::PropertyAccess { variable, property }) =
        (left, right)
    {
        if let Some(val) = params.get(name.as_str()) {
            if match_vars.iter().any(|(v, _)| v == variable) {
                return Some((variable.clone(), property.clone(), val.clone()));
            }
        }
    }

    // id(variable) = literal → treat as variable.id = literal
    // This enables O(1) lookup via lookup_by_id instead of full scan.
    if let (Expression::FunctionCall { name, args, .. }, Expression::Literal(val)) = (left, right) {
        if name == "id" {
            if let Some(Expression::Variable(var)) = args.first() {
                if match_vars.iter().any(|(v, _)| v == var) {
                    return Some((var.clone(), "id".to_string(), val.clone()));
                }
            }
        }
    }
    if let (Expression::Literal(val), Expression::FunctionCall { name, args, .. }) = (left, right) {
        if name == "id" {
            if let Some(Expression::Variable(var)) = args.first() {
                if match_vars.iter().any(|(v, _)| v == var) {
                    return Some((var.clone(), "id".to_string(), val.clone()));
                }
            }
        }
    }

    // id(variable) = $param and its commutation — resolved from bound params
    // exactly like the `v.prop = $x` arms above. Missing them once let
    // `WHERE id(v) = 2` push into the pattern while `WHERE id(v) = $x` did
    // not, and against the then-lossy untyped id anchor the two spellings
    // answered DIFFERENT rows (measured 1 vs 68, 2026-08-15). They must plan
    // identically.
    if let (Expression::FunctionCall { name, args, .. }, Expression::Parameter(pname)) =
        (left, right)
    {
        if name == "id" {
            if let (Some(Expression::Variable(var)), Some(val)) =
                (args.first(), params.get(pname.as_str()))
            {
                if match_vars.iter().any(|(v, _)| v == var) {
                    return Some((var.clone(), "id".to_string(), val.clone()));
                }
            }
        }
    }
    if let (Expression::Parameter(pname), Expression::FunctionCall { name, args, .. }) =
        (left, right)
    {
        if name == "id" {
            if let (Some(Expression::Variable(var)), Some(val)) =
                (args.first(), params.get(pname.as_str()))
            {
                if match_vars.iter().any(|(v, _)| v == var) {
                    return Some((var.clone(), "id".to_string(), val.clone()));
                }
            }
        }
    }

    None
}

/// Try to extract a correlated node-prop equality: `cur.prop = prior.other_prop`.
/// Returns `(cur_var, cur_prop, prior_var, prior_prop)` when either side is a
/// current-match property access and the other side is a prior-bound node's
/// property access. The prior-bound node's property is read at row-execute time
/// via the `EqualsNodeProp` matcher.
pub(super) fn try_extract_correlated_nodeprop(
    left: &Expression,
    right: &Expression,
    match_vars: &[(String, Option<String>)],
    prior_node_vars: &HashSet<String>,
) -> Option<(String, String, String, String)> {
    let is_cur = |v: &str| match_vars.iter().any(|(name, _)| name == v);
    let is_prior = |v: &str| prior_node_vars.contains(v);
    if let (
        Expression::PropertyAccess {
            variable: lv,
            property: lp,
        },
        Expression::PropertyAccess {
            variable: rv,
            property: rp,
        },
    ) = (left, right)
    {
        // Refuse self-equality (would shortcut a variable to itself)
        if lv == rv {
            return None;
        }
        if is_cur(lv) && is_prior(rv) {
            return Some((lv.clone(), lp.clone(), rv.clone(), rp.clone()));
        }
        if is_cur(rv) && is_prior(lv) {
            return Some((rv.clone(), rp.clone(), lv.clone(), lp.clone()));
        }
    }
    None
}

/// Try to extract a scalar-var equality: `cur.prop = scalar_var`, where
/// `scalar_var` is defined by a prior WITH/UNWIND/LOAD CSV. Returns `(cur_var,
/// cur_prop, ref_name)` that the planner pushes as an `EqualsVar` matcher.
pub(super) fn try_extract_scalar_var(
    left: &Expression,
    right: &Expression,
    match_vars: &[(String, Option<String>)],
    prior_scalar_vars: &HashSet<String>,
) -> Option<(String, String, String)> {
    let is_cur = |v: &str| match_vars.iter().any(|(name, _)| name == v);
    if let (Expression::PropertyAccess { variable, property }, Expression::Variable(ref_name)) =
        (left, right)
    {
        if is_cur(variable) && prior_scalar_vars.contains(ref_name) {
            return Some((variable.clone(), property.clone(), ref_name.clone()));
        }
    }
    if let (Expression::Variable(ref_name), Expression::PropertyAccess { variable, property }) =
        (left, right)
    {
        if is_cur(variable) && prior_scalar_vars.contains(ref_name) {
            return Some((variable.clone(), property.clone(), ref_name.clone()));
        }
    }
    None
}

/// Try to extract a comparison: variable.property OP literal_or_param
/// When the literal is on the left (e.g. `30 < n.age`), reverse the operator
/// so it becomes `n.age > 30`.
pub(super) fn try_extract_comparison(
    left: &Expression,
    right: &Expression,
    op: ComparisonOp,
    match_vars: &[(String, Option<String>)],
    params: &HashMap<String, Value>,
) -> Option<(String, String, ComparisonOp, Value)> {
    if let (Expression::PropertyAccess { variable, property }, Expression::Literal(val)) =
        (left, right)
    {
        if match_vars.iter().any(|(v, _)| v == variable) {
            return Some((variable.clone(), property.clone(), op, val.clone()));
        }
    }

    if let (Expression::Literal(val), Expression::PropertyAccess { variable, property }) =
        (left, right)
    {
        if match_vars.iter().any(|(v, _)| v == variable) {
            let reversed = match op {
                ComparisonOp::GreaterThan => ComparisonOp::LessThan,
                ComparisonOp::GreaterThanEq => ComparisonOp::LessThanEq,
                ComparisonOp::LessThan => ComparisonOp::GreaterThan,
                ComparisonOp::LessThanEq => ComparisonOp::GreaterThanEq,
                other => other,
            };
            return Some((variable.clone(), property.clone(), reversed, val.clone()));
        }
    }

    if let (Expression::PropertyAccess { variable, property }, Expression::Parameter(name)) =
        (left, right)
    {
        if let Some(val) = params.get(name.as_str()) {
            if match_vars.iter().any(|(v, _)| v == variable) {
                return Some((variable.clone(), property.clone(), op, val.clone()));
            }
        }
    }

    if let (Expression::Parameter(name), Expression::PropertyAccess { variable, property }) =
        (left, right)
    {
        if let Some(val) = params.get(name.as_str()) {
            if match_vars.iter().any(|(v, _)| v == variable) {
                let reversed = match op {
                    ComparisonOp::GreaterThan => ComparisonOp::LessThan,
                    ComparisonOp::GreaterThanEq => ComparisonOp::LessThanEq,
                    ComparisonOp::LessThan => ComparisonOp::GreaterThan,
                    ComparisonOp::LessThanEq => ComparisonOp::GreaterThanEq,
                    other => other,
                };
                return Some((variable.clone(), property.clone(), reversed, val.clone()));
            }
        }
    }

    None
}

/// Apply a comparison condition to the matching node pattern in MATCH.
/// If the same property already has a comparison matcher (e.g. `year >= 2015`
/// followed by `year <= 2022`), merge them into a `Range` matcher.
pub(super) fn apply_comparison_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    op: ComparisonOp,
    value: Value,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    if let Some(existing) = props.get(property) {
                        if let Some(merged) = merge_comparison(existing, op, &value) {
                            props.insert(property.to_string(), merged);
                            return true;
                        }
                        return false;
                    }
                    let matcher = match op {
                        ComparisonOp::GreaterThan => PropertyMatcher::GreaterThan(value),
                        ComparisonOp::GreaterThanEq => PropertyMatcher::GreaterOrEqual(value),
                        ComparisonOp::LessThan => PropertyMatcher::LessThan(value),
                        ComparisonOp::LessThanEq => PropertyMatcher::LessOrEqual(value),
                        _ => return false,
                    };
                    props.insert(property.to_string(), matcher);
                    return true;
                }
            }
        }
    }
    false
}

/// Merge two comparison matchers on the same property into a Range.
/// E.g. existing `>= 2015` + new `<= 2022` → `Range { 2015..=2022 }`.
pub(super) fn merge_comparison(
    existing: &PropertyMatcher,
    new_op: ComparisonOp,
    new_val: &Value,
) -> Option<PropertyMatcher> {
    let (existing_lower, existing_val, existing_inclusive) = match existing {
        PropertyMatcher::GreaterThan(v) => (true, v, false),
        PropertyMatcher::GreaterOrEqual(v) => (true, v, true),
        PropertyMatcher::LessThan(v) => (false, v, false),
        PropertyMatcher::LessOrEqual(v) => (false, v, true),
        _ => return None,
    };

    let (new_lower, new_inclusive) = match new_op {
        ComparisonOp::GreaterThan => (true, false),
        ComparisonOp::GreaterThanEq => (true, true),
        ComparisonOp::LessThan => (false, false),
        ComparisonOp::LessThanEq => (false, true),
        _ => return None,
    };

    // Only opposite directions merge cleanly.
    if existing_lower == new_lower {
        return None;
    }

    if existing_lower {
        Some(PropertyMatcher::Range {
            lower: existing_val.clone(),
            lower_inclusive: existing_inclusive,
            upper: new_val.clone(),
            upper_inclusive: new_inclusive,
        })
    } else {
        Some(PropertyMatcher::Range {
            lower: new_val.clone(),
            lower_inclusive: new_inclusive,
            upper: existing_val.clone(),
            upper_inclusive: existing_inclusive,
        })
    }
}

pub(super) fn apply_property_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    value: Value,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    // Don't overwrite an existing matcher (e.g. IN or Range)
                    if props.contains_key(property) {
                        return false;
                    }
                    props.insert(property.to_string(), PropertyMatcher::Equals(value));
                    return true;
                }
            }
        }
    }
    false
}

/// Apply a positive string matcher to the matching node pattern. STARTS WITH
/// can use a persistent prefix index; CONTAINS and ENDS WITH linearly filter
/// the node candidates before any relationship expansion.
pub(super) fn apply_text_matcher_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    matcher: PropertyMatcher,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    if props.contains_key(property) {
                        return false;
                    }
                    props.insert(property.to_string(), matcher);
                    return true;
                }
            }
        }
    }
    false
}

pub(super) fn apply_in_property_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    values: Vec<Value>,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    if props.contains_key(property) {
                        return false;
                    }
                    props.insert(
                        property.to_string(),
                        PropertyMatcher::In(crate::graph::core::membership::MembershipSet::new(
                            values,
                        )),
                    );
                    return true;
                }
            }
        }
    }
    false
}

/// Apply a scalar-var reference (EqualsVar) to the matching node pattern.
/// Resolved at row-execute time from projected scalar values.
pub(super) fn apply_var_property_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    ref_name: String,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    if props.contains_key(property) {
                        return false;
                    }
                    props.insert(property.to_string(), PropertyMatcher::EqualsVar(ref_name));
                    return true;
                }
            }
        }
    }
    false
}

/// Apply a correlated node-prop reference (EqualsNodeProp) to the matching
/// node pattern. Resolved at row-execute time by reading the prior-bound
/// node's property.
pub(super) fn apply_nodeprop_to_patterns(
    patterns: &mut [crate::graph::core::pattern_matching::Pattern],
    var_name: &str,
    property: &str,
    ref_var: String,
    ref_prop: String,
) -> bool {
    for pattern in patterns.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(ref mut np) = element {
                if np.variable.as_deref() == Some(var_name) {
                    let props = np.properties.get_or_insert_with(Default::default);
                    if props.contains_key(property) {
                        return false;
                    }
                    props.insert(
                        property.to_string(),
                        PropertyMatcher::EqualsNodeProp {
                            var: ref_var,
                            prop: ref_prop,
                        },
                    );
                    return true;
                }
            }
        }
    }
    false
}

/// True when every conjunct of `pred` is *already* enforced, identically, by
/// node property matchers on `patterns`.
///
/// `push_where_into_match` deliberately leaves a fully-pushed WHERE in place as
/// a safety net, because most consumers of the rewritten clause list either
/// ignore pattern properties or change *which* fusion fires once the WHERE
/// disappears. That net costs a second evaluation of every predicate for every
/// surviving row — measured as the dominant cost of a low-selectivity filter +
/// aggregate. This answers the question a consumer needs before dropping it:
/// "would re-running the extraction against a property-free copy of this
/// pattern reproduce, term for term, the matchers the pattern already carries,
/// with nothing left over?" Only a caller that provably applies those matchers
/// (the fused node-scan operators, via `find_matching_nodes`) may act on a
/// `true`; everyone else keeps the net.
///
/// Conservative by construction — any shape the extractor cannot fully consume,
/// any term that resolves against a row binding (`EqualsVar` /
/// `EqualsNodeProp`), and any text matcher (an early candidate filter, not an
/// equivalent of its predicate) answers `false`.
pub(super) fn where_subsumed_by_pattern(
    pred: &Predicate,
    patterns: &[crate::graph::core::pattern_matching::Pattern],
    params: &HashMap<String, Value>,
) -> bool {
    let match_vars = collect_pattern_variables(patterns);
    let empty = HashSet::new();
    let PushableResult {
        pushable,
        pushable_in,
        pushable_cmp,
        pushable_var,
        pushable_nodeprop,
        pushable_text,
        remaining,
    } = extract_pushable_equalities(pred, &match_vars, &empty, &empty, params, HashSet::new());

    // Anything the extractor could not consume is still doing work.
    if remaining.is_some() {
        return false;
    }
    // The never-equivalent kinds (see the doc above). `extract_from_predicate`
    // never consumes a text predicate, so the last check is belt-and-braces.
    if !pushable_var.is_empty() || !pushable_nodeprop.is_empty() || !pushable_text.is_empty() {
        return false;
    }

    // Replay the push against a property-free copy and compare. Going through
    // `apply_pushables` rather than re-deriving the expected matcher by hand is
    // what makes the two agree about range folding, application order, and the
    // "no home for this term" bail.
    let mut probe: Vec<crate::graph::core::pattern_matching::Pattern> = patterns.to_vec();
    for pattern in probe.iter_mut() {
        for element in &mut pattern.elements {
            if let PatternElement::Node(np) = element {
                np.properties = None;
            }
        }
    }
    if !apply_pushables(
        &mut probe,
        pushable,
        pushable_in,
        pushable_cmp,
        Vec::new(),
        Vec::new(),
        Vec::new(),
    ) {
        return false;
    }

    // Every matcher the replay produced must sit on the real pattern unchanged.
    // Extra properties there are inline filters from the query text — they
    // constrain the scan further and are applied by the same matcher run, so
    // they are not this predicate's business.
    for (probe_pattern, real_pattern) in probe.iter().zip(patterns) {
        for (probe_element, real_element) in
            probe_pattern.elements.iter().zip(&real_pattern.elements)
        {
            let (PatternElement::Node(probe_np), PatternElement::Node(real_np)) =
                (probe_element, real_element)
            else {
                continue;
            };
            let Some(replayed) = &probe_np.properties else {
                continue;
            };
            for (key, matcher) in replayed {
                match real_np.properties.as_ref().and_then(|p| p.get(key)) {
                    Some(present) if matchers_equivalent(present, matcher) => {}
                    _ => return false,
                }
            }
        }
    }
    true
}

/// Structural equality for the matcher kinds a pushdown replay can produce.
/// Deliberately a local function rather than a `PartialEq` derive on
/// `PropertyMatcher`: only these kinds are ever compared here, and a derived
/// impl would invite equality tests on the deferred kinds, whose sameness is a
/// question about *bindings* rather than about the matcher.
fn matchers_equivalent(a: &PropertyMatcher, b: &PropertyMatcher) -> bool {
    match (a, b) {
        (PropertyMatcher::Equals(x), PropertyMatcher::Equals(y)) => x == y,
        (PropertyMatcher::In(x), PropertyMatcher::In(y)) => **x == **y,
        (PropertyMatcher::GreaterThan(x), PropertyMatcher::GreaterThan(y))
        | (PropertyMatcher::GreaterOrEqual(x), PropertyMatcher::GreaterOrEqual(y))
        | (PropertyMatcher::LessThan(x), PropertyMatcher::LessThan(y))
        | (PropertyMatcher::LessOrEqual(x), PropertyMatcher::LessOrEqual(y)) => x == y,
        (
            PropertyMatcher::Range {
                lower: al,
                lower_inclusive: ali,
                upper: au,
                upper_inclusive: aui,
            },
            PropertyMatcher::Range {
                lower: bl,
                lower_inclusive: bli,
                upper: bu,
                upper_inclusive: bui,
            },
        ) => al == bl && ali == bli && au == bu && aui == bui,
        _ => false,
    }
}

#[cfg(test)]
mod subsumption_tests {
    //! Plan-shape goldens for the safety-net WHERE drop.
    //!
    //! The drop is a pure-performance rewrite: no answer changes, so no
    //! result-value test can see it and a measurement is too noisy to gate on.
    //! What *is* observable is the plan — whether the fused node-scan operator
    //! carries a `where_predicate` it would re-evaluate per row. Each case below
    //! pins that field for one shape, and the ABSENT/PRESENT split is the whole
    //! contract: absent exactly when the pattern provably enforces the
    //! predicate, present everywhere else.
    //!
    //! Forcing `where_subsumed_by_pattern` to `true` turns the PRESENT cases
    //! into wrong answers (the regex conjunct, the text predicate and the
    //! collided inline property all stop being applied), which is the
    //! mutate-to-red these goldens exist to catch.

    use super::super::optimize;
    use crate::graph::languages::cypher::ast::Clause;
    use crate::graph::languages::cypher::parser::parse_cypher;
    use crate::graph::schema::DirGraph;
    use std::collections::HashMap;

    /// The `where_predicate` of whichever fused node-scan clause the plan ends
    /// up with. `None` for "fused, no surviving filter"; the outer `Option`
    /// distinguishes "did not fuse at all", which every PRESENT case that is
    /// about routing rather than subsumption needs to tell apart.
    fn fused_filter(query: &str) -> Option<bool> {
        let mut parsed = parse_cypher(query).unwrap();
        let graph = DirGraph::new();
        optimize(&mut parsed, &graph, &HashMap::new());
        parsed.clauses.iter().find_map(|clause| match clause {
            Clause::FusedNodeScanAggregate {
                where_predicate, ..
            }
            | Clause::FusedNodeScanTopK {
                where_predicate, ..
            } => Some(where_predicate.is_some()),
            _ => None,
        })
    }

    /// Whether a standalone `WHERE` clause survived anywhere in the plan —
    /// the safety net for the shapes that never reach a fused node scan.
    fn has_where_clause(query: &str) -> bool {
        let mut parsed = parse_cypher(query).unwrap();
        let graph = DirGraph::new();
        optimize(&mut parsed, &graph, &HashMap::new());
        parsed
            .clauses
            .iter()
            .any(|clause| matches!(clause, Clause::Where(_)))
    }

    // ── ABSENT: the pattern already enforces every conjunct ──────────────

    #[test]
    fn equality_only_where_is_dropped_by_the_scan_aggregate() {
        assert_eq!(
            fused_filter("MATCH (n:Person) WHERE n.city = 'Oslo' RETURN n.dept, count(n)"),
            Some(false)
        );
    }

    #[test]
    fn comparison_where_is_dropped_by_the_scan_aggregate() {
        assert_eq!(
            fused_filter("MATCH (n:Person) WHERE n.age > 30 RETURN n.city, count(n)"),
            Some(false)
        );
    }

    #[test]
    fn merged_range_where_is_dropped() {
        // Two conjuncts fold into one `Range` matcher; the replay has to
        // reproduce that fold to recognise the pattern as equivalent.
        assert_eq!(
            fused_filter(
                "MATCH (n:Person) WHERE n.year >= 2015 AND n.year <= 2022 \
                 RETURN n.city, count(n)"
            ),
            Some(false)
        );
    }

    #[test]
    fn literal_in_list_where_is_dropped() {
        assert_eq!(
            fused_filter("MATCH (n:Person) WHERE n.city IN ['Oslo', 'Bergen'] RETURN count(n)"),
            Some(false)
        );
    }

    #[test]
    fn inline_property_alongside_a_pushed_one_still_drops_the_where() {
        // `{city: 'Oslo'}` is the query text's own filter, not this WHERE's
        // business: an extra matcher on the pattern must not block the drop.
        assert_eq!(
            fused_filter(
                "MATCH (n:Person {city: 'Oslo'}) WHERE n.age > 30 RETURN n.dept, count(n)"
            ),
            Some(false)
        );
    }

    #[test]
    fn top_k_scan_drops_a_fully_pushed_where() {
        assert_eq!(
            fused_filter("MATCH (n:Person) WHERE n.age > 30 RETURN n.name ORDER BY n.age LIMIT 5"),
            Some(false)
        );
    }

    // ── PRESENT: the net stays ──────────────────────────────────────────

    #[test]
    fn partially_pushed_where_keeps_the_whole_predicate() {
        // The regex conjunct is not pushable, so nothing may be dropped —
        // `push_where_into_match` leaves the *entire* original predicate.
        assert_eq!(
            fused_filter(
                "MATCH (n:Person) WHERE n.age > 30 AND n.name =~ '.*a.*' \
                 RETURN n.city, count(n)"
            ),
            Some(true)
        );
    }

    #[test]
    fn text_matcher_keeps_its_predicate() {
        // A `STARTS WITH` matcher is an early candidate filter, not an
        // equivalent of its predicate — the extractor never consumes one.
        assert_eq!(
            fused_filter("MATCH (n:Person) WHERE n.name STARTS WITH 'A' RETURN n.city, count(n)"),
            Some(true)
        );
    }

    #[test]
    fn where_colliding_with_an_inline_property_keeps_its_predicate() {
        // `{age: 30}` occupies the slot, so `n.age > 5` was never pushed and is
        // the only thing enforcing it.
        assert_eq!(
            fused_filter("MATCH (n:Person {age: 30}) WHERE n.age > 5 RETURN n.city, count(n)"),
            Some(true)
        );
    }

    #[test]
    fn top_k_scan_keeps_a_partially_pushed_where() {
        assert_eq!(
            fused_filter(
                "MATCH (n:Person) WHERE n.age > 30 AND n.name =~ '.*a.*' \
                 RETURN n.name ORDER BY n.age LIMIT 5"
            ),
            Some(true)
        );
    }

    // ── PRESENT: operators outside the covered family ───────────────────

    #[test]
    fn edge_pattern_aggregate_keeps_its_where_clause() {
        // Not a node scan — and the drop must not happen upstream in the
        // pushdown pass, where it would change `(Match, Where, Return)` into
        // the `(Match, Return)` adjacency a *different* fusion keys off.
        assert!(has_where_clause(
            "MATCH (a:Person)-[e:KNOWS]->(b:Person) WHERE a.city = 'Oslo' \
             RETURN b.name, count(e)"
        ));
    }

    #[test]
    fn optional_match_keeps_its_scoped_where() {
        let query = "MATCH (a:Person) OPTIONAL MATCH (a)-[:KNOWS]->(b:Person) \
                     WHERE b.age > 30 RETURN a.name, count(b)";
        let mut parsed = parse_cypher(query).unwrap();
        let graph = DirGraph::new();
        optimize(&mut parsed, &graph, &HashMap::new());
        let scoped_where_survives = parsed
            .clauses
            .iter()
            .any(|clause| matches!(clause, Clause::OptionalMatch(m) if m.where_clause.is_some()));
        assert!(scoped_where_survives);
    }

    #[test]
    fn non_first_match_is_not_a_fused_node_scan() {
        // A correlated conjunct pushes as `EqualsNodeProp`, which resolves
        // against a row binding — never subsumable, and never fused here.
        assert_eq!(
            fused_filter(
                "MATCH (a:Person) MATCH (b:Person) WHERE b.city = a.city \
                 RETURN b.dept, count(b)"
            ),
            None
        );
    }

    // ── the subsumption predicate itself ────────────────────────────────

    #[test]
    fn correlated_and_text_terms_are_never_subsumed() {
        use crate::graph::languages::cypher::ast::Clause as C;

        for query in [
            "MATCH (n:Person) WHERE n.name CONTAINS 'a' RETURN n",
            "MATCH (n:Person) WHERE n.age > 30 AND n.rank < n.score RETURN n",
        ] {
            let mut parsed = parse_cypher(query).unwrap();
            let graph = DirGraph::new();
            let params = HashMap::new();
            optimize(&mut parsed, &graph, &params);
            let (C::Match(m), C::Where(w)) = (&parsed.clauses[0], &parsed.clauses[1]) else {
                panic!("expected MATCH + WHERE for `{query}`");
            };
            assert!(
                !super::where_subsumed_by_pattern(&w.predicate, &m.patterns, &params),
                "`{query}` must not be reported as subsumed"
            );
        }
    }
}