interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
//! Integration tests for MmapGraph persistent storage.
//!
//! These tests verify the memory-mapped storage backend functionality including:
//! - Database creation and opening
//! - Vertex and edge persistence
//! - Checkpoint and WAL operations
//! - Crash recovery
//!
//! Tests use tempfile for isolation and are independent of each other.

use interstellar::storage::{GraphStorage, MmapGraph};
use std::collections::HashMap;
use tempfile::TempDir;

// =============================================================================
// Helper Functions
// =============================================================================

/// Create a temporary directory and return it along with the database path.
fn temp_db() -> (TempDir, std::path::PathBuf) {
    let dir = TempDir::new().expect("create temp dir");
    let db_path = dir.path().join("test.db");
    (dir, db_path)
}

// =============================================================================
// Phase 4.6: Checkpoint Tests
// =============================================================================

/// Test: Add data, checkpoint, verify WAL empty
///
/// This test verifies that the checkpoint() method:
/// 1. Flushes all pending writes to the data file
/// 2. Truncates the WAL file (removes all entries)
///
/// After a checkpoint, the WAL should be empty because all committed
/// transactions have been persisted to the main data file.
#[test]
fn test_checkpoint_empties_wal() {
    let (_dir, db_path) = temp_db();
    let wal_path = db_path.with_extension("wal");

    // Create graph and add data
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add some vertices (which write to WAL)
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex 1");
    let v2 = graph
        .add_vertex("software", HashMap::new())
        .expect("add vertex 2");

    // Add an edge (which also writes to WAL)
    graph
        .add_edge(v1, v2, "created", HashMap::new())
        .expect("add edge");

    // WAL should have content before checkpoint
    let wal_size_before = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert!(
        wal_size_before > 0,
        "WAL should have content before checkpoint (size: {})",
        wal_size_before
    );

    // Checkpoint
    graph.checkpoint().expect("checkpoint");

    // WAL should be empty after checkpoint
    let wal_size_after = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert_eq!(
        wal_size_after, 0,
        "WAL should be empty after checkpoint (size: {})",
        wal_size_after
    );
}

/// Test that data is still accessible after checkpoint.
///
/// Checkpoint should not affect the ability to read data - it just
/// ensures durability and clears the WAL.
#[test]
fn test_data_accessible_after_checkpoint() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add vertices with properties
    let alice = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Alice".into())]),
        )
        .expect("add alice");
    let bob = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Bob".into())]),
        )
        .expect("add bob");

    // Add edge
    let edge_id = graph
        .add_edge(alice, bob, "knows", HashMap::new())
        .expect("add edge");

    // Checkpoint
    graph.checkpoint().expect("checkpoint");

    // Verify data is still accessible
    let alice_vertex = graph.get_vertex(alice).expect("get alice");
    assert_eq!(alice_vertex.label, "person");
    assert_eq!(
        alice_vertex.properties.get("name").and_then(|v| v.as_str()),
        Some("Alice")
    );

    let bob_vertex = graph.get_vertex(bob).expect("get bob");
    assert_eq!(bob_vertex.label, "person");
    assert_eq!(
        bob_vertex.properties.get("name").and_then(|v| v.as_str()),
        Some("Bob")
    );

    let edge = graph.get_edge(edge_id).expect("get edge");
    assert_eq!(edge.label, "knows");
    assert_eq!(edge.src, alice);
    assert_eq!(edge.dst, bob);

    // Verify counts
    assert_eq!(graph.vertex_count(), 2);
    assert_eq!(graph.edge_count(), 1);
}

/// Test multiple checkpoints in sequence.
///
/// Should be able to call checkpoint() multiple times without issues.
#[test]
fn test_multiple_checkpoints() {
    let (_dir, db_path) = temp_db();
    let wal_path = db_path.with_extension("wal");

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // First batch of data
    graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    graph.checkpoint().expect("checkpoint 1");

    let wal_size_1 = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert_eq!(wal_size_1, 0, "WAL should be empty after first checkpoint");

    // Second batch of data
    graph
        .add_vertex("software", HashMap::new())
        .expect("add vertex");
    graph.checkpoint().expect("checkpoint 2");

    let wal_size_2 = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert_eq!(wal_size_2, 0, "WAL should be empty after second checkpoint");

    // Third batch of data
    let v1 = graph
        .add_vertex("location", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("location", HashMap::new())
        .expect("add vertex");
    graph
        .add_edge(v1, v2, "connected", HashMap::new())
        .expect("add edge");
    graph.checkpoint().expect("checkpoint 3");

    let wal_size_3 = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert_eq!(wal_size_3, 0, "WAL should be empty after third checkpoint");

    // Verify all data is present
    assert_eq!(graph.vertex_count(), 4);
    assert_eq!(graph.edge_count(), 1);
}

/// Test checkpoint on empty database.
///
/// Should be able to checkpoint even when no data has been added.
#[test]
fn test_checkpoint_empty_database() {
    let (_dir, db_path) = temp_db();
    let wal_path = db_path.with_extension("wal");

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Checkpoint with no data
    graph.checkpoint().expect("checkpoint empty db");

    // WAL should be empty (or very small - just checkpoint entry then truncated)
    let wal_size = std::fs::metadata(&wal_path).map(|m| m.len()).unwrap_or(0);
    assert_eq!(wal_size, 0, "WAL should be empty after checkpoint");

    // Should still be able to add data after
    graph
        .add_vertex("test", HashMap::new())
        .expect("add vertex after checkpoint");
    assert_eq!(graph.vertex_count(), 1);
}

// =============================================================================
// Phase 5.4: Basic Operations Tests
// =============================================================================

/// Test creating a new database.
#[test]
fn test_create_new_database() {
    let (_dir, db_path) = temp_db();

    assert!(!db_path.exists(), "database should not exist initially");

    let graph = MmapGraph::open(&db_path).expect("open graph");

    assert!(db_path.exists(), "database file should be created");
    assert_eq!(graph.vertex_count(), 0);
    assert_eq!(graph.edge_count(), 0);
}

/// Test adding vertices.
#[test]
fn test_add_vertex() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add vertex without properties
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");

    // Add vertex with properties
    let v2 = graph
        .add_vertex(
            "software",
            HashMap::from([
                ("name".to_string(), "Interstellar".into()),
                ("version".to_string(), "0.1.0".into()),
            ]),
        )
        .expect("add vertex with props");

    assert_eq!(graph.vertex_count(), 2);

    // Verify vertex 1
    let vertex1 = graph.get_vertex(v1).expect("get v1");
    assert_eq!(vertex1.label, "person");
    assert!(vertex1.properties.is_empty());

    // Verify vertex 2
    let vertex2 = graph.get_vertex(v2).expect("get v2");
    assert_eq!(vertex2.label, "software");
    assert_eq!(
        vertex2.properties.get("name").and_then(|v| v.as_str()),
        Some("Interstellar")
    );
    assert_eq!(
        vertex2.properties.get("version").and_then(|v| v.as_str()),
        Some("0.1.0")
    );
}

/// Test adding edges.
#[test]
fn test_add_edge() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices
    let alice = graph
        .add_vertex("person", HashMap::new())
        .expect("add alice");
    let bob = graph.add_vertex("person", HashMap::new()).expect("add bob");

    // Add edge without properties
    let e1 = graph
        .add_edge(alice, bob, "knows", HashMap::new())
        .expect("add edge");

    assert_eq!(graph.edge_count(), 1);

    // Verify edge
    let edge = graph.get_edge(e1).expect("get edge");
    assert_eq!(edge.label, "knows");
    assert_eq!(edge.src, alice);
    assert_eq!(edge.dst, bob);
    assert!(edge.properties.is_empty());
}

/// Test adding edge with properties.
#[test]
fn test_add_edge_with_properties() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    let alice = graph
        .add_vertex("person", HashMap::new())
        .expect("add alice");
    let project = graph
        .add_vertex("software", HashMap::new())
        .expect("add project");

    let edge_id = graph
        .add_edge(
            alice,
            project,
            "created",
            HashMap::from([
                ("year".to_string(), 2024i64.into()),
                ("role".to_string(), "lead".into()),
            ]),
        )
        .expect("add edge with props");

    let edge = graph.get_edge(edge_id).expect("get edge");
    assert_eq!(edge.label, "created");
    assert_eq!(
        edge.properties.get("year").and_then(|v| v.as_i64()),
        Some(2024)
    );
    assert_eq!(
        edge.properties.get("role").and_then(|v| v.as_str()),
        Some("lead")
    );
}

/// Test persistence across reopens.
#[test]
fn test_persistence() {
    let (dir, db_path) = temp_db();

    // Create graph and add data
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        let alice = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add alice");
        let bob = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Bob".into())]),
            )
            .expect("add bob");

        graph
            .add_edge(
                alice,
                bob,
                "knows",
                HashMap::from([("since".to_string(), 2020i64.into())]),
            )
            .expect("add edge");

        // Checkpoint to ensure durability
        graph.checkpoint().expect("checkpoint");

        // Graph is dropped here
    }

    // Reopen and verify data persisted
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        assert_eq!(graph.vertex_count(), 2, "vertex count should persist");
        assert_eq!(graph.edge_count(), 1, "edge count should persist");

        // Verify vertices by label
        let people: Vec<_> = graph.vertices_with_label("person").collect();
        assert_eq!(people.len(), 2, "should have 2 people");

        // Verify edge
        let edges: Vec<_> = graph.edges_with_label("knows").collect();
        assert_eq!(edges.len(), 1, "should have 1 knows edge");
        assert_eq!(
            edges[0].properties.get("since").and_then(|v| v.as_i64()),
            Some(2020)
        );
    }

    // Keep dir alive until after second open
    drop(dir);
}

/// Test label index functionality.
#[test]
fn test_label_index() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add vertices with different labels
    graph
        .add_vertex("person", HashMap::new())
        .expect("add person 1");
    graph
        .add_vertex("person", HashMap::new())
        .expect("add person 2");
    graph
        .add_vertex("person", HashMap::new())
        .expect("add person 3");
    graph
        .add_vertex("software", HashMap::new())
        .expect("add software 1");
    graph
        .add_vertex("software", HashMap::new())
        .expect("add software 2");
    graph
        .add_vertex("company", HashMap::new())
        .expect("add company");

    // Verify label queries
    assert_eq!(graph.vertices_with_label("person").count(), 3);
    assert_eq!(graph.vertices_with_label("software").count(), 2);
    assert_eq!(graph.vertices_with_label("company").count(), 1);
    assert_eq!(graph.vertices_with_label("nonexistent").count(), 0);
}

/// Test adjacency traversal.
#[test]
fn test_adjacency_traversal() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a small graph: alice -> bob -> charlie
    //                        |              ^
    //                        +--------------+
    let alice = graph
        .add_vertex("person", HashMap::new())
        .expect("add alice");
    let bob = graph.add_vertex("person", HashMap::new()).expect("add bob");
    let charlie = graph
        .add_vertex("person", HashMap::new())
        .expect("add charlie");

    graph
        .add_edge(alice, bob, "knows", HashMap::new())
        .expect("alice->bob");
    graph
        .add_edge(bob, charlie, "knows", HashMap::new())
        .expect("bob->charlie");
    graph
        .add_edge(alice, charlie, "knows", HashMap::new())
        .expect("alice->charlie");

    // Test out_edges
    let alice_out: Vec<_> = graph.out_edges(alice).collect();
    assert_eq!(alice_out.len(), 2, "alice should have 2 outgoing edges");

    let bob_out: Vec<_> = graph.out_edges(bob).collect();
    assert_eq!(bob_out.len(), 1, "bob should have 1 outgoing edge");

    let charlie_out: Vec<_> = graph.out_edges(charlie).collect();
    assert_eq!(charlie_out.len(), 0, "charlie should have 0 outgoing edges");

    // Test in_edges
    let alice_in: Vec<_> = graph.in_edges(alice).collect();
    assert_eq!(alice_in.len(), 0, "alice should have 0 incoming edges");

    let bob_in: Vec<_> = graph.in_edges(bob).collect();
    assert_eq!(bob_in.len(), 1, "bob should have 1 incoming edge");

    let charlie_in: Vec<_> = graph.in_edges(charlie).collect();
    assert_eq!(charlie_in.len(), 2, "charlie should have 2 incoming edges");
}

// =============================================================================
// Phase 5.5: Large Graph Tests
// =============================================================================

/// Test large graph with many vertices and edges.
///
/// This test verifies that the storage can handle:
/// - 1,000+ vertices  
/// - 5,000+ edges
/// - Automatic table growth when capacity is exceeded
///
/// Note: The full 10K vertices / 100K edges test is available as test_large_graph_full
/// but is ignored by default due to fsync overhead making it slow (~minutes).
#[test]
fn test_large_graph() {
    let (_dir, db_path) = temp_db();

    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Reduced size for fast CI - still tests table growth (initial capacity is 1024)
    const NUM_VERTICES: u64 = 1_500;
    const EDGES_PER_VERTEX: u64 = 4;

    // Add vertices
    let mut vertex_ids = Vec::with_capacity(NUM_VERTICES as usize);
    for i in 0..NUM_VERTICES {
        let props = HashMap::from([("index".to_string(), (i as i64).into())]);
        let id = graph.add_vertex("node", props).expect("add vertex");
        vertex_ids.push(id);
    }

    assert_eq!(
        graph.vertex_count(),
        NUM_VERTICES,
        "should have {} vertices",
        NUM_VERTICES
    );

    // Add edges (each vertex connects to next EDGES_PER_VERTEX vertices, wrapping)
    let mut edge_count = 0u64;
    for (i, &src) in vertex_ids.iter().enumerate() {
        for j in 1..=EDGES_PER_VERTEX {
            let dst_idx = (i as u64 + j) % NUM_VERTICES;
            let dst = vertex_ids[dst_idx as usize];
            graph
                .add_edge(src, dst, "connects", HashMap::new())
                .expect("add edge");
            edge_count += 1;
        }
    }

    let expected_edges = NUM_VERTICES * EDGES_PER_VERTEX;
    assert_eq!(
        graph.edge_count(),
        expected_edges,
        "should have {} edges",
        expected_edges
    );
    assert_eq!(edge_count, expected_edges);

    // Verify some random vertices have correct properties
    for &id in vertex_ids.iter().step_by(500) {
        let vertex = graph.get_vertex(id).expect("get vertex");
        assert_eq!(vertex.label, "node");
        assert!(vertex.properties.contains_key("index"));
    }

    // Verify adjacency lists
    for &id in vertex_ids.iter().take(50) {
        let out_edges: Vec<_> = graph.out_edges(id).collect();
        assert_eq!(
            out_edges.len(),
            EDGES_PER_VERTEX as usize,
            "each vertex should have {} outgoing edges",
            EDGES_PER_VERTEX
        );
    }
}

/// Test that node table growth preserves existing vertex data.
///
/// This test specifically verifies that when the node table grows (capacity exceeded),
/// all existing vertices remain accessible with correct properties.
/// Initial node capacity is 1000, so adding 1030 vertices triggers growth.
#[test]
fn test_grow_node_table_preserves_vertices() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add vertices beyond initial capacity (1000) to trigger growth
    let mut ids = Vec::new();
    for i in 0..1030 {
        let props = HashMap::from([("i".to_string(), (i as i64).into())]);
        let id = graph.add_vertex("node", props).expect("add vertex");
        ids.push(id);
    }

    // Verify all vertices are accessible after growth
    assert_eq!(graph.vertex_count(), 1030, "should have 1030 vertices");

    // Check first, middle, and last vertices
    let first = graph.get_vertex(ids[0]).expect("first vertex");
    assert_eq!(first.properties.get("i"), Some(&0i64.into()));

    let middle = graph.get_vertex(ids[500]).expect("middle vertex");
    assert_eq!(middle.properties.get("i"), Some(&500i64.into()));

    let last = graph.get_vertex(ids[1029]).expect("last vertex");
    assert_eq!(last.properties.get("i"), Some(&1029i64.into()));
}

/// Test that file grows correctly when capacity is exceeded.
///
/// Verifies that the storage automatically grows tables when the initial
/// capacity is exceeded.
#[test]
fn test_file_growth() {
    let (_dir, db_path) = temp_db();

    let initial_size = {
        let graph = MmapGraph::open(&db_path).expect("open graph");
        graph.checkpoint().expect("checkpoint");
        std::fs::metadata(&db_path).expect("get metadata").len()
    };

    // Reopen and add enough vertices to trigger table growth (initial capacity is 1000)
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        // Add 1100 vertices - just enough to exceed initial capacity of 1024
        for i in 0..1100 {
            let props = HashMap::from([("i".to_string(), (i as i64).into())]);
            graph.add_vertex("node", props).expect("add vertex");
        }

        graph.checkpoint().expect("checkpoint");
    }

    let final_size = std::fs::metadata(&db_path).expect("get metadata").len();
    assert!(
        final_size > initial_size,
        "file should grow from {} to larger size, got {}",
        initial_size,
        final_size
    );
}

/// Test reopening and appending to existing database.
///
/// Verifies that we can:
/// 1. Create a database and add data
/// 2. Close it
/// 3. Reopen and add more data
/// 4. All data is preserved
#[test]
fn test_reopen_and_append() {
    let (dir, db_path) = temp_db();

    // First session: add initial data
    let (first_vertex, _first_edge) = {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        let v1 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add v1");
        let v2 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Bob".into())]),
            )
            .expect("add v2");

        let e1 = graph
            .add_edge(v1, v2, "knows", HashMap::new())
            .expect("add edge");

        graph.checkpoint().expect("checkpoint");

        assert_eq!(graph.vertex_count(), 2);
        assert_eq!(graph.edge_count(), 1);

        (v1, e1)
    };

    // Second session: append more data
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        // Verify existing data
        assert_eq!(
            graph.vertex_count(),
            2,
            "should have 2 vertices from before"
        );
        assert_eq!(graph.edge_count(), 1, "should have 1 edge from before");

        let alice = graph.get_vertex(first_vertex).expect("get alice");
        assert_eq!(
            alice.properties.get("name").and_then(|v| v.as_str()),
            Some("Alice")
        );

        // Add more data
        let v3 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Charlie".into())]),
            )
            .expect("add v3");
        let v4 = graph
            .add_vertex(
                "software",
                HashMap::from([("name".to_string(), "Interstellar".into())]),
            )
            .expect("add v4");

        graph
            .add_edge(v3, v4, "created", HashMap::new())
            .expect("add edge");
        graph
            .add_edge(first_vertex, v3, "knows", HashMap::new())
            .expect("add edge");

        graph.checkpoint().expect("checkpoint");

        assert_eq!(graph.vertex_count(), 4);
        assert_eq!(graph.edge_count(), 3);
    }

    // Third session: verify all data persisted
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph again");

        assert_eq!(graph.vertex_count(), 4, "should have 4 vertices total");
        assert_eq!(graph.edge_count(), 3, "should have 3 edges total");

        // Verify by label
        assert_eq!(graph.vertices_with_label("person").count(), 3);
        assert_eq!(graph.vertices_with_label("software").count(), 1);
        assert_eq!(graph.edges_with_label("knows").count(), 2);
        assert_eq!(graph.edges_with_label("created").count(), 1);
    }

    drop(dir);
}

// =============================================================================
// Phase 5.6: Crash Recovery Tests
// =============================================================================

/// Test crash recovery with uncommitted transaction.
///
/// Simulates a "crash" by:
/// 1. Creating a graph and adding data
/// 2. Adding more data WITHOUT checkpointing
/// 3. Dropping the graph (simulates crash - WAL has uncommitted entries)
/// 4. Reopening - recovery should run
/// 5. Only committed (checkpointed) data should be present
///
/// Note: In our current implementation, each add_vertex/add_edge is its own
/// committed transaction in the WAL, so "uncommitted" means data written to
/// WAL but not yet flushed to the main data file via checkpoint.
#[test]
fn test_crash_recovery_uncommitted() {
    let (dir, db_path) = temp_db();

    // First session: add data and checkpoint
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        let v1 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add v1");
        let v2 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Bob".into())]),
            )
            .expect("add v2");

        graph
            .add_edge(v1, v2, "knows", HashMap::new())
            .expect("add edge");

        // Checkpoint - these are "committed" to the data file
        graph.checkpoint().expect("checkpoint");

        assert_eq!(graph.vertex_count(), 2);
        assert_eq!(graph.edge_count(), 1);
    }

    // Second session: add data WITHOUT checkpoint (simulates crash before checkpoint)
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        // These writes go to WAL and in-memory structures
        graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Charlie".into())]),
            )
            .expect("add v3");
        graph
            .add_vertex(
                "software",
                HashMap::from([("name".to_string(), "Graph".into())]),
            )
            .expect("add v4");

        // In-memory we have 4 vertices
        assert_eq!(graph.vertex_count(), 4);

        // Drop WITHOUT checkpoint - simulates crash
        // WAL has uncommitted entries that will be recovered
    }

    // Third session: verify recovery
    {
        let graph = MmapGraph::open(&db_path).expect("reopen after crash");

        // Recovery should replay WAL, so we should have all 4 vertices
        // (our WAL logs each operation as a committed transaction)
        assert_eq!(
            graph.vertex_count(),
            4,
            "recovery should restore all WAL entries"
        );

        // Verify the recovered vertices are accessible
        let people: Vec<_> = graph.vertices_with_label("person").collect();
        assert_eq!(people.len(), 3, "should have 3 person vertices");

        let software: Vec<_> = graph.vertices_with_label("software").collect();
        assert_eq!(software.len(), 1, "should have 1 software vertex");
    }

    drop(dir);
}

/// Test that committed transactions are recovered.
///
/// This verifies the positive case: data written and committed should
/// survive a "crash" (drop without explicit checkpoint).
#[test]
fn test_committed_transaction_recovery() {
    let (dir, db_path) = temp_db();

    // Create graph and add data (each operation is committed to WAL)
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        // Add vertices - each write is a committed transaction in WAL
        for i in 0..10 {
            let props = HashMap::from([("index".to_string(), (i as i64).into())]);
            graph.add_vertex("node", props).expect("add vertex");
        }

        // Add edges
        let vertices: Vec<_> = graph.all_vertices().collect();
        for i in 0..9 {
            graph
                .add_edge(vertices[i].id, vertices[i + 1].id, "next", HashMap::new())
                .expect("add edge");
        }

        assert_eq!(graph.vertex_count(), 10);
        assert_eq!(graph.edge_count(), 9);

        // NO checkpoint - drop "crashes" the database
    }

    // Reopen - recovery should replay WAL
    {
        let graph = MmapGraph::open(&db_path).expect("reopen after crash");

        // All data should be recovered from WAL
        assert_eq!(graph.vertex_count(), 10, "all vertices should be recovered");
        assert_eq!(graph.edge_count(), 9, "all edges should be recovered");

        // Verify data integrity
        let vertices: Vec<_> = graph.all_vertices().collect();
        assert_eq!(vertices.len(), 10);

        for vertex in &vertices {
            assert_eq!(vertex.label, "node");
            assert!(vertex.properties.contains_key("index"));
        }

        let edges: Vec<_> = graph.all_edges().collect();
        assert_eq!(edges.len(), 9);
        for edge in &edges {
            assert_eq!(edge.label, "next");
        }
    }

    drop(dir);
}

/// Test recovery is idempotent.
///
/// Opening a database multiple times should not corrupt data even if
/// recovery runs each time.
#[test]
fn test_recovery_idempotent() {
    let (dir, db_path) = temp_db();

    // Initial data
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");
        for i in 0..5 {
            let props = HashMap::from([("i".to_string(), (i as i64).into())]);
            graph.add_vertex("node", props).expect("add vertex");
        }
        // No checkpoint
    }

    // Open multiple times without checkpointing
    for _ in 0..3 {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");
        assert_eq!(graph.vertex_count(), 5, "vertex count should remain stable");
        // No checkpoint - each reopen may trigger recovery
    }

    // Final verification
    {
        let graph = MmapGraph::open(&db_path).expect("final reopen");
        assert_eq!(graph.vertex_count(), 5);

        let vertices: Vec<_> = graph.all_vertices().collect();
        for vertex in &vertices {
            assert_eq!(vertex.label, "node");
        }
    }

    drop(dir);
}

/// Test mixed operations recovery.
///
/// Tests that a mix of add and remove operations are correctly recovered.
#[test]
fn test_mixed_operations_recovery() {
    let (dir, db_path) = temp_db();

    // Create graph with mixed operations
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        // Add vertices
        let v1 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add v1");
        let v2 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Bob".into())]),
            )
            .expect("add v2");
        let v3 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Charlie".into())]),
            )
            .expect("add v3");

        // Add edges
        let e1 = graph
            .add_edge(v1, v2, "knows", HashMap::new())
            .expect("add e1");
        graph
            .add_edge(v2, v3, "knows", HashMap::new())
            .expect("add e2");

        // Remove some data
        graph.remove_edge(e1).expect("remove e1");
        graph.remove_vertex(v2).expect("remove v2");

        // Final state: 2 vertices (v1, v3), 0 edges (e2 was removed with v2)
        assert_eq!(graph.vertex_count(), 2);
        assert_eq!(graph.edge_count(), 0);

        // No checkpoint - simulate crash
    }

    // Recover and verify
    {
        let graph = MmapGraph::open(&db_path).expect("reopen after crash");

        assert_eq!(
            graph.vertex_count(),
            2,
            "should have 2 vertices after recovery"
        );
        assert_eq!(graph.edge_count(), 0, "should have 0 edges after recovery");

        // Verify the right vertices remain
        let people: Vec<_> = graph.vertices_with_label("person").collect();
        assert_eq!(people.len(), 2);

        let names: Vec<_> = people
            .iter()
            .filter_map(|v| v.properties.get("name").and_then(|v| v.as_str()))
            .collect();
        assert!(names.contains(&"Alice"));
        assert!(names.contains(&"Charlie"));
        assert!(!names.contains(&"Bob")); // Bob was deleted
    }

    drop(dir);
}

// =============================================================================
// Batch Mode Tests
// =============================================================================

/// Test basic batch mode workflow.
///
/// Verifies that:
/// 1. begin_batch() starts batch mode
/// 2. add_vertex/add_edge work in batch mode
/// 3. commit_batch() commits all operations
/// 4. Data is readable after commit
#[test]
fn test_batch_mode_basic() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Not in batch mode initially
    assert!(!graph.is_batch_mode());

    // Start batch mode
    graph.begin_batch().expect("begin batch");
    assert!(graph.is_batch_mode());

    // Add vertices in batch mode
    let v1 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Alice".into())]),
        )
        .expect("add v1");
    let v2 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Bob".into())]),
        )
        .expect("add v2");

    // Add edge in batch mode
    graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");

    // Data should be readable immediately (written to main file)
    assert_eq!(graph.vertex_count(), 2);
    assert_eq!(graph.edge_count(), 1);

    // Commit the batch
    graph.commit_batch().expect("commit batch");
    assert!(!graph.is_batch_mode());

    // Data still there after commit
    assert_eq!(graph.vertex_count(), 2);
    assert_eq!(graph.edge_count(), 1);
}

/// Test batch mode performance improvement.
///
/// In batch mode, we should see significantly better throughput than normal mode.
/// This test verifies that batch mode completes in reasonable time.
#[test]
fn test_batch_mode_performance() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let num_vertices = 1000;

    // Start batch mode
    graph.begin_batch().expect("begin batch");

    // Add many vertices - this should be fast in batch mode
    let start = std::time::Instant::now();
    let mut vertex_ids = Vec::with_capacity(num_vertices);
    for i in 0..num_vertices {
        let props = HashMap::from([("i".to_string(), (i as i64).into())]);
        let id = graph.add_vertex("node", props).expect("add vertex");
        vertex_ids.push(id);
    }

    // Add edges
    for i in 0..(num_vertices - 1) {
        graph
            .add_edge(vertex_ids[i], vertex_ids[i + 1], "next", HashMap::new())
            .expect("add edge");
    }

    // Commit
    graph.commit_batch().expect("commit batch");
    let elapsed = start.elapsed();

    // In batch mode, this should complete in under 15 seconds
    // (Normal mode would take ~5ms * 1999 operations = ~10 seconds just for fsync)
    // We're still doing file I/O for each operation, just skipping fsync
    assert!(elapsed.as_secs() < 15, "Batch mode too slow: {:?}", elapsed);

    // Verify data
    assert_eq!(graph.vertex_count(), num_vertices as u64);
    assert_eq!(graph.edge_count(), (num_vertices - 1) as u64);
}

/// Test that begin_batch fails if already in batch mode.
#[test]
fn test_batch_mode_double_begin_fails() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    graph.begin_batch().expect("begin batch");

    // Second begin should fail
    let result = graph.begin_batch();
    assert!(result.is_err());
}

/// Test that commit_batch fails if not in batch mode.
#[test]
fn test_commit_batch_without_begin_fails() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // commit without begin should fail
    let result = graph.commit_batch();
    assert!(result.is_err());
}

/// Test that abort_batch discards uncommitted operations.
#[test]
fn test_abort_batch() {
    let (_dir, db_path) = temp_db();

    // First session: add data in batch mode, then abort
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        graph.begin_batch().expect("begin batch");
        graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add vertex");

        // Abort the batch
        graph.abort_batch().expect("abort batch");
        assert!(!graph.is_batch_mode());

        // Data is in memory/file but transaction is aborted in WAL
        // The vertex is there for this session
        assert_eq!(graph.vertex_count(), 1);
    }

    // Second session: on reopen, recovery should discard the aborted transaction
    // Note: This depends on recovery implementation - if we checkpoint before close,
    // the data would persist. Without checkpoint, it depends on WAL recovery.
}

/// Test batch mode with checkpoint.
///
/// After commit_batch, a checkpoint should work normally.
#[test]
fn test_batch_mode_with_checkpoint() {
    let (dir, db_path) = temp_db();

    // Add data in batch mode, commit, then checkpoint
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        graph.begin_batch().expect("begin batch");

        let v1 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Alice".into())]),
            )
            .expect("add v1");
        let v2 = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), "Bob".into())]),
            )
            .expect("add v2");
        graph
            .add_edge(v1, v2, "knows", HashMap::new())
            .expect("add edge");

        graph.commit_batch().expect("commit batch");
        graph.checkpoint().expect("checkpoint");
    }

    // Reopen and verify data persisted
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        assert_eq!(graph.vertex_count(), 2);
        assert_eq!(graph.edge_count(), 1);

        let vertices: Vec<_> = graph.vertices_with_label("person").collect();
        assert_eq!(vertices.len(), 2);
    }

    drop(dir);
}

/// Test multiple batch operations.
///
/// Verifies that we can do multiple begin_batch/commit_batch cycles.
#[test]
fn test_multiple_batches() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // First batch
    graph.begin_batch().expect("begin batch 1");
    let v1 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Alice".into())]),
        )
        .expect("add v1");
    graph.commit_batch().expect("commit batch 1");

    assert_eq!(graph.vertex_count(), 1);

    // Second batch
    graph.begin_batch().expect("begin batch 2");
    let v2 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Bob".into())]),
        )
        .expect("add v2");
    graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");
    graph.commit_batch().expect("commit batch 2");

    assert_eq!(graph.vertex_count(), 2);
    assert_eq!(graph.edge_count(), 1);
}

/// Test that data is readable during batch mode.
///
/// Even before commit, data should be readable because it's written
/// to the main file (just not durably synced yet).
#[test]
fn test_batch_mode_read_during_write() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    graph.begin_batch().expect("begin batch");

    let v1 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Alice".into())]),
        )
        .expect("add v1");

    // Should be able to read the vertex immediately
    let vertex = graph.get_vertex(v1).expect("get vertex");
    assert_eq!(vertex.label, "person");
    assert_eq!(
        vertex.properties.get("name").and_then(|v| v.as_str()),
        Some("Alice")
    );

    // Add another vertex that references the first
    let v2 = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), "Bob".into())]),
        )
        .expect("add v2");

    // Add edge between them
    graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");

    // Should be able to traverse the edge
    let edges: Vec<_> = graph.out_edges(v1).collect();
    assert_eq!(edges.len(), 1);
    assert_eq!(edges[0].dst, v2);

    graph.commit_batch().expect("commit batch");
}

// =============================================================================
// Phase 5.7: Property Roundtrip Tests
// =============================================================================

use interstellar::value::{EdgeId, Value, VertexId};

/// Test that Null property values roundtrip correctly.
#[test]
fn test_property_roundtrip_null() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([("nullprop".to_string(), Value::Null)]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("nullprop"), Some(&Value::Null));
}

/// Test that Bool property values roundtrip correctly.
#[test]
fn test_property_roundtrip_bool() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("flag_true".to_string(), Value::Bool(true)),
                ("flag_false".to_string(), Value::Bool(false)),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("flag_true"), Some(&Value::Bool(true)));
    assert_eq!(
        vertex.properties.get("flag_false"),
        Some(&Value::Bool(false))
    );
}

/// Test that Int property values roundtrip correctly.
#[test]
fn test_property_roundtrip_int() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("positive".to_string(), Value::Int(42)),
                ("negative".to_string(), Value::Int(-7)),
                ("zero".to_string(), Value::Int(0)),
                ("large".to_string(), Value::Int(i64::MAX)),
                ("small".to_string(), Value::Int(i64::MIN)),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("positive"), Some(&Value::Int(42)));
    assert_eq!(vertex.properties.get("negative"), Some(&Value::Int(-7)));
    assert_eq!(vertex.properties.get("zero"), Some(&Value::Int(0)));
    assert_eq!(vertex.properties.get("large"), Some(&Value::Int(i64::MAX)));
    assert_eq!(vertex.properties.get("small"), Some(&Value::Int(i64::MIN)));
}

/// Test that Float property values roundtrip correctly.
#[test]
fn test_property_roundtrip_float() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("pi".to_string(), Value::Float(3.14159)),
                ("negative".to_string(), Value::Float(-2.5)),
                ("zero".to_string(), Value::Float(0.0)),
                ("infinity".to_string(), Value::Float(f64::INFINITY)),
                ("neg_infinity".to_string(), Value::Float(f64::NEG_INFINITY)),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("pi"), Some(&Value::Float(3.14159)));
    assert_eq!(vertex.properties.get("negative"), Some(&Value::Float(-2.5)));
    assert_eq!(vertex.properties.get("zero"), Some(&Value::Float(0.0)));
    assert_eq!(
        vertex.properties.get("infinity"),
        Some(&Value::Float(f64::INFINITY))
    );
    assert_eq!(
        vertex.properties.get("neg_infinity"),
        Some(&Value::Float(f64::NEG_INFINITY))
    );
}

/// Test that Float NaN property values roundtrip correctly.
#[test]
fn test_property_roundtrip_float_nan() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([("nan".to_string(), Value::Float(f64::NAN))]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    let nan_val = vertex.properties.get("nan").expect("nan property");
    match nan_val {
        Value::Float(f) => assert!(f.is_nan(), "Expected NaN, got {}", f),
        _ => panic!("Expected Float variant, got {:?}", nan_val),
    }
}

/// Test that String property values roundtrip correctly.
#[test]
fn test_property_roundtrip_string() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("name".to_string(), Value::String("Alice".to_string())),
                ("empty".to_string(), Value::String("".to_string())),
                (
                    "unicode".to_string(),
                    Value::String("Hello 世界 🌍".to_string()),
                ),
                (
                    "special".to_string(),
                    Value::String("line\nbreak\ttab".to_string()),
                ),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Alice".to_string()))
    );
    assert_eq!(
        vertex.properties.get("empty"),
        Some(&Value::String("".to_string()))
    );
    assert_eq!(
        vertex.properties.get("unicode"),
        Some(&Value::String("Hello 世界 🌍".to_string()))
    );
    assert_eq!(
        vertex.properties.get("special"),
        Some(&Value::String("line\nbreak\ttab".to_string()))
    );
}

/// Test that List property values roundtrip correctly.
#[test]
fn test_property_roundtrip_list() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let mixed_list = Value::List(vec![
        Value::Int(1),
        Value::String("two".to_string()),
        Value::Bool(true),
        Value::Float(4.0),
        Value::Null,
    ]);

    let nested_list = Value::List(vec![
        Value::List(vec![Value::Int(1), Value::Int(2)]),
        Value::List(vec![Value::Int(3), Value::Int(4)]),
    ]);

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("empty_list".to_string(), Value::List(vec![])),
                (
                    "int_list".to_string(),
                    Value::List(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
                ),
                ("mixed".to_string(), mixed_list.clone()),
                ("nested".to_string(), nested_list.clone()),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("empty_list"),
        Some(&Value::List(vec![]))
    );
    assert_eq!(
        vertex.properties.get("int_list"),
        Some(&Value::List(vec![
            Value::Int(1),
            Value::Int(2),
            Value::Int(3)
        ]))
    );
    assert_eq!(vertex.properties.get("mixed"), Some(&mixed_list));
    assert_eq!(vertex.properties.get("nested"), Some(&nested_list));
}

/// Test that Map property values roundtrip correctly.
#[test]
fn test_property_roundtrip_map() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let simple_map = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("x".to_string(), Value::Int(10)),
        ("y".to_string(), Value::Int(20)),
    ]));

    let nested_map = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([(
        "outer".to_string(),
        Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([(
            "inner".to_string(),
            Value::String("value".to_string()),
        )])),
    )]));

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("empty_map".to_string(), Value::Map(Default::default())),
                ("simple".to_string(), simple_map.clone()),
                ("nested".to_string(), nested_map.clone()),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("empty_map"),
        Some(&Value::Map(Default::default()))
    );
    assert_eq!(vertex.properties.get("simple"), Some(&simple_map));
    assert_eq!(vertex.properties.get("nested"), Some(&nested_map));
}

/// Test that Vertex ID property values roundtrip correctly.
#[test]
fn test_property_roundtrip_vertex_id() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex first to get a valid ID
    let ref_vertex = graph
        .add_vertex("reference", HashMap::new())
        .expect("add reference vertex");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("ref".to_string(), Value::Vertex(ref_vertex)),
                ("external".to_string(), Value::Vertex(VertexId(12345))),
                ("zero".to_string(), Value::Vertex(VertexId(0))),
                ("max".to_string(), Value::Vertex(VertexId(u64::MAX))),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("ref"),
        Some(&Value::Vertex(ref_vertex))
    );
    assert_eq!(
        vertex.properties.get("external"),
        Some(&Value::Vertex(VertexId(12345)))
    );
    assert_eq!(
        vertex.properties.get("zero"),
        Some(&Value::Vertex(VertexId(0)))
    );
    assert_eq!(
        vertex.properties.get("max"),
        Some(&Value::Vertex(VertexId(u64::MAX)))
    );
}

/// Test that Edge ID property values roundtrip correctly.
#[test]
fn test_property_roundtrip_edge_id() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices and an edge to get valid IDs
    let v1 = graph
        .add_vertex("node", HashMap::new())
        .expect("add vertex 1");
    let v2 = graph
        .add_vertex("node", HashMap::new())
        .expect("add vertex 2");
    let ref_edge = graph
        .add_edge(v1, v2, "link", HashMap::new())
        .expect("add edge");

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("ref".to_string(), Value::Edge(ref_edge)),
                ("external".to_string(), Value::Edge(EdgeId(67890))),
                ("zero".to_string(), Value::Edge(EdgeId(0))),
                ("max".to_string(), Value::Edge(EdgeId(u64::MAX))),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("ref"), Some(&Value::Edge(ref_edge)));
    assert_eq!(
        vertex.properties.get("external"),
        Some(&Value::Edge(EdgeId(67890)))
    );
    assert_eq!(vertex.properties.get("zero"), Some(&Value::Edge(EdgeId(0))));
    assert_eq!(
        vertex.properties.get("max"),
        Some(&Value::Edge(EdgeId(u64::MAX)))
    );
}

/// Test that edge properties roundtrip correctly with all Value types.
#[test]
fn test_edge_property_roundtrip() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v1 = graph.add_vertex("person", HashMap::new()).expect("add v1");
    let v2 = graph.add_vertex("person", HashMap::new()).expect("add v2");

    let nested = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("count".to_string(), Value::Int(5)),
        (
            "tags".to_string(),
            Value::List(vec![
                Value::String("friend".to_string()),
                Value::String("colleague".to_string()),
            ]),
        ),
    ]));

    let e = graph
        .add_edge(
            v1,
            v2,
            "knows",
            HashMap::from([
                ("weight".to_string(), Value::Float(0.85)),
                ("since".to_string(), Value::Int(2020)),
                ("active".to_string(), Value::Bool(true)),
                (
                    "note".to_string(),
                    Value::String("Met at conference".to_string()),
                ),
                ("metadata".to_string(), nested.clone()),
            ]),
        )
        .expect("add edge");

    graph.checkpoint().expect("checkpoint");

    let edge = graph.get_edge(e).expect("get edge");
    assert_eq!(edge.properties.get("weight"), Some(&Value::Float(0.85)));
    assert_eq!(edge.properties.get("since"), Some(&Value::Int(2020)));
    assert_eq!(edge.properties.get("active"), Some(&Value::Bool(true)));
    assert_eq!(
        edge.properties.get("note"),
        Some(&Value::String("Met at conference".to_string()))
    );
    assert_eq!(edge.properties.get("metadata"), Some(&nested));
}

/// Test that multi-property vertices roundtrip correctly.
#[test]
fn test_multi_property_vertex() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex with many properties of different types
    let mut props = HashMap::new();
    props.insert("name".to_string(), Value::String("Test Entity".to_string()));
    props.insert("count".to_string(), Value::Int(42));
    props.insert("ratio".to_string(), Value::Float(0.75));
    props.insert("enabled".to_string(), Value::Bool(true));
    props.insert("disabled".to_string(), Value::Bool(false));
    props.insert("empty".to_string(), Value::Null);
    props.insert(
        "tags".to_string(),
        Value::List(vec![
            Value::String("a".to_string()),
            Value::String("b".to_string()),
        ]),
    );
    props.insert(
        "config".to_string(),
        Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
            ("key1".to_string(), Value::Int(1)),
            ("key2".to_string(), Value::Int(2)),
        ])),
    );
    props.insert("vertex_ref".to_string(), Value::Vertex(VertexId(100)));
    props.insert("edge_ref".to_string(), Value::Edge(EdgeId(200)));

    let v = graph
        .add_vertex("entity", props.clone())
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.label, "entity");
    assert_eq!(vertex.properties.len(), props.len());

    for (key, expected_value) in &props {
        let actual_value = vertex.properties.get(key);
        assert_eq!(
            actual_value,
            Some(expected_value),
            "Property '{}' mismatch",
            key
        );
    }
}

/// Test that empty properties roundtrip correctly.
#[test]
fn test_empty_properties() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex("empty", HashMap::new())
        .expect("add vertex");

    let v1 = graph.add_vertex("node", HashMap::new()).expect("add v1");
    let v2 = graph.add_vertex("node", HashMap::new()).expect("add v2");
    let e = graph
        .add_edge(v1, v2, "link", HashMap::new())
        .expect("add edge");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert!(vertex.properties.is_empty());

    let edge = graph.get_edge(e).expect("get edge");
    assert!(edge.properties.is_empty());
}

/// Test that large strings (> 256 bytes) roundtrip correctly.
#[test]
fn test_large_string_property() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create strings of various sizes
    let small = "a".repeat(100);
    let medium = "b".repeat(500);
    let large = "c".repeat(1000);
    let very_large = "d".repeat(10_000);

    let v = graph
        .add_vertex(
            "test",
            HashMap::from([
                ("small".to_string(), Value::String(small.clone())),
                ("medium".to_string(), Value::String(medium.clone())),
                ("large".to_string(), Value::String(large.clone())),
                ("very_large".to_string(), Value::String(very_large.clone())),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("small"), Some(&Value::String(small)));
    assert_eq!(
        vertex.properties.get("medium"),
        Some(&Value::String(medium))
    );
    assert_eq!(vertex.properties.get("large"), Some(&Value::String(large)));
    assert_eq!(
        vertex.properties.get("very_large"),
        Some(&Value::String(very_large))
    );
}

/// Test property roundtrip across database close and reopen.
#[test]
fn test_property_persistence_across_reopen() {
    let (dir, db_path) = temp_db();

    let (vertex_id, edge_id) = {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        let v = graph
            .add_vertex(
                "entity",
                HashMap::from([
                    ("name".to_string(), Value::String("Persistent".to_string())),
                    ("count".to_string(), Value::Int(999)),
                    ("ratio".to_string(), Value::Float(1.5)),
                    ("active".to_string(), Value::Bool(true)),
                    (
                        "list".to_string(),
                        Value::List(vec![Value::Int(1), Value::Int(2)]),
                    ),
                    (
                        "map".to_string(),
                        Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([(
                            "nested".to_string(),
                            Value::Null,
                        )])),
                    ),
                ]),
            )
            .expect("add vertex");

        let v2 = graph.add_vertex("other", HashMap::new()).expect("add v2");

        let e = graph
            .add_edge(
                v,
                v2,
                "relates",
                HashMap::from([
                    ("strength".to_string(), Value::Float(0.9)),
                    ("label".to_string(), Value::String("strong".to_string())),
                ]),
            )
            .expect("add edge");

        graph.checkpoint().expect("checkpoint");

        (v, e)
    };

    // Reopen and verify
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        let vertex = graph.get_vertex(vertex_id).expect("get vertex");
        assert_eq!(
            vertex.properties.get("name"),
            Some(&Value::String("Persistent".to_string()))
        );
        assert_eq!(vertex.properties.get("count"), Some(&Value::Int(999)));
        assert_eq!(vertex.properties.get("ratio"), Some(&Value::Float(1.5)));
        assert_eq!(vertex.properties.get("active"), Some(&Value::Bool(true)));
        assert_eq!(
            vertex.properties.get("list"),
            Some(&Value::List(vec![Value::Int(1), Value::Int(2)]))
        );
        assert_eq!(
            vertex.properties.get("map"),
            Some(&Value::Map(
                ::indexmap::IndexMap::<String, Value>::from_iter([(
                    "nested".to_string(),
                    Value::Null
                )])
            ))
        );

        let edge = graph.get_edge(edge_id).expect("get edge");
        assert_eq!(edge.properties.get("strength"), Some(&Value::Float(0.9)));
        assert_eq!(
            edge.properties.get("label"),
            Some(&Value::String("strong".to_string()))
        );
    }

    drop(dir);
}

/// Test deeply nested property structures roundtrip correctly.
#[test]
fn test_deeply_nested_properties() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a deeply nested structure
    let level3 = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("leaf".to_string(), Value::String("deep".to_string())),
        ("number".to_string(), Value::Int(42)),
    ]));

    let level2 = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("nested".to_string(), level3.clone()),
        (
            "list".to_string(),
            Value::List(vec![Value::Int(1), Value::Int(2)]),
        ),
    ]));

    let level1 = Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([
        ("data".to_string(), level2.clone()),
        ("name".to_string(), Value::String("level1".to_string())),
    ]));

    let nested_list = Value::List(vec![
        Value::List(vec![
            Value::List(vec![Value::Int(1), Value::Int(2)]),
            Value::List(vec![Value::Int(3), Value::Int(4)]),
        ]),
        Value::List(vec![Value::List(vec![Value::Int(5), Value::Int(6)])]),
    ]);

    let v = graph
        .add_vertex(
            "nested",
            HashMap::from([
                ("deep_map".to_string(), level1.clone()),
                ("deep_list".to_string(), nested_list.clone()),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(vertex.properties.get("deep_map"), Some(&level1));
    assert_eq!(vertex.properties.get("deep_list"), Some(&nested_list));
}

/// Test all Value types in a single vertex property map.
#[test]
fn test_all_value_types_combined() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex(
            "comprehensive",
            HashMap::from([
                ("null".to_string(), Value::Null),
                ("bool_true".to_string(), Value::Bool(true)),
                ("bool_false".to_string(), Value::Bool(false)),
                ("int_pos".to_string(), Value::Int(123)),
                ("int_neg".to_string(), Value::Int(-456)),
                ("float_pos".to_string(), Value::Float(3.14)),
                ("float_neg".to_string(), Value::Float(-2.71)),
                ("string".to_string(), Value::String("hello".to_string())),
                (
                    "list".to_string(),
                    Value::List(vec![Value::Int(1), Value::String("a".to_string())]),
                ),
                (
                    "map".to_string(),
                    Value::Map(::indexmap::IndexMap::<String, Value>::from_iter([(
                        "k".to_string(),
                        Value::Bool(true),
                    )])),
                ),
                ("vertex".to_string(), Value::Vertex(VertexId(111))),
                ("edge".to_string(), Value::Edge(EdgeId(222))),
            ]),
        )
        .expect("add vertex");

    graph.checkpoint().expect("checkpoint");

    let vertex = graph.get_vertex(v).expect("get vertex");

    assert_eq!(vertex.properties.get("null"), Some(&Value::Null));
    assert_eq!(vertex.properties.get("bool_true"), Some(&Value::Bool(true)));
    assert_eq!(
        vertex.properties.get("bool_false"),
        Some(&Value::Bool(false))
    );
    assert_eq!(vertex.properties.get("int_pos"), Some(&Value::Int(123)));
    assert_eq!(vertex.properties.get("int_neg"), Some(&Value::Int(-456)));
    assert_eq!(
        vertex.properties.get("float_pos"),
        Some(&Value::Float(3.14))
    );
    assert_eq!(
        vertex.properties.get("float_neg"),
        Some(&Value::Float(-2.71))
    );
    assert_eq!(
        vertex.properties.get("string"),
        Some(&Value::String("hello".to_string()))
    );
    assert_eq!(
        vertex.properties.get("list"),
        Some(&Value::List(vec![
            Value::Int(1),
            Value::String("a".to_string())
        ]))
    );
    assert_eq!(
        vertex.properties.get("map"),
        Some(&Value::Map(
            ::indexmap::IndexMap::<String, Value>::from_iter([(
                "k".to_string(),
                Value::Bool(true)
            )])
        ))
    );
    assert_eq!(
        vertex.properties.get("vertex"),
        Some(&Value::Vertex(VertexId(111)))
    );
    assert_eq!(
        vertex.properties.get("edge"),
        Some(&Value::Edge(EdgeId(222)))
    );
}

// =============================================================================
// Phase 5.8: Error Handling Tests
// =============================================================================

use interstellar::error::StorageError;

/// Test that opening a file with invalid magic number returns InvalidFormat error.
///
/// This test creates a file with a wrong magic number (0xDEADBEEF) and verifies
/// that MmapGraph::open() returns StorageError::InvalidFormat.
#[test]
fn test_error_corrupted_file_bad_magic() {
    let (_dir, db_path) = temp_db();

    // Create a file with invalid magic number
    // The header format is: magic (4 bytes) | version (4 bytes) | ...
    // We write a wrong magic but correct version to test magic validation
    {
        use std::io::Write;
        let mut file = std::fs::File::create(&db_path).expect("create file");

        // Write invalid magic (0xDEADBEEF instead of 0x47524D4C "GRML")
        let bad_magic: u32 = 0xDEADBEEF;
        file.write_all(&bad_magic.to_ne_bytes())
            .expect("write magic");

        // Write correct version
        let version: u32 = 1;
        file.write_all(&version.to_ne_bytes())
            .expect("write version");

        // Pad to at least HEADER_SIZE (104 bytes) so it passes size check
        let padding = vec![0u8; 104 - 8];
        file.write_all(&padding).expect("write padding");
    }

    // Try to open - should fail with InvalidFormat
    let result = MmapGraph::open(&db_path);
    assert!(result.is_err(), "Expected error for bad magic");
    match result {
        Err(StorageError::InvalidFormat) => {} // Expected
        Err(e) => panic!("Expected InvalidFormat, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that opening a file with unsupported version returns VersionMismatch error.
///
/// This test creates a file with correct magic but wrong version (999) and verifies
/// that MmapGraph::open() returns StorageError::VersionMismatch.
#[test]
fn test_error_corrupted_file_bad_version() {
    let (_dir, db_path) = temp_db();

    // Create a file with correct magic but invalid version
    {
        use std::io::Write;
        let mut file = std::fs::File::create(&db_path).expect("create file");

        // Write correct magic (0x47524D4C "GRML")
        let magic: u32 = 0x47524D4C;
        file.write_all(&magic.to_ne_bytes()).expect("write magic");

        // Write invalid version (999 instead of 1 or 2)
        let bad_version: u32 = 999;
        file.write_all(&bad_version.to_ne_bytes())
            .expect("write version");

        // Pad to at least HEADER_SIZE (192 bytes for V2) so it passes size check
        let padding = vec![0u8; 192 - 8];
        file.write_all(&padding).expect("write padding");
    }

    // Try to open - should fail with VersionMismatch
    let result = MmapGraph::open(&db_path);
    assert!(result.is_err(), "Expected error for bad version");
    match result {
        Err(StorageError::VersionMismatch {
            file_version: 999,
            min_supported: 1,
            max_supported: 2,
        }) => {} // Expected
        Err(e) => panic!("Expected VersionMismatch, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that adding an edge with non-existent source vertex returns VertexNotFound.
#[test]
fn test_error_add_edge_nonexistent_source() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add one valid vertex
    let valid_vertex = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");

    // Try to add edge with non-existent source
    let result = graph.add_edge(VertexId(999), valid_vertex, "knows", HashMap::new());

    assert!(result.is_err(), "Expected error for non-existent source");
    match result {
        Err(StorageError::VertexNotFound(id)) => {
            assert_eq!(id, VertexId(999), "Expected VertexId(999)");
        }
        Err(e) => panic!("Expected VertexNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that adding an edge with non-existent destination vertex returns VertexNotFound.
#[test]
fn test_error_add_edge_nonexistent_destination() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add one valid vertex
    let valid_vertex = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");

    // Try to add edge with non-existent destination
    let result = graph.add_edge(valid_vertex, VertexId(999), "knows", HashMap::new());

    assert!(
        result.is_err(),
        "Expected error for non-existent destination"
    );
    match result {
        Err(StorageError::VertexNotFound(id)) => {
            assert_eq!(id, VertexId(999), "Expected VertexId(999)");
        }
        Err(e) => panic!("Expected VertexNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that get_vertex and get_edge with invalid IDs return None without panicking.
///
/// This test verifies that the storage gracefully handles lookups for non-existent
/// elements by returning None rather than panicking.
#[test]
fn test_error_operations_no_panic() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Add some data so the graph isn't empty
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let e1 = graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");

    // Test get_vertex with non-existent IDs - should return None, not panic
    assert!(graph.get_vertex(VertexId(999)).is_none());
    assert!(graph.get_vertex(VertexId(u64::MAX)).is_none());
    // Note: VertexId(0) is the first valid ID, so it exists (v1)

    // Test get_edge with non-existent IDs - should return None, not panic
    assert!(graph.get_edge(EdgeId(999)).is_none());
    assert!(graph.get_edge(EdgeId(u64::MAX)).is_none());
    // Note: EdgeId(0) is the first valid ID, so it exists (e1)

    // Verify valid IDs still work
    assert!(graph.get_vertex(v1).is_some());
    assert!(graph.get_vertex(v2).is_some());
    assert!(graph.get_edge(e1).is_some());

    // Test out_edges/in_edges with non-existent vertex - should return empty iterator
    assert_eq!(graph.out_edges(VertexId(999)).count(), 0);
    assert_eq!(graph.in_edges(VertexId(999)).count(), 0);
}

/// Test that opening a file that is too small returns InvalidFormat error.
///
/// The header requires 104 bytes minimum. A smaller file should be rejected.
#[test]
fn test_error_file_too_small() {
    let (_dir, db_path) = temp_db();

    // Create a file smaller than HEADER_SIZE (104 bytes)
    {
        use std::io::Write;
        let mut file = std::fs::File::create(&db_path).expect("create file");
        // Write only 50 bytes - less than header size
        let data = vec![0u8; 50];
        file.write_all(&data).expect("write data");
    }

    // Try to open - should fail with InvalidFormat
    let result = MmapGraph::open(&db_path);
    assert!(result.is_err(), "Expected error for small file");
    match result {
        Err(StorageError::InvalidFormat) => {} // Expected
        Err(e) => panic!("Expected InvalidFormat, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that remove_vertex on non-existent vertex returns appropriate error.
#[test]
fn test_error_remove_nonexistent_vertex() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Try to remove a vertex that doesn't exist
    let result = graph.remove_vertex(VertexId(999));

    assert!(result.is_err(), "Expected error for non-existent vertex");
    match result {
        Err(StorageError::VertexNotFound(id)) => {
            assert_eq!(id, VertexId(999));
        }
        Err(e) => panic!("Expected VertexNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

/// Test that remove_edge on non-existent edge returns appropriate error.
#[test]
fn test_error_remove_nonexistent_edge() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Try to remove an edge that doesn't exist
    let result = graph.remove_edge(EdgeId(999));

    assert!(result.is_err(), "Expected error for non-existent edge");
    match result {
        Err(StorageError::EdgeNotFound(id)) => {
            assert_eq!(id, EdgeId(999));
        }
        Err(e) => panic!("Expected EdgeNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error, got success"),
    }
}

// =============================================================================
// Phase 10: Mutation Tests for MmapGraph
// =============================================================================

use interstellar::traversal::{MutationExecutor, PendingMutation};

/// Test that set_vertex_property adds a new property to an existing vertex.
#[test]
fn test_set_vertex_property_adds_new_property() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex with initial properties
    let v = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), Value::String("Alice".to_string()))]),
        )
        .expect("add vertex");

    // Add a new property
    graph
        .set_vertex_property(v, "age", Value::Int(30))
        .expect("set property");

    // Verify both properties exist
    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Alice".to_string()))
    );
    assert_eq!(vertex.properties.get("age"), Some(&Value::Int(30)));
}

/// Test that set_vertex_property updates an existing property.
#[test]
fn test_set_vertex_property_updates_existing() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex with initial properties
    let v = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), Value::String("Alice".to_string()))]),
        )
        .expect("add vertex");

    // Update the existing property
    graph
        .set_vertex_property(v, "name", Value::String("Bob".to_string()))
        .expect("set property");

    // Verify property was updated
    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Bob".to_string()))
    );
}

/// Test that set_edge_property adds a new property to an existing edge.
#[test]
fn test_set_edge_property_adds_new_property() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices and edge
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let e = graph
        .add_edge(
            v1,
            v2,
            "knows",
            HashMap::from([("since".to_string(), Value::Int(2020))]),
        )
        .expect("add edge");

    // Add a new property
    graph
        .set_edge_property(e, "weight", Value::Float(0.8))
        .expect("set property");

    // Verify both properties exist
    let edge = graph.get_edge(e).expect("get edge");
    assert_eq!(edge.properties.get("since"), Some(&Value::Int(2020)));
    assert_eq!(edge.properties.get("weight"), Some(&Value::Float(0.8)));
}

/// Test that set_edge_property updates an existing property.
#[test]
fn test_set_edge_property_updates_existing() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices and edge
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let e = graph
        .add_edge(
            v1,
            v2,
            "knows",
            HashMap::from([("since".to_string(), Value::Int(2020))]),
        )
        .expect("add edge");

    // Update the existing property
    graph
        .set_edge_property(e, "since", Value::Int(2021))
        .expect("set property");

    // Verify property was updated
    let edge = graph.get_edge(e).expect("get edge");
    assert_eq!(edge.properties.get("since"), Some(&Value::Int(2021)));
}

/// Test that property updates persist across checkpoint and reopen.
#[test]
fn test_property_updates_persist_across_reopen() {
    let (_dir, db_path) = temp_db();

    let (v, e) = {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        // Create vertex and edge
        let v = graph
            .add_vertex(
                "person",
                HashMap::from([("name".to_string(), Value::String("Alice".to_string()))]),
            )
            .expect("add vertex");
        let v2 = graph
            .add_vertex("person", HashMap::new())
            .expect("add vertex");
        let e = graph
            .add_edge(v, v2, "knows", HashMap::new())
            .expect("add edge");

        // Update properties
        graph
            .set_vertex_property(v, "age", Value::Int(30))
            .expect("set vertex property");
        graph
            .set_edge_property(e, "weight", Value::Float(0.5))
            .expect("set edge property");

        graph.checkpoint().expect("checkpoint");
        (v, e)
    };

    // Reopen and verify
    let graph = MmapGraph::open(&db_path).expect("reopen graph");

    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Alice".to_string()))
    );
    assert_eq!(vertex.properties.get("age"), Some(&Value::Int(30)));

    let edge = graph.get_edge(e).expect("get edge");
    assert_eq!(edge.properties.get("weight"), Some(&Value::Float(0.5)));
}

/// Test that MmapGraph implements GraphStorageMut and works with MutationExecutor.
#[test]
fn test_mmap_graph_storage_mut_trait() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // Create pending add_v mutation
    let add_v = PendingMutation::AddVertex {
        label: "person".to_string(),
        properties: HashMap::from([
            ("name".to_string(), Value::String("Charlie".to_string())),
            ("age".to_string(), Value::Int(35)),
        ]),
    };

    // Execute mutation using MutationExecutor with MmapGraph
    let mut executor = MutationExecutor::new(&mut graph);
    let result = executor.execute_mutation(add_v);

    // Verify vertex was created
    assert!(result.is_some());
    if let Some(Value::Vertex(id)) = result {
        let vertex = graph.get_vertex(id).expect("Vertex should exist");
        assert_eq!(vertex.label, "person");
        assert_eq!(
            vertex.properties.get("name"),
            Some(&Value::String("Charlie".to_string()))
        );
        assert_eq!(vertex.properties.get("age"), Some(&Value::Int(35)));
    } else {
        panic!("Expected Value::Vertex");
    }
}

/// Test that MutationExecutor can add edges with MmapGraph.
#[test]
fn test_mmap_mutation_executor_adds_edge() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // First create vertices
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");

    // Create pending add_e mutation
    let add_e = PendingMutation::AddEdge {
        label: "knows".to_string(),
        from: v1,
        to: v2,
        properties: HashMap::from([("since".to_string(), Value::Int(2024))]),
    };

    // Execute mutation
    let mut executor = MutationExecutor::new(&mut graph);
    let result = executor.execute_mutation(add_e);

    // Verify edge was created
    assert!(result.is_some());
    if let Some(Value::Edge(id)) = result {
        let edge = graph.get_edge(id).expect("Edge should exist");
        assert_eq!(edge.label, "knows");
        assert_eq!(edge.src, v1);
        assert_eq!(edge.dst, v2);
        assert_eq!(edge.properties.get("since"), Some(&Value::Int(2024)));
    } else {
        panic!("Expected Value::Edge");
    }
}

/// Test that MutationExecutor can update vertex properties with MmapGraph.
#[test]
fn test_mmap_mutation_executor_sets_vertex_property() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex
    let v = graph
        .add_vertex(
            "person",
            HashMap::from([("name".to_string(), Value::String("Alice".to_string()))]),
        )
        .expect("add vertex");

    // Create pending property mutation
    let set_prop = PendingMutation::SetVertexProperty {
        id: v,
        key: "email".to_string(),
        value: Value::String("alice@example.com".to_string()),
    };

    // Execute mutation
    let mut executor = MutationExecutor::new(&mut graph);
    executor.execute_mutation(set_prop);

    // Verify property was set
    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("email"),
        Some(&Value::String("alice@example.com".to_string()))
    );
}

/// Test that MutationExecutor can update edge properties with MmapGraph.
#[test]
fn test_mmap_mutation_executor_sets_edge_property() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices and edge
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let e = graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");

    // Create pending property mutation
    let set_prop = PendingMutation::SetEdgeProperty {
        id: e,
        key: "strength".to_string(),
        value: Value::Float(0.9),
    };

    // Execute mutation
    let mut executor = MutationExecutor::new(&mut graph);
    executor.execute_mutation(set_prop);

    // Verify property was set
    let edge = graph.get_edge(e).expect("get edge");
    assert_eq!(edge.properties.get("strength"), Some(&Value::Float(0.9)));
}

/// Test that MutationExecutor can remove vertices with MmapGraph.
#[test]
fn test_mmap_mutation_executor_removes_vertex() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // Create a vertex
    let v = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    assert!(graph.get_vertex(v).is_some());

    // Create pending drop mutation
    let drop_v = PendingMutation::DropVertex { id: v };

    // Execute mutation
    let mut executor = MutationExecutor::new(&mut graph);
    executor.execute_mutation(drop_v);

    // Verify vertex was removed
    assert!(graph.get_vertex(v).is_none());
}

/// Test that MutationExecutor can remove edges with MmapGraph.
#[test]
fn test_mmap_mutation_executor_removes_edge() {
    let (_dir, db_path) = temp_db();
    let mut graph = MmapGraph::open(&db_path).expect("open graph");

    // Create vertices and edge
    let v1 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let v2 = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");
    let e = graph
        .add_edge(v1, v2, "knows", HashMap::new())
        .expect("add edge");
    assert!(graph.get_edge(e).is_some());

    // Create pending drop mutation
    let drop_e = PendingMutation::DropEdge { id: e };

    // Execute mutation
    let mut executor = MutationExecutor::new(&mut graph);
    executor.execute_mutation(drop_e);

    // Verify edge was removed
    assert!(graph.get_edge(e).is_none());
}

/// Test set_vertex_property on non-existent vertex returns error.
#[test]
fn test_set_vertex_property_nonexistent_vertex() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Try to set property on non-existent vertex
    let result = graph.set_vertex_property(VertexId(999), "key", Value::Int(1));

    assert!(result.is_err());
    match result {
        Err(StorageError::VertexNotFound(id)) => {
            assert_eq!(id, VertexId(999));
        }
        Err(e) => panic!("Expected VertexNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error"),
    }
}

/// Test set_edge_property on non-existent edge returns error.
#[test]
fn test_set_edge_property_nonexistent_edge() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Try to set property on non-existent edge
    let result = graph.set_edge_property(EdgeId(999), "key", Value::Int(1));

    assert!(result.is_err());
    match result {
        Err(StorageError::EdgeNotFound(id)) => {
            assert_eq!(id, EdgeId(999));
        }
        Err(e) => panic!("Expected EdgeNotFound, got {:?}", e),
        Ok(_) => panic!("Expected error"),
    }
}

/// Test multiple property updates on same vertex.
#[test]
fn test_multiple_property_updates_same_vertex() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let v = graph
        .add_vertex("person", HashMap::new())
        .expect("add vertex");

    // Add multiple properties
    graph
        .set_vertex_property(v, "name", Value::String("Alice".to_string()))
        .expect("set name");
    graph
        .set_vertex_property(v, "age", Value::Int(30))
        .expect("set age");
    graph
        .set_vertex_property(v, "active", Value::Bool(true))
        .expect("set active");

    // Update one of them
    graph
        .set_vertex_property(v, "age", Value::Int(31))
        .expect("update age");

    // Verify all properties
    let vertex = graph.get_vertex(v).expect("get vertex");
    assert_eq!(
        vertex.properties.get("name"),
        Some(&Value::String("Alice".to_string()))
    );
    assert_eq!(vertex.properties.get("age"), Some(&Value::Int(31)));
    assert_eq!(vertex.properties.get("active"), Some(&Value::Bool(true)));
}

// =============================================================================
// Query Storage Tests
// =============================================================================

use interstellar::query::QueryType;

/// Test saving and retrieving a Gremlin query.
#[test]
fn test_save_and_get_gremlin_query() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Save a query - returns query ID
    let query_id = graph
        .save_query(
            "find_person",
            QueryType::Gremlin,
            "Find person by name",
            "g.V().hasLabel('person').has('name', $name)",
        )
        .expect("save query");

    assert!(query_id > 0);

    // Retrieve by name
    let retrieved = graph.get_query("find_person").expect("query should exist");
    assert_eq!(retrieved.name, "find_person");
    assert_eq!(
        retrieved.query,
        "g.V().hasLabel('person').has('name', $name)"
    );
    assert_eq!(retrieved.query_type, QueryType::Gremlin);
    assert_eq!(retrieved.id, query_id);
    assert!(
        !retrieved.parameters.is_empty(),
        "should extract $name parameter"
    );

    // Retrieve by ID
    let by_id = graph
        .get_query_by_id(query_id)
        .expect("query by id should exist");
    assert_eq!(by_id.name, "find_person");
}

/// Test saving and retrieving a GQL query.
#[test]
fn test_save_and_get_gql_query() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let query_id = graph
        .save_query(
            "match_nodes",
            QueryType::Gql,
            "Find people older than min_age",
            "MATCH (n:Person) WHERE n.age > $min_age RETURN n",
        )
        .expect("save query");

    let retrieved = graph.get_query("match_nodes").expect("query should exist");
    assert_eq!(retrieved.name, "match_nodes");
    assert_eq!(retrieved.query_type, QueryType::Gql);
    assert_eq!(retrieved.description, "Find people older than min_age");
    assert_eq!(retrieved.id, query_id);
}

/// Test listing all saved queries.
#[test]
fn test_list_queries() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Initially no queries
    let queries = graph.list_queries();
    assert!(queries.is_empty());

    // Add some queries
    graph
        .save_query("query1", QueryType::Gremlin, "", "g.V()")
        .expect("save query1");
    graph
        .save_query("query2", QueryType::Gremlin, "", "g.E()")
        .expect("save query2");
    graph
        .save_query("query3", QueryType::Gql, "", "MATCH (n) RETURN n")
        .expect("save query3");

    let queries = graph.list_queries();
    assert_eq!(queries.len(), 3);

    let names: Vec<_> = queries.iter().map(|q| q.name.as_str()).collect();
    assert!(names.contains(&"query1"));
    assert!(names.contains(&"query2"));
    assert!(names.contains(&"query3"));
}

/// Test deleting a query.
#[test]
fn test_delete_query() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let query_id = graph
        .save_query("to_delete", QueryType::Gremlin, "", "g.V()")
        .expect("save query");

    // Query exists
    assert!(graph.get_query("to_delete").is_some());

    // Delete it
    graph.delete_query("to_delete").expect("delete query");

    // Query no longer exists
    assert!(graph.get_query("to_delete").is_none());

    // Get by ID should also return None now
    assert!(graph.get_query_by_id(query_id).is_none());

    // List should be empty
    let queries = graph.list_queries();
    assert!(queries.is_empty());
}

/// Test that duplicate query names are rejected.
#[test]
fn test_duplicate_query_name_rejected() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    graph
        .save_query("my_query", QueryType::Gremlin, "", "g.V()")
        .expect("save first query");

    // Try to save with same name
    let result = graph.save_query("my_query", QueryType::Gremlin, "", "g.E()");
    assert!(result.is_err(), "should reject duplicate name");
}

/// Test query name validation.
#[test]
fn test_query_name_validation() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Empty name should fail
    let result = graph.save_query("", QueryType::Gremlin, "", "g.V()");
    assert!(result.is_err(), "empty name should be rejected");

    // Name with spaces should fail
    let result = graph.save_query("my query", QueryType::Gremlin, "", "g.V()");
    assert!(result.is_err(), "name with spaces should be rejected");

    // Valid names should work
    graph
        .save_query("valid_name", QueryType::Gremlin, "", "g.V()")
        .expect("underscore name");
    graph
        .save_query("valid-name-2", QueryType::Gremlin, "", "g.V()")
        .expect("hyphen name");
    graph
        .save_query("CamelCase", QueryType::Gremlin, "", "g.V()")
        .expect("camel case name");
}

/// Test query persistence across reopens.
#[test]
fn test_query_persistence() {
    let (dir, db_path) = temp_db();

    // First session: save queries
    {
        let graph = MmapGraph::open(&db_path).expect("open graph");

        graph
            .save_query(
                "persistent_query",
                QueryType::Gremlin,
                "A persistent query",
                "g.V().count()",
            )
            .expect("save query");

        graph.checkpoint().expect("checkpoint");
    }

    // Second session: verify queries persisted
    {
        let graph = MmapGraph::open(&db_path).expect("reopen graph");

        let query = graph
            .get_query("persistent_query")
            .expect("query should exist");
        assert_eq!(query.name, "persistent_query");
        assert_eq!(query.query, "g.V().count()");
        assert_eq!(query.query_type, QueryType::Gremlin);
    }

    drop(dir);
}

/// Test parameter extraction from query text.
#[test]
fn test_query_parameter_extraction() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Query with multiple parameters
    graph
        .save_query(
            "parameterized",
            QueryType::Gremlin,
            "",
            "g.V().has('name', $name).has('age', $age).has('active', $is_active)",
        )
        .expect("save query");

    let query = graph
        .get_query("parameterized")
        .expect("query should exist");
    assert_eq!(query.parameters.len(), 3);

    let param_names: Vec<_> = query.parameters.iter().map(|p| p.name.as_str()).collect();
    assert!(param_names.contains(&"name"));
    assert!(param_names.contains(&"age"));
    assert!(param_names.contains(&"is_active"));
}

/// Test saving query with unicode characters.
#[test]
fn test_query_with_unicode() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    graph
        .save_query(
            "unicode_query",
            QueryType::Gremlin,
            "Query with Japanese text 日本語",
            "g.V().has('name', '日本語')",
        )
        .expect("save query");

    let retrieved = graph
        .get_query("unicode_query")
        .expect("query should exist");
    assert_eq!(retrieved.query, "g.V().has('name', '日本語')");
    assert_eq!(retrieved.description, "Query with Japanese text 日本語");
}

/// Test getting a non-existent query.
#[test]
fn test_get_nonexistent_query() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    assert!(graph.get_query("does_not_exist").is_none());
    assert!(graph.get_query_by_id(99999).is_none());
}

/// Test deleting a non-existent query.
#[test]
fn test_delete_nonexistent_query() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    let result = graph.delete_query("does_not_exist");
    assert!(result.is_err());
}

/// Test saving many queries.
#[test]
fn test_save_many_queries() {
    let (_dir, db_path) = temp_db();
    let graph = MmapGraph::open(&db_path).expect("open graph");

    // Save 100 queries
    for i in 0..100 {
        graph
            .save_query(
                &format!("query_{}", i),
                QueryType::Gremlin,
                "",
                &format!("g.V().has('index', {})", i),
            )
            .expect(&format!("save query {}", i));
    }

    // Verify all are listed
    let queries = graph.list_queries();
    assert_eq!(queries.len(), 100);

    // Verify random access works
    let q42 = graph.get_query("query_42").expect("query_42 should exist");
    assert_eq!(q42.query, "g.V().has('index', 42)");

    let q99 = graph.get_query("query_99").expect("query_99 should exist");
    assert_eq!(q99.query, "g.V().has('index', 99)");
}