grafeo-core 0.5.42

Core graph models, indexes, and execution primitives for Grafeo
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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
//! Merge operator for MERGE clause execution.
//!
//! The MERGE operator implements the Cypher MERGE semantics:
//! 1. Try to match the pattern in the graph
//! 2. If found, return existing element (optionally apply ON MATCH SET)
//! 3. If not found, create the element (optionally apply ON CREATE SET)

use super::{
    ConstraintValidator, ExpressionPredicate, Operator, OperatorResult, PropertySource,
    SessionContext,
};
use crate::execution::chunk::{DataChunk, DataChunkBuilder};
use crate::graph::{GraphStore, GraphStoreMut, GraphStoreSearch};
use grafeo_common::types::{
    EdgeId, EpochId, LogicalType, NodeId, PropertyKey, TransactionId, Value,
};
use std::sync::Arc;

/// Configuration for a node merge operation.
pub struct MergeConfig {
    /// Variable name for the merged node.
    pub variable: String,
    /// Labels to match/create.
    pub labels: Vec<String>,
    /// Properties that must match (also used for creation).
    pub match_properties: Vec<(String, PropertySource)>,
    /// Properties to set on CREATE.
    pub on_create_properties: Vec<(String, PropertySource)>,
    /// Properties to set on MATCH.
    pub on_match_properties: Vec<(String, PropertySource)>,
    /// Output schema (input columns + node column).
    pub output_schema: Vec<LogicalType>,
    /// Column index where the merged node ID is placed.
    pub output_column: usize,
    /// If the merge variable was already bound in the input, this column index
    /// is used to detect NULL references (e.g., from unmatched OPTIONAL MATCH).
    /// `None` for standalone MERGE that introduces a new variable.
    pub bound_variable_column: Option<usize>,
}

/// Merge operator for MERGE clause.
///
/// Tries to match a node with the given labels and properties.
/// If found, returns the existing node. If not found, creates a new node.
///
/// When an input operator is provided (chained MERGE), input rows are
/// passed through with the merged node ID appended as an additional column.
pub struct MergeOperator {
    /// The graph store.
    store: Arc<dyn GraphStoreMut>,
    /// Optional input operator (for chained MERGE patterns).
    input: Option<Box<dyn Operator>>,
    /// Merge configuration.
    config: MergeConfig,
    /// Whether we've already executed (standalone mode only).
    executed: bool,
    /// Epoch for MVCC versioning.
    viewing_epoch: Option<EpochId>,
    /// Transaction ID for undo log tracking.
    transaction_id: Option<TransactionId>,
    /// Optional constraint validator for schema enforcement.
    validator: Option<Arc<dyn ConstraintValidator>>,
    /// Search-store handle used to evaluate `PropertySource::Expression`
    /// runtime expressions in `ON CREATE` / `ON MATCH SET`. None when no
    /// expression sources are present (the planner skips threading it).
    search_store: Option<Arc<dyn GraphStoreSearch>>,
    /// Session context for expression evaluation (info, schema, etc.).
    session_context: SessionContext,
}

impl MergeOperator {
    /// Creates a new merge operator.
    pub fn new(
        store: Arc<dyn GraphStoreMut>,
        input: Option<Box<dyn Operator>>,
        config: MergeConfig,
    ) -> Self {
        Self {
            store,
            input,
            config,
            executed: false,
            viewing_epoch: None,
            transaction_id: None,
            validator: None,
            search_store: None,
            session_context: SessionContext::default(),
        }
    }

    /// Returns the variable name for the merged node.
    #[must_use]
    pub fn variable(&self) -> &str {
        &self.config.variable
    }

    /// Sets the transaction context for versioned mutations.
    pub fn with_transaction_context(
        mut self,
        epoch: EpochId,
        transaction_id: Option<TransactionId>,
    ) -> Self {
        self.viewing_epoch = Some(epoch);
        self.transaction_id = transaction_id;
        self
    }

    /// Sets the constraint validator for schema enforcement.
    pub fn with_validator(mut self, validator: Arc<dyn ConstraintValidator>) -> Self {
        self.validator = Some(validator);
        self
    }

    /// Provides a search-store handle so `PropertySource::Expression`
    /// sources in `ON CREATE` / `ON MATCH SET` can be evaluated.
    #[must_use]
    pub fn with_search_store(mut self, search_store: Arc<dyn GraphStoreSearch>) -> Self {
        self.search_store = Some(search_store);
        self
    }

    /// Sets the session context used during expression evaluation.
    #[must_use]
    pub fn with_session_context(mut self, context: SessionContext) -> Self {
        self.session_context = context;
        self
    }

    /// Resolves property sources to concrete values for a given row.
    ///
    /// Skips [`PropertySource::Expression`] sources: those need an augmented
    /// row containing the merged node/edge and are evaluated separately by
    /// [`Self::resolve_action_properties`].
    fn resolve_properties(
        props: &[(String, PropertySource)],
        chunk: Option<&DataChunk>,
        row: usize,
        store: &dyn GraphStore,
    ) -> Vec<(String, Value)> {
        props
            .iter()
            .map(|(name, source)| {
                let value = if let Some(chunk) = chunk {
                    source.resolve(chunk, row, store)
                } else {
                    // Standalone mode: only constants are valid
                    match source {
                        PropertySource::Constant(v) => v.clone(),
                        _ => Value::Null,
                    }
                };
                (name.clone(), value)
            })
            .collect()
    }

    /// True when at least one property source in the slice requires the
    /// augmented-row evaluation path.
    fn has_expression_source(props: &[(String, PropertySource)]) -> bool {
        props
            .iter()
            .any(|(_, src)| matches!(src, PropertySource::Expression { .. }))
    }

    /// Builds a one-row chunk containing the input row plus the merged node
    /// in the column reserved for the MERGE variable.
    ///
    /// Used to evaluate `PropertySource::Expression` sources for ON CREATE /
    /// ON MATCH SET. The augmented chunk's schema matches `output_schema`.
    fn build_augmented_node_chunk(
        &self,
        chunk: Option<&DataChunk>,
        row: usize,
        merged_node: NodeId,
    ) -> DataChunk {
        let mut builder = DataChunkBuilder::with_capacity(&self.config.output_schema, 1);
        if let Some(input) = chunk {
            for col_idx in 0..input.column_count() {
                let val = input
                    .column(col_idx)
                    .and_then(|c| c.get_value(row))
                    .unwrap_or(Value::Null);
                if let Some(dst) = builder.column_mut(col_idx) {
                    dst.push_value(val);
                }
            }
        }
        if let Some(dst) = builder.column_mut(self.config.output_column) {
            dst.push_node_id(merged_node);
        }
        builder.advance_row();
        builder.finish()
    }

    /// Resolves an action-property source list (ON CREATE or ON MATCH) given
    /// the merged node id. Lazily builds the augmented chunk only if at least
    /// one source needs it.
    ///
    /// Returns an error only when an expression source is present but no
    /// search store was attached, which would be a planner/wiring bug.
    fn resolve_action_properties(
        &self,
        props: &[(String, PropertySource)],
        chunk: Option<&DataChunk>,
        row: usize,
        merged_node: NodeId,
    ) -> Result<Vec<(String, Value)>, super::OperatorError> {
        if !Self::has_expression_source(props) {
            // Fast path: no runtime expressions, fall through to the existing
            // resolver which understands Column/Constant/PropertyAccess.
            return Ok(Self::resolve_properties(
                props,
                chunk,
                row,
                self.store.as_ref(),
            ));
        }

        let augmented = self.build_augmented_node_chunk(chunk, row, merged_node);
        let mut out = Vec::with_capacity(props.len());
        for (name, source) in props {
            let value = match source {
                PropertySource::Expression {
                    expr,
                    variable_columns,
                } => {
                    let search_store = self.search_store.as_ref().ok_or_else(|| {
                        super::OperatorError::Execution(
                            "MERGE expression source requires search store; planner did not attach one"
                                .to_string(),
                        )
                    })?;
                    let mut predicate = ExpressionPredicate::new(
                        (**expr).clone(),
                        variable_columns.clone(),
                        Arc::clone(search_store),
                    )
                    .with_session_context(self.session_context.clone());
                    if let Some(epoch) = self.viewing_epoch {
                        predicate = predicate.with_transaction_context(epoch, self.transaction_id);
                    }
                    predicate.eval_at(&augmented, 0).unwrap_or(Value::Null)
                }
                _ => source.resolve(&augmented, 0, self.store.as_ref()),
            };
            out.push((name.clone(), value));
        }
        Ok(out)
    }

    /// Tries to find a matching node with the given resolved properties.
    fn find_matching_node(&self, resolved_match_props: &[(String, Value)]) -> Option<NodeId> {
        // Use a property index when available to avoid a full label scan.
        // Null conditions are excluded from the index query and verified in the loop.
        let use_index = resolved_match_props
            .iter()
            .any(|(k, v)| !v.is_null() && self.store.has_property_index(k));

        let candidates: Vec<NodeId> = if use_index {
            let conditions: Vec<(&str, Value)> = resolved_match_props
                .iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| (k.as_str(), v.clone()))
                .collect();
            self.store.find_nodes_by_properties(&conditions)
        } else if let Some(first_label) = self.config.labels.first() {
            self.store.nodes_by_label(first_label)
        } else {
            self.store.node_ids()
        };

        for node_id in candidates {
            // Transactional creates write their version at `EpochId::PENDING`,
            // so the unversioned `get_node` (which checks visibility against
            // the current real epoch) hides nodes this same transaction has
            // just created. UNWIND-driven MERGE relies on seeing those rows
            // to dedupe, so route through the versioned read when we have a
            // transaction context attached.
            let node_opt = match (self.viewing_epoch, self.transaction_id) {
                (Some(epoch), Some(tid)) => self.store.get_node_versioned(node_id, epoch, tid),
                _ => self.store.get_node(node_id),
            };
            let Some(node) = node_opt else { continue };

            let has_all_labels = self.config.labels.iter().all(|label| node.has_label(label));
            if !has_all_labels {
                continue;
            }

            let has_all_props = resolved_match_props.iter().all(|(key, expected_value)| {
                let prop = node.properties.get(&PropertyKey::new(key.as_str()));
                if expected_value.is_null() {
                    // Null in a MERGE pattern matches both absent and explicitly null properties
                    prop.map_or(true, |v| v.is_null())
                } else {
                    prop.is_some_and(|v| v == expected_value)
                }
            });

            if has_all_props {
                return Some(node_id);
            }
        }

        None
    }

    /// Merges match and ON CREATE property lists, with ON CREATE values
    /// overriding match values for the same key.
    fn merge_node_props(
        resolved_match_props: &[(String, Value)],
        resolved_create_props: &[(String, Value)],
    ) -> Vec<(String, Value)> {
        let mut merged: Vec<(String, Value)> = resolved_match_props.to_vec();
        for (k, v) in resolved_create_props {
            if let Some(existing) = merged.iter_mut().find(|(key, _)| key == k) {
                existing.1 = v.clone();
            } else {
                merged.push((k.clone(), v.clone()));
            }
        }
        merged
    }

    /// Writes a freshly-created node's properties through the versioned
    /// API when the operator is participating in a transaction, so that
    /// rollback can undo them via the MVCC undo log. Falls back to the
    /// non-versioned setter only when no transaction context is attached
    /// (test paths and standalone operator construction).
    fn write_node_props(&self, id: NodeId, props: &[(PropertyKey, Value)]) {
        if let Some(tid) = self.transaction_id {
            for (key, value) in props {
                self.store
                    .set_node_property_versioned(id, key.as_str(), value.clone(), tid);
            }
        } else {
            for (key, value) in props {
                self.store
                    .set_node_property(id, key.as_str(), value.clone());
            }
        }
    }

    /// Creates a node through the versioned API so the create itself is
    /// tagged with the operator's transaction (when one is attached) and
    /// can be undone by transaction rollback. The non-versioned
    /// `create_node_with_props` would tag the create with
    /// [`TransactionId::SYSTEM`], leaving the node visible after the
    /// surrounding session transaction rolls back.
    fn store_create_node(&self, label_refs: &[&str]) -> NodeId {
        let epoch = self
            .viewing_epoch
            .unwrap_or_else(|| self.store.current_epoch());
        let tx = self.transaction_id.unwrap_or(TransactionId::SYSTEM);
        self.store.create_node_versioned(label_refs, epoch, tx)
    }

    /// Creates a new node with the specified labels and resolved properties.
    fn create_node(
        &self,
        resolved_match_props: &[(String, Value)],
        resolved_create_props: &[(String, Value)],
    ) -> Result<NodeId, super::OperatorError> {
        let all_props = Self::merge_node_props(resolved_match_props, resolved_create_props);

        // Validate constraints before creating the node
        if let Some(ref validator) = self.validator {
            validator.validate_node_labels_allowed(&self.config.labels)?;
            for (name, value) in &all_props {
                validator.validate_node_property(&self.config.labels, name, value)?;
                validator.check_unique_node_property(&self.config.labels, name, value)?;
            }
            validator.validate_node_complete(&self.config.labels, &all_props)?;
        }

        let prop_pairs: Vec<(PropertyKey, Value)> = all_props
            .into_iter()
            .map(|(k, v)| (PropertyKey::new(k.as_str()), v))
            .collect();

        let labels: Vec<&str> = self.config.labels.iter().map(String::as_str).collect();
        let id = self.store_create_node(&labels);
        self.write_node_props(id, &prop_pairs);
        Ok(id)
    }

    /// Phase one of the two-phase create path: creates the node from match
    /// properties only, deferring the completeness check until ON CREATE
    /// expression properties are resolved (since those properties may
    /// satisfy NOT NULL / PRIMARY KEY requirements that match props alone
    /// would fail). Per-property type checks and uniqueness checks for the
    /// match properties still run here.
    ///
    /// Both the create and the property writes go through the versioned
    /// API, so a failure in phase two (or in `apply_on_match`) is undone
    /// when the surrounding session transaction rolls back. Without that,
    /// the node would persist as an orphan visible to later queries.
    fn create_node_phase_one(
        &self,
        resolved_match_props: &[(String, Value)],
    ) -> Result<NodeId, super::OperatorError> {
        if let Some(ref validator) = self.validator {
            validator.validate_node_labels_allowed(&self.config.labels)?;
            for (name, value) in resolved_match_props {
                validator.validate_node_property(&self.config.labels, name, value)?;
                validator.check_unique_node_property(&self.config.labels, name, value)?;
            }
        }

        let prop_pairs: Vec<(PropertyKey, Value)> = resolved_match_props
            .iter()
            .map(|(k, v)| (PropertyKey::new(k.as_str()), v.clone()))
            .collect();

        let labels: Vec<&str> = self.config.labels.iter().map(String::as_str).collect();
        let id = self.store_create_node(&labels);
        self.write_node_props(id, &prop_pairs);
        Ok(id)
    }

    /// Phase two of the two-phase create path: validates ON CREATE
    /// properties (type, uniqueness) and the full property set
    /// (completeness) after expressions have been evaluated against the
    /// freshly created node, but before the values are written. The just
    /// created node holds only match properties at this point, so a
    /// uniqueness check on an ON CREATE property cannot conflict with the
    /// node itself.
    fn validate_on_create_phase_two(
        &self,
        resolved_match_props: &[(String, Value)],
        resolved_create_props: &[(String, Value)],
    ) -> Result<(), super::OperatorError> {
        let Some(ref validator) = self.validator else {
            return Ok(());
        };
        for (name, value) in resolved_create_props {
            validator.validate_node_property(&self.config.labels, name, value)?;
            validator.check_unique_node_property(&self.config.labels, name, value)?;
        }
        let all_props = Self::merge_node_props(resolved_match_props, resolved_create_props);
        validator.validate_node_complete(&self.config.labels, &all_props)?;
        Ok(())
    }

    /// Finds or creates a matching node for a single row, applying ON MATCH/ON CREATE.
    fn merge_node_for_row(
        &self,
        chunk: Option<&DataChunk>,
        row: usize,
    ) -> Result<NodeId, super::OperatorError> {
        let store_ref: &dyn GraphStore = self.store.as_ref();
        // Match properties cannot reference the MERGE variable (ISO §15.5),
        // so they resolve against the input chunk directly.
        let resolved_match =
            Self::resolve_properties(&self.config.match_properties, chunk, row, store_ref);

        if let Some(existing_id) = self.find_matching_node(&resolved_match) {
            // Resolve ON MATCH SET against an augmented row containing the
            // matched node id, so `coalesce(n.x, 0)` can read the live value.
            let resolved_on_match = self.resolve_action_properties(
                &self.config.on_match_properties,
                chunk,
                row,
                existing_id,
            )?;
            self.apply_on_match(existing_id, &resolved_on_match)?;
            Ok(existing_id)
        } else if Self::has_expression_source(&self.config.on_create_properties) {
            // Two-phase create: build the node from match properties first so
            // the new id exists, then evaluate ON CREATE against an augmented
            // row referencing it, then write those properties via the same
            // path used for ON MATCH SET. Completeness and uniqueness on the
            // ON CREATE properties are validated between phases via
            // `validate_on_create_phase_two` so neither premature rejection
            // (when ON CREATE supplies a NOT NULL / PRIMARY KEY property) nor
            // silent constraint bypass (UNIQUE on an ON CREATE property)
            // occurs.
            let new_id = self.create_node_phase_one(&resolved_match)?;
            let resolved_on_create = self.resolve_action_properties(
                &self.config.on_create_properties,
                chunk,
                row,
                new_id,
            )?;
            self.validate_on_create_phase_two(&resolved_match, &resolved_on_create)?;
            self.apply_on_match(new_id, &resolved_on_create)?;
            Ok(new_id)
        } else {
            // Fast path: no runtime expressions; create with all properties at once.
            let resolved_on_create =
                Self::resolve_properties(&self.config.on_create_properties, chunk, row, store_ref);
            self.create_node(&resolved_match, &resolved_on_create)
        }
    }

    /// Applies ON MATCH properties to an existing node.
    fn apply_on_match(
        &self,
        node_id: NodeId,
        resolved_on_match: &[(String, Value)],
    ) -> Result<(), super::OperatorError> {
        for (key, value) in resolved_on_match {
            if let Some(ref validator) = self.validator {
                validator.validate_node_property(&self.config.labels, key, value)?;
            }
            if let Some(tid) = self.transaction_id {
                self.store
                    .set_node_property_versioned(node_id, key.as_str(), value.clone(), tid);
            } else {
                self.store
                    .set_node_property(node_id, key.as_str(), value.clone());
            }
        }
        Ok(())
    }
}

impl Operator for MergeOperator {
    fn next(&mut self) -> OperatorResult {
        // When we have an input operator, pass through input rows with the
        // merged node ID appended (used for chained inline MERGE patterns).
        if let Some(ref mut input) = self.input {
            if let Some(chunk) = input.next()? {
                let mut builder =
                    DataChunkBuilder::with_capacity(&self.config.output_schema, chunk.row_count());

                for row in chunk.selected_indices() {
                    // Reject NULL bound variables (e.g., from unmatched OPTIONAL MATCH)
                    if let Some(bound_col) = self.config.bound_variable_column {
                        let is_null = chunk.column(bound_col).map_or(true, |col| col.is_null(row));
                        if is_null {
                            return Err(super::OperatorError::TypeMismatch {
                                expected: format!(
                                    "non-null node for MERGE variable '{}'",
                                    self.config.variable
                                ),
                                found: "NULL".to_string(),
                            });
                        }
                    }

                    // Merge the node per-row: resolve properties from this row
                    let node_id = self.merge_node_for_row(Some(&chunk), row)?;

                    // Copy input columns to output
                    for col_idx in 0..chunk.column_count() {
                        if let (Some(src), Some(dst)) =
                            (chunk.column(col_idx), builder.column_mut(col_idx))
                        {
                            if let Some(val) = src.get_value(row) {
                                dst.push_value(val);
                            } else {
                                dst.push_value(Value::Null);
                            }
                        }
                    }

                    // Append the merged node ID
                    if let Some(dst) = builder.column_mut(self.config.output_column) {
                        dst.push_node_id(node_id);
                    }

                    builder.advance_row();
                }

                return Ok(Some(builder.finish()));
            }
            return Ok(None);
        }

        // Standalone mode (no input operator)
        if self.executed {
            return Ok(None);
        }
        self.executed = true;

        let node_id = self.merge_node_for_row(None, 0)?;

        let mut builder = DataChunkBuilder::new(&self.config.output_schema);
        if let Some(dst) = builder.column_mut(self.config.output_column) {
            dst.push_node_id(node_id);
        }
        builder.advance_row();

        Ok(Some(builder.finish()))
    }

    fn reset(&mut self) {
        self.executed = false;
        if let Some(ref mut input) = self.input {
            input.reset();
        }
    }

    fn name(&self) -> &'static str {
        "Merge"
    }

    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
        self
    }
}

/// Configuration for a relationship merge operation.
pub struct MergeRelationshipConfig {
    /// Column index for the source node ID in the input.
    pub source_column: usize,
    /// Column index for the target node ID in the input.
    pub target_column: usize,
    /// Variable name for the source node (for error messages).
    pub source_variable: String,
    /// Variable name for the target node (for error messages).
    pub target_variable: String,
    /// Relationship type to match/create.
    pub edge_type: String,
    /// Properties that must match (also used for creation).
    pub match_properties: Vec<(String, PropertySource)>,
    /// Properties to set on CREATE.
    pub on_create_properties: Vec<(String, PropertySource)>,
    /// Properties to set on MATCH.
    pub on_match_properties: Vec<(String, PropertySource)>,
    /// Output schema (input columns + edge column).
    pub output_schema: Vec<LogicalType>,
    /// Column index for the edge variable in the output.
    pub edge_output_column: usize,
}

/// Merge operator for relationship patterns.
///
/// Takes input rows containing source and target node IDs, then for each row:
/// 1. Searches for an existing relationship matching the type and properties
/// 2. If found, applies ON MATCH properties and returns the existing edge
/// 3. If not found, creates a new relationship and applies ON CREATE properties
pub struct MergeRelationshipOperator {
    /// The graph store.
    store: Arc<dyn GraphStoreMut>,
    /// Input operator providing rows with source/target node columns.
    input: Box<dyn Operator>,
    /// Merge configuration.
    config: MergeRelationshipConfig,
    /// Epoch for MVCC versioning.
    viewing_epoch: Option<EpochId>,
    /// Transaction ID for undo log tracking.
    transaction_id: Option<TransactionId>,
    /// Optional constraint validator for schema enforcement.
    validator: Option<Arc<dyn ConstraintValidator>>,
    /// Search-store handle for evaluating `PropertySource::Expression`.
    search_store: Option<Arc<dyn GraphStoreSearch>>,
    /// Session context for expression evaluation.
    session_context: SessionContext,
}

impl MergeRelationshipOperator {
    /// Creates a new merge relationship operator.
    pub fn new(
        store: Arc<dyn GraphStoreMut>,
        input: Box<dyn Operator>,
        config: MergeRelationshipConfig,
    ) -> Self {
        Self {
            store,
            input,
            config,
            viewing_epoch: None,
            transaction_id: None,
            validator: None,
            search_store: None,
            session_context: SessionContext::default(),
        }
    }

    /// Sets the transaction context for versioned mutations.
    pub fn with_transaction_context(
        mut self,
        epoch: EpochId,
        transaction_id: Option<TransactionId>,
    ) -> Self {
        self.viewing_epoch = Some(epoch);
        self.transaction_id = transaction_id;
        self
    }

    /// Sets the constraint validator for schema enforcement.
    pub fn with_validator(mut self, validator: Arc<dyn ConstraintValidator>) -> Self {
        self.validator = Some(validator);
        self
    }

    /// Provides a search-store handle for runtime expression evaluation.
    #[must_use]
    pub fn with_search_store(mut self, search_store: Arc<dyn GraphStoreSearch>) -> Self {
        self.search_store = Some(search_store);
        self
    }

    /// Sets the session context used during expression evaluation.
    #[must_use]
    pub fn with_session_context(mut self, context: SessionContext) -> Self {
        self.session_context = context;
        self
    }

    /// Builds a one-row chunk containing the input row plus the merged edge
    /// in the column reserved for the MERGE relationship variable.
    fn build_augmented_edge_chunk(
        &self,
        chunk: &DataChunk,
        row: usize,
        merged_edge: EdgeId,
    ) -> DataChunk {
        let mut builder = DataChunkBuilder::with_capacity(&self.config.output_schema, 1);
        for col_idx in 0..chunk.column_count() {
            let val = chunk
                .column(col_idx)
                .and_then(|c| c.get_value(row))
                .unwrap_or(Value::Null);
            if let Some(dst) = builder.column_mut(col_idx) {
                dst.push_value(val);
            }
        }
        if let Some(dst) = builder.column_mut(self.config.edge_output_column) {
            dst.push_edge_id(merged_edge);
        }
        builder.advance_row();
        builder.finish()
    }

    /// Resolves an action-property list (ON CREATE / ON MATCH SET) against
    /// an augmented row that includes the merged edge id. Falls back to the
    /// fast path when no expression sources are present.
    fn resolve_action_properties(
        &self,
        props: &[(String, PropertySource)],
        chunk: &DataChunk,
        row: usize,
        merged_edge: EdgeId,
    ) -> Result<Vec<(String, Value)>, super::OperatorError> {
        if !MergeOperator::has_expression_source(props) {
            return Ok(MergeOperator::resolve_properties(
                props,
                Some(chunk),
                row,
                self.store.as_ref(),
            ));
        }

        let augmented = self.build_augmented_edge_chunk(chunk, row, merged_edge);
        let mut out = Vec::with_capacity(props.len());
        for (name, source) in props {
            let value = match source {
                PropertySource::Expression {
                    expr,
                    variable_columns,
                } => {
                    let search_store = self.search_store.as_ref().ok_or_else(|| {
                        super::OperatorError::Execution(
                            "MERGE expression source requires search store; planner did not attach one"
                                .to_string(),
                        )
                    })?;
                    let mut predicate = ExpressionPredicate::new(
                        (**expr).clone(),
                        variable_columns.clone(),
                        Arc::clone(search_store),
                    )
                    .with_session_context(self.session_context.clone());
                    if let Some(epoch) = self.viewing_epoch {
                        predicate = predicate.with_transaction_context(epoch, self.transaction_id);
                    }
                    predicate.eval_at(&augmented, 0).unwrap_or(Value::Null)
                }
                _ => source.resolve(&augmented, 0, self.store.as_ref()),
            };
            out.push((name.clone(), value));
        }
        Ok(out)
    }

    /// Tries to find a matching relationship between source and target.
    fn find_matching_edge(
        &self,
        src: NodeId,
        dst: NodeId,
        resolved_match_props: &[(String, Value)],
    ) -> Option<EdgeId> {
        use crate::graph::Direction;

        for (target, edge_id) in self.store.edges_from(src, Direction::Outgoing) {
            if target != dst {
                continue;
            }

            if let Some(edge) = self.store.get_edge(edge_id) {
                if edge.edge_type.as_str() != self.config.edge_type {
                    continue;
                }

                let has_all_props = resolved_match_props
                    .iter()
                    .all(|(key, expected)| edge.get_property(key).is_some_and(|v| v == expected));

                if has_all_props {
                    return Some(edge_id);
                }
            }
        }

        None
    }

    /// Versioned-API edge create. See [`MergeOperator::store_create_node`]
    /// for the rationale: the create itself must be tagged with the
    /// operator's transaction so that rollback can undo it.
    fn store_create_edge(&self, src: NodeId, dst: NodeId) -> EdgeId {
        let epoch = self
            .viewing_epoch
            .unwrap_or_else(|| self.store.current_epoch());
        let tx = self.transaction_id.unwrap_or(TransactionId::SYSTEM);
        self.store
            .create_edge_versioned(src, dst, &self.config.edge_type, epoch, tx)
    }

    /// Writes a freshly-created edge's properties through the versioned
    /// setter when a transaction is attached, mirroring
    /// [`MergeOperator::write_node_props`].
    fn write_edge_props(&self, id: EdgeId, props: &[(PropertyKey, Value)]) {
        if let Some(tid) = self.transaction_id {
            for (key, value) in props {
                self.store
                    .set_edge_property_versioned(id, key.as_str(), value.clone(), tid);
            }
        } else {
            for (key, value) in props {
                self.store
                    .set_edge_property(id, key.as_str(), value.clone());
            }
        }
    }

    /// Creates a new edge with resolved match and on_create properties.
    fn create_edge(
        &self,
        src: NodeId,
        dst: NodeId,
        resolved_match_props: &[(String, Value)],
        resolved_create_props: &[(String, Value)],
    ) -> Result<EdgeId, super::OperatorError> {
        let all_props =
            MergeOperator::merge_node_props(resolved_match_props, resolved_create_props);

        // Validate constraints before creating the edge
        if let Some(ref validator) = self.validator {
            validator.validate_edge_type_allowed(&self.config.edge_type)?;
            for (name, value) in &all_props {
                validator.validate_edge_property(&self.config.edge_type, name, value)?;
            }
            validator.validate_edge_complete(&self.config.edge_type, &all_props)?;
        }

        let prop_pairs: Vec<(PropertyKey, Value)> = all_props
            .into_iter()
            .map(|(k, v)| (PropertyKey::new(k.as_str()), v))
            .collect();

        let id = self.store_create_edge(src, dst);
        self.write_edge_props(id, &prop_pairs);
        Ok(id)
    }

    /// Phase one of the two-phase edge create path: validates per-property
    /// types on match props and writes the edge, deferring the completeness
    /// check until ON CREATE expression properties are resolved. See
    /// [`MergeOperator::create_node_phase_one`] for the rationale.
    ///
    /// Both the create and the property writes go through the versioned
    /// API, so a failure in phase two (or in `apply_on_match_edge`) is
    /// undone when the surrounding session transaction rolls back.
    fn create_edge_phase_one(
        &self,
        src: NodeId,
        dst: NodeId,
        resolved_match_props: &[(String, Value)],
    ) -> Result<EdgeId, super::OperatorError> {
        if let Some(ref validator) = self.validator {
            validator.validate_edge_type_allowed(&self.config.edge_type)?;
            for (name, value) in resolved_match_props {
                validator.validate_edge_property(&self.config.edge_type, name, value)?;
            }
        }

        let prop_pairs: Vec<(PropertyKey, Value)> = resolved_match_props
            .iter()
            .map(|(k, v)| (PropertyKey::new(k.as_str()), v.clone()))
            .collect();

        let id = self.store_create_edge(src, dst);
        self.write_edge_props(id, &prop_pairs);
        Ok(id)
    }

    /// Phase two of the two-phase edge create path: validates ON CREATE
    /// edge properties and the full property set for completeness after
    /// expressions have been evaluated against the freshly created edge.
    fn validate_on_create_edge_phase_two(
        &self,
        resolved_match_props: &[(String, Value)],
        resolved_create_props: &[(String, Value)],
    ) -> Result<(), super::OperatorError> {
        let Some(ref validator) = self.validator else {
            return Ok(());
        };
        for (name, value) in resolved_create_props {
            validator.validate_edge_property(&self.config.edge_type, name, value)?;
        }
        let all_props =
            MergeOperator::merge_node_props(resolved_match_props, resolved_create_props);
        validator.validate_edge_complete(&self.config.edge_type, &all_props)?;
        Ok(())
    }

    /// Applies ON MATCH properties to an existing edge.
    fn apply_on_match_edge(
        &self,
        edge_id: EdgeId,
        resolved_on_match: &[(String, Value)],
    ) -> Result<(), super::OperatorError> {
        for (key, value) in resolved_on_match {
            if let Some(ref validator) = self.validator {
                validator.validate_edge_property(&self.config.edge_type, key, value)?;
            }
            if let Some(tid) = self.transaction_id {
                self.store
                    .set_edge_property_versioned(edge_id, key.as_str(), value.clone(), tid);
            } else {
                self.store
                    .set_edge_property(edge_id, key.as_str(), value.clone());
            }
        }
        Ok(())
    }
}

impl Operator for MergeRelationshipOperator {
    fn next(&mut self) -> OperatorResult {
        use super::OperatorError;

        if let Some(chunk) = self.input.next()? {
            let mut builder =
                DataChunkBuilder::with_capacity(&self.config.output_schema, chunk.row_count());

            for row in chunk.selected_indices() {
                let src_val = chunk
                    .column(self.config.source_column)
                    .and_then(|c| c.get_node_id(row))
                    .ok_or_else(|| OperatorError::TypeMismatch {
                        expected: format!(
                            "non-null node for MERGE variable '{}'",
                            self.config.source_variable
                        ),
                        found: "NULL".to_string(),
                    })?;

                let dst_val = chunk
                    .column(self.config.target_column)
                    .and_then(|c| c.get_node_id(row))
                    .ok_or_else(|| OperatorError::TypeMismatch {
                        expected: format!(
                            "non-null node for MERGE variable '{}'",
                            self.config.target_variable
                        ),
                        found: "None".to_string(),
                    })?;

                let store_ref: &dyn GraphStore = self.store.as_ref();
                let resolved_match = MergeOperator::resolve_properties(
                    &self.config.match_properties,
                    Some(&chunk),
                    row,
                    store_ref,
                );

                let edge_id = if let Some(existing) =
                    self.find_matching_edge(src_val, dst_val, &resolved_match)
                {
                    let resolved_on_match = self.resolve_action_properties(
                        &self.config.on_match_properties,
                        &chunk,
                        row,
                        existing,
                    )?;
                    self.apply_on_match_edge(existing, &resolved_on_match)?;
                    existing
                } else if MergeOperator::has_expression_source(&self.config.on_create_properties) {
                    // Two-phase create so ON CREATE expressions can reference
                    // the new edge. Completeness validation is deferred to
                    // `validate_on_create_edge_phase_two` so an ON CREATE
                    // property is allowed to satisfy a NOT NULL constraint
                    // that match properties alone would fail.
                    let new_id = self.create_edge_phase_one(src_val, dst_val, &resolved_match)?;
                    let resolved_on_create = self.resolve_action_properties(
                        &self.config.on_create_properties,
                        &chunk,
                        row,
                        new_id,
                    )?;
                    self.validate_on_create_edge_phase_two(&resolved_match, &resolved_on_create)?;
                    self.apply_on_match_edge(new_id, &resolved_on_create)?;
                    new_id
                } else {
                    let resolved_on_create = MergeOperator::resolve_properties(
                        &self.config.on_create_properties,
                        Some(&chunk),
                        row,
                        store_ref,
                    );
                    self.create_edge(src_val, dst_val, &resolved_match, &resolved_on_create)?
                };

                // Copy input columns to output, then add the edge column
                for col_idx in 0..self.config.output_schema.len() {
                    if col_idx == self.config.edge_output_column {
                        if let Some(dst_col) = builder.column_mut(col_idx) {
                            dst_col.push_edge_id(edge_id);
                        }
                    } else if let (Some(src_col), Some(dst_col)) =
                        (chunk.column(col_idx), builder.column_mut(col_idx))
                        && let Some(val) = src_col.get_value(row)
                    {
                        dst_col.push_value(val);
                    }
                }

                builder.advance_row();
            }

            return Ok(Some(builder.finish()));
        }

        Ok(None)
    }

    fn reset(&mut self) {
        self.input.reset();
    }

    fn name(&self) -> &'static str {
        "MergeRelationship"
    }

    fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
        self
    }
}

#[cfg(all(test, feature = "lpg"))]
mod tests {
    use super::*;
    use crate::graph::lpg::LpgStore;

    fn const_props(props: Vec<(&str, Value)>) -> Vec<(String, PropertySource)> {
        props
            .into_iter()
            .map(|(k, v)| (k.to_string(), PropertySource::Constant(v)))
            .collect()
    }

    #[test]
    fn test_merge_creates_new_node() {
        let store: Arc<dyn GraphStoreMut> = Arc::new(LpgStore::new().unwrap());

        // MERGE should create a new node since none exists
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Alix".into()))]),
                on_create_properties: vec![],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let result = merge.next().unwrap();
        assert!(result.is_some());

        // Verify node was created
        let nodes = store.nodes_by_label("Person");
        assert_eq!(nodes.len(), 1);

        let node = store.get_node(nodes[0]).unwrap();
        assert!(node.has_label("Person"));
        assert_eq!(
            node.properties.get(&PropertyKey::new("name")),
            Some(&Value::String("Alix".into()))
        );
    }

    #[test]
    fn test_merge_matches_existing_node() {
        let store: Arc<dyn GraphStoreMut> = Arc::new(LpgStore::new().unwrap());

        // Create an existing node
        store.create_node_with_props(
            &["Person"],
            &[(PropertyKey::new("name"), Value::String("Gus".into()))],
        );

        // MERGE should find the existing node
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Gus".into()))]),
                on_create_properties: vec![],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let result = merge.next().unwrap();
        assert!(result.is_some());

        // Verify only one node exists (no new node created)
        let nodes = store.nodes_by_label("Person");
        assert_eq!(nodes.len(), 1);
    }

    #[test]
    fn test_merge_with_on_create() {
        let store: Arc<dyn GraphStoreMut> = Arc::new(LpgStore::new().unwrap());

        // MERGE with ON CREATE SET
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Vincent".into()))]),
                on_create_properties: const_props(vec![("created", Value::Bool(true))]),
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let _ = merge.next().unwrap();

        // Verify node has both match properties and on_create properties
        let nodes = store.nodes_by_label("Person");
        let node = store.get_node(nodes[0]).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("name")),
            Some(&Value::String("Vincent".into()))
        );
        assert_eq!(
            node.properties.get(&PropertyKey::new("created")),
            Some(&Value::Bool(true))
        );
    }

    #[test]
    fn test_merge_with_on_match() {
        let store: Arc<dyn GraphStoreMut> = Arc::new(LpgStore::new().unwrap());

        // Create an existing node
        let node_id = store.create_node_with_props(
            &["Person"],
            &[(PropertyKey::new("name"), Value::String("Jules".into()))],
        );

        // MERGE with ON MATCH SET
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Jules".into()))]),
                on_create_properties: vec![],
                on_match_properties: const_props(vec![("updated", Value::Bool(true))]),
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let _ = merge.next().unwrap();

        // Verify node has the on_match property added
        let node = store.get_node(node_id).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("updated")),
            Some(&Value::Bool(true))
        );
    }

    #[test]
    fn test_merge_uses_property_index() {
        let lpg_store = Arc::new(LpgStore::new().unwrap());
        lpg_store.create_property_index("name");
        assert!(lpg_store.has_property_index("name"));

        // Use the trait object for node creation so the &[(PropertyKey, Value)] signature applies.
        let store: Arc<dyn GraphStoreMut> = lpg_store;

        for i in 0..50u32 {
            store.create_node_with_props(
                &["Person"],
                &[(
                    PropertyKey::new("name"),
                    Value::String(format!("person_{i}").into()),
                )],
            );
        }

        let target_id = store.create_node_with_props(
            &["Person"],
            &[(PropertyKey::new("name"), Value::String("Beatrix".into()))],
        );

        // MERGE should find the existing node via index lookup
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Beatrix".into()))]),
                on_create_properties: vec![],
                on_match_properties: const_props(vec![("found", Value::Bool(true))]),
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let result = merge.next().unwrap();
        assert!(result.is_some());

        // ON MATCH should have fired on the correct node
        let node = store.get_node(target_id).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("found")),
            Some(&Value::Bool(true))
        );

        // No new node should have been created
        let persons = store.nodes_by_label("Person");
        assert_eq!(persons.len(), 51);
    }

    #[test]
    fn test_merge_creates_via_index_miss() {
        let lpg_store = Arc::new(LpgStore::new().unwrap());
        lpg_store.create_property_index("name");

        let store: Arc<dyn GraphStoreMut> = lpg_store;

        store.create_node_with_props(
            &["Person"],
            &[(PropertyKey::new("name"), Value::String("Django".into()))],
        );

        // MERGE for a name not in the index — should create
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: const_props(vec![("name", Value::String("Shosanna".into()))]),
                on_create_properties: const_props(vec![("created", Value::Bool(true))]),
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );

        let result = merge.next().unwrap();
        assert!(result.is_some());

        let persons = store.nodes_by_label("Person");
        assert_eq!(persons.len(), 2);

        let new_nodes: Vec<_> = persons
            .iter()
            .filter_map(|&id| store.get_node(id))
            .filter(|n| {
                n.properties.get(&PropertyKey::new("name"))
                    == Some(&Value::String("Shosanna".into()))
            })
            .collect();
        assert_eq!(new_nodes.len(), 1);
        assert_eq!(
            new_nodes[0].properties.get(&PropertyKey::new("created")),
            Some(&Value::Bool(true))
        );
    }

    // GrafeoDB/grafeo#317. Operator-level test: a `PropertySource::Expression`
    // for ON CREATE / ON MATCH SET must evaluate against an augmented row that
    // contains the merged node, not against the (potentially absent) input row.

    #[test]
    fn test_merge_on_match_resolves_expression_against_merged_node() {
        use super::super::filter::FilterExpression;
        use crate::graph::lpg::LpgStore;
        use std::collections::HashMap;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;
        let search: Arc<dyn GraphStoreSearch> = Arc::clone(&lpg) as Arc<dyn GraphStoreSearch>;

        // Pre-create the matching node so the MERGE goes into the ON MATCH branch.
        let id = store.create_node_with_props(
            &["Item"],
            &[
                (PropertyKey::new("val"), Value::Int64(1)),
                (PropertyKey::new("x"), Value::Int64(7)),
            ],
        );

        // ON MATCH SET n.x = n.x + 5
        let expr = FilterExpression::Binary {
            left: Box::new(FilterExpression::Property {
                variable: "n".to_string(),
                property: "x".to_string(),
            }),
            op: super::super::filter::BinaryFilterOp::Add,
            right: Box::new(FilterExpression::Literal(Value::Int64(5))),
        };
        let mut variable_columns = HashMap::new();
        // Standalone MERGE: input is None, so the augmented row only has the
        // MERGE variable column at index 0.
        variable_columns.insert("n".to_string(), 0_usize);

        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Item".to_string()],
                match_properties: const_props(vec![("val", Value::Int64(1))]),
                on_create_properties: vec![],
                on_match_properties: vec![(
                    "x".to_string(),
                    PropertySource::Expression {
                        expr: Box::new(expr),
                        variable_columns,
                    },
                )],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        )
        .with_search_store(Arc::clone(&search));

        merge.next().unwrap();

        let node = store.get_node(id).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("x")),
            Some(&Value::Int64(12)),
            "ON MATCH expression must read the merged node, not NULL"
        );
    }

    #[test]
    fn test_merge_on_create_resolves_expression_against_new_node() {
        // ON CREATE coalesce(n.x, 99) must see the freshly-created node and
        // fall back to 99 because `x` is not yet set on it.
        use super::super::filter::FilterExpression;
        use crate::graph::lpg::LpgStore;
        use std::collections::HashMap;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;
        let search: Arc<dyn GraphStoreSearch> = Arc::clone(&lpg) as Arc<dyn GraphStoreSearch>;

        let coalesce = FilterExpression::FunctionCall {
            name: "coalesce".to_string(),
            args: vec![
                FilterExpression::Property {
                    variable: "n".to_string(),
                    property: "x".to_string(),
                },
                FilterExpression::Literal(Value::Int64(99)),
            ],
        };
        let mut variable_columns = HashMap::new();
        variable_columns.insert("n".to_string(), 0_usize);

        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Item".to_string()],
                match_properties: const_props(vec![("val", Value::Int64(1))]),
                on_create_properties: vec![(
                    "x".to_string(),
                    PropertySource::Expression {
                        expr: Box::new(coalesce),
                        variable_columns,
                    },
                )],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        )
        .with_search_store(Arc::clone(&search));

        merge.next().unwrap();

        let nodes = store.nodes_by_label("Item");
        assert_eq!(nodes.len(), 1);
        let node = store.get_node(nodes[0]).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("x")),
            Some(&Value::Int64(99))
        );
    }

    // ── Two-phase constraint validation regression tests ──────────────
    //
    // The two-phase create path (ON CREATE expression sources) used to call
    // `create_node` / `create_edge` with an empty on_create list, which made
    // `validate_node_complete` and `check_unique_node_property` only see the
    // match properties. The fix routes the two phases through dedicated
    // helpers that validate the full property set at the right time.

    use super::ConstraintValidator;

    /// Minimal validator that enforces NOT NULL on a single named property.
    struct RequirePropertyValidator {
        required_property: &'static str,
    }

    impl ConstraintValidator for RequirePropertyValidator {
        fn validate_node_property(
            &self,
            _labels: &[String],
            _key: &str,
            _value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn validate_node_complete(
            &self,
            _labels: &[String],
            properties: &[(String, Value)],
        ) -> Result<(), super::super::OperatorError> {
            if !properties.iter().any(|(k, _)| k == self.required_property) {
                return Err(super::super::OperatorError::ConstraintViolation(format!(
                    "missing required property '{}'",
                    self.required_property
                )));
            }
            Ok(())
        }
        fn check_unique_node_property(
            &self,
            _labels: &[String],
            _key: &str,
            _value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn validate_edge_property(
            &self,
            _edge_type: &str,
            _key: &str,
            _value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn validate_edge_complete(
            &self,
            _edge_type: &str,
            properties: &[(String, Value)],
        ) -> Result<(), super::super::OperatorError> {
            if !properties.iter().any(|(k, _)| k == self.required_property) {
                return Err(super::super::OperatorError::ConstraintViolation(format!(
                    "missing required edge property '{}'",
                    self.required_property
                )));
            }
            Ok(())
        }
    }

    /// Validator that records every uniqueness check it sees, so the test
    /// can assert ON CREATE properties were not silently bypassed.
    struct RecordingUniqueValidator {
        seen: std::sync::Mutex<Vec<(String, Value)>>,
    }

    impl RecordingUniqueValidator {
        fn new() -> Self {
            Self {
                seen: std::sync::Mutex::new(Vec::new()),
            }
        }
    }

    impl ConstraintValidator for RecordingUniqueValidator {
        fn validate_node_property(
            &self,
            _labels: &[String],
            _key: &str,
            _value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn validate_node_complete(
            &self,
            _labels: &[String],
            _properties: &[(String, Value)],
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn check_unique_node_property(
            &self,
            _labels: &[String],
            key: &str,
            value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            self.seen
                .lock()
                .unwrap()
                .push((key.to_string(), value.clone()));
            Ok(())
        }
        fn validate_edge_property(
            &self,
            _edge_type: &str,
            _key: &str,
            _value: &Value,
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
        fn validate_edge_complete(
            &self,
            _edge_type: &str,
            _properties: &[(String, Value)],
        ) -> Result<(), super::super::OperatorError> {
            Ok(())
        }
    }

    fn coalesce_n_x_else(default: i64) -> super::super::filter::FilterExpression {
        use super::super::filter::FilterExpression;
        FilterExpression::FunctionCall {
            name: "coalesce".to_string(),
            args: vec![
                FilterExpression::Property {
                    variable: "n".to_string(),
                    property: "x".to_string(),
                },
                FilterExpression::Literal(Value::Int64(default)),
            ],
        }
    }

    #[test]
    fn test_merge_two_phase_completeness_uses_full_property_set() {
        // Regression: phase one used to run completeness against match
        // properties only, falsely rejecting an ON CREATE property that
        // satisfies a NOT NULL requirement. With the fix, completeness is
        // checked once both phases have produced their properties.
        use crate::graph::lpg::LpgStore;
        use std::collections::HashMap;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;
        let search: Arc<dyn GraphStoreSearch> = Arc::clone(&lpg) as Arc<dyn GraphStoreSearch>;

        let mut variable_columns = HashMap::new();
        variable_columns.insert("n".to_string(), 0_usize);

        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Item".to_string()],
                match_properties: const_props(vec![("val", Value::Int64(1))]),
                // ON CREATE supplies the NOT NULL property `x`.
                on_create_properties: vec![(
                    "x".to_string(),
                    PropertySource::Expression {
                        expr: Box::new(coalesce_n_x_else(99)),
                        variable_columns,
                    },
                )],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        )
        .with_search_store(Arc::clone(&search))
        .with_validator(Arc::new(RequirePropertyValidator {
            required_property: "x",
        }));

        merge
            .next()
            .expect("MERGE must succeed because ON CREATE supplies the required property");

        let nodes = store.nodes_by_label("Item");
        assert_eq!(nodes.len(), 1);
        let node = store.get_node(nodes[0]).unwrap();
        assert_eq!(
            node.properties.get(&PropertyKey::new("x")),
            Some(&Value::Int64(99)),
            "ON CREATE expression value must be persisted"
        );
    }

    #[test]
    fn test_merge_two_phase_unique_check_runs_on_on_create_props() {
        // Regression: phase one used to skip uniqueness checks on ON CREATE
        // properties because the empty list passed to `create_node` hid
        // them. The fix runs `check_unique_node_property` for ON CREATE
        // values in phase two.
        use crate::graph::lpg::LpgStore;
        use std::collections::HashMap;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;
        let search: Arc<dyn GraphStoreSearch> = Arc::clone(&lpg) as Arc<dyn GraphStoreSearch>;

        let mut variable_columns = HashMap::new();
        variable_columns.insert("n".to_string(), 0_usize);

        let recorder = Arc::new(RecordingUniqueValidator::new());

        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Item".to_string()],
                match_properties: const_props(vec![("val", Value::Int64(1))]),
                on_create_properties: vec![(
                    "x".to_string(),
                    PropertySource::Expression {
                        expr: Box::new(coalesce_n_x_else(42)),
                        variable_columns,
                    },
                )],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        )
        .with_search_store(Arc::clone(&search))
        .with_validator(Arc::clone(&recorder) as Arc<dyn ConstraintValidator>);

        merge.next().unwrap();

        let seen = recorder.seen.lock().unwrap().clone();
        assert!(
            seen.iter().any(|(k, v)| k == "x" && *v == Value::Int64(42)),
            "uniqueness check must fire for ON CREATE expression property `x`, observed: {seen:?}"
        );
    }

    #[test]
    fn test_merge_relationship_two_phase_completeness_uses_full_property_set() {
        // Edge-equivalent of the node completeness regression.
        use super::super::filter::FilterExpression;
        use crate::execution::chunk::DataChunkBuilder;
        use crate::graph::lpg::LpgStore;
        use std::collections::HashMap;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;
        let search: Arc<dyn GraphStoreSearch> = Arc::clone(&lpg) as Arc<dyn GraphStoreSearch>;

        let src_id = store.create_node_with_props(
            &["Node"],
            &[(PropertyKey::new("name"), Value::String("Vincent".into()))],
        );
        let dst_id = store.create_node_with_props(
            &["Node"],
            &[(PropertyKey::new("name"), Value::String("Mia".into()))],
        );

        // Build an input chunk: [src_id, dst_id] with the edge column at index 2.
        let input_schema = vec![LogicalType::Node, LogicalType::Node];
        let mut builder = DataChunkBuilder::with_capacity(&input_schema, 1);
        builder.column_mut(0).unwrap().push_node_id(src_id);
        builder.column_mut(1).unwrap().push_node_id(dst_id);
        builder.advance_row();
        let chunk = builder.finish();

        struct OneShot(Option<DataChunk>);
        impl Operator for OneShot {
            fn next(&mut self) -> OperatorResult {
                Ok(self.0.take())
            }
            fn reset(&mut self) {}
            fn name(&self) -> &'static str {
                "OneShot"
            }
            fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
                self
            }
        }

        // ON CREATE supplies NOT NULL property `x` via expression.
        let coalesce = FilterExpression::FunctionCall {
            name: "coalesce".to_string(),
            args: vec![
                FilterExpression::Property {
                    variable: "r".to_string(),
                    property: "x".to_string(),
                },
                FilterExpression::Literal(Value::Int64(7)),
            ],
        };
        let mut variable_columns = HashMap::new();
        // Augmented edge chunk: [src, dst, r] → r at index 2.
        variable_columns.insert("r".to_string(), 2_usize);

        let mut merge_rel = MergeRelationshipOperator::new(
            Arc::clone(&store),
            Box::new(OneShot(Some(chunk))),
            MergeRelationshipConfig {
                source_column: 0,
                target_column: 1,
                source_variable: "a".to_string(),
                target_variable: "b".to_string(),
                edge_type: "KNOWS".to_string(),
                match_properties: vec![],
                on_create_properties: vec![(
                    "x".to_string(),
                    PropertySource::Expression {
                        expr: Box::new(coalesce),
                        variable_columns,
                    },
                )],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node, LogicalType::Node, LogicalType::Edge],
                edge_output_column: 2,
            },
        )
        .with_search_store(Arc::clone(&search))
        .with_validator(Arc::new(RequirePropertyValidator {
            required_property: "x",
        }));

        merge_rel.next().expect(
            "MERGE relationship must succeed because ON CREATE supplies the required property",
        );

        // Confirm the edge was created with `x` set to the expression value.
        use crate::graph::Direction;
        let edges: Vec<EdgeId> = store
            .edges_from(src_id, Direction::Outgoing)
            .into_iter()
            .filter_map(|(target, edge_id)| (target == dst_id).then_some(edge_id))
            .collect();
        assert_eq!(edges.len(), 1, "expected exactly one outgoing edge");
        let edge = store.get_edge(edges[0]).unwrap();
        assert_eq!(edge.get_property("x"), Some(&Value::Int64(7)));
    }

    #[test]
    fn test_merge_in_transaction_dedupes_within_unwind() {
        // Regression: MERGE inside UNWIND, executed in a transaction (auto-
        // commit or otherwise), tags its creates at `EpochId::PENDING`.
        // `find_matching_node`'s read path used to call the unversioned
        // `get_node`, which rejects PENDING records, so subsequent rows of
        // the same UNWIND could not see the node the operator had just
        // created and produced a duplicate per row.
        use crate::execution::chunk::DataChunkBuilder;
        use crate::graph::lpg::LpgStore;
        use grafeo_common::types::EpochId;

        let lpg = Arc::new(LpgStore::new().unwrap());
        let store: Arc<dyn GraphStoreMut> = Arc::clone(&lpg) as Arc<dyn GraphStoreMut>;

        // Build an input chunk emulating `UNWIND [1, 1, 1] AS i`.
        let input_schema = vec![LogicalType::Int64];
        let mut builder = DataChunkBuilder::with_capacity(&input_schema, 3);
        for _ in 0..3 {
            builder.column_mut(0).unwrap().push_value(Value::Int64(1));
            builder.advance_row();
        }
        let chunk = builder.finish();

        struct OneShot(Option<DataChunk>);
        impl Operator for OneShot {
            fn next(&mut self) -> OperatorResult {
                Ok(self.0.take())
            }
            fn reset(&mut self) {}
            fn name(&self) -> &'static str {
                "OneShot"
            }
            fn into_any(self: Box<Self>) -> Box<dyn std::any::Any + Send> {
                self
            }
        }

        // Use a non-SYSTEM transaction so versioned creates land at PENDING.
        let tx = TransactionId::new(1);
        let mut merge = MergeOperator::new(
            Arc::clone(&store),
            Some(Box::new(OneShot(Some(chunk)))),
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Item".to_string()],
                match_properties: vec![("val".to_string(), PropertySource::Column(0))],
                on_create_properties: vec![],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Int64, LogicalType::Node],
                output_column: 1,
                bound_variable_column: None,
            },
        )
        .with_transaction_context(EpochId::INITIAL, Some(tx));

        while merge.next().unwrap().is_some() {}

        // All three rows had val = 1, so MERGE must observe the node it
        // created on iteration 1 in iterations 2 and 3 and skip the create.
        let nodes = store.nodes_by_label("Item");
        let visible: Vec<_> = nodes
            .iter()
            .filter_map(|&id| store.get_node_versioned(id, EpochId::INITIAL, tx))
            .collect();
        assert_eq!(
            visible.len(),
            1,
            "MERGE inside UNWIND must dedupe nodes its own transaction created in earlier rows"
        );
    }

    #[test]
    fn test_merge_into_any() {
        let store: Arc<dyn GraphStoreMut> = Arc::new(LpgStore::new().unwrap());
        let op = MergeOperator::new(
            Arc::clone(&store),
            None,
            MergeConfig {
                variable: "n".to_string(),
                labels: vec!["Person".to_string()],
                match_properties: vec![],
                on_create_properties: vec![],
                on_match_properties: vec![],
                output_schema: vec![LogicalType::Node],
                output_column: 0,
                bound_variable_column: None,
            },
        );
        let any = Box::new(op).into_any();
        assert!(any.downcast::<MergeOperator>().is_ok());
    }
}