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
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
use super::evaluator::{StratifiedEvaluator, evaluate_not_join};
use super::functions::{AggImpl, FunctionRegistry, apply_builtin_aggregate, value_cmp};
use super::matcher::{PatternMatcher, edn_to_entity_id, edn_to_value};
use super::optimizer;
use super::rules::RuleRegistry;
use super::types::{
AsOf, AttributeSpec, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, Order,
Pattern, Rule, Transaction, UnaryOp, ValidAt, WhereClause, WindowFunc,
};
use crate::graph::FactStorage;
use crate::graph::types::{Fact, TransactOptions, TxId, Value, tx_id_now};
use anyhow::{Result, anyhow};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
/// Returns true if any where clause (at any depth) contains a per-fact
/// pseudo-attribute pattern (ValidFrom / ValidTo / TxCount / TxId).
/// Used to enforce the `:any-valid-time` requirement.
fn query_uses_per_fact_pseudo_attr(query: &DatalogQuery) -> bool {
fn check_clauses(clauses: &[WhereClause]) -> bool {
clauses.iter().any(|c| match c {
WhereClause::Pattern(p) => matches!(
&p.attribute,
AttributeSpec::Pseudo(pa) if pa.is_per_fact()
),
WhereClause::Not(inner) => check_clauses(inner),
WhereClause::NotJoin { clauses: inner, .. } => check_clauses(inner),
WhereClause::Or(branches) => branches.iter().any(|b| check_clauses(b)),
WhereClause::OrJoin { branches, .. } => branches.iter().any(|b| check_clauses(b)),
_ => false,
})
}
check_clauses(&query.where_clauses)
}
/// Recursively collect all `Pattern` clauses from a slice of where clauses,
/// including those nested inside `Not`, `NotJoin`, `Or`, and `OrJoin` bodies.
/// Used by `selective_fact_fetch` to ensure every pattern that references a fact
/// (including not-body patterns) is considered when deciding which indexes to query.
fn collect_all_patterns(clauses: &[WhereClause]) -> Vec<Pattern> {
let mut patterns = Vec::new();
for clause in clauses {
match clause {
WhereClause::Pattern(p) => patterns.push(p.clone()),
WhereClause::Not(inner) => patterns.extend(collect_all_patterns(inner)),
WhereClause::NotJoin { clauses: inner, .. } => {
patterns.extend(collect_all_patterns(inner))
}
WhereClause::Or(branches) | WhereClause::OrJoin { branches, .. } => {
for branch in branches {
patterns.extend(collect_all_patterns(branch));
}
}
WhereClause::RuleInvocation { .. } | WhereClause::Expr { .. } => {}
}
}
patterns
}
/// The result of executing a Datalog command via [`crate::db::Minigraf::execute`].
///
/// Pattern-match on this to distinguish query results from write confirmations:
///
/// ```
/// # use minigraf::{Minigraf, QueryResult};
/// # let db = Minigraf::in_memory().unwrap();
/// # db.execute(r#"(transact [[:alice :person/name "Alice"]])"#).unwrap();
/// match db.execute("(query [:find ?name :where [?e :person/name ?name]])").unwrap() {
/// QueryResult::QueryResults { vars, results } => {
/// for row in &results {
/// println!("{}: {:?}", vars[0], row[0]);
/// }
/// }
/// QueryResult::Transacted(tx_id) => println!("tx {}", tx_id),
/// QueryResult::Retracted(tx_id) => println!("retracted tx {}", tx_id),
/// QueryResult::Ok => {}
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum QueryResult {
/// Transaction completed successfully. The inner value is the transaction ID
/// (Unix milliseconds). Use [`crate::db::Minigraf::current_tx_count`] to retrieve
/// the monotonic counter (`:as-of N` value) after a write.
Transacted(TxId),
/// Retraction completed successfully. The inner value is the transaction ID
/// (Unix milliseconds). Use [`crate::db::Minigraf::current_tx_count`] to retrieve
/// the monotonic counter (`:as-of N` value) after a write.
Retracted(TxId),
/// Query results: list of variable bindings
QueryResults {
/// The variable names in the order they appear in the `:find` clause.
vars: Vec<String>,
/// Each inner `Vec<Value>` is one result row, aligned with `vars`.
results: Vec<Vec<Value>>,
},
/// Acknowledgement for commands that produce no data (e.g. rule definitions
/// inside a [`crate::db::WriteTransaction`]).
Ok,
}
/// Executor for Datalog commands
pub struct DatalogExecutor {
storage: FactStorage,
facts_override: Option<Arc<[Fact]>>,
read_now_floor: Option<i64>,
rules: Arc<RwLock<RuleRegistry>>,
// RwLock pre-wired for 7.7b register_aggregate API.
functions: Arc<RwLock<FunctionRegistry>>,
indexes: Arc<crate::storage::index::Indexes>,
max_derived_facts: usize,
max_results: usize,
}
impl DatalogExecutor {
#[allow(dead_code)]
pub fn new(storage: FactStorage) -> Self {
DatalogExecutor {
storage,
facts_override: None,
read_now_floor: None,
rules: Arc::new(RwLock::new(RuleRegistry::new())),
functions: Arc::new(RwLock::new(FunctionRegistry::with_builtins())),
indexes: Arc::new(crate::storage::index::Indexes::new()),
max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS,
max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS,
}
}
/// Create a `DatalogExecutor` with a shared rule registry and function registry.
///
/// Used by `Minigraf` to share registries across all `execute()` calls.
pub fn new_with_rules_and_functions(
storage: FactStorage,
rules: Arc<RwLock<RuleRegistry>>,
functions: Arc<RwLock<FunctionRegistry>>,
) -> Self {
DatalogExecutor {
storage,
facts_override: None,
read_now_floor: None,
rules,
functions,
indexes: Arc::new(crate::storage::index::Indexes::new()),
max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS,
max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS,
}
}
/// Create a `DatalogExecutor` over a merged fact slice while sharing rules and functions.
pub(crate) fn new_from_facts_with_rules_and_functions(
facts: Arc<[Fact]>,
pending_read_now_floor: Option<i64>,
rules: Arc<RwLock<RuleRegistry>>,
functions: Arc<RwLock<FunctionRegistry>>,
) -> Self {
DatalogExecutor {
storage: FactStorage::new(),
facts_override: Some(facts),
read_now_floor: pending_read_now_floor,
rules,
functions,
indexes: Arc::new(crate::storage::index::Indexes::new()),
max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS,
max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS,
}
}
/// Convenience constructor for tests. Shares `rules` with other executors but creates
/// a fresh `FunctionRegistry::with_builtins()`. Production code uses
/// [`new_with_rules_and_functions`] to share the registry from `Minigraf::Inner`.
#[allow(dead_code)]
pub fn new_with_rules(storage: FactStorage, rules: Arc<RwLock<RuleRegistry>>) -> Self {
Self::new_with_rules_and_functions(
storage,
rules,
Arc::new(RwLock::new(FunctionRegistry::with_builtins())),
)
}
/// Create a `DatalogExecutor` with custom complexity limits.
///
/// Used by `Minigraf` when `OpenOptions` specifies non-default limits.
#[allow(dead_code)]
pub fn new_with_limits(
storage: FactStorage,
rules: Arc<RwLock<RuleRegistry>>,
functions: Arc<RwLock<FunctionRegistry>>,
max_derived_facts: usize,
max_results: usize,
) -> Self {
let indexes = storage.pending_indexes_snapshot();
DatalogExecutor {
storage,
facts_override: None,
read_now_floor: None,
rules,
functions,
indexes: Arc::new(indexes),
max_derived_facts,
max_results,
}
}
/// Set complexity limits on an existing executor.
pub fn set_limits(&mut self, max_derived_facts: usize, max_results: usize) {
self.max_derived_facts = max_derived_facts;
self.max_results = max_results;
}
/// Read-time "now" for query visibility.
///
/// Overlay reads floor the wall clock to the newest staged fact so buffered
/// writes remain visible even if their synthetic metadata is slightly ahead
/// of the current millisecond.
fn read_now(&self) -> i64 {
let now = tx_id_now().cast_signed();
self.read_now_floor.map_or(now, |floor| now.max(floor))
}
/// Execute a Datalog command
pub fn execute(&self, command: DatalogCommand) -> Result<QueryResult> {
match command {
DatalogCommand::Transact(tx) => self.execute_transact(tx),
DatalogCommand::Retract(tx) => self.execute_retract(tx),
DatalogCommand::Query(query) => self.execute_query(query),
DatalogCommand::Rule(rule) => self.execute_rule(rule),
}
}
/// Execute a transact command: add facts to storage
fn execute_transact(&self, tx: Transaction) -> Result<QueryResult> {
// Transaction-level valid-time options (fallback when no per-fact override)
let tx_opts = if tx.valid_from.is_some() || tx.valid_to.is_some() {
Some(TransactOptions::new(tx.valid_from, tx.valid_to))
} else {
None
};
// Collect all facts into a single batch so they share one tx_count.
// Each fact carries its own per-fact opts (or None to fall back to tx_opts).
let mut fact_tuples = Vec::new();
for pattern in tx.facts {
let entity_id =
edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?;
let attribute = match &pattern.attribute {
AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(),
AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")),
AttributeSpec::Pseudo(_) => {
return Err(anyhow!("Cannot transact a pseudo-attribute"));
}
};
let value =
edn_to_value(&pattern.value).map_err(|e| anyhow!("Invalid value: {}", e))?;
let per_fact_opts = if pattern.valid_from.is_some() || pattern.valid_to.is_some() {
Some(TransactOptions::new(pattern.valid_from, pattern.valid_to))
} else {
None
};
fact_tuples.push((entity_id, attribute, value, per_fact_opts));
}
let (tx_id, _tx_count) = self
.storage
.transact_batch(fact_tuples, tx_opts)
.map_err(|e| anyhow!("Transaction failed: {}", e))?;
Ok(QueryResult::Transacted(tx_id))
}
/// Execute a retract command: retract facts from storage
fn execute_retract(&self, tx: Transaction) -> Result<QueryResult> {
let mut fact_tuples = Vec::new();
for pattern in tx.facts {
let entity_id =
edn_to_entity_id(&pattern.entity).map_err(|e| anyhow!("Invalid entity: {}", e))?;
let attribute = match &pattern.attribute {
AttributeSpec::Real(EdnValue::Keyword(k)) => k.clone(),
AttributeSpec::Real(_) => return Err(anyhow!("Attribute must be a keyword")),
AttributeSpec::Pseudo(_) => {
return Err(anyhow!("Cannot transact a pseudo-attribute"));
}
};
let value =
edn_to_value(&pattern.value).map_err(|e| anyhow!("Invalid value: {}", e))?;
fact_tuples.push((entity_id, attribute, value));
}
let (tx_id, _tx_count) = self
.storage
.retract(fact_tuples)
.map_err(|e| anyhow!("Retraction failed: {}", e))?;
Ok(QueryResult::Retracted(tx_id))
}
/// Build a filtered fact snapshot for a query's temporal constraints.
///
/// Step 1: apply transaction-time filter (`:as-of`) — defaults to all facts.
/// Step 2: discard retracted facts within the tx window (`net_asserted_facts`).
/// Step 3: apply valid-time filter (`:valid-at`) — defaults to "currently valid".
///
/// Returns an `Arc<[Fact]>` snapshot. `.clone()` is a cheap Arc refcount increment,
/// so `or`-branches and `not`/`not-join` sub-evaluations share the same allocation.
/// The three steps above are paid exactly once per `execute_query` /
/// `execute_query_with_rules` call.
///
/// Step 1 uses selective index-backed fetches when query patterns bind concrete entities
/// or attributes (up to 4 distinct lookups); falls back to `get_all_facts()` otherwise.
/// Step 2 (caching `net_asserted_facts()`) remains a future optimisation opportunity.
fn filter_facts_for_query(&self, query: &DatalogQuery) -> Result<Arc<[Fact]>> {
let now = self.read_now();
let source_facts: Vec<Fact> = match (&self.facts_override, query.as_of.as_ref()) {
(Some(facts), Some(as_of)) => {
crate::graph::storage::filter_facts_as_of(facts.iter().cloned().collect(), as_of)
}
(Some(facts), None) => facts.iter().cloned().collect(),
(None, Some(as_of)) => self.storage.get_facts_as_of(as_of)?,
(None, None) => {
// Selective fetch is only safe when no rule invocations are present —
// rules require the full fact base to evaluate correctly.
if !query.uses_rules() {
let patterns = collect_all_patterns(&query.where_clauses);
match self.selective_fact_fetch(&patterns, 4) {
Some(facts) => facts,
None => self.storage.get_all_facts()?,
}
} else {
self.storage.get_all_facts()?
}
}
};
let tx_filtered = source_facts;
// Step 2: compute net-asserted view — for each (entity, attribute, value) triple,
// keep it only if the record with the highest tx_count is an assertion.
// This correctly hides facts that have been retracted.
let asserted = crate::graph::storage::net_asserted_facts(tx_filtered);
// Step 3: valid-time filter
let valid_filtered: Vec<Fact> = match &query.valid_at {
Some(ValidAt::Timestamp(t)) => asserted
.into_iter()
.filter(|f| f.valid_from <= *t && *t < f.valid_to)
.collect(),
Some(ValidAt::AnyValidTime) => asserted,
Some(ValidAt::Slot(_)) => {
return Err(anyhow!(
"internal: unsubstituted :valid-at bind slot reached the executor"
));
}
None => asserted
.into_iter()
.filter(|f| f.valid_from <= now && now < f.valid_to)
.collect(),
};
Ok(Arc::from(valid_filtered))
}
/// Attempt a selective index-backed fact fetch for the given patterns.
///
/// Inspects `patterns` for bound entity literals (UUID or keyword → deterministic UUID)
/// and bound attribute keywords. If the total distinct lookup count is 0 (nothing bound)
/// or exceeds `threshold` (too many — full scan is cheaper), returns `None`.
/// Otherwise returns `Some(facts)` — the union of all selectively fetched facts,
/// deduplicated by `(entity, attribute, tx_count)`.
fn selective_fact_fetch(&self, patterns: &[Pattern], threshold: usize) -> Option<Vec<Fact>> {
use std::collections::HashSet;
let mut entity_ids: HashSet<uuid::Uuid> = HashSet::new();
let mut attributes: HashSet<String> = HashSet::new();
for pattern in patterns {
// Bound entity: UUID literal or keyword that resolves deterministically
match &pattern.entity {
EdnValue::Uuid(u) => {
entity_ids.insert(*u);
}
EdnValue::Keyword(_) => {
if let Ok(uid) = edn_to_entity_id(&pattern.entity) {
entity_ids.insert(uid);
}
}
_ => {}
}
// Bound attribute: non-variable keyword
if let AttributeSpec::Real(EdnValue::Keyword(attr)) = &pattern.attribute {
attributes.insert(attr.clone());
}
}
let total = entity_ids.len() + attributes.len();
if total == 0 || total > threshold {
return None;
}
// Dedup key: (entity uuid, attribute string, tx_count) — avoids Value debug formatting.
let mut seen: HashSet<(uuid::Uuid, String, u64)> = HashSet::new();
let mut all_facts: Vec<Fact> = Vec::new();
for uid in &entity_ids {
match self.storage.get_facts_by_entity(uid) {
Ok(facts) => {
for fact in facts {
let key = (fact.entity, fact.attribute.clone(), fact.tx_count);
if seen.insert(key) {
all_facts.push(fact);
}
}
}
Err(_) => return None,
}
}
for attr in &attributes {
match self.storage.get_facts_by_attribute(attr) {
Ok(facts) => {
for fact in facts {
let key = (fact.entity, fact.attribute.clone(), fact.tx_count);
if seen.insert(key) {
all_facts.push(fact);
}
}
}
Err(_) => return None,
}
}
Some(all_facts)
}
/// Execute a query: find matching facts and return specified variables
fn execute_query(&self, query: DatalogQuery) -> Result<QueryResult> {
// Check if query uses rules
if query.uses_rules() {
// Use StratifiedEvaluator for queries with rule invocations (handles negation and strata)
return self.execute_query_with_rules(query);
}
// Warn about queries with no binding mechanism
if !query.has_binding_mechanism() {
return Err(anyhow!(
"query has no :where clause, rules, or aggregates — nothing binds the variables. \
Add a :where clause (e.g., [:find ?e ?a ?v :where [?e ?a ?v]]) or use an aggregate."
));
}
// Compute query-level valid_at value for :db/valid-at pseudo-attribute binding.
let now = self.read_now();
let valid_at_value = match &query.valid_at {
Some(ValidAt::Timestamp(t)) => Value::Integer(*t),
Some(ValidAt::AnyValidTime) => Value::Null,
Some(ValidAt::Slot(_)) => {
return Err(anyhow!(
"internal: unsubstituted :valid-at bind slot reached the executor"
));
}
None => Value::Integer(now),
};
// Hard-error: per-fact pseudo-attrs require :any-valid-time.
if query_uses_per_fact_pseudo_attr(&query)
&& !matches!(query.valid_at, Some(ValidAt::AnyValidTime))
{
return Err(anyhow!(
"temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \
:db/tx-id require :any-valid-time; add :any-valid-time to your query"
));
}
// Apply temporal filters before pattern matching
let filtered_facts = self.filter_facts_for_query(&query)?;
let matcher = PatternMatcher::from_slice_with_valid_at(
filtered_facts.clone(),
valid_at_value.clone(),
);
// Acquire function registry before the plan loop — needed for inline Expr evaluation.
let registry = self
.functions
.read()
.map_err(|_| anyhow!("functions lock poisoned"))?;
// Pre-validate UDF predicate names: surface unknown predicates as errors before
// processing any rows (matches the behaviour of the former apply_expr_clauses post-pass).
for clause in &query.where_clauses {
if let WhereClause::Expr {
expr: Expr::UnaryOp(UnaryOp::Udf(name), _),
..
} = clause
&& registry.get_predicate(name).is_none()
{
anyhow::bail!("unknown predicate: '{}'", name);
}
}
// Collect Pattern and Expr top-level clauses for the planner.
// Not/NotJoin/Or/OrJoin are extracted separately below and applied as post-filters.
let plan_clauses: Vec<WhereClause> = query
.where_clauses
.iter()
.filter(|c| matches!(c, WhereClause::Pattern(_) | WhereClause::Expr { .. }))
.cloned()
.collect();
let planned = optimizer::plan(plan_clauses, &self.indexes);
// Process planned clauses in order: Pattern → expand bindings, Expr → filter/extend.
let mut bindings: Vec<Binding> = vec![Binding::new()];
for (clause, hint) in planned {
match clause {
WhereClause::Pattern(p) => {
bindings = matcher.match_with_hint_seeded(
bindings,
&p,
hint.as_ref().unwrap_or(&optimizer::IndexHint::Eavt),
);
}
WhereClause::Expr { expr, binding: out } => {
bindings = bindings
.into_iter()
.filter_map(|mut b| match eval_expr(&expr, &b, Some(®istry)) {
Ok(v) => {
if let Some(var) = &out {
b.insert(var.clone(), v);
Some(b)
} else if is_truthy(&v) {
Some(b)
} else {
None
}
}
Err(_) => None,
})
.collect();
}
_ => {}
}
}
// Apply Or/OrJoin clauses (post-pass: after pattern matching, before not/expr)
let rules_guard = self
.rules
.read()
.map_err(|_| anyhow!("rules lock poisoned"))?;
let bindings = apply_or_clauses(
&query.where_clauses,
bindings,
filtered_facts.clone(),
&rules_guard,
query.as_of.clone(),
query.valid_at.clone(),
®istry,
)?;
drop(rules_guard);
// Apply not-filter for WhereClause::Not and WhereClause::NotJoin clauses
// (no rules involved — pure post-filter)
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut not_clauses: Vec<&Vec<WhereClause>> = query
.where_clauses
.iter()
.filter_map(|c| match c {
WhereClause::Not(inner) => Some(inner),
_ => None,
})
.collect();
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut not_join_clauses: Vec<(Vec<String>, Vec<WhereClause>)> = query
.where_clauses
.iter()
.filter_map(|c| match c {
WhereClause::NotJoin { join_vars, clauses } => {
Some((join_vars.clone(), clauses.clone()))
}
_ => None,
})
.collect();
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
#[cfg(not(feature = "wasm"))]
not_clauses.sort_by_key(|body| optimizer::clause_cost(&WhereClause::Not(body.to_vec())));
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
#[cfg(not(feature = "wasm"))]
not_join_clauses.sort_by_key(|(vars, clauses)| {
optimizer::clause_cost(&WhereClause::NotJoin {
join_vars: vars.clone(),
clauses: clauses.clone(),
})
});
let not_filtered: Vec<_> = if not_clauses.is_empty() && not_join_clauses.is_empty() {
bindings
} else {
// Pre-compute exclusion sets — one evaluation per not-body, not per outer binding.
//
// For each not-body, run pattern matching once against `filtered_facts` to get
// all bindings where the body is satisfiable. Then collect the "join keys" (the
// subset of variables that appear in the outer bindings) into a HashSet.
// The filter loop below does one O(1) probe per outer binding instead of a full
// pattern match.
//
// Edge case: expr-only bodies (no patterns) produce no pre-computed set and fall
// through to `not_body_matches` as before (rare, already fast).
use std::collections::HashSet;
// --- Not bodies ---
// Each element: either Some((has_expr, HashSet of excluded join-key tuples)) or None
// (expr-only, use slow path). `has_expr` is computed once here during pre-compute,
// not inside the per-binding filter closure.
let not_exclusion_sets: Vec<NotExclusionEntry> = not_clauses
.iter()
.map(|not_body| {
let has_expr = not_body
.iter()
.any(|c| matches!(c, WhereClause::Expr { .. }));
let patterns: Vec<_> = not_body
.iter()
.filter_map(|c| match c {
WhereClause::Pattern(p) => Some(p.clone()),
_ => None,
})
.collect();
if patterns.is_empty() {
// Expr-only body: no pre-computation possible.
return None;
}
let matcher = PatternMatcher::from_slice_with_valid_at(
filtered_facts.clone(),
valid_at_value.clone(),
);
let body_bindings = matcher.match_patterns(&patterns);
// Store all body bindings as sorted (key, value) vecs for probing.
// Normalize values (e.g. keyword entities → Ref) so that probe keys from
// the outer binding match body bindings regardless of representation.
let exclusion_set: HashSet<Vec<(String, Value)>> = body_bindings
.into_iter()
.map(|mut b| {
// Drop hidden metadata keys (prefixed `__f`)
b.retain(|k, _| !k.starts_with("__f"));
let mut kv: Vec<(String, Value)> = b
.into_iter()
.map(|(k, v)| (k, normalize_value(&v)))
.collect();
kv.sort_unstable_by(|a, b| a.0.cmp(&b.0));
kv
})
.collect();
Some((has_expr, exclusion_set))
})
.collect();
// --- Not-join bodies ---
// Each entry: Some((has_expr, key_vars, HashSet)) where key_vars are the join_vars
// that actually appear in ALL body binding rows (the intersection of join_vars and
// vars bound in every row). This handles cases like `not-join [?u ?r]` where the
// body only binds `?r`.
//
// Values are normalized: Value::Keyword(k) that represents an entity keyword is
// converted to Value::Ref(uuid) so that probe keys from the outer binding (which
// may store entity references as keywords) match the body bindings (which bind
// entity fields as Value::Ref). `has_expr` is computed once here, not per-binding.
let not_join_exclusion_sets: Vec<NotJoinExclusionEntry> = not_join_clauses
.iter()
.map(|(join_vars, nj_clauses)| {
let has_expr = nj_clauses
.iter()
.any(|c| matches!(c, WhereClause::Expr { .. }));
let patterns: Vec<_> = nj_clauses
.iter()
.filter_map(|c| match c {
WhereClause::Pattern(p) => Some(p.clone()),
_ => None,
})
.collect();
if patterns.is_empty() {
return None;
}
let matcher = PatternMatcher::from_slice_with_valid_at(
filtered_facts.clone(),
valid_at_value.clone(),
);
let body_bindings = matcher.match_patterns(&patterns);
if body_bindings.is_empty() {
return Some((has_expr, join_vars.clone(), HashSet::new()));
}
let key_vars: Vec<String> = join_vars
.iter()
.filter(|v| body_bindings.iter().all(|b| b.contains_key(*v)))
.cloned()
.collect();
let exclusion_set: HashSet<Vec<(String, Value)>> = body_bindings
.into_iter()
.map(|b| {
let mut kv: Vec<(String, Value)> = key_vars
.iter()
.filter_map(|v| {
b.get(v).map(|val| (v.clone(), normalize_value(val)))
})
.collect();
kv.sort_unstable_by(|a, b| a.0.cmp(&b.0));
kv
})
.collect();
Some((has_expr, key_vars, exclusion_set))
})
.collect();
bindings
.into_iter()
.filter(|binding| {
// Check not-bodies via pre-computed exclusion sets (fast path) or
// via not_body_matches (slow path for expr-only bodies).
for (not_body, exclusion_entry) in
not_clauses.iter().zip(not_exclusion_sets.iter())
{
match exclusion_entry {
Some((has_expr, exclusion_set)) => {
if exclusion_set.is_empty() && !has_expr {
// No excluding bindings → this outer binding is safe.
continue;
}
if !has_expr {
// Fast path: probe exclusion set using the outer binding's
// values for the join variables, normalized for consistency.
if let Some(sample) = exclusion_set.iter().next() {
let key: Vec<(String, Value)> = sample
.iter()
.filter_map(|(var, _)| {
binding
.get(var)
.map(|val| (var.clone(), normalize_value(val)))
})
.collect();
if key.len() == sample.len() {
// All join vars are bound in the outer binding.
if exclusion_set.contains(&key) {
return false;
}
continue;
}
// Outer binding is underspecified (fewer vars than
// the exclusion set key) — fall back to slow path.
if not_body_matches(
not_body,
binding,
filtered_facts.clone(),
valid_at_value.clone(),
®istry,
) {
return false;
}
continue;
}
}
// Slow path fallback (expr clauses or empty exclusion set with exprs)
if not_body_matches(
not_body,
binding,
filtered_facts.clone(),
valid_at_value.clone(),
®istry,
) {
return false;
}
}
None => {
// Expr-only body: slow path.
if not_body_matches(
not_body,
binding,
filtered_facts.clone(),
valid_at_value.clone(),
®istry,
) {
return false;
}
}
}
}
// Check not-join-bodies.
for ((join_vars, nj_clauses), nj_exclusion_entry) in
not_join_clauses.iter().zip(not_join_exclusion_sets.iter())
{
match nj_exclusion_entry {
Some((has_expr, key_vars, exclusion_set)) => {
if !has_expr {
if key_vars.is_empty() {
// Body bound no join vars: if exclusion set non-empty,
// exclude all outer bindings (body always succeeds).
if !exclusion_set.is_empty() {
return false;
}
continue;
}
// Build probe key from outer binding using key_vars.
// Normalize values so keyword entities match ref entities.
let mut key: Vec<(String, Value)> = key_vars
.iter()
.filter_map(|v| {
binding
.get(v)
.map(|val| (v.clone(), normalize_value(val)))
})
.collect();
key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if key.len() == key_vars.len() {
if exclusion_set.contains(&key) {
return false;
}
continue;
}
// Outer binding underspecified relative to the not-join body —
// fall back to the slow path so the body is correctly evaluated.
if evaluate_not_join(
join_vars,
nj_clauses,
binding,
filtered_facts.clone(),
®istry,
) {
return false;
}
continue;
}
// Fall through to slow path if expr clauses present.
if evaluate_not_join(
join_vars,
nj_clauses,
binding,
filtered_facts.clone(),
®istry,
) {
return false;
}
}
None => {
if evaluate_not_join(
join_vars,
nj_clauses,
binding,
filtered_facts.clone(),
®istry,
) {
return false;
}
}
}
}
true
})
.collect()
};
let results =
apply_post_processing(not_filtered, &query.find, &query.with_vars, ®istry)?;
Ok(QueryResult::QueryResults {
vars: query.find.iter().map(|s| s.display_name()).collect(),
results,
})
}
/// Execute a query that uses recursive rules
fn execute_query_with_rules(&self, query: DatalogQuery) -> Result<QueryResult> {
// Extract ALL predicates (including inside not bodies) so the StratifiedEvaluator
// evaluates every referenced rule. This is needed for not-post-filter to work.
let all_rule_invocations = query.get_rule_invocations();
let predicates: Vec<String> = all_rule_invocations
.iter()
.map(|(pred, _)| pred.clone())
.collect();
// Compute query-level valid_at value for :db/valid-at pseudo-attribute binding.
let now = self.read_now();
let valid_at_value = match &query.valid_at {
Some(ValidAt::Timestamp(t)) => Value::Integer(*t),
Some(ValidAt::AnyValidTime) => Value::Null,
Some(ValidAt::Slot(_)) => {
return Err(anyhow!(
"internal: unsubstituted :valid-at bind slot reached the executor"
));
}
None => Value::Integer(now),
};
// Hard-error: per-fact pseudo-attrs require :any-valid-time.
if query_uses_per_fact_pseudo_attr(&query)
&& !matches!(query.valid_at, Some(ValidAt::AnyValidTime))
{
return Err(anyhow!(
"temporal pseudo-attributes :db/valid-from, :db/valid-to, :db/tx-count, and \
:db/tx-id require :any-valid-time; add :any-valid-time to your query"
));
}
// Apply temporal filters before evaluating recursive rules
let filtered_facts = self.filter_facts_for_query(&query)?;
// Convert to FactStorage for StratifiedEvaluator (needs mutable accumulation)
// TODO (post-1.0): use FactStorage::new_noindex() once profiling confirms rules-path
// index rebuild is also a bottleneck.
let filtered_storage = FactStorage::new();
for fact in filtered_facts.iter().cloned() {
filtered_storage.load_fact(fact)?;
}
// Create StratifiedEvaluator — handles negation, stratification, and positive-only rules
let evaluator = StratifiedEvaluator::new(
filtered_storage,
self.rules.clone(),
self.functions.clone(),
1000, // max iterations
self.max_derived_facts,
self.max_results,
);
let derived_storage = evaluator.evaluate(&predicates)?;
// Compute derived_facts Arc once; reuse for plan loop, or-clauses and not-post-filter.
// Must use derived_storage (includes rule-derived facts), not filtered_facts (base only).
let derived_facts: Arc<[Fact]> =
Arc::from(derived_storage.get_asserted_facts().unwrap_or_default());
let matcher =
PatternMatcher::from_slice_with_valid_at(derived_facts.clone(), valid_at_value.clone());
// Acquire function registry before the plan loop — needed for inline Expr evaluation.
let registry = self
.functions
.read()
.map_err(|_| anyhow!("functions lock poisoned"))?;
// Pre-validate UDF predicate names.
for clause in &query.where_clauses {
if let WhereClause::Expr {
expr: Expr::UnaryOp(UnaryOp::Udf(name), _),
..
} = clause
&& registry.get_predicate(name).is_none()
{
anyhow::bail!("unknown predicate: '{}'", name);
}
}
// Collect Pattern and Expr top-level clauses for the planner.
// Rule invocations are converted to WhereClause::Pattern against derived_storage.
let mut plan_clauses: Vec<WhereClause> = query
.where_clauses
.iter()
.filter(|c| matches!(c, WhereClause::Pattern(_) | WhereClause::Expr { .. }))
.cloned()
.collect();
for (predicate, args) in query.get_top_level_rule_invocations() {
let pattern = match args.len() {
1 => {
#[allow(clippy::indexing_slicing)]
let entity = args[0].clone();
Pattern::new(
entity,
EdnValue::Keyword(format!(":{}", predicate)),
EdnValue::Symbol("?_rule_value".to_string()),
)
}
2 => {
#[allow(clippy::indexing_slicing)]
let entity = args[0].clone();
#[allow(clippy::indexing_slicing)]
let value = args[1].clone();
Pattern::new(entity, EdnValue::Keyword(format!(":{}", predicate)), value)
}
n => {
return Err(anyhow!(
"Rule invocation '{}' must have 1 or 2 arguments, got {}",
predicate,
n
));
}
};
plan_clauses.push(WhereClause::Pattern(pattern));
}
let planned = optimizer::plan(plan_clauses, &self.indexes);
// Process planned clauses in order: Pattern → expand, Expr → filter/extend.
let mut bindings: Vec<Binding> = vec![Binding::new()];
for (clause, hint) in planned {
match clause {
WhereClause::Pattern(p) => {
bindings = matcher.match_with_hint_seeded(
bindings,
&p,
hint.as_ref().unwrap_or(&optimizer::IndexHint::Eavt),
);
}
WhereClause::Expr { expr, binding: out } => {
bindings = bindings
.into_iter()
.filter_map(|mut b| match eval_expr(&expr, &b, Some(®istry)) {
Ok(v) => {
if let Some(var) = &out {
b.insert(var.clone(), v);
Some(b)
} else if is_truthy(&v) {
Some(b)
} else {
None
}
}
Err(_) => None,
})
.collect();
}
_ => {}
}
}
// Apply Or/OrJoin clauses against derived facts (rules already evaluated)
let rules_guard = self
.rules
.read()
.map_err(|_| anyhow!("rules lock poisoned"))?;
let bindings = apply_or_clauses(
&query.where_clauses,
bindings,
derived_facts.clone(),
&rules_guard,
query.as_of.clone(),
query.valid_at.clone(),
®istry,
)?;
drop(rules_guard);
// Apply not-post-filter for WhereClause::Not and WhereClause::NotJoin clauses
// in the query body. (The StratifiedEvaluator handles `not`/`not-join` in rule
// bodies; this handles them appearing directly in the query body alongside rule
// invocations.)
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut not_clauses: Vec<&Vec<WhereClause>> = query
.where_clauses
.iter()
.filter_map(|c| match c {
WhereClause::Not(inner) => Some(inner),
_ => None,
})
.collect();
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut not_join_clauses: Vec<(Vec<String>, Vec<WhereClause>)> = query
.where_clauses
.iter()
.filter_map(|c| match c {
WhereClause::NotJoin { join_vars, clauses } => {
Some((join_vars.clone(), clauses.clone()))
}
_ => None,
})
.collect();
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
#[cfg(not(feature = "wasm"))]
not_clauses.sort_by_key(|body| optimizer::clause_cost(&WhereClause::Not(body.to_vec())));
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
#[cfg(not(feature = "wasm"))]
not_join_clauses.sort_by_key(|(vars, clauses)| {
optimizer::clause_cost(&WhereClause::NotJoin {
join_vars: vars.clone(),
clauses: clauses.clone(),
})
});
let not_filtered: Vec<_> = if not_clauses.is_empty() && not_join_clauses.is_empty() {
bindings
} else {
bindings
.into_iter()
.filter(|binding| {
for not_body in ¬_clauses {
// Collect pattern and rule-invocation clauses into patterns.
let substituted: Vec<Pattern> = not_body
.iter()
.filter_map(|c| match c {
WhereClause::Pattern(p) => {
Some(crate::query::datalog::evaluator::substitute_pattern(
p, binding,
))
}
WhereClause::RuleInvocation { predicate, args } => {
// Convert rule invocation to a pattern against derived storage.
// Apply the current binding to any variables in args first.
let resolved_args: Vec<EdnValue> = args
.iter()
.map(|a| match a {
EdnValue::Symbol(s) if s.starts_with('?') => {
// Look up the bound value and convert back to EdnValue
binding
.get(s)
.map(|v| match v {
Value::Keyword(k) => {
EdnValue::Keyword(k.clone())
}
Value::String(s) => {
EdnValue::String(s.clone())
}
Value::Integer(i) => EdnValue::Integer(*i),
Value::Float(f) => EdnValue::Float(*f),
Value::Boolean(b) => EdnValue::Boolean(*b),
Value::Ref(u) => EdnValue::Uuid(*u),
Value::Null => EdnValue::Nil,
})
.unwrap_or_else(|| a.clone())
}
other => other.clone(),
})
.collect();
// Safety: match arms guarantee len()==1 or len()==2.
let pattern = match resolved_args.len() {
1 => {
#[allow(clippy::indexing_slicing)]
let entity = resolved_args[0].clone();
Pattern::new(
entity,
EdnValue::Keyword(format!(":{}", predicate)),
EdnValue::Symbol("?_rule_value".to_string()),
)
}
2 => {
#[allow(clippy::indexing_slicing)]
let entity = resolved_args[0].clone();
#[allow(clippy::indexing_slicing)]
let value = resolved_args[1].clone();
Pattern::new(
entity,
EdnValue::Keyword(format!(":{}", predicate)),
value,
)
}
_ => return None,
};
Some(crate::query::datalog::evaluator::substitute_pattern(
&pattern, binding,
))
}
_ => None,
})
.collect();
// Compute not_bindings: if no patterns, seed with current binding.
let m = PatternMatcher::from_slice_with_valid_at(
derived_facts.clone(),
valid_at_value.clone(),
);
let mut not_bindings: Vec<Binding> = if substituted.is_empty() {
vec![binding.clone()]
} else {
m.match_patterns(&substituted)
.into_iter()
.map(|mut nb| {
for (k, v) in binding {
nb.entry(k.clone()).or_insert_with(|| v.clone());
}
nb
})
.collect()
};
// Apply Expr clauses from the not body.
// Errors (e.g. unknown UDF predicate) are treated as "no match".
not_bindings = apply_expr_clauses(not_bindings, not_body, ®istry)
.unwrap_or_default();
if !not_bindings.is_empty() {
return false; // not condition violated
}
}
// Use the already-acquired registry instead of re-acquiring the lock.
for (join_vars, nj_clauses) in ¬_join_clauses {
if evaluate_not_join(
join_vars,
nj_clauses,
binding,
derived_facts.clone(),
®istry,
) {
return false;
}
}
true
})
.collect()
};
let results =
apply_post_processing(not_filtered, &query.find, &query.with_vars, ®istry)?;
Ok(QueryResult::QueryResults {
vars: query.find.iter().map(|s| s.display_name()).collect(),
results,
})
}
/// Execute a rule command: register the rule for later use
fn execute_rule(&self, rule: Rule) -> Result<QueryResult> {
// Extract predicate name from rule head
// Head format: (predicate ?arg1 ?arg2 ...)
let predicate = self.extract_predicate(&rule)?;
// Register the rule
self.rules
.write()
.map_err(|_| anyhow!("rules lock poisoned"))?
.register_rule(predicate, rule)?;
Ok(QueryResult::Ok)
}
/// Extract the predicate name from a rule head
fn extract_predicate(&self, rule: &Rule) -> Result<String> {
if rule.head.is_empty() {
return Err(anyhow!("Rule head cannot be empty"));
}
// Safety: is_empty() check above guarantees index 0 exists.
#[allow(clippy::indexing_slicing)]
match &rule.head[0] {
EdnValue::Symbol(s) => Ok(s.clone()),
_ => Err(anyhow!(
"Rule head must start with a symbol (predicate name)"
)),
}
}
/// Get the underlying storage (for testing)
#[allow(dead_code)]
pub fn storage(&self) -> &FactStorage {
&self.storage
}
/// Get the rule registry (for testing)
#[cfg(test)]
pub fn rules(&self) -> Arc<RwLock<RuleRegistry>> {
self.rules.clone()
}
}
/// Normalize a `Value` for use as a hash-join key.
///
/// Entity keywords (`:foo`) and entity refs (`Value::Ref(uuid)`) represent the same
/// entity but appear as different variants depending on whether the value was stored in
/// the entity position (→ `Ref`) or the value position (→ `Keyword`) of a fact.
/// Normalize both to `Value::Ref` so that exclusion-set probes work correctly across
/// these two representations.
fn normalize_value(v: &Value) -> Value {
if let Value::Keyword(k) = v {
use crate::query::datalog::matcher::edn_to_entity_id;
use crate::query::datalog::types::EdnValue;
if let Ok(uuid) = edn_to_entity_id(&EdnValue::Keyword(k.clone())) {
return Value::Ref(uuid);
}
}
v.clone()
}
/// Evaluate a `not` body against the current outer binding.
///
/// Returns true if the body "matches" (i.e., the outer binding should be excluded).
fn not_body_matches(
not_body: &[WhereClause],
outer: &Binding,
storage: Arc<[Fact]>,
valid_at: Value,
registry: &FunctionRegistry,
) -> bool {
use crate::query::datalog::evaluator::substitute_pattern;
let patterns: Vec<_> = not_body
.iter()
.filter_map(|c| match c {
WhereClause::Pattern(p) => Some(substitute_pattern(p, outer)),
// INVARIANT: not_body_matches is only called from execute_query, which is
// only reached when query.uses_rules() is false. uses_rules() descends into
// Not bodies via rule_invocations(), so any not body containing a
// RuleInvocation is routed to execute_query_with_rules instead.
// WhereClause::Expr clauses are handled by apply_expr_clauses below.
_ => None,
})
.collect();
let matcher = crate::query::datalog::matcher::PatternMatcher::from_slice_with_valid_at(
storage.clone(),
valid_at,
);
let mut not_bindings: Vec<Binding> = if patterns.is_empty() {
// Expr-only not body: start with the outer binding so variables resolve.
vec![outer.clone()]
} else {
// Merge outer binding with pattern-match results.
matcher
.match_patterns(&patterns)
.into_iter()
.map(|mut nb| {
for (k, v) in outer {
nb.entry(k.clone()).or_insert_with(|| v.clone());
}
nb
})
.collect()
};
// Apply Expr clauses from the not body.
// Errors (e.g. unknown UDF predicate) are treated as "no match" — same as an
// empty result — so the outer row is kept (not-condition not violated).
not_bindings = apply_expr_clauses(not_bindings, not_body, registry).unwrap_or_default();
!not_bindings.is_empty()
}
/// Extract plain variable values from bindings (non-aggregate path).
fn extract_variables(
bindings: Vec<std::collections::HashMap<String, Value>>,
find_specs: &[FindSpec],
) -> Vec<Vec<Value>> {
let mut results = Vec::new();
for binding in bindings {
let mut row = Vec::new();
for spec in find_specs {
if let Some(value) = binding.get(spec.var()) {
row.push(value.clone());
} else {
break;
}
}
if row.len() == find_specs.len() {
results.push(row);
}
}
results
}
type Binding = std::collections::HashMap<String, Value>;
/// Internal type alias for pre-computed not-body exclusion sets.
type NotExclusionEntry = Option<(bool, std::collections::HashSet<Vec<(String, Value)>>)>;
/// Internal type alias for pre-computed not-join exclusion sets.
type NotJoinExclusionEntry = Option<(
bool,
Vec<String>,
std::collections::HashSet<Vec<(String, Value)>>,
)>;
/// Unified post-processing: handles plain-variable extraction, aggregation,
/// window functions, and mixed (aggregate + window) queries.
///
/// - Plain variables only → `extract_variables` (no change from current path).
/// - Aggregates only → group-by collapse, then project.
/// - Windows only → partition/sort/accumulate per spec, then project.
/// - Mixed → aggregate collapses first, window runs over collapsed rows.
fn apply_post_processing(
bindings: Vec<Binding>,
find_specs: &[FindSpec],
with_vars: &[String],
registry: &FunctionRegistry,
) -> Result<Vec<Vec<Value>>> {
let has_aggregates = find_specs
.iter()
.any(|s| matches!(s, FindSpec::Aggregate { .. }));
let has_windows = find_specs.iter().any(|s| matches!(s, FindSpec::Window(_)));
if !has_aggregates && !has_windows {
return Ok(extract_variables(bindings, find_specs));
}
// Step 1: Aggregate (collapses rows, produces binding maps).
let mut working: Vec<Binding> = if has_aggregates {
compute_aggregation(bindings, find_specs, with_vars, registry)?
} else {
bindings
};
// Step 2: Window functions (annotate each row, no collapse).
if has_windows {
apply_window_functions(&mut working, find_specs, registry)?;
}
// Step 3: Project to output rows in find-spec order.
Ok(project_find_specs(&working, find_specs))
}
/// Group bindings by non-aggregate find vars + with_vars, apply aggregate functions,
/// return one binding map per group. Aggregate results stored under `"__agg_{i}"`.
fn compute_aggregation(
bindings: Vec<Binding>,
find_specs: &[FindSpec],
with_vars: &[String],
registry: &FunctionRegistry,
) -> Result<Vec<Binding>> {
let has_grouping_vars = find_specs
.iter()
.any(|s| matches!(s, FindSpec::Variable(_)));
// Special case: zero bindings + all-count specs → one zero row.
if bindings.is_empty() {
let all_count = !has_grouping_vars
&& find_specs.iter().all(|s| {
matches!(s, FindSpec::Aggregate { func, .. }
if func == "count" || func == "count-distinct")
});
if all_count {
let mut b = Binding::new();
for (i, _) in find_specs.iter().enumerate() {
b.insert(format!("__agg_{}", i), Value::Integer(0));
}
return Ok(vec![b]);
}
return Ok(vec![]);
}
// In a mixed aggregate+window query, :with vars must NOT be added to the
// grouping key. The window phase runs after aggregation, so :with vars that
// are used only by window specs (var, order_by) would otherwise inflate the
// number of groups. Even :with vars used by aggregate specs (e.g. ?e in
// count(?e)) should not split groups — the aggregate operates over all rows
// in the base group determined by the Variable find specs.
let has_windows = find_specs.iter().any(|s| matches!(s, FindSpec::Window(_)));
// Grouping key = Variable find specs (in find order).
// In pure-aggregate queries, also include with_vars (Datomic semantics: :with
// prevents pre-aggregation de-duplication by adding vars to the group key).
let mut group_var_names: Vec<&str> = find_specs
.iter()
.filter_map(|s| match s {
FindSpec::Variable(v) => Some(v.as_str()),
_ => None,
})
.collect();
if !has_windows {
// Pure aggregate: with_vars add to grouping key.
group_var_names.extend(with_vars.iter().map(|s| s.as_str()));
}
// Group using BTreeMap keyed by group key (O(log g) instead of O(g) per binding).
use std::collections::BTreeMap;
let mut groups: BTreeMap<Vec<Value>, Vec<Binding>> = BTreeMap::new();
for b in bindings {
let key: Vec<Value> = group_var_names
.iter()
.map(|v| b.get(*v).cloned().unwrap_or(Value::Null))
.collect();
groups.entry(key).or_default().push(b);
}
// Build a position map for Variable specs only (indices 0..n_vars in the key vector).
// with_vars occupy key positions n_vars..end and are used only for grouping, not for output.
// Map of Variable spec name → its index in the group key Vec.
let mut group_key_idx: std::collections::HashMap<&str, usize> =
std::collections::HashMap::new();
{
let mut var_pos = 0usize;
for spec in find_specs {
if let FindSpec::Variable(v) = spec {
group_key_idx.insert(v.as_str(), var_pos);
var_pos += 1;
}
}
}
let mut results: Vec<Binding> = Vec::new();
for (key, group_bindings) in groups.iter() {
let mut binding = Binding::new();
let mut skip = false;
// Plain variable values from group key.
for (v, &idx) in &group_key_idx {
if let Some(val) = key.get(idx) {
binding.insert((*v).to_string(), val.clone());
}
}
// Aggregate values stored under "__agg_{i}".
for (i, spec) in find_specs.iter().enumerate() {
if let FindSpec::Aggregate { func, var } = spec {
let non_null: Vec<&Value> = group_bindings
.iter()
.filter_map(|b| b.get(var.as_str()))
.filter(|v| !matches!(v, Value::Null))
.collect();
let agg_val: anyhow::Result<Value> = match registry.get(func.as_str()) {
Some(desc) if desc.is_builtin => {
// Built-in: use batch path which enforces strict type-error semantics.
apply_builtin_aggregate(func, &non_null)
}
Some(desc) => {
if let AggImpl::Udf(ops) = &desc.impl_ {
if non_null.is_empty() {
Ok(Value::Null)
} else {
let mut acc = (ops.init)();
for v in &non_null {
(ops.step)(&mut acc, v);
}
Ok((ops.finalise)(&acc, non_null.len()))
}
} else {
// AggImpl::Builtin with is_builtin=false shouldn't happen
apply_builtin_aggregate(func, &non_null)
}
}
None => Err(anyhow::anyhow!("unknown aggregate function: '{}'", func)),
};
match agg_val {
Ok(v) => {
binding.insert(format!("__agg_{}", i), v);
}
Err(e) => {
let msg = e.to_string();
if msg.contains("no non-null values in group") {
skip = true;
break;
}
return Err(e);
}
}
}
}
if !skip {
results.push(binding);
}
}
Ok(results)
}
/// Compute window function values for each row and store under `"__win_{i}"`.
/// Modifies `bindings` in place.
fn apply_window_functions(
bindings: &mut [Binding],
find_specs: &[FindSpec],
registry: &FunctionRegistry,
) -> Result<()> {
for (i, spec) in find_specs.iter().enumerate() {
let FindSpec::Window(ws) = spec else {
continue;
};
let key = format!("__win_{}", i);
// Build partitions: (partition_key, sorted row indices).
let mut partitions: HashMap<Option<Value>, Vec<usize>> = HashMap::new();
for (row_idx, binding) in bindings.iter().enumerate() {
let part_key = ws
.partition_by
.as_ref()
.and_then(|pv| binding.get(pv))
.cloned();
partitions.entry(part_key).or_default().push(row_idx);
}
// For each partition: sort, compute window values, write back.
for row_indices in partitions.values_mut() {
// Pre-extract order_by values into a contiguous Vec so the sort
// comparator never touches the HashMap — O(n) lookups here instead
// of O(n log n) random HashMap accesses inside sort_by.
// Safety: row_indices are populated from 0..bindings.len() enumeration above,
// so all indices are valid.
#[allow(clippy::indexing_slicing)]
let mut keyed: Vec<(Value, usize)> = row_indices
.iter()
.map(|&i| {
let k = bindings[i]
.get(&ws.order_by)
.cloned()
.unwrap_or(Value::Null);
(k, i)
})
.collect();
keyed.sort_by(|(a, _), (b, _)| {
let cmp = value_cmp(a, b);
match ws.order {
Order::Asc => cmp,
Order::Desc => cmp.reverse(),
}
});
// Rewrite row_indices in sorted order for the write-back step.
for (dest, (_, src)) in row_indices.iter_mut().zip(keyed.iter()) {
*dest = *src;
}
// Compute one window value per row in sorted order.
let window_values: Vec<Value> = match ws.func {
WindowFunc::RowNumber => {
let mut values = Vec::with_capacity(keyed.len());
for pos in 1..=keyed.len() {
values.push(Value::Integer(
i64::try_from(pos).map_err(|_| anyhow!("row number overflow"))?,
));
}
values
}
WindowFunc::Rank => {
// Reuse pre-extracted keys for tie-detection — no extra HashMap lookups.
let mut values = Vec::with_capacity(keyed.len());
let mut rank = 1i64;
let mut prev: Option<&Value> = None;
for (row_num, (key, _)) in (1i64..).zip(keyed.iter()) {
if prev != Some(key) {
rank = row_num;
prev = Some(key);
}
values.push(Value::Integer(rank));
}
values
}
_ => {
// Accumulator-based: built-ins (sum, count, min, max, avg) and UDF aggregates.
// UDF aggregates (WindowFunc::Udf) also route here via registry lookup.
let func_name = ws.func_name();
let desc = registry.get(&func_name).ok_or_else(|| {
anyhow::anyhow!(
"unknown window function '{}' — register it with register_aggregate() before querying",
func_name
)
})?;
let mut values = Vec::with_capacity(keyed.len());
// Safety: row_idx values come from enumerate() over bindings, so indices are valid.
#[allow(clippy::indexing_slicing)]
match &desc.impl_ {
AggImpl::Builtin(ops) => {
let mut acc = (ops.init)();
for (_, row_idx) in keyed.iter() {
let val = ws
.var
.as_ref()
.and_then(|v| bindings[*row_idx].get(v))
.unwrap_or(&Value::Null);
(ops.step)(&mut acc, val);
values.push((ops.finalise)(&acc));
}
}
AggImpl::Udf(ops) => {
let mut acc = (ops.init)();
let mut row_count = 0usize;
for (_, row_idx) in keyed.iter() {
let val = ws
.var
.as_ref()
.and_then(|v| bindings[*row_idx].get(v))
.unwrap_or(&Value::Null);
(ops.step)(&mut acc, val);
row_count += 1;
values.push((ops.finalise)(&acc, row_count));
}
}
}
values
}
};
// Write window values back to rows.
// Safety: row_idx values come from enumerate() over bindings, so indices are valid.
for (&row_idx, window_val) in row_indices.iter().zip(window_values) {
#[allow(clippy::indexing_slicing)]
bindings[row_idx].insert(key.clone(), window_val);
}
}
}
Ok(())
}
/// Project binding maps to output rows in find-spec order.
fn project_find_specs(bindings: &[Binding], find_specs: &[FindSpec]) -> Vec<Vec<Value>> {
let mut results = Vec::new();
for binding in bindings {
let mut row = Vec::new();
let mut complete = true;
for (i, spec) in find_specs.iter().enumerate() {
let val = match spec {
FindSpec::Variable(v) => binding.get(v).cloned(),
FindSpec::Aggregate { .. } => binding.get(&format!("__agg_{}", i)).cloned(),
FindSpec::Window(_) => binding.get(&format!("__win_{}", i)).cloned(),
};
match val {
Some(v) => row.push(v),
// Invariant: all __agg_{i} and __win_{i} keys are populated for non-skipped rows.
// None here only occurs for skipped aggregate groups (e.g. min/max on all-null input).
None => {
complete = false;
break;
}
}
}
if complete {
results.push(row);
}
}
results
}
/// Evaluate a single branch of an `or`/`or-join` against incoming bindings.
///
/// Processing order (note: top-level execute_query now uses an interleaved plan loop
/// where Expr clauses are pushed down inline; branches retain their own Expr post-pass):
/// 1. Pattern/RuleInvocation → match_patterns_seeded
/// 2. Nested Or/OrJoin → apply_or_clauses (recursive)
/// 3. Not/NotJoin → post-filter
/// 4. Expr → apply_expr_clauses
pub(crate) fn evaluate_branch(
branch: &[WhereClause],
incoming: Vec<Binding>,
storage: Arc<[Fact]>,
rules: &crate::query::datalog::rules::RuleRegistry,
as_of: Option<AsOf>,
valid_at: Option<ValidAt>,
registry: &FunctionRegistry,
) -> anyhow::Result<Vec<Binding>> {
use crate::query::datalog::evaluator::rule_invocation_to_pattern;
use crate::query::datalog::matcher::PatternMatcher;
if incoming.is_empty() {
return Ok(vec![]);
}
// Compute valid_at_value for pseudo-attribute binding in this branch.
let branch_valid_at_value = match &valid_at {
Some(ValidAt::Timestamp(t)) => Value::Integer(*t),
Some(ValidAt::AnyValidTime) => Value::Null,
Some(ValidAt::Slot(_)) => {
return Err(anyhow!(
"internal: unsubstituted :valid-at bind slot reached the executor"
));
}
None => Value::Integer(tx_id_now().cast_signed()),
};
// Step 1: Collect Pattern and RuleInvocation clauses
let patterns: Vec<Pattern> = branch
.iter()
.filter_map(|c| match c {
WhereClause::Pattern(p) => Some(p.clone()),
WhereClause::RuleInvocation { predicate, args } => {
rule_invocation_to_pattern(predicate, args).ok()
}
_ => None,
})
.collect();
let matcher =
PatternMatcher::from_slice_with_valid_at(storage.clone(), branch_valid_at_value.clone());
let bindings = if patterns.is_empty() {
incoming
} else {
matcher.match_patterns_seeded(&patterns, incoming)
};
if bindings.is_empty() {
return Ok(vec![]);
}
// Step 2: Nested Or/OrJoin
let bindings = apply_or_clauses(
branch,
bindings,
storage.clone(),
rules,
as_of.clone(),
valid_at.clone(),
registry,
)?;
if bindings.is_empty() {
return Ok(vec![]);
}
// Step 3: Not/NotJoin post-filter
let not_clauses: Vec<&Vec<WhereClause>> = branch
.iter()
.filter_map(|c| match c {
WhereClause::Not(inner) => Some(inner),
_ => None,
})
.collect();
let not_join_clauses: Vec<(Vec<String>, Vec<WhereClause>)> = branch
.iter()
.filter_map(|c| match c {
WhereClause::NotJoin { join_vars, clauses } => {
Some((join_vars.clone(), clauses.clone()))
}
_ => None,
})
.collect();
let bindings = if not_clauses.is_empty() && not_join_clauses.is_empty() {
bindings
} else {
bindings
.into_iter()
.filter(|binding| {
for not_body in ¬_clauses {
if not_body_matches(
not_body,
binding,
storage.clone(),
branch_valid_at_value.clone(),
registry,
) {
return false;
}
}
for (join_vars, nj_clauses) in ¬_join_clauses {
if evaluate_not_join(join_vars, nj_clauses, binding, storage.clone(), registry)
{
return false;
}
}
true
})
.collect()
};
// Step 4: Expr clauses
let bindings = apply_expr_clauses(bindings, branch, registry)?;
Ok(bindings)
}
/// Apply all Or/OrJoin clauses from `clauses` to `bindings` in sequence.
///
/// Non-Or/OrJoin clauses are ignored (handled elsewhere).
/// For `Or`: union results from all branches (deduplicated by full binding map).
/// For `OrJoin`: union results, then project out branch-private variables.
pub(crate) fn apply_or_clauses(
clauses: &[WhereClause],
mut bindings: Vec<Binding>,
storage: Arc<[Fact]>,
rules: &crate::query::datalog::rules::RuleRegistry,
as_of: Option<AsOf>,
valid_at: Option<ValidAt>,
registry: &FunctionRegistry,
) -> anyhow::Result<Vec<Binding>> {
for clause in clauses {
match clause {
WhereClause::Or(branches) => {
let sorted_or_branches: Vec<&Vec<WhereClause>> = {
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut b: Vec<&Vec<WhereClause>> = branches.iter().collect();
// Sort branches by cost ascending so cheaper branches evaluate first.
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
// Note: all branches still evaluated (no short-circuit); ordering is
// infrastructure for issue #250.
#[cfg(not(feature = "wasm"))]
b.sort_by_key(|br| optimizer::branch_cost(br));
b
};
// If any branch contains Not/NotJoin clauses (which need bound variables
// from the outer scope to evaluate correctly), fall back to the classic
// seeded-branch evaluation to preserve correctness.
let any_branch_has_not = sorted_or_branches.iter().any(|b| {
b.iter()
.any(|c| matches!(c, WhereClause::Not(_) | WhereClause::NotJoin { .. }))
});
if any_branch_has_not {
// Classic O(N·B) seeded evaluation: each incoming binding seeds each branch.
let mut seen: std::collections::HashSet<Vec<(String, Value)>> =
std::collections::HashSet::new();
let mut result: Vec<Binding> = Vec::new();
for branch in &sorted_or_branches {
let branch_result = evaluate_branch(
branch,
bindings.clone(),
storage.clone(),
rules,
as_of.clone(),
valid_at.clone(),
registry,
)?;
for b in branch_result {
let mut key: Vec<_> = b
.iter()
.filter(|(k, _)| !k.starts_with("__"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if seen.insert(key) {
result.push(b);
}
}
}
bindings = result;
continue;
}
// Fast path: no Not/NotJoin in any branch.
// Evaluate every branch from an empty seed (independent of incoming bindings),
// then hash-join the union back onto incoming bindings on shared variables.
let empty_seed: Vec<Binding> = vec![HashMap::new()];
let mut union_bindings: Vec<Binding> = Vec::new();
let mut seen_keys: std::collections::HashSet<Vec<(String, Value)>> =
std::collections::HashSet::new();
for branch in &sorted_or_branches {
let branch_result = evaluate_branch(
branch,
empty_seed.clone(),
storage.clone(),
rules,
as_of.clone(),
valid_at.clone(),
registry,
)?;
for b in branch_result {
// Deduplicate on user-visible variables only (exclude internal `__` keys).
let mut key: Vec<_> = b
.iter()
.filter(|(k, _)| !k.starts_with("__"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if seen_keys.insert(key) {
union_bindings.push(b);
}
}
}
// Determine shared variable names: variables present in both
// incoming bindings and branch results.
// Exclude internal metadata keys (prefixed with `__`) — those are
// fact-specific and differ between patterns for the same entity.
let branch_var_names: std::collections::HashSet<&str> = union_bindings
.iter()
.flat_map(|b| b.keys().map(|k| k.as_str()))
.filter(|k| !k.starts_with("__"))
.collect();
let shared_vars: Vec<String> = bindings
.iter()
.flat_map(|b| b.keys().cloned())
.collect::<std::collections::HashSet<_>>()
.into_iter()
.filter(|v| !v.starts_with("__") && branch_var_names.contains(v.as_str()))
.collect();
if shared_vars.is_empty() {
// No shared user-visible variables between incoming bindings and branch
// results. This is semantically equivalent to a cross-join, which only
// makes sense when `bindings` carries no meaningful state yet (i.e. it
// is a single empty binding — the query start state — or all incoming
// variables are fact-metadata keys that the branch does not reference).
// In that case the cross-join degenerates to "replace with branch union",
// which is what the original seeded evaluation produced. Incoming bindings
// that carry user-visible variables but none matching any branch variable
// would be silently dropped here — that situation should not arise given
// that `or` must share at least one variable with the surrounding clause.
bindings = union_bindings;
continue;
}
// Build HashMap: shared-key tuple → Vec<branch Binding>
let mut branch_map: HashMap<Vec<(String, Value)>, Vec<Binding>> = HashMap::new();
for b in union_bindings {
let key: Vec<(String, Value)> = shared_vars
.iter()
.filter_map(|v| b.get(v).map(|val| (v.clone(), val.clone())))
.collect();
branch_map.entry(key).or_default().push(b);
}
// For each incoming binding, look up matching branch results and merge.
let mut result: Vec<Binding> = Vec::new();
let mut seen_result: std::collections::HashSet<Vec<(String, Value)>> =
std::collections::HashSet::new();
for incoming in &bindings {
let key: Vec<(String, Value)> = shared_vars
.iter()
.filter_map(|v| incoming.get(v).map(|val| (v.clone(), val.clone())))
.collect();
if let Some(matches) = branch_map.get(&key) {
for branch_binding in matches {
// Merge: start with incoming, extend with branch-introduced vars.
let mut merged = incoming.clone();
for (k, v) in branch_binding {
merged.entry(k.clone()).or_insert_with(|| v.clone());
}
let mut dedup_key: Vec<_> =
merged.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
dedup_key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if seen_result.insert(dedup_key) {
result.push(merged);
}
}
}
}
bindings = result;
}
WhereClause::OrJoin {
join_vars,
branches,
} => {
let sorted_oj_branches: Vec<&Vec<WhereClause>> = {
#[cfg_attr(feature = "wasm", allow(unused_mut))]
let mut b: Vec<&Vec<WhereClause>> = branches.iter().collect();
// Sort branches by cost ascending so cheaper branches evaluate first.
// WASM omission: small datasets + determinism — see optimizer::selectivity_score().
// Note: all branches still evaluated (no short-circuit); ordering is
// infrastructure for issue #250.
#[cfg(not(feature = "wasm"))]
b.sort_by_key(|br| optimizer::branch_cost(br));
b
};
let outer_keys: std::collections::HashSet<String> =
bindings.iter().flat_map(|b| b.keys().cloned()).collect();
// Defensive check: every join_var must be bound in the incoming scope.
// The parser validates this, but guard here to avoid silent wrong results
// if a join_var is missing from outer_keys (hash-join key would be partial).
for jv in join_vars.iter() {
if !outer_keys.contains(jv.as_str()) {
anyhow::bail!("or-join variable {} is not bound in the incoming scope", jv);
}
}
let empty_seed: Vec<Binding> = vec![HashMap::new()];
let mut projected: Vec<Binding> = Vec::new();
let mut seen_proj: std::collections::HashSet<Vec<(String, Value)>> =
std::collections::HashSet::new();
for branch in &sorted_oj_branches {
let branch_result = evaluate_branch(
branch,
empty_seed.clone(),
storage.clone(),
rules,
as_of.clone(),
valid_at.clone(),
registry,
)?;
for mut b in branch_result {
if !join_vars.iter().all(|v| b.contains_key(v)) {
continue;
}
// Project to outer_keys (preserves join_vars since join_vars ⊆ outer_keys)
b.retain(|k, _| outer_keys.contains(k));
let mut key: Vec<_> =
b.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if seen_proj.insert(key) {
projected.push(b);
}
}
}
// Build HashMap keyed on join_vars tuple.
let mut branch_map: HashMap<Vec<(String, Value)>, Vec<Binding>> = HashMap::new();
for b in projected {
let key: Vec<(String, Value)> = join_vars
.iter()
.filter_map(|v| b.get(v).map(|val| (v.clone(), val.clone())))
.collect();
branch_map.entry(key).or_default().push(b);
}
let mut result: Vec<Binding> = Vec::new();
let mut seen_result: std::collections::HashSet<Vec<(String, Value)>> =
std::collections::HashSet::new();
for incoming in &bindings {
let key: Vec<(String, Value)> = join_vars
.iter()
.filter_map(|v| incoming.get(v).map(|val| (v.clone(), val.clone())))
.collect();
if let Some(matches) = branch_map.get(&key) {
for branch_binding in matches {
let mut merged = incoming.clone();
for (k, v) in branch_binding {
merged.entry(k.clone()).or_insert_with(|| v.clone());
}
let mut dedup_key: Vec<_> =
merged.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
dedup_key.sort_unstable_by(|a, b| a.0.cmp(&b.0));
if seen_result.insert(dedup_key) {
result.push(merged);
}
}
}
}
bindings = result;
}
_ => {} // Other clause types handled elsewhere
}
}
Ok(bindings)
}
/// Returns true for Boolean(true), non-zero Integer, non-zero Float.
/// All other Value variants (String, Keyword, Ref, Null, Float(0.0)) → false.
/// Note: `Float(-0.0)` is falsy because `-0.0 == 0.0` in IEEE 754.
pub(crate) fn is_truthy(v: &Value) -> bool {
match v {
Value::Boolean(b) => *b,
Value::Integer(i) => *i != 0,
Value::Float(f) => *f != 0.0,
_ => false,
}
}
/// Promote both values to f64 for numeric comparison / float arithmetic.
/// Returns Err(()) if either operand is not Integer or Float.
fn to_float_pair(l: &Value, r: &Value) -> Result<(f64, f64), ()> {
let lf = match l {
Value::Integer(i) => *i as f64,
Value::Float(f) => *f,
_ => return Err(()),
};
let rf = match r {
Value::Integer(i) => *i as f64,
Value::Float(f) => *f,
_ => return Err(()),
};
Ok((lf, rf))
}
fn eval_binop(op: &BinOp, l: Value, r: Value) -> Result<Value, ()> {
match op {
// Structural equality — works for all Value variants; no type mismatch error.
BinOp::Eq => return Ok(Value::Boolean(l == r)),
BinOp::Neq => return Ok(Value::Boolean(l != r)),
_ => {}
}
match op {
// Numeric comparisons — require both numeric; int/float promotion via to_float_pair.
BinOp::Lt | BinOp::Gt | BinOp::Lte | BinOp::Gte => {
let (lf, rf) = to_float_pair(&l, &r)?;
Ok(Value::Boolean(match op {
BinOp::Lt => lf < rf,
BinOp::Gt => lf > rf,
BinOp::Lte => lf <= rf,
BinOp::Gte => lf >= rf,
#[allow(clippy::unreachable)]
_ => unreachable!(),
}))
}
// Arithmetic: integer-integer stays integer; any float promotes result to float.
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => match (&l, &r) {
(Value::Integer(a), Value::Integer(b)) => match op {
BinOp::Add => Ok(Value::Integer(a.wrapping_add(*b))),
BinOp::Sub => Ok(Value::Integer(a.wrapping_sub(*b))),
BinOp::Mul => Ok(Value::Integer(a.wrapping_mul(*b))),
BinOp::Div => {
if *b == 0 {
Err(())
} else {
Ok(Value::Integer(a / b))
}
}
#[allow(clippy::unreachable)]
_ => unreachable!(),
},
_ => {
let (lf, rf) = to_float_pair(&l, &r)?;
match op {
BinOp::Add => {
let r = lf + rf;
if r.is_nan() {
Err(())
} else {
Ok(Value::Float(r))
}
}
BinOp::Sub => {
let r = lf - rf;
if r.is_nan() {
Err(())
} else {
Ok(Value::Float(r))
}
}
BinOp::Mul => {
let r = lf * rf;
if r.is_nan() {
Err(())
} else {
Ok(Value::Float(r))
}
}
BinOp::Div => {
if rf == 0.0 || rf.is_nan() {
Err(())
} else {
Ok(Value::Float(lf / rf))
}
}
#[allow(clippy::unreachable)]
_ => unreachable!(),
}
}
},
// String predicates — both operands must be String.
BinOp::StartsWith => match (l, r) {
(Value::String(s), Value::String(prefix)) => {
Ok(Value::Boolean(s.starts_with(prefix.as_str())))
}
_ => Err(()),
},
BinOp::EndsWith => match (l, r) {
(Value::String(s), Value::String(suffix)) => {
Ok(Value::Boolean(s.ends_with(suffix.as_str())))
}
_ => Err(()),
},
BinOp::Contains => match (l, r) {
(Value::String(s), Value::String(needle)) => {
Ok(Value::Boolean(s.contains(needle.as_str())))
}
_ => Err(()),
},
BinOp::Matches { regex: re, .. } => match (l, r) {
(Value::String(s), Value::String(_)) => Ok(Value::Boolean(re.is_match(&s))),
_ => Err(()),
},
// Eq/Neq handled above
BinOp::Eq | BinOp::Neq => unreachable!(),
}
}
/// Evaluate an Expr against a binding map.
///
/// Returns `Err(())` on: unbound variable, type mismatch, division by zero, unknown UDF predicate.
pub(crate) fn eval_expr(
expr: &Expr,
binding: &std::collections::HashMap<String, Value>,
registry: Option<&FunctionRegistry>,
) -> Result<Value, ()> {
match expr {
Expr::Var(v) => binding.get(v).cloned().ok_or(()),
Expr::Lit(val) => Ok(val.clone()),
Expr::UnaryOp(op, arg) => {
let v = eval_expr(arg, binding, registry)?;
match op {
UnaryOp::StringQ => Ok(Value::Boolean(matches!(v, Value::String(_)))),
UnaryOp::IntegerQ => Ok(Value::Boolean(matches!(v, Value::Integer(_)))),
UnaryOp::FloatQ => Ok(Value::Boolean(matches!(v, Value::Float(_)))),
UnaryOp::BooleanQ => Ok(Value::Boolean(matches!(v, Value::Boolean(_)))),
UnaryOp::NilQ => Ok(Value::Boolean(matches!(v, Value::Null))),
UnaryOp::Udf(name) => {
let desc = registry.and_then(|r| r.get_predicate(name)).ok_or(())?;
Ok(Value::Boolean((desc.f)(&v)))
}
}
}
Expr::BinOp(op, lhs, rhs) => {
let l = eval_expr(lhs, binding, registry)?;
let r = eval_expr(rhs, binding, registry)?;
eval_binop(op, l, r)
}
Expr::Slot(_) => {
// Unsubstituted bind slot — treat as eval error (unbound variable equivalent).
Err(())
}
}
}
/// Apply all WhereClause::Expr clauses from `where_clauses` to `bindings`.
///
/// Filter-form (`binding: None`) drops the row if the expr is not truthy or errors.
/// Binding-form (`binding: Some(var)`) extends the row with the computed value.
/// Type mismatches and errors silently drop the row.
///
/// Pre-validates UDF predicate names: returns `Err` if a named UDF predicate is not
/// registered, so callers get a clear error rather than silently empty results.
pub(crate) fn apply_expr_clauses(
mut bindings: Vec<Binding>,
where_clauses: &[WhereClause],
registry: &FunctionRegistry,
) -> anyhow::Result<Vec<Binding>> {
// Pre-validate: surface unknown UDF predicate names as errors before filtering rows.
for clause in where_clauses {
if let WhereClause::Expr {
expr: Expr::UnaryOp(UnaryOp::Udf(name), _),
..
} = clause
&& registry.get_predicate(name).is_none()
{
anyhow::bail!("unknown predicate: '{}'", name);
}
}
for clause in where_clauses {
if let WhereClause::Expr { expr, binding: out } = clause {
bindings = bindings
.into_iter()
.filter_map(|mut b| match eval_expr(expr, &b, Some(registry)) {
Ok(v) => {
if let Some(var) = out {
b.insert(var.clone(), v);
Some(b)
} else if is_truthy(&v) {
Some(b)
} else {
None
}
}
Err(()) => None,
})
.collect();
}
}
Ok(bindings)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::datalog::parser::parse_datalog_command;
use crate::query::datalog::types::WhereClause;
use uuid::Uuid;
#[test]
fn test_execute_transact() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command(
r#"(transact [[:alice :person/name "Alice"]
[:alice :person/age 30]])"#,
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::Transacted(tx_id) => {
assert!(tx_id > 0);
}
_ => panic!("Expected Transacted result"),
}
// Verify facts were added
let facts = executor.storage().get_asserted_facts().unwrap();
assert_eq!(facts.len(), 2);
}
#[test]
fn test_execute_simple_query() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Add some facts
let alice_id = Uuid::new_v4();
storage
.transact(
vec![
(
alice_id,
":person/name".to_string(),
Value::String("Alice".to_string()),
),
(alice_id, ":person/age".to_string(), Value::Integer(30)),
],
None,
)
.unwrap();
// Query for name
let cmd = parse_datalog_command(r#"(query [:find ?name :where [?e :person/name ?name]])"#)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?name"]);
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::String("Alice".to_string()));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_multi_pattern_query() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Add some facts
let alice_id = Uuid::new_v4();
storage
.transact(
vec![
(
alice_id,
":person/name".to_string(),
Value::String("Alice".to_string()),
),
(alice_id, ":person/age".to_string(), Value::Integer(30)),
],
None,
)
.unwrap();
// Query for both name and age
let cmd = parse_datalog_command(
r#"(query [:find ?name ?age
:where [?e :person/name ?name]
[?e :person/age ?age]])"#,
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?name", "?age"]);
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::String("Alice".to_string()));
assert_eq!(results[0][1], Value::Integer(30));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_query_no_results() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Query with no matching facts
let cmd = parse_datalog_command(r#"(query [:find ?name :where [?e :person/name ?name]])"#)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?name"]);
assert_eq!(results.len(), 0);
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_retract() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Add a fact
let alice_id = Uuid::new_v4();
storage
.transact(
vec![(alice_id, ":person/age".to_string(), Value::Integer(30))],
None,
)
.unwrap();
// Verify it exists
let current_value = storage
.get_current_value(&alice_id, &":person/age".to_string())
.unwrap();
assert_eq!(current_value, Some(Value::Integer(30)));
// Small delay to ensure different timestamp
std::thread::sleep(std::time::Duration::from_millis(2));
// Retract it using UUID-based entity reference
let cmd = parse_datalog_command(
format!(r#"(retract [[#uuid "{}" :person/age 30]])"#, alice_id).as_str(),
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::Retracted(tx_id) => {
assert!(tx_id > 0);
}
_ => panic!("Expected Retracted result"),
}
// Verify it's retracted (current value should be None)
let current_value = storage
.get_current_value(&alice_id, &":person/age".to_string())
.unwrap();
assert_eq!(current_value, None);
}
#[test]
fn test_transact_with_keyword_entity() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Transact with keyword-based entity (will be converted to deterministic UUID)
let cmd = parse_datalog_command(
r#"(transact [[:alice :person/name "Alice"]
[:alice :person/age 30]])"#,
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::Transacted(_) => {}
_ => panic!("Expected Transacted result"),
}
// Query to verify both facts share the same entity
let query_cmd = parse_datalog_command(
r#"(query [:find ?name ?age
:where [?e :person/name ?name]
[?e :person/age ?age]])"#,
)
.unwrap();
let result = executor.execute(query_cmd).unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::String("Alice".to_string()));
assert_eq!(results[0][1], Value::Integer(30));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_register_rule() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Parse and execute a rule command
let cmd =
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap();
let result = executor.execute(cmd).unwrap();
assert_eq!(result, QueryResult::Ok);
// Verify rule was registered
let registry = executor.rules();
let rules = registry.read().unwrap().get_rules("reachable");
assert_eq!(rules.len(), 1);
}
#[test]
fn test_register_multiple_rules_same_predicate() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Register base case
let cmd1 =
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap();
executor.execute(cmd1).unwrap();
// Register recursive case
let cmd2 = parse_datalog_command(
r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#,
)
.unwrap();
executor.execute(cmd2).unwrap();
// Verify both rules registered
let registry = executor.rules();
let rules = registry.read().unwrap().get_rules("reachable");
assert_eq!(rules.len(), 2);
}
#[test]
fn test_register_rules_different_predicates() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Register reachable rule
let cmd1 =
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap();
executor.execute(cmd1).unwrap();
// Register ancestor rule
let cmd2 = parse_datalog_command(r#"(rule [(ancestor ?a ?d) [?a :parent ?d]])"#).unwrap();
executor.execute(cmd2).unwrap();
// Verify both predicates have rules
let registry = executor.rules();
let reg_read = registry.read().unwrap();
assert!(reg_read.has_rule("reachable"));
assert!(reg_read.has_rule("ancestor"));
assert_eq!(reg_read.predicate_count(), 2);
}
#[test]
fn test_query_with_rule_invocation() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Create graph: A->B, A->C
let a = Uuid::new_v4();
let b = Uuid::new_v4();
let c = Uuid::new_v4();
storage
.transact(
vec![
(a, ":connected".to_string(), Value::Ref(b)),
(a, ":connected".to_string(), Value::Ref(c)),
],
None,
)
.unwrap();
// Register reachable rule (base case only - no recursion yet)
let rule1 =
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap();
executor.execute(rule1).unwrap();
// Query using rule invocation: find all nodes reachable from A
let query_str = format!(
r#"(query [:find ?to :where (reachable #uuid "{}" ?to)])"#,
a
);
let query_cmd = parse_datalog_command(&query_str).unwrap();
let result = executor.execute(query_cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?to"]);
// Should find B and C (direct connections)
assert_eq!(results.len(), 2);
// Collect result UUIDs
let result_uuids: Vec<Uuid> = results
.iter()
.map(|row| match &row[0] {
Value::Ref(uuid) => *uuid,
_ => panic!("Expected Ref value"),
})
.collect();
assert!(result_uuids.contains(&b));
assert!(result_uuids.contains(&c));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_query_mixed_pattern_and_rule() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Create graph with names: A->B, A->C, and give B a name
let a = Uuid::new_v4();
let b = Uuid::new_v4();
let c = Uuid::new_v4();
storage
.transact(
vec![
(a, ":connected".to_string(), Value::Ref(b)),
(a, ":connected".to_string(), Value::Ref(c)),
(
b,
":person/name".to_string(),
Value::String("Bob".to_string()),
),
],
None,
)
.unwrap();
// Register reachable rule (base case only - no recursion yet)
executor
.execute(
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap(),
)
.unwrap();
// Query: find names of nodes reachable from A
let query_str = format!(
r#"(query [:find ?name :where (reachable #uuid "{}" ?to) [?to :person/name ?name]])"#,
a
);
let query_cmd = parse_datalog_command(&query_str).unwrap();
let result = executor.execute(query_cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?name"]);
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::String("Bob".to_string()));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_query_with_recursive_transitive_closure() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Create graph: A->B->C
let a = Uuid::new_v4();
let b = Uuid::new_v4();
let c = Uuid::new_v4();
storage
.transact(
vec![
(a, ":connected".to_string(), Value::Ref(b)),
(b, ":connected".to_string(), Value::Ref(c)),
],
None,
)
.unwrap();
// Register reachable rules (base + recursive)
executor
.execute(
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap(),
)
.unwrap();
executor
.execute(
parse_datalog_command(
r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#,
)
.unwrap(),
)
.unwrap();
// Query: find all nodes reachable from A
let query_str = format!(
r#"(query [:find ?to :where (reachable #uuid "{}" ?to)])"#,
a
);
let query_cmd = parse_datalog_command(&query_str).unwrap();
let result = executor.execute(query_cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?to"]);
// Should find B and C via transitive closure
assert_eq!(results.len(), 2);
// Collect result UUIDs
let result_uuids: Vec<Uuid> = results
.iter()
.map(|row| match &row[0] {
Value::Ref(uuid) => *uuid,
_ => panic!("Expected Ref value"),
})
.collect();
assert!(result_uuids.contains(&b));
assert!(result_uuids.contains(&c));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_default_query_filters_to_currently_valid() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
let alice = Uuid::new_v4();
// Fact valid forever (default) - tx_count=1
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":person/name".to_string()),
EdnValue::String("Alice".to_string()),
)],
valid_from: None,
valid_to: None,
}))
.unwrap();
// Fact with valid_to in the past (expired) - tx_count=2
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":employment/status".to_string()),
EdnValue::Keyword(":active".to_string()),
)],
valid_from: Some(1000_i64),
valid_to: Some(2000_i64), // expired long ago
}))
.unwrap();
// Default query (no :valid-at) should only return the forever-valid fact
let result = executor
.execute(DatalogCommand::Query(DatalogQuery::new(
vec![FindSpec::Variable("?attr".to_string())],
vec![WhereClause::Pattern(Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Symbol("?attr".to_string()),
EdnValue::Symbol("?v".to_string()),
))],
)))
.unwrap();
let rows = match result {
QueryResult::QueryResults { results, .. } => results,
_ => panic!("expected query results"),
};
assert_eq!(rows.len(), 1); // only the name fact
}
#[test]
fn test_as_of_counter_shows_past_state() {
use crate::query::datalog::types::AsOf;
use crate::query::datalog::types::ValidAt;
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let alice = Uuid::new_v4();
// tx_count=1: assert name
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":person/name".to_string()),
EdnValue::String("Alice".to_string()),
)],
valid_from: None,
valid_to: None,
}))
.unwrap();
// tx_count=2: assert age
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":person/age".to_string()),
EdnValue::Integer(30),
)],
valid_from: None,
valid_to: None,
}))
.unwrap();
// :as-of 1 → only name fact visible (age was added at tx_count=2)
let result = executor
.execute(DatalogCommand::Query(DatalogQuery {
find: vec![FindSpec::Variable("?attr".to_string())],
where_clauses: vec![WhereClause::Pattern(Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Symbol("?attr".to_string()),
EdnValue::Symbol("?v".to_string()),
))],
as_of: Some(AsOf::Counter(1)),
valid_at: Some(ValidAt::AnyValidTime),
with_vars: Vec::new(),
}))
.unwrap();
let rows = match result {
QueryResult::QueryResults { results, .. } => results,
_ => panic!("expected query results"),
};
assert_eq!(rows.len(), 1);
}
#[test]
fn test_valid_at_any_valid_time_shows_all() {
use crate::query::datalog::types::ValidAt;
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let alice = Uuid::new_v4();
// Fact valid forever (default)
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":person/name".to_string()),
EdnValue::String("Alice".to_string()),
)],
valid_from: None,
valid_to: None,
}))
.unwrap();
// Fact with valid_to already in the past
executor
.execute(DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Keyword(":employment/status".to_string()),
EdnValue::Keyword(":active".to_string()),
)],
valid_from: Some(1000_i64),
valid_to: Some(2000_i64), // expired
}))
.unwrap();
// :valid-at :any-valid-time → both facts returned
let result = executor
.execute(DatalogCommand::Query(DatalogQuery {
find: vec![FindSpec::Variable("?attr".to_string())],
where_clauses: vec![WhereClause::Pattern(Pattern::new(
EdnValue::Uuid(alice),
EdnValue::Symbol("?attr".to_string()),
EdnValue::Symbol("?v".to_string()),
))],
as_of: None,
valid_at: Some(ValidAt::AnyValidTime),
with_vars: Vec::new(),
}))
.unwrap();
let rows = match result {
QueryResult::QueryResults { results, .. } => results,
_ => panic!("expected query results"),
};
assert_eq!(rows.len(), 2);
}
#[test]
fn test_query_recursive_with_mixed_patterns() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
// Create graph: A->B->C, give C a name
let a = Uuid::new_v4();
let b = Uuid::new_v4();
let c = Uuid::new_v4();
storage
.transact(
vec![
(a, ":connected".to_string(), Value::Ref(b)),
(b, ":connected".to_string(), Value::Ref(c)),
(
c,
":person/name".to_string(),
Value::String("Charlie".to_string()),
),
],
None,
)
.unwrap();
// Register recursive reachable rules
executor
.execute(
parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#).unwrap(),
)
.unwrap();
executor
.execute(
parse_datalog_command(
r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#,
)
.unwrap(),
)
.unwrap();
// Query: find names of nodes transitively reachable from A
let query_str = format!(
r#"(query [:find ?name :where (reachable #uuid "{}" ?to) [?to :person/name ?name]])"#,
a
);
let query_cmd = parse_datalog_command(&query_str).unwrap();
let result = executor.execute(query_cmd).unwrap();
match result {
QueryResult::QueryResults { vars, results } => {
assert_eq!(vars, vec!["?name"]);
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::String("Charlie".to_string()));
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_query_not_as_pure_filter() {
// Query: [:find ?e :where [?e :applied true] (not [?e :rejected true])]
// No rule invocations — pure not-filter path in execute_query.
use crate::query::datalog::types::WhereClause;
let storage = FactStorage::new();
let alice = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
let bob = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();
// alice: applied + rejected
storage
.transact(
vec![
(alice, ":applied".to_string(), Value::Boolean(true)),
(alice, ":rejected".to_string(), Value::Boolean(true)),
],
None,
)
.unwrap();
// bob: applied only
storage
.transact(
vec![(bob, ":applied".to_string(), Value::Boolean(true))],
None,
)
.unwrap();
let query = DatalogQuery::new(
vec![FindSpec::Variable("?e".to_string())],
vec![
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?e".to_string()),
EdnValue::Keyword(":applied".to_string()),
EdnValue::Boolean(true),
)),
WhereClause::Not(vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?e".to_string()),
EdnValue::Keyword(":rejected".to_string()),
EdnValue::Boolean(true),
))]),
],
);
let executor = DatalogExecutor::new(storage);
let result = executor
.execute(crate::query::datalog::types::DatalogCommand::Query(query))
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "only bob should pass (alice is rejected)");
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_query_with_rules_not_in_query_body() {
// Query: [:find ?x :where (reachable ?_a ?x) (not [?x :blocked true])]
// rule invocation + pattern-not in same query body
use crate::query::datalog::types::{Pattern, WhereClause};
let storage = FactStorage::new();
let a = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
let b = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();
let c = uuid::Uuid::parse_str("00000000-0000-0000-0000-000000000003").unwrap();
storage
.transact(
vec![
(a, ":connected".to_string(), Value::Ref(b)),
(a, ":connected".to_string(), Value::Ref(c)),
(c, ":blocked".to_string(), Value::Boolean(true)),
],
None,
)
.unwrap();
let rules = Arc::new(RwLock::new(RuleRegistry::new()));
// reachable(?from ?to) :- [?from :connected ?to]
{
use crate::query::datalog::types::{Rule, WhereClause as WC};
let rule = Rule {
head: vec![
EdnValue::Symbol("reachable".to_string()),
EdnValue::Symbol("?from".to_string()),
EdnValue::Symbol("?to".to_string()),
],
body: vec![WC::Pattern(Pattern::new(
EdnValue::Symbol("?from".to_string()),
EdnValue::Keyword(":connected".to_string()),
EdnValue::Symbol("?to".to_string()),
))],
};
rules
.write()
.unwrap()
.register_rule("reachable".to_string(), rule)
.unwrap();
}
let query = DatalogQuery::new(
vec![FindSpec::Variable("?x".to_string())],
vec![
WhereClause::RuleInvocation {
predicate: "reachable".to_string(),
args: vec![
EdnValue::Symbol("?_a".to_string()),
EdnValue::Symbol("?x".to_string()),
],
},
WhereClause::Not(vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":blocked".to_string()),
EdnValue::Boolean(true),
))]),
],
);
let executor = DatalogExecutor::new_with_rules(storage, rules);
let result = executor
.execute(crate::query::datalog::types::DatalogCommand::Query(query))
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
1,
"c should be excluded (blocked), only b passes"
);
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_query_not_join_basic() {
// Query: find entities that have :submitted but NO blocked dependency
// alice: submitted, has-dep dep1, dep1:blocked=true -> excluded
// bob: submitted, no deps -> included
let storage = FactStorage::new();
let alice = Uuid::new_v4();
let bob = Uuid::new_v4();
let dep1 = Uuid::new_v4();
storage
.transact(
vec![
(alice, ":submitted".to_string(), Value::Boolean(true)),
(alice, ":has-dep".to_string(), Value::Ref(dep1)),
(dep1, ":blocked".to_string(), Value::Boolean(true)),
(bob, ":submitted".to_string(), Value::Boolean(true)),
],
None,
)
.unwrap();
let query = DatalogQuery::new(
vec![FindSpec::Variable("?x".to_string())],
vec![
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":submitted".to_string()),
EdnValue::Boolean(true),
)),
WhereClause::NotJoin {
join_vars: vec!["?x".to_string()],
clauses: vec![
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":has-dep".to_string()),
EdnValue::Symbol("?d".to_string()),
)),
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?d".to_string()),
EdnValue::Keyword(":blocked".to_string()),
EdnValue::Boolean(true),
)),
],
},
],
);
let executor = DatalogExecutor::new(storage);
let result = executor
.execute(crate::query::datalog::types::DatalogCommand::Query(query))
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "only bob should be returned");
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_execute_query_with_rules_not_join_in_query_body() {
// Rule: (reachable ?x ?y) :- [?x :edge ?y]
// Query: find ?y reachable from root that do NOT have a blocked dep
let storage = FactStorage::new();
let root = Uuid::new_v4();
let a = Uuid::new_v4();
let b = Uuid::new_v4();
let dep1 = Uuid::new_v4();
storage
.transact(
vec![
(root, ":edge".to_string(), Value::Ref(a)),
(root, ":edge".to_string(), Value::Ref(b)),
(a, ":has-dep".to_string(), Value::Ref(dep1)),
(dep1, ":blocked".to_string(), Value::Boolean(true)),
],
None,
)
.unwrap();
let rules = Arc::new(RwLock::new(RuleRegistry::new()));
{
use crate::query::datalog::types::{Rule, WhereClause as WC};
let rule = Rule {
head: vec![
EdnValue::Symbol("reachable".to_string()),
EdnValue::Symbol("?x".to_string()),
EdnValue::Symbol("?y".to_string()),
],
body: vec![WC::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":edge".to_string()),
EdnValue::Symbol("?y".to_string()),
))],
};
rules
.write()
.unwrap()
.register_rule("reachable".to_string(), rule)
.unwrap();
}
let query = DatalogQuery::new(
vec![FindSpec::Variable("?y".to_string())],
vec![
WhereClause::RuleInvocation {
predicate: "reachable".to_string(),
args: vec![EdnValue::Uuid(root), EdnValue::Symbol("?y".to_string())],
},
WhereClause::NotJoin {
join_vars: vec!["?y".to_string()],
clauses: vec![
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?y".to_string()),
EdnValue::Keyword(":has-dep".to_string()),
EdnValue::Symbol("?d".to_string()),
)),
WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?d".to_string()),
EdnValue::Keyword(":blocked".to_string()),
EdnValue::Boolean(true),
)),
],
},
],
);
let executor = DatalogExecutor::new_with_rules(storage, rules);
let result = executor
.execute(crate::query::datalog::types::DatalogCommand::Query(query))
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
// a is excluded (has a blocked dep); b passes
assert_eq!(results.len(), 1, "only b should pass");
}
_ => panic!("Expected QueryResults"),
}
}
#[test]
fn test_optimizer_does_not_change_query_results() {
// A multi-pattern query that the optimizer would reorder.
// Results must be identical regardless of execution order.
let storage = FactStorage::new();
let alice = uuid::Uuid::new_v4();
let bob = uuid::Uuid::new_v4();
storage
.transact(
vec![
(
alice,
":name".to_string(),
Value::String("Alice".to_string()),
),
(alice, ":friend".to_string(), Value::Ref(bob)),
(bob, ":name".to_string(), Value::String("Bob".to_string())),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// Simple query: find all names (no join reordering needed)
let result = executor
.execute(
parse_datalog_command("(query [:find ?name :where [?e :name ?name]])").unwrap(),
)
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 2, "Alice and Bob both have names");
}
_ => panic!("Expected QueryResults"),
}
}
// Helper: build a binding map from key-value pairs
fn binding(pairs: &[(&str, Value)]) -> std::collections::HashMap<String, Value> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect()
}
#[test]
fn test_apply_aggregation_count_basic() {
let bindings = vec![
binding(&[("?e", Value::Integer(1))]),
binding(&[("?e", Value::Integer(2))]),
binding(&[("?e", Value::Integer(3))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "count".to_string(),
var: "?e".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results.len(), 1);
assert_eq!(results[0][0], Value::Integer(3));
}
#[test]
fn test_apply_aggregation_count_with_grouping() {
let bindings = vec![
binding(&[
("?dept", Value::String("eng".to_string())),
("?e", Value::Integer(1)),
]),
binding(&[
("?dept", Value::String("eng".to_string())),
("?e", Value::Integer(2)),
]),
binding(&[
("?dept", Value::String("hr".to_string())),
("?e", Value::Integer(3)),
]),
];
let find_specs = vec![
FindSpec::Variable("?dept".to_string()),
FindSpec::Aggregate {
func: "count".to_string(),
var: "?e".to_string(),
},
];
let mut results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
results.sort_by_key(|r| match &r[0] {
Value::String(s) => s.clone(),
_ => String::new(),
});
assert_eq!(results.len(), 2);
assert_eq!(
results[0],
vec![Value::String("eng".to_string()), Value::Integer(2)]
);
assert_eq!(
results[1],
vec![Value::String("hr".to_string()), Value::Integer(1)]
);
}
#[test]
fn test_apply_aggregation_count_distinct() {
let bindings = vec![
binding(&[("?v", Value::Integer(1))]),
binding(&[("?v", Value::Integer(1))]), // duplicate
binding(&[("?v", Value::Integer(2))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "count-distinct".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(2));
}
#[test]
fn test_apply_aggregation_count_empty_no_grouping_vars() {
// count with no grouping vars + zero bindings → [[0]]
let find_specs = vec![FindSpec::Aggregate {
func: "count".to_string(),
var: "?e".to_string(),
}];
let results =
apply_post_processing(vec![], &find_specs, &[], &FunctionRegistry::with_builtins())
.unwrap();
assert_eq!(results.len(), 1, "should return one row with 0");
assert_eq!(results[0][0], Value::Integer(0));
}
#[test]
fn test_apply_aggregation_count_empty_with_grouping_var() {
// count with grouping var + zero bindings → empty result
let find_specs = vec![
FindSpec::Variable("?dept".to_string()),
FindSpec::Aggregate {
func: "count".to_string(),
var: "?e".to_string(),
},
];
let results =
apply_post_processing(vec![], &find_specs, &[], &FunctionRegistry::with_builtins())
.unwrap();
assert_eq!(results.len(), 0, "should return empty set");
}
#[test]
fn test_apply_aggregation_sum_integers() {
let bindings = vec![
binding(&[("?v", Value::Integer(10))]),
binding(&[("?v", Value::Integer(20))]),
binding(&[("?v", Value::Integer(30))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "sum".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(60));
}
#[test]
fn test_apply_aggregation_sum_widens_to_float() {
let bindings = vec![
binding(&[("?v", Value::Integer(10))]),
binding(&[("?v", Value::Float(0.5))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "sum".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Float(10.5));
}
#[test]
fn test_apply_aggregation_sum_distinct_deduplicates() {
let bindings = vec![
binding(&[("?v", Value::Integer(5))]),
binding(&[("?v", Value::Integer(5))]), // duplicate
binding(&[("?v", Value::Integer(10))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "sum-distinct".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(15)); // 5 + 10, not 5 + 5 + 10
}
#[test]
fn test_apply_aggregation_sum_type_error() {
let bindings = vec![binding(&[("?v", Value::String("bad".to_string()))])];
let find_specs = vec![FindSpec::Aggregate {
func: "sum".to_string(),
var: "?v".to_string(),
}];
let result = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
);
assert!(result.is_err(), "sum of string should fail");
}
#[test]
fn test_apply_aggregation_min_integers() {
let bindings = vec![
binding(&[("?v", Value::Integer(30))]),
binding(&[("?v", Value::Integer(10))]),
binding(&[("?v", Value::Integer(20))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "min".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(10));
}
#[test]
fn test_apply_aggregation_max_strings() {
let bindings = vec![
binding(&[("?v", Value::String("apple".to_string()))]),
binding(&[("?v", Value::String("zebra".to_string()))]),
binding(&[("?v", Value::String("mango".to_string()))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "max".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::String("zebra".to_string()));
}
#[test]
fn test_apply_aggregation_min_type_error_boolean() {
let bindings = vec![binding(&[("?v", Value::Boolean(true))])];
let find_specs = vec![FindSpec::Aggregate {
func: "min".to_string(),
var: "?v".to_string(),
}];
let result = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
);
assert!(result.is_err(), "min of boolean should fail");
}
#[test]
fn test_apply_aggregation_min_mixed_int_float_error() {
let bindings = vec![
binding(&[("?v", Value::Integer(1))]),
binding(&[("?v", Value::Float(2.0))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "min".to_string(),
var: "?v".to_string(),
}];
let result = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
);
assert!(result.is_err(), "min of mixed Integer/Float should fail");
}
#[test]
fn test_apply_aggregation_skips_nulls_in_sum() {
let bindings = vec![
binding(&[("?v", Value::Integer(10))]),
binding(&[("?v", Value::Null)]),
binding(&[("?v", Value::Integer(20))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "sum".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(30));
}
#[test]
fn test_apply_aggregation_skips_nulls_in_count() {
let bindings = vec![
binding(&[("?v", Value::Integer(1))]),
binding(&[("?v", Value::Null)]),
binding(&[("?v", Value::Integer(2))]),
];
let find_specs = vec![FindSpec::Aggregate {
func: "count".to_string(),
var: "?v".to_string(),
}];
let results = apply_post_processing(
bindings,
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results[0][0], Value::Integer(2)); // null not counted
}
#[test]
fn test_apply_aggregation_sum_empty_bindings() {
let find_specs = vec![FindSpec::Aggregate {
func: "sum".to_string(),
var: "?v".to_string(),
}];
let results =
apply_post_processing(vec![], &find_specs, &[], &FunctionRegistry::with_builtins())
.unwrap();
assert_eq!(results.len(), 0, "sum on empty should return empty set");
}
#[test]
fn test_apply_aggregation_with_var_grouping() {
// :with ?e adds ?e to the group key. Two entities with same dept but different ?e
// form separate groups.
let bindings = vec![
binding(&[
("?dept", Value::String("eng".to_string())),
("?salary", Value::Integer(50)),
("?e", Value::Integer(1)),
]),
binding(&[
("?dept", Value::String("eng".to_string())),
("?salary", Value::Integer(50)),
("?e", Value::Integer(2)),
]),
];
let find_specs = vec![
FindSpec::Variable("?dept".to_string()),
FindSpec::Aggregate {
func: "sum".to_string(),
var: "?salary".to_string(),
},
];
// Without :with: group key = ("eng",). Both bindings in one group → sum = 100.
let results_no_with = apply_post_processing(
bindings.clone(),
&find_specs,
&[],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results_no_with.len(), 1);
assert_eq!(results_no_with[0][1], Value::Integer(100));
// With :with ?e: group key = ("eng", e). Two separate groups → two rows, each sum = 50.
let results_with = apply_post_processing(
bindings,
&find_specs,
&["?e".to_string()],
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(results_with.len(), 2);
assert_eq!(results_with[0][1], Value::Integer(50));
}
#[test]
fn test_filter_facts_for_query_returns_net_asserted_slice() {
// Setup: one fact asserted then retracted, one fact left standing.
// After filter_facts_for_query, only the standing fact should appear.
// The return type (Arc<[Fact]>) exposes .len() and index access [0].
use uuid::Uuid;
let storage = FactStorage::new();
let alice = Uuid::new_v4();
// tx 1: assert name
storage
.transact(
vec![(
alice,
":person/name".to_string(),
Value::String("Alice".to_string()),
)],
None,
)
.unwrap();
// tx 2: retract name — net state for name is now gone
storage
.retract(vec![(
alice,
":person/name".to_string(),
Value::String("Alice".to_string()),
)])
.unwrap();
// tx 3: assert age — this is the only net-asserted fact
storage
.transact(
vec![(alice, ":person/age".to_string(), Value::Integer(30))],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
let query = DatalogQuery {
find: vec![],
where_clauses: vec![],
as_of: None,
valid_at: Some(ValidAt::AnyValidTime),
with_vars: vec![],
};
let facts = executor.filter_facts_for_query(&query).unwrap();
assert_eq!(facts.len(), 1, "expected exactly 1 net-asserted fact");
assert_eq!(facts[0].attribute, ":person/age");
}
#[test]
fn test_filter_facts_for_query_valid_time_filter() {
// Setup: one fact with a narrow valid-time window (1000..2000), one open-ended.
// Query with valid_at inside the window → both facts visible.
// Query with valid_at outside the window → only the open-ended fact visible.
// filter_facts_for_query now returns Result<Arc<[Fact]>> (changed in Task 5).
use crate::graph::types::TransactOptions;
use uuid::Uuid;
let storage = FactStorage::new();
let alice = Uuid::new_v4();
// Fact valid only during [1000, 2000)
storage
.transact(
vec![(
alice,
":employment/status".to_string(),
Value::String("active".to_string()),
)],
Some(TransactOptions::new(Some(1000_i64), Some(2000_i64))),
)
.unwrap();
// Fact valid forever (open-ended): explicit valid_from=0 so it is visible at t=1500 and t=3000.
// Passing None would set valid_from=tx_id_now() (current epoch ms ≈ 1.7T), which is
// far beyond the test's query timestamps.
storage
.transact(
vec![(
alice,
":person/name".to_string(),
Value::String("Alice".to_string()),
)],
Some(TransactOptions::new(Some(0_i64), None)),
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// Query inside the window: both facts should be visible
let query_inside = DatalogQuery {
find: vec![],
where_clauses: vec![],
as_of: None,
valid_at: Some(ValidAt::Timestamp(1500_i64)),
with_vars: vec![],
};
let facts_inside = executor.filter_facts_for_query(&query_inside).unwrap();
assert_eq!(facts_inside.len(), 2, "both facts visible at t=1500");
// Query outside the window: only the open-ended name fact should be visible
let query_outside = DatalogQuery {
find: vec![],
where_clauses: vec![],
as_of: None,
valid_at: Some(ValidAt::Timestamp(3000_i64)),
with_vars: vec![],
};
let facts_outside = executor.filter_facts_for_query(&query_outside).unwrap();
assert_eq!(
facts_outside.len(),
1,
"only open-ended fact visible at t=3000"
);
assert_eq!(facts_outside[0].attribute, ":person/name");
}
}
#[cfg(test)]
mod expr_eval_tests {
use super::*;
use crate::graph::types::Value;
use crate::query::datalog::parser::parse_datalog_command;
use crate::query::datalog::types::{BinOp, Expr, UnaryOp, WhereClause};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;
fn b(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect()
}
#[test]
fn test_eval_lit() {
let e = Expr::Lit(Value::Integer(42));
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Integer(42)));
}
#[test]
fn test_eval_var_bound() {
let e = Expr::Var("?x".to_string());
let binding = b(&[("?x", Value::Integer(10))]);
assert_eq!(eval_expr(&e, &binding, None), Ok(Value::Integer(10)));
}
#[test]
fn test_eval_var_unbound_is_err() {
let e = Expr::Var("?x".to_string());
assert_eq!(eval_expr(&e, &HashMap::new(), None), Err(()));
}
#[test]
fn test_eval_lt_true() {
let e = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Var("?v".to_string())),
Box::new(Expr::Lit(Value::Integer(100))),
);
let binding = b(&[("?v", Value::Integer(50))]);
assert_eq!(eval_expr(&e, &binding, None), Ok(Value::Boolean(true)));
}
#[test]
fn test_eval_lt_false() {
let e = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Var("?v".to_string())),
Box::new(Expr::Lit(Value::Integer(100))),
);
let binding = b(&[("?v", Value::Integer(150))]);
assert_eq!(eval_expr(&e, &binding, None), Ok(Value::Boolean(false)));
}
#[test]
fn test_eval_add_integers() {
let e = Expr::BinOp(
BinOp::Add,
Box::new(Expr::Var("?a".to_string())),
Box::new(Expr::Var("?b".to_string())),
);
let binding = b(&[("?a", Value::Integer(3)), ("?b", Value::Integer(4))]);
assert_eq!(eval_expr(&e, &binding, None), Ok(Value::Integer(7)));
}
#[test]
fn test_eval_add_int_float_promotes() {
let e = Expr::BinOp(
BinOp::Add,
Box::new(Expr::Lit(Value::Integer(1))),
Box::new(Expr::Lit(Value::Float(1.5))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Float(2.5)));
}
#[test]
fn test_eval_div_integer_truncates() {
let e = Expr::BinOp(
BinOp::Div,
Box::new(Expr::Lit(Value::Integer(5))),
Box::new(Expr::Lit(Value::Integer(2))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Integer(2)));
}
#[test]
fn test_eval_div_by_zero_is_err() {
let e = Expr::BinOp(
BinOp::Div,
Box::new(Expr::Lit(Value::Integer(5))),
Box::new(Expr::Lit(Value::Integer(0))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Err(()));
}
#[test]
fn test_eval_eq_strings() {
let e = Expr::BinOp(
BinOp::Eq,
Box::new(Expr::Lit(Value::String("Alice".to_string()))),
Box::new(Expr::Lit(Value::String("Alice".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_eval_eq_int_float_false() {
// Different Value variants → structural inequality
let e = Expr::BinOp(
BinOp::Eq,
Box::new(Expr::Lit(Value::Integer(1))),
Box::new(Expr::Lit(Value::Float(1.0))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(false))
);
}
#[test]
fn test_eval_type_mismatch_comparison_is_err() {
let e = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Lit(Value::String("hello".to_string()))),
Box::new(Expr::Lit(Value::Integer(100))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Err(()));
}
#[test]
fn test_eval_string_q_true() {
let e = Expr::UnaryOp(
UnaryOp::StringQ,
Box::new(Expr::Lit(Value::String("hi".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_eval_string_q_false() {
let e = Expr::UnaryOp(UnaryOp::StringQ, Box::new(Expr::Lit(Value::Integer(1))));
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(false))
);
}
#[test]
fn test_eval_starts_with_true() {
let e = Expr::BinOp(
BinOp::StartsWith,
Box::new(Expr::Lit(Value::String("foobar".to_string()))),
Box::new(Expr::Lit(Value::String("foo".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_eval_ends_with_true() {
let e = Expr::BinOp(
BinOp::EndsWith,
Box::new(Expr::Lit(Value::String("foobar".to_string()))),
Box::new(Expr::Lit(Value::String("bar".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_eval_contains_true() {
let e = Expr::BinOp(
BinOp::Contains,
Box::new(Expr::Lit(Value::String("engineer at co".to_string()))),
Box::new(Expr::Lit(Value::String("engineer".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_eval_matches_true() {
let re = regex_lite::Regex::new("^[^@]+@[^@]+$").unwrap();
let e = Expr::BinOp(
BinOp::Matches {
regex: re,
pattern: "^[^@]+@[^@]+$".to_string(),
},
Box::new(Expr::Lit(Value::String("test@example.com".to_string()))),
Box::new(Expr::Lit(Value::String("^[^@]+@[^@]+$".to_string()))),
);
assert_eq!(
eval_expr(&e, &HashMap::new(), None),
Ok(Value::Boolean(true))
);
}
#[test]
fn test_is_truthy() {
assert!(is_truthy(&Value::Boolean(true)));
assert!(!is_truthy(&Value::Boolean(false)));
assert!(is_truthy(&Value::Integer(1)));
assert!(!is_truthy(&Value::Integer(0)));
assert!(is_truthy(&Value::Float(0.1)));
assert!(!is_truthy(&Value::Float(0.0)));
assert!(!is_truthy(&Value::Null));
assert!(!is_truthy(&Value::String("hi".to_string())));
}
#[test]
fn test_apply_expr_filter_keeps_truthy() {
// [(< ?v 100)] — keeps row where ?v < 100
use crate::query::datalog::types::WhereClause;
let expr = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Var("?v".to_string())),
Box::new(Expr::Lit(Value::Integer(100))),
);
let clauses = vec![WhereClause::Expr {
expr,
binding: None,
}];
let bindings = vec![
b(&[("?v", Value::Integer(50))]),
b(&[("?v", Value::Integer(150))]),
];
let result =
apply_expr_clauses(bindings, &clauses, &FunctionRegistry::with_builtins()).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].get("?v"), Some(&Value::Integer(50)));
}
#[test]
fn test_apply_expr_binding_extends_row() {
// [(+ ?a ?b) ?sum] — binds ?sum
use crate::query::datalog::types::WhereClause;
let expr = Expr::BinOp(
BinOp::Add,
Box::new(Expr::Var("?a".to_string())),
Box::new(Expr::Var("?b".to_string())),
);
let clauses = vec![WhereClause::Expr {
expr,
binding: Some("?sum".to_string()),
}];
let bindings = vec![b(&[("?a", Value::Integer(3)), ("?b", Value::Integer(4))])];
let result =
apply_expr_clauses(bindings, &clauses, &FunctionRegistry::with_builtins()).unwrap();
assert_eq!(result.len(), 1);
assert_eq!(result[0].get("?sum"), Some(&Value::Integer(7)));
}
#[test]
fn test_apply_expr_type_mismatch_drops_row() {
// [(< ?v 100)] where ?v = "hello" — type mismatch silently drops row
use crate::query::datalog::types::WhereClause;
let expr = Expr::BinOp(
BinOp::Lt,
Box::new(Expr::Var("?v".to_string())),
Box::new(Expr::Lit(Value::Integer(100))),
);
let clauses = vec![WhereClause::Expr {
expr,
binding: None,
}];
let bindings = vec![b(&[("?v", Value::String("hello".to_string()))])];
let result =
apply_expr_clauses(bindings, &clauses, &FunctionRegistry::with_builtins()).unwrap();
assert_eq!(result.len(), 0);
}
#[test]
fn test_execute_expr_filter_lt() {
use crate::graph::storage::FactStorage;
use crate::query::datalog::rules::RuleRegistry;
use std::sync::{Arc, RwLock};
let storage = FactStorage::new();
let rules = Arc::new(RwLock::new(RuleRegistry::new()));
let executor = DatalogExecutor::new_with_rules(storage.clone(), rules);
// Transact two items with different prices
executor
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(transact [[:item1 :item/price 50] [:item2 :item/price 150]])",
)
.unwrap(),
)
.unwrap();
// Query: find items where price < 100
let result = executor.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :item/price ?p] [(< ?p 100)]])",
)
.unwrap(),
);
assert!(result.is_ok(), "expr filter query failed");
match result.unwrap() {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "expected exactly one result");
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_apply_or_clauses_union_from_two_branches() {
// e1 has :color :red, e2 has :color :blue.
// or-only where clause: (or [?e :color :red] [?e :color :blue])
// Without apply_or_clauses, get_patterns() returns [] → match_patterns returns
// [{}] (one empty binding) → extract_variables finds no ?e binding → 0 results.
// With apply_or_clauses, both entities are returned → 2 results.
use uuid::Uuid;
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(e1, ":color".to_string(), Value::Keyword(":red".to_string())),
(
e2,
":color".to_string(),
Value::Keyword(":blue".to_string()),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage.clone());
let cmd = crate::query::datalog::parser::parse_datalog_command(
r#"(query [:find ?e
:where (or [?e :color :red] [?e :color :blue])])"#,
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 2, "both entities should match via or");
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_apply_or_clauses_deduplication() {
// e1 has :color :red AND :shape :circle.
// or clause: (or [?e :color :red] [?e :shape :circle])
// Without apply_or_clauses: or is skipped → 0 results (no non-or patterns).
// With apply_or_clauses: e1 is returned by both branches → deduplicated to 1 result.
use uuid::Uuid;
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
storage
.transact(
vec![
(e1, ":color".to_string(), Value::Keyword(":red".to_string())),
(
e1,
":shape".to_string(),
Value::Keyword(":circle".to_string()),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage.clone());
let cmd = crate::query::datalog::parser::parse_datalog_command(
r#"(query [:find ?e
:where (or [?e :color :red] [?e :shape :circle])])"#,
)
.unwrap();
let result = executor.execute(cmd).unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
1,
"one entity matched by both branches → deduplicated"
);
}
_ => panic!("expected QueryResults"),
}
}
// ── Stream 3: branches unreachable via the parser ─────────────────────────
#[test]
fn execute_transact_non_keyword_attribute_error() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Construct a transact with a String attribute (not a keyword)
let cmd = DatalogCommand::Transact(Transaction {
facts: vec![Pattern::new(
EdnValue::Keyword(":e".to_string()),
EdnValue::String("not-a-keyword".to_string()),
EdnValue::String("value".to_string()),
)],
valid_from: None,
valid_to: None,
});
let r = executor.execute(cmd);
assert!(r.is_err(), "non-keyword attribute in transact must fail");
}
#[test]
fn execute_retract_non_keyword_attribute_error() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = DatalogCommand::Retract(Transaction {
facts: vec![Pattern::new(
EdnValue::Keyword(":e".to_string()),
EdnValue::Integer(42),
EdnValue::String("value".to_string()),
)],
valid_from: None,
valid_to: None,
});
let r = executor.execute(cmd);
assert!(r.is_err(), "non-keyword attribute in retract must fail");
}
#[test]
fn execute_transact_pseudo_attr_error() {
// Exercises executor.rs line 103: Pseudo(_) arm in execute_transact
use crate::query::datalog::types::{PseudoAttr, Transaction};
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = DatalogCommand::Transact(Transaction {
facts: vec![Pattern::pseudo(
EdnValue::Keyword(":e".to_string()),
PseudoAttr::ValidFrom,
EdnValue::Integer(0),
)],
valid_from: None,
valid_to: None,
});
let r = executor.execute(cmd);
assert!(r.is_err(), "transacting a pseudo-attribute must fail");
}
#[test]
fn execute_retract_pseudo_attr_error() {
// Exercises executor.rs line 139: Pseudo(_) arm in execute_retract
use crate::query::datalog::types::{PseudoAttr, Transaction};
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = DatalogCommand::Retract(Transaction {
facts: vec![Pattern::pseudo(
EdnValue::Keyword(":e".to_string()),
PseudoAttr::TxCount,
EdnValue::Integer(0),
)],
valid_from: None,
valid_to: None,
});
let r = executor.execute(cmd);
assert!(r.is_err(), "retracting a pseudo-attribute must fail");
}
#[test]
fn execute_rule_empty_head_error() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = DatalogCommand::Rule(Rule {
head: vec![],
body: vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":a".to_string()),
EdnValue::Symbol("?v".to_string()),
))],
});
let r = executor.execute(cmd);
assert!(r.is_err(), "rule with empty head must fail");
}
#[test]
fn execute_rule_non_symbol_head_error() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = DatalogCommand::Rule(Rule {
head: vec![EdnValue::Integer(99)], // not a Symbol
body: vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":a".to_string()),
EdnValue::Symbol("?v".to_string()),
))],
});
let r = executor.execute(cmd);
assert!(r.is_err(), "rule head starting with non-symbol must fail");
}
// ── Float arithmetic edge cases ──────────────────────────────────────────
#[test]
fn test_eval_float_div_by_zero_is_err() {
// Line 1096: rf == 0.0 → Err(()) for float division
let e = Expr::BinOp(
BinOp::Div,
Box::new(Expr::Lit(Value::Float(5.0))),
Box::new(Expr::Lit(Value::Float(0.0))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Err(()));
}
#[test]
fn test_eval_float_div_succeeds() {
// Line 1096 false branch: rf != 0.0 → Ok(Float)
let e = Expr::BinOp(
BinOp::Div,
Box::new(Expr::Lit(Value::Float(6.0))),
Box::new(Expr::Lit(Value::Float(2.0))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Float(3.0)));
}
#[test]
fn test_eval_float_sub() {
// Line 1079-1085: float subtraction
let e = Expr::BinOp(
BinOp::Sub,
Box::new(Expr::Lit(Value::Float(5.0))),
Box::new(Expr::Lit(Value::Float(2.0))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Float(3.0)));
}
#[test]
fn test_eval_float_mul() {
// Line 1087-1093: float multiplication
let e = Expr::BinOp(
BinOp::Mul,
Box::new(Expr::Lit(Value::Float(3.0))),
Box::new(Expr::Lit(Value::Float(4.0))),
);
assert_eq!(eval_expr(&e, &HashMap::new(), None), Ok(Value::Float(12.0)));
}
// ── Aggregation edge cases ────────────────────────────────────────────────
#[test]
fn test_agg_count_empty_bindings_returns_zero() {
// (count ?x) with no matching facts → zero bindings → special-case returns 0
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command("(query [:find (count ?x) :where [?x :no-such-attr _]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "should return one row with count 0");
assert_eq!(results[0][0], crate::graph::types::Value::Integer(0));
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_agg_sum_empty_no_grouping_returns_zero() {
// (sum ?v) with no matching facts and no grouping vars
// bindings is empty → `has_grouping_vars` is false but it's not count → returns []
let storage = FactStorage::new();
storage
.transact(
vec![(
Uuid::new_v4(),
":item/price".to_string(),
crate::graph::types::Value::Integer(50),
)],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// Query for non-existing attribute to produce empty bindings, then sum
let cmd = parse_datalog_command("(query [:find (sum ?v) :where [?x :no-such-attr ?v]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
// empty bindings with non-count agg and no grouping → returns []
assert_eq!(results.len(), 0, "empty bindings with sum returns no rows");
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_agg_sum_distinct_float_values() {
// sum-distinct on float values exercises the SumDistinct + has_float path
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":item/weight".to_string(),
crate::graph::types::Value::Float(1.5),
),
(
e2,
":item/weight".to_string(),
crate::graph::types::Value::Float(1.5),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
let cmd =
parse_datalog_command("(query [:find (sum-distinct ?w) :where [?e :item/weight ?w]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
// Both have weight 1.5 but sum-distinct deduplicates → result is 1.5
assert_eq!(results.len(), 1, "expected one result row");
assert_eq!(
results[0][0],
crate::graph::types::Value::Float(1.5),
"sum-distinct of [1.5, 1.5] should be 1.5"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_agg_min_max_on_all_null_group_skips_row() {
// min/max on a group where all values are Null → row is skipped
// We insert a fact with value Null and query for min
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
storage
.transact(
vec![(
e1,
":item/score".to_string(),
crate::graph::types::Value::Null,
)],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// min on only Null values → "no non-null values in group" → row skipped → 0 rows
let cmd = parse_datalog_command("(query [:find (min ?s) :where [?e :item/score ?s]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
0,
"min on all-null group should produce 0 rows"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_agg_min_on_strings() {
// min on strings exercises the String comparison path in apply_agg_func
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":item/name".to_string(),
crate::graph::types::Value::String("banana".to_string()),
),
(
e2,
":item/name".to_string(),
crate::graph::types::Value::String("apple".to_string()),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command("(query [:find (min ?n) :where [?e :item/name ?n]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "expected one result");
assert_eq!(
results[0][0],
crate::graph::types::Value::String("apple".to_string()),
"min of strings should return lexicographically smallest"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_agg_max_on_floats() {
// max on floats exercises the Float comparison path
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":item/score".to_string(),
crate::graph::types::Value::Float(3.5),
),
(
e2,
":item/score".to_string(),
crate::graph::types::Value::Float(2.5),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command("(query [:find (max ?s) :where [?e :item/score ?s]])")
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "expected one result");
assert_eq!(
results[0][0],
crate::graph::types::Value::Float(3.5),
"max of floats should return largest"
);
}
_ => panic!("expected QueryResults"),
}
}
// ── evaluate_branch / apply_or_clauses edge cases ────────────────────────
#[test]
fn test_evaluate_branch_with_timestamp_valid_at() {
// Exercises executor.rs lines 930-931: evaluate_branch with Timestamp/AnyValidTime
use crate::query::datalog::types::ValidAt;
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
storage
.transact(
vec![(
e1,
":tag".to_string(),
crate::graph::types::Value::Integer(1),
)],
None,
)
.unwrap();
let facts: Arc<[crate::graph::types::Fact]> =
Arc::from(storage.get_asserted_facts().unwrap().as_slice());
let rules = crate::query::datalog::rules::RuleRegistry::new();
let branch = vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?e".to_string()),
EdnValue::Keyword(":tag".to_string()),
EdnValue::Symbol("?v".to_string()),
))];
let mut initial = std::collections::HashMap::new();
initial.insert("?seed".to_string(), crate::graph::types::Value::Integer(0));
// Line 930: Some(ValidAt::Timestamp(t)) arm
let ts_result = evaluate_branch(
&branch,
vec![initial.clone()],
facts.clone(),
&rules,
None,
Some(ValidAt::Timestamp(crate::graph::types::tx_id_now() as i64)),
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(ts_result.len(), 1, "timestamp valid_at should match");
// Line 931: Some(ValidAt::AnyValidTime) arm
let any_result = evaluate_branch(
&branch,
vec![initial],
facts,
&rules,
None,
Some(ValidAt::AnyValidTime),
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(any_result.len(), 1, "any_valid_time should match");
}
#[test]
fn test_execute_query_with_rules_valid_at_timestamp() {
// Exercises executor.rs lines 341-342 (valid_at_value in execute_query_with_rules
// for Timestamp and AnyValidTime arms) and lines 348-350 (hard-error guard).
use crate::query::datalog::parser::parse_datalog_command;
use crate::query::datalog::types::ValidAt;
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Register a rule so the query routes through execute_query_with_rules
let rule_cmd = parse_datalog_command(r#"(rule [(tagged ?e) [?e :item/tag ?v]])"#)
.expect("rule parse failed");
executor.execute(rule_cmd).expect("rule register failed");
// Transact a fact
executor
.execute(
parse_datalog_command(r#"(transact [[:item1 :item/tag "x"]])"#)
.expect("transact parse failed"),
)
.expect("transact failed");
// Lines 341-342: call execute_query_with_rules directly with Timestamp and AnyValidTime.
// The public execute() routing may bypass it if query_uses_rules returns false;
// calling the private method directly guarantees coverage.
let q_ts = crate::query::datalog::types::DatalogQuery {
find: vec![crate::query::datalog::types::FindSpec::Variable(
"?e".to_string(),
)],
where_clauses: vec![],
as_of: None,
valid_at: Some(ValidAt::Timestamp(946684800000)), // 2000-01-01
with_vars: vec![],
};
let r_ts = executor.execute_query_with_rules(q_ts);
assert!(
r_ts.is_ok(),
"execute_query_with_rules with Timestamp must not error"
);
let q_any = crate::query::datalog::types::DatalogQuery {
find: vec![crate::query::datalog::types::FindSpec::Variable(
"?e".to_string(),
)],
where_clauses: vec![],
as_of: None,
valid_at: Some(ValidAt::AnyValidTime),
with_vars: vec![],
};
let r_any = executor.execute_query_with_rules(q_any);
assert!(
r_any.is_ok(),
"execute_query_with_rules with AnyValidTime must not error"
);
// Lines 348-350: hard-error guard in execute_query_with_rules
// Per-fact pseudo-attr without :any-valid-time in a rules query
let err_cmd = parse_datalog_command(
"(query [:find ?e ?vf :where (tagged ?e) [?e :db/valid-from ?vf]])",
)
.expect("err query parse failed");
let err_result = executor.execute(err_cmd);
assert!(
err_result.is_err(),
"per-fact pseudo-attr without :any-valid-time in rules query must fail"
);
}
#[test]
fn test_evaluate_branch_empty_incoming_returns_empty() {
// evaluate_branch with empty incoming bindings → returns [] immediately (line 842)
let storage = FactStorage::new();
storage
.transact(
vec![(
Uuid::new_v4(),
":a".to_string(),
crate::graph::types::Value::Integer(1),
)],
None,
)
.unwrap();
let facts: Arc<[crate::graph::types::Fact]> =
Arc::from(storage.get_asserted_facts().unwrap().as_slice());
let rules = crate::query::datalog::rules::RuleRegistry::new();
let branch = vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":a".to_string()),
EdnValue::Symbol("?v".to_string()),
))];
let result = evaluate_branch(
&branch,
vec![],
facts,
&rules,
None,
None,
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(result.len(), 0, "empty incoming should return empty");
}
#[test]
fn test_evaluate_branch_no_match_patterns_empty_bindings_returns_empty() {
// evaluate_branch: patterns exist but match nothing → bindings is empty (line 865)
let storage = FactStorage::new();
let facts: Arc<[crate::graph::types::Fact]> =
Arc::from(storage.get_asserted_facts().unwrap().as_slice());
let rules = crate::query::datalog::rules::RuleRegistry::new();
// Branch has a pattern that won't match empty storage
let branch = vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":no-such-attr".to_string()),
EdnValue::Symbol("?v".to_string()),
))];
// Seed with one binding so the branch has something to work with
let mut initial = std::collections::HashMap::new();
initial.insert("?init".to_string(), crate::graph::types::Value::Integer(1));
let result = evaluate_branch(
&branch,
vec![initial],
facts,
&rules,
None,
None,
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(
result.len(),
0,
"no matching facts should return empty bindings"
);
}
#[test]
fn test_evaluate_branch_not_filter_excludes_matching() {
// evaluate_branch with Not clause: entities that match the not body are excluded (line 909)
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":color".to_string(),
crate::graph::types::Value::Keyword(":red".to_string()),
),
(
e2,
":color".to_string(),
crate::graph::types::Value::Keyword(":blue".to_string()),
),
(
e1,
":flagged".to_string(),
crate::graph::types::Value::Boolean(true),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// Query: find entities with :color but not :flagged
// Uses the not_body_matches path in not-post-filter (line 909)
let cmd = parse_datalog_command(
"(query [:find ?e :where [?e :color ?c] (not-join [?e] [?e :flagged ?fv])])",
)
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "only e2 (non-flagged) should match");
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_or_join_deduplication() {
// or-join where both branches bind ?e → duplicate bindings are deduplicated
// (line 991: if !result.contains(&b) { result.push(b); })
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":color".to_string(),
crate::graph::types::Value::Keyword(":red".to_string()),
),
(
e1,
":shape".to_string(),
crate::graph::types::Value::Keyword(":circle".to_string()),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// or-join [?e] with two branches that both match e1 → deduplicated to 1
// ?e must be bound by an earlier clause; use :color as the primary clause
let cmd = parse_datalog_command(
"(query [:find ?e :where [?e :color ?c] (or-join [?e] [?e :color ?c2] [?e :shape ?s])])",
)
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
1,
"e1 should appear once despite two matching branches"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_transact_with_tx_level_valid_time() {
// Exercises the tx_opts = Some(...) path when valid_from/valid_to set at tx level (line 66)
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command(
r#"(transact {:valid-from "2020-01-01T00:00:00Z" :valid-to "2025-01-01T00:00:00Z"} [[:alice :person/name "Alice"]])"#,
)
.expect("parse with tx-level valid-time should succeed");
let result = executor.execute(cmd);
assert!(
result.is_ok(),
"transact with tx-level valid-time should succeed"
);
}
#[test]
fn test_transact_with_per_fact_valid_time() {
// Exercises the per_fact_opts = Some(...) path when valid_from/valid_to set per fact (line 87)
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command(
r#"(transact [[:alice :person/name "Alice" {:valid-from "2020-01-01T00:00:00Z"}]])"#,
)
.expect("parse with per-fact valid-time should succeed");
let result = executor.execute(cmd);
assert!(
result.is_ok(),
"transact with per-fact valid-time should succeed"
);
}
#[test]
fn test_transact_with_valid_to_only_at_tx_level() {
// Exercises the `|| tx.valid_to.is_some()` branch (line 66 col 53)
// when valid_from is None but valid_to is Some
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command(
r#"(transact {:valid-to "2025-01-01T00:00:00Z"} [[:alice :person/name "Alice"]])"#,
)
.expect("parse with tx-level valid-to only should succeed");
let result = executor.execute(cmd);
assert!(
result.is_ok(),
"transact with valid-to only at tx level should succeed"
);
}
#[test]
fn test_transact_with_valid_to_only_per_fact() {
// Exercises the `|| pattern.valid_to.is_some()` branch (line 87 col 68)
// when per-fact valid_from is None but valid_to is Some
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
let cmd = parse_datalog_command(
r#"(transact [[:alice :person/name "Alice" {:valid-to "2025-01-01T00:00:00Z"}]])"#,
)
.expect("parse with per-fact valid-to only should succeed");
let result = executor.execute(cmd);
assert!(
result.is_ok(),
"transact with valid-to only per fact should succeed"
);
}
#[test]
fn test_evaluate_branch_empty_patterns_passes_incoming_through() {
// Line 859: patterns.is_empty() = true → bindings = incoming (pass through)
// Achieved when branch contains only Not/Expr clauses, no Pattern/RuleInvocation
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
storage
.transact(
vec![(
e1,
":a".to_string(),
crate::graph::types::Value::Integer(10),
)],
None,
)
.unwrap();
let facts: Arc<[crate::graph::types::Fact]> =
Arc::from(storage.get_asserted_facts().unwrap().as_slice());
let rules = crate::query::datalog::rules::RuleRegistry::new();
// Branch with only an Expr clause (no patterns) — patterns.is_empty() = true
let branch = vec![WhereClause::Expr {
expr: crate::query::datalog::types::Expr::Lit(crate::graph::types::Value::Boolean(
true,
)),
binding: None,
}];
// Incoming with one binding
let mut initial = std::collections::HashMap::new();
initial.insert("?x".to_string(), crate::graph::types::Value::Integer(42));
let result = evaluate_branch(
&branch,
vec![initial],
facts,
&rules,
None,
None,
&FunctionRegistry::with_builtins(),
)
.unwrap();
// The expr is truthy so the binding passes through
assert_eq!(
result.len(),
1,
"expr-only branch should pass binding through"
);
}
#[test]
fn test_evaluate_branch_or_clause_produces_empty_bindings() {
// Line 879: bindings empty after apply_or_clauses → return Ok([])
// This happens when an Or clause produces no results
let storage = FactStorage::new();
// Empty storage → no facts
let facts: Arc<[crate::graph::types::Fact]> =
Arc::from(storage.get_asserted_facts().unwrap().as_slice());
let rules = crate::query::datalog::rules::RuleRegistry::new();
// Branch with an Or clause that matches nothing
let or_branch = vec![WhereClause::Pattern(Pattern::new(
EdnValue::Symbol("?x".to_string()),
EdnValue::Keyword(":no-attr".to_string()),
EdnValue::Symbol("?v".to_string()),
))];
let branch = vec![WhereClause::Or(vec![or_branch])];
let mut initial = std::collections::HashMap::new();
initial.insert("?seed".to_string(), crate::graph::types::Value::Integer(1));
let result = evaluate_branch(
&branch,
vec![initial],
facts,
&rules,
None,
None,
&FunctionRegistry::with_builtins(),
)
.unwrap();
assert_eq!(
result.len(),
0,
"or clause with no matches should yield empty"
);
}
#[test]
fn test_evaluate_branch_not_join_excludes_matching() {
// Line 914: evaluate_not_join returns true inside evaluate_branch → exclude
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":status".to_string(),
crate::graph::types::Value::Keyword(":active".to_string()),
),
(
e2,
":status".to_string(),
crate::graph::types::Value::Keyword(":inactive".to_string()),
),
(
e2,
":blocked".to_string(),
crate::graph::types::Value::Boolean(true),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// not-join: exclude entities that have :blocked = true
let cmd = parse_datalog_command(
"(query [:find ?e :where [?e :status ?s] (not-join [?e] [?e :blocked ?b])])",
)
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
1,
"only non-blocked entity should be returned"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn test_not_body_expr_only_filters_binding() {
// Exercises not_body_matches with patterns.is_empty() (Expr-only not body) at line 561
let storage = FactStorage::new();
let e1 = Uuid::new_v4();
let e2 = Uuid::new_v4();
storage
.transact(
vec![
(
e1,
":item/price".to_string(),
crate::graph::types::Value::Integer(200),
),
(
e2,
":item/price".to_string(),
crate::graph::types::Value::Integer(50),
),
],
None,
)
.unwrap();
let executor = DatalogExecutor::new(storage);
// not with expr-only body: exclude items where price > 100
let cmd = parse_datalog_command(
"(query [:find ?e :where [?e :item/price ?p] (not [(> ?p 100)])])",
)
.expect("parse failed");
let result = executor.execute(cmd).expect("query failed");
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(
results.len(),
1,
"only the item with price 50 should survive"
);
}
_ => panic!("expected QueryResults"),
}
}
#[test]
fn window_sum_resets_per_partition() {
use super::super::functions::FunctionRegistry;
use super::super::types::{Order, WindowFunc, WindowSpec};
let mut bindings: Vec<std::collections::HashMap<String, Value>> = vec![
[
("dept".into(), Value::String("A".into())),
("salary".into(), Value::Integer(10)),
]
.into_iter()
.collect(),
[
("dept".into(), Value::String("A".into())),
("salary".into(), Value::Integer(20)),
]
.into_iter()
.collect(),
[
("dept".into(), Value::String("B".into())),
("salary".into(), Value::Integer(100)),
]
.into_iter()
.collect(),
];
let find_specs = vec![
FindSpec::Variable("dept".into()),
FindSpec::Variable("salary".into()),
FindSpec::Window(WindowSpec {
func: WindowFunc::Sum,
var: Some("salary".into()),
partition_by: Some("dept".into()),
order_by: "salary".into(),
order: Order::Asc,
}),
];
let registry = FunctionRegistry::with_builtins();
apply_window_functions(&mut bindings, &find_specs, ®istry).expect("window");
// Partition A: 10 → sum=10, 20 → sum=30
let row_a10 = bindings
.iter()
.find(|b| b.get("salary") == Some(&Value::Integer(10)))
.unwrap();
assert_eq!(row_a10.get("__win_2"), Some(&Value::Integer(10)));
let row_a20 = bindings
.iter()
.find(|b| b.get("salary") == Some(&Value::Integer(20)))
.unwrap();
assert_eq!(row_a20.get("__win_2"), Some(&Value::Integer(30)));
// Partition B: 100 → sum=100 (accumulator reset, NOT 130)
let row_b100 = bindings
.iter()
.find(|b| b.get("salary") == Some(&Value::Integer(100)))
.unwrap();
assert_eq!(row_b100.get("__win_2"), Some(&Value::Integer(100)));
}
}
#[cfg(test)]
mod selective_lookup_tests {
use crate::graph::FactStorage;
use crate::query::datalog::executor::DatalogExecutor;
fn make_db_with_entities(n: usize) -> DatalogExecutor {
let storage = FactStorage::new();
let exec = DatalogExecutor::new(storage);
for batch_start in (0..n).step_by(50) {
let batch_end = (batch_start + 50).min(n);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!(r#"[:e{i} :name "entity{i}"]"#, i = i));
cmd.push_str(&format!("[:e{i} :val {i}]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
exec
}
#[test]
fn entity_bound_query_returns_correct_results() {
let exec = make_db_with_entities(100);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
r#"(query [:find ?n :where [:e5 :name ?n]])"#,
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), 1, "expected exactly 1 result for entity :e5");
assert_eq!(
results[0][0],
crate::graph::types::Value::String("entity5".to_string())
);
} else {
panic!("expected QueryResults");
}
}
#[test]
fn attribute_bound_query_returns_correct_results() {
let exec = make_db_with_entities(100);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e ?v :where [?e :val ?v]])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(
results.len(),
100,
"expected 100 results for :val attribute scan"
);
} else {
panic!("expected QueryResults");
}
}
#[test]
fn as_of_query_still_works_after_change() {
let exec = make_db_with_entities(10);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?n :where [?e :name ?n] :as-of 1])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert!(!results.is_empty(), "expected results from as-of 1 query");
} else {
panic!("expected QueryResults");
}
}
}
#[cfg(test)]
mod not_hash_join_tests {
use crate::graph::FactStorage;
use crate::query::datalog::executor::DatalogExecutor;
fn make_not_db(n: usize, excluded: usize) -> DatalogExecutor {
let storage = FactStorage::new();
let exec = DatalogExecutor::new(storage);
for batch_start in (0..n).step_by(100) {
let batch_end = (batch_start + 100).min(n);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :val {i}]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
for batch_start in (0..excluded).step_by(100) {
let batch_end = (batch_start + 100).min(excluded);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :banned true]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
exec
}
#[test]
fn not_filter_returns_correct_count() {
let n = 1_000;
let excluded = n / 10; // 100 banned
let exec = make_not_db(n, excluded);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :val ?v] (not [?e :banned true])])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(
results.len(),
n - excluded,
"expected {} results after not-filter",
n - excluded
);
} else {
panic!("expected QueryResults");
}
}
#[test]
fn not_join_filter_returns_correct_count() {
let n = 1_000;
let excluded = n / 10;
let storage = FactStorage::new();
let exec = DatalogExecutor::new(storage);
for batch_start in (0..n).step_by(100) {
let batch_end = (batch_start + 100).min(n);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :val {i}]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
exec.execute(
crate::query::datalog::parser::parse_datalog_command(
"(transact [[:d-bad :status :bad]])",
)
.unwrap(),
)
.unwrap();
for batch_start in (0..excluded).step_by(100) {
let batch_end = (batch_start + 100).min(excluded);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :dep :d-bad]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :val ?v] \
(not-join [?e] [?e :dep ?d] [?d :status :bad])])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(
results.len(),
n - excluded,
"expected {} results after not-join-filter",
n - excluded
);
} else {
panic!("expected QueryResults");
}
}
}
#[cfg(test)]
mod or_hash_join_tests {
use crate::graph::FactStorage;
use crate::query::datalog::executor::DatalogExecutor;
fn make_or_db(n: usize, a_count: usize, b_count: usize) -> DatalogExecutor {
let storage = FactStorage::new();
let exec = DatalogExecutor::new(storage);
for batch_start in (0..n).step_by(100) {
let batch_end = (batch_start + 100).min(n);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :val {i}]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
for batch_start in (0..a_count).step_by(100) {
let batch_end = (batch_start + 100).min(a_count);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :tag-a true]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
let b_start = n.saturating_sub(b_count);
for batch_start in (b_start..n).step_by(100) {
let batch_end = (batch_start + 100).min(n);
let mut cmd = String::from("(transact [");
for i in batch_start..batch_end {
cmd.push_str(&format!("[:e{i} :tag-b true]", i = i));
}
cmd.push_str("])");
exec.execute(crate::query::datalog::parser::parse_datalog_command(&cmd).unwrap())
.unwrap();
}
exec
}
#[test]
fn or_clause_returns_correct_count() {
// 1000 entities, first 250 have :tag-a, last 250 have :tag-b, no overlap
let n = 1_000;
let a = n / 4;
let b = n / 4;
let exec = make_or_db(n, a, b);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :val ?v] \
(or [?e :tag-a true] [?e :tag-b true])])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(
results.len(),
a + b,
"expected {} results from or (a={} b={} no overlap)",
a + b,
a,
b
);
} else {
panic!("expected QueryResults");
}
}
#[test]
fn or_join_clause_returns_correct_count() {
let n = 1_000;
let a = n / 4;
let b = n / 4;
let exec = make_or_db(n, a, b);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :val ?v] \
(or-join [?e] [?e :tag-a true] [?e :tag-b true])])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(
results.len(),
a + b,
"expected {} results from or-join",
a + b
);
} else {
panic!("expected QueryResults");
}
}
#[test]
fn or_clause_with_overlap_deduplicates() {
// 100 entities, all have both :tag-a and :tag-b → result should be 100, not 200
let n = 100;
let exec = make_or_db(n, n, n);
let result = exec
.execute(
crate::query::datalog::parser::parse_datalog_command(
"(query [:find ?e :where [?e :val ?v] \
(or [?e :tag-a true] [?e :tag-b true])])",
)
.unwrap(),
)
.unwrap();
if let crate::query::datalog::executor::QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), n, "expected {} deduplicated results", n);
} else {
panic!("expected QueryResults");
}
}
}
#[cfg(test)]
mod pushdown_tests {
use crate::graph::FactStorage;
use crate::graph::types::Value;
use crate::query::datalog::executor::{DatalogExecutor, QueryResult};
use crate::query::datalog::parser::parse_datalog_command;
#[test]
fn test_expr_pushdown_preserves_query_results() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
executor
.execute(
parse_datalog_command("(transact [[:e1 :val 10] [:e2 :val 20] [:e3 :val 30]])")
.unwrap(),
)
.unwrap();
let result = executor
.execute(
parse_datalog_command("(query [:find ?e ?v :where [?e :val ?v] [(> ?v 15)]])")
.unwrap(),
)
.unwrap();
if let QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), 2, "only :e2 and :e3 have :val > 15");
} else {
panic!("expected QueryResults");
}
}
#[test]
fn test_expr_pushdown_multi_pattern_preserves_results() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
executor
.execute(
parse_datalog_command(
r#"(transact [[:e1 :val 5] [:e1 :name "a"] [:e2 :val 20] [:e2 :name "b"]])"#,
)
.unwrap(),
)
.unwrap();
let result = executor
.execute(
parse_datalog_command(
r#"(query [:find ?e ?n :where [?e :val ?v] [?e :name ?n] [(> ?v 10)]])"#,
)
.unwrap(),
)
.unwrap();
if let QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), 1, "only :e2 passes the predicate");
} else {
panic!("expected QueryResults");
}
}
#[test]
fn test_expr_binding_form_preserves_results() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
executor
.execute(parse_datalog_command("(transact [[:e1 :val 5] [:e2 :val 10]])").unwrap())
.unwrap();
let result = executor
.execute(
parse_datalog_command(
"(query [:find ?e ?doubled :where [?e :val ?v] [(* ?v 2) ?doubled]])",
)
.unwrap(),
)
.unwrap();
if let QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), 2, "both entities must appear");
} else {
panic!("expected QueryResults");
}
}
#[test]
fn test_expr_pushdown_with_rules_preserves_results() {
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage.clone());
executor
.execute(
parse_datalog_command("(transact [[:e1 :val 5] [:e2 :val 20] [:e3 :val 30]])")
.unwrap(),
)
.unwrap();
executor
.execute(parse_datalog_command("(rule [(high ?e) [?e :val ?v] [(> ?v 15)]])").unwrap())
.unwrap();
let result = executor
.execute(parse_datalog_command("(query [:find ?e :where (high ?e)])").unwrap())
.unwrap();
if let QueryResult::QueryResults { results, .. } = result {
assert_eq!(results.len(), 2, "only :e2 and :e3 qualify");
} else {
panic!("expected QueryResults");
}
}
#[test]
fn test_not_clause_ordering_correctness() {
// Two `not` clauses given in expensive-first source order; results must be
// identical regardless of which order the optimizer chooses to evaluate them.
// This is a correctness regression guard — semantics must not change.
let storage = FactStorage::new();
let executor = DatalogExecutor::new(storage);
// Transact 3 items: widget, gadget, doohickey
executor
.execute(
parse_datalog_command(
r#"(transact [[:item1 :item/name "widget"]
[:item2 :item/name "gadget"]
[:item3 :item/name "doohickey"]])"#,
)
.unwrap(),
)
.unwrap();
// Query: find items that are NOT "widget" AND NOT "gadget"
// Clauses are given in expensive-first order to exercise the cost-based sort.
let result = executor
.execute(
parse_datalog_command(
r#"(query [:find ?name
:where [?e :item/name ?name]
(not [?e :item/name "gadget"])
(not [?e :item/name "widget"])])"#,
)
.unwrap(),
)
.unwrap();
match result {
QueryResult::QueryResults { results, .. } => {
assert_eq!(results.len(), 1, "only doohickey should pass");
if let Value::String(ref s) = results[0][0] {
assert_eq!(s.as_str(), "doohickey", "result should be doohickey");
} else {
panic!("expected a String value for the result");
}
}
_ => panic!("expected QueryResults"),
}
}
}