icydb-core 0.144.13

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
use super::*;
use crate::db::{
    executor::EntityAuthority,
    schema::commit_schema_fingerprint_for_entity,
    session::{query::QueryPlanVisibility, sql::SqlCompiledCommandCacheKey},
    sql::lowering::{SqlCommand, compile_sql_command},
};
use std::collections::HashSet;

// Assert that one representative SQL surface stays fail-closed for a matrix of
// statement lanes that belong to some other surface.
fn assert_sql_surface_rejects_statement_lanes<T, F>(cases: &[(&str, &str)], mut execute: F)
where
    F: FnMut(&str) -> Result<T, QueryError>,
{
    for (sql, context) in cases {
        assert_unsupported_sql_surface_result(execute(sql), context);
    }
}

// Assert that one representative SQL surface keeps its own user-facing lane
// rejection message for each disallowed statement family.
fn assert_sql_surface_rejects_statement_lanes_with_message<T, F>(
    cases: &[(&str, &str)],
    mut execute: F,
    surface: &str,
) where
    F: FnMut(&str) -> Result<T, QueryError>,
{
    for (sql, expected) in cases {
        let Err(err) = execute(sql) else {
            panic!("{surface} should reject the non-owned lane: {sql}");
        };
        assert!(
            err.to_string().contains(expected),
            "{surface} should preserve a surface-local lane boundary message: {sql}",
        );
    }
}

// Assert that one unsupported SQL feature is surfaced with the same parser
// detail label through the selected SQL surface.
fn assert_sql_surface_preserves_unsupported_feature_detail<T, F>(
    cases: &[(&str, &'static str)],
    mut execute: F,
) where
    F: FnMut(&str) -> Result<T, QueryError>,
{
    for (sql, feature) in cases {
        let Err(err) = execute(sql) else {
            panic!("unsupported SQL feature should fail through the SQL surface: {sql}");
        };
        assert_sql_unsupported_feature_detail(err, feature);
    }
}

// Require one session-compiled SELECT artifact to preserve the same canonical
// structural and logical identity as the directly lowered internal query.
fn assert_compiled_select_query_matches_lowered_identity_for_entity<E>(
    compiled: &crate::db::session::sql::CompiledSqlCommand,
    sql: &str,
    context: &str,
) where
    E: PersistedRow<Canister = SessionSqlCanister> + EntityValue,
{
    let lowered = compile_sql_command::<E>(sql, MissingRowPolicy::Ignore)
        .unwrap_or_else(|err| panic!("{context} should lower into one canonical query: {err:?}"));
    let SqlCommand::Query(lowered_query) = lowered else {
        panic!("{context} should lower to one query command");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select { query, .. } = compiled else {
        panic!("{context} should compile into one SELECT artifact");
    };

    assert_eq!(
        query.structural_cache_key(),
        lowered_query.structural().structural_cache_key(),
        "{context} must canonicalize onto the same structural query cache key before cache insertion",
    );
    assert_eq!(
        query
            .build_plan()
            .expect("compiled session query plan should build")
            .fingerprint(),
        lowered_query
            .plan()
            .expect("canonical lowered query plan should build")
            .into_inner()
            .fingerprint(),
        "{context} must preserve the same canonical logical plan identity as the lowered internal form",
    );
}

fn assert_compiled_select_query_matches_lowered_identity(
    compiled: &crate::db::session::sql::CompiledSqlCommand,
    sql: &str,
    context: &str,
) {
    assert_compiled_select_query_matches_lowered_identity_for_entity::<SessionSqlEntity>(
        compiled, sql, context,
    );
}

// Require two distinct SQL SELECT artifacts to preserve distinct canonical
// structural identity once lowered onto the shared query surface.
fn assert_compiled_select_queries_remain_distinct_for_entity(
    left: &crate::db::session::sql::CompiledSqlCommand,
    right: &crate::db::session::sql::CompiledSqlCommand,
    context: &str,
) {
    let crate::db::session::sql::CompiledSqlCommand::Select { query: left, .. } = left else {
        panic!("{context} left SQL should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select { query: right, .. } = right else {
        panic!("{context} right SQL should compile into one SELECT artifact");
    };

    assert_ne!(
        left.structural_cache_key(),
        right.structural_cache_key(),
        "{context} must not collapse onto the same structural query cache key",
    );
}

fn assert_distinct_compiled_selects_execute_through_shared_query_plan_for_entity<E>(
    session: &DbSession<SessionSqlCanister>,
    left: &crate::db::session::sql::CompiledSqlCommand,
    right: &crate::db::session::sql::CompiledSqlCommand,
) where
    E: PersistedRow<Canister = SessionSqlCanister> + EntityValue,
{
    let _ = session
        .execute_compiled_sql::<E>(left)
        .expect("executing the left compiled SELECT should succeed through the shared lower cache");

    let _ = session.execute_compiled_sql::<E>(right).expect(
        "executing the right compiled SELECT should succeed through the shared lower cache",
    );
}

// This query-surface matrix keeps every non-query statement rejection on one
// outward contract table so the boundary stays easy to audit.
#[expect(
    clippy::too_many_lines,
    reason = "query-surface rejection matrix is intentionally tabular"
)]
#[test]
fn sql_query_surfaces_reject_non_query_statement_lanes_matrix() {
    reset_session_sql_store();
    let session = sql_session();

    // Phase 1: keep the lowered query entrypoint fail-closed for every
    // non-query statement family.
    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "EXPLAIN SELECT * FROM SessionSqlEntity",
                "SQL query lowering must reject EXPLAIN statements",
            ),
            (
                "DESCRIBE SessionSqlEntity",
                "SQL query lowering must reject DESCRIBE statements",
            ),
            (
                "SHOW INDEXES SessionSqlEntity",
                "SQL query lowering must reject SHOW INDEXES statements",
            ),
            (
                "SHOW COLUMNS SessionSqlEntity",
                "SQL query lowering must reject SHOW COLUMNS statements",
            ),
            (
                "SHOW ENTITIES",
                "SQL query lowering must reject SHOW ENTITIES statements",
            ),
            (
                "INSERT INTO SessionSqlEntity (id, name, age) VALUES (1, 'Ada', 21)",
                "SQL query lowering must reject INSERT statements",
            ),
            (
                "INSERT INTO SessionSqlEntity (name, age) SELECT name, age FROM SessionSqlEntity ORDER BY id ASC LIMIT 1",
                "SQL query lowering must reject INSERT statements",
            ),
            (
                "UPDATE SessionSqlEntity SET age = 22 WHERE id = 1",
                "SQL query lowering must reject UPDATE statements",
            ),
        ],
        |sql| lower_select_query_for_tests::<SessionSqlEntity>(&session, sql),
    );

    // Phase 2: require both executable query entrypoints to preserve their
    // own surface-local lane boundary messages for the same non-query SQL.
    let message_cases = [
        (
            "EXPLAIN SELECT * FROM SessionSqlEntity",
            "scalar SELECT helper rejects EXPLAIN",
        ),
        (
            "DESCRIBE SessionSqlEntity",
            "scalar SELECT helper rejects DESCRIBE",
        ),
        (
            "SHOW INDEXES SessionSqlEntity",
            "scalar SELECT helper rejects SHOW INDEXES",
        ),
        (
            "SHOW COLUMNS SessionSqlEntity",
            "scalar SELECT helper rejects SHOW COLUMNS",
        ),
        (
            "SHOW ENTITIES",
            "scalar SELECT helper rejects SHOW ENTITIES",
        ),
        (
            "INSERT INTO SessionSqlEntity (id, name, age) VALUES (1, 'Ada', 21)",
            "scalar SELECT helper rejects INSERT",
        ),
        (
            "INSERT INTO SessionSqlEntity (name, age) SELECT name, age FROM SessionSqlEntity ORDER BY id ASC LIMIT 1",
            "scalar SELECT helper rejects INSERT",
        ),
        (
            "UPDATE SessionSqlEntity SET age = 22 WHERE id = 1",
            "scalar SELECT helper rejects UPDATE",
        ),
    ];
    assert_sql_surface_rejects_statement_lanes_with_message(
        &message_cases,
        |sql| execute_scalar_select_for_tests::<SessionSqlEntity>(&session, sql),
        "scalar SELECT helper",
    );

    let grouped_cases = [
        (
            "EXPLAIN SELECT * FROM SessionSqlEntity",
            "grouped SELECT helper rejects EXPLAIN",
        ),
        (
            "DESCRIBE SessionSqlEntity",
            "grouped SELECT helper rejects DESCRIBE",
        ),
        (
            "SHOW INDEXES SessionSqlEntity",
            "grouped SELECT helper rejects SHOW INDEXES",
        ),
        (
            "SHOW COLUMNS SessionSqlEntity",
            "grouped SELECT helper rejects SHOW COLUMNS",
        ),
        (
            "SHOW ENTITIES",
            "grouped SELECT helper rejects SHOW ENTITIES",
        ),
        (
            "INSERT INTO SessionSqlEntity (id, name, age) VALUES (1, 'Ada', 21)",
            "grouped SELECT helper rejects INSERT",
        ),
        (
            "INSERT INTO SessionSqlEntity (name, age) SELECT name, age FROM SessionSqlEntity ORDER BY id ASC LIMIT 1",
            "grouped SELECT helper rejects INSERT",
        ),
        (
            "UPDATE SessionSqlEntity SET age = 22 WHERE id = 1",
            "grouped SELECT helper rejects UPDATE",
        ),
    ];

    assert_sql_surface_rejects_statement_lanes_with_message(
        &grouped_cases,
        |sql| execute_grouped_select_for_tests::<SessionSqlEntity>(&session, sql, None),
        "grouped SELECT helper",
    );
}

#[test]
fn sql_query_lowering_projection_matrix_normalizes_to_scalar_fields() {
    reset_session_sql_store();
    let session = sql_session();

    for (sql, expected_field_names, context) in [
        (
            "SELECT name, age FROM SessionSqlEntity",
            vec!["name".to_string(), "age".to_string()],
            "field-list SQL projection",
        ),
        (
            "SELECT alias.name \
             FROM SessionSqlEntity alias \
             WHERE alias.age >= 21 \
             ORDER BY alias.age DESC LIMIT 1",
            vec!["name".to_string()],
            "single-table alias SQL projection",
        ),
    ] {
        let query = lower_select_query_for_tests::<SessionSqlEntity>(&session, sql)
            .unwrap_or_else(|err| panic!("{context} should lower: {err}"));
        let projection = query
            .plan()
            .unwrap_or_else(|err| panic!("{context} plan should build: {err}"))
            .projection_spec();
        let field_names = projection
            .fields()
            .map(|field| match field {
                ProjectionField::Scalar {
                    expr: Expr::Field(field),
                    alias: None,
                } => field.as_str().to_string(),
                other @ ProjectionField::Scalar { .. } => {
                    panic!("{context} should lower to canonical field exprs: {other:?}")
                }
            })
            .collect::<Vec<_>>();

        assert_eq!(
            field_names, expected_field_names,
            "{context} should normalize to scalar field selection",
        );
    }
}

#[test]
fn sql_surface_text_specific_computed_projection_rejection_matrix_preserves_lane_messages() {
    reset_session_sql_store();
    let session = sql_session();

    let query_err = lower_select_query_for_tests::<SessionSqlEntity>(&session, "SELECT TRIM(name) FROM SessionSqlEntity")
        .expect_err(
            "SQL query lowering should stay on the structural lowered-query lane and reject text-specific computed projection forms",
        );
    assert!(
        query_err
            .to_string()
            .contains("SQL query lowering does not accept text-specific computed projection"),
        "SQL query lowering should reject text-specific computed projection with an actionable boundary message",
    );

    let execute_err = execute_scalar_select_for_tests::<SessionSqlEntity>(
        &session,
        "SELECT TRIM(name) FROM SessionSqlEntity",
    )
    .expect_err(
        "scalar SELECT helper should keep text-specific computed projection on the statement-owned lane",
    );
    assert!(
        execute_err
            .to_string()
            .contains("scalar SELECT helper rejects text-specific computed projection"),
        "scalar SELECT helper should reject text-specific computed projection with an actionable boundary message",
    );
}

#[test]
fn execute_sql_rejects_quoted_identifiers_in_reduced_parser() {
    reset_session_sql_store();
    let session = sql_session();

    let err = execute_scalar_select_for_tests::<SessionSqlEntity>(
        &session,
        "SELECT \"name\" FROM SessionSqlEntity",
    )
    .expect_err("quoted identifiers should be rejected by reduced SQL parser");

    assert!(
        matches!(
            err,
            QueryError::Execute(crate::db::query::intent::QueryExecutionError::Unsupported(
                _
            ))
        ),
        "quoted identifiers should fail closed through unsupported SQL boundary",
    );
}

#[test]
fn sql_metadata_surfaces_match_typed_payloads() {
    reset_session_sql_store();
    let session = sql_session();

    let describe_from_sql =
        statement_describe_sql::<SessionSqlEntity>(&session, "DESCRIBE SessionSqlEntity")
            .expect("describe_sql should succeed");
    let show_indexes_from_sql =
        statement_show_indexes_sql::<SessionSqlEntity>(&session, "SHOW INDEXES SessionSqlEntity")
            .expect("show_indexes_sql should succeed");
    let show_columns_from_sql =
        statement_show_columns_sql::<SessionSqlEntity>(&session, "SHOW COLUMNS SessionSqlEntity")
            .expect("show_columns_sql should succeed");
    let show_entities_from_sql = statement_show_entities_sql(&session, "SHOW ENTITIES")
        .expect("show_entities_sql should succeed");
    let show_tables_from_sql = statement_show_entities_sql(&session, "SHOW TABLES")
        .expect("show tables alias should succeed");

    assert_eq!(
        describe_from_sql,
        session.describe_entity::<SessionSqlEntity>(),
        "describe_sql should project through canonical describe_entity payload",
    );
    assert_eq!(
        show_indexes_from_sql,
        session.show_indexes::<SessionSqlEntity>(),
        "show_indexes_sql should project through canonical show_indexes payload",
    );
    assert_eq!(
        show_columns_from_sql,
        session.show_columns::<SessionSqlEntity>(),
        "show_columns_sql should project through canonical show_columns payload",
    );
    assert_eq!(
        show_entities_from_sql,
        session.show_entities(),
        "show_entities_sql should project through canonical show_entities payload",
    );
    assert_eq!(
        session.show_tables(),
        session.show_entities(),
        "typed show_tables helper should stay a direct alias of show_entities",
    );
    assert_eq!(
        show_tables_from_sql,
        session.show_entities(),
        "SHOW TABLES should stay a direct alias of SHOW ENTITIES",
    );
}

// This metadata/explain matrix keeps every non-owned statement rejection on
// one outward surface contract instead of splitting the statement families.
#[expect(
    clippy::too_many_lines,
    reason = "metadata and explain rejection matrix is intentionally tabular"
)]
#[test]
fn sql_metadata_and_explain_surfaces_reject_non_owned_statement_lanes_matrix() {
    reset_session_sql_store();
    let session = sql_session();

    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "SELECT * FROM SessionSqlEntity",
                "describe_sql should reject SELECT statements",
            ),
            (
                "EXPLAIN SELECT * FROM SessionSqlEntity",
                "describe_sql should reject EXPLAIN statements",
            ),
            (
                "SHOW INDEXES SessionSqlEntity",
                "describe_sql should reject SHOW INDEXES statements",
            ),
            (
                "SHOW COLUMNS SessionSqlEntity",
                "describe_sql should reject SHOW COLUMNS statements",
            ),
            (
                "SHOW ENTITIES",
                "describe_sql should reject SHOW ENTITIES statements",
            ),
        ],
        |sql| statement_describe_sql::<SessionSqlEntity>(&session, sql),
    );
    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "SELECT * FROM SessionSqlEntity",
                "show_indexes_sql should reject SELECT statements",
            ),
            (
                "EXPLAIN SELECT * FROM SessionSqlEntity",
                "show_indexes_sql should reject EXPLAIN statements",
            ),
            (
                "DESCRIBE SessionSqlEntity",
                "show_indexes_sql should reject DESCRIBE statements",
            ),
            (
                "SHOW COLUMNS SessionSqlEntity",
                "show_indexes_sql should reject SHOW COLUMNS statements",
            ),
            (
                "SHOW ENTITIES",
                "show_indexes_sql should reject SHOW ENTITIES statements",
            ),
        ],
        |sql| statement_show_indexes_sql::<SessionSqlEntity>(&session, sql),
    );
    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "SELECT * FROM SessionSqlEntity",
                "show_columns_sql should reject SELECT statements",
            ),
            (
                "EXPLAIN SELECT * FROM SessionSqlEntity",
                "show_columns_sql should reject EXPLAIN statements",
            ),
            (
                "DESCRIBE SessionSqlEntity",
                "show_columns_sql should reject DESCRIBE statements",
            ),
            (
                "SHOW INDEXES SessionSqlEntity",
                "show_columns_sql should reject SHOW INDEXES statements",
            ),
            (
                "SHOW ENTITIES",
                "show_columns_sql should reject SHOW ENTITIES statements",
            ),
        ],
        |sql| statement_show_columns_sql::<SessionSqlEntity>(&session, sql),
    );
    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "SELECT * FROM SessionSqlEntity",
                "show_entities_sql should reject SELECT statements",
            ),
            (
                "EXPLAIN SELECT * FROM SessionSqlEntity",
                "show_entities_sql should reject EXPLAIN statements",
            ),
            (
                "DESCRIBE SessionSqlEntity",
                "show_entities_sql should reject DESCRIBE statements",
            ),
            (
                "SHOW INDEXES SessionSqlEntity",
                "show_entities_sql should reject SHOW INDEXES statements",
            ),
            (
                "SHOW COLUMNS SessionSqlEntity",
                "show_entities_sql should reject SHOW COLUMNS statements",
            ),
        ],
        |sql| statement_show_entities_sql(&session, sql),
    );
    assert_sql_surface_rejects_statement_lanes(
        &[
            (
                "DESCRIBE SessionSqlEntity",
                "explain_sql should reject DESCRIBE statements",
            ),
            (
                "SHOW INDEXES SessionSqlEntity",
                "explain_sql should reject SHOW INDEXES statements",
            ),
            (
                "SHOW COLUMNS SessionSqlEntity",
                "explain_sql should reject SHOW COLUMNS statements",
            ),
            (
                "SHOW ENTITIES",
                "explain_sql should reject SHOW ENTITIES statements",
            ),
        ],
        |sql| statement_explain_sql::<SessionSqlEntity>(&session, sql),
    );
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "this matrix test intentionally proves one shared unsupported-feature contract across several SQL surfaces"
)]
fn sql_surfaces_preserve_unsupported_feature_detail_labels() {
    reset_session_sql_store();
    let session = sql_session();
    let parser_owned_cases = unsupported_sql_parser_feature_cases();
    let lowering_owned_cases = unsupported_sql_feature_cases();

    assert_sql_surface_preserves_unsupported_feature_detail(&parser_owned_cases, |sql| {
        parse_sql_statement_for_tests(&session, sql).map(|_| ())
    });
    assert_sql_surface_preserves_unsupported_feature_detail(&lowering_owned_cases, |sql| {
        lower_select_query_for_tests::<SessionSqlEntity>(&session, sql)
    });
    assert_sql_surface_preserves_unsupported_feature_detail(&lowering_owned_cases, |sql| {
        execute_scalar_select_for_tests::<SessionSqlEntity>(&session, sql)
    });
    assert_sql_surface_preserves_unsupported_feature_detail(&lowering_owned_cases, |sql| {
        statement_projection_rows::<SessionSqlEntity>(&session, sql)
    });
    assert_sql_surface_preserves_unsupported_feature_detail(&lowering_owned_cases, |sql| {
        execute_grouped_select_for_tests::<SessionSqlEntity>(&session, sql, None)
    });
    assert_sql_surface_preserves_unsupported_feature_detail(&lowering_owned_cases, |sql| {
        let explain_sql = format!("EXPLAIN {sql}");
        statement_explain_sql::<SessionSqlEntity>(&session, explain_sql.as_str())
    });
    let sql = "INSERT INTO SessionSqlEntity (name, age) VALUES ('Ada', 21) RETURNING id";

    assert_unsupported_sql_surface_result(
        lower_select_query_for_tests::<SessionSqlEntity>(&session, sql),
        "SQL query lowering should reject INSERT lane even when RETURNING is present",
    );
    assert_unsupported_sql_surface_result(
        execute_scalar_select_for_tests::<SessionSqlEntity>(&session, sql),
        "scalar SELECT helper should reject INSERT lane even when RETURNING is present",
    );
    let returning_rows = statement_projection_rows::<SessionSqlEntity>(&session, sql)
        .expect("statement execution should admit INSERT RETURNING");
    assert_eq!(returning_rows.len(), 1);
    assert_eq!(returning_rows[0].len(), 1);
    assert!(
        matches!(returning_rows[0][0], Value::Ulid(_)),
        "statement INSERT RETURNING should project the requested generated id",
    );
    assert_unsupported_sql_surface_result(
        execute_grouped_select_for_tests::<SessionSqlEntity>(&session, sql, None),
        "grouped SELECT helper should reject INSERT lane even when RETURNING is present",
    );

    let update_returning_sql =
        "UPDATE SessionSqlEntity SET age = 22 WHERE name = 'Ada' RETURNING id, age";

    assert_unsupported_sql_surface_result(
        lower_select_query_for_tests::<SessionSqlEntity>(&session, update_returning_sql),
        "SQL query lowering should reject UPDATE lane even when RETURNING is present",
    );
    assert_unsupported_sql_surface_result(
        execute_scalar_select_for_tests::<SessionSqlEntity>(&session, update_returning_sql),
        "scalar SELECT helper should reject UPDATE lane even when RETURNING is present",
    );
    let updated_rows =
        statement_projection_rows::<SessionSqlEntity>(&session, update_returning_sql)
            .expect("statement execution should admit UPDATE RETURNING");
    assert_eq!(updated_rows.len(), 1);
    assert_eq!(updated_rows[0].len(), 2);
    assert!(
        matches!(updated_rows[0][0], Value::Ulid(_)),
        "statement UPDATE RETURNING should project the requested generated id",
    );
    assert_eq!(
        updated_rows[0][1],
        Value::Uint(22),
        "statement UPDATE RETURNING should project the updated scalar field",
    );
    assert_unsupported_sql_surface_result(
        execute_grouped_select_for_tests::<SessionSqlEntity>(&session, update_returning_sql, None),
        "grouped SELECT helper should reject UPDATE lane even when RETURNING is present",
    );

    let delete_returning_sql =
        "DELETE FROM SessionSqlEntity WHERE age > 20 ORDER BY age ASC LIMIT 1 RETURNING id";

    let query_from_err =
        lower_select_query_for_tests::<SessionSqlEntity>(&session, delete_returning_sql)
            .map(|_| ())
            .expect_err("SQL query lowering should reject DELETE RETURNING");
    assert!(
        query_from_err
            .to_string()
            .contains("DELETE RETURNING; use execute_sql_update::<E>()"),
        "SQL query lowering should preserve explicit DELETE RETURNING guidance",
    );

    let execute_sql_err =
        execute_scalar_select_for_tests::<SessionSqlEntity>(&session, delete_returning_sql)
            .map(|_| ())
            .expect_err("scalar SELECT helper should reject DELETE entirely");
    assert!(
        execute_sql_err
            .to_string()
            .contains("scalar SELECT helper rejects DELETE; use execute_sql_update::<E>()"),
        "scalar SELECT helper should preserve explicit fluent delete guidance",
    );

    let grouped_err =
        execute_grouped_select_for_tests::<SessionSqlEntity>(&session, delete_returning_sql, None)
            .map(|_| ())
            .expect_err("grouped SELECT helper should still reject DELETE at the grouped surface");
    assert!(
        grouped_err
            .to_string()
            .contains("grouped SELECT helper rejects DELETE"),
        "grouped SQL surface should preserve its own lane boundary before RETURNING guidance",
    );
}

#[test]
fn execute_sql_statement_admits_supported_single_entity_read_shapes() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("ada", 21), ("bob", 21), ("carol", 32)]);

    let scalar = execute_sql_statement_for_tests::<SessionSqlEntity>(
        &session,
        "SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
    )
    .expect("execute_sql_statement should admit scalar SELECT");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = scalar
    else {
        panic!("execute_sql_statement scalar SELECT should emit projection rows");
    };
    assert_eq!(columns, vec!["name".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Text("ada".to_string()))]]);
    assert_eq!(row_count, 1);

    let grouped = execute_sql_statement_for_tests::<SessionSqlEntity>(
        &session,
        "SELECT age, COUNT(*) FROM SessionSqlEntity GROUP BY age",
    )
    .expect("execute_sql_statement should admit grouped SELECT");
    let SqlStatementResult::Grouped {
        columns, row_count, ..
    } = grouped
    else {
        panic!("execute_sql_statement grouped SELECT should emit grouped rows");
    };
    assert_eq!(columns, vec!["age".to_string(), "COUNT(*)".to_string()]);
    assert_eq!(row_count, 2);

    let aggregate = execute_sql_statement_for_tests::<SessionSqlEntity>(
        &session,
        "SELECT COUNT(*) FROM SessionSqlEntity",
    )
    .expect("execute_sql_statement should admit global aggregate SELECT");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = aggregate
    else {
        panic!("execute_sql_statement aggregate SELECT should emit projection rows");
    };
    assert_eq!(columns, vec!["COUNT(*)".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Uint(3))]]);
    assert_eq!(row_count, 1);
}

#[test]
fn execute_sql_statement_admits_supported_single_entity_mutation_shapes() {
    reset_session_sql_store();
    let session = sql_session();

    let insert = execute_sql_statement_for_tests::<SessionSqlWriteEntity>(
        &session,
        "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
    )
    .expect("execute_sql_statement should admit INSERT");
    let SqlStatementResult::Count { row_count } = insert else {
        panic!("execute_sql_statement INSERT should emit count payload");
    };
    assert_eq!(row_count, 1);

    let update = execute_sql_statement_for_tests::<SessionSqlWriteEntity>(
        &session,
        "UPDATE SessionSqlWriteEntity SET age = 22 WHERE id = 1",
    )
    .expect("execute_sql_statement should admit UPDATE");
    let SqlStatementResult::Count { row_count } = update else {
        panic!("execute_sql_statement UPDATE should emit count payload");
    };
    assert_eq!(row_count, 1);

    let delete = execute_sql_statement_for_tests::<SessionSqlWriteEntity>(
        &session,
        "DELETE FROM SessionSqlWriteEntity WHERE name = 'Ada' RETURNING name",
    )
    .expect("execute_sql_statement should admit DELETE RETURNING");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = delete
    else {
        panic!("execute_sql_statement DELETE RETURNING should emit projection rows");
    };
    assert_eq!(columns, vec!["name".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Text("Ada".to_string()))]]);
    assert_eq!(row_count, 1);
}

#[test]
fn execute_sql_query_rejects_supported_single_entity_mutation_shapes() {
    reset_session_sql_store();
    let session = sql_session();

    for (sql, expected, context) in [
        (
            "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
            "execute_sql_query rejects INSERT; use execute_sql_update::<E>()",
            "query SQL surface should reject INSERT",
        ),
        (
            "UPDATE SessionSqlWriteEntity SET age = 22 WHERE id = 1",
            "execute_sql_query rejects UPDATE; use execute_sql_update::<E>()",
            "query SQL surface should reject UPDATE",
        ),
        (
            "DELETE FROM SessionSqlWriteEntity WHERE id = 1",
            "execute_sql_query rejects DELETE; use execute_sql_update::<E>()",
            "query SQL surface should reject DELETE",
        ),
    ] {
        let err = session
            .execute_sql_query::<SessionSqlWriteEntity>(sql)
            .expect_err(context);
        assert!(
            err.to_string().contains(expected),
            "{context} should preserve the query-to-update guidance",
        );
    }
}

#[test]
fn execute_sql_query_admits_supported_single_entity_read_shapes() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("ada", 21), ("bob", 21), ("carol", 32)]);

    let scalar = session
        .execute_sql_query::<SessionSqlEntity>(
            "SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("execute_sql_query should admit scalar SELECT");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = scalar
    else {
        panic!("execute_sql_query scalar SELECT should emit projection rows");
    };
    assert_eq!(columns, vec!["name".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Text("ada".to_string()))]]);
    assert_eq!(row_count, 1);

    let grouped = session
        .execute_sql_query::<SessionSqlEntity>(
            "SELECT age, COUNT(*) FROM SessionSqlEntity GROUP BY age",
        )
        .expect("execute_sql_query should admit grouped SELECT");
    let SqlStatementResult::Grouped {
        columns, row_count, ..
    } = grouped
    else {
        panic!("execute_sql_query grouped SELECT should emit grouped rows");
    };
    assert_eq!(columns, vec!["age".to_string(), "COUNT(*)".to_string()]);
    assert_eq!(row_count, 2);

    let aggregate = session
        .execute_sql_query::<SessionSqlEntity>("SELECT COUNT(*) FROM SessionSqlEntity")
        .expect("execute_sql_query should admit global aggregate SELECT");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = aggregate
    else {
        panic!("execute_sql_query aggregate SELECT should emit projection rows");
    };
    assert_eq!(columns, vec!["COUNT(*)".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Uint(3))]]);
    assert_eq!(row_count, 1);
}

#[expect(
    clippy::too_many_lines,
    reason = "artifact-family matrix intentionally keeps one representative read-lane table together"
)]
#[test]
fn compile_sql_query_and_execute_compiled_preserve_supported_read_families() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("ada", 21), ("bob", 21), ("carol", 32)]);

    let scalar = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("scalar SELECT should compile");
    assert!(
        matches!(
            scalar,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "scalar SELECT should compile to lowered SELECT artifact",
    );
    let SqlStatementResult::Projection { row_count, .. } = session
        .execute_compiled_sql::<SessionSqlEntity>(&scalar)
        .expect("compiled scalar SELECT should execute")
    else {
        panic!("compiled scalar SELECT should emit projection rows");
    };
    assert_eq!(row_count, 1);

    let grouped = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT age, COUNT(*) FROM SessionSqlEntity GROUP BY age",
        )
        .expect("grouped SELECT should compile");
    assert!(
        matches!(
            grouped,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped SELECT should stay on the lowered SELECT artifact family",
    );
    let SqlStatementResult::Grouped { row_count, .. } = session
        .execute_compiled_sql::<SessionSqlEntity>(&grouped)
        .expect("compiled grouped SELECT should execute")
    else {
        panic!("compiled grouped SELECT should emit grouped rows");
    };
    assert_eq!(row_count, 2);

    let aggregate = session
        .compile_sql_query::<SessionSqlEntity>("SELECT COUNT(*) FROM SessionSqlEntity")
        .expect("global aggregate SELECT should compile");
    assert!(
        matches!(
            aggregate,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "global aggregate SELECT should compile to dedicated aggregate artifact",
    );
    let SqlStatementResult::Projection { row_count, .. } = session
        .execute_compiled_sql::<SessionSqlEntity>(&aggregate)
        .expect("compiled aggregate SELECT should execute")
    else {
        panic!("compiled aggregate SELECT should emit projection rows");
    };
    assert_eq!(row_count, 1);

    let aggregate_with_having_alias = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT COUNT(*) AS total_rows \
             FROM SessionSqlEntity \
             HAVING total_rows > 1",
        )
        .expect("aliased global aggregate HAVING should compile");
    assert!(
        matches!(
            aggregate_with_having_alias,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "aliased global aggregate HAVING should stay on the dedicated aggregate artifact family",
    );

    let aggregate_without_else_truth_wrapper = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT COUNT(*) \
             FROM SessionSqlEntity \
             HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE END",
        )
        .expect("truth-wrapped global aggregate omitted-ELSE HAVING should compile");
    let aggregate_explicit_null = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT COUNT(*) \
             FROM SessionSqlEntity \
             HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE NULL END",
        )
        .expect("explicit ELSE NULL global aggregate HAVING should compile");
    assert!(
        matches!(
            aggregate_without_else_truth_wrapper,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "truth-wrapped global aggregate omitted-ELSE HAVING should stay on the dedicated aggregate artifact family",
    );
    assert!(
        matches!(
            aggregate_explicit_null,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "explicit ELSE NULL global aggregate HAVING should stay on the dedicated aggregate artifact family",
    );

    let explain = session
        .compile_sql_query::<SessionSqlEntity>(
            "EXPLAIN SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("EXPLAIN SELECT should compile");
    assert!(
        matches!(
            explain,
            crate::db::session::sql::CompiledSqlCommand::Explain(_)
        ),
        "EXPLAIN SELECT should compile to lowered explain artifact",
    );
    let SqlStatementResult::Explain(rendered) = session
        .execute_compiled_sql::<SessionSqlEntity>(&explain)
        .expect("compiled EXPLAIN should execute")
    else {
        panic!("compiled EXPLAIN should emit explain text");
    };
    assert!(
        !rendered.is_empty(),
        "compiled EXPLAIN should render a non-empty explain payload",
    );
}

#[test]
fn execute_sql_update_admits_supported_single_entity_mutation_shapes() {
    reset_session_sql_store();
    let session = sql_session();

    let insert = session
        .execute_sql_update::<SessionSqlWriteEntity>(
            "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
        )
        .expect("execute_sql_update should admit INSERT");
    let SqlStatementResult::Count { row_count } = insert else {
        panic!("execute_sql_update INSERT should emit count payload");
    };
    assert_eq!(row_count, 1);

    let update = session
        .execute_sql_update::<SessionSqlWriteEntity>(
            "UPDATE SessionSqlWriteEntity SET age = 22 WHERE id = 1",
        )
        .expect("execute_sql_update should admit UPDATE");
    let SqlStatementResult::Count { row_count } = update else {
        panic!("execute_sql_update UPDATE should emit count payload");
    };
    assert_eq!(row_count, 1);

    let delete = session
        .execute_sql_update::<SessionSqlWriteEntity>(
            "DELETE FROM SessionSqlWriteEntity WHERE name = 'Ada' RETURNING name",
        )
        .expect("execute_sql_update should admit DELETE RETURNING");
    let SqlStatementResult::Projection {
        columns,
        rows,
        row_count,
        ..
    } = delete
    else {
        panic!("execute_sql_update DELETE RETURNING should emit projection rows");
    };
    assert_eq!(columns, vec!["name".to_string()]);
    assert_eq!(rows, vec![vec![output(Value::Text("Ada".to_string()))]]);
    assert_eq!(row_count, 1);
}

#[test]
fn compile_sql_update_and_execute_compiled_preserve_supported_mutation_families() {
    reset_session_sql_store();
    let session = sql_session();

    let insert = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
        )
        .expect("INSERT should compile");
    assert!(
        matches!(
            insert,
            crate::db::session::sql::CompiledSqlCommand::Insert(_)
        ),
        "INSERT should compile to prepared INSERT artifact",
    );
    let SqlStatementResult::Count { row_count } = session
        .execute_compiled_sql::<SessionSqlWriteEntity>(&insert)
        .expect("compiled INSERT should execute")
    else {
        panic!("compiled INSERT should emit count payload");
    };
    assert_eq!(row_count, 1);

    let update = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "UPDATE SessionSqlWriteEntity SET age = 22 WHERE id = 1",
        )
        .expect("UPDATE should compile");
    assert!(
        matches!(
            update,
            crate::db::session::sql::CompiledSqlCommand::Update(_)
        ),
        "UPDATE should compile to prepared UPDATE artifact",
    );
    let SqlStatementResult::Count { row_count } = session
        .execute_compiled_sql::<SessionSqlWriteEntity>(&update)
        .expect("compiled UPDATE should execute")
    else {
        panic!("compiled UPDATE should emit count payload");
    };
    assert_eq!(row_count, 1);

    let delete = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "DELETE FROM SessionSqlWriteEntity WHERE name = 'Ada' RETURNING name",
        )
        .expect("DELETE RETURNING should compile through update surface");
    let crate::db::session::sql::CompiledSqlCommand::Delete { returning, .. } = &delete else {
        panic!("DELETE RETURNING should compile to lowered DELETE artifact");
    };
    assert!(
        matches!(
            returning,
            Some(crate::db::sql::parser::SqlReturningProjection::Fields(fields))
                if matches!(fields.as_slice(), [field] if field == "name")
        ),
        "compiled DELETE artifact should retain only the RETURNING projection contract",
    );
    let SqlStatementResult::Projection { row_count, .. } = session
        .execute_compiled_sql::<SessionSqlWriteEntity>(&delete)
        .expect("compiled DELETE RETURNING should execute")
    else {
        panic!("compiled DELETE RETURNING should emit projection rows");
    };
    assert_eq!(row_count, 1);
}

#[test]
fn sql_compile_cache_keeps_query_and_update_surfaces_separate() {
    reset_session_sql_store();
    let session = sql_session();

    let insert_sql = "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)";
    let insert = session
        .compile_sql_update::<SessionSqlWriteEntity>(insert_sql)
        .expect("update surface should compile INSERT into the session-local cache");
    assert!(
        matches!(
            insert,
            crate::db::session::sql::CompiledSqlCommand::Insert(_)
        ),
        "update surface should cache the INSERT artifact under the update lane only",
    );

    let err = session
        .compile_sql_query::<SessionSqlWriteEntity>(insert_sql)
        .expect_err("query surface must not reuse the cached update artifact");
    assert!(
        err.to_string()
            .contains("execute_sql_query rejects INSERT; use execute_sql_update::<E>()"),
        "query surface should preserve its own lane boundary after an update-surface cache fill",
    );
}

#[test]
fn sql_compile_cache_covers_query_surface_read_explain_and_metadata_families() {
    reset_session_sql_store();
    let session = sql_session();

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        0,
        "new SQL session should start with an empty compiled-command cache",
    );

    let scalar = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("scalar SELECT should compile into the query-surface cache");
    assert!(
        matches!(
            scalar,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "scalar SELECT should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "first query-surface compile should populate one cache entry",
    );

    let scalar_repeat = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("same scalar SELECT should compile from the existing cache entry");
    assert!(
        matches!(
            scalar_repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeated scalar SELECT should still resolve to the same artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical query-surface compile must not grow the cache",
    );
    assert_scalar_compiled_select_executes_through_shared_query_plan(&session, &scalar_repeat);

    let explain = session
        .compile_sql_query::<SessionSqlEntity>(
            "EXPLAIN SELECT name FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("EXPLAIN should compile into the query-surface cache");
    assert!(
        matches!(
            explain,
            crate::db::session::sql::CompiledSqlCommand::Explain(_)
        ),
        "EXPLAIN should use its dedicated compiled artifact family",
    );

    let describe = session
        .compile_sql_query::<SessionSqlEntity>("DESCRIBE SessionSqlEntity")
        .expect("DESCRIBE should compile into the query-surface cache");
    assert!(
        matches!(
            describe,
            crate::db::session::sql::CompiledSqlCommand::DescribeEntity
        ),
        "DESCRIBE should cache its dedicated metadata artifact",
    );

    let show_indexes = session
        .compile_sql_query::<SessionSqlEntity>("SHOW INDEXES SessionSqlEntity")
        .expect("SHOW INDEXES should compile into the query-surface cache");
    assert!(
        matches!(
            show_indexes,
            crate::db::session::sql::CompiledSqlCommand::ShowIndexesEntity
        ),
        "SHOW INDEXES should cache its dedicated metadata artifact",
    );

    let show_columns = session
        .compile_sql_query::<SessionSqlEntity>("SHOW COLUMNS SessionSqlEntity")
        .expect("SHOW COLUMNS should compile into the query-surface cache");
    assert!(
        matches!(
            show_columns,
            crate::db::session::sql::CompiledSqlCommand::ShowColumnsEntity
        ),
        "SHOW COLUMNS should cache its dedicated metadata artifact",
    );

    let show_entities = session
        .compile_sql_query::<SessionSqlEntity>("SHOW ENTITIES")
        .expect("SHOW ENTITIES should compile into the query-surface cache");
    assert!(
        matches!(
            show_entities,
            crate::db::session::sql::CompiledSqlCommand::ShowEntities
        ),
        "SHOW ENTITIES should cache its dedicated metadata artifact",
    );

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        6,
        "query-surface cache should retain distinct entries for SELECT, EXPLAIN, and metadata families",
    );
}

fn assert_compiled_select_executes_through_shared_query_plan_for_entity<E>(
    session: &DbSession<SessionSqlCanister>,
    compiled: &crate::db::session::sql::CompiledSqlCommand,
) where
    E: PersistedRow<Canister = SessionSqlCanister> + EntityValue,
{
    let _ = session
        .execute_compiled_sql::<E>(compiled)
        .expect("executing one compiled SELECT should succeed through the shared lower cache");

    let _ = session.execute_compiled_sql::<E>(compiled).expect(
        "repeating one compiled SELECT should still succeed through the shared lower cache",
    );
}

fn assert_scalar_compiled_select_executes_through_shared_query_plan(
    session: &DbSession<SessionSqlCanister>,
    compiled: &crate::db::session::sql::CompiledSqlCommand,
) {
    assert_compiled_select_executes_through_shared_query_plan_for_entity::<SessionSqlEntity>(
        session, compiled,
    );
}

#[test]
fn shared_query_plan_cache_is_reused_by_fluent_and_sql_select_surfaces() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 21), ("Bob", 32)]);

    assert_eq!(
        session.query_plan_cache_len(),
        0,
        "new session should start with an empty shared query-plan cache",
    );

    let sql = session
        .compile_sql_query::<SessionSqlEntity>(
            "SELECT * FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
        )
        .expect("scalar SELECT * should compile");
    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&sql)
        .expect("executing one compiled SQL select should populate the shared query-plan cache");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first SQL execution should populate one shared query-plan cache entry",
    );

    let fluent = session
        .load::<SessionSqlEntity>()
        .order_term(crate::db::asc("age"))
        .order_term(crate::db::asc("id"))
        .limit(1);
    let _ = session
        .execute_query(fluent.query())
        .expect("equivalent fluent query should execute");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "equivalent fluent execution should reuse the shared structural query-plan entry",
    );
}

#[test]
fn shared_query_plan_cache_reuses_canonical_equivalent_scalar_filter_forms() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    let searched_case_sql = "SELECT name \
                             FROM SessionSqlEntity \
                             WHERE CASE WHEN age >= 30 THEN TRUE ELSE age = 20 END \
                             ORDER BY age ASC, id ASC LIMIT 2";
    let canonical_sql = "SELECT name \
                         FROM SessionSqlEntity \
                         WHERE COALESCE(age >= 30, FALSE) \
                            OR (NOT COALESCE(age >= 30, FALSE) AND age = 20) \
                         ORDER BY age ASC, id ASC LIMIT 2";

    let searched_case = session
        .compile_sql_query::<SessionSqlEntity>(searched_case_sql)
        .expect("searched CASE scalar filter query should compile");
    let canonical = session
        .compile_sql_query::<SessionSqlEntity>(canonical_sql)
        .expect("canonical scalar filter query should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "different SQL spellings should remain distinct compiled-command cache entries",
    );
    assert_eq!(
        session.query_plan_cache_len(),
        0,
        "query-plan cache should still start empty before execution",
    );

    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&searched_case)
        .expect("searched CASE scalar filter query should execute");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first canonical-equivalent scalar filter execution should populate one shared query-plan cache entry",
    );

    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&canonical)
        .expect("canonical scalar filter query should execute");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "canonical-equivalent scalar filter execution should reuse the same shared query-plan cache entry",
    );
}

#[test]
fn shared_query_plan_cache_keeps_semantically_distinct_expression_filters_separate() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    let left_sql = "SELECT name \
                    FROM SessionSqlEntity \
                    WHERE COALESCE(age >= 30, FALSE) \
                       OR (NOT COALESCE(age >= 30, FALSE) AND age = 20) \
                    ORDER BY age ASC, id ASC LIMIT 2";
    let right_sql = "SELECT name \
                     FROM SessionSqlEntity \
                     WHERE COALESCE(age >= 31, FALSE) \
                        OR (NOT COALESCE(age >= 31, FALSE) AND age = 20) \
                     ORDER BY age ASC, id ASC LIMIT 2";

    let left = session
        .compile_sql_query::<SessionSqlEntity>(left_sql)
        .expect("left scalar filter query should compile");
    let right = session
        .compile_sql_query::<SessionSqlEntity>(right_sql)
        .expect("right scalar filter query should compile");

    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&left)
        .expect("left scalar filter query should execute");
    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&right)
        .expect("right scalar filter query should execute");

    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "semantically distinct expression-owned scalar filters must not alias on the shared query-plan cache",
    );
}

#[test]
fn shared_query_plan_cache_keeps_is_true_and_is_not_true_filters_separate() {
    reset_session_sql_store();
    let session = sql_session();

    for (label, active, archived) in [
        ("bool-a", true, false),
        ("bool-b", false, false),
        ("bool-c", true, true),
    ] {
        session
            .insert(SessionSqlBoolCompareEntity {
                id: Ulid::generate(),
                label: label.to_string(),
                active,
                archived,
            })
            .expect("bool compare fixture insert should succeed");
    }

    let is_true = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(
            "SELECT label \
             FROM SessionSqlBoolCompareEntity \
             WHERE active IS TRUE \
             ORDER BY label ASC",
        )
        .expect("IS TRUE query should compile");
    let is_not_true = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(
            "SELECT label \
             FROM SessionSqlBoolCompareEntity \
             WHERE active IS NOT TRUE \
             ORDER BY label ASC",
        )
        .expect("IS NOT TRUE query should compile");

    let true_rows = statement_projection_rows::<SessionSqlBoolCompareEntity>(
        &session,
        "SELECT label FROM SessionSqlBoolCompareEntity WHERE active IS TRUE ORDER BY label ASC",
    )
    .expect("IS TRUE query should execute");
    let not_true_rows = statement_projection_rows::<SessionSqlBoolCompareEntity>(
        &session,
        "SELECT label FROM SessionSqlBoolCompareEntity WHERE active IS NOT TRUE ORDER BY label ASC",
    )
    .expect("IS NOT TRUE query should execute");

    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "semantic negation must not alias shared query-plan cache identity with the positive boolean filter",
    );
    assert_ne!(
        true_rows, not_true_rows,
        "IS TRUE and IS NOT TRUE must not reuse the same compiled semantic plan",
    );

    let _ = is_true;
    let _ = is_not_true;
}

#[expect(
    clippy::too_many_lines,
    reason = "scalar truth-wrapper identity matrix intentionally proves one semantic boundary"
)]
#[test]
fn scalar_bool_truth_wrappers_reuse_semantic_identity() {
    reset_session_sql_store();
    let session = sql_session();

    for (label, active, archived) in [
        ("bool-a", true, false),
        ("bool-b", false, false),
        ("bool-c", true, true),
    ] {
        session
            .insert(SessionSqlBoolCompareEntity {
                id: Ulid::generate(),
                label: label.to_string(),
                active,
                archived,
            })
            .expect("bool compare fixture insert should succeed");
    }

    // Phase 1: compile four syntax-distinct spellings that should collapse into
    // two canonical scalar truth-condition identities.
    let is_true_sql = "SELECT label \
                       FROM SessionSqlBoolCompareEntity \
                       WHERE active IS TRUE \
                       ORDER BY label ASC";
    let bare_sql = "SELECT label \
                    FROM SessionSqlBoolCompareEntity \
                    WHERE active \
                    ORDER BY label ASC";
    let is_false_sql = "SELECT label \
                        FROM SessionSqlBoolCompareEntity \
                        WHERE active IS FALSE \
                        ORDER BY label ASC";
    let not_sql = "SELECT label \
                   FROM SessionSqlBoolCompareEntity \
                   WHERE NOT active \
                   ORDER BY label ASC";
    let is_true = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(is_true_sql)
        .expect("IS TRUE query should compile");
    let bare = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(bare_sql)
        .expect("bare bool truth query should compile");
    let is_false = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(is_false_sql)
        .expect("IS FALSE query should compile");
    let not_active = session
        .compile_sql_query::<SessionSqlBoolCompareEntity>(not_sql)
        .expect("NOT bool truth query should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        4,
        "scalar bool wrapper spellings should still occupy distinct compiled-command cache entries",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<SessionSqlBoolCompareEntity>(
        &is_true,
        is_true_sql,
        "IS TRUE bool truth query should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<SessionSqlBoolCompareEntity>(
        &bare,
        bare_sql,
        "bare bool truth query should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<SessionSqlBoolCompareEntity>(
        &is_false,
        is_false_sql,
        "IS FALSE bool truth query should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<SessionSqlBoolCompareEntity>(
        &not_active,
        not_sql,
        "NOT bool truth query should preserve canonical lowered identity",
    );

    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: is_true_query,
        ..
    } = &is_true
    else {
        panic!("IS TRUE query should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: bare_query, ..
    } = &bare
    else {
        panic!("bare bool truth query should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: is_false_query,
        ..
    } = &is_false
    else {
        panic!("IS FALSE query should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: not_query, ..
    } = &not_active
    else {
        panic!("NOT bool truth query should compile into one SELECT artifact");
    };

    // Phase 2: require canonical truth-wrapper identities to agree on both the
    // structural cache key and the semantic plan fingerprint.
    assert_eq!(
        is_true_query.structural_cache_key(),
        bare_query.structural_cache_key(),
        "IS TRUE must collapse onto the same structural cache identity as the bare bool truth condition",
    );
    assert_eq!(
        is_true_query
            .build_plan()
            .expect("IS TRUE bool plan should build")
            .fingerprint(),
        bare_query
            .build_plan()
            .expect("bare bool truth plan should build")
            .fingerprint(),
        "IS TRUE must share semantic plan fingerprint identity with the bare bool truth condition",
    );
    assert_eq!(
        is_false_query.structural_cache_key(),
        not_query.structural_cache_key(),
        "IS FALSE must collapse onto the same structural cache identity as NOT <bool expr>",
    );
    assert_eq!(
        is_false_query
            .build_plan()
            .expect("IS FALSE bool plan should build")
            .fingerprint(),
        not_query
            .build_plan()
            .expect("NOT bool truth plan should build")
            .fingerprint(),
        "IS FALSE must share semantic plan fingerprint identity with NOT <bool expr>",
    );

    // Phase 3: execution should still allocate one shared query-plan cache
    // entry per canonical truth-condition identity.
    let _ = session
        .execute_compiled_sql::<SessionSqlBoolCompareEntity>(&is_true)
        .expect("executing IS TRUE query should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first scalar truth-wrapper execution should populate one shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<SessionSqlBoolCompareEntity>(&bare)
        .expect("executing bare bool truth query should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "bare bool truth condition should reuse the IS TRUE semantic plan identity",
    );
    let _ = session
        .execute_compiled_sql::<SessionSqlBoolCompareEntity>(&is_false)
        .expect("executing IS FALSE query should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "second scalar truth-condition family should allocate a second shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<SessionSqlBoolCompareEntity>(&not_active)
        .expect("executing NOT bool truth query should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "NOT <bool expr> should reuse the IS FALSE semantic plan identity",
    );
}

#[test]
fn trace_query_reuses_canonical_equivalent_scalar_filter_plan_identity() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    // Phase 1: lower two SQL spellings that now belong to the same canonical
    // scalar filter identity after 0.107/0.108 normalization.
    let searched_case_sql = "SELECT name \
                             FROM SessionSqlEntity \
                             WHERE CASE WHEN age >= 30 THEN TRUE ELSE age = 20 END \
                             ORDER BY age ASC, id ASC LIMIT 2";
    let canonical_sql = "SELECT name \
                         FROM SessionSqlEntity \
                         WHERE COALESCE(age >= 30, FALSE) \
                            OR (NOT COALESCE(age >= 30, FALSE) AND age = 20) \
                         ORDER BY age ASC, id ASC LIMIT 2";
    let searched_case =
        lower_select_query_for_tests::<SessionSqlEntity>(&session, searched_case_sql)
            .expect("searched CASE scalar filter query should lower for trace parity");
    let canonical = lower_select_query_for_tests::<SessionSqlEntity>(&session, canonical_sql)
        .expect("canonical scalar filter query should lower for trace parity");

    assert_eq!(
        session.query_plan_cache_len(),
        0,
        "trace parity fixture should start with an empty shared query-plan cache",
    );

    // Phase 2: require trace-query planning to reuse the same canonical plan
    // identity and outward trace payload for both lowered query spellings.
    let searched_trace = session
        .trace_query(&searched_case)
        .expect("searched CASE scalar filter trace should build");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first canonical-equivalent trace should populate one shared query-plan entry",
    );

    let canonical_trace = session
        .trace_query(&canonical)
        .expect("canonical scalar filter trace should build");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "canonical-equivalent trace should reuse the same shared query-plan entry",
    );
    assert_eq!(
        searched_trace.plan_hash(),
        canonical_trace.plan_hash(),
        "trace plan hashes must follow canonical scalar filter identity rather than SQL spelling",
    );
    assert_eq!(
        searched_trace.reuse().artifact_class(),
        crate::db::TraceReuseArtifactClass::SharedPreparedQueryPlan,
        "trace should surface the shipped semantic-reuse artifact class",
    );
    assert!(
        !searched_trace.reuse().is_hit(),
        "first canonical trace should miss shared prepared-plan reuse before the cache is warm",
    );
    assert!(
        canonical_trace.reuse().is_hit(),
        "canonical-equivalent second trace should hit shared prepared-plan reuse",
    );
    assert_eq!(
        searched_trace.explain(),
        canonical_trace.explain(),
        "trace explain payloads must follow the same canonical scalar filter identity",
    );
    assert_eq!(
        searched_trace.access_strategy(),
        canonical_trace.access_strategy(),
        "trace access summaries must stay aligned once canonical filter identity collapses the SQL spellings",
    );
}

#[test]
fn fluent_trace_and_plan_hash_reuse_canonical_equivalent_filter_order() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    // Phase 1: build two fluent queries whose scalar filters are semantically
    // identical but arrive through different mutation order.
    let left = session
        .load::<SessionSqlEntity>()
        .filter(crate::db::FieldRef::new("age").gte(20_u64))
        .filter(crate::db::FieldRef::new("age").lt(40_u64))
        .order_term(crate::db::asc("age"))
        .order_term(crate::db::asc("id"))
        .limit(2);
    let right = session
        .load::<SessionSqlEntity>()
        .filter(crate::db::FieldRef::new("age").lt(40_u64))
        .filter(crate::db::FieldRef::new("age").gte(20_u64))
        .order_term(crate::db::asc("age"))
        .order_term(crate::db::asc("id"))
        .limit(2);

    let left_hash = left
        .plan_hash_hex()
        .expect("left fluent query should derive one canonical plan hash");
    let right_hash = right
        .plan_hash_hex()
        .expect("right fluent query should derive one canonical plan hash");
    assert_eq!(
        left_hash, right_hash,
        "canonical-equivalent fluent filter order must share one outward plan hash",
    );
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "plan-hash derivation should populate the shared prepared query-plan cache",
    );

    // Phase 2: require the public fluent trace wrapper to reuse the same
    // canonical shared query-plan entry warmed by plan-hash derivation.
    let left_trace = left
        .trace()
        .expect("left fluent trace should build through the shared session surface");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first fluent trace should reuse the shared query-plan entry warmed by plan-hash derivation",
    );

    let right_trace = right
        .trace()
        .expect("right fluent trace should build through the shared session surface");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "canonical-equivalent fluent trace should reuse the same shared query-plan entry",
    );
    assert_eq!(
        left_trace.plan_hash(),
        right_trace.plan_hash(),
        "fluent trace plan hash must follow canonical filter identity rather than append order",
    );
    assert_eq!(
        left_trace.explain(),
        right_trace.explain(),
        "fluent trace explain payloads must stay identical for canonical-equivalent filter order",
    );
}

#[test]
fn fluent_trace_and_plan_hash_reuse_canonical_equivalent_grouped_having_order() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    // Phase 1: build two grouped fluent queries whose HAVING clauses are
    // semantically identical but arrive through different builder order.
    let left = session
        .load::<SessionSqlEntity>()
        .group_by("age")
        .expect("left grouped fluent query should resolve group field")
        .aggregate(crate::db::count())
        .having_group(
            "age",
            crate::db::CompareOp::Gte,
            crate::value::InputValue::from(Value::Int(20)),
        )
        .expect("left grouped fluent query should accept group-field HAVING")
        .having_aggregate(
            0,
            crate::db::CompareOp::Gt,
            crate::value::InputValue::from(Value::Uint(0)),
        )
        .expect("left grouped fluent query should accept aggregate HAVING");
    let right = session
        .load::<SessionSqlEntity>()
        .group_by("age")
        .expect("right grouped fluent query should resolve group field")
        .aggregate(crate::db::count())
        .having_aggregate(
            0,
            crate::db::CompareOp::Gt,
            crate::value::InputValue::from(Value::Uint(0)),
        )
        .expect("right grouped fluent query should accept aggregate HAVING")
        .having_group(
            "age",
            crate::db::CompareOp::Gte,
            crate::value::InputValue::from(Value::Int(20)),
        )
        .expect("right grouped fluent query should accept group-field HAVING");

    let left_hash = left
        .plan_hash_hex()
        .expect("left grouped fluent query should derive one canonical plan hash");
    let right_hash = right
        .plan_hash_hex()
        .expect("right grouped fluent query should derive one canonical plan hash");
    assert_eq!(
        left_hash, right_hash,
        "canonical-equivalent grouped HAVING order must share one outward plan hash",
    );
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "grouped plan-hash derivation should populate the shared query-plan cache",
    );

    // Phase 2: require grouped fluent trace reuse to follow the same canonical
    // HAVING identity and shared query-plan cache entry warmed by plan-hash
    // derivation.
    let left_trace = left
        .trace()
        .expect("left grouped fluent trace should build through the shared session surface");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first grouped fluent trace should reuse the shared query-plan entry warmed by plan-hash derivation",
    );

    let right_trace = right
        .trace()
        .expect("right grouped fluent trace should build through the shared session surface");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "canonical-equivalent grouped fluent trace should reuse the same shared query-plan entry",
    );
    assert_eq!(
        left_trace.plan_hash(),
        right_trace.plan_hash(),
        "grouped fluent trace plan hash must follow canonical HAVING identity rather than append order",
    );
    assert_eq!(
        left_trace.reuse().artifact_class(),
        crate::db::TraceReuseArtifactClass::SharedPreparedQueryPlan,
        "grouped trace should surface the shipped semantic-reuse artifact class",
    );
    assert!(
        left_trace.reuse().is_hit(),
        "first grouped trace should hit shared prepared-plan reuse after plan-hash derivation warms the cache",
    );
    assert!(
        right_trace.reuse().is_hit(),
        "canonical-equivalent grouped trace should hit shared prepared-plan reuse",
    );
    assert_eq!(
        left_trace.explain(),
        right_trace.explain(),
        "grouped fluent trace explain payloads must stay identical for canonical-equivalent HAVING order",
    );
}

#[test]
fn trace_query_reports_reuse_miss_for_distinct_semantic_identity() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    let left_sql = "SELECT name \
                    FROM SessionSqlEntity \
                    WHERE age >= 20 \
                    ORDER BY age ASC, id ASC LIMIT 2";
    let right_sql = "SELECT name \
                     FROM SessionSqlEntity \
                     WHERE age >= 20 \
                     ORDER BY age DESC, id DESC LIMIT 1";
    let left = lower_select_query_for_tests::<SessionSqlEntity>(&session, left_sql)
        .expect("left trace identity fixture should lower");
    let right = lower_select_query_for_tests::<SessionSqlEntity>(&session, right_sql)
        .expect("right trace identity fixture should lower");

    let left_trace = session
        .trace_query(&left)
        .expect("left distinct-identity trace should build");
    let right_trace = session
        .trace_query(&right)
        .expect("right distinct-identity trace should build");

    assert!(
        !left_trace.reuse().is_hit(),
        "first distinct query should miss shared prepared-plan reuse",
    );
    assert!(
        !right_trace.reuse().is_hit(),
        "different semantic identity should build a second plan instead of reusing the first",
    );
    assert_ne!(
        left_trace.plan_hash(),
        right_trace.plan_hash(),
        "distinct semantic identity fixture should stay on different plan hashes",
    );
}

#[test]
fn trace_query_reports_reuse_miss_for_distinct_projection_identity() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    let left_sql = "SELECT name \
                    FROM SessionSqlEntity \
                    WHERE age >= 20 \
                    ORDER BY age ASC, id ASC LIMIT 2";
    let right_sql = "SELECT age \
                     FROM SessionSqlEntity \
                     WHERE age >= 20 \
                     ORDER BY age ASC, id ASC LIMIT 2";
    let left = lower_select_query_for_tests::<SessionSqlEntity>(&session, left_sql)
        .expect("left projection-identity fixture should lower");
    let right = lower_select_query_for_tests::<SessionSqlEntity>(&session, right_sql)
        .expect("right projection-identity fixture should lower");

    let left_trace = session
        .trace_query(&left)
        .expect("left projection-identity trace should build");
    let right_trace = session
        .trace_query(&right)
        .expect("right projection-identity trace should build");

    assert!(
        !left_trace.reuse().is_hit(),
        "first projection shape should miss shared prepared-plan reuse",
    );
    assert!(
        !right_trace.reuse().is_hit(),
        "different projection shape should build a second plan instead of reusing the first",
    );
    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "distinct projection identity should occupy separate shared query-plan cache entries",
    );
    assert_ne!(
        left_trace.plan_hash(),
        right_trace.plan_hash(),
        "distinct projection identity should stay on different plan hashes",
    );
}

#[test]
fn trace_query_reports_reuse_miss_for_distinct_grouping_identity() {
    reset_session_sql_store();
    let session = sql_session();
    seed_session_sql_entities(&session, &[("Ada", 20), ("Bea", 30), ("Cara", 31)]);

    let left_sql = "SELECT age \
                    FROM SessionSqlEntity \
                    WHERE age >= 20 \
                    ORDER BY age ASC, id ASC LIMIT 2";
    let right_sql = "SELECT age, COUNT(*) \
                     FROM SessionSqlEntity \
                     WHERE age >= 20 \
                     GROUP BY age \
                     ORDER BY age ASC LIMIT 2";
    let left = lower_select_query_for_tests::<SessionSqlEntity>(&session, left_sql)
        .expect("left grouping-identity fixture should lower");
    let right = lower_select_query_for_tests::<SessionSqlEntity>(&session, right_sql)
        .expect("right grouping-identity fixture should lower");

    let left_trace = session
        .trace_query(&left)
        .expect("left grouping-identity trace should build");
    let right_trace = session
        .trace_query(&right)
        .expect("right grouping-identity trace should build");

    assert!(
        !left_trace.reuse().is_hit(),
        "first grouping shape should miss shared prepared-plan reuse",
    );
    assert!(
        !right_trace.reuse().is_hit(),
        "different grouping shape should build a second plan instead of reusing the first",
    );
    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "distinct grouping identity should occupy separate shared query-plan cache entries",
    );
    assert_ne!(
        left_trace.plan_hash(),
        right_trace.plan_hash(),
        "distinct grouping identity should stay on different plan hashes",
    );
}

#[test]
fn shared_query_plan_cache_key_version_mismatch_fails_closed() {
    reset_session_sql_store();
    let session = sql_session();
    let query = session
        .load::<SessionSqlEntity>()
        .order_term(crate::db::asc("age"))
        .order_term(crate::db::asc("id"))
        .limit(1);
    let schema_fingerprint = commit_schema_fingerprint_for_entity::<SessionSqlEntity>();
    let authority = EntityAuthority::for_type::<SessionSqlEntity>();
    let old_key = DbSession::<SessionSqlCanister>::query_plan_cache_key_for_tests(
        authority,
        schema_fingerprint,
        QueryPlanVisibility::StoreReady,
        query.query().structural(),
        1,
    );
    let new_key = DbSession::<SessionSqlCanister>::query_plan_cache_key_for_tests(
        authority,
        schema_fingerprint,
        QueryPlanVisibility::StoreReady,
        query.query().structural(),
        2,
    );
    let mut cache = HashSet::new();
    cache.insert(old_key.clone());

    assert_ne!(
        old_key, new_key,
        "shared lower-plan cache identity must include one explicit method version",
    );
    assert!(
        !cache.contains(&new_key),
        "shared lower-plan cache version mismatch must fail closed instead of reusing an older entry",
    );
}

#[test]
fn sql_cache_key_version_mismatch_fails_closed() {
    let compiled_v1 =
        SqlCompiledCommandCacheKey::query_for_entity_with_method_version::<SessionSqlEntity>(
            "SELECT * FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
            1,
        );
    let compiled_v2 =
        SqlCompiledCommandCacheKey::query_for_entity_with_method_version::<SessionSqlEntity>(
            "SELECT * FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
            2,
        );
    let mut compiled_cache = HashSet::new();
    compiled_cache.insert(compiled_v1.clone());

    assert_ne!(
        compiled_v1, compiled_v2,
        "compiled SQL cache identity must include one explicit method version",
    );
    assert!(
        !compiled_cache.contains(&compiled_v2),
        "compiled SQL cache version mismatch must fail closed instead of reusing an older entry",
    );
}

#[test]
fn sql_cache_key_version_keeps_query_and_update_surfaces_separate() {
    let query_key =
        SqlCompiledCommandCacheKey::query_for_entity_with_method_version::<SessionSqlEntity>(
            "SELECT * FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
            1,
        );
    let update_key =
        SqlCompiledCommandCacheKey::update_for_entity_with_method_version::<SessionSqlEntity>(
            "SELECT * FROM SessionSqlEntity ORDER BY age ASC, id ASC LIMIT 1",
            1,
        );
    let mut cache = HashSet::new();
    cache.insert(query_key.clone());

    assert_ne!(
        query_key, update_key,
        "cache method versioning must not collapse query and update surface identity",
    );
    assert!(
        !cache.contains(&update_key),
        "query/update surface mismatch must fail closed even when the cache method version matches",
    );
}

#[test]
fn bounded_numeric_order_terms_use_the_normal_sql_surface_identity_and_cache_path() {
    for (sql, compile_context, identity_context) in [
        (
            "SELECT age + 1 AS next_age FROM SessionSqlEntity ORDER BY next_age ASC LIMIT 2",
            "bounded numeric ORDER BY alias",
            "admitted ORDER BY aliases",
        ),
        (
            "SELECT age FROM SessionSqlEntity ORDER BY age + 1 ASC LIMIT 2",
            "direct bounded numeric ORDER BY",
            "direct bounded numeric ORDER BY terms",
        ),
    ] {
        reset_session_sql_store();
        let session = sql_session();

        assert_eq!(
            session.sql_compiled_command_cache_len(),
            0,
            "new SQL session should start with an empty compiled-command cache",
        );
        let compiled = session
            .compile_sql_query::<SessionSqlEntity>(sql)
            .unwrap_or_else(|err| {
                panic!("{compile_context} should compile through the SQL surface: {err:?}")
            });
        let repeat = session
            .compile_sql_query::<SessionSqlEntity>(sql)
            .unwrap_or_else(|err| panic!("repeating one {compile_context} compile should hit the same compiled-command cache entry: {err:?}"));

        assert!(
            matches!(
                compiled,
                crate::db::session::sql::CompiledSqlCommand::Select { .. }
            ),
            "{compile_context} should stay on the normal SELECT compile lane",
        );
        assert!(
            matches!(
                repeat,
                crate::db::session::sql::CompiledSqlCommand::Select { .. }
            ),
            "repeating one {compile_context} compile should stay on the normal SELECT compile lane",
        );
        assert_eq!(
            session.sql_compiled_command_cache_len(),
            1,
            "repeating one identical {compile_context} compile must not grow the compiled-command cache",
        );

        assert_compiled_select_query_matches_lowered_identity(
            &compiled,
            sql,
            format!(
                "{identity_context} must canonicalize onto the same structural query cache key before cache insertion"
            )
            .as_str(),
        );

        assert_scalar_compiled_select_executes_through_shared_query_plan(&session, &compiled);
    }
}

#[test]
fn grouped_aggregate_order_alias_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let sql = "SELECT name, AVG(age) AS avg_age \
               FROM IndexedSessionSqlEntity \
               GROUP BY name \
               ORDER BY avg_age DESC, name ASC LIMIT 2";

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        0,
        "new indexed SQL session should start with an empty compiled-command cache",
    );
    let compiled = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("grouped aggregate ORDER BY alias should compile through the normal SQL surface");
    let repeat = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("repeating one grouped aggregate ORDER BY alias compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped aggregate ORDER BY alias should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one grouped aggregate ORDER BY alias compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical grouped aggregate ORDER BY alias compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &compiled,
        sql,
        "grouped aggregate ORDER BY aliases must canonicalize onto the same structural query cache key before cache insertion",
    );
}

#[test]
fn grouped_aggregate_input_order_alias_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let sql = "SELECT name, AVG(age + 1) AS avg_plus_one \
               FROM IndexedSessionSqlEntity \
               GROUP BY name \
               ORDER BY avg_plus_one DESC, name ASC LIMIT 2";

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        0,
        "new indexed SQL session should start with an empty compiled-command cache",
    );
    let compiled = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect(
            "grouped aggregate input ORDER BY alias should compile through the normal SQL surface",
        );
    let repeat = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("repeating one grouped aggregate input ORDER BY alias compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped aggregate input ORDER BY alias should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one grouped aggregate input ORDER BY alias compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical grouped aggregate input ORDER BY alias compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &compiled,
        sql,
        "grouped aggregate input ORDER BY aliases must canonicalize onto the same structural query cache key before cache insertion",
    );
}

#[test]
fn searched_case_scalar_projection_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_session_sql_store();
    let session = sql_session();

    let sql = "SELECT CASE WHEN age >= 30 THEN name ELSE 'young' END AS age_bucket \
               FROM SessionSqlEntity \
               ORDER BY id ASC LIMIT 2";

    let compiled = session
        .compile_sql_query::<SessionSqlEntity>(sql)
        .expect("searched CASE scalar projection should compile through the normal SQL surface");
    let repeat = session
        .compile_sql_query::<SessionSqlEntity>(sql)
        .expect("repeating one searched CASE scalar projection compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "searched CASE scalar projection should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one searched CASE scalar projection compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical searched CASE scalar projection compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity(
        &compiled,
        sql,
        "searched CASE scalar projections must canonicalize onto the same structural query cache key before cache insertion",
    );
    assert_scalar_compiled_select_executes_through_shared_query_plan(&session, &compiled);
}

#[test]
fn searched_case_grouped_projection_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let sql = "SELECT age, CASE WHEN COUNT(*) > 1 THEN 'multi' ELSE 'single' END AS bucket \
               FROM IndexedSessionSqlEntity \
               GROUP BY age \
               ORDER BY age ASC LIMIT 2";

    let compiled = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("grouped searched CASE projection should compile through the normal SQL surface");
    let repeat = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("repeating one grouped searched CASE projection compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped searched CASE projection should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one grouped searched CASE projection compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical grouped searched CASE projection compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &compiled,
        sql,
        "grouped searched CASE projections must canonicalize onto the same structural query cache key before cache insertion",
    );
    assert_compiled_select_executes_through_shared_query_plan_for_entity::<IndexedSessionSqlEntity>(
        &session, &compiled,
    );
}

#[test]
fn searched_case_grouped_having_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let sql = "SELECT age, COUNT(*) \
               FROM IndexedSessionSqlEntity \
               GROUP BY age \
               HAVING CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END = 1 \
               ORDER BY age ASC LIMIT 2";

    let compiled = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("grouped searched CASE HAVING should compile through the normal SQL surface");
    let repeat = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("repeating one grouped searched CASE HAVING compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped searched CASE HAVING should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one grouped searched CASE HAVING compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical grouped searched CASE HAVING compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &compiled,
        sql,
        "grouped searched CASE HAVING must canonicalize onto the same structural query cache key before cache insertion",
    );
    assert_compiled_select_executes_through_shared_query_plan_for_entity::<IndexedSessionSqlEntity>(
        &session, &compiled,
    );
}

#[test]
fn searched_case_aggregate_input_alias_uses_the_normal_sql_surface_identity_and_cache_path() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let sql = "SELECT age, SUM(CASE WHEN age > 10 THEN 1 ELSE 0 END) AS high_count \
               FROM IndexedSessionSqlEntity \
               GROUP BY age \
               ORDER BY high_count DESC, age ASC LIMIT 2";

    let compiled = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("grouped searched CASE aggregate input ORDER BY alias should compile through the normal SQL surface");
    let repeat = session
        .compile_sql_query::<IndexedSessionSqlEntity>(sql)
        .expect("repeating one grouped searched CASE aggregate input ORDER BY alias compile should hit the same compiled-command cache entry");

    assert!(
        matches!(
            compiled,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "grouped searched CASE aggregate input ORDER BY alias should stay on the lowered SELECT artifact family",
    );
    assert!(
        matches!(
            repeat,
            crate::db::session::sql::CompiledSqlCommand::Select { .. }
        ),
        "repeating one grouped searched CASE aggregate input ORDER BY alias compile should stay on the lowered SELECT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical grouped searched CASE aggregate input ORDER BY alias compile must not grow the compiled-command cache",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &compiled,
        sql,
        "grouped searched CASE aggregate input ORDER BY aliases must canonicalize onto the same structural query cache key before cache insertion",
    );
    assert_compiled_select_executes_through_shared_query_plan_for_entity::<IndexedSessionSqlEntity>(
        &session, &compiled,
    );
}

#[test]
fn searched_case_semantic_differences_do_not_alias_sql_cache_identity() {
    reset_session_sql_store();
    let session = sql_session();

    let left_sql = "SELECT CASE WHEN age >= 30 THEN name ELSE 'young' END AS age_bucket \
                    FROM SessionSqlEntity \
                    ORDER BY id ASC LIMIT 2";
    let right_sql = "SELECT CASE WHEN age >= 31 THEN name ELSE 'young' END AS age_bucket \
                     FROM SessionSqlEntity \
                     ORDER BY id ASC LIMIT 2";

    let left = session
        .compile_sql_query::<SessionSqlEntity>(left_sql)
        .expect("left searched CASE scalar projection should compile");
    let right = session
        .compile_sql_query::<SessionSqlEntity>(right_sql)
        .expect("right searched CASE scalar projection should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "searched CASE condition changes must not collapse onto one compiled-command cache entry",
    );

    assert_compiled_select_query_matches_lowered_identity(
        &left,
        left_sql,
        "left searched CASE scalar projection should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity(
        &right,
        right_sql,
        "right searched CASE scalar projection should preserve canonical lowered identity",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &left,
        &right,
        "searched CASE condition changes",
    );
    assert_distinct_compiled_selects_execute_through_shared_query_plan_for_entity::<SessionSqlEntity>(
        &session, &left, &right,
    );
}

#[test]
fn grouped_case_having_semantic_differences_do_not_alias_sql_cache_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let left_sql = "SELECT age, COUNT(*) \
                    FROM IndexedSessionSqlEntity \
                    GROUP BY age \
                    HAVING CASE WHEN COUNT(*) > 1 THEN 1 ELSE 0 END = 1 \
                    ORDER BY age ASC LIMIT 2";
    let right_sql = "SELECT age, COUNT(*) \
                     FROM IndexedSessionSqlEntity \
                     GROUP BY age \
                     HAVING CASE WHEN COUNT(*) > 2 THEN 1 ELSE 0 END = 1 \
                     ORDER BY age ASC LIMIT 2";

    let left = session
        .compile_sql_query::<IndexedSessionSqlEntity>(left_sql)
        .expect("left grouped searched CASE HAVING should compile");
    let right = session
        .compile_sql_query::<IndexedSessionSqlEntity>(right_sql)
        .expect("right grouped searched CASE HAVING should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "grouped searched CASE HAVING threshold changes must not collapse onto one compiled-command cache entry",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &left,
        left_sql,
        "left grouped searched CASE HAVING should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &right,
        right_sql,
        "right grouped searched CASE HAVING should preserve canonical lowered identity",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &left,
        &right,
        "grouped searched CASE HAVING threshold changes",
    );
    assert_distinct_compiled_selects_execute_through_shared_query_plan_for_entity::<
        IndexedSessionSqlEntity,
    >(&session, &left, &right);
}

#[test]
fn grouped_boolean_case_having_canonical_equivalence_reuses_semantic_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let case_sql = "SELECT age, COUNT(*) \
                    FROM IndexedSessionSqlEntity \
                    GROUP BY age \
                    HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE FALSE END \
                    ORDER BY age ASC LIMIT 2";
    let canonical_sql = "SELECT age, COUNT(*) \
                         FROM IndexedSessionSqlEntity \
                         GROUP BY age \
                         HAVING COALESCE(COUNT(*) > 1, FALSE) OR FALSE \
                         ORDER BY age ASC LIMIT 2";

    let case = session
        .compile_sql_query::<IndexedSessionSqlEntity>(case_sql)
        .expect("grouped boolean searched CASE HAVING should compile");
    let canonical = session
        .compile_sql_query::<IndexedSessionSqlEntity>(canonical_sql)
        .expect("canonical grouped boolean HAVING should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "different grouped HAVING SQL spellings should still occupy distinct compiled-command cache entries",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &case,
        case_sql,
        "grouped boolean searched CASE HAVING should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &canonical,
        canonical_sql,
        "canonical grouped boolean HAVING should preserve canonical lowered identity",
    );

    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: case_query, ..
    } = &case
    else {
        panic!("grouped boolean searched CASE HAVING should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: canonical_query,
        ..
    } = &canonical
    else {
        panic!("canonical grouped boolean HAVING should compile into one SELECT artifact");
    };

    assert_eq!(
        case_query.structural_cache_key(),
        canonical_query.structural_cache_key(),
        "explicit-ELSE grouped searched CASE HAVING must collapse onto the same structural cache identity as its canonical grouped boolean form",
    );
    assert_eq!(
        case_query
            .build_plan()
            .expect("grouped searched CASE plan should build")
            .fingerprint(),
        canonical_query
            .build_plan()
            .expect("canonical grouped boolean plan should build")
            .fingerprint(),
        "explicit-ELSE grouped searched CASE HAVING must share semantic plan fingerprint identity with its canonical grouped boolean form",
    );

    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&case)
        .expect("executing grouped searched CASE HAVING should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first grouped canonical-equivalent execution should populate one shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&canonical)
        .expect("executing canonical grouped boolean HAVING should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "canonical-equivalent grouped searched CASE HAVING should reuse the same shared query-plan cache entry",
    );
}

#[test]
fn grouped_boolean_case_having_truth_wrapper_reuses_semantic_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let canonical_sql = "SELECT age, COUNT(*) \
                         FROM IndexedSessionSqlEntity \
                         GROUP BY age \
                         HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE FALSE END \
                         ORDER BY age ASC LIMIT 2";
    let wrapped_sql = "SELECT age, COUNT(*) \
                       FROM IndexedSessionSqlEntity \
                       GROUP BY age \
                       HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE ELSE FALSE END \
                       ORDER BY age ASC LIMIT 2";

    let canonical = session
        .compile_sql_query::<IndexedSessionSqlEntity>(canonical_sql)
        .expect("canonical grouped boolean searched CASE HAVING should compile");
    let wrapped = session
        .compile_sql_query::<IndexedSessionSqlEntity>(wrapped_sql)
        .expect("truth-wrapped grouped boolean searched CASE HAVING should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "truth-wrapper grouped HAVING spellings should still occupy distinct compiled-command cache entries",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &canonical,
        canonical_sql,
        "canonical grouped boolean searched CASE HAVING should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &wrapped,
        wrapped_sql,
        "truth-wrapped grouped boolean searched CASE HAVING should preserve canonical lowered identity",
    );

    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: canonical_query,
        ..
    } = &canonical
    else {
        panic!(
            "canonical grouped boolean searched CASE HAVING should compile into one SELECT artifact"
        );
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: wrapped_query,
        ..
    } = &wrapped
    else {
        panic!(
            "truth-wrapped grouped boolean searched CASE HAVING should compile into one SELECT artifact"
        );
    };

    assert_eq!(
        canonical_query.structural_cache_key(),
        wrapped_query.structural_cache_key(),
        "truth-wrapper grouped searched CASE HAVING must collapse onto the same structural cache identity as the canonical grouped boolean spelling",
    );
    assert_eq!(
        canonical_query
            .build_plan()
            .expect("canonical grouped searched CASE plan should build")
            .fingerprint(),
        wrapped_query
            .build_plan()
            .expect("truth-wrapped grouped searched CASE plan should build")
            .fingerprint(),
        "truth-wrapper grouped searched CASE HAVING must share semantic plan fingerprint identity with the canonical grouped boolean spelling",
    );

    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&canonical)
        .expect("executing canonical grouped searched CASE HAVING should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first truth-wrapper grouped canonical-equivalent execution should populate one shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&wrapped)
        .expect("executing truth-wrapped grouped searched CASE HAVING should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "truth-wrapper grouped canonical-equivalent execution should reuse the same shared query-plan cache entry",
    );
}

#[expect(
    clippy::too_many_lines,
    reason = "grouped omitted-ELSE identity matrix intentionally proves one semantic boundary"
)]
#[test]
fn grouped_boolean_case_having_without_else_reuses_explicit_null_semantic_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let omitted_else_sql = "SELECT age, COUNT(*) \
                            FROM IndexedSessionSqlEntity \
                            GROUP BY age \
                            HAVING CASE WHEN COUNT(*) > 1 THEN TRUE END \
                            ORDER BY age ASC LIMIT 2";
    let explicit_null_sql = "SELECT age, COUNT(*) \
                             FROM IndexedSessionSqlEntity \
                             GROUP BY age \
                             HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE NULL END \
                             ORDER BY age ASC LIMIT 2";
    let explicit_false_sql = "SELECT age, COUNT(*) \
                              FROM IndexedSessionSqlEntity \
                              GROUP BY age \
                              HAVING COALESCE(COUNT(*) > 1, FALSE) OR FALSE \
                              ORDER BY age ASC LIMIT 2";

    let omitted_else = session
        .compile_sql_query::<IndexedSessionSqlEntity>(omitted_else_sql)
        .expect("grouped searched CASE HAVING without ELSE should compile");
    let explicit_null = session
        .compile_sql_query::<IndexedSessionSqlEntity>(explicit_null_sql)
        .expect("grouped searched CASE HAVING with explicit ELSE NULL should compile");
    let explicit_false = session
        .compile_sql_query::<IndexedSessionSqlEntity>(explicit_false_sql)
        .expect("canonical explicit-ELSE FALSE grouped boolean HAVING should compile");

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &omitted_else,
        omitted_else_sql,
        "grouped searched CASE HAVING without ELSE should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &explicit_null,
        explicit_null_sql,
        "grouped searched CASE HAVING with explicit ELSE NULL should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &explicit_false,
        explicit_false_sql,
        "canonical explicit-ELSE FALSE grouped boolean HAVING should preserve canonical lowered identity",
    );
    let SqlCommand::Query(omitted_else_lowered) =
        compile_sql_command::<IndexedSessionSqlEntity>(omitted_else_sql, MissingRowPolicy::Ignore)
            .expect("grouped searched CASE HAVING without ELSE should lower into one query")
    else {
        panic!("grouped searched CASE HAVING without ELSE should lower into one query command");
    };
    let SqlCommand::Query(explicit_null_lowered) =
        compile_sql_command::<IndexedSessionSqlEntity>(explicit_null_sql, MissingRowPolicy::Ignore)
            .expect(
                "grouped searched CASE HAVING with explicit ELSE NULL should lower into one query",
            )
    else {
        panic!(
            "grouped searched CASE HAVING with explicit ELSE NULL should lower into one query command"
        );
    };
    let SqlCommand::Query(explicit_false_lowered) = compile_sql_command::<IndexedSessionSqlEntity>(
        explicit_false_sql,
        MissingRowPolicy::Ignore,
    )
    .expect("canonical explicit-ELSE FALSE grouped boolean HAVING should lower into one query") else {
        panic!(
            "canonical explicit-ELSE FALSE grouped boolean HAVING should lower into one query command"
        );
    };

    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: omitted_else_query,
        ..
    } = &omitted_else
    else {
        panic!("grouped searched CASE HAVING without ELSE should compile into one SELECT artifact");
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: explicit_null_query,
        ..
    } = &explicit_null
    else {
        panic!(
            "grouped searched CASE HAVING with explicit ELSE NULL should compile into one SELECT artifact"
        );
    };
    assert_eq!(
        omitted_else_query.structural_cache_key(),
        explicit_null_query.structural_cache_key(),
        "grouped searched CASE HAVING without ELSE must collapse onto the same structural cache identity as the explicit ELSE NULL grouped boolean family",
    );
    assert_eq!(
        omitted_else_lowered
            .plan_hash_hex()
            .expect("grouped searched CASE HAVING without ELSE plan hash should build"),
        explicit_null_lowered
            .plan_hash_hex()
            .expect("grouped searched CASE HAVING with explicit ELSE NULL plan hash should build"),
        "grouped searched CASE HAVING without ELSE must share one outward plan hash with the explicit ELSE NULL grouped boolean family",
    );
    assert_eq!(
        omitted_else_query
            .build_plan()
            .expect("grouped searched CASE HAVING without ELSE plan should build")
            .fingerprint(),
        explicit_null_query
            .build_plan()
            .expect("grouped searched CASE HAVING with explicit ELSE NULL plan should build")
            .fingerprint(),
        "grouped searched CASE HAVING without ELSE must share semantic plan identity with the explicit ELSE NULL grouped boolean family",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &omitted_else,
        &explicit_false,
        "grouped searched CASE HAVING without ELSE versus explicit-ELSE FALSE grouped boolean form",
    );
    assert_ne!(
        omitted_else_lowered
            .plan_hash_hex()
            .expect("grouped searched CASE HAVING without ELSE plan hash should build"),
        explicit_false_lowered
            .plan_hash_hex()
            .expect("canonical explicit-ELSE FALSE grouped boolean HAVING plan hash should build"),
        "grouped searched CASE HAVING without ELSE must stay outward-hash distinct from the explicit-ELSE FALSE grouped boolean family",
    );

    let omitted_else_trace = session
        .trace_query(&omitted_else_lowered)
        .expect("grouped searched CASE HAVING without ELSE trace should build");
    let explicit_null_trace = session
        .trace_query(&explicit_null_lowered)
        .expect("grouped searched CASE HAVING with explicit ELSE NULL trace should build");
    assert_eq!(
        omitted_else_trace.plan_hash(),
        explicit_null_trace.plan_hash(),
        "grouped searched CASE HAVING without ELSE trace must share one outward plan hash with the explicit ELSE NULL grouped boolean family",
    );
    assert_eq!(
        omitted_else_trace.explain(),
        explicit_null_trace.explain(),
        "grouped searched CASE HAVING without ELSE trace explain must stay identical to the explicit ELSE NULL grouped boolean family",
    );
    assert_eq!(
        omitted_else_trace.reuse().artifact_class(),
        crate::db::TraceReuseArtifactClass::SharedPreparedQueryPlan,
        "grouped omitted-ELSE trace should surface the shared prepared query-plan reuse artifact",
    );
    assert!(
        !omitted_else_trace.reuse().is_hit(),
        "first grouped omitted-ELSE trace should miss shared prepared-plan reuse before the cache is warm",
    );
    assert!(
        explicit_null_trace.reuse().is_hit(),
        "grouped explicit ELSE NULL trace should hit shared prepared-plan reuse after the omitted-ELSE canonical equivalent warm-up",
    );

    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&omitted_else)
        .expect("executing grouped searched CASE HAVING without ELSE should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first grouped omitted-ELSE HAVING execution should populate one shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&explicit_null)
        .expect("executing grouped searched CASE HAVING with explicit ELSE NULL should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "omitted-ELSE grouped searched CASE HAVING should reuse the explicit ELSE NULL grouped boolean plan identity",
    );
    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&explicit_false)
        .expect("executing canonical explicit-ELSE FALSE grouped boolean HAVING should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        2,
        "omitted-ELSE grouped searched CASE HAVING must stay distinct from the explicit-ELSE FALSE grouped boolean family",
    );
}

#[test]
fn grouped_boolean_case_having_without_else_truth_wrapper_reuses_explicit_null_semantic_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let explicit_null_sql = "SELECT age, COUNT(*) \
                             FROM IndexedSessionSqlEntity \
                             GROUP BY age \
                             HAVING CASE WHEN COUNT(*) > 1 THEN TRUE ELSE NULL END \
                             ORDER BY age ASC LIMIT 2";
    let wrapped_omitted_else_sql = "SELECT age, COUNT(*) \
                                    FROM IndexedSessionSqlEntity \
                                    GROUP BY age \
                                    HAVING CASE WHEN (COUNT(*) > 1) = TRUE THEN TRUE END \
                                    ORDER BY age ASC LIMIT 2";

    let explicit_null = session
        .compile_sql_query::<IndexedSessionSqlEntity>(explicit_null_sql)
        .expect("grouped searched CASE HAVING with explicit ELSE NULL should compile");
    let wrapped_omitted_else = session
        .compile_sql_query::<IndexedSessionSqlEntity>(wrapped_omitted_else_sql)
        .expect("truth-wrapped grouped searched CASE HAVING without ELSE should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        2,
        "truth-wrapped omitted-ELSE and explicit ELSE NULL grouped HAVING spellings should still occupy distinct compiled-command cache entries",
    );

    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &explicit_null,
        explicit_null_sql,
        "grouped searched CASE HAVING with explicit ELSE NULL should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity_for_entity::<IndexedSessionSqlEntity>(
        &wrapped_omitted_else,
        wrapped_omitted_else_sql,
        "truth-wrapped grouped searched CASE HAVING without ELSE should preserve canonical lowered identity",
    );

    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: explicit_null_query,
        ..
    } = &explicit_null
    else {
        panic!(
            "grouped searched CASE HAVING with explicit ELSE NULL should compile into one SELECT artifact"
        );
    };
    let crate::db::session::sql::CompiledSqlCommand::Select {
        query: wrapped_omitted_else_query,
        ..
    } = &wrapped_omitted_else
    else {
        panic!(
            "truth-wrapped grouped searched CASE HAVING without ELSE should compile into one SELECT artifact"
        );
    };

    assert_eq!(
        explicit_null_query.structural_cache_key(),
        wrapped_omitted_else_query.structural_cache_key(),
        "truth-wrapped grouped searched CASE HAVING without ELSE must collapse onto the same structural cache identity as the explicit ELSE NULL grouped boolean family",
    );
    assert_eq!(
        explicit_null_query
            .build_plan()
            .expect("grouped searched CASE HAVING with explicit ELSE NULL plan should build")
            .fingerprint(),
        wrapped_omitted_else_query
            .build_plan()
            .expect("truth-wrapped grouped searched CASE HAVING without ELSE plan should build")
            .fingerprint(),
        "truth-wrapped grouped searched CASE HAVING without ELSE must share semantic plan identity with the explicit ELSE NULL grouped boolean family",
    );

    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&explicit_null)
        .expect("executing grouped searched CASE HAVING with explicit ELSE NULL should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "first truth-wrapped omitted-ELSE grouped canonical-equivalent execution should populate one shared query-plan cache entry",
    );
    let _ = session
        .execute_compiled_sql::<IndexedSessionSqlEntity>(&wrapped_omitted_else)
        .expect("executing truth-wrapped grouped searched CASE HAVING without ELSE should succeed");
    assert_eq!(
        session.query_plan_cache_len(),
        1,
        "truth-wrapped grouped searched CASE HAVING without ELSE should reuse the explicit ELSE NULL grouped boolean plan identity",
    );
}

#[test]
fn aggregate_distinct_and_order_direction_changes_do_not_alias_sql_cache_identity() {
    reset_indexed_session_sql_store();
    let session = indexed_sql_session();

    let distinct_sql = "SELECT name, AVG(DISTINCT age) AS avg_age \
                        FROM IndexedSessionSqlEntity \
                        GROUP BY name \
                        ORDER BY avg_age DESC, name ASC LIMIT 2";
    let desc_sql = "SELECT name, AVG(age) AS avg_age \
                    FROM IndexedSessionSqlEntity \
                    GROUP BY name \
                    ORDER BY avg_age DESC, name ASC LIMIT 2";
    let asc_sql = "SELECT name, AVG(age) AS avg_age \
                   FROM IndexedSessionSqlEntity \
                   GROUP BY name \
                   ORDER BY avg_age ASC, name ASC LIMIT 2";

    let distinct = session
        .compile_sql_query::<IndexedSessionSqlEntity>(distinct_sql)
        .expect("DISTINCT aggregate query should compile");
    let desc = session
        .compile_sql_query::<IndexedSessionSqlEntity>(desc_sql)
        .expect("descending aggregate ORDER BY query should compile");
    let asc = session
        .compile_sql_query::<IndexedSessionSqlEntity>(asc_sql)
        .expect("ascending aggregate ORDER BY query should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        3,
        "aggregate DISTINCT and ORDER BY direction changes must stay on distinct compiled-command cache entries",
    );

    assert_compiled_select_queries_remain_distinct_for_entity(
        &distinct,
        &desc,
        "aggregate DISTINCT changes",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &desc,
        &asc,
        "aggregate ORDER BY direction changes",
    );
    assert_distinct_compiled_selects_execute_through_shared_query_plan_for_entity::<
        IndexedSessionSqlEntity,
    >(&session, &distinct, &desc);
}

#[test]
fn aggregate_filter_semantic_differences_do_not_alias_sql_cache_identity() {
    reset_session_sql_store();
    let session = sql_session();

    let filtered_sql = "SELECT COUNT(*) FILTER (WHERE age >= 30) \
                        FROM SessionSqlEntity";
    let threshold_sql = "SELECT COUNT(*) FILTER (WHERE age >= 31) \
                         FROM SessionSqlEntity";
    let unfiltered_sql = "SELECT COUNT(*) FROM SessionSqlEntity";

    let filtered = session
        .compile_sql_query::<SessionSqlEntity>(filtered_sql)
        .expect("filtered global aggregate query should compile");
    let threshold = session
        .compile_sql_query::<SessionSqlEntity>(threshold_sql)
        .expect("threshold-varied filtered global aggregate query should compile");
    let unfiltered = session
        .compile_sql_query::<SessionSqlEntity>(unfiltered_sql)
        .expect("unfiltered global aggregate query should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        3,
        "aggregate FILTER semantic changes must stay on distinct compiled-command cache entries",
    );

    assert!(
        matches!(
            filtered,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "filtered global aggregate query should stay on the dedicated global aggregate artifact family",
    );
    assert!(
        matches!(
            threshold,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "threshold-varied filtered global aggregate query should stay on the dedicated global aggregate artifact family",
    );
    assert!(
        matches!(
            unfiltered,
            crate::db::session::sql::CompiledSqlCommand::GlobalAggregate { .. }
        ),
        "unfiltered global aggregate query should stay on the dedicated global aggregate artifact family",
    );

    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&filtered)
        .expect("filtered global aggregate query should execute after compile");
    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&threshold)
        .expect("threshold-varied filtered global aggregate query should execute after compile");
    let _ = session
        .execute_compiled_sql::<SessionSqlEntity>(&unfiltered)
        .expect("unfiltered global aggregate query should execute after compile");
}

#[test]
fn grouped_aggregate_filter_semantic_differences_do_not_alias_sql_cache_identity() {
    reset_session_sql_store();
    let session = sql_session();

    let filtered_sql = "SELECT age, COUNT(*) FILTER (WHERE age >= 20) \
                        FROM SessionSqlEntity \
                        GROUP BY age \
                        ORDER BY age ASC LIMIT 2";
    let operator_sql = "SELECT age, COUNT(*) FILTER (WHERE age > 20) \
                        FROM SessionSqlEntity \
                        GROUP BY age \
                        ORDER BY age ASC LIMIT 2";
    let unfiltered_sql = "SELECT age, COUNT(*) \
                          FROM SessionSqlEntity \
                          GROUP BY age \
                          ORDER BY age ASC LIMIT 2";

    let filtered = session
        .compile_sql_query::<SessionSqlEntity>(filtered_sql)
        .expect("filtered grouped aggregate query should compile");
    let operator = session
        .compile_sql_query::<SessionSqlEntity>(operator_sql)
        .expect("operator-varied grouped aggregate query should compile");
    let unfiltered = session
        .compile_sql_query::<SessionSqlEntity>(unfiltered_sql)
        .expect("unfiltered grouped aggregate query should compile");

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        3,
        "grouped aggregate FILTER semantic changes must stay on distinct compiled-command cache entries",
    );

    assert_compiled_select_query_matches_lowered_identity(
        &filtered,
        filtered_sql,
        "filtered grouped aggregate query should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity(
        &operator,
        operator_sql,
        "operator-varied grouped aggregate query should preserve canonical lowered identity",
    );
    assert_compiled_select_query_matches_lowered_identity(
        &unfiltered,
        unfiltered_sql,
        "unfiltered grouped aggregate query should preserve canonical lowered identity",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &filtered,
        &operator,
        "grouped aggregate FILTER operator changes",
    );
    assert_compiled_select_queries_remain_distinct_for_entity(
        &filtered,
        &unfiltered,
        "filtered versus unfiltered grouped aggregate changes",
    );
    assert_distinct_compiled_selects_execute_through_shared_query_plan_for_entity::<SessionSqlEntity>(
        &session, &filtered, &operator,
    );
}

#[test]
fn sql_compile_cache_covers_insert_update_and_delete_mutation_families() {
    reset_session_sql_store();
    let session = sql_session();

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        0,
        "new SQL session should start with an empty compiled-command cache",
    );

    let insert = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
        )
        .expect("INSERT should compile into the update-surface cache");
    assert!(
        matches!(
            insert,
            crate::db::session::sql::CompiledSqlCommand::Insert(_)
        ),
        "INSERT should cache the prepared INSERT artifact",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "first update-surface compile should populate one cache entry",
    );

    let insert_repeat = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "INSERT INTO SessionSqlWriteEntity (id, name, age) VALUES (1, 'Ada', 21)",
        )
        .expect("same INSERT should compile from the existing update-surface cache entry");
    assert!(
        matches!(
            insert_repeat,
            crate::db::session::sql::CompiledSqlCommand::Insert(_)
        ),
        "repeated INSERT should stay on the prepared INSERT artifact family",
    );
    assert_eq!(
        session.sql_compiled_command_cache_len(),
        1,
        "repeating one identical update-surface compile must not grow the cache",
    );

    let update = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "UPDATE SessionSqlWriteEntity SET age = 22 WHERE id = 1",
        )
        .expect("UPDATE should compile into the update-surface cache");
    assert!(
        matches!(
            update,
            crate::db::session::sql::CompiledSqlCommand::Update(_)
        ),
        "UPDATE should cache the prepared UPDATE artifact",
    );

    let delete = session
        .compile_sql_update::<SessionSqlWriteEntity>(
            "DELETE FROM SessionSqlWriteEntity WHERE name = 'Ada' RETURNING name",
        )
        .expect("DELETE RETURNING should compile into the update-surface cache");
    assert!(
        matches!(
            delete,
            crate::db::session::sql::CompiledSqlCommand::Delete { .. }
        ),
        "DELETE RETURNING should cache the lowered DELETE artifact",
    );

    assert_eq!(
        session.sql_compiled_command_cache_len(),
        3,
        "update-surface cache should retain distinct entries for INSERT, UPDATE, and DELETE",
    );
}