contextdb-engine 0.3.4

Embedded database engine for agentic memory — relational, graph, and vector under unified MVCC transactions
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
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
use contextdb_core::Lsn;
use contextdb_core::{MemoryAccountant, Value};
use contextdb_engine::Database;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Barrier};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::TempDir;
use uuid::Uuid;

fn params(pairs: Vec<(&str, Value)>) -> HashMap<String, Value> {
    pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
}

fn empty() -> HashMap<String, Value> {
    HashMap::new()
}

fn disk_limit_kib_for_path(path: &std::path::Path, extra_kib: u64) -> u64 {
    let bytes = std::fs::metadata(path).expect("metadata").len();
    bytes.div_ceil(1024) + extra_kib
}

// ============================================================
// Group 1: Comparison Operators
// ============================================================

#[test]
fn cmp_01_less_than_integer() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, score INTEGER)",
        &empty(),
    )
    .unwrap();
    let ids: Vec<Uuid> = (0..3).map(|_| Uuid::new_v4()).collect();
    for (id, score) in ids.iter().zip(&[10i64, 20, 30]) {
        db.execute(
            "INSERT INTO items (id, score) VALUES ($id, $score)",
            &params(vec![
                ("id", Value::Uuid(*id)),
                ("score", Value::Int64(*score)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM items WHERE score < 20", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1, "expected 1 row with score < 20");
    let score_idx = result.columns.iter().position(|c| c == "score").unwrap();
    assert_eq!(result.rows[0][score_idx], Value::Int64(10));
}

#[test]
fn cmp_02_gte_float() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE readings (id UUID PRIMARY KEY, value REAL)",
        &empty(),
    )
    .unwrap();
    for val in &[1.5f64, 2.5, 3.5] {
        db.execute(
            "INSERT INTO readings (id, value) VALUES ($id, $value)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("value", Value::Float64(*val)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM readings WHERE value >= 2.5", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2, "expected 2 rows with value >= 2.5");
    let val_idx = result.columns.iter().position(|c| c == "value").unwrap();
    let values: Vec<&Value> = result.rows.iter().map(|r| &r[val_idx]).collect();
    assert!(values.contains(&&Value::Float64(2.5)));
    assert!(values.contains(&&Value::Float64(3.5)));
}

#[test]
fn cmp_03_gt_text_lexicographic() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE words (id UUID PRIMARY KEY, word TEXT)",
        &empty(),
    )
    .unwrap();
    for w in &["apple", "banana", "cherry"] {
        db.execute(
            "INSERT INTO words (id, word) VALUES ($id, $word)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("word", Value::Text(w.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM words WHERE word > 'banana'", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let word_idx = result.columns.iter().position(|c| c == "word").unwrap();
    assert_eq!(result.rows[0][word_idx], Value::Text("cherry".to_string()));
}

#[test]
fn cmp_04_cross_type_int_vs_float() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE mixed (id UUID PRIMARY KEY, val INTEGER)",
        &empty(),
    )
    .unwrap();
    for v in &[2i64, 3, 4] {
        db.execute(
            "INSERT INTO mixed (id, val) VALUES ($id, $val)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("val", Value::Int64(*v)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM mixed WHERE val > 2.5", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2, "expected val=3 and val=4");
    let val_idx = result.columns.iter().position(|c| c == "val").unwrap();
    let values: Vec<&Value> = result.rows.iter().map(|r| &r[val_idx]).collect();
    assert!(values.contains(&&Value::Int64(3)));
    assert!(values.contains(&&Value::Int64(4)));
}

#[test]
fn cmp_05_timestamp_vs_int() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE events (id UUID PRIMARY KEY, ts TIMESTAMP)",
        &empty(),
    )
    .unwrap();
    for ts in &[1000i64, 2000, 3000] {
        db.execute(
            "INSERT INTO events (id, ts) VALUES ($id, $ts)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("ts", Value::Timestamp(*ts)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM events WHERE ts >= 2000", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2, "expected ts=2000 and ts=3000");
    let ts_idx = result.columns.iter().position(|c| c == "ts").unwrap();
    let ts_values: Vec<_> = result.rows.iter().map(|r| r[ts_idx].clone()).collect();
    assert!(ts_values.contains(&Value::Timestamp(2000)));
    assert!(ts_values.contains(&Value::Timestamp(3000)));
    assert!(!ts_values.contains(&Value::Timestamp(1000)));
}

#[test]
fn cmp_06_null_eq_null_is_false() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullable (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullable (id, val) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullable (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("hello".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT * FROM nullable WHERE val = NULL", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 0, "NULL = NULL must be false in SQL");
}

#[test]
fn cmp_07_neq_null_is_false() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullable2 (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    for v in &[None, Some("hello"), Some("world")] {
        let mut p = vec![("id", Value::Uuid(Uuid::new_v4()))];
        if let Some(s) = v {
            p.push(("val", Value::Text(s.to_string())));
        }
        let sql = if v.is_some() {
            "INSERT INTO nullable2 (id, val) VALUES ($id, $val)"
        } else {
            "INSERT INTO nullable2 (id, val) VALUES ($id, NULL)"
        };
        db.execute(sql, &params(p)).unwrap();
    }

    let result = db
        .execute("SELECT * FROM nullable2 WHERE val <> NULL", &empty())
        .unwrap();
    assert_eq!(
        result.rows.len(),
        0,
        "col <> NULL must be false for all rows in SQL"
    );
}

// ============================================================
// Group 2: Logical Operators
// ============================================================

fn setup_products_db() -> Database {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE products (id UUID PRIMARY KEY, price INTEGER, category TEXT)",
        &empty(),
    )
    .unwrap();
    let data = vec![(10i64, "food"), (20, "food"), (10, "drink"), (30, "drink")];
    for (price, cat) in data {
        db.execute(
            "INSERT INTO products (id, price, category) VALUES ($id, $price, $category)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("price", Value::Int64(price)),
                ("category", Value::Text(cat.into())),
            ]),
        )
        .unwrap();
    }
    db
}

#[test]
fn log_01_and_combines_filters() {
    let db = setup_products_db();
    let result = db
        .execute(
            "SELECT * FROM products WHERE price <= 10 AND category = 'food'",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let price_idx = result.columns.iter().position(|c| c == "price").unwrap();
    let cat_idx = result.columns.iter().position(|c| c == "category").unwrap();
    assert_eq!(result.rows[0][price_idx], Value::Int64(10));
    assert_eq!(result.rows[0][cat_idx], Value::Text("food".into()));
}

#[test]
fn log_02_or_matches_either() {
    let db = setup_products_db();
    let result = db
        .execute(
            "SELECT * FROM products WHERE price = 30 OR category = 'food'",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 3, "food(10), food(20), drink(30)");
    let price_idx = result.columns.iter().position(|c| c == "price").unwrap();
    let cat_idx = result.columns.iter().position(|c| c == "category").unwrap();
    let rows: Vec<(Value, Value)> = result
        .rows
        .iter()
        .map(|r| (r[price_idx].clone(), r[cat_idx].clone()))
        .collect();
    assert!(rows.contains(&(Value::Int64(10), Value::Text("food".into()))));
    assert!(rows.contains(&(Value::Int64(20), Value::Text("food".into()))));
    assert!(rows.contains(&(Value::Int64(30), Value::Text("drink".into()))));
    // drink(10) must NOT be present
    assert!(!rows.contains(&(Value::Int64(10), Value::Text("drink".into()))));
}

#[test]
fn log_03_not_negates() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE flags (id UUID PRIMARY KEY, active BOOLEAN)",
        &empty(),
    )
    .unwrap();
    for b in &[true, false, true] {
        db.execute(
            "INSERT INTO flags (id, active) VALUES ($id, $active)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("active", Value::Bool(*b)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM flags WHERE NOT active = true", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let active_idx = result.columns.iter().position(|c| c == "active").unwrap();
    assert_eq!(result.rows[0][active_idx], Value::Bool(false));
}

#[test]
fn log_04_null_propagation() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullcheck (id UUID PRIMARY KEY, a TEXT, b TEXT)",
        &empty(),
    )
    .unwrap();
    // id1: a=NULL, b='x'
    db.execute(
        "INSERT INTO nullcheck (id, a, b) VALUES ($id, NULL, $b)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("b", Value::Text("x".into())),
        ]),
    )
    .unwrap();
    // id2: a='y', b='x'
    db.execute(
        "INSERT INTO nullcheck (id, a, b) VALUES ($id, $a, $b)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("a", Value::Text("y".into())),
            ("b", Value::Text("x".into())),
        ]),
    )
    .unwrap();
    // id3: a=NULL, b=NULL
    db.execute(
        "INSERT INTO nullcheck (id, a, b) VALUES ($id, NULL, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();

    // false AND anything = false
    let r1 = db
        .execute(
            "SELECT * FROM nullcheck WHERE a = 'missing' AND b = 'x'",
            &empty(),
        )
        .unwrap();
    assert_eq!(r1.rows.len(), 0, "false AND anything = false");

    // OR: a='y' matches id2; b='x' matches id1,id2
    let r2 = db
        .execute("SELECT * FROM nullcheck WHERE a = 'y' OR b = 'x'", &empty())
        .unwrap();
    assert_eq!(r2.rows.len(), 2, "id1 and id2 match via OR");
}

// ============================================================
// Group 3: Expression Operators
// ============================================================

fn setup_colors_db() -> Database {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE colors (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    for c in &["red", "green", "blue", "yellow"] {
        db.execute(
            "INSERT INTO colors (id, name) VALUES ($id, $name)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("name", Value::Text(c.to_string())),
            ]),
        )
        .unwrap();
    }
    db
}

#[test]
fn expr_01_in_list() {
    let db = setup_colors_db();
    let result = db
        .execute(
            "SELECT * FROM colors WHERE name IN ('red', 'blue')",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<&Value> = result.rows.iter().map(|r| &r[name_idx]).collect();
    assert!(names.contains(&&Value::Text("red".into())));
    assert!(names.contains(&&Value::Text("blue".into())));
}

#[test]
fn expr_02_not_in() {
    let db = setup_colors_db();
    let result = db
        .execute(
            "SELECT * FROM colors WHERE name NOT IN ('red', 'blue')",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<&Value> = result.rows.iter().map(|r| &r[name_idx]).collect();
    assert!(names.contains(&&Value::Text("green".into())));
    assert!(names.contains(&&Value::Text("yellow".into())));
}

#[test]
fn expr_03_in_subquery() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE departments (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE employees (id UUID PRIMARY KEY, dept TEXT, name TEXT)",
        &empty(),
    )
    .unwrap();
    for dept in &["engineering", "sales"] {
        db.execute(
            "INSERT INTO departments (id, name) VALUES ($id, $name)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("name", Value::Text(dept.to_string())),
            ]),
        )
        .unwrap();
    }
    let emp_data = vec![
        ("engineering", "alice"),
        ("marketing", "bob"),
        ("sales", "carol"),
    ];
    for (dept, name) in emp_data {
        db.execute(
            "INSERT INTO employees (id, dept, name) VALUES ($id, $dept, $name)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("dept", Value::Text(dept.into())),
                ("name", Value::Text(name.into())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute(
            "SELECT * FROM employees WHERE dept IN (SELECT name FROM departments)",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<&Value> = result.rows.iter().map(|r| &r[name_idx]).collect();
    assert!(names.contains(&&Value::Text("alice".into())));
    assert!(names.contains(&&Value::Text("carol".into())));
}

#[test]
fn expr_04_like_percent() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE files (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    for f in &["report.pdf", "report.docx", "invoice.pdf", "notes.txt"] {
        db.execute(
            "INSERT INTO files (id, name) VALUES ($id, $name)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("name", Value::Text(f.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM files WHERE name LIKE 'report%'", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<&Value> = result.rows.iter().map(|r| &r[name_idx]).collect();
    assert!(names.contains(&&Value::Text("report.pdf".into())));
    assert!(names.contains(&&Value::Text("report.docx".into())));
}

#[test]
fn expr_05_like_underscore() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE codes (id UUID PRIMARY KEY, code TEXT)",
        &empty(),
    )
    .unwrap();
    for c in &["cat", "bat", "at", "cart"] {
        db.execute(
            "INSERT INTO codes (id, code) VALUES ($id, $code)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("code", Value::Text(c.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM codes WHERE code LIKE '_at'", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let code_idx = result.columns.iter().position(|c| c == "code").unwrap();
    let codes: Vec<&Value> = result.rows.iter().map(|r| &r[code_idx]).collect();
    assert!(codes.contains(&&Value::Text("cat".into())));
    assert!(codes.contains(&&Value::Text("bat".into())));
}

#[test]
fn expr_06_not_like() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE files2 (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    for f in &["report.pdf", "report.docx", "invoice.pdf", "notes.txt"] {
        db.execute(
            "INSERT INTO files2 (id, name) VALUES ($id, $name)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("name", Value::Text(f.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM files2 WHERE name NOT LIKE '%.pdf'", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<&Value> = result.rows.iter().map(|r| &r[name_idx]).collect();
    assert!(names.contains(&&Value::Text("report.docx".into())));
    assert!(names.contains(&&Value::Text("notes.txt".into())));
}

#[test]
fn expr_07_between_inclusive() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE temps (id UUID PRIMARY KEY, celsius INTEGER)",
        &empty(),
    )
    .unwrap();
    for c in &[10i64, 20, 25, 30, 40] {
        db.execute(
            "INSERT INTO temps (id, celsius) VALUES ($id, $c)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("c", Value::Int64(*c)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute(
            "SELECT * FROM temps WHERE celsius BETWEEN 20 AND 30",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 3, "20, 25, 30 are in range");
    let c_idx = result.columns.iter().position(|c| c == "celsius").unwrap();
    let vals: Vec<&Value> = result.rows.iter().map(|r| &r[c_idx]).collect();
    assert!(vals.contains(&&Value::Int64(20)));
    assert!(vals.contains(&&Value::Int64(25)));
    assert!(vals.contains(&&Value::Int64(30)));
}

#[test]
fn expr_08_is_null() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE optional (id UUID PRIMARY KEY, note TEXT)",
        &empty(),
    )
    .unwrap();
    let null_id = Uuid::new_v4();
    db.execute(
        "INSERT INTO optional (id, note) VALUES ($id, $note)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("note", Value::Text("hello".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO optional (id, note) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(null_id))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO optional (id, note) VALUES ($id, $note)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("note", Value::Text("world".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT * FROM optional WHERE note IS NULL", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let id_idx = result.columns.iter().position(|c| c == "id").unwrap();
    assert_eq!(result.rows[0][id_idx], Value::Uuid(null_id));
}

#[test]
fn expr_09_is_not_null() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE optional2 (id UUID PRIMARY KEY, note TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO optional2 (id, note) VALUES ($id, $note)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("note", Value::Text("hello".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO optional2 (id, note) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO optional2 (id, note) VALUES ($id, $note)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("note", Value::Text("world".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT * FROM optional2 WHERE note IS NOT NULL", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let note_idx = result.columns.iter().position(|c| c == "note").unwrap();
    let notes: Vec<&Value> = result.rows.iter().map(|r| &r[note_idx]).collect();
    assert!(notes.contains(&&Value::Text("hello".into())));
    assert!(notes.contains(&&Value::Text("world".into())));
}

// ============================================================
// Group 4: Aggregation
// ============================================================

#[test]
fn agg_01_count_star() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE counttable (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    for v in &["a", "b", "c"] {
        db.execute(
            "INSERT INTO counttable (id, val) VALUES ($id, $val)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("val", Value::Text(v.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT COUNT(*) FROM counttable", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1, "aggregate returns single row");
    assert_eq!(result.rows[0][0], Value::Int64(3));
    assert!(
        result.columns.iter().any(|c| c == "COUNT"),
        "column name must preserve SQL case"
    );
}

#[test]
fn agg_02_count_expr_excludes_nulls() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullcount (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullcount (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("a".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullcount (id, val) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullcount (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("c".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullcount (id, val) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();

    let result = db
        .execute("SELECT COUNT(val) FROM nullcount", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    assert_eq!(
        result.rows[0][0],
        Value::Int64(2),
        "COUNT(val) excludes NULLs"
    );
}

#[test]
fn agg_03_mixed_aggregate_error() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE mixagg (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO mixagg (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("a".into())),
        ]),
    )
    .unwrap();

    let result = db.execute("SELECT COUNT(*), val FROM mixagg", &empty());
    assert!(
        result.is_err(),
        "mixed aggregate + bare column without GROUP BY must error"
    );
}

// ============================================================
// Group 5: Functions
// ============================================================

#[test]
fn fn_01_coalesce_first_non_null() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE coaltable (id UUID PRIMARY KEY, a TEXT, b TEXT, c TEXT)",
        &empty(),
    )
    .unwrap();
    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    db.execute(
        "INSERT INTO coaltable (id, a, b, c) VALUES ($id, NULL, NULL, $c)",
        &params(vec![
            ("id", Value::Uuid(id1)),
            ("c", Value::Text("fallback".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO coaltable (id, a, b, c) VALUES ($id, NULL, $b, $c)",
        &params(vec![
            ("id", Value::Uuid(id2)),
            ("b", Value::Text("second".into())),
            ("c", Value::Text("third".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT COALESCE(a, b, c) FROM coaltable ORDER BY id ASC",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    // We check both rows have the correct first-non-null value.
    // Order depends on UUID, so we collect and check set membership.
    let values: Vec<&Value> = result.rows.iter().map(|r| &r[0]).collect();
    assert!(values.contains(&&Value::Text("fallback".into())));
    assert!(values.contains(&&Value::Text("second".into())));
}

#[test]
fn fn_02_now_without_from() {
    let db = Database::open_memory();
    let result = db.execute("SELECT NOW()", &empty()).unwrap();
    assert_eq!(result.rows.len(), 1);
    match &result.rows[0][0] {
        Value::Timestamp(ts) => {
            let now_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            assert!(
                (now_secs - ts).abs() < 5,
                "NOW() should be within 5s of system time"
            );
        }
        other => panic!("expected Timestamp, got {:?}", other),
    }
}

#[test]
fn fn_03_now_with_from() {
    let db = Database::open_memory();
    db.execute("CREATE TABLE dummy (id UUID PRIMARY KEY)", &empty())
        .unwrap();
    db.execute(
        "INSERT INTO dummy (id) VALUES ($id)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();

    let result = db.execute("SELECT NOW() FROM dummy", &empty()).unwrap();
    assert_eq!(result.rows.len(), 1);
    match &result.rows[0][0] {
        Value::Timestamp(ts) => {
            let now_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs() as i64;
            assert!(
                (now_secs - ts).abs() < 5,
                "NOW() should be within 5s of system time"
            );
        }
        other => panic!("expected Timestamp, got {:?}", other),
    }
}

// ============================================================
// Group 5b: SQL Correctness Regression Cases
// ============================================================

#[test]
fn sql_01_default_now_produces_timestamp() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE events (id UUID PRIMARY KEY, created_at TIMESTAMP DEFAULT NOW())",
        &empty(),
    )
    .unwrap();

    let id = Uuid::new_v4();
    db.execute(
        "INSERT INTO events (id) VALUES ($id)",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT created_at FROM events WHERE id = $id",
            &params(vec![("id", Value::Uuid(id))]),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    match &result.rows[0][0] {
        Value::Timestamp(ts) => assert!(
            *ts > 1_700_000_000,
            "created_at should be a recent unix timestamp, got {ts}"
        ),
        other => panic!("expected TIMESTAMP from DEFAULT NOW(), got {:?}", other),
    }
}

#[test]
fn sql_02_edge_insert_routes_to_graph_once() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT)",
        &empty(),
    )
    .unwrap();

    let source = Uuid::new_v4();
    let target = Uuid::new_v4();
    for _ in 0..2 {
        db.execute(
            "INSERT INTO edges (id, source_id, target_id, edge_type) VALUES ($id, $source_id, $target_id, $edge_type)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("source_id", Value::Uuid(source)),
                ("target_id", Value::Uuid(target)),
                ("edge_type", Value::Text("RELATES_TO".to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute(
            "SELECT b_id FROM GRAPH_TABLE(edges MATCH (a)-[:RELATES_TO]->(b) WHERE a.id = $source_id COLUMNS (b.id AS b_id))",
            &params(vec![("source_id", Value::Uuid(source))]),
        )
        .unwrap();
    assert_eq!(
        result.rows.len(),
        1,
        "graph traversal should see exactly one reachable target after duplicate SQL edge inserts"
    );
    assert_eq!(result.rows[0][0], Value::Uuid(target));
}

#[test]
fn sql_03_group_by_clean_error() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, tag TEXT)",
        &empty(),
    )
    .unwrap();

    let err = db
        .execute("SELECT tag, COUNT(*) FROM items GROUP BY tag", &empty())
        .unwrap_err()
        .to_string();
    assert!(
        err.contains("GROUP BY") && err.contains("not supported"),
        "expected a clean GROUP BY not-supported error, got: {err}"
    );
}

#[test]
fn sql_04_join_ambiguous_column_error() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE left_t (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE right_t (id UUID PRIMARY KEY, name TEXT, value INT)",
        &empty(),
    )
    .unwrap();

    let id = Uuid::new_v4();
    db.execute(
        "INSERT INTO left_t (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(id)),
            ("name", Value::Text("left".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO right_t (id, name, value) VALUES ($id, $name, $value)",
        &params(vec![
            ("id", Value::Uuid(id)),
            ("name", Value::Text("right".into())),
            ("value", Value::Int64(1)),
        ]),
    )
    .unwrap();

    let err = db
        .execute(
            "SELECT name FROM left_t INNER JOIN right_t ON left_t.id = right_t.id",
            &empty(),
        )
        .unwrap_err()
        .to_string();
    assert!(
        err.contains("ambiguous"),
        "expected ambiguous column error, got: {err}"
    );
}

#[test]
fn sql_05_scenario3_multi_hop_cascade() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE intentions (id UUID PRIMARY KEY, description TEXT, status TEXT) STATE MACHINE (status: active -> [archived, paused, superseded])",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE decisions (id UUID PRIMARY KEY, description TEXT, status TEXT, intention_id UUID REFERENCES intentions(id) ON STATE archived PROPAGATE SET invalidated, embedding VECTOR(128)) STATE MACHINE (status: active -> [invalidated, superseded]) PROPAGATE ON EDGE CITES INCOMING STATE invalidated SET invalidated",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT) DAG('CITES')",
        &empty(),
    )
    .unwrap();

    let intention_id = Uuid::new_v4();
    let decision_a = Uuid::new_v4();
    let decision_b = Uuid::new_v4();

    db.execute(
        "INSERT INTO intentions (id, description, status) VALUES ($id, $description, $status)",
        &params(vec![
            ("id", Value::Uuid(intention_id)),
            ("description", Value::Text("root".into())),
            ("status", Value::Text("active".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO decisions (id, description, status, intention_id) VALUES ($id, $description, $status, $intention_id)",
        &params(vec![
            ("id", Value::Uuid(decision_a)),
            ("description", Value::Text("a".into())),
            ("status", Value::Text("active".into())),
            ("intention_id", Value::Uuid(intention_id)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO decisions (id, description, status, intention_id) VALUES ($id, $description, $status, $intention_id)",
        &params(vec![
            ("id", Value::Uuid(decision_b)),
            ("description", Value::Text("b".into())),
            ("status", Value::Text("active".into())),
            ("intention_id", Value::Uuid(intention_id)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO edges (id, source_id, target_id, edge_type) VALUES ($id, $source_id, $target_id, $edge_type)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("source_id", Value::Uuid(decision_b)),
            ("target_id", Value::Uuid(decision_a)),
            ("edge_type", Value::Text("CITES".into())),
        ]),
    )
    .unwrap();

    db.execute(
        "UPDATE intentions SET status = 'archived' WHERE id = $id",
        &params(vec![("id", Value::Uuid(intention_id))]),
    )
    .unwrap();

    let decision_a_row = db
        .execute(
            "SELECT status FROM decisions WHERE id = $id",
            &params(vec![("id", Value::Uuid(decision_a))]),
        )
        .unwrap();
    let decision_b_row = db
        .execute(
            "SELECT status FROM decisions WHERE id = $id",
            &params(vec![("id", Value::Uuid(decision_b))]),
        )
        .unwrap();
    assert_eq!(decision_a_row.rows[0][0], Value::Text("invalidated".into()));
    assert_eq!(decision_b_row.rows[0][0], Value::Text("invalidated".into()));
}

#[test]
fn sql_06_uuid_column_validation() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();

    let result = db.execute("INSERT INTO items VALUES ('not-a-uuid', 'test')", &empty());
    assert!(
        result.is_err(),
        "invalid UUID literal should be rejected, but insert succeeded"
    );
}

#[test]
fn sql_07_join_double_qualification() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE employees (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE orders (id UUID PRIMARY KEY, name TEXT, employee_id UUID)",
        &empty(),
    )
    .unwrap();

    let employee_id = Uuid::new_v4();
    let order_id = Uuid::new_v4();
    db.execute(
        "INSERT INTO employees (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(employee_id)),
            ("name", Value::Text("employee".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO orders (id, name, employee_id) VALUES ($id, $name, $employee_id)",
        &params(vec![
            ("id", Value::Uuid(order_id)),
            ("name", Value::Text("order".into())),
            ("employee_id", Value::Uuid(employee_id)),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT e.name, o.name FROM employees e INNER JOIN orders o ON e.id = o.employee_id",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    assert_eq!(result.rows[0][0], Value::Text("employee".into()));
    assert_eq!(result.rows[0][1], Value::Text("order".into()));
}

#[test]
fn sql_08_distinct_not_quadratic() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, tag TEXT)",
        &empty(),
    )
    .unwrap();

    for i in 0..5_000 {
        let tag = format!("tag-{}", i % 100);
        db.execute(
            "INSERT INTO items (id, tag) VALUES ($id, $tag)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("tag", Value::Text(tag)),
            ]),
        )
        .unwrap();
    }

    let started = Instant::now();
    let result = db
        .execute("SELECT DISTINCT tag FROM items", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 100);
    assert!(
        started.elapsed().as_secs_f32() < 5.0,
        "SELECT DISTINCT should finish within 5 seconds on 5k rows"
    );
}

// ============================================================
// Group 6: Query Shaping
// ============================================================

#[test]
fn shp_01_distinct_removes_duplicates() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE tags (id UUID PRIMARY KEY, tag TEXT)",
        &empty(),
    )
    .unwrap();
    for t in &["rust", "python", "rust", "go", "python"] {
        db.execute(
            "INSERT INTO tags (id, tag) VALUES ($id, $tag)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("tag", Value::Text(t.to_string())),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT DISTINCT tag FROM tags", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 3, "3 distinct tags: rust, python, go");
    let tags: Vec<&Value> = result.rows.iter().map(|r| &r[0]).collect();
    assert!(tags.contains(&&Value::Text("rust".into())));
    assert!(tags.contains(&&Value::Text("python".into())));
    assert!(tags.contains(&&Value::Text("go".into())));
}

#[test]
fn shp_02_column_alias() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE people (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO people (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("name", Value::Text("alice".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT name AS person_name FROM people", &empty())
        .unwrap();
    assert!(
        result.columns.contains(&"person_name".to_string()),
        "output column should be aliased"
    );
    assert!(
        !result.columns.contains(&"name".to_string()),
        "original name should not appear"
    );
    assert_eq!(result.rows[0][0], Value::Text("alice".into()));
}

#[test]
fn shp_03_order_by_asc() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE sorted (id UUID PRIMARY KEY, num INTEGER)",
        &empty(),
    )
    .unwrap();
    for n in &[30i64, 10, 20] {
        db.execute(
            "INSERT INTO sorted (id, num) VALUES ($id, $num)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("num", Value::Int64(*n)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM sorted ORDER BY num ASC", &empty())
        .unwrap();
    let num_idx = result.columns.iter().position(|c| c == "num").unwrap();
    assert_eq!(result.rows[0][num_idx], Value::Int64(10));
    assert_eq!(result.rows[1][num_idx], Value::Int64(20));
    assert_eq!(result.rows[2][num_idx], Value::Int64(30));
}

#[test]
fn shp_04_order_by_multi_column_mixed() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE ranked (id UUID PRIMARY KEY, group_name TEXT, score INTEGER)",
        &empty(),
    )
    .unwrap();
    let data = vec![("alpha", 10i64), ("alpha", 20), ("beta", 10), ("beta", 20)];
    for (g, s) in data {
        db.execute(
            "INSERT INTO ranked (id, group_name, score) VALUES ($id, $g, $s)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("g", Value::Text(g.into())),
                ("s", Value::Int64(s)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute(
            "SELECT * FROM ranked ORDER BY group_name ASC, score DESC",
            &empty(),
        )
        .unwrap();
    let g_idx = result
        .columns
        .iter()
        .position(|c| c == "group_name")
        .unwrap();
    let s_idx = result.columns.iter().position(|c| c == "score").unwrap();
    assert_eq!(result.rows[0][g_idx], Value::Text("alpha".into()));
    assert_eq!(result.rows[0][s_idx], Value::Int64(20));
    assert_eq!(result.rows[1][g_idx], Value::Text("alpha".into()));
    assert_eq!(result.rows[1][s_idx], Value::Int64(10));
    assert_eq!(result.rows[2][g_idx], Value::Text("beta".into()));
    assert_eq!(result.rows[2][s_idx], Value::Int64(20));
    assert_eq!(result.rows[3][g_idx], Value::Text("beta".into()));
    assert_eq!(result.rows[3][s_idx], Value::Int64(10));
}

#[test]
fn shp_05_order_by_asc_nulls_last() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullsort (id UUID PRIMARY KEY, val INTEGER)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Int64(3)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort (id, val) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Int64(1)),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT * FROM nullsort ORDER BY val ASC", &empty())
        .unwrap();
    let val_idx = result.columns.iter().position(|c| c == "val").unwrap();
    assert_eq!(result.rows[0][val_idx], Value::Int64(1));
    assert_eq!(result.rows[1][val_idx], Value::Int64(3));
    assert_eq!(result.rows[2][val_idx], Value::Null);
}

#[test]
fn shp_06_order_by_desc_nulls_first() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE nullsort2 (id UUID PRIMARY KEY, val INTEGER)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort2 (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Int64(3)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort2 (id, val) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO nullsort2 (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Int64(1)),
        ]),
    )
    .unwrap();

    let result = db
        .execute("SELECT * FROM nullsort2 ORDER BY val DESC", &empty())
        .unwrap();
    let val_idx = result.columns.iter().position(|c| c == "val").unwrap();
    assert_eq!(result.rows[0][val_idx], Value::Null);
    assert_eq!(result.rows[1][val_idx], Value::Int64(3));
    assert_eq!(result.rows[2][val_idx], Value::Int64(1));
}

#[test]
fn shp_07_limit() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE big (id UUID PRIMARY KEY, num INTEGER)",
        &empty(),
    )
    .unwrap();
    for n in 1..=5i64 {
        db.execute(
            "INSERT INTO big (id, num) VALUES ($id, $num)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("num", Value::Int64(n)),
            ]),
        )
        .unwrap();
    }

    let result = db
        .execute("SELECT * FROM big ORDER BY num ASC LIMIT 3", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 3);
    let num_idx = result.columns.iter().position(|c| c == "num").unwrap();
    assert_eq!(result.rows[0][num_idx], Value::Int64(1));
    assert_eq!(result.rows[1][num_idx], Value::Int64(2));
    assert_eq!(result.rows[2][num_idx], Value::Int64(3));
}

// ============================================================
// Group 7: JOIN
// ============================================================

fn setup_authors_books_db() -> Database {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE authors (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE books (id UUID PRIMARY KEY, title TEXT, author_id UUID)",
        &empty(),
    )
    .unwrap();
    db
}

#[test]
fn jn_01_inner_join() {
    let db = setup_authors_books_db();
    let aid1 = Uuid::new_v4();
    let aid2 = Uuid::new_v4();
    db.execute(
        "INSERT INTO authors (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(aid1)),
            ("name", Value::Text("alice".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO authors (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(aid2)),
            ("name", Value::Text("bob".into())),
        ]),
    )
    .unwrap();
    // Two books by alice, one by nonexistent author
    db.execute(
        "INSERT INTO books (id, title, author_id) VALUES ($id, $title, $aid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("title", Value::Text("book_a".into())),
            ("aid", Value::Uuid(aid1)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO books (id, title, author_id) VALUES ($id, $title, $aid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("title", Value::Text("book_b".into())),
            ("aid", Value::Uuid(aid1)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO books (id, title, author_id) VALUES ($id, $title, $aid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("title", Value::Text("book_c".into())),
            ("aid", Value::Uuid(Uuid::new_v4())), // nonexistent author
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT a.name, b.title FROM authors a INNER JOIN books b ON a.id = b.author_id",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 2, "only alice's 2 books match");
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let title_idx = result.columns.iter().position(|c| c == "title").unwrap();
    for row in &result.rows {
        assert_eq!(row[name_idx], Value::Text("alice".into()));
    }
    let titles: Vec<&Value> = result.rows.iter().map(|r| &r[title_idx]).collect();
    assert!(titles.contains(&&Value::Text("book_a".into())));
    assert!(titles.contains(&&Value::Text("book_b".into())));
}

#[test]
fn jn_02_left_join_unmatched_nulls() {
    let db = setup_authors_books_db();
    let aid1 = Uuid::new_v4();
    let aid2 = Uuid::new_v4();
    db.execute(
        "INSERT INTO authors (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(aid1)),
            ("name", Value::Text("alice".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO authors (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(aid2)),
            ("name", Value::Text("bob".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO books (id, title, author_id) VALUES ($id, $title, $aid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("title", Value::Text("book_a".into())),
            ("aid", Value::Uuid(aid1)),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO books (id, title, author_id) VALUES ($id, $title, $aid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("title", Value::Text("book_b".into())),
            ("aid", Value::Uuid(aid1)),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT a.name, b.title FROM authors a LEFT JOIN books b ON a.id = b.author_id",
            &empty(),
        )
        .unwrap();
    assert_eq!(
        result.rows.len(),
        3,
        "alice's 2 books + bob with NULL title"
    );
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let title_idx = result.columns.iter().position(|c| c == "title").unwrap();
    // Find bob's row
    let bob_rows: Vec<_> = result
        .rows
        .iter()
        .filter(|r| r[name_idx] == Value::Text("bob".into()))
        .collect();
    assert_eq!(bob_rows.len(), 1);
    assert_eq!(
        bob_rows[0][title_idx],
        Value::Null,
        "unmatched left row has NULL for right columns"
    );
}

#[test]
fn jn_03_disambiguated_columns() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE left_t (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE right_t (id UUID PRIMARY KEY, val TEXT, left_id UUID)",
        &empty(),
    )
    .unwrap();
    let lid = Uuid::new_v4();
    db.execute(
        "INSERT INTO left_t (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(lid)),
            ("val", Value::Text("left_val".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO right_t (id, val, left_id) VALUES ($id, $val, $lid)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("right_val".into())),
            ("lid", Value::Uuid(lid)),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT l.val, r.val FROM left_t l INNER JOIN right_t r ON l.id = r.left_id",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    assert_eq!(result.rows[0][0], Value::Text("left_val".into()));
    assert_eq!(result.rows[0][1], Value::Text("right_val".into()));
}

#[test]
fn jn_04_cte_graph_join_relational() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE entities (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT)",
        &empty(),
    )
    .unwrap();

    let eid1 = Uuid::new_v4();
    let eid2 = Uuid::new_v4();
    let eid3 = Uuid::new_v4();
    db.execute(
        "INSERT INTO entities (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(eid1)),
            ("name", Value::Text("root".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO entities (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(eid2)),
            ("name", Value::Text("child".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO entities (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(eid3)),
            ("name", Value::Text("orphan".into())),
        ]),
    )
    .unwrap();

    // Insert edge via transaction (graph subsystem)
    let tx = db.begin();
    db.insert_edge(tx, eid1, eid2, "DEPENDS_ON".into(), HashMap::new())
        .unwrap();
    // Also insert into edges table for relational consistency
    db.insert_row(tx, "edges", {
        let mut m = HashMap::new();
        m.insert("id".to_string(), Value::Uuid(Uuid::new_v4()));
        m.insert("source_id".to_string(), Value::Uuid(eid1));
        m.insert("target_id".to_string(), Value::Uuid(eid2));
        m.insert("edge_type".to_string(), Value::Text("DEPENDS_ON".into()));
        m
    })
    .unwrap();
    db.commit(tx).unwrap();

    let result = db
        .execute(
            "WITH reachable AS (
            SELECT b_id FROM GRAPH_TABLE(
                edges MATCH (a)-[:DEPENDS_ON]->(b)
                WHERE a.id = $root_id
                COLUMNS (b.id AS b_id)
            )
        )
        SELECT e.name FROM entities e INNER JOIN reachable r ON e.id = r.b_id",
            &params(vec![("root_id", Value::Uuid(eid1))]),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    assert_eq!(result.rows[0][name_idx], Value::Text("child".into()));
}

#[test]
fn jn_05_inner_join_no_matches_empty() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE table_a (id UUID PRIMARY KEY, key_col TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE table_b (id UUID PRIMARY KEY, ref_key TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO table_a (id, key_col) VALUES ($id, $key)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("key", Value::Text("x".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO table_b (id, ref_key) VALUES ($id, $key)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("key", Value::Text("y".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT * FROM table_a a INNER JOIN table_b b ON a.key_col = b.ref_key",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 0, "no matching keys means empty result");
}

#[test]
fn jn_06_cte_filtered_vector_ordering_executes() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE entities (id UUID PRIMARY KEY, name TEXT, embedding VECTOR(3), is_deprecated BOOLEAN)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT)",
        &empty(),
    )
    .unwrap();

    let root = Uuid::new_v4();
    let near = Uuid::new_v4();
    let far = Uuid::new_v4();

    for (id, name, embedding) in [
        (root, "root", vec![0.0, 0.0, 1.0]),
        (near, "near", vec![1.0, 0.0, 0.0]),
        (far, "far", vec![0.0, 1.0, 0.0]),
    ] {
        db.execute(
            "INSERT INTO entities (id, name, embedding, is_deprecated) VALUES ($id, $name, $embedding, $deprecated)",
            &params(vec![
                ("id", Value::Uuid(id)),
                ("name", Value::Text(name.into())),
                ("embedding", Value::Vector(embedding)),
                ("deprecated", Value::Bool(false)),
            ]),
        )
        .unwrap();
    }

    let tx = db.begin();
    for target in [near, far] {
        db.insert_edge(tx, root, target, "RELATES_TO".into(), HashMap::new())
            .unwrap();
        db.insert_row(tx, "edges", {
            let mut m = HashMap::new();
            m.insert("id".to_string(), Value::Uuid(Uuid::new_v4()));
            m.insert("source_id".to_string(), Value::Uuid(root));
            m.insert("target_id".to_string(), Value::Uuid(target));
            m.insert("edge_type".to_string(), Value::Text("RELATES_TO".into()));
            m
        })
        .unwrap();
    }
    db.commit(tx).unwrap();

    let result = db
        .execute(
            "WITH neighborhood AS (
                SELECT b_id FROM GRAPH_TABLE(
                    edges MATCH (a)-[:RELATES_TO]->(b)
                    WHERE a.id = $root_id
                    COLUMNS (b.id AS b_id)
                )
            ),
            filtered AS (
                SELECT id, name, embedding
                FROM entities e
                INNER JOIN neighborhood n ON e.id = n.b_id
                WHERE e.is_deprecated = FALSE
            )
            SELECT id, name FROM filtered ORDER BY embedding <=> $query LIMIT 2",
            &params(vec![
                ("root_id", Value::Uuid(root)),
                ("query", Value::Vector(vec![1.0, 0.0, 0.0])),
            ]),
        )
        .expect("CTE-backed vector ordering should execute");

    assert_eq!(result.rows.len(), 2);
    assert_eq!(result.rows[0][0], Value::Uuid(near));
    assert_eq!(result.rows[0][1], Value::Text("near".into()));
    assert_eq!(result.rows[1][0], Value::Uuid(far));
    assert_eq!(result.rows[1][1], Value::Text("far".into()));
}

// ============================================================
// Group 8: Constraints
// ============================================================

#[test]
fn con_01_not_null_rejects_null() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE strict (id UUID PRIMARY KEY, name TEXT NOT NULL)",
        &empty(),
    )
    .unwrap();

    let result = db.execute(
        "INSERT INTO strict (id, name) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    );
    assert!(result.is_err(), "NOT NULL column must reject NULL insert");
}

#[test]
fn con_02_unique_duplicate_is_noop() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE uniq (id UUID PRIMARY KEY, email TEXT UNIQUE)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO uniq (id, email) VALUES ($id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();

    db.execute(
        "INSERT INTO uniq (id, email) VALUES ($id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();

    let rows = db.scan("uniq", db.snapshot()).unwrap();
    assert_eq!(rows.len(), 1, "duplicate UNIQUE insert must be a no-op");
}

#[test]
fn con_03_backward_compat_column_def_serde() {
    // Simulate old serialized ColumnDef without `unique` or `default` fields.
    // The core ColumnDef currently has: name, column_type, nullable, primary_key.
    // After adding `unique: bool` and `default: Option<String>` with #[serde(default)],
    // old data must still deserialize.
    let old_json = r#"{
        "columns": [
            {"name": "id", "column_type": "Uuid", "nullable": false, "primary_key": true},
            {"name": "val", "column_type": "Text", "nullable": true, "primary_key": false}
        ],
        "immutable": false,
        "state_machine": null,
        "dag_edge_types": [],
        "natural_key_column": null,
        "propagation_rules": []
    }"#;

    let meta: contextdb_core::TableMeta = serde_json::from_str(old_json).unwrap();
    assert_eq!(meta.columns.len(), 2);
    assert_eq!(meta.columns[0].name, "id");
    assert_eq!(meta.columns[1].name, "val");
    // After implementation adds `unique` field with serde(default), this should default to false.
    // For now, this test verifies the current schema deserializes without error.
}

#[test]
fn con_04_composite_unique_duplicate_is_noop() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE memberships (id UUID PRIMARY KEY, org_id UUID NOT NULL, email TEXT NOT NULL, UNIQUE (org_id, email))",
        &empty(),
    )
    .unwrap();

    db.execute(
        "INSERT INTO memberships (id, org_id, email) VALUES ($id, $org_id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("org_id", Value::Uuid(Uuid::from_u128(1))),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();

    db.execute(
        "INSERT INTO memberships (id, org_id, email) VALUES ($id, $org_id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("org_id", Value::Uuid(Uuid::from_u128(1))),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();

    let rows = db.scan("memberships", db.snapshot()).unwrap();
    assert_eq!(rows.len(), 1, "duplicate composite tuple must be a no-op");
}

#[test]
fn con_05_composite_unique_allows_distinct_tuple() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE memberships (id UUID PRIMARY KEY, org_id UUID NOT NULL, email TEXT NOT NULL, UNIQUE (org_id, email))",
        &empty(),
    )
    .unwrap();

    db.execute(
        "INSERT INTO memberships (id, org_id, email) VALUES ($id, $org_id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("org_id", Value::Uuid(Uuid::from_u128(1))),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO memberships (id, org_id, email) VALUES ($id, $org_id, $email)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("org_id", Value::Uuid(Uuid::from_u128(2))),
            ("email", Value::Text("alice@example.com".into())),
        ]),
    )
    .unwrap();

    let rows = db.scan("memberships", db.snapshot()).unwrap();
    assert_eq!(rows.len(), 2);
}

// ============================================================
// Group 9: Other
// ============================================================

#[test]
fn idx_01_create_index_accepted() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE indexed (id UUID PRIMARY KEY, name TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO indexed (id, name) VALUES ($id, $name)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("name", Value::Text("alice".into())),
        ]),
    )
    .unwrap();

    let result = db.execute("CREATE INDEX idx_name ON indexed (name)", &empty());
    assert!(result.is_ok(), "CREATE INDEX should be accepted (no-op)");

    // Verify queries still work after index creation
    let q = db
        .execute("SELECT * FROM indexed WHERE name = 'alice'", &empty())
        .unwrap();
    assert_eq!(q.rows.len(), 1);
}

#[test]
fn dual_01_select_without_from() {
    let db = Database::open_memory();
    let result = db.execute("SELECT NOW()", &empty()).unwrap();
    assert_eq!(result.rows.len(), 1);
    assert!(
        matches!(result.rows[0][0], Value::Timestamp(_)),
        "SELECT NOW() without FROM should return timestamp"
    );
}

#[test]
fn err_01_triple_not_evaluates_correctly() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE errtest (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO errtest (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("hello".into())),
        ]),
    )
    .unwrap();

    // NOT NOT NOT (val = 'hello') = NOT NOT false = NOT true = false => 0 rows
    let result = db
        .execute(
            "SELECT * FROM errtest WHERE NOT NOT NOT val = 'hello'",
            &empty(),
        )
        .unwrap();
    assert_eq!(
        result.rows.len(),
        0,
        "triple NOT of true = false, so 0 rows"
    );
}

// ---------------------------------------------------------------------------
// cmt_01 — Line comment stripped
// ---------------------------------------------------------------------------
#[test]
fn cmt_01_line_comment() {
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (id UUID PRIMARY KEY, val TEXT)", &empty())
        .unwrap();
    db.execute(
        "INSERT INTO t (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("hello".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT * FROM t -- this is a comment\nWHERE val = 'hello'",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let val_idx = result.columns.iter().position(|c| c == "val").unwrap();
    assert_eq!(result.rows[0][val_idx], Value::Text("hello".into()));
}

// ---------------------------------------------------------------------------
// cmt_02 — Block comment stripped
// ---------------------------------------------------------------------------
#[test]
fn cmt_02_block_comment() {
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (id UUID PRIMARY KEY, val TEXT)", &empty())
        .unwrap();
    db.execute(
        "INSERT INTO t (id, val) VALUES ($id, $val)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("val", Value::Text("hello".into())),
        ]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT /* all columns */ * FROM t WHERE val = 'hello'",
            &empty(),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    let val_idx = result.columns.iter().position(|c| c == "val").unwrap();
    assert_eq!(result.rows[0][val_idx], Value::Text("hello".into()));
}

// ---------------------------------------------------------------------------
// upd_01 — UPDATE SET count = count + 1
// ---------------------------------------------------------------------------
#[test]
fn upd_01_update_with_arithmetic() {
    let db = Database::open_memory();
    let id1 = Uuid::new_v4();
    db.execute(
        "CREATE TABLE counters (id UUID PRIMARY KEY, count INTEGER)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO counters (id, count) VALUES ($id, $count)",
        &params(vec![("id", Value::Uuid(id1)), ("count", Value::Int64(10))]),
    )
    .unwrap();

    db.execute(
        "UPDATE counters SET count = count + 1 WHERE id = $id",
        &params(vec![("id", Value::Uuid(id1))]),
    )
    .unwrap();

    let row = db
        .point_lookup("counters", "id", &Value::Uuid(id1), db.snapshot())
        .unwrap()
        .expect("row must exist");
    assert_eq!(
        row.values.get("count"),
        Some(&Value::Int64(11)),
        "count must be 11 after +1"
    );
}

// ---------------------------------------------------------------------------
// upd_02 — UPDATE SET ts = NOW()
// ---------------------------------------------------------------------------
#[test]
fn upd_02_update_with_now() {
    let db = Database::open_memory();
    let id1 = Uuid::new_v4();
    db.execute(
        "CREATE TABLE events (id UUID PRIMARY KEY, ts TIMESTAMP)",
        &empty(),
    )
    .unwrap();
    db.execute(
        "INSERT INTO events (id, ts) VALUES ($id, $ts)",
        &params(vec![("id", Value::Uuid(id1)), ("ts", Value::Timestamp(0))]),
    )
    .unwrap();

    db.execute(
        "UPDATE events SET ts = NOW() WHERE id = $id",
        &params(vec![("id", Value::Uuid(id1))]),
    )
    .unwrap();

    let row = db
        .point_lookup("events", "id", &Value::Uuid(id1), db.snapshot())
        .unwrap()
        .expect("row must exist");
    match row.values.get("ts") {
        Some(Value::Timestamp(t)) => assert!(*t > 0, "NOW() must produce a timestamp > 0"),
        other => panic!("expected Timestamp, got {:?}", other),
    }
}

#[test]
fn upd_03_update_embedding_changes_vector_recall_immediately() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE observations (id UUID PRIMARY KEY, embedding VECTOR(3))",
        &empty(),
    )
    .unwrap();

    let id_a = Uuid::new_v4();
    let id_b = Uuid::new_v4();
    db.execute(
        "INSERT INTO observations (id, embedding) VALUES ($id, $embedding)",
        &params(vec![
            ("id", Value::Uuid(id_a)),
            ("embedding", Value::Vector(vec![0.95, 0.05, 0.0])),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO observations (id, embedding) VALUES ($id, $embedding)",
        &params(vec![
            ("id", Value::Uuid(id_b)),
            ("embedding", Value::Vector(vec![0.9, 0.1, 0.0])),
        ]),
    )
    .unwrap();

    let before = db
        .execute(
            "SELECT id FROM observations ORDER BY embedding <=> $query LIMIT 1",
            &params(vec![("query", Value::Vector(vec![1.0, 0.0, 0.0]))]),
        )
        .unwrap();
    assert_eq!(before.rows.len(), 1);
    assert_eq!(before.rows[0][0], Value::Uuid(id_a));

    db.execute(
        "UPDATE observations SET embedding = $embedding WHERE id = $id",
        &params(vec![
            ("id", Value::Uuid(id_a)),
            ("embedding", Value::Vector(vec![-1.0, 0.0, 0.0])),
        ]),
    )
    .unwrap();

    let after = db
        .execute(
            "SELECT id FROM observations ORDER BY embedding <=> $query LIMIT 2",
            &params(vec![("query", Value::Vector(vec![1.0, 0.0, 0.0]))]),
        )
        .unwrap();
    assert_eq!(after.rows.len(), 2);
    assert_eq!(after.rows[0][0], Value::Uuid(id_b));
    assert_eq!(after.rows[1][0], Value::Uuid(id_a));
}

fn setup_cte_sensor_db() -> Database {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE sensors (id UUID PRIMARY KEY, name TEXT, status TEXT, reading REAL)",
        &empty(),
    )
    .unwrap();

    for (id, name, status, reading) in [
        (
            Uuid::from_u128(1),
            "sensor-north",
            "active",
            Value::Float64(42.0),
        ),
        (
            Uuid::from_u128(2),
            "sensor-south",
            "inactive",
            Value::Float64(10.0),
        ),
        (
            Uuid::from_u128(3),
            "widget-east",
            "active",
            Value::Float64(99.0),
        ),
    ] {
        db.execute(
            "INSERT INTO sensors (id, name, status, reading) VALUES ($id, $name, $status, $reading)",
            &params(vec![
                ("id", Value::Uuid(id)),
                ("name", Value::Text(name.to_string())),
                ("status", Value::Text(status.to_string())),
                ("reading", reading),
            ]),
        )
        .unwrap();
    }

    db
}

#[test]
fn cte_01_outer_where_filters_cte_rows() {
    let db = setup_cte_sensor_db();

    let result = db
        .execute(
            "WITH active AS (SELECT id, name, reading FROM sensors WHERE status = 'active') \
             SELECT id, name FROM active WHERE name LIKE 'sensor%'",
            &empty(),
        )
        .unwrap();

    assert_eq!(
        result.rows.len(),
        1,
        "outer WHERE on CTE should keep only sensor-prefixed active rows"
    );
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let names: Vec<_> = result
        .rows
        .iter()
        .map(|row| row[name_idx].clone())
        .collect();
    assert_eq!(names, vec![Value::Text("sensor-north".to_string())]);
    assert!(
        !names.contains(&Value::Text("widget-east".to_string())),
        "widget-east is active but should be filtered out by outer LIKE predicate"
    );
}

#[test]
fn cte_02_outer_where_comparison_filters_cte_rows() {
    let db = setup_cte_sensor_db();

    let result = db
        .execute(
            "WITH high AS (SELECT id, name, reading FROM sensors WHERE status = 'active') \
             SELECT id, name, reading FROM high WHERE reading > 50.0",
            &empty(),
        )
        .unwrap();

    assert_eq!(
        result.rows.len(),
        1,
        "outer WHERE on CTE should keep only rows above the reading threshold"
    );
    let name_idx = result.columns.iter().position(|c| c == "name").unwrap();
    let reading_idx = result.columns.iter().position(|c| c == "reading").unwrap();
    assert_eq!(
        result.rows[0][name_idx],
        Value::Text("widget-east".to_string())
    );
    assert_eq!(result.rows[0][reading_idx], Value::Float64(99.0));
}

#[test]
fn dag_01_cycle_rejected_via_insert_sql() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE dependencies (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT) DAG('DEPENDS_ON')",
        &empty(),
    )
    .unwrap();

    let a = Uuid::from_u128(101);
    let b = Uuid::from_u128(102);

    db.execute(
        "INSERT INTO dependencies (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, $edge_type)",
        &params(vec![
            ("id", Value::Uuid(Uuid::from_u128(201))),
            ("source", Value::Uuid(a)),
            ("target", Value::Uuid(b)),
            ("edge_type", Value::Text("DEPENDS_ON".to_string())),
        ]),
    )
    .unwrap();

    let err = db
        .execute(
            "INSERT INTO dependencies (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, $edge_type)",
            &params(vec![
                ("id", Value::Uuid(Uuid::from_u128(202))),
                ("source", Value::Uuid(b)),
                ("target", Value::Uuid(a)),
                ("edge_type", Value::Text("DEPENDS_ON".to_string())),
            ]),
        )
        .unwrap_err();

    assert!(
        err.to_string().to_lowercase().contains("cycle"),
        "expected cycle rejection on reverse insert, got {err}"
    );
}

#[test]
fn dag_02_self_loop_rejected_via_insert_sql() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE dependencies (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT) DAG('DEPENDS_ON')",
        &empty(),
    )
    .unwrap();

    let node = Uuid::from_u128(103);
    let err = db
        .execute(
            "INSERT INTO dependencies (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, $edge_type)",
            &params(vec![
                ("id", Value::Uuid(Uuid::from_u128(203))),
                ("source", Value::Uuid(node)),
                ("target", Value::Uuid(node)),
                ("edge_type", Value::Text("DEPENDS_ON".to_string())),
            ]),
        )
        .unwrap_err();

    assert!(
        err.to_string().to_lowercase().contains("cycle"),
        "expected self-loop insert to be rejected as a cycle, got {err}"
    );
}

#[test]
fn prop_01_fk_propagate_fires_on_update() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE intentions (id UUID PRIMARY KEY, status TEXT) STATE MACHINE (status: active -> [archived, completed])",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE decisions (id UUID PRIMARY KEY, intention_id UUID REFERENCES intentions(id) ON STATE archived PROPAGATE SET invalidated, status TEXT) STATE MACHINE (status: active -> [invalidated, superseded])",
        &empty(),
    )
    .unwrap();

    let intention_id = Uuid::from_u128(301);
    let decision_id = Uuid::from_u128(302);

    db.execute(
        "INSERT INTO intentions (id, status) VALUES ($id, $status)",
        &params(vec![
            ("id", Value::Uuid(intention_id)),
            ("status", Value::Text("active".to_string())),
        ]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO decisions (id, intention_id, status) VALUES ($id, $intention_id, $status)",
        &params(vec![
            ("id", Value::Uuid(decision_id)),
            ("intention_id", Value::Uuid(intention_id)),
            ("status", Value::Text("active".to_string())),
        ]),
    )
    .unwrap();

    db.execute(
        "UPDATE intentions SET status = 'archived' WHERE id = $id",
        &params(vec![("id", Value::Uuid(intention_id))]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT status FROM decisions WHERE id = $id",
            &params(vec![("id", Value::Uuid(decision_id))]),
        )
        .unwrap();
    assert_eq!(result.rows.len(), 1);
    assert_eq!(
        result.rows[0][0],
        Value::Text("invalidated".to_string()),
        "child decision should be invalidated after parent UPDATE archives intention"
    );
}

#[test]
fn prop_02_fk_propagate_cascades_multiple_children() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE intentions (id UUID PRIMARY KEY, status TEXT) STATE MACHINE (status: active -> [archived, completed])",
        &empty(),
    )
    .unwrap();
    db.execute(
        "CREATE TABLE decisions (id UUID PRIMARY KEY, intention_id UUID REFERENCES intentions(id) ON STATE archived PROPAGATE SET invalidated, status TEXT) STATE MACHINE (status: active -> [invalidated, superseded])",
        &empty(),
    )
    .unwrap();

    let intention_id = Uuid::from_u128(401);
    let decision_a = Uuid::from_u128(402);
    let decision_b = Uuid::from_u128(403);

    db.execute(
        "INSERT INTO intentions (id, status) VALUES ($id, $status)",
        &params(vec![
            ("id", Value::Uuid(intention_id)),
            ("status", Value::Text("active".to_string())),
        ]),
    )
    .unwrap();

    for decision_id in [decision_a, decision_b] {
        db.execute(
            "INSERT INTO decisions (id, intention_id, status) VALUES ($id, $intention_id, $status)",
            &params(vec![
                ("id", Value::Uuid(decision_id)),
                ("intention_id", Value::Uuid(intention_id)),
                ("status", Value::Text("active".to_string())),
            ]),
        )
        .unwrap();
    }

    db.execute(
        "UPDATE intentions SET status = 'archived' WHERE id = $id",
        &params(vec![("id", Value::Uuid(intention_id))]),
    )
    .unwrap();

    let result = db
        .execute("SELECT id, status FROM decisions ORDER BY id", &empty())
        .unwrap();
    assert_eq!(result.rows.len(), 2);
    let id_idx = result.columns.iter().position(|c| c == "id").unwrap();
    let status_idx = result.columns.iter().position(|c| c == "status").unwrap();

    assert_eq!(result.rows[0][id_idx], Value::Uuid(decision_a));
    assert_eq!(
        result.rows[0][status_idx],
        Value::Text("invalidated".to_string())
    );
    assert_eq!(result.rows[1][id_idx], Value::Uuid(decision_b));
    assert_eq!(
        result.rows[1][status_idx],
        Value::Text("invalidated".to_string())
    );
}

fn ddl_name(change: &contextdb_engine::sync_types::DdlChange) -> String {
    match change {
        contextdb_engine::sync_types::DdlChange::CreateTable { name, .. }
        | contextdb_engine::sync_types::DdlChange::DropTable { name }
        | contextdb_engine::sync_types::DdlChange::AlterTable { name, .. } => name.clone(),
        contextdb_engine::sync_types::DdlChange::CreateIndex { table, .. }
        | contextdb_engine::sync_types::DdlChange::DropIndex { table, .. } => table.clone(),
    }
}

fn max_non_ddl_lsn(changes: &contextdb_engine::sync_types::ChangeSet) -> Option<Lsn> {
    let row_max = changes.rows.iter().map(|r| r.lsn).max();
    let edge_max = changes.edges.iter().map(|e| e.lsn).max();
    let vector_max = changes.vectors.iter().map(|v| v.lsn).max();
    row_max.into_iter().chain(edge_max).chain(vector_max).max()
}

#[test]
fn sql_15_ddl_dml_lsn_causal_ordering() {
    let db = Arc::new(Database::open_memory());
    db.execute(
        "CREATE TABLE shared (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();

    let workers = 4;
    let iterations = 40;
    let barrier = Arc::new(Barrier::new(workers + 1));
    let done = Arc::new(AtomicBool::new(false));
    let expected_tables: Vec<String> = (0..workers)
        .flat_map(|worker| (0..iterations).map(move |i| format!("lsn_race_{worker}_{i}")))
        .collect();
    let poller_expected = Arc::new(expected_tables.clone());
    let poller_db = db.clone();
    let poller_done = done.clone();
    let poller_barrier = barrier.clone();

    let poller = thread::spawn(move || {
        let mut watermark = Lsn(0);
        let mut seen_creates = std::collections::HashSet::new();
        let mut row_before_create = Vec::new();
        let mut idle_after_done_since = None;
        poller_barrier.wait();

        loop {
            let expected_len = poller_expected.len();
            let changes = poller_db.changes_since(watermark);
            let before_seen = seen_creates.len();
            if !changes.ddl.is_empty() || !changes.rows.is_empty() {
                for ddl in &changes.ddl {
                    if matches!(
                        ddl,
                        contextdb_engine::sync_types::DdlChange::CreateTable { .. }
                    ) {
                        seen_creates.insert(ddl_name(ddl));
                    }
                }
                for row in &changes.rows {
                    if row.table.starts_with("lsn_race_") && !seen_creates.contains(&row.table) {
                        row_before_create.push(row.table.clone());
                    }
                }
                if let Some(lsn) = max_non_ddl_lsn(&changes) {
                    watermark = lsn;
                }
            } else {
                thread::yield_now();
            }

            if poller_done.load(Ordering::SeqCst) && seen_creates.len() >= expected_len {
                break;
            }
            if poller_done.load(Ordering::SeqCst) {
                if seen_creates.len() == before_seen {
                    idle_after_done_since.get_or_insert_with(Instant::now);
                } else {
                    idle_after_done_since = None;
                }
                if idle_after_done_since
                    .is_some_and(|started| started.elapsed() > Duration::from_secs(3))
                {
                    break;
                }
            }
        }

        let expected = poller_expected.as_ref().clone();
        (row_before_create, seen_creates, expected)
    });

    let mut handles = Vec::new();
    for worker in 0..workers {
        let db = db.clone();
        let barrier = barrier.clone();
        handles.push(thread::spawn(move || {
            barrier.wait();
            for i in 0..iterations {
                let table = format!("lsn_race_{worker}_{i}");
                db.execute(
                    &format!("CREATE TABLE {table} (id UUID PRIMARY KEY, val TEXT)"),
                    &empty(),
                )
                .unwrap();
                db.execute(
                    &format!("INSERT INTO {table} (id, val) VALUES ($id, 'data')"),
                    &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
                )
                .unwrap();
                db.execute(
                    "INSERT INTO shared (id, val) VALUES ($id, 'shared')",
                    &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
                )
                .unwrap();
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }
    done.store(true, Ordering::SeqCst);
    let (row_before_create, seen_creates, expected) = poller.join().unwrap();

    assert!(
        row_before_create.is_empty(),
        "sync consumer observed row changes before CREATE TABLE DDL for tables: {:?}",
        row_before_create
    );
    for table in expected {
        assert!(
            seen_creates.contains(&table),
            "sync consumer missed CREATE TABLE DDL for {table}"
        );
    }
}

#[test]
fn sql_16_ddl_lsn_no_duplicates_under_contention() {
    let db = Arc::new(Database::open_memory());
    db.execute(
        "CREATE TABLE shared (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();

    let workers = 4;
    let iterations = 25;
    let barrier = Arc::new(Barrier::new(workers + 1));
    let done = Arc::new(AtomicBool::new(false));
    let expected_columns: Vec<String> = (0..workers)
        .flat_map(|worker| (0..iterations).map(move |i| format!("c_{worker}_{i}")))
        .collect();
    let poller_expected = Arc::new(expected_columns.clone());
    let poller_db = db.clone();
    let poller_done = done.clone();
    let poller_barrier = barrier.clone();

    let poller = thread::spawn(move || {
        let mut watermark = Lsn(0);
        let mut seen_columns = std::collections::HashSet::new();
        let mut idle_after_done_since = None;
        poller_barrier.wait();

        loop {
            let expected_len = poller_expected.len();
            let changes = poller_db.changes_since(watermark);
            let before_seen = seen_columns.len();
            if !changes.ddl.is_empty() || !changes.rows.is_empty() {
                for ddl in &changes.ddl {
                    if let contextdb_engine::sync_types::DdlChange::AlterTable {
                        name, columns, ..
                    } = ddl
                        && name == "shared"
                    {
                        for (column, _) in columns {
                            if column.starts_with("c_") {
                                seen_columns.insert(column.clone());
                            }
                        }
                    }
                }
                if let Some(lsn) = max_non_ddl_lsn(&changes) {
                    watermark = lsn;
                }
            } else {
                thread::yield_now();
            }

            if poller_done.load(Ordering::SeqCst) && seen_columns.len() >= expected_len {
                break;
            }
            if poller_done.load(Ordering::SeqCst) {
                if seen_columns.len() == before_seen {
                    idle_after_done_since.get_or_insert_with(Instant::now);
                } else {
                    idle_after_done_since = None;
                }
                if idle_after_done_since
                    .is_some_and(|started| started.elapsed() > Duration::from_secs(3))
                {
                    break;
                }
            }
        }

        let expected = poller_expected.len();
        (seen_columns, poller_expected.as_ref().clone(), expected)
    });

    let mut handles = Vec::new();
    for worker in 0..workers {
        let db = db.clone();
        let barrier = barrier.clone();
        handles.push(thread::spawn(move || {
            barrier.wait();
            for i in 0..iterations {
                let col = format!("c_{worker}_{i}");
                db.execute(
                    "INSERT INTO shared (id, val) VALUES ($id, 'data')",
                    &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
                )
                .unwrap();
                db.execute(
                    &format!("ALTER TABLE shared ADD COLUMN {col} TEXT"),
                    &empty(),
                )
                .unwrap();
            }
        }));
    }

    for handle in handles {
        handle.join().unwrap();
    }
    done.store(true, Ordering::SeqCst);
    let (seen_columns, expected_columns, expected) = poller.join().unwrap();

    assert_eq!(expected_columns.len(), expected);
    for column in expected_columns {
        assert!(
            seen_columns.contains(&column),
            "sync consumer missed ALTER TABLE DDL for added column {column}"
        );
    }
}

#[test]
fn sql_17_sync_watermark_does_not_skip_ddl() {
    let db = Arc::new(Database::open_memory());
    db.execute(
        "CREATE TABLE shared (id UUID PRIMARY KEY, val TEXT)",
        &empty(),
    )
    .unwrap();

    let barrier = Arc::new(Barrier::new(3));
    let done = Arc::new(AtomicBool::new(false));
    let expected_tables: Vec<String> = (0..120).map(|i| format!("watermark_race_{i}")).collect();

    let poller_db = db.clone();
    let poller_done = done.clone();
    let poller_expected = Arc::new(expected_tables.clone());
    let poller_barrier = barrier.clone();
    let poller = thread::spawn(move || {
        let mut watermark = Lsn(0);
        let mut seen_tables = std::collections::HashSet::new();
        let mut idle_after_done_since = None;
        poller_barrier.wait();

        loop {
            let expected_len = poller_expected.len();
            let changes = poller_db.changes_since(watermark);
            let before_seen = seen_tables.len();
            if !changes.ddl.is_empty() || !changes.rows.is_empty() {
                for ddl in &changes.ddl {
                    if matches!(
                        ddl,
                        contextdb_engine::sync_types::DdlChange::CreateTable { .. }
                    ) {
                        seen_tables.insert(ddl_name(ddl));
                    }
                }
                if let Some(lsn) = max_non_ddl_lsn(&changes) {
                    watermark = lsn;
                }
            } else {
                thread::yield_now();
            }

            if poller_done.load(Ordering::SeqCst) && seen_tables.len() >= expected_len {
                break;
            }
            if poller_done.load(Ordering::SeqCst) {
                if seen_tables.len() == before_seen {
                    idle_after_done_since.get_or_insert_with(Instant::now);
                } else {
                    idle_after_done_since = None;
                }
                if idle_after_done_since
                    .is_some_and(|started| started.elapsed() > Duration::from_secs(3))
                {
                    break;
                }
            }
        }

        let expected = poller_expected.as_ref().clone();
        (seen_tables, expected)
    });

    let ddl_db = db.clone();
    let ddl_barrier = barrier.clone();
    let ddl_thread = thread::spawn(move || {
        ddl_barrier.wait();
        for i in 0..120 {
            let table = format!("watermark_race_{i}");
            ddl_db
                .execute(
                    &format!("CREATE TABLE {table} (id UUID PRIMARY KEY, val TEXT)"),
                    &empty(),
                )
                .unwrap();
        }
    });

    let dml_db = db.clone();
    let dml_barrier = barrier.clone();
    let dml_thread = thread::spawn(move || {
        dml_barrier.wait();
        for _ in 0..400 {
            dml_db
                .execute(
                    "INSERT INTO shared (id, val) VALUES ($id, 'shared')",
                    &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
                )
                .unwrap();
        }
    });

    ddl_thread.join().unwrap();
    dml_thread.join().unwrap();
    done.store(true, Ordering::SeqCst);
    let (seen_tables, expected) = poller.join().unwrap();

    for table in expected {
        assert!(
            seen_tables.contains(&table),
            "watermark advance skipped CREATE TABLE DDL for {table}"
        );
    }
}

#[test]
fn disk_01_set_disk_limit_parses() {
    let db = Database::open_memory();
    let result = db.execute("SET DISK_LIMIT '1G'", &empty());
    assert!(result.is_ok(), "SET DISK_LIMIT must parse: {result:?}");
}

#[test]
fn disk_02_show_disk_limit_parses() {
    let db = Database::open_memory();
    let result = db.execute("SHOW DISK_LIMIT", &empty()).unwrap();
    assert_eq!(
        result.columns,
        vec!["limit", "used", "available", "startup_ceiling"]
    );
    assert_eq!(result.rows.len(), 1);
}

#[test]
fn disk_03_disk_limit_noop_for_memory() {
    let db = Database::open_memory();
    db.execute("SET DISK_LIMIT '1M'", &empty()).unwrap();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, payload TEXT)",
        &empty(),
    )
    .unwrap();
    let payload = "x".repeat(128 * 1024);
    let insert = db.execute(
        "INSERT INTO items (id, payload) VALUES ($id, $payload)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("payload", Value::Text(payload)),
        ]),
    );
    assert!(
        insert.is_ok(),
        "in-memory databases must ignore disk limits: {insert:?}"
    );

    let result = db.execute("SHOW DISK_LIMIT", &empty()).unwrap();
    assert_eq!(
        result.columns,
        vec!["limit", "used", "available", "startup_ceiling"]
    );
    assert!(
        match &result.rows[0][0] {
            Value::Null => true,
            Value::Text(s) if s == "none" => true,
            _ => false,
        },
        "in-memory SHOW DISK_LIMIT must report no active limit: {:?}",
        result.rows[0]
    );
}

#[test]
fn disk_04_insert_rejected_when_over_disk_budget() {
    let tmp = TempDir::new().expect("tempdir");
    let db_path = tmp.path().join("disk_04.db");
    let db = Database::open(&db_path).unwrap();
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, payload TEXT)",
        &empty(),
    )
    .unwrap();

    let limit_kib = disk_limit_kib_for_path(&db_path, 64);
    db.execute(&format!("SET DISK_LIMIT '{limit_kib}K'"), &empty())
        .unwrap();

    let payload = "x".repeat(16 * 1024);
    let mut inserted = 0usize;
    let mut failure = None;
    for _ in 0..64 {
        match db.execute(
            "INSERT INTO items (id, payload) VALUES ($id, $payload)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("payload", Value::Text(payload.clone())),
            ]),
        ) {
            Ok(_) => inserted += 1,
            Err(err) => {
                failure = Some(err.to_string());
                break;
            }
        }
    }

    assert!(
        inserted > 0,
        "disk budget should allow at least one insert before rejecting writes"
    );
    let err = failure.expect("eventually expected disk budget rejection");
    assert!(
        err.to_lowercase().contains("disk budget"),
        "error must mention disk budget, got: {err}"
    );
}

#[test]
fn disk_05_disk_limit_persists_across_reopen() {
    let tmp = TempDir::new().expect("tempdir");
    let db_path = tmp.path().join("disk_05.db");
    let configured_limit_bytes = {
        let db = Database::open(&db_path).unwrap();
        db.execute(
            "CREATE TABLE items (id UUID PRIMARY KEY, payload TEXT)",
            &empty(),
        )
        .unwrap();
        let limit_kib = disk_limit_kib_for_path(&db_path, 64);
        let configured_limit_bytes = (limit_kib * 1024) as i64;
        db.execute(&format!("SET DISK_LIMIT '{limit_kib}K'"), &empty())
            .unwrap();
        let before = db.execute("SHOW DISK_LIMIT", &empty()).unwrap();
        assert!(
            before.rows[0].contains(&Value::Int64(configured_limit_bytes)),
            "SHOW DISK_LIMIT must reflect configured limit before reopen: {:?}",
            before.rows
        );
        db.close().unwrap();
        configured_limit_bytes
    };

    let reopened = Database::open(&db_path).unwrap();
    let after = reopened.execute("SHOW DISK_LIMIT", &empty()).unwrap();
    assert!(
        after.rows[0].contains(&Value::Int64(configured_limit_bytes)),
        "SHOW DISK_LIMIT must reflect persisted limit after reopen: {:?}",
        after.rows
    );

    let payload = "x".repeat(16 * 1024);
    let mut failure = None;
    for _ in 0..64 {
        match reopened.execute(
            "INSERT INTO items (id, payload) VALUES ($id, $payload)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("payload", Value::Text(payload.clone())),
            ]),
        ) {
            Ok(_) => {}
            Err(err) => {
                failure = Some(err.to_string());
                break;
            }
        }
    }
    let err = failure.expect("persisted disk limit must still reject writes after reopen");
    assert!(
        err.to_lowercase().contains("disk budget"),
        "reopened file-backed database must still enforce persisted disk limit: {err}"
    );
}

#[test]
fn disk_06_sync_pull_rejected_when_over_disk_budget() {
    let edge_tmp = TempDir::new().expect("edge tempdir");
    let server_tmp = TempDir::new().expect("server tempdir");
    let edge_path = edge_tmp.path().join("edge.db");
    let server_path = server_tmp.path().join("server.db");

    let edge = Database::open(&edge_path).unwrap();
    edge.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, payload TEXT)",
        &empty(),
    )
    .unwrap();
    for _ in 0..24 {
        edge.execute(
            "INSERT INTO items (id, payload) VALUES ($id, $payload)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("payload", Value::Text("x".repeat(8 * 1024))),
            ]),
        )
        .unwrap();
    }
    let changes = edge.changes_since(Lsn(0));

    let server = Database::open(&server_path).unwrap();
    server
        .execute(
            "CREATE TABLE items (id UUID PRIMARY KEY, payload TEXT)",
            &empty(),
        )
        .unwrap();
    server
        .execute(
            "INSERT INTO items (id, payload) VALUES ($id, $payload)",
            &params(vec![
                ("id", Value::Uuid(Uuid::new_v4())),
                ("payload", Value::Text("prime".repeat(1024))),
            ]),
        )
        .unwrap();
    let limit_kib = (std::fs::metadata(&server_path).unwrap().len() / 1024).max(1);
    server
        .execute(&format!("SET DISK_LIMIT '{limit_kib}K'"), &empty())
        .unwrap();
    server.close().unwrap();

    let server = Database::open(&server_path).unwrap();

    let result = server.apply_changes(
        changes,
        &contextdb_engine::sync_types::ConflictPolicies::uniform(
            contextdb_engine::sync_types::ConflictPolicy::LatestWins,
        ),
    );
    assert!(
        result.is_err(),
        "sync pull must fail when disk budget blocks persistence"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.to_lowercase().contains("disk budget"),
        "sync pull failure must mention disk budget, got: {err}"
    );

    let count = server
        .execute("SELECT COUNT(*) FROM items", &empty())
        .unwrap()
        .rows[0][0]
        .clone();
    assert_eq!(
        count,
        Value::Int64(1),
        "failed sync pull must not make remote rows visible on the server"
    );
}

#[test]
fn sql_09_vector_text_coercion() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE docs (id UUID PRIMARY KEY, embedding VECTOR(3))",
        &empty(),
    )
    .unwrap();

    let id_a = Uuid::from_u128(9001);
    let id_b = Uuid::from_u128(9002);

    db.execute(
        "INSERT INTO docs (id, embedding) VALUES ($id, $embedding)",
        &params(vec![
            ("id", Value::Uuid(id_a)),
            ("embedding", Value::Vector(vec![0.1, 0.2, 0.3])),
        ]),
    )
    .unwrap();

    db.execute(
        "INSERT INTO docs (id, embedding) VALUES ($id, '[0.4, 0.5, 0.6]')",
        &params(vec![("id", Value::Uuid(id_b))]),
    )
    .unwrap();

    let rows = db
        .execute("SELECT id, embedding FROM docs ORDER BY id", &empty())
        .unwrap();
    let id_idx = rows.columns.iter().position(|c| c == "id").unwrap();
    let embedding_idx = rows.columns.iter().position(|c| c == "embedding").unwrap();

    assert_eq!(rows.rows.len(), 2);
    assert_eq!(rows.rows[0][id_idx], Value::Uuid(id_a));
    assert!(matches!(rows.rows[0][embedding_idx], Value::Vector(_)));
    assert_eq!(rows.rows[1][id_idx], Value::Uuid(id_b));
    assert!(
        matches!(rows.rows[1][embedding_idx], Value::Vector(_)),
        "quoted vector literal should be coerced to Value::Vector, got {:?}",
        rows.rows[1][embedding_idx]
    );

    let search = db
        .execute(
            "SELECT id FROM docs ORDER BY embedding <=> $query LIMIT 2",
            &params(vec![("query", Value::Vector(vec![0.4, 0.5, 0.6]))]),
        )
        .unwrap();
    let search_id_idx = search.columns.iter().position(|c| c == "id").unwrap();
    let ids: Vec<Value> = search
        .rows
        .iter()
        .map(|r| r[search_id_idx].clone())
        .collect();
    assert!(ids.contains(&Value::Uuid(id_a)));
    assert!(ids.contains(&Value::Uuid(id_b)));
}

#[test]
fn sql_10_edge_dedup_no_relational_leak() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT)",
        &empty(),
    )
    .unwrap();

    let source = Uuid::from_u128(9101);
    let target = Uuid::from_u128(9102);

    db.execute(
        "INSERT INTO edges (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, 'CITES')",
        &params(vec![
            ("id", Value::Uuid(Uuid::from_u128(9103))),
            ("source", Value::Uuid(source)),
            ("target", Value::Uuid(target)),
        ]),
    )
    .unwrap();

    let second = db
        .execute(
            "INSERT INTO edges (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, 'CITES')",
            &params(vec![
                ("id", Value::Uuid(Uuid::from_u128(9104))),
                ("source", Value::Uuid(source)),
                ("target", Value::Uuid(target)),
            ]),
        )
        .unwrap();

    let count = db
        .execute(
            "SELECT COUNT(*) FROM edges WHERE source_id = $source AND target_id = $target AND edge_type = 'CITES'",
            &params(vec![
                ("source", Value::Uuid(source)),
                ("target", Value::Uuid(target)),
            ]),
        )
        .unwrap();

    assert_eq!(
        count.rows[0][0],
        Value::Int64(1),
        "duplicate logical edge should not leave a second relational row"
    );
    assert_eq!(
        second.rows_affected, 0,
        "deduped second edge insert should report zero affected rows"
    );
}

#[test]
fn sql_11_upsert_set_clause_values() {
    let db = Database::open_memory();
    db.execute("CREATE TABLE kv (id UUID PRIMARY KEY, val TEXT)", &empty())
        .unwrap();

    let id = Uuid::from_u128(9201);
    db.execute(
        "INSERT INTO kv (id, val) VALUES ($id, 'original')",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();

    db.execute(
        "INSERT INTO kv (id, val) VALUES ($id, 'from-insert') ON CONFLICT (id) DO UPDATE SET val = 'from-update'",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();

    let out = db
        .execute(
            "SELECT val FROM kv WHERE id = $id",
            &params(vec![("id", Value::Uuid(id))]),
        )
        .unwrap();
    assert_eq!(out.rows.len(), 1);
    assert_eq!(
        out.rows[0][0],
        Value::Text("from-update".to_string()),
        "upsert should apply SET clause values, not the INSERT value map"
    );
}

#[test]
fn sql_12_not_between() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE scores (id UUID PRIMARY KEY, val REAL)",
        &empty(),
    )
    .unwrap();

    for (id, val) in [
        (Uuid::from_u128(9301), 0.1_f64),
        (Uuid::from_u128(9302), 0.5_f64),
        (Uuid::from_u128(9303), 0.9_f64),
    ] {
        db.execute(
            "INSERT INTO scores (id, val) VALUES ($id, $val)",
            &params(vec![("id", Value::Uuid(id)), ("val", Value::Float64(val))]),
        )
        .unwrap();
    }

    let out = db
        .execute(
            "SELECT val FROM scores WHERE val NOT BETWEEN 0.3 AND 0.7 ORDER BY val",
            &empty(),
        )
        .unwrap();

    let vals: Vec<Value> = out.rows.into_iter().map(|r| r[0].clone()).collect();
    assert_eq!(vals, vec![Value::Float64(0.1), Value::Float64(0.9)]);
}

#[test]
fn sql_13_null_in_nullable_uuid() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE refs (id UUID PRIMARY KEY, parent_id UUID)",
        &empty(),
    )
    .unwrap();

    let id = Uuid::from_u128(9401);
    db.execute(
        "INSERT INTO refs (id, parent_id) VALUES ($id, NULL)",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();

    let out = db
        .execute(
            "SELECT parent_id FROM refs WHERE id = $id",
            &params(vec![("id", Value::Uuid(id))]),
        )
        .unwrap();
    assert_eq!(out.rows.len(), 1);
    assert_eq!(out.rows[0][0], Value::Null);
}

#[test]
fn integrity_01_text_memory_estimate_not_pathologically_high() {
    let accountant = Arc::new(MemoryAccountant::with_budget(32 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());
    db.execute(
        "CREATE TABLE docs (id UUID PRIMARY KEY, body TEXT)",
        &empty(),
    )
    .unwrap();

    let body = "x".repeat(1024);
    let result = db.execute(
        "INSERT INTO docs (id, body) VALUES ($id, $body)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("body", Value::Text(body)),
        ]),
    );
    assert!(
        result.is_ok(),
        "1KiB TEXT insert should fit within a 32KiB budget: {result:?}"
    );
    assert!(
        accountant.usage().used < 16 * 1024,
        "1KiB TEXT row should not consume pathological memory, got {} bytes",
        accountant.usage().used
    );
}

#[test]
fn integrity_02_upsert_noop_does_not_leak_memory() {
    let accountant = Arc::new(MemoryAccountant::with_budget(12 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());
    db.execute("CREATE TABLE kv (id UUID PRIMARY KEY, val TEXT)", &empty())
        .unwrap();

    let id = Uuid::new_v4();
    db.execute(
        "INSERT INTO kv (id, val) VALUES ($id, 'same')",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();
    let baseline = accountant.usage().used;

    for _ in 0..20 {
        db.execute(
            "INSERT INTO kv (id, val) VALUES ($id, 'same') ON CONFLICT (id) DO UPDATE SET val = 'same'",
            &params(vec![("id", Value::Uuid(id))]),
        )
        .unwrap();
    }

    let used = accountant.usage().used;
    assert!(
        used <= baseline + 256,
        "noop upserts must not leak memory: baseline={baseline}, used={used}"
    );
}

#[test]
fn integrity_03_retain_pruning_releases_memory() {
    let accountant = Arc::new(MemoryAccountant::with_budget(256 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());
    db.execute(
        "CREATE TABLE obs (id UUID PRIMARY KEY, data TEXT) RETAIN 1 SECONDS",
        &empty(),
    )
    .unwrap();

    let baseline = accountant.usage().used;
    db.execute(
        "INSERT INTO obs (id, data) VALUES ($id, $data)",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("data", Value::Text("x".repeat(4096))),
        ]),
    )
    .unwrap();
    let used_after_insert = accountant.usage().used;
    assert!(used_after_insert > baseline);

    std::thread::sleep(Duration::from_millis(1100));
    let pruned = db.run_pruning_cycle();
    assert_eq!(pruned, 1, "expired row must be pruned");

    let used_after_prune = accountant.usage().used;
    assert!(
        used_after_prune + 512 < used_after_insert,
        "pruning must release row memory: before={used_after_insert}, after={used_after_prune}"
    );
    assert_eq!(
        db.execute("SELECT COUNT(*) FROM obs", &empty())
            .unwrap()
            .rows[0][0],
        Value::Int64(0)
    );
}

#[test]
fn integrity_04_edge_delete_releases_memory() {
    let accountant = Arc::new(MemoryAccountant::with_budget(256 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());

    let source = Uuid::new_v4();
    let target = Uuid::new_v4();
    let baseline = accountant.usage().used;

    let tx = db.begin();
    assert!(
        db.insert_edge(tx, source, target, "REL".to_string(), HashMap::new())
            .unwrap()
    );
    db.commit(tx).unwrap();

    let used_after_insert = accountant.usage().used;
    assert!(used_after_insert > baseline);

    let tx = db.begin();
    db.delete_edge(tx, source, target, "REL").unwrap();
    db.commit(tx).unwrap();

    let used_after_delete = accountant.usage().used;
    assert!(
        used_after_delete + 128 < used_after_insert,
        "edge delete must release adjacency memory: before={used_after_insert}, after={used_after_delete}"
    );
}

#[test]
fn integrity_05_drop_table_releases_edge_memory() {
    let accountant = Arc::new(MemoryAccountant::with_budget(256 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());
    db.execute(
        "CREATE TABLE edges (id UUID PRIMARY KEY, source_id UUID, target_id UUID, edge_type TEXT)",
        &empty(),
    )
    .unwrap();

    let source = Uuid::new_v4();
    let target = Uuid::new_v4();
    db.execute(
        "INSERT INTO edges (id, source_id, target_id, edge_type) VALUES ($id, $source, $target, 'REL')",
        &params(vec![
            ("id", Value::Uuid(Uuid::new_v4())),
            ("source", Value::Uuid(source)),
            ("target", Value::Uuid(target)),
        ]),
    )
    .unwrap();
    let used_after_insert = accountant.usage().used;

    db.execute("DROP TABLE edges", &empty()).unwrap();

    assert!(
        accountant.usage().used + 128 < used_after_insert,
        "DROP TABLE must release edge allocations: before={used_after_insert}, after={}",
        accountant.usage().used
    );
    let bfs = db
        .query_bfs(
            source,
            Some(&["REL".to_string()]),
            contextdb_core::Direction::Outgoing,
            1,
            db.snapshot(),
        )
        .unwrap();
    assert_eq!(
        bfs.nodes.len(),
        0,
        "dropped edge table must not leave graph edges behind"
    );
}

#[test]
fn integrity_06_create_table_honors_disk_budget() {
    let tmp = TempDir::new().unwrap();
    let path = tmp.path().join("integrity-create-table.db");
    let db = Database::open(&path).unwrap();

    let limit_kib = disk_limit_kib_for_path(&path, 0);
    db.execute(&format!("SET DISK_LIMIT '{limit_kib}K'"), &empty())
        .unwrap();

    let result = db.execute("CREATE TABLE blocked (id UUID PRIMARY KEY)", &empty());
    assert!(
        result.is_err(),
        "CREATE TABLE must fail when disk budget is already exhausted"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.to_lowercase().contains("disk budget"),
        "disk-budget rejection must mention disk budget, got: {err}"
    );
    assert!(
        db.table_meta("blocked").is_none(),
        "failed CREATE TABLE must not leave table metadata behind"
    );
}

#[test]
fn integrity_07_alter_table_honors_disk_budget() {
    let tmp = TempDir::new().unwrap();
    let path = tmp.path().join("integrity-alter-table.db");
    let db = Database::open(&path).unwrap();
    db.execute("CREATE TABLE items (id UUID PRIMARY KEY)", &empty())
        .unwrap();

    let limit_kib = disk_limit_kib_for_path(&path, 0);
    db.execute(&format!("SET DISK_LIMIT '{limit_kib}K'"), &empty())
        .unwrap();

    let result = db.execute("ALTER TABLE items ADD COLUMN note TEXT", &empty());
    assert!(
        result.is_err(),
        "ALTER TABLE must fail when disk budget is already exhausted"
    );
    let err = result.unwrap_err().to_string();
    assert!(
        err.to_lowercase().contains("disk budget"),
        "disk-budget rejection must mention disk budget, got: {err}"
    );
    let meta = db.table_meta("items").unwrap();
    assert!(
        meta.columns.iter().all(|c| c.name != "note"),
        "failed ALTER TABLE must not mutate schema"
    );
}

#[test]
fn integrity_08_upsert_insert_indexes_vector() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE docs (id UUID PRIMARY KEY, embedding VECTOR(3))",
        &empty(),
    )
    .unwrap();

    let id = Uuid::new_v4();
    db.execute(
        "INSERT INTO docs (id, embedding) VALUES ($id, '[1.0, 0.0, 0.0]')",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();
    db.execute(
        "INSERT INTO docs (id, embedding) VALUES ($id, '[0.0, 1.0, 0.0]') ON CONFLICT (id) DO UPDATE SET embedding = '[0.0, 1.0, 0.0]'",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();

    let result = db
        .execute(
            "SELECT id FROM docs ORDER BY embedding <=> $query LIMIT 1",
            &params(vec![("query", Value::Vector(vec![0.0, 1.0, 0.0]))]),
        )
        .unwrap()
        .rows;
    assert_eq!(
        result.len(),
        1,
        "vector search must still find the upserted row"
    );
    assert_eq!(
        result[0][0],
        Value::Uuid(id),
        "vector search must resolve to the row updated by ON CONFLICT DO UPDATE"
    );
}

#[test]
fn integrity_09_drop_table_removes_vectors() {
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE docs (id UUID PRIMARY KEY, embedding VECTOR(3))",
        &empty(),
    )
    .unwrap();

    let id = Uuid::new_v4();
    db.execute(
        "INSERT INTO docs (id, embedding) VALUES ($id, '[0.1, 0.2, 0.3]')",
        &params(vec![("id", Value::Uuid(id))]),
    )
    .unwrap();
    let row_id = db
        .point_lookup("docs", "id", &Value::Uuid(id), db.snapshot())
        .unwrap()
        .expect("row must exist")
        .row_id;
    assert!(
        db.live_vector_entry(row_id, db.snapshot()).is_some(),
        "vector must exist before DROP TABLE"
    );

    db.execute("DROP TABLE docs", &empty()).unwrap();

    assert!(
        db.live_vector_entry(row_id, db.snapshot()).is_none(),
        "DROP TABLE must remove vector entries for dropped rows"
    );
}

#[test]
fn integrity_10_failed_insert_does_not_leak_memory() {
    let accountant = Arc::new(MemoryAccountant::with_budget(12 * 1024));
    let db = Database::open_memory_with_accountant(accountant.clone());
    db.execute(
        "CREATE TABLE items (id UUID PRIMARY KEY, name TEXT UNIQUE)",
        &empty(),
    )
    .unwrap();

    db.execute(
        "INSERT INTO items (id, name) VALUES ($id, 'dup')",
        &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
    )
    .unwrap();
    let baseline = accountant.usage().used;

    for _ in 0..20 {
        db.execute(
            "INSERT INTO items (id, name) VALUES ($id, 'dup')",
            &params(vec![("id", Value::Uuid(Uuid::new_v4()))]),
        )
        .unwrap();
    }

    let used = accountant.usage().used;
    assert!(
        used <= baseline + 256,
        "duplicate no-op inserts must not leak memory: baseline={baseline}, used={used}"
    );
}

// ======== T20 ========
#[test]
fn test_coerce_uuid_name_based_still_works_post_catchall_removal() {
    use contextdb_core::Value;
    use contextdb_engine::Database;
    use std::collections::HashMap;
    use uuid::Uuid;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute(
        "CREATE TABLE t (id INTEGER, user_id INTEGER, other_id INTEGER, plain INTEGER)",
        &empty,
    )
    .expect("CREATE TABLE with four INTEGER columns must succeed");

    let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
    let expected_uuid = Uuid::parse_str(uuid_str).expect("fixture uuid must parse");

    let mut row: HashMap<String, Value> = HashMap::new();
    row.insert("id".to_string(), Value::Text(uuid_str.into()));
    row.insert("user_id".to_string(), Value::Text(uuid_str.into()));
    row.insert("other_id".to_string(), Value::Text(uuid_str.into()));
    row.insert("plain".to_string(), Value::Text(uuid_str.into()));

    db.execute(
        "INSERT INTO t (id, user_id, other_id, plain) VALUES ($id, $user_id, $other_id, $plain)",
        &row,
    )
    .expect("INSERT must succeed under UUID name-based coercion");

    let result = db
        .execute("SELECT * FROM t", &empty)
        .expect("SELECT * FROM t must succeed");
    assert_eq!(result.rows.len(), 1, "exactly one row expected");
    let row_vals = &result.rows[0];
    let col_idx = |name: &str| {
        result
            .columns
            .iter()
            .position(|c| c == name)
            .unwrap_or_else(|| panic!("column {name:?} must exist in result"))
    };

    assert_eq!(
        row_vals[col_idx("id")],
        Value::Uuid(expected_uuid),
        "id column must coerce Text → Uuid",
    );
    assert_eq!(
        row_vals[col_idx("user_id")],
        Value::Uuid(expected_uuid),
        "user_id column must coerce Text → Uuid (name ends in _id)",
    );
    assert_eq!(
        row_vals[col_idx("other_id")],
        Value::Uuid(expected_uuid),
        "other_id column must coerce Text → Uuid (name ends in _id)",
    );
    assert_eq!(
        row_vals[col_idx("plain")],
        Value::Text(uuid_str.into()),
        "plain column (no _id suffix) must retain Value::Text without coercion",
    );
}

// ======== T21 ========
#[test]
fn where_txid_bound_int64_returns_rows() {
    use contextdb_core::{TxId, Value};
    use contextdb_engine::Database;
    use std::collections::HashMap;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (x TXID NOT NULL)", &empty)
        .expect("CREATE TABLE t (x TXID NOT NULL) must parse");

    // Drive watermark past 200 so inserts are allowed.
    db.execute("CREATE TABLE bump (id UUID PRIMARY KEY, n INTEGER)", &empty)
        .unwrap();
    for n in 0..250i64 {
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("id".to_string(), Value::Uuid(uuid::Uuid::new_v4()));
        r.insert("n".to_string(), Value::Int64(n));
        db.execute("INSERT INTO bump (id, n) VALUES ($id, $n)", &r)
            .unwrap();
    }

    // Insert the three TxId rows via library API.
    for tx_val in &[TxId(10), TxId(50), TxId(200)] {
        let tx = db.begin();
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("x".to_string(), Value::TxId(*tx_val));
        db.insert_row(tx, "t", r)
            .unwrap_or_else(|e| panic!("insert Value::TxId({tx_val:?}) must succeed: {e:?}"));
        db.commit(tx).expect("commit must succeed");
    }

    let mut bind: HashMap<String, Value> = HashMap::new();
    bind.insert("bound".to_string(), Value::Int64(100));
    let result = db
        .execute("SELECT * FROM t WHERE x > $bound", &bind)
        .expect("SELECT with bound Int64 must succeed on TXID column");

    assert_eq!(
        result.rows.len(),
        1,
        "exactly one row must match x > 100 (only TxId(200))",
    );
    let x_idx = result
        .columns
        .iter()
        .position(|c| c == "x")
        .expect("result must have column \"x\"");
    assert_eq!(
        result.rows[0][x_idx],
        Value::TxId(TxId(200)),
        "the one matching row must be Value::TxId(TxId(200))",
    );
}

// ======== T22 ========
#[test]
fn where_txid_negative_literal_below_all() {
    use contextdb_core::{TxId, Value};
    use contextdb_engine::Database;
    use std::collections::HashMap;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (x TXID NOT NULL)", &empty)
        .expect("CREATE TABLE t (x TXID NOT NULL) must parse");

    // Bump watermark past 200.
    db.execute("CREATE TABLE bump (id UUID PRIMARY KEY, n INTEGER)", &empty)
        .unwrap();
    for n in 0..250i64 {
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("id".to_string(), Value::Uuid(uuid::Uuid::new_v4()));
        r.insert("n".to_string(), Value::Int64(n));
        db.execute("INSERT INTO bump (id, n) VALUES ($id, $n)", &r)
            .unwrap();
    }

    for tx_val in &[TxId(10), TxId(50), TxId(200)] {
        let tx = db.begin();
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("x".to_string(), Value::TxId(*tx_val));
        db.insert_row(tx, "t", r)
            .unwrap_or_else(|e| panic!("insert Value::TxId({tx_val:?}) must succeed: {e:?}"));
        db.commit(tx).expect("commit must succeed");
    }

    let mut bind: HashMap<String, Value> = HashMap::new();
    bind.insert("bound".to_string(), Value::Int64(-1));
    let result = db
        .execute("SELECT COUNT(*) AS c FROM t WHERE x > $bound", &bind)
        .expect("COUNT(*) with negative bound must succeed on TXID column");

    assert_eq!(
        result.rows.len(),
        1,
        "COUNT(*) result must have exactly one row",
    );
    let c_idx = result
        .columns
        .iter()
        .position(|c| c == "c")
        .expect("result must have the aliased count column \"c\"");
    assert_eq!(
        result.rows[0][c_idx],
        Value::Int64(3),
        "COUNT(*) of TxIds > -1 must equal 3 (all three rows match)",
    );
}

// ======== T23 ========
#[test]
fn where_txid_text_literal_returns_no_rows() {
    use contextdb_core::{TxId, Value};
    use contextdb_engine::Database;
    use std::collections::HashMap;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (x TXID NOT NULL)", &empty)
        .expect("CREATE TABLE t (x TXID NOT NULL) must parse");

    // Bump watermark past 42.
    db.execute("CREATE TABLE bump (id UUID PRIMARY KEY, n INTEGER)", &empty)
        .unwrap();
    for n in 0..50i64 {
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("id".to_string(), Value::Uuid(uuid::Uuid::new_v4()));
        r.insert("n".to_string(), Value::Int64(n));
        db.execute("INSERT INTO bump (id, n) VALUES ($id, $n)", &r)
            .unwrap();
    }

    let tx = db.begin();
    let mut r: HashMap<String, Value> = HashMap::new();
    r.insert("x".to_string(), Value::TxId(TxId(42)));
    db.insert_row(tx, "t", r)
        .expect("insert Value::TxId(TxId(42)) must succeed");
    db.commit(tx).expect("commit must succeed");

    // Positive control: prove the row is actually present with x = Value::TxId(TxId(42))
    // before we test the text-bind negative case. This prevents a stub or regression
    // that silently drops inserts from trivially satisfying the "0 rows" assertion below.
    let unfiltered = db
        .execute("SELECT x FROM t", &empty)
        .expect("SELECT x FROM t (no filter) must succeed");
    assert_eq!(
        unfiltered.rows.len(),
        1,
        "positive control: exactly one row must be present after insert",
    );
    assert_eq!(
        unfiltered.rows[0][0],
        Value::TxId(TxId(42)),
        "positive control: the stored x column must be Value::TxId(TxId(42))",
    );

    let mut bind: HashMap<String, Value> = HashMap::new();
    bind.insert("bound".to_string(), Value::Text("42".into()));
    let result = db
        .execute("SELECT * FROM t WHERE x = $bound", &bind)
        .expect("SELECT with Text bound on TXID column must not error — just return empty");

    assert_eq!(
        result.rows.len(),
        0,
        "no rows must be returned — Text must never coerce to TxId; got rows: {:?}",
        result.rows,
    );
}

// ======== T24 ========
#[test]
fn insert_sql_literal_int_into_txid_rejected() {
    use contextdb_core::{Error, Value};
    use contextdb_engine::Database;
    use std::collections::HashMap;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (x TXID NOT NULL)", &empty)
        .expect("CREATE TABLE t (x TXID NOT NULL) must parse");

    let err = db
        .execute("INSERT INTO t (x) VALUES (42)", &empty)
        .expect_err("INSERT INTO t (x) VALUES (42) must be rejected — literal Int64 into TXID");

    match err {
        Error::ColumnTypeMismatch {
            table,
            column,
            expected,
            actual,
        } => {
            assert_eq!(table, "t", "error.table must be \"t\"");
            assert_eq!(column, "x", "error.column must be \"x\"");
            assert_eq!(expected, "TXID", "error.expected must be \"TXID\"");
            assert_eq!(
                actual, "Int64",
                "error.actual must be \"Int64\" (SQL literal 42 parses to Value::Int64)",
            );
        }
        other => panic!("expected Error::ColumnTypeMismatch, got {other:?}",),
    }
}

// ======== T25 ========
#[test]
fn orderby_txid_asc_desc() {
    use contextdb_core::{TxId, Value};
    use contextdb_engine::Database;
    use std::collections::HashMap;

    let empty: HashMap<String, Value> = HashMap::new();
    let db = Database::open_memory();
    db.execute("CREATE TABLE t (x TXID NOT NULL)", &empty)
        .expect("CREATE TABLE t (x TXID NOT NULL) must parse");

    // Bump watermark past 42.
    db.execute("CREATE TABLE bump (id UUID PRIMARY KEY, n INTEGER)", &empty)
        .unwrap();
    for n in 0..50i64 {
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("id".to_string(), Value::Uuid(uuid::Uuid::new_v4()));
        r.insert("n".to_string(), Value::Int64(n));
        db.execute("INSERT INTO bump (id, n) VALUES ($id, $n)", &r)
            .unwrap();
    }

    // Insert out of order: 7, 1, 42, 3.
    for tx_val in &[TxId(7), TxId(1), TxId(42), TxId(3)] {
        let tx = db.begin();
        let mut r: HashMap<String, Value> = HashMap::new();
        r.insert("x".to_string(), Value::TxId(*tx_val));
        db.insert_row(tx, "t", r)
            .unwrap_or_else(|e| panic!("insert Value::TxId({tx_val:?}) must succeed: {e:?}"));
        db.commit(tx).expect("commit must succeed");
    }

    // ASC
    let asc = db
        .execute("SELECT x FROM t ORDER BY x ASC", &empty)
        .expect("SELECT ... ORDER BY x ASC must succeed");
    let x_idx = asc
        .columns
        .iter()
        .position(|c| c == "x")
        .expect("asc result must have column \"x\"");
    let asc_vals: Vec<Value> = asc.rows.iter().map(|r| r[x_idx].clone()).collect();
    assert_eq!(
        asc_vals,
        vec![
            Value::TxId(TxId(1)),
            Value::TxId(TxId(3)),
            Value::TxId(TxId(7)),
            Value::TxId(TxId(42)),
        ],
        "ORDER BY x ASC must sort TxIds by native u64::cmp",
    );

    // DESC
    let desc = db
        .execute("SELECT x FROM t ORDER BY x DESC", &empty)
        .expect("SELECT ... ORDER BY x DESC must succeed");
    let x_idx_d = desc
        .columns
        .iter()
        .position(|c| c == "x")
        .expect("desc result must have column \"x\"");
    let desc_vals: Vec<Value> = desc.rows.iter().map(|r| r[x_idx_d].clone()).collect();
    assert_eq!(
        desc_vals,
        vec![
            Value::TxId(TxId(42)),
            Value::TxId(TxId(7)),
            Value::TxId(TxId(3)),
            Value::TxId(TxId(1)),
        ],
        "ORDER BY x DESC must reverse the ASC sequence",
    );
}