cognee-graph 0.1.1

Knowledge-graph database abstraction (embedded Ladybug) for the cognee pipeline.
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
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
//!
//! Implementation of GraphDBTrait using Ladybug (lbug) embedded graph database.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use cognee_utils::redact::redact;
use cognee_utils::tracing_keys::{COGNEE_DB_QUERY, COGNEE_DB_ROW_COUNT};
use lbug::{Connection, Database, SystemConfig, Value as LbugValue};
use serde_json::{Value, json};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tracing::{Span, instrument};

/// Default max database size: 1 GiB.
///
/// Kuzu's built-in default is 8 TiB, which it reserves via a sparse mmap on
/// startup. Many container runtimes (including GitHub Actions runners) cap the
/// process address space well below 8 TiB, causing initialization to fail.
/// 1 GiB is sufficient for typical knowledge-graph workloads and works in all
/// CI environments. Override with `GRAPH_MAX_DB_SIZE` (bytes) for larger graphs.
const DEFAULT_MAX_DB_SIZE: u64 = 1024 * 1024 * 1024;

fn read_max_db_size() -> u64 {
    std::env::var("GRAPH_MAX_DB_SIZE")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_MAX_DB_SIZE)
}

use crate::{EdgeData, GraphDBError, GraphDBResult, GraphDBTrait, GraphNode, NodeData};

/// Strip control characters (`\u{0000}`–`\u{001F}`, except `\t`, `\n`, `\r`)
/// from all string values inside a `serde_json::Value` tree.
///
/// LLM-extracted text occasionally contains stray control characters.
/// They carry no semantic value and corrupt the JSON round-trip through
/// Ladybug's text property storage, so we remove them at the write boundary.
fn sanitize_json_value(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::String(s)
            if s.bytes()
                .any(|b| b < 0x20 && b != b'\t' && b != b'\n' && b != b'\r') =>
        {
            *s = s
                .chars()
                .filter(|&c| c >= '\u{0020}' || c == '\t' || c == '\n' || c == '\r')
                .collect();
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                sanitize_json_value(item);
            }
        }
        serde_json::Value::Object(map) => {
            for val in map.values_mut() {
                sanitize_json_value(val);
            }
        }
        _ => {}
    }
}

/// Defence-in-depth: escape unescaped control characters in a raw JSON
/// string read back from Ladybug, so that `serde_json::from_str` succeeds.
///
/// The primary sanitisation happens on _write_ (see [`sanitize_json_value`]),
/// but data that was stored before the write-side fix still needs this.
fn sanitize_json_control_chars(s: &str) -> Cow<'_, str> {
    if s.bytes().any(|b| b < 0x20) {
        let mut out = String::with_capacity(s.len());
        for ch in s.chars() {
            if ch < '\u{0020}' && ch != '\n' && ch != '\r' && ch != '\t' {
                out.push_str(&format!("\\u{:04x}", ch as u32));
            } else if ch == '\n' {
                out.push_str("\\n");
            } else if ch == '\r' {
                out.push_str("\\r");
            } else if ch == '\t' {
                out.push_str("\\t");
            } else {
                out.push(ch);
            }
        }
        Cow::Owned(out)
    } else {
        Cow::Borrowed(s)
    }
}

/// Ladybug graph database adapter.
///
/// This adapter provides a complete implementation of GraphDBTrait using
/// the Ladybug (lbug) embedded graph database.
///
/// Parity note:
/// Python documents the default file-backed deployment model as a single
/// owning process for SQLite/Ladybug/LanceDB access (for example via the
/// API server `--api-url` mode and single-worker session locks), while also
/// supporting an opt-in Redis-backed shared Ladybug lock for multi-process
/// coordination. Rust currently matches the default single-process model:
/// overlapping writes are serialized in-process, and cross-process locking is
/// intentionally out of scope.
///
/// # Schema
///
/// The adapter creates the following schema:
///
/// ```cypher
/// CREATE NODE TABLE Node (
///     id STRING PRIMARY KEY,
///     name STRING,
///     type STRING,
///     created_at TIMESTAMP,
///     updated_at TIMESTAMP,
///     properties STRING  -- JSON-encoded additional properties
/// )
///
/// CREATE REL TABLE EDGE (
///     FROM Node TO Node,
///     relationship_name STRING,
///     created_at TIMESTAMP,
///     updated_at TIMESTAMP,
///     properties STRING  -- JSON-encoded edge properties
/// )
/// ```
///
/// # Example
///
/// ```ignore
/// use cognee_graph::{LadybugAdapter, GraphDBTrait};
/// use cognee_models::Entity;
///
/// let adapter = LadybugAdapter::new("./my_graph").await?;
/// adapter.initialize().await?;
///
/// // Add nodes
/// let entity = Entity::new("Alice", entity_type, Some("dataset-1"));
/// adapter.add_node(&entity).await?;
/// ```
pub struct LadybugAdapter {
    db_path: String,
    db: Arc<Database>,
    // Single-process assumption: this lock serializes overlapping writes
    // within one process. Cross-process locking is intentionally out of scope.
    write_lock: Arc<Mutex<()>>,
}

impl LadybugAdapter {
    /// Number of columns in node query: id, name, type, properties
    pub const NODE_QUERY_COLUMN_COUNT: usize = 4;

    /// Number of columns in edge query: source_id, target_id, relationship_name, properties
    pub const EDGE_QUERY_COLUMN_COUNT: usize = 4;

    /// Create a new Ladybug adapter.
    ///
    /// # Arguments
    /// * `db_path` - Path to the database directory
    ///
    /// # Returns
    /// A new LadybugAdapter instance
    ///
    /// # Errors
    /// Returns GraphDBError::InitializationError if database creation fails
    ///
    pub async fn new(db_path: &str) -> GraphDBResult<Self> {
        let config = SystemConfig::default().max_db_size(read_max_db_size());
        let db = Database::new(db_path, config).map_err(|e| {
            GraphDBError::InitializationError(format!("Failed to create database: {e}"))
        })?;

        Ok(Self {
            db_path: db_path.to_string(),
            db: Arc::new(db),
            write_lock: Arc::new(Mutex::new(())),
        })
    }

    /// Get the database path.
    pub fn db_path(&self) -> &str {
        &self.db_path
    }

    /// Execute a query and convert results to JSON values.
    ///
    /// Helper method that executes a Cypher query and converts the QueryResult
    /// to a Vec of Vec of JSON values for easier processing.
    #[instrument(
        name = "cognee.db.graph.query",
        level = "info",
        skip_all,
        fields(
            cognee.db.system = "ladybug",
            cognee.db.query = tracing::field::Empty,
            cognee.db.row_count = tracing::field::Empty,
        ),
        err,
    )]
    fn execute_query(&self, query: &str) -> GraphDBResult<Vec<Vec<serde_json::Value>>> {
        // Truncate-then-redact (locked decision 9). The 500-char
        // truncation must come BEFORE redact() so a redacted form
        // longer than 500 chars cannot be re-truncated and split the
        // literal `***REDACTED***` marker. Walk to the last UTF-8
        // char boundary at-or-before byte 500 so non-ASCII queries
        // do not panic on slicing.
        let truncated = if query.len() > 500 {
            let mut end = 500;
            while !query.is_char_boundary(end) {
                end -= 1;
            }
            &query[..end]
        } else {
            query
        };
        Span::current().record(COGNEE_DB_QUERY, redact(truncated).as_ref());

        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        let result = conn
            .query(query)
            .map_err(|e| GraphDBError::QueryError(format!("Query failed: {e}")))?;

        let rows: Vec<Vec<serde_json::Value>> = result
            .map(|row| row.into_iter().map(Self::lbug_value_to_json).collect())
            .collect();

        Span::current().record(COGNEE_DB_ROW_COUNT, rows.len() as i64);
        Ok(rows)
    }

    /// Convert lbug::Value to serde_json::Value
    /// Convert lbug::Value to serde_json::Value
    fn lbug_value_to_json(value: LbugValue) -> serde_json::Value {
        use LbugValue::*;
        match value {
            Null(_) => serde_json::Value::Null,
            Bool(b) => serde_json::Value::Bool(b),
            Int8(i) => json!(i),
            Int16(i) => json!(i),
            Int32(i) => json!(i),
            Int64(i) => json!(i),
            UInt8(i) => json!(i),
            UInt16(i) => json!(i),
            UInt32(i) => json!(i),
            UInt64(i) => json!(i),
            Int128(i) => json!(i.to_string()),
            UUID(u) => json!(u.to_string()),
            Float(f) => json!(f),
            Double(d) => json!(d),
            String(s) => serde_json::Value::String(s),
            Blob(b) => json!(format!("<blob {} bytes>", b.len())),
            Date(d) => json!(d.to_string()),
            Timestamp(ts) => json!(ts.to_string()),
            TimestampTz(ts) => json!(ts.to_string()),
            TimestampNs(ts) => json!(ts.to_string()),
            TimestampMs(ts) => json!(ts.to_string()),
            TimestampSec(ts) => json!(ts.to_string()),
            Interval(interval) => json!(format!("{:?}", interval)),
            InternalID(id) => json!(format!("{:?}", id)),
            Node(node) => {
                let mut obj = serde_json::Map::new();
                obj.insert("id".to_string(), json!(format!("{:?}", node.get_node_id())));
                obj.insert("label".to_string(), json!(node.get_label_name()));
                for (key, val) in node.get_properties() {
                    obj.insert(key.to_string(), Self::lbug_value_to_json(val.clone()));
                }
                serde_json::Value::Object(obj)
            }
            Rel(rel) => {
                let mut obj = serde_json::Map::new();
                obj.insert("label".to_string(), json!(rel.get_label_name()));
                for (key, val) in rel.get_properties() {
                    obj.insert(key.to_string(), Self::lbug_value_to_json(val.clone()));
                }
                serde_json::Value::Object(obj)
            }
            List(_, list) | Array(_, list) => {
                let arr: Vec<serde_json::Value> = list
                    .iter()
                    .map(|v| Self::lbug_value_to_json(v.clone()))
                    .collect();
                serde_json::Value::Array(arr)
            }
            Struct(fields) => {
                let mut obj = serde_json::Map::new();
                for (key, val) in fields {
                    obj.insert(key.clone(), Self::lbug_value_to_json(val.clone()));
                }
                serde_json::Value::Object(obj)
            }
            Map(_, pairs) => {
                let mut obj = serde_json::Map::new();
                for (i, (k, v)) in pairs.iter().enumerate() {
                    obj.insert(format!("key_{i}"), Self::lbug_value_to_json(k.clone()));
                    obj.insert(format!("val_{i}"), Self::lbug_value_to_json(v.clone()));
                }
                serde_json::Value::Object(obj)
            }
            Union { types, value } => {
                let mut obj = serde_json::Map::new();
                obj.insert("union_type_count".to_string(), json!(types.len()));
                obj.insert(
                    "value".to_string(),
                    Self::lbug_value_to_json((*value).clone()),
                );
                serde_json::Value::Object(obj)
            }
            Decimal(d) => json!(d.to_string()),
            RecursiveRel { nodes, rels } => {
                let mut obj = serde_json::Map::new();
                obj.insert("nodes".to_string(), json!(nodes.len()));
                obj.insert("rels".to_string(), json!(rels.len()));
                serde_json::Value::Object(obj)
            }
        }
    }
    /// Build a node properties JSON string from a serializable object.
    ///
    /// Extracts core fields (id, name, type) and serializes remaining fields
    /// as a JSON properties string.
    ///
    fn serialize_to_node_props(&self, node: &serde_json::Value) -> GraphDBResult<NodeProperties> {
        let mut props = if let serde_json::Value::Object(map) = node.clone() {
            map
        } else {
            return Err(GraphDBError::DatabaseError(
                "Expected JSON object".to_string(),
            ));
        };

        let created_at = props
            .get("created_at")
            .and_then(|v| v.as_str())
            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(Utc::now);

        let updated_at = props
            .get("updated_at")
            .and_then(|v| v.as_str())
            .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(Utc::now);

        let id = props
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let name = props
            .remove("name")
            .and_then(|v| v.as_str().map(String::from))
            .unwrap_or_default();

        // Accept both "type" (DataPoint via #[serde(rename = "type")]) and
        // "data_type" (plain structs used in tests and older code).
        let node_type = props
            .get("type")
            .or_else(|| props.get("data_type"))
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown")
            .to_string();

        props.remove("id");
        props.remove("created_at");
        props.remove("updated_at");
        props.remove("type");
        props.remove("data_type");

        // Strip control characters from LLM-produced string values before
        // persisting, so the JSON round-trip through Ladybug stays clean.
        let mut props_value = serde_json::Value::Object(props);
        sanitize_json_value(&mut props_value);

        let properties_json =
            serde_json::to_string(&props_value).map_err(GraphDBError::SerializationError)?;

        Ok(NodeProperties {
            id,
            name,
            node_type,
            created_at,
            updated_at,
            properties: properties_json,
        })
    }

    /// Parse a node from query results.
    ///
    fn parse_node_data(&self, mut data: NodeData) -> GraphDBResult<NodeData> {
        if let Some(props_value) = data.remove("properties")
            && let Some(props_str) = props_value.as_str()
        {
            let clean = sanitize_json_control_chars(props_str);
            let additional_props: HashMap<Cow<'static, str>, serde_json::Value> =
                serde_json::from_str(&clean).map_err(GraphDBError::SerializationError)?;
            data.extend(additional_props);
        }
        Ok(data)
    }

    /// Check if a node matches property filters.
    ///
    /// This method checks if a node matches the given attribute filters.
    /// Core fields (id, name, type) are already filtered in the query,
    /// so this method only checks additional property fields.
    ///
    /// # Arguments
    /// * `node` - The parsed node data to check
    /// * `filters` - HashMap of attribute filters (key -> list of values)
    ///
    /// # Returns
    /// `true` if the node matches all property filters, `false` otherwise
    ///
    fn matches_property_filters(
        &self,
        node: &NodeData,
        filters: &HashMap<Cow<'static, str>, Vec<serde_json::Value>>,
    ) -> bool {
        for (attr, values) in filters {
            // Skip core fields - already filtered in query
            if matches!(attr.as_ref(), "id" | "name" | "type") {
                continue;
            }

            // Check if node has this property and if it matches any value
            if let Some(node_value) = node.get(attr.as_ref()) {
                if !values.iter().any(|filter_value| node_value == filter_value) {
                    return false;
                }
            } else {
                // Property not present = doesn't match filter
                return false;
            }
        }
        true
    }

    fn escape_cypher_string(value: &str) -> String {
        value.replace('\\', "\\\\").replace('\'', "\\'")
    }

    fn upsert_node_with_conn(
        &self,
        conn: &Connection,
        props: &NodeProperties,
    ) -> GraphDBResult<()> {
        let id = Self::escape_cypher_string(&props.id);
        let name = Self::escape_cypher_string(&props.name);
        let node_type = Self::escape_cypher_string(&props.node_type);
        let properties = Self::escape_cypher_string(&props.properties);
        let created_at_str = props.created_at.format("%Y-%m-%d %H:%M:%S%.6f").to_string();
        let updated_at_str = props.updated_at.format("%Y-%m-%d %H:%M:%S%.6f").to_string();

        let exists_query = format!("MATCH (n:Node) WHERE n.id = '{id}' RETURN COUNT(n) AS count");
        let exists = conn
            .query(&exists_query)
            .map_err(|e| GraphDBError::NodeError(format!("Failed to check node existence: {e}")))?
            .next()
            .and_then(|row| row.into_iter().next())
            .and_then(|value| match value {
                LbugValue::Int64(count) => Some(count > 0),
                LbugValue::Int32(count) => Some(count > 0),
                LbugValue::UInt64(count) => Some(count > 0),
                LbugValue::UInt32(count) => Some(count > 0),
                _ => None,
            })
            .unwrap_or(false);

        let query = if exists {
            format!(
                r#"MATCH (n:Node) WHERE n.id = '{id}'
SET n.name = '{name}',
    n.type = '{node_type}',
    n.updated_at = timestamp('{updated_at_str}'),
    n.properties = '{properties}'"#
            )
        } else {
            format!(
                r#"CREATE (:Node {{
    id: '{id}',
    name: '{name}',
    type: '{node_type}',
    created_at: timestamp('{created_at_str}'),
    updated_at: timestamp('{updated_at_str}'),
    properties: '{properties}'
}})"#
            )
        };

        conn.query(&query).map_err(|e| {
            GraphDBError::NodeError(format!("Failed to upsert node '{}': {e}", props.id))
        })?;

        Ok(())
    }

    fn serialize_edge_properties(
        &self,
        properties: Option<HashMap<Cow<'static, str>, serde_json::Value>>,
    ) -> GraphDBResult<String> {
        if let Some(props) = properties {
            let mut val = serde_json::to_value(&props).map_err(GraphDBError::SerializationError)?;
            sanitize_json_value(&mut val);
            serde_json::to_string(&val).map_err(GraphDBError::SerializationError)
        } else {
            Ok("{}".to_string())
        }
    }

    fn upsert_edge_with_conn(
        &self,
        conn: &Connection,
        source_id: &str,
        target_id: &str,
        relationship_name: &str,
        properties_json: &str,
        updated_at: DateTime<Utc>,
    ) -> GraphDBResult<()> {
        let source_id = Self::escape_cypher_string(source_id);
        let target_id = Self::escape_cypher_string(target_id);
        let relationship_name = Self::escape_cypher_string(relationship_name);
        let properties_json = Self::escape_cypher_string(properties_json);
        let timestamp_str = updated_at.format("%Y-%m-%d %H:%M:%S%.6f").to_string();

        let exists_query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id = '{source_id}' AND b.id = '{target_id}' AND r.relationship_name = '{relationship_name}' RETURN COUNT(r) AS count"
        );
        let exists = conn
            .query(&exists_query)
            .map_err(|e| GraphDBError::EdgeError(format!("Failed to check edge existence: {e}")))?
            .next()
            .and_then(|row| row.into_iter().next())
            .and_then(|value| match value {
                LbugValue::Int64(count) => Some(count > 0),
                LbugValue::Int32(count) => Some(count > 0),
                LbugValue::UInt64(count) => Some(count > 0),
                LbugValue::UInt32(count) => Some(count > 0),
                _ => None,
            })
            .unwrap_or(false);

        let query = if exists {
            format!(
                r#"MATCH (a:Node)-[r:EDGE]->(b:Node)
WHERE a.id = '{source_id}' AND b.id = '{target_id}' AND r.relationship_name = '{relationship_name}'
SET r.updated_at = timestamp('{timestamp_str}'),
    r.properties = '{properties_json}'"#
            )
        } else {
            format!(
                r#"MATCH (a:Node {{id: '{source_id}'}}), (b:Node {{id: '{target_id}'}})
CREATE (a)-[:EDGE {{
    relationship_name: '{relationship_name}',
    created_at: timestamp('{timestamp_str}'),
    updated_at: timestamp('{timestamp_str}'),
    properties: '{properties_json}'
}}]->(b)"#
            )
        };

        conn.query(&query).map_err(|e| {
            GraphDBError::EdgeError(format!(
                "Failed to upsert edge {source_id} -[{relationship_name}]-> {target_id}: {e}"
            ))
        })?;

        Ok(())
    }
}

/// Helper struct for node properties extracted from DataPoint
struct NodeProperties {
    id: String,
    name: String,
    node_type: String,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
    properties: String, // JSON-encoded
}

#[async_trait]
impl GraphDBTrait for LadybugAdapter {
    async fn initialize(&self) -> GraphDBResult<()> {
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        // Try to install and load JSON extension (optional)
        // Ignore errors if extension is not available
        let _ = conn.query("INSTALL json");
        let _ = conn.query("LOAD EXTENSION json");

        // Create Node table
        let create_node_table = r#"
            CREATE NODE TABLE IF NOT EXISTS Node(
                id STRING PRIMARY KEY,
                name STRING,
                type STRING,
                created_at TIMESTAMP,
                updated_at TIMESTAMP,
                properties STRING
            )
        "#;

        conn.query(create_node_table).map_err(|e| {
            GraphDBError::InitializationError(format!("Failed to create Node table: {e}"))
        })?;

        // Create Edge relationship table
        let create_edge_table = r#"
            CREATE REL TABLE IF NOT EXISTS EDGE(
                FROM Node TO Node,
                relationship_name STRING,
                created_at TIMESTAMP,
                updated_at TIMESTAMP,
                properties STRING
            )
        "#;

        conn.query(create_edge_table).map_err(|e| {
            GraphDBError::InitializationError(format!("Failed to create EDGE table: {e}"))
        })?;

        Ok(())
    }

    async fn is_empty(&self) -> GraphDBResult<bool> {
        let results = self.execute_query("MATCH (n:Node) RETURN COUNT(n) AS count")?;

        // Parse the count from results
        if let Some(first_row) = results.first()
            && let Some(count_value) = first_row.first()
            && let Some(count) = count_value.as_i64()
        {
            return Ok(count == 0);
        }

        // If we can't parse, assume empty (safe default)
        Ok(true)
    }

    async fn query(
        &self,
        query: &str,
        params: Option<HashMap<Cow<'static, str>, serde_json::Value>>,
    ) -> GraphDBResult<Vec<Vec<serde_json::Value>>> {
        // Ladybug doesn't support parameterized queries
        if params.is_some() {
            return Err(GraphDBError::QueryError(
                "Ladybug adapter does not support parameterized queries".to_string(),
            ));
        }
        self.execute_query(query)
    }

    async fn delete_graph(&self) -> GraphDBResult<()> {
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        // Delete all edges first
        conn.query("MATCH (a:Node)-[r:EDGE]->(b:Node) DELETE r")
            .map_err(|e| GraphDBError::QueryError(format!("Failed to delete edges: {e}")))?;

        // Delete all nodes
        conn.query("MATCH (n:Node) DELETE n")
            .map_err(|e| GraphDBError::QueryError(format!("Failed to delete nodes: {e}")))?;

        Ok(())
    }

    async fn has_node(&self, node_id: &str) -> GraphDBResult<bool> {
        let query = format!(
            "MATCH (n:Node) WHERE n.id = '{}' RETURN COUNT(n) AS count",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;

        // Parse the count from results
        if let Some(first_row) = results.first()
            && let Some(count_value) = first_row.first()
            && let Some(count) = count_value.as_i64()
        {
            return Ok(count > 0);
        }

        Ok(false)
    }

    async fn add_node_raw(&self, node: Value) -> GraphDBResult<()> {
        let props = self.serialize_to_node_props(&node)?;
        let _write_guard = self.write_lock.lock().map_err(|_| {
            GraphDBError::ConnectionError("Ladybug write lock poisoned".to_string())
        })?;
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        self.upsert_node_with_conn(&conn, &props)
    }

    async fn add_nodes_raw(&self, nodes: Vec<Value>) -> GraphDBResult<()> {
        // Batch insert optimization: process nodes in chunks to avoid
        // query size limits and improve performance
        const BATCH_SIZE: usize = 500;

        if nodes.is_empty() {
            return Ok(());
        }

        let _write_guard = self.write_lock.lock().map_err(|_| {
            GraphDBError::ConnectionError("Ladybug write lock poisoned".to_string())
        })?;

        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        // Process in batches. Each batch is a single `UNWIND … MERGE` query
        // (mirrors the Python Ladybug adapter) instead of a per-node
        // exists-check + CREATE/SET — one round-trip per batch, and MERGE makes
        // it idempotent without the extra COUNT query.
        for chunk in nodes.chunks(BATCH_SIZE) {
            let mut items = Vec::with_capacity(chunk.len());
            for node in chunk {
                let p = self.serialize_to_node_props(node)?;
                items.push(format!(
                    "{{id:'{}', name:'{}', type:'{}', properties:'{}', created_at:'{}', updated_at:'{}'}}",
                    Self::escape_cypher_string(&p.id),
                    Self::escape_cypher_string(&p.name),
                    Self::escape_cypher_string(&p.node_type),
                    Self::escape_cypher_string(&p.properties),
                    p.created_at.format("%Y-%m-%d %H:%M:%S%.6f"),
                    p.updated_at.format("%Y-%m-%d %H:%M:%S%.6f"),
                ));
            }
            let query = format!(
                "UNWIND [{}] AS node \
                 MERGE (n:Node {{id: node.id}}) \
                 ON CREATE SET n.name = node.name, n.type = node.type, \
                     n.created_at = timestamp(node.created_at), \
                     n.updated_at = timestamp(node.updated_at), n.properties = node.properties \
                 ON MATCH SET n.name = node.name, n.type = node.type, \
                     n.updated_at = timestamp(node.updated_at), n.properties = node.properties",
                items.join(", ")
            );
            conn.query(&query).map_err(|e| {
                GraphDBError::NodeError(format!(
                    "Failed to batch-upsert {} nodes: {e}",
                    chunk.len()
                ))
            })?;
        }

        Ok(())
    }

    async fn delete_node(&self, node_id: &str) -> GraphDBResult<()> {
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        let query = format!(
            "MATCH (n:Node) WHERE n.id = '{}' DETACH DELETE n",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        conn.query(&query)
            .map_err(|e| GraphDBError::NodeError(format!("Failed to delete node: {e}")))?;

        Ok(())
    }

    async fn delete_nodes(&self, node_ids: &[String]) -> GraphDBResult<()> {
        for node_id in node_ids {
            self.delete_node(node_id).await?;
        }
        Ok(())
    }

    async fn get_node(&self, node_id: &str) -> GraphDBResult<Option<NodeData>> {
        let query = format!(
            "MATCH (n:Node) WHERE n.id = '{}' RETURN n.id AS id, n.name AS name, n.type AS type, n.properties AS properties",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;

        // Parse the first row if it exists
        if let Some(row) = results.first()
            && row.len() >= 4
        {
            let mut node_data = NodeData::new();
            if let Some(id_str) = row[0].as_str() {
                node_data.insert(Cow::Borrowed("id"), json!(id_str));
            }
            if let Some(name_str) = row[1].as_str() {
                node_data.insert(Cow::Borrowed("name"), json!(name_str));
            }
            if let Some(type_str) = row[2].as_str() {
                node_data.insert(Cow::Borrowed("type"), json!(type_str));
            }
            if let Some(props_str) = row[3].as_str() {
                node_data.insert(Cow::Borrowed("properties"), json!(props_str));
            }
            return Ok(Some(self.parse_node_data(node_data)?));
        }

        Ok(None)
    }

    async fn get_nodes(&self, node_ids: &[String]) -> GraphDBResult<Vec<NodeData>> {
        let mut nodes = Vec::new();
        for node_id in node_ids {
            if let Some(node) = self.get_node(node_id).await? {
                nodes.push(node);
            }
        }
        Ok(nodes)
    }

    async fn has_edge(
        &self,
        source_id: &str,
        target_id: &str,
        relationship_name: &str,
    ) -> GraphDBResult<bool> {
        let query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id = '{}' AND b.id = '{}' AND r.relationship_name = '{}' RETURN COUNT(r) AS count",
            source_id.replace('\\', "\\\\").replace('\'', "\\'"),
            target_id.replace('\\', "\\\\").replace('\'', "\\'"),
            relationship_name.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;

        // Parse the count from results
        if let Some(first_row) = results.first()
            && let Some(count_value) = first_row.first()
            && let Some(count) = count_value.as_i64()
        {
            return Ok(count > 0);
        }

        Ok(false)
    }

    async fn has_edges(&self, edges: &[EdgeData]) -> GraphDBResult<Vec<EdgeData>> {
        let mut existing_edges = Vec::new();
        for edge in edges {
            if self.has_edge(&edge.0, &edge.1, &edge.2).await? {
                existing_edges.push(edge.clone());
            }
        }
        Ok(existing_edges)
    }

    async fn add_edge(
        &self,
        source_id: &str,
        target_id: &str,
        relationship_name: &str,
        properties: Option<HashMap<Cow<'static, str>, serde_json::Value>>,
    ) -> GraphDBResult<()> {
        let _write_guard = self.write_lock.lock().map_err(|_| {
            GraphDBError::ConnectionError("Ladybug write lock poisoned".to_string())
        })?;
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        let now = Utc::now();
        let props_json = self.serialize_edge_properties(properties)?;

        self.upsert_edge_with_conn(
            &conn,
            source_id,
            target_id,
            relationship_name,
            &props_json,
            now,
        )
    }

    async fn add_edges(&self, edges: &[EdgeData]) -> GraphDBResult<()> {
        if edges.is_empty() {
            return Ok(());
        }

        let _write_guard = self.write_lock.lock().map_err(|_| {
            GraphDBError::ConnectionError("Ladybug write lock poisoned".to_string())
        })?;
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;

        // One `UNWIND … MATCH … MERGE` query per batch (mirrors the Python
        // Ladybug adapter), replacing the per-edge exists-check + CREATE/SET.
        const BATCH_SIZE: usize = 500;
        let now = Utc::now().format("%Y-%m-%d %H:%M:%S%.6f").to_string();
        for chunk in edges.chunks(BATCH_SIZE) {
            let mut items = Vec::with_capacity(chunk.len());
            for edge in chunk {
                let props_json = self.serialize_edge_properties(Some(edge.3.clone()))?;
                items.push(format!(
                    "{{from_id:'{}', to_id:'{}', relationship_name:'{}', properties:'{}', created_at:'{now}', updated_at:'{now}'}}",
                    Self::escape_cypher_string(&edge.0),
                    Self::escape_cypher_string(&edge.1),
                    Self::escape_cypher_string(&edge.2),
                    Self::escape_cypher_string(&props_json),
                ));
            }
            let query = format!(
                "UNWIND [{}] AS edge \
                 MATCH (a:Node), (b:Node) WHERE a.id = edge.from_id AND b.id = edge.to_id \
                 MERGE (a)-[r:EDGE {{relationship_name: edge.relationship_name}}]->(b) \
                 ON CREATE SET r.created_at = timestamp(edge.created_at), \
                     r.updated_at = timestamp(edge.updated_at), r.properties = edge.properties \
                 ON MATCH SET r.updated_at = timestamp(edge.updated_at), r.properties = edge.properties",
                items.join(", ")
            );
            conn.query(&query).map_err(|e| {
                GraphDBError::EdgeError(format!(
                    "Failed to batch-upsert {} edges: {e}",
                    chunk.len()
                ))
            })?;
        }
        Ok(())
    }

    async fn get_edges(&self, node_id: &str) -> GraphDBResult<Vec<EdgeData>> {
        let query = format!(
            "MATCH (n:Node)-[r:EDGE]-(m:Node) WHERE n.id = '{}' RETURN n.id AS source_id, m.id AS target_id, r.relationship_name AS rel_name, r.properties AS props",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;
        let mut edges = Vec::new();

        // Parse each row into EdgeData
        for row in results {
            if row.len() >= Self::EDGE_QUERY_COLUMN_COUNT {
                let source_id = row[0].as_str().unwrap_or("").to_string();
                let target_id = row[1].as_str().unwrap_or("").to_string();
                let rel_name = row[2].as_str().unwrap_or("").to_string();

                let props = if let Some(props_str) = row[3].as_str() {
                    let clean = sanitize_json_control_chars(props_str);
                    serde_json::from_str::<HashMap<Cow<'static, str>, serde_json::Value>>(&clean)
                        .unwrap_or_default()
                } else {
                    HashMap::new()
                };

                edges.push((source_id, target_id, rel_name, props));
            }
        }

        Ok(edges)
    }

    async fn get_neighbors(&self, node_id: &str) -> GraphDBResult<Vec<NodeData>> {
        let query = format!(
            "MATCH (n:Node)-[r:EDGE]-(m:Node) WHERE n.id = '{}' RETURN DISTINCT m.id AS id, m.name AS name, m.type AS type, m.properties AS properties",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;
        let mut neighbors = Vec::new();

        // Parse each row into NodeData
        for row in results {
            if row.len() >= Self::NODE_QUERY_COLUMN_COUNT {
                let mut node_data = NodeData::new();
                if let Some(id_str) = row[0].as_str() {
                    node_data.insert(Cow::Borrowed("id"), json!(id_str));
                }
                if let Some(name_str) = row[1].as_str() {
                    node_data.insert(Cow::Borrowed("name"), json!(name_str));
                }
                if let Some(type_str) = row[2].as_str() {
                    node_data.insert(Cow::Borrowed("type"), json!(type_str));
                }
                if let Some(props_str) = row[3].as_str() {
                    node_data.insert(Cow::Borrowed("properties"), json!(props_str));
                }
                neighbors.push(self.parse_node_data(node_data)?);
            }
        }

        Ok(neighbors)
    }

    async fn get_connections(
        &self,
        node_id: &str,
    ) -> GraphDBResult<
        Vec<(
            NodeData,
            HashMap<Cow<'static, str>, serde_json::Value>,
            NodeData,
        )>,
    > {
        /// Number of columns expected from query: 4 (source node) + 2 (edge) + 4 (target node) = 10
        const GET_CONNECTIONS_COLUMN_COUNT: usize = 10;

        let query = format!(
            r#"MATCH (n:Node)-[r:EDGE]-(m:Node)
            WHERE n.id = '{}'
            RETURN 
                n.id AS source_id, 
                n.name AS source_name, 
                n.type AS source_type, 
                n.properties AS source_props,
                r.relationship_name AS rel_name,
                r.properties AS rel_props,
                m.id AS target_id,
                m.name AS target_name,
                m.type AS target_type,
                m.properties AS target_props"#,
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );

        let results = self.execute_query(&query)?;
        let mut connections = Vec::new();

        for row in results {
            if row.len() >= GET_CONNECTIONS_COLUMN_COUNT {
                // Parse source node
                let mut source_node = NodeData::new();
                if let Some(id) = row[0].as_str() {
                    source_node.insert(Cow::Borrowed("id"), json!(id));
                }
                if let Some(name) = row[1].as_str() {
                    source_node.insert(Cow::Borrowed("name"), json!(name));
                }
                if let Some(node_type) = row[2].as_str() {
                    source_node.insert(Cow::Borrowed("type"), json!(node_type));
                }
                if let Some(props) = row[3].as_str() {
                    source_node.insert(Cow::Borrowed("properties"), json!(props));
                }
                let source_node = self.parse_node_data(source_node)?;

                // Parse edge properties
                let mut edge_props = HashMap::new();
                if let Some(rel_name) = row[4].as_str() {
                    edge_props.insert(Cow::Borrowed("relationship_name"), json!(rel_name));
                }
                if let Some(rel_props_str) = row[5].as_str() {
                    let clean = sanitize_json_control_chars(rel_props_str);
                    let additional_props: HashMap<Cow<'static, str>, serde_json::Value> =
                        serde_json::from_str(&clean).unwrap_or_default();
                    edge_props.extend(additional_props);
                }

                // Parse target node
                let mut target_node = NodeData::new();
                if let Some(id) = row[6].as_str() {
                    target_node.insert(Cow::Borrowed("id"), json!(id));
                }
                if let Some(name) = row[7].as_str() {
                    target_node.insert(Cow::Borrowed("name"), json!(name));
                }
                if let Some(node_type) = row[8].as_str() {
                    target_node.insert(Cow::Borrowed("type"), json!(node_type));
                }
                if let Some(props) = row[9].as_str() {
                    target_node.insert(Cow::Borrowed("properties"), json!(props));
                }
                let target_node = self.parse_node_data(target_node)?;

                connections.push((source_node, edge_props, target_node));
            }
        }

        Ok(connections)
    }

    async fn get_graph_data(&self) -> GraphDBResult<(Vec<GraphNode>, Vec<EdgeData>)> {
        // Get all nodes
        let nodes_query = "MATCH (n:Node) RETURN n.id AS id, n.name AS name, n.type AS type, n.properties AS properties";
        let node_results = self.execute_query(nodes_query)?;

        let mut nodes = Vec::new();
        for row in node_results {
            if row.len() >= Self::NODE_QUERY_COLUMN_COUNT {
                let mut node_data = NodeData::new();
                if let Some(id_str) = row[0].as_str() {
                    node_data.insert(Cow::Borrowed("id"), json!(id_str));
                }
                if let Some(name_str) = row[1].as_str() {
                    node_data.insert(Cow::Borrowed("name"), json!(name_str));
                }
                if let Some(type_str) = row[2].as_str() {
                    node_data.insert(Cow::Borrowed("type"), json!(type_str));
                }
                if let Some(props_str) = row[3].as_str() {
                    node_data.insert(Cow::Borrowed("properties"), json!(props_str));
                }
                let parsed_node = self.parse_node_data(node_data)?;
                if let Some(id_str) = parsed_node.get("id").and_then(|v| v.as_str()) {
                    nodes.push((id_str.to_string(), parsed_node));
                }
            }
        }

        // Get all edges
        let edges_query = "MATCH (a:Node)-[r:EDGE]->(b:Node) RETURN a.id AS source_id, b.id AS target_id, r.relationship_name AS rel_name, r.properties AS props";
        let edge_results = self.execute_query(edges_query)?;

        let mut edges = Vec::new();
        for row in edge_results {
            if row.len() >= Self::EDGE_QUERY_COLUMN_COUNT {
                let source_id = row[0].as_str().unwrap_or("").to_string();
                let target_id = row[1].as_str().unwrap_or("").to_string();
                let rel_name = row[2].as_str().unwrap_or("").to_string();

                let props = if let Some(props_str) = row[3].as_str() {
                    let clean = sanitize_json_control_chars(props_str);
                    serde_json::from_str::<HashMap<Cow<'static, str>, serde_json::Value>>(&clean)
                        .unwrap_or_default()
                } else {
                    HashMap::new()
                };

                edges.push((source_id, target_id, rel_name, props));
            }
        }

        Ok((nodes, edges))
    }

    async fn get_graph_metrics(
        &self,
        _include_optional: bool,
    ) -> GraphDBResult<HashMap<Cow<'static, str>, serde_json::Value>> {
        let mut metrics = HashMap::new();

        // Get node count
        let node_count_results = self.execute_query("MATCH (n:Node) RETURN COUNT(n) AS count")?;
        let node_count = node_count_results
            .first()
            .and_then(|row| row.first())
            .and_then(|v| v.as_i64())
            .unwrap_or(0);

        // Get edge count
        let edge_count_results =
            self.execute_query("MATCH ()-[r:EDGE]->() RETURN COUNT(r) AS count")?;
        let edge_count = edge_count_results
            .first()
            .and_then(|row| row.first())
            .and_then(|v| v.as_i64())
            .unwrap_or(0);

        metrics.insert(Cow::Borrowed("node_count"), json!(node_count));
        metrics.insert(Cow::Borrowed("edge_count"), json!(edge_count));

        Ok(metrics)
    }

    async fn get_filtered_graph_data(
        &self,
        attribute_filters: &HashMap<Cow<'static, str>, Vec<serde_json::Value>>,
    ) -> GraphDBResult<(Vec<GraphNode>, Vec<EdgeData>)> {
        // If no filters, return entire graph
        if attribute_filters.is_empty() {
            return self.get_graph_data().await;
        }

        // Build WHERE clause for core fields (id, name, type)
        let mut where_clauses = Vec::new();

        for (attr, values) in attribute_filters {
            if values.is_empty() {
                continue;
            }

            // Check if this is a core field
            let is_core_field = matches!(attr.as_ref(), "id" | "name" | "type");

            if is_core_field {
                // Direct field match
                let value_clauses: Vec<String> = values
                    .iter()
                    .map(|v| {
                        if let Some(s) = v.as_str() {
                            format!(
                                "n.{} = '{}'",
                                attr,
                                s.replace('\\', "\\\\").replace('\'', "\\'")
                            )
                        } else {
                            format!("n.{attr} = {v}")
                        }
                    })
                    .collect();

                if value_clauses.len() == 1 {
                    where_clauses.push(value_clauses[0].clone());
                } else {
                    where_clauses.push(format!("({})", value_clauses.join(" OR ")));
                }
            }
            // Property fields are filtered in Rust after loading
        }

        // Build final query with optional WHERE clause
        let where_clause = if where_clauses.is_empty() {
            String::new()
        } else {
            format!("WHERE {}", where_clauses.join(" AND "))
        };

        // Get filtered nodes
        let nodes_query = format!(
            "MATCH (n:Node) {where_clause} RETURN n.id AS id, n.name AS name, n.type AS type, n.properties AS properties"
        );

        let node_results = self.execute_query(&nodes_query)?;

        // Parse nodes and collect IDs
        let mut nodes = Vec::new();
        let mut node_ids = Vec::new();

        for row in node_results {
            if row.len() >= Self::NODE_QUERY_COLUMN_COUNT {
                let mut node_data = NodeData::new();
                if let Some(id_str) = row[0].as_str() {
                    node_data.insert(Cow::Borrowed("id"), json!(id_str));
                }
                if let Some(name_str) = row[1].as_str() {
                    node_data.insert(Cow::Borrowed("name"), json!(name_str));
                }
                if let Some(type_str) = row[2].as_str() {
                    node_data.insert(Cow::Borrowed("type"), json!(type_str));
                }
                if let Some(props_str) = row[3].as_str() {
                    node_data.insert(Cow::Borrowed("properties"), json!(props_str));
                }

                let parsed_node = self.parse_node_data(node_data)?;

                // Apply property filters in Rust if needed
                if self.matches_property_filters(&parsed_node, attribute_filters)
                    && let Some(id_str) = parsed_node.get("id").and_then(|v| v.as_str())
                {
                    node_ids.push(id_str.to_string());
                    nodes.push((id_str.to_string(), parsed_node));
                }
            }
        }

        // Get edges connecting filtered nodes
        if node_ids.is_empty() {
            return Ok((nodes, Vec::new()));
        }

        // Build IN clause for edge query
        let id_list = node_ids
            .iter()
            .map(|id| format!("'{}'", id.replace('\\', "\\\\").replace('\'', "\\'")))
            .collect::<Vec<_>>()
            .join(", ");

        let edges_query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id IN [{id_list}] AND b.id IN [{id_list}] RETURN a.id, b.id, r.relationship_name, r.properties"
        );

        let edge_results = self.execute_query(&edges_query)?;
        let mut edges = Vec::new();

        for row in edge_results {
            if row.len() >= Self::EDGE_QUERY_COLUMN_COUNT {
                let source_id = row[0].as_str().unwrap_or("").to_string();
                let target_id = row[1].as_str().unwrap_or("").to_string();
                let rel_name = row[2].as_str().unwrap_or("").to_string();
                let props = if let Some(props_str) = row[3].as_str() {
                    let clean = sanitize_json_control_chars(props_str);
                    serde_json::from_str(&clean).unwrap_or_default()
                } else {
                    HashMap::new()
                };
                edges.push((source_id, target_id, rel_name, props));
            }
        }

        Ok((nodes, edges))
    }

    async fn get_nodeset_subgraph(
        &self,
        node_type: &str,
        node_names: &[String],
        node_name_filter_operator: &str,
    ) -> GraphDBResult<(Vec<GraphNode>, Vec<EdgeData>)> {
        use std::collections::HashSet;

        // Early return for empty node_names
        if node_names.is_empty() {
            return Ok((Vec::new(), Vec::new()));
        }

        // Build IN clause for names
        let name_list = node_names
            .iter()
            .map(|name| format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'")))
            .collect::<Vec<_>>()
            .join(", ");

        // Query for specific (primary) nodes matching type and names
        let nodes_query = format!(
            "MATCH (n:Node) WHERE n.type = '{}' AND n.name IN [{}] RETURN n.id AS id, n.name AS name, n.type AS type, n.properties AS properties",
            node_type.replace('\\', "\\\\").replace('\'', "\\'"),
            name_list
        );

        let node_results = self.execute_query(&nodes_query)?;

        let mut primary_node_ids: Vec<String> = Vec::new();

        // Parse primary node IDs
        for row in &node_results {
            if row.len() >= Self::NODE_QUERY_COLUMN_COUNT
                && let Some(id_str) = row[0].as_str()
            {
                primary_node_ids.push(id_str.to_string());
            }
        }

        if primary_node_ids.is_empty() {
            return Ok((Vec::new(), Vec::new()));
        }

        // Gather 1-hop neighbor IDs per primary node, applying OR/AND logic.
        let use_and = node_name_filter_operator.eq_ignore_ascii_case("AND");
        let mut neighbor_id_set: Option<HashSet<String>> = None;

        for primary_id in &primary_node_ids {
            let escaped_id = primary_id.replace('\\', "\\\\").replace('\'', "\\'");
            let neighbor_query = format!(
                "MATCH (n:Node)-[:EDGE]-(nbr:Node) WHERE n.id = '{escaped_id}' RETURN DISTINCT nbr.id"
            );
            let nbr_results = self.execute_query(&neighbor_query)?;
            let nbr_ids: HashSet<String> = nbr_results
                .iter()
                .filter_map(|row| row.first().and_then(|v| v.as_str()).map(str::to_string))
                .collect();

            match neighbor_id_set {
                None => {
                    neighbor_id_set = Some(nbr_ids);
                }
                Some(ref mut existing) => {
                    if use_and {
                        // AND: keep only IDs present in all sets (intersection)
                        existing.retain(|id| nbr_ids.contains(id));
                    } else {
                        // OR: add all neighbor IDs (union)
                        existing.extend(nbr_ids);
                    }
                }
            }
        }

        // Union of primary nodes and their filtered neighbors
        let mut all_ids: HashSet<String> = primary_node_ids.iter().cloned().collect();
        if let Some(nbr_set) = neighbor_id_set {
            all_ids.extend(nbr_set);
        }

        let id_list = all_ids
            .iter()
            .map(|id| format!("'{}'", id.replace('\\', "\\\\").replace('\'', "\\'")))
            .collect::<Vec<_>>()
            .join(", ");

        // Fetch full node data for all IDs
        let all_nodes_query = format!(
            "MATCH (n:Node) WHERE n.id IN [{id_list}] RETURN n.id AS id, n.name AS name, n.type AS type, n.properties AS properties"
        );
        let all_node_results = self.execute_query(&all_nodes_query)?;

        let mut nodes: Vec<GraphNode> = Vec::new();
        for row in all_node_results {
            if row.len() >= Self::NODE_QUERY_COLUMN_COUNT {
                let mut node_data = NodeData::new();
                if let Some(id_str) = row[0].as_str() {
                    node_data.insert(Cow::Borrowed("id"), json!(id_str));
                }
                if let Some(name_str) = row[1].as_str() {
                    node_data.insert(Cow::Borrowed("name"), json!(name_str));
                }
                if let Some(type_str) = row[2].as_str() {
                    node_data.insert(Cow::Borrowed("type"), json!(type_str));
                }
                if let Some(props_str) = row[3].as_str() {
                    node_data.insert(Cow::Borrowed("properties"), json!(props_str));
                }

                let parsed_node = self.parse_node_data(node_data)?;
                if let Some(id_str) = parsed_node.get("id").and_then(|v| v.as_str()) {
                    nodes.push((id_str.to_string(), parsed_node));
                }
            }
        }

        // Get all edges between nodes in the final set
        let edges_query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id IN [{id_list}] AND b.id IN [{id_list}] RETURN a.id, b.id, r.relationship_name, r.properties"
        );

        let edge_results = self.execute_query(&edges_query)?;
        let mut edges = Vec::new();

        for row in edge_results {
            if row.len() >= Self::EDGE_QUERY_COLUMN_COUNT {
                let source_id = row[0].as_str().unwrap_or("").to_string();
                let target_id = row[1].as_str().unwrap_or("").to_string();
                let rel_name = row[2].as_str().unwrap_or("").to_string();
                let props = if let Some(props_str) = row[3].as_str() {
                    let clean = sanitize_json_control_chars(props_str);
                    serde_json::from_str(&clean).unwrap_or_default()
                } else {
                    HashMap::new()
                };
                edges.push((source_id, target_id, rel_name, props));
            }
        }

        Ok((nodes, edges))
    }

    // -----------------------------------------------------------------
    // In-place property updates
    // -----------------------------------------------------------------
    //
    // Ladybug stores node/edge custom properties as a JSON string column
    // named `properties`. To update a single key without cascading
    // deletes, we read the current JSON, merge the new value, and rewrite
    // the column via a single MATCH ... SET ... statement.
    async fn update_node_property(
        &self,
        node_id: &str,
        key: &str,
        value: serde_json::Value,
    ) -> GraphDBResult<()> {
        let read_query = format!(
            "MATCH (n:Node) WHERE n.id = '{}' RETURN n.properties AS properties",
            node_id.replace('\\', "\\\\").replace('\'', "\\'")
        );
        let rows = self.execute_query(&read_query)?;
        let mut props: serde_json::Map<String, serde_json::Value> = if let Some(row) = rows.first()
            && let Some(props_str) = row.first().and_then(|v| v.as_str())
        {
            let clean = sanitize_json_control_chars(props_str);
            serde_json::from_str(&clean).unwrap_or_default()
        } else {
            return Err(GraphDBError::NodeError(format!(
                "Node not found: {node_id}"
            )));
        };
        props.insert(key.to_string(), value);
        let mut props_val = serde_json::Value::Object(props);
        sanitize_json_value(&mut props_val);
        let props_json =
            serde_json::to_string(&props_val).map_err(GraphDBError::SerializationError)?;

        let now = Utc::now();
        let ts = now.format("%Y-%m-%d %H:%M:%S%.6f").to_string();
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;
        let set_query = format!(
            "MATCH (n:Node) WHERE n.id = '{}' SET n.properties = '{}', n.updated_at = timestamp('{}')",
            node_id.replace('\\', "\\\\").replace('\'', "\\'"),
            props_json.replace('\\', "\\\\").replace('\'', "\\'"),
            ts
        );
        conn.query(&set_query)
            .map_err(|e| GraphDBError::NodeError(format!("Failed to update node property: {e}")))?;
        Ok(())
    }

    async fn update_edge_property(
        &self,
        source_id: &str,
        target_id: &str,
        relationship_name: &str,
        key: &str,
        value: serde_json::Value,
    ) -> GraphDBResult<()> {
        let src_esc = source_id.replace('\\', "\\\\").replace('\'', "\\'");
        let tgt_esc = target_id.replace('\\', "\\\\").replace('\'', "\\'");
        let rel_esc = relationship_name.replace('\\', "\\\\").replace('\'', "\\'");

        let read_query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id = '{src_esc}' AND b.id = '{tgt_esc}' AND r.relationship_name = '{rel_esc}' RETURN r.properties AS properties"
        );
        let rows = self.execute_query(&read_query)?;
        let mut props: serde_json::Map<String, serde_json::Value> = if let Some(row) = rows.first()
            && let Some(props_str) = row.first().and_then(|v| v.as_str())
        {
            let clean = sanitize_json_control_chars(props_str);
            serde_json::from_str(&clean).unwrap_or_default()
        } else {
            return Err(GraphDBError::EdgeError(format!(
                "Edge not found: {source_id} -[{relationship_name}]-> {target_id}"
            )));
        };
        props.insert(key.to_string(), value);
        let mut props_val = serde_json::Value::Object(props);
        sanitize_json_value(&mut props_val);
        let props_json =
            serde_json::to_string(&props_val).map_err(GraphDBError::SerializationError)?;

        let now = Utc::now();
        let ts = now.format("%Y-%m-%d %H:%M:%S%.6f").to_string();
        let conn = Connection::new(&self.db).map_err(|e| {
            GraphDBError::ConnectionError(format!("Failed to create connection: {e}"))
        })?;
        let set_query = format!(
            "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id = '{src_esc}' AND b.id = '{tgt_esc}' AND r.relationship_name = '{rel_esc}' SET r.properties = '{}', r.updated_at = timestamp('{ts}')",
            props_json.replace('\\', "\\\\").replace('\'', "\\'")
        );
        conn.query(&set_query)
            .map_err(|e| GraphDBError::EdgeError(format!("Failed to update edge property: {e}")))?;
        Ok(())
    }

    // -----------------------------------------------------------------
    // Batch feedback-weight methods — read the JSON properties column in
    // bulk and write individual in-place updates. We keep the writes in
    // individual statements (one per element) rather than a single
    // UNWIND because each node/edge carries its own merged JSON blob.
    // -----------------------------------------------------------------
    async fn get_node_feedback_weights(
        &self,
        node_ids: &[String],
    ) -> GraphDBResult<HashMap<String, f64>> {
        if node_ids.is_empty() {
            return Ok(HashMap::new());
        }
        let id_list = node_ids
            .iter()
            .map(|id| format!("'{}'", id.replace('\\', "\\\\").replace('\'', "\\'")))
            .collect::<Vec<_>>()
            .join(", ");
        let query = format!(
            "MATCH (n:Node) WHERE n.id IN [{id_list}] RETURN n.id AS id, n.properties AS properties"
        );
        let rows = self.execute_query(&query)?;
        let mut out = HashMap::with_capacity(rows.len());
        for row in rows {
            if row.len() < 2 {
                continue;
            }
            let id = match row[0].as_str() {
                Some(s) => s.to_string(),
                None => continue,
            };
            if let Some(props_str) = row[1].as_str() {
                let clean = sanitize_json_control_chars(props_str);
                if let Ok(map) =
                    serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&clean)
                    && let Some(v) = map.get("feedback_weight").and_then(|v| v.as_f64())
                {
                    out.insert(id, v);
                }
            }
        }
        Ok(out)
    }

    async fn set_node_feedback_weights(
        &self,
        updates: &HashMap<String, f64>,
    ) -> GraphDBResult<HashMap<String, bool>> {
        let mut out = HashMap::with_capacity(updates.len());
        for (id, w) in updates {
            let ok = self
                .update_node_property(id, "feedback_weight", serde_json::json!(w))
                .await
                .is_ok();
            out.insert(id.clone(), ok);
        }
        Ok(out)
    }

    async fn get_edge_feedback_weights(
        &self,
        edge_keys: &[crate::traits::EdgeKey],
    ) -> GraphDBResult<HashMap<crate::traits::EdgeKey, f64>> {
        if edge_keys.is_empty() {
            return Ok(HashMap::new());
        }
        let mut out = HashMap::with_capacity(edge_keys.len());
        // Per-edge lookup: Ladybug's property filter on relationships is
        // simplest when driven by (source_id, target_id, rel_name) tuples.
        for key in edge_keys {
            let src_esc = key.0.replace('\\', "\\\\").replace('\'', "\\'");
            let tgt_esc = key.1.replace('\\', "\\\\").replace('\'', "\\'");
            let rel_esc = key.2.replace('\\', "\\\\").replace('\'', "\\'");
            let query = format!(
                "MATCH (a:Node)-[r:EDGE]->(b:Node) WHERE a.id = '{src_esc}' AND b.id = '{tgt_esc}' AND r.relationship_name = '{rel_esc}' RETURN r.properties AS properties"
            );
            let rows = self.execute_query(&query)?;
            if let Some(row) = rows.first()
                && let Some(props_str) = row.first().and_then(|v| v.as_str())
            {
                let clean = sanitize_json_control_chars(props_str);
                if let Ok(map) =
                    serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&clean)
                    && let Some(v) = map.get("feedback_weight").and_then(|v| v.as_f64())
                {
                    out.insert(key.clone(), v);
                }
            }
        }
        Ok(out)
    }

    async fn set_edge_feedback_weights(
        &self,
        updates: &HashMap<crate::traits::EdgeKey, f64>,
    ) -> GraphDBResult<HashMap<crate::traits::EdgeKey, bool>> {
        let mut out = HashMap::with_capacity(updates.len());
        for (key, w) in updates {
            let ok = self
                .update_edge_property(
                    &key.0,
                    &key.1,
                    &key.2,
                    "feedback_weight",
                    serde_json::json!(w),
                )
                .await
                .is_ok();
            out.insert(key.clone(), ok);
        }
        Ok(out)
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "test code — panics are acceptable failures"
)]
mod tests {
    use super::*;
    use crate::GraphDBTraitExt;
    use serde::Serialize;
    use serial_test::serial;
    use tempfile::TempDir;
    use tokio::task::JoinSet;

    /// Simple test node for testing batch operations
    #[derive(Debug, Clone, Serialize)]
    struct TestNode {
        id: String,
        name: String,
        data_type: String,
        created_at: String,
        updated_at: String,
        value: i32,
    }

    impl TestNode {
        fn new(id: &str, name: &str, value: i32) -> Self {
            let now = chrono::Utc::now().to_rfc3339();
            Self {
                id: id.to_string(),
                name: name.to_string(),
                data_type: "TestNode".to_string(),
                created_at: now.clone(),
                updated_at: now,
                value,
            }
        }
    }

    async fn setup_adapter() -> (LadybugAdapter, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let adapter = LadybugAdapter::new(db_path.to_str().unwrap())
            .await
            .unwrap();
        adapter.initialize().await.unwrap();
        (adapter, temp_dir)
    }

    /// Regression: lbug supports a single batched `UNWIND … MERGE` (inline
    /// struct list) and it is idempotent — the basis for the batched
    /// `add_nodes_raw`/`add_edges` upserts that replaced per-item exists-check
    /// + CREATE/SET.
    #[tokio::test]
    #[serial]
    async fn ladybug_supports_idempotent_unwind_merge_batch() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("merge.db");
        let config = SystemConfig::default().max_db_size(read_max_db_size());
        let db = Database::new(db_path.to_str().unwrap(), config).unwrap();
        let conn = Connection::new(&db).unwrap();
        conn.query(
            "CREATE NODE TABLE IF NOT EXISTS Node(id STRING PRIMARY KEY, name STRING, \
             type STRING, created_at TIMESTAMP, updated_at TIMESTAMP, properties STRING)",
        )
        .unwrap();

        let batch = r#"
            UNWIND [
              {id:'a', name:'Alice', type:'P', properties:'{}', created_at:'2026-01-01 00:00:00.000000', updated_at:'2026-01-01 00:00:00.000000'},
              {id:'b', name:'Bob',   type:'P', properties:'{}', created_at:'2026-01-01 00:00:00.000000', updated_at:'2026-01-01 00:00:00.000000'}
            ] AS node
            MERGE (n:Node {id: node.id})
            ON CREATE SET n.name = node.name, n.type = node.type,
                n.created_at = timestamp(node.created_at), n.updated_at = timestamp(node.updated_at),
                n.properties = node.properties
            ON MATCH SET n.name = node.name, n.type = node.type,
                n.updated_at = timestamp(node.updated_at), n.properties = node.properties
        "#;

        conn.query(batch)
            .expect("UNWIND+MERGE batch should be supported by lbug");
        // Run again — MERGE must be idempotent (no duplicate-PK error, still 2 nodes).
        conn.query(batch)
            .expect("re-running MERGE batch must not error");

        let count = conn
            .query("MATCH (n:Node) RETURN COUNT(n) AS c")
            .unwrap()
            .next()
            .and_then(|row| row.into_iter().next())
            .and_then(|v| match v {
                LbugValue::Int64(c) => Some(c),
                LbugValue::Int32(c) => Some(c as i64),
                LbugValue::UInt64(c) => Some(c as i64),
                _ => None,
            })
            .unwrap();
        assert_eq!(count, 2, "MERGE must upsert, not duplicate");
    }

    #[tokio::test]
    #[serial]
    async fn test_adapter_creation() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");

        let adapter = LadybugAdapter::new(db_path.to_str().unwrap()).await;
        assert!(adapter.is_ok());
    }

    #[tokio::test]
    #[serial]
    async fn test_initialize() {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test_init.db");

        let adapter = LadybugAdapter::new(db_path.to_str().unwrap())
            .await
            .unwrap();
        let result = adapter.initialize().await;
        if let Err(e) = &result {
            eprintln!("Initialization error: {e:?}");
        }
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_empty() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Test with empty slice
        let nodes: Vec<&TestNode> = vec![];
        let result = adapter.add_nodes(&nodes).await;
        assert!(result.is_ok());

        // Verify no nodes were added
        assert!(adapter.is_empty().await.unwrap());
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_single_node() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node = TestNode::new("test-1", "Node 1", 100);
        let nodes = vec![&node];

        let result = adapter.add_nodes(&nodes).await;
        assert!(result.is_ok());

        // Verify node was added
        assert!(!adapter.is_empty().await.unwrap());
        assert!(adapter.has_node("test-1").await.unwrap());
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_ten_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let nodes: Vec<TestNode> = (0..10)
            .map(|i| TestNode::new(&format!("test-{i}"), &format!("Node {i}"), i * 10))
            .collect();
        let node_refs: Vec<&TestNode> = nodes.iter().collect();

        let result = adapter.add_nodes(&node_refs).await;
        assert!(result.is_ok());

        // Verify all nodes were added
        for i in 0..10 {
            assert!(
                adapter.has_node(&format!("test-{i}")).await.unwrap(),
                "Node test-{i} should exist"
            );
        }

        // Check total count
        let metrics = adapter.get_graph_metrics(false).await.unwrap();
        assert_eq!(metrics.get("node_count").unwrap().as_i64().unwrap(), 10);
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_hundred_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let nodes: Vec<TestNode> = (0..100)
            .map(|i| TestNode::new(&format!("test-{i}"), &format!("Node {i}"), i * 10))
            .collect();
        let node_refs: Vec<&TestNode> = nodes.iter().collect();

        let result = adapter.add_nodes(&node_refs).await;
        assert!(result.is_ok());

        // Verify count
        let metrics = adapter.get_graph_metrics(false).await.unwrap();
        assert_eq!(metrics.get("node_count").unwrap().as_i64().unwrap(), 100);

        // Spot check a few nodes
        assert!(adapter.has_node("test-0").await.unwrap());
        assert!(adapter.has_node("test-50").await.unwrap());
        assert!(adapter.has_node("test-99").await.unwrap());
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_thousand_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let nodes: Vec<TestNode> = (0..1000)
            .map(|i| TestNode::new(&format!("test-{i}"), &format!("Node {i}"), i * 10))
            .collect();
        let node_refs: Vec<&TestNode> = nodes.iter().collect();

        let result = adapter.add_nodes(&node_refs).await;
        assert!(result.is_ok());

        // Verify count (should process in chunks of 500)
        let metrics = adapter.get_graph_metrics(false).await.unwrap();
        assert_eq!(metrics.get("node_count").unwrap().as_i64().unwrap(), 1000);

        // Spot check nodes across batch boundaries
        assert!(adapter.has_node("test-0").await.unwrap());
        assert!(adapter.has_node("test-499").await.unwrap()); // Last of first batch
        assert!(adapter.has_node("test-500").await.unwrap()); // First of second batch
        assert!(adapter.has_node("test-999").await.unwrap());
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_insert_preserves_data() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let nodes: Vec<TestNode> = vec![
            TestNode::new("test-a", "Alice", 100),
            TestNode::new("test-b", "Bob", 200),
            TestNode::new("test-c", "Charlie", 300),
        ];
        let node_refs: Vec<&TestNode> = nodes.iter().collect();

        adapter.add_nodes(&node_refs).await.unwrap();

        // Verify node data is preserved
        let alice = adapter.get_node("test-a").await.unwrap().unwrap();
        assert_eq!(alice.get("id").unwrap().as_str().unwrap(), "test-a");
        assert_eq!(alice.get("name").unwrap().as_str().unwrap(), "Alice");
        assert_eq!(alice.get("value").unwrap().as_i64().unwrap(), 100);

        let bob = adapter.get_node("test-b").await.unwrap().unwrap();
        assert_eq!(bob.get("name").unwrap().as_str().unwrap(), "Bob");
        assert_eq!(bob.get("value").unwrap().as_i64().unwrap(), 200);

        let charlie = adapter.get_node("test-c").await.unwrap().unwrap();
        assert_eq!(charlie.get("name").unwrap().as_str().unwrap(), "Charlie");
        assert_eq!(charlie.get("value").unwrap().as_i64().unwrap(), 300);
    }

    #[tokio::test]
    #[serial]
    async fn test_add_node_upserts_duplicate_id() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let original = TestNode::new("dup-node", "Original", 100);
        let replacement = TestNode::new("dup-node", "Updated", 200);

        adapter.add_node(&original).await.unwrap();
        adapter.add_node(&replacement).await.unwrap();

        let node = adapter.get_node("dup-node").await.unwrap().unwrap();
        assert_eq!(node.get("name").unwrap().as_str().unwrap(), "Updated");
        assert_eq!(node.get("value").unwrap().as_i64().unwrap(), 200);

        let metrics = adapter.get_graph_metrics(false).await.unwrap();
        assert_eq!(metrics.get("node_count").unwrap().as_i64().unwrap(), 1);
    }

    #[tokio::test]
    #[serial]
    async fn test_batch_vs_sequential_equivalence() {
        // Create two adapters
        let (adapter_batch, _temp_dir_batch) = setup_adapter().await;
        let (adapter_seq, _temp_dir_seq) = setup_adapter().await;

        let nodes: Vec<TestNode> = (0..20)
            .map(|i| TestNode::new(&format!("test-{i}"), &format!("Node {i}"), i * 10))
            .collect();
        let node_refs: Vec<&TestNode> = nodes.iter().collect();

        // Batch insert
        adapter_batch.add_nodes(&node_refs).await.unwrap();

        // Sequential insert
        for node in &node_refs {
            adapter_seq.add_node(node).await.unwrap();
        }

        // Both should have same node count
        let metrics_batch = adapter_batch.get_graph_metrics(false).await.unwrap();
        let metrics_seq = adapter_seq.get_graph_metrics(false).await.unwrap();

        assert_eq!(
            metrics_batch.get("node_count").unwrap(),
            metrics_seq.get("node_count").unwrap()
        );

        // Spot check that same nodes exist in both
        for i in 0..20 {
            let node_id = format!("test-{i}");
            assert!(adapter_batch.has_node(&node_id).await.unwrap());
            assert!(adapter_seq.has_node(&node_id).await.unwrap());
        }
    }

    // Tests for get_connections()
    #[tokio::test]
    #[serial]
    async fn test_get_connections_node_with_no_connections() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node = TestNode::new("isolated", "Isolated Node", 42);
        adapter.add_node(&node).await.unwrap();

        let connections = adapter.get_connections("isolated").await.unwrap();
        assert_eq!(connections.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_outgoing_only() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Create nodes
        let node_a = TestNode::new("node-a", "Node A", 1);
        let node_b = TestNode::new("node-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Add edge A -> B
        adapter
            .add_edge("node-a", "node-b", "points_to", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        assert_eq!(connections.len(), 1);

        let (source, edge_props, target) = &connections[0];
        assert_eq!(source.get("id").unwrap().as_str().unwrap(), "node-a");
        assert_eq!(target.get("id").unwrap().as_str().unwrap(), "node-b");
        assert_eq!(
            edge_props
                .get("relationship_name")
                .unwrap()
                .as_str()
                .unwrap(),
            "points_to"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_incoming_only() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Node A", 1);
        let node_b = TestNode::new("node-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Add edge A -> B (so B has incoming edge)
        adapter
            .add_edge("node-a", "node-b", "points_to", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-b").await.unwrap();
        assert_eq!(connections.len(), 1);

        let (source, _, target) = &connections[0];
        assert_eq!(source.get("id").unwrap().as_str().unwrap(), "node-b");
        assert_eq!(target.get("id").unwrap().as_str().unwrap(), "node-a");
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_bidirectional() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Node A", 1);
        let node_b = TestNode::new("node-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Add both directions
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-b", "node-a", "knows", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        assert_eq!(connections.len(), 2);

        // Both connections should involve node-a and node-b
        for (source, _, target) in &connections {
            let source_id = source.get("id").unwrap().as_str().unwrap();
            let target_id = target.get("id").unwrap().as_str().unwrap();
            assert_eq!(source_id, "node-a");
            assert!(target_id == "node-b" || target_id == "node-a");
        }
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_self_loop() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node = TestNode::new("node-a", "Node A", 1);
        adapter.add_node(&node).await.unwrap();

        // Self-loop
        adapter
            .add_edge("node-a", "node-a", "references", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        // Self-loop appears twice due to bidirectional pattern (once as outgoing, once as incoming)
        assert_eq!(connections.len(), 2);

        // Both should be self-references
        for (source, edge_props, target) in &connections {
            assert_eq!(source.get("id").unwrap().as_str().unwrap(), "node-a");
            assert_eq!(target.get("id").unwrap().as_str().unwrap(), "node-a");
            assert_eq!(
                edge_props
                    .get("relationship_name")
                    .unwrap()
                    .as_str()
                    .unwrap(),
                "references"
            );
        }
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_multiple_relationship_types() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Node A", 1);
        let node_b = TestNode::new("node-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Multiple edges with different relationships
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-b", "works_with", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-b", "lives_near", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        assert_eq!(connections.len(), 3);

        // Collect all relationship names
        let rel_names: Vec<String> = connections
            .iter()
            .map(|(_, edge_props, _)| {
                edge_props
                    .get("relationship_name")
                    .unwrap()
                    .as_str()
                    .unwrap()
                    .to_string()
            })
            .collect();

        assert!(rel_names.contains(&"knows".to_string()));
        assert!(rel_names.contains(&"works_with".to_string()));
        assert!(rel_names.contains(&"lives_near".to_string()));
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_edge_properties() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Node A", 1);
        let node_b = TestNode::new("node-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Add edge with custom properties
        let mut props = HashMap::new();
        props.insert(Cow::Borrowed("since"), json!(2020));
        props.insert(Cow::Borrowed("strength"), json!("strong"));

        adapter
            .add_edge("node-a", "node-b", "knows", Some(props))
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        assert_eq!(connections.len(), 1);

        let (_, edge_props, _) = &connections[0];
        assert_eq!(
            edge_props
                .get("relationship_name")
                .unwrap()
                .as_str()
                .unwrap(),
            "knows"
        );
        assert_eq!(edge_props.get("since").unwrap().as_i64().unwrap(), 2020);
        assert_eq!(
            edge_props.get("strength").unwrap().as_str().unwrap(),
            "strong"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_add_edge_upserts_duplicate_key() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("edge-a", "Node A", 1);
        let node_b = TestNode::new("edge-b", "Node B", 2);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        let mut original_props = HashMap::new();
        original_props.insert(Cow::Borrowed("since"), json!(2020));

        let mut replacement_props = HashMap::new();
        replacement_props.insert(Cow::Borrowed("since"), json!(2024));
        replacement_props.insert(Cow::Borrowed("strength"), json!("high"));

        adapter
            .add_edge("edge-a", "edge-b", "knows", Some(original_props))
            .await
            .unwrap();
        adapter
            .add_edge("edge-a", "edge-b", "knows", Some(replacement_props))
            .await
            .unwrap();

        let edges = adapter.get_edges("edge-a").await.unwrap();
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].2, "knows");
        assert_eq!(edges[0].3.get("since").unwrap().as_i64().unwrap(), 2024);
        assert_eq!(
            edges[0].3.get("strength").unwrap().as_str().unwrap(),
            "high"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_concurrent_upsert_regression_single_process() {
        let (adapter, _temp_dir) = setup_adapter().await;
        let adapter = Arc::new(adapter);

        let mut node_tasks = JoinSet::new();
        for idx in 0..16 {
            let adapter = Arc::clone(&adapter);
            node_tasks.spawn(async move {
                let node = TestNode::new("race-node", &format!("Name-{idx}"), idx);
                adapter.add_node(&node).await
            });
        }

        while let Some(join_result) = node_tasks.join_next().await {
            let op_result = join_result.expect("node task should not panic");
            assert!(op_result.is_ok(), "node upsert should not fail");
        }

        let race_node = adapter
            .get_node("race-node")
            .await
            .unwrap()
            .expect("race-node should exist");
        assert!(
            race_node.get("name").and_then(|v| v.as_str()).is_some(),
            "race-node should preserve string fields"
        );

        let mut edge_tasks = JoinSet::new();
        for idx in 0..16 {
            let adapter = Arc::clone(&adapter);
            edge_tasks.spawn(async move {
                let mut props = HashMap::new();
                props.insert(Cow::Borrowed("iteration"), json!(idx));
                adapter
                    .add_edge("race-node", "race-node", "self", Some(props))
                    .await
            });
        }

        while let Some(join_result) = edge_tasks.join_next().await {
            let op_result = join_result.expect("edge task should not panic");
            assert!(op_result.is_ok(), "edge upsert should not fail");
        }

        assert!(
            adapter
                .has_edge("race-node", "race-node", "self")
                .await
                .unwrap(),
            "self edge should exist"
        );
        let metrics = adapter.get_graph_metrics(false).await.unwrap();
        assert_eq!(
            metrics.get("edge_count").unwrap().as_i64().unwrap(),
            1,
            "self edge should remain idempotent"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_get_connections_node_properties_expanded() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Create nodes with custom properties
        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();

        let connections = adapter.get_connections("node-a").await.unwrap();
        assert_eq!(connections.len(), 1);

        let (source, _, target) = &connections[0];

        // Verify source node properties
        assert_eq!(source.get("id").unwrap().as_str().unwrap(), "node-a");
        assert_eq!(source.get("name").unwrap().as_str().unwrap(), "Alice");
        assert_eq!(source.get("value").unwrap().as_i64().unwrap(), 100);

        // Verify target node properties
        assert_eq!(target.get("id").unwrap().as_str().unwrap(), "node-b");
        assert_eq!(target.get("name").unwrap().as_str().unwrap(), "Bob");
        assert_eq!(target.get("value").unwrap().as_i64().unwrap(), 200);
    }

    // Tests for get_filtered_graph_data

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_empty_filters() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Create some test nodes
        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();

        // Empty filters should return entire graph
        let filters = HashMap::new();
        let (nodes, edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        assert_eq!(edges.len(), 1);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_single_attribute_single_value() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Filter by name = "Alice"
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("name"), vec![json!("Alice")]);

        let (nodes, _edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].1.get("name").unwrap().as_str().unwrap(), "Alice");
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_single_attribute_multiple_values() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Filter by name IN ["Alice", "Charlie"] (OR logic)
        let mut filters = HashMap::new();
        filters.insert(
            Cow::Borrowed("name"),
            vec![json!("Alice"), json!("Charlie")],
        );

        let (nodes, _edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        let names: Vec<_> = nodes
            .iter()
            .map(|(_, n)| n.get("name").unwrap().as_str().unwrap())
            .collect();
        assert!(names.contains(&"Alice"));
        assert!(names.contains(&"Charlie"));
        assert!(!names.contains(&"Bob"));
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_multiple_attributes_and_logic() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Create test nodes with different types
        #[derive(Serialize)]
        struct TypedNode {
            id: String,
            name: String,
            data_type: String, // This maps to the 'type' column in DB
            created_at: String,
            updated_at: String,
        }

        let node_a = TypedNode {
            id: "node-a".to_string(),
            name: "Alice".to_string(),
            data_type: "Person".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };

        let node_b = TypedNode {
            id: "node-b".to_string(),
            name: "Bob".to_string(),
            data_type: "Person".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };

        let node_c = TypedNode {
            id: "node-c".to_string(),
            name: "Charlie".to_string(),
            data_type: "Organization".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };

        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Filter by type = "Person" AND name IN ["Alice", "Bob"] (AND logic)
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("type"), vec![json!("Person")]);
        filters.insert(Cow::Borrowed("name"), vec![json!("Alice"), json!("Bob")]);

        let (nodes, _edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        for (_, node) in &nodes {
            assert_eq!(node.get("type").unwrap().as_str().unwrap(), "Person");
            let name = node.get("name").unwrap().as_str().unwrap();
            assert!(name == "Alice" || name == "Bob");
        }
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_property_filters() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 100);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Filter by value = 100 (property field, filtered in Rust)
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("value"), vec![json!(100)]);

        let (nodes, _edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        for (_, node) in &nodes {
            assert_eq!(node.get("value").unwrap().as_i64().unwrap(), 100);
        }
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_mixed_core_and_property_filters() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 100);
        let node_c = TestNode::new("node-c", "Charlie", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Filter by name IN ["Alice", "Bob"] (core) AND value = 100 (property)
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("name"), vec![json!("Alice"), json!("Bob")]);
        filters.insert(Cow::Borrowed("value"), vec![json!(100)]);

        let (nodes, _edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        for (_, node) in &nodes {
            let name = node.get("name").unwrap().as_str().unwrap();
            assert!(name == "Alice" || name == "Bob");
            assert_eq!(node.get("value").unwrap().as_i64().unwrap(), 100);
        }
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_no_matches() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Filter by non-existent name
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("name"), vec![json!("NonExistent")]);

        let (nodes, edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 0);
        assert_eq!(edges.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_edges_between_filtered_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Create edges: A -> B, B -> C, A -> C
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-b", "node-c", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-c", "knows", None)
            .await
            .unwrap();

        // Filter for Alice and Bob only
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("name"), vec![json!("Alice"), json!("Bob")]);

        let (nodes, edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        // Only edge A -> B should be returned (both nodes in filter)
        // Edge B -> C and A -> C should NOT be returned (Charlie not in filter)
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].0, "node-a"); // source
        assert_eq!(edges[0].1, "node-b"); // target
    }

    #[tokio::test]
    #[serial]
    async fn test_get_filtered_graph_data_multiple_relationship_types() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Create multiple edges with different relationship types
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-b", "works_with", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-b", "friends_with", None)
            .await
            .unwrap();

        // Filter for both nodes
        let mut filters = HashMap::new();
        filters.insert(Cow::Borrowed("name"), vec![json!("Alice"), json!("Bob")]);

        let (nodes, edges) = adapter.get_filtered_graph_data(&filters).await.unwrap();

        assert_eq!(nodes.len(), 2);
        // All three edges should be returned
        assert_eq!(edges.len(), 3);

        let rel_names: Vec<_> = edges.iter().map(|(_, _, rel, _)| rel.as_str()).collect();
        assert!(rel_names.contains(&"knows"));
        assert!(rel_names.contains(&"works_with"));
        assert!(rel_names.contains(&"friends_with"));
    }

    // Tests for get_nodeset_subgraph

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_empty_node_names() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        adapter.add_node(&node_a).await.unwrap();

        // Empty node_names should return empty result
        let (nodes, edges) = adapter
            .get_nodeset_subgraph("TestNode", &[], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 0);
        assert_eq!(edges.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_non_existent_type() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        adapter.add_node(&node_a).await.unwrap();

        // Non-existent type should return empty result
        let (nodes, edges) = adapter
            .get_nodeset_subgraph("NonExistentType", &["Alice".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 0);
        assert_eq!(edges.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_non_existent_names() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        adapter.add_node(&node_a).await.unwrap();

        // Non-existent names should return empty result
        let (nodes, edges) = adapter
            .get_nodeset_subgraph("test", &["Bob".to_string(), "Charlie".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 0);
        assert_eq!(edges.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_valid_single_node() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // Get single node by type + name (no edges, so no neighbors)
        let (nodes, _edges) = adapter
            .get_nodeset_subgraph("TestNode", &["Alice".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].1.get("name").unwrap().as_str().unwrap(), "Alice");
        assert_eq!(
            nodes[0].1.get("type").unwrap().as_str().unwrap(),
            "TestNode"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_valid_multiple_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Get multiple nodes by type + names (no edges, so no neighbors)
        let (nodes, _edges) = adapter
            .get_nodeset_subgraph(
                "TestNode",
                &["Alice".to_string(), "Charlie".to_string()],
                "OR",
            )
            .await
            .unwrap();

        assert_eq!(nodes.len(), 2);
        let names: Vec<_> = nodes
            .iter()
            .map(|(_, n)| n.get("name").unwrap().as_str().unwrap())
            .collect();
        assert!(names.contains(&"Alice"));
        assert!(names.contains(&"Charlie"));
        assert!(!names.contains(&"Bob"));
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_edges_only_between_specified_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Create edges: A -> B, B -> C, A -> C
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-b", "node-c", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-c", "knows", None)
            .await
            .unwrap();

        // Get subgraph for Alice and Bob — with OR mode their neighbors are also included.
        // Alice's neighbors (via A→B, A→C): Bob, Charlie
        // Bob's neighbors (via A→B, B→C): Alice, Charlie
        // Union: Alice + Bob + Charlie
        let (nodes, edges) = adapter
            .get_nodeset_subgraph("TestNode", &["Alice".to_string(), "Bob".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 3);
        // All three edges connect nodes in the subgraph: A→B, B→C, A→C
        assert_eq!(edges.len(), 3);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_no_edges_between_nodes() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();

        // No edges created — neighbors will be empty, only primary nodes returned
        let (nodes, edges) = adapter
            .get_nodeset_subgraph("TestNode", &["Alice".to_string(), "Bob".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 2);
        assert_eq!(edges.len(), 0);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_densely_connected() {
        let (adapter, _temp_dir) = setup_adapter().await;

        let node_a = TestNode::new("node-a", "Alice", 100);
        let node_b = TestNode::new("node-b", "Bob", 200);
        let node_c = TestNode::new("node-c", "Charlie", 300);
        adapter.add_node(&node_a).await.unwrap();
        adapter.add_node(&node_b).await.unwrap();
        adapter.add_node(&node_c).await.unwrap();

        // Create a densely connected subgraph: all pairs connected
        adapter
            .add_edge("node-a", "node-b", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-b", "node-a", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-a", "node-c", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-c", "node-a", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-b", "node-c", "knows", None)
            .await
            .unwrap();
        adapter
            .add_edge("node-c", "node-b", "knows", None)
            .await
            .unwrap();

        // Get all three nodes (OR mode — neighbors already all included in primary set)
        let (nodes, edges) = adapter
            .get_nodeset_subgraph(
                "TestNode",
                &[
                    "Alice".to_string(),
                    "Bob".to_string(),
                    "Charlie".to_string(),
                ],
                "OR",
            )
            .await
            .unwrap();

        assert_eq!(nodes.len(), 3);
        // All 6 edges should be returned
        assert_eq!(edges.len(), 6);
    }

    #[tokio::test]
    #[serial]
    async fn test_get_nodeset_subgraph_filters_by_type() {
        let (adapter, _temp_dir) = setup_adapter().await;

        // Create nodes with different types
        #[derive(Serialize)]
        struct TypedNode {
            id: String,
            name: String,
            data_type: String,
            created_at: String,
            updated_at: String,
        }

        let person_a = TypedNode {
            id: "node-a".to_string(),
            name: "Alice".to_string(),
            data_type: "Person".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };

        let org_a = TypedNode {
            id: "node-b".to_string(),
            name: "Alice".to_string(), // Same name, different type
            data_type: "Organization".to_string(),
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: chrono::Utc::now().to_rfc3339(),
        };

        adapter.add_node(&person_a).await.unwrap();
        adapter.add_node(&org_a).await.unwrap();

        // Get only Person type with name Alice (no edges, so no neighbors)
        let (nodes, _edges) = adapter
            .get_nodeset_subgraph("Person", &["Alice".to_string()], "OR")
            .await
            .unwrap();

        assert_eq!(nodes.len(), 1);
        assert_eq!(nodes[0].1.get("name").unwrap().as_str().unwrap(), "Alice");
        assert_eq!(nodes[0].1.get("type").unwrap().as_str().unwrap(), "Person");
    }
}