rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
//! Stage-1 candidate prefilter for imposter stub matching (issues #292, #707).
//!
//! The imposter match loop (`core/matching.rs`) would otherwise be a linear scan running full
//! Mountebank predicate evaluation on every stub. This index narrows that to a candidate set, so
//! only stubs that *could* match are evaluated.
//!
//! # The dimension framework (issue #707)
//!
//! The index is a set of independent **dimensions**, one per request attribute (path, method, path
//! literals (#710), path regexes (#709), and — via the sibling issue built on this seam — deepEquals
//! bodies (#708)). Each dimension answers one question for a request: *which stubs can this
//! attribute not rule out?* The answers are [`CandidateBits`] — dense bitsets over stub ids, where
//! a stub's id is its position in the snapshot's stub vector (declaration-ordered).
//!
//! [`StubIndex::candidates`] ANDs the per-dimension bitsets and walks the surviving bits ascending.
//! This is the Lucent Bit Vector technique from packet classification: each dimension prunes
//! independently, and the intersection is the candidate set. Ascending iteration *is* Mountebank's
//! first-match-wins order, so Stage-2 evaluation order is unchanged.
//!
//! ## The soundness rule — the one invariant every dimension must uphold
//!
//! A dimension's bitset for a request is `matched_bits | always_bits`, where:
//!
//! * `matched_bits` — stubs whose constraint on this attribute the request *satisfies*;
//! * `always_bits` — stubs that either do not constrain this attribute at all, or constrain it in
//!   a shape this dimension cannot index (precomputed once at build).
//!
//! **A dimension may only ever exclude a stub it can prove cannot match.** Everything else must be
//! in `always_bits`. The index is therefore a strict *over-approximation*: `candidates()` returns a
//! superset of the true matches, and full predicate verification (`stub_matches`, unchanged) stays
//! the single source of truth for semantics — including `and`/`or`/`not`, `except`, selectors,
//! case flags, and `inject`. Widening a dimension's eligibility later is a pure optimization, never
//! a semantics question.
//!
//! Eligibility is deliberately conservative and uniform across dimensions: a stub is indexed only
//! when a *top-level* (implicitly AND-ed) predicate constrains the raw field — no `selector`, no
//! `except` ([`is_value_preserving`]). Such a predicate is *required* for the stub to match, so a
//! request failing it can never match the stub → safe to exclude. The dimensions that compare
//! strings themselves additionally require not-`caseSensitive` ([`is_safely_indexable`]), because
//! they fold both sides eagerly at build; the regex dimension instead routes the case flag to one
//! of two automata, which is why the two gates are separate.
//!
//! ## Adding a dimension
//!
//! Implement [`Dimension`], add it as a field of [`StubIndex`], build its `always_bits` from the
//! stubs it cannot index, and AND it in [`StubIndex::candidates`]. Dimensions are concrete fields
//! rather than `Box<dyn Dimension>` so the match loop dispatches statically and allocates nothing
//! extra. The guardrail is `differential_index_matches_linear_oracle` below: a dimension that
//! under-approximates fails it immediately.

use super::StubState;
use super::bitset::CandidateBits;
use crate::imposter::predicates::json::{leaf_text, structural_hash};
use crate::imposter::types::Stub;
use crate::util::FastMap;
use aho_corasick::{AhoCorasick, MatchKind as AcMatchKind};
use regex_automata::util::syntax;
use regex_automata::{Input, MatchKind, PatternSet, meta};
use rift_types::predicate::{Predicate, PredicateOperation};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;

/// The request attributes the index prunes on. Extended as sibling dimensions land.
pub(crate) struct DimensionRequest<'a> {
    pub(crate) method: &'a str,
    pub(crate) path: &'a str,
    /// The request body, parsed as JSON on first use (#290, #1442). Only the body dimensions read
    /// it, and only when they prune, so a request no body-keyed stub can match is never parsed.
    /// Not JSON or absent reads as `None` — the body dimension (#708) prunes JSON bodies only.
    pub(crate) body: &'a crate::behaviors::LazyJson<'a>,
}

/// One pruning dimension of the index. See the module docs for the soundness rule this contract
/// requires: `select` must set a bit for **every** stub the request cannot rule out.
trait Dimension {
    /// Write `matched_bits | always_bits` for `request` into `out`, overwriting it entirely.
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits);

    /// Whether any stub is indexed on this dimension at all.
    ///
    /// When none is, `always_bits` is all-ones, so `select` can only ever produce all-ones and
    /// intersecting it is a no-op — [`StubIndex::candidates`] skips the dimension entirely rather
    /// than pay a full-width copy and intersect to learn nothing. Constant per snapshot.
    fn prunes(&self) -> bool;
}

/// A required path constraint extracted from a stub's top-level predicates.
///
/// `startsWith`/`contains`/`endsWith` moved off this enum in #710 — they are now the literal
/// dimension's `LiteralAnchor`, indexed by Aho-Corasick instead of a per-anchor bucket walk. Only
/// `equals` remains here.
enum PathAnchor {
    Exact(String),
}

/// The `path` value of a predicate's field map, folded for indexing, if present and a string.
fn field_path(fields: &HashMap<String, serde_json::Value>) -> Option<String> {
    match fields.get("path") {
        Some(serde_json::Value::String(s)) => Some(fold(s)),
        _ => None,
    }
}

/// The case fold the index compares under.
///
/// This MUST be the evaluator's fold, not merely *a* fold. The default (non-`caseSensitive`)
/// comparison in `predicates::mod` is `eq_ignore_ascii_case` / `starts_with_ignore_ascii_case` /
/// `contains_ignore_ascii_case` — **ASCII**. Folding both sides with `to_ascii_lowercase` is
/// exactly equivalent to those, so the path dimension neither over- nor under-approximates.
///
/// Unicode `to_lowercase` would be wrong here, and not merely conservative: it is length-changing
/// and context-sensitive, so it breaks the prefix/substring relation the dimension relies on. Stub
/// `startsWith "/ΟΣ"` vs request `/ΟΣΑ` is the counter-example — the evaluator matches (its ASCII
/// fold leaves Greek untouched), but Unicode-lowercasing the anchor yields a final sigma (`/ος`)
/// that `"/οσα"` does not start with, so the stub would be pruned and silently stop matching.
fn fold(s: &str) -> String {
    s.to_ascii_lowercase()
}

/// Whether a predicate compares its field values against the **raw** request value — the soundness
/// gate every dimension's eligibility rule shares.
///
/// Anything that transforms or re-scopes the compared value cannot be indexed against the raw
/// field: `except` rewrites the value before comparison and `selector` re-scopes it. One home for
/// the rule, because the dimensions added on this seam (#708-#710) must not let their copies of it
/// drift.
fn is_value_preserving(p: &rift_types::predicate::PredicateParameters) -> bool {
    p.except.is_empty() && p.selector.is_none()
}

/// [`is_value_preserving`] plus the fold requirement, for the dimensions that compare *strings*
/// themselves.
///
/// `caseSensitive` opts out of the fold [`fold`] assumes, and the path/method dimensions have no
/// way to represent a case-sensitive compare — they fold both sides eagerly at build. The regex
/// dimension does not share that limitation (the automaton carries its own case flag), so it gates
/// on [`is_value_preserving`] and routes on the flag instead.
fn is_safely_indexable(p: &rift_types::predicate::PredicateParameters) -> bool {
    is_value_preserving(p) && p.case_sensitive != Some(true)
}

/// A single predicate's path anchor, if it is a safely-indexable required `equals` path
/// constraint. `startsWith`/`contains`/`endsWith` are the literal dimension's concern (#710).
fn path_anchor(pred: &Predicate) -> Option<PathAnchor> {
    if !is_safely_indexable(&pred.parameters) {
        return None;
    }
    match &pred.operation {
        PredicateOperation::Equals(fields) => field_path(fields).map(PathAnchor::Exact),
        _ => None,
    }
}

/// The first required path anchor among a stub's top-level (AND-ed) predicates, or `None` if the
/// stub can't be safely path-indexed (→ `always_bits`).
fn classify(stub: &Stub) -> Option<PathAnchor> {
    stub.predicates.iter().find_map(path_anchor)
}

/// The exact-path dimension (issue #292, ported onto the #707 bitset framework).
///
/// Handles only `equals` on `path` — an O(1) hashmap lookup per request. `startsWith`/`contains`/
/// `endsWith` used to be linear-walked buckets on this same type; #710 supersedes both walks with
/// the literal dimension's Aho-Corasick pass, so this type shrinks to just the exact bucket. A
/// stub can be indexed on both: an `equals` anchor here and a `startsWith` anchor on the literal
/// dimension are independent required constraints, and both are allowed to prune.
///
/// The bucket stays `Vec<usize>` rather than a bitset: a bucket holds only the stubs sharing an
/// anchor, so materializing it costs O(matched) rather than O(stubs/64), and build memory stays
/// O(stubs) instead of O(stubs x buckets).
struct PathDimension {
    // Rebuilt on every stub-set replace/mutation (issue #704); its keys come from operator stub
    // config, not request traffic — see `crate::util::fastmap` doc for the HashDoS policy.
    exact: FastMap<String, Vec<usize>>,
    /// Stubs with no indexable top-level `equals` path constraint — always candidates on this
    /// dimension.
    always: CandidateBits,
}

impl Dimension for PathDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        out.copy_from(&self.always);
        // Anchors were folded at build; fold the request the same way — see `fold`. Request paths
        // are overwhelmingly already lowercase, so probe the map with the borrowed `&str` directly
        // and pay for the folded `String` only when an uppercase ASCII byte is actually present
        // (issue #731 — the fold's only effect is ASCII case, so a path with no uppercase byte
        // folds to itself).
        let matched = if request.path.bytes().any(|b| b.is_ascii_uppercase()) {
            self.exact.get(&fold(request.path))
        } else {
            self.exact.get(request.path)
        };
        if let Some(v) = matched {
            v.iter().for_each(|i| out.set(*i));
        }
    }

    fn prunes(&self) -> bool {
        !self.exact.is_empty()
    }
}

/// The fixed method slots. Any method outside the standard set (or a stub constraining an
/// unusual one) shares `Other` — a coarser bucket is still sound, it just prunes less.
const METHOD_SLOTS: usize = 8;
const SLOT_OTHER: usize = METHOD_SLOTS - 1;

/// The slot a method name belongs to, matched case-insensitively and without allocating.
fn method_slot(method: &str) -> usize {
    const NAMED: [&str; SLOT_OTHER] = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
    NAMED
        .iter()
        .position(|m| method.eq_ignore_ascii_case(m))
        .unwrap_or(SLOT_OTHER)
}

/// The method required by a single predicate, if it is a safely-indexable required constraint.
fn method_anchor(pred: &Predicate) -> Option<&str> {
    if !is_safely_indexable(&pred.parameters) {
        return None;
    }
    match &pred.operation {
        PredicateOperation::Equals(fields) => match fields.get("method") {
            Some(serde_json::Value::String(s)) => Some(s.as_str()),
            _ => None,
        },
        _ => None,
    }
}

/// The method dimension (issue #707) — the cheapest possible dimension, and the proof of the
/// framework: a POST-only stub stops being a candidate for every GET.
struct MethodDimension {
    slots: [Vec<usize>; METHOD_SLOTS],
    /// Stubs with no indexable top-level method constraint — always candidates on this dimension.
    always: CandidateBits,
}

impl Dimension for MethodDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        out.copy_from(&self.always);
        self.slots[method_slot(request.method)]
            .iter()
            .for_each(|i| out.set(*i));
    }

    fn prunes(&self) -> bool {
        self.slots.iter().any(|s| !s.is_empty())
    }
}

/// Which relation a literal anchor requires between the pattern and the path.
///
/// `Copy` because [`LiteralSet::mark`] reads one out of `entries` through `&self` on every match —
/// see the field doc there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LiteralKind {
    Contains,
    StartsWith,
    EndsWith,
}

/// One case class's Aho-Corasick automaton, plus the (stub, relation) each pattern id speaks for.
struct LiteralSet {
    ac: AhoCorasick,
    /// Indexed by pattern id — 1:1 with the patterns handed to `AhoCorasick::build`, so identical
    /// literals from two stubs get two ids, not one (mirrors [`MultiRegex::pattern_stubs`]).
    entries: Vec<(usize, LiteralKind)>,
}

impl LiteralSet {
    /// Set a bit for every stub whose literal anchor holds against `path`, in one overlapping pass
    /// over the haystack.
    ///
    /// `startsWith`/`endsWith` are not separate automata: a hit's *position* proves which relation
    /// holds, since `find_overlapping_iter` already reports the match span. `contains` needs no
    /// further check — the substring itself is the constraint.
    fn mark(&self, path: &str, out: &mut CandidateBits) {
        for m in self.ac.find_overlapping_iter(path) {
            let (stub, kind) = self.entries[m.pattern().as_usize()];
            let hit = match kind {
                LiteralKind::Contains => true,
                LiteralKind::StartsWith => m.start() == 0,
                LiteralKind::EndsWith => m.end() == path.len(),
            };
            if hit {
                out.set(stub);
            }
        }
    }
}

/// Build one case class's automaton, falling back that class's stubs wholesale on failure.
///
/// Unlike the regex dimension's per-pattern retry ([`build_case_class`]), a literal string cannot
/// be individually invalid the way a regex can — there is no analogue of "this one pattern is a
/// typo". A build failure here is only ever aho-corasick's own construction limits being overrun
/// in aggregate, so there is nothing to retry pattern-by-pattern: every entry in this case class
/// falls back to `always_bits`, which over-approximates it safely (Stage 2 still evaluates it).
fn build_literal_class(
    entries: Vec<(usize, String, LiteralKind)>,
    case_insensitive: bool,
) -> (Option<LiteralSet>, Vec<usize>) {
    if entries.is_empty() {
        return (None, Vec::new());
    }
    let patterns: Vec<&str> = entries.iter().map(|(_, p, _)| p.as_str()).collect();
    match AhoCorasick::builder()
        .match_kind(AcMatchKind::Standard)
        .ascii_case_insensitive(case_insensitive)
        .build(&patterns)
    {
        Ok(ac) => {
            let entries = entries
                .into_iter()
                .map(|(stub, _, kind)| (stub, kind))
                .collect();
            (Some(LiteralSet { ac, entries }), Vec::new())
        }
        Err(e) => {
            tracing::warn!(
                stubs = entries.len(),
                case_insensitive,
                error = %e,
                "literal dimension: multi-pattern build failed for the whole set; all its stubs \
                 fall back to full predicate evaluation"
            );
            (None, entries.into_iter().map(|(stub, _, _)| stub).collect())
        }
    }
}

/// A stub's required literal-path constraint: the text, the relation it requires, and which case
/// class it belongs to.
struct LiteralAnchor<'a> {
    text: &'a str,
    kind: LiteralKind,
    case_sensitive: bool,
}

/// A single predicate's literal anchor, if it is an indexable required constraint.
///
/// Deliberately narrower than the evaluator, same rationale as [`regex_anchor`]: only a **string**
/// literal qualifies. A non-string value is still a real constraint (the evaluator renders it via
/// `to_string`) — just not one worth the eligibility bookkeeping — so it falls to `always_bits`,
/// which over-approximates it safely.
fn literal_anchor(pred: &Predicate) -> Option<LiteralAnchor<'_>> {
    if !is_value_preserving(&pred.parameters) {
        return None;
    }
    let (fields, kind) = match &pred.operation {
        PredicateOperation::Contains(fields) => (fields, LiteralKind::Contains),
        PredicateOperation::StartsWith(fields) => (fields, LiteralKind::StartsWith),
        PredicateOperation::EndsWith(fields) => (fields, LiteralKind::EndsWith),
        _ => return None,
    };
    match fields.get("path") {
        Some(serde_json::Value::String(text)) => Some(LiteralAnchor {
            text,
            kind,
            case_sensitive: pred.parameters.case_sensitive == Some(true),
        }),
        _ => None,
    }
}

/// The literal dimension (issue #710) — supersedes the path dimension's old prefix/contains
/// linear-bucket walks, and additionally indexes `endsWith`, which was never indexed before it.
///
/// # One automaton per case class, not one per (case class, relation)
///
/// A stub is eligible on `contains`/`startsWith`/`endsWith`, and case-sensitive/insensitive, which
/// suggests up to six automata. This type builds only two — one per case class — because which
/// relation a hit proves is a property of *where* it landed, not of which automaton found it:
/// `find_overlapping_iter` already reports the match span, so [`LiteralSet::mark`] resolves
/// `startsWith` as `m.start() == 0` and `endsWith` as `m.end() == path.len()` after the fact, with
/// `contains` needing no further check. One overlapping pass per case class answers all three.
///
/// # Why `MatchKind::Standard` + `find_overlapping_iter`, not a single-winner search
///
/// A non-overlapping search, or a search under `LeftmostFirst`/`LeftmostLongest`, reports only the
/// winning pattern at a position and moves on — so of two literals that both match the same path
/// (e.g. `startsWith "/api"` and `startsWith "/api/v1"` against `/api/v1/x`), only one would be
/// reported and the other's stub would silently drop out of the candidate set: an
/// under-approximation, i.e. a silent no-match in production. This is exactly the bug class #709's
/// regex dimension guards against with `MatchKind::All`; `overlapping_literals_are_all_candidates`
/// below is its regression test here. `find_overlapping_iter` requires `MatchKind::Standard` (the
/// non-overlapping, single-winner kinds cannot drive it at all) — it is the only combination that
/// is a sound, all-reporting search.
///
/// # Case semantics — an exact mirror, not merely an over-approximation
///
/// `predicates/mod.rs:255-277` dispatches `case_sensitive` to either an exact-byte compare or to
/// `contains_ignore_ascii_case`/`starts_with_ignore_ascii_case`/`ends_with_ignore_ascii_case`
/// (`mod.rs:123-142`) — all of which are byte-level ASCII folds (`eq_ignore_ascii_case`), not
/// Unicode. `AhoCorasick::ascii_case_insensitive(true)` is that exact same byte-level ASCII fold,
/// so the CI automaton matches the evaluator's default precisely and the CS automaton (flag off)
/// matches its exact-byte compare precisely — neither over- nor under-approximates. This is
/// UNLIKE the sibling regex dimension, whose `matches` predicate folds with *Unicode*
/// case-insensitivity ([`RegexDimension`]'s doc); do not carry that automaton-per-flag reasoning
/// over here without re-checking which fold the predicate in question actually uses.
struct LiteralDimension {
    /// The default class: `ascii_case_insensitive(true)`, matching the evaluator's default fold.
    insensitive: Option<LiteralSet>,
    /// `caseSensitive: true`, matching the evaluator's exact-byte compare.
    sensitive: Option<LiteralSet>,
    /// Stubs with no indexable top-level literal constraint, an empty-string literal (an
    /// unconditional pass in the evaluator — see `empty_literal_always_matches`), or whose case
    /// class's automaton build failed — always candidates on this dimension.
    always: CandidateBits,
}

impl Dimension for LiteralDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        out.copy_from(&self.always);
        for s in [&self.insensitive, &self.sensitive].into_iter().flatten() {
            s.mark(request.path, out);
        }
    }

    fn prunes(&self) -> bool {
        self.insensitive.is_some() || self.sensitive.is_some()
    }
}

/// Ceiling on the NFA a single multi-pattern build may occupy. Matches the `regex` crate's own
/// default `size_limit`, so a pattern set this rejects is one whose patterns the evaluator would
/// have struggled to compile individually anyway — and rejection is only ever a fall back to
/// `always_bits`, never an error.
const NFA_SIZE_LIMIT: usize = 10 * (1 << 20);

/// Lazy-DFA budgets, raised well above the defaults on purpose.
///
/// These do not gate whether a build *succeeds* — they decide which engine the meta regex picks at
/// search time. A multi-pattern set that overruns them silently degrades to the PikeVM
/// (rust-lang/regex#881), which is the slow path this dimension exists to avoid; the whole point is
/// one prefiltered automaton pass, so buy the cache rather than the fallback.
const DFA_SIZE_LIMIT: usize = 32 * (1 << 20);
const HYBRID_CACHE_CAPACITY: usize = 16 * (1 << 20);

/// One multi-pattern automaton plus the stub each pattern id speaks for.
struct MultiRegex {
    re: meta::Regex,
    /// Indexed by pattern id. One entry per pattern handed to `build_many`, so this is 1:1 with
    /// the automaton's pattern ids — identical patterns from two stubs get two ids, not one.
    pattern_stubs: Vec<usize>,
}

thread_local! {
    /// Scratch [`PatternSet`] for [`MultiRegex::mark`]. regex-automata recommends reusing a
    /// `PatternSet` across searches (clearing between calls) rather than allocating one per call.
    /// `StubSnapshot`/dimensions are `Arc`-shared and read concurrently, so the reuse buffer must
    /// be per-thread. Matching runs synchronously in both of its homes (inline on a tokio worker,
    /// or on a `spawn_blocking` thread for inject/scenario snapshots) and never holds this borrow
    /// across an `.await`, so the scoped borrow is sound in both (issue #731).
    static PATTERN_SCRATCH: RefCell<PatternSet> = RefCell::new(PatternSet::new(0));
}

impl MultiRegex {
    /// Set a bit for every stub whose pattern matches `path`, in one pass over the haystack.
    fn mark(&self, path: &str, out: &mut CandidateBits) {
        PATTERN_SCRATCH.with_borrow_mut(|set| {
            // `which_overlapping_matches` needs a `PatternSet` sized for this automaton. Grow the
            // reused buffer only when this automaton has more patterns than any seen before on
            // this thread; otherwise `clear` it — a larger capacity is fine, `iter` yields only
            // the pids actually inserted by this search.
            let needed = self.re.pattern_len();
            if set.capacity() < needed {
                *set = PatternSet::new(needed);
            } else {
                set.clear();
            }
            self.re.which_overlapping_matches(&Input::new(path), set);
            for pid in set.iter() {
                out.set(self.pattern_stubs[pid.as_usize()]);
            }
        });
    }
}

/// Build one automaton over `patterns`. `case_insensitive` is the *default* for the set; inline
/// flags in a pattern still override it, exactly as they do for the evaluator's `RegexBuilder`.
fn build_multi_regex(
    patterns: &[&str],
    case_insensitive: bool,
) -> Result<meta::Regex, Box<meta::BuildError>> {
    meta::Regex::builder()
        .syntax(syntax::Config::new().case_insensitive(case_insensitive))
        .configure(
            meta::Config::new()
                // Load-bearing, and the whole reason this dimension is equivalent to per-pattern
                // `is_match`. `which_overlapping_matches` reports *every* matching pattern only
                // under `MatchKind::All`; under the default (`LeftmostFirst`) it reports the
                // leftmost-first winner and stops, so of two patterns that both match a path only
                // one would be reported and the other's stub would be dropped from the candidate
                // set — an under-approximation, i.e. a silent no-match in production.
                .match_kind(MatchKind::All)
                .nfa_size_limit(Some(NFA_SIZE_LIMIT))
                .dfa_size_limit(Some(DFA_SIZE_LIMIT))
                .hybrid_cache_capacity(HYBRID_CACHE_CAPACITY),
        )
        .build_many(patterns)
        .map_err(Box::new)
}

/// A log-safe rendering of an operator-supplied pattern.
///
/// A rejected pattern is frequently rejected *because* it is enormous, so cap what reaches the log
/// line — and cut on a char boundary, since patterns may be non-ASCII.
fn pattern_preview(p: &str) -> String {
    const MAX: usize = 80;
    if p.len() <= MAX {
        return p.to_owned();
    }
    let cut = (0..=MAX)
        .rev()
        .find(|i| p.is_char_boundary(*i))
        .unwrap_or(0);
    format!("{}… ({} bytes total)", &p[..cut], p.len())
}

/// Assemble the automaton for one case class, returning the stubs that must fall back to
/// `always_bits` because no automaton can speak for them.
///
/// `build_many` fails the *whole set* on the first pattern it rejects, so one typo'd or oversized
/// pattern would otherwise cost every other regex stub its pruning. The happy path pays nothing for
/// that: only on failure do we re-validate pattern-by-pattern, drop the offenders, and rebuild.
///
/// Falling back is always sound in the direction that matters: `always_bits` over-approximates, so
/// the stub simply keeps the pre-#709 behaviour of being fully evaluated by Stage 2. (Note the
/// rejected set is what *this* multi-pattern build rejects, which is not necessarily what the
/// evaluator's own `Regex::new` would reject — the soundness argument rests on
/// over-approximation, not on parity with the evaluator.)
fn build_case_class(
    entries: Vec<(usize, String)>,
    case_insensitive: bool,
) -> (Option<MultiRegex>, Vec<usize>) {
    let assemble = |entries: &[(usize, String)]| -> Option<MultiRegex> {
        if entries.is_empty() {
            return None;
        }
        let patterns: Vec<&str> = entries.iter().map(|(_, p)| p.as_str()).collect();
        let re = build_multi_regex(&patterns, case_insensitive).ok()?;
        Some(MultiRegex {
            re,
            pattern_stubs: entries.iter().map(|(stub, _)| *stub).collect(),
        })
    };

    if entries.is_empty() {
        return (None, Vec::new());
    }
    if let Some(m) = assemble(&entries) {
        return (Some(m), Vec::new());
    }

    // Something in the set is unbuildable. Find it by pattern, so its neighbours keep their
    // pruning and the operator learns which stub lost its index and why.
    let mut ok: Vec<(usize, String)> = Vec::new();
    let mut fallback: Vec<usize> = Vec::new();
    for (stub, pattern) in entries {
        match build_multi_regex(&[pattern.as_str()], case_insensitive) {
            Ok(_) => ok.push((stub, pattern)),
            Err(e) => {
                tracing::warn!(
                    stub,
                    pattern = %pattern_preview(&pattern),
                    case_insensitive,
                    error = %e,
                    "regex dimension: pattern rejected by the multi-pattern build; this stub falls \
                     back to full predicate evaluation"
                );
                fallback.push(stub);
            }
        }
    }

    // With every individually-bad pattern removed, retry. If none was individually bad, the set
    // only overruns the limits in aggregate and rebuilding the same patterns would fail again.
    if !fallback.is_empty()
        && let Some(m) = assemble(&ok)
    {
        return (Some(m), fallback);
    }

    tracing::warn!(
        stubs = ok.len(),
        case_insensitive,
        "regex dimension: multi-pattern build failed for the whole set (aggregate size); all its \
         stubs fall back to full predicate evaluation"
    );
    fallback.extend(ok.into_iter().map(|(stub, _)| stub));
    (None, fallback)
}

/// A stub's required path-regex constraint: the pattern, and which case class it belongs to.
struct RegexAnchor<'a> {
    pattern: &'a str,
    case_sensitive: bool,
}

/// A single predicate's path-regex anchor, if it is an indexable required constraint.
///
/// Deliberately narrower than the evaluator: only a **string** pattern qualifies. The evaluator
/// renders a non-string value with `to_string` and matches that (`fields.rs`), so such a predicate
/// is still a real constraint — just not one worth the eligibility bookkeeping. It falls to
/// `always_bits`, which over-approximates it safely.
fn regex_anchor(pred: &Predicate) -> Option<RegexAnchor<'_>> {
    if !is_value_preserving(&pred.parameters) {
        return None;
    }
    let PredicateOperation::Matches(fields) = &pred.operation else {
        return None;
    };
    match fields.get("path") {
        Some(serde_json::Value::String(pattern)) => Some(RegexAnchor {
            pattern,
            case_sensitive: pred.parameters.case_sensitive == Some(true),
        }),
        _ => None,
    }
}

/// The regex dimension (issue #709).
///
/// Answers "which of these N path patterns match?" in a single pass per case class, rather than the
/// N independent `is_match` calls Stage 2 would otherwise run — the meta engine extracts the
/// patterns' required literals and prefilters with memchr/Teddy, so most requests never enter an
/// automaton state.
///
/// # Why two automata
///
/// `matches` does **not** fold like the string operators, and this is the one thing to get right
/// here. `fields.rs` builds its regex as `cached_regex(pattern, !case_sensitive)`, so the default
/// (no `caseSensitive`) is `RegexBuilder::case_insensitive(true)` — the regex crate's *Unicode*
/// fold, not the ASCII `eq_ignore_ascii_case` that [`fold`] above mirrors. The case flag is a
/// per-automaton syntax config, not something that can be folded into a pattern string, so the two
/// classes get one automaton each. Inline flags (`(?i)`/`(?-i)`) override the automaton default
/// per pattern exactly as they override `RegexBuilder`'s, so they need no special handling.
struct RegexDimension {
    /// The default class: `case_insensitive(true)`, matching `cached_regex(p, true)`.
    insensitive: Option<MultiRegex>,
    /// `caseSensitive: true`, matching `cached_regex(p, false)`.
    sensitive: Option<MultiRegex>,
    /// Stubs with no indexable top-level path-regex constraint, plus any whose pattern no
    /// automaton could take — always candidates on this dimension.
    always: CandidateBits,
}

impl Dimension for RegexDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        out.copy_from(&self.always);
        for m in [&self.insensitive, &self.sensitive].into_iter().flatten() {
            m.mark(request.path, out);
        }
    }

    fn prunes(&self) -> bool {
        self.insensitive.is_some() || self.sensitive.is_some()
    }
}

/// The structural hash of a stub predicate's eligible `deepEquals`-on-`body` constraint (#708).
///
/// Eligible (conservative first cut): a top-level `deepEquals` whose `body` field is an object or
/// array (a scalar `body` compares against the raw request string, not the parse — `fields.rs`),
/// that is safely indexable ([`is_safely_indexable`]: no `except`, no selector, not
/// `caseSensitive: true`) and not `keyCaseSensitive: true`, and whose expected body has no JSON-ish
/// string leaf ([`structural_hash`] → `Some`). Anything else → `None` → `always_bits`.
///
/// Other fields on the same `deepEquals`, and the stub's other predicates, are further required
/// constraints; ignoring them here only over-approximates (Stage-2 still checks them), exactly as
/// the path/regex/literal classifiers index only their first anchor.
fn body_anchor(pred: &Predicate) -> Option<u64> {
    if !is_safely_indexable(&pred.parameters) || pred.parameters.key_case_sensitive == Some(true) {
        return None;
    }
    let PredicateOperation::DeepEquals(fields) = &pred.operation else {
        return None;
    };
    match fields.get("body") {
        Some(v @ (serde_json::Value::Object(_) | serde_json::Value::Array(_))) => {
            structural_hash(v)
        }
        _ => None,
    }
}

/// The deepEquals-body dimension (issue #708): collapses "which of N `deepEquals`-on-body stubs
/// equals this request body" from O(stubs × body) structural comparisons into one hash probe.
struct BodyHashDimension {
    /// `structural_hash(expected body)` → the stubs sharing it. A `Vec` bucket (not a bitset) like
    /// [`PathDimension`], since it holds only the stubs at one hash. Keyed by our own `FixedState`-
    /// derived `u64`, so the request-scoped `FastMap` hasher just re-hashes an already-good `u64`.
    by_hash: FastMap<u64, Vec<usize>>,
    /// Stubs with no eligible `deepEquals` body anchor — always candidates on this dimension.
    always: CandidateBits,
    len: usize,
}

impl Dimension for BodyHashDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        match request.body.get() {
            // A non-JSON (or absent) body can never `deepEquals` an object/array expected body, so
            // every indexed stub is soundly excluded — only `always` stubs survive.
            None => out.copy_from(&self.always),
            Some(body) => match structural_hash(body) {
                // A JSON-ish string leaf in the request body is equivalent (both directions) to a
                // container an indexed stub may expect, which no structural hash can reconcile — so
                // this dimension must not prune this request. Widen to all; Stage-2 decides.
                None => out.copy_from(&CandidateBits::all(self.len)),
                Some(h) => {
                    out.copy_from(&self.always);
                    if let Some(ids) = self.by_hash.get(&h) {
                        ids.iter().for_each(|i| out.set(*i));
                    }
                }
            },
        }
    }

    fn prunes(&self) -> bool {
        !self.by_hash.is_empty()
    }
}

/// The multi-dimensional candidate prefilter over a stub snapshot. See the module docs.
/// Fold a scalar JSON leaf to the exact string the default `equals` comparator compares on:
/// [`leaf_text`] (number→its JS spelling, bool→`"true"`/`"false"`, null→`"null"`, string→raw) then
/// ASCII-lowercase (the comparator's `eq_ignore_ascii_case`). A null value matches only a null
/// expectation, which is never indexed, so its text here only ever over-approximates. This is the crux of soundness: the
/// comparator **string-coerces** leaves — `5` ≡ `"5"`, `true` ≡ `"true"` — so a *type-matching*
/// automaton would under-approximate (drop stubs Stage-2 matches). Applying this same stringify to
/// **both** the pattern and the event makes quamina match the comparator's canonical form, never
/// the JSON type. It is exactly the leaf normalization [`structural_hash`] uses for #708.
fn folded_leaf_string(v: &serde_json::Value) -> String {
    leaf_text(v).to_ascii_lowercase()
}

/// Normalize a request body for the automaton: recurse containers (lowercasing object keys), and
/// replace **every scalar leaf** with its [`folded_leaf_string`], so the event carries the same
/// stringified-and-folded values the `equals` comparator compares on (issue #767). Called only
/// after [`structural_hash`] has confirmed the body has no JSON-ish string leaf (which no purely
/// structural matcher can reconcile — the request side widens to all in that case).
#[cfg(feature = "quamina-matching")]
fn normalize_json_value(v: &serde_json::Value) -> serde_json::Value {
    use serde_json::Value;
    match v {
        Value::Object(map) => Value::Object(
            map.iter()
                .map(|(k, val)| (k.to_ascii_lowercase(), normalize_json_value(val)))
                .collect(),
        ),
        Value::Array(items) => Value::Array(items.iter().map(normalize_json_value).collect()),
        scalar => Value::String(folded_leaf_string(scalar)),
    }
}

/// Translate one expected `body` sub-tree into a quamina exact-match pattern value: each scalar
/// leaf becomes `[folded_leaf_string(leaf)]` (a one-element array of the comparator's folded string
/// form), object keys lowercased. Returns `None` if any leaf is ineligible, so the whole stub falls
/// back to `always_bits` (issue #767):
///
/// * **arrays** — MB `equals` on an array is ordered whole-array equality; a quamina array pattern
///   is OR-over-values. Different semantics ⇒ ineligible.
/// * **null** — excluded in v1 (`null` vs absent field is subtle; conservative fallback is sound).
/// * **the empty string** — a missing field reads `""` (`testPredicate`, issue #1579), so `{"a": ""}`
///   matches a body without `a`, or one that is not JSON, which no field pattern can express.
///
/// Numbers (any) and bools are fine because they are stringified, not type-matched — the same
/// reason [`structural_hash`] handles them. JSON-ish string leaves are rejected earlier by the
/// `structural_hash(body).is_some()` gate in [`body_field_pattern`].
fn to_quamina_pattern_value(v: &serde_json::Value) -> Option<serde_json::Value> {
    use serde_json::Value;
    match v {
        Value::String(s) if s.is_empty() => None,
        Value::String(_) | Value::Bool(_) | Value::Number(_) => {
            Some(Value::Array(vec![Value::String(folded_leaf_string(v))]))
        }
        Value::Object(map) => {
            let mut out = serde_json::Map::with_capacity(map.len());
            for (k, val) in map {
                out.insert(k.to_ascii_lowercase(), to_quamina_pattern_value(val)?);
            }
            Some(Value::Object(out))
        }
        // Array, Null, "" → ineligible.
        _ => None,
    }
}

/// A single predicate's body-field pattern for the quamina dimension (issue #767), if it is a
/// safely-indexable required `equals` whose `body` field is an object with only exact-matchable
/// leaves. Mirrors [`body_anchor`]'s eligibility (default flags — no `except`/`selector`, not
/// `caseSensitive`/`keyCaseSensitive`), but on `Equals` (field-level subset) rather than
/// `DeepEquals` (whole-body exactness, which stays #708's hash dimension). Only the first eligible
/// predicate is indexed; the stub's other constraints stay required and are checked by Stage-2.
fn body_field_pattern(pred: &Predicate) -> Option<String> {
    if !is_safely_indexable(&pred.parameters) || pred.parameters.key_case_sensitive == Some(true) {
        return None;
    }
    let PredicateOperation::Equals(fields) = &pred.operation else {
        return None;
    };
    let body = match fields.get("body") {
        Some(v @ serde_json::Value::Object(map)) if !map.is_empty() => v,
        _ => return None, // scalar/array/absent/empty body ⇒ not this dimension
    };
    // A JSON-ish string leaf (`"{...}"`) is equivalent to a container in both directions for the
    // comparator, which no structural pattern can reconcile — reject so the stub is `always_bits`
    // (the same guard #708's `body_anchor` applies via `structural_hash`).
    structural_hash(body)?;
    let pattern = to_quamina_pattern_value(body)?;
    serde_json::to_string(&pattern).ok()
}

/// The body-field dimension (issue #767): a quamina automaton over field-level `equals`-on-body
/// predicates, so "which of N field-equals stubs matches this body" is one automaton pass instead
/// of an O(N) Stage-2 scan. Complements #708's [`BodyHashDimension`] (whole-body `deepEquals`),
/// which quamina's subset semantics cannot express.
struct BodyFieldDimension {
    /// Patterns keyed by stub id; `None` when zero stubs are eligible (or the feature is off), in
    /// which case [`Dimension::prunes`] is false and this dimension is skipped entirely.
    #[cfg(feature = "quamina-matching")]
    quamina: Option<quamina::Quamina<usize>>,
    /// Stubs not indexed here (ineligible predicate, or a per-stub `add_pattern` failure) — always
    /// candidates on this dimension.
    ///
    /// Complete **only when `quamina.is_some()`**. When the dimension is deactivated (#792) the
    /// eligible stubs are in neither `quamina` nor here, because [`Dimension::prunes`] is false and
    /// [`Dimension::select`] is therefore never reached. Reading this bitset with `quamina == None`
    /// would prune every body-field stub — an under-approximation, i.e. stubs silently ceasing to
    /// match. `select` debug-asserts the coupling so a future refactor breaks loudly in tests.
    always: CandidateBits,
    /// Only read on the fail-open widen path, which is feature-gated.
    #[cfg(feature = "quamina-matching")]
    len: usize,
}

impl Dimension for BodyFieldDimension {
    fn select(&self, request: &DimensionRequest<'_>, out: &mut CandidateBits) {
        // `always` is only complete while the automaton exists — see its field doc (#792).
        #[cfg(feature = "quamina-matching")]
        debug_assert!(
            self.quamina.is_some(),
            "select() on a deactivated body-field dimension would under-approximate: its indexed \
             stubs are in neither `quamina` nor `always`"
        );
        out.copy_from(&self.always);
        #[cfg(not(feature = "quamina-matching"))]
        let _ = request; // the automaton (and its `request` read) is feature-gated below
        #[cfg(feature = "quamina-matching")]
        {
            let Some(q) = &self.quamina else { return };
            // A field-equals-on-object predicate can never match a non-JSON/absent body, so only
            // `always` stubs survive — exactly like the body-hash dimension.
            let Some(body) = request.body.get() else {
                return;
            };
            // A JSON-ish string leaf in the request body is equivalent to a container an indexed
            // stub may expect (both directions), which no structural pass can reconcile — so this
            // dimension must not prune this request. Widen to all; Stage-2 decides (mirrors the
            // body-hash dimension's identical `structural_hash` guard).
            if structural_hash(body).is_none() {
                out.copy_from(&CandidateBits::all(self.len));
                return;
            }
            // Serializing a `Value` cannot fail, but never under-approximate: fail OPEN.
            let Ok(event) = serde_json::to_vec(&normalize_json_value(body)) else {
                out.copy_from(&CandidateBits::all(self.len));
                return;
            };
            match q.matches_for_event(&event) {
                Ok(ids) => ids.into_iter().for_each(|i| out.set(i)),
                // Fail OPEN to over-approximation, never closed (Stage-2 decides).
                Err(_) => out.copy_from(&CandidateBits::all(self.len)),
            }
        }
    }

    fn prunes(&self) -> bool {
        #[cfg(feature = "quamina-matching")]
        {
            self.quamina.is_some()
        }
        #[cfg(not(feature = "quamina-matching"))]
        {
            false
        }
    }
}

/// Whether the body-field automaton can tell two stubs apart for this stub set (issue #792).
///
/// Two body-field stubs are worth discriminating only if one request can reach both — their path
/// sets must intersect AND their method sets must intersect. When every body-field stub owns a
/// distinct `(path, method)`, the path and method dimensions have already narrowed the candidate
/// set to at most one stub before the body is read.
///
/// Note this is *discrimination*, not pruning in general: with a single reachable stub the
/// automaton can still prune it away (a body matching no pattern yields an empty set, skipping
/// Stage-2 for that request). Deactivating trades that away — one Stage-2 predicate evaluation on
/// the no-match request — to stop paying the automaton on every request, which #779 measured as a
/// net ~6.5% throughput win on exactly this shape.
///
/// Conservative in both wildcard directions: a stub with no indexable path anchor is a candidate
/// for *every* path, and one with no method anchor for *every* method, so either can co-occur with
/// anything and keeps the dimension active. This is why counting distinct `(path, method)` tuples
/// is not enough — `(/p, GET)`, `(/p, POST)` and `(/p, *)` are three distinct keys, yet one GET
/// reaches two of them.
#[cfg(feature = "quamina-matching")]
fn body_field_discriminates(
    indexed: &CandidateBits,
    exact: &FastMap<String, Vec<usize>>,
    path_always: &CandidateBits,
    method_of: &[Option<usize>],
) -> bool {
    // Fewer than two indexed stubs ⇒ nothing to tell apart, whatever their anchors. Checked before
    // the wildcard branch below, which would otherwise activate on a lone path-unanchored stub that
    // has no sibling to collide with.
    if indexed.count() < 2 {
        return false;
    }
    if indexed.iter().any(|i| path_always.contains(i)) {
        return true;
    }
    exact.values().any(|bucket| {
        let members: Vec<usize> = bucket
            .iter()
            .copied()
            .filter(|&i| indexed.contains(i))
            .collect();
        if members.len() < 2 {
            return false;
        }
        // Slots are bounded by METHOD_SLOTS, so the dedup is a bitmask rather than a set. The
        // assertion is what makes that safe to assume: widening METHOD_SLOTS past a u8 would
        // otherwise shift out of range and silently stop detecting same-slot collisions.
        const _: () = assert!(METHOD_SLOTS <= u8::BITS as usize);
        let mut seen: u8 = 0;
        for i in members {
            match method_of[i] {
                None => return true,
                Some(slot) => {
                    let bit = 1u8 << slot;
                    if seen & bit != 0 {
                        return true;
                    }
                    seen |= bit;
                }
            }
        }
        false
    })
}

pub(crate) struct StubIndex {
    len: usize,
    path: PathDimension,
    method: MethodDimension,
    literal: LiteralDimension,
    regex: RegexDimension,
    body: BodyHashDimension,
    body_field: BodyFieldDimension,
}

impl StubIndex {
    /// Build every dimension in one pass over the stubs, preserving ascending stub id within each
    /// bucket (so iteration stays declaration-ordered).
    fn build(stubs: &[Arc<StubState>]) -> Self {
        let len = stubs.len();
        let mut exact: FastMap<String, Vec<usize>> = FastMap::default();
        let mut path_always = CandidateBits::zeros(len);

        let mut slots: [Vec<usize>; METHOD_SLOTS] = Default::default();
        let mut method_always = CandidateBits::zeros(len);

        let mut literal_ci: Vec<(usize, String, LiteralKind)> = Vec::new();
        let mut literal_cs: Vec<(usize, String, LiteralKind)> = Vec::new();
        let mut literal_always = CandidateBits::zeros(len);

        let mut regex_ci: Vec<(usize, String)> = Vec::new();
        let mut regex_cs: Vec<(usize, String)> = Vec::new();
        let mut regex_always = CandidateBits::zeros(len);

        let mut body_by_hash: FastMap<u64, Vec<usize>> = FastMap::default();
        let mut body_always = CandidateBits::zeros(len);

        // #792: the automaton is built only if it can prune, which is knowable once every stub's
        // path/method anchor is known — i.e. after this loop. So the eligible patterns are
        // collected here and added to a `Quamina` below, rather than as they are found.
        #[cfg(feature = "quamina-matching")]
        let mut body_field_patterns: Vec<(usize, String)> = Vec::new();
        #[cfg(feature = "quamina-matching")]
        let mut body_field_indexed = CandidateBits::zeros(len);
        #[cfg(feature = "quamina-matching")]
        let mut method_of: Vec<Option<usize>> = vec![None; len];
        let mut body_field_always = CandidateBits::zeros(len);

        for (i, state) in stubs.iter().enumerate() {
            match classify(&state.stub) {
                Some(PathAnchor::Exact(k)) => exact.entry(k).or_default().push(i),
                None => path_always.set(i),
            }
            match state.stub.predicates.iter().find_map(method_anchor) {
                Some(m) => {
                    let slot = method_slot(m);
                    slots[slot].push(i);
                    #[cfg(feature = "quamina-matching")]
                    {
                        method_of[i] = Some(slot);
                    }
                }
                None => method_always.set(i),
            }
            // Only the first literal anchor is indexed — same rule as `classify`/`regex_anchor`.
            // An empty literal is an unconditional pass in the evaluator (see
            // `empty_literal_always_matches`), so it must never reach the automaton: feeding it in
            // would ask aho-corasick to match the empty string, and even if that "worked" it would
            // be solving the wrong problem — the stub must be a candidate for every path, not just
            // ones the empty pattern happens to hit.
            match state.stub.predicates.iter().find_map(literal_anchor) {
                Some(a) if a.text.is_empty() => literal_always.set(i),
                Some(a) if a.case_sensitive => literal_cs.push((i, a.text.to_owned(), a.kind)),
                Some(a) => literal_ci.push((i, a.text.to_owned(), a.kind)),
                None => literal_always.set(i),
            }
            // Only the first regex anchor is indexed. A stub's further `matches` predicates are
            // also required, so ignoring them only ever over-approximates — Stage 2 still checks
            // them. Same rule as the path dimension's `classify`.
            match state.stub.predicates.iter().find_map(regex_anchor) {
                Some(a) if a.case_sensitive => regex_cs.push((i, a.pattern.to_owned())),
                Some(a) => regex_ci.push((i, a.pattern.to_owned())),
                None => regex_always.set(i),
            }
            // Only the first eligible deepEquals-body anchor is indexed — same first-anchor rule as
            // above; a stub's further body constraints stay required and are checked by Stage 2.
            match state.stub.predicates.iter().find_map(body_anchor) {
                Some(h) => body_by_hash.entry(h).or_default().push(i),
                None => body_always.set(i),
            }
            // First eligible field-level equals-on-body predicate → one quamina pattern (#767).
            match state.stub.predicates.iter().find_map(body_field_pattern) {
                Some(_pattern) => {
                    #[cfg(feature = "quamina-matching")]
                    {
                        body_field_indexed.set(i);
                        body_field_patterns.push((i, _pattern));
                    }
                    #[cfg(not(feature = "quamina-matching"))]
                    body_field_always.set(i);
                }
                None => body_field_always.set(i),
            }
        }

        let (literal_insensitive, literal_ci_fallback) = build_literal_class(literal_ci, true);
        let (literal_sensitive, literal_cs_fallback) = build_literal_class(literal_cs, false);
        for i in literal_ci_fallback.into_iter().chain(literal_cs_fallback) {
            literal_always.set(i);
        }

        let (insensitive, ci_fallback) = build_case_class(regex_ci, true);
        let (sensitive, cs_fallback) = build_case_class(regex_cs, false);
        for i in ci_fallback.into_iter().chain(cs_fallback) {
            regex_always.set(i);
        }

        // #792: build the automaton only when one request can reach two body-field stubs at once.
        // Otherwise the path/method dimensions have already narrowed to a single stub and it would
        // cost ~6.5% to re-derive that. Skipping it leaves those stubs unpruned on this dimension,
        // which is a pure over-approximation — Stage-2 still decides, so results are unchanged.
        #[cfg(feature = "quamina-matching")]
        let body_field_quamina = if body_field_discriminates(
            &body_field_indexed,
            &exact,
            &path_always,
            &method_of,
        ) {
            let mut q = quamina::Quamina::new();
            for (i, pattern) in &body_field_patterns {
                // A per-stub `add_pattern` failure (PatternLimits/malformed) falls that stub
                // back to `always` — a build-time (admin-rate) warn, never the per-request
                // trap of #741.
                if let Err(e) = q.add_pattern(*i, pattern) {
                    tracing::warn!(stub = *i, error = %e,
                            "body-field dimension: pattern rejected; stub falls back to full evaluation");
                    body_field_always.set(*i);
                }
            }
            Some(q)
        } else {
            None
        };

        let path = PathDimension {
            exact,
            always: path_always,
        };
        let method = MethodDimension {
            slots,
            always: method_always,
        };
        let literal = LiteralDimension {
            insensitive: literal_insensitive,
            sensitive: literal_sensitive,
            always: literal_always,
        };
        let regex = RegexDimension {
            insensitive,
            sensitive,
            always: regex_always,
        };
        let body = BodyHashDimension {
            by_hash: body_by_hash,
            always: body_always,
            len,
        };
        let body_field = BodyFieldDimension {
            #[cfg(feature = "quamina-matching")]
            quamina: body_field_quamina,
            always: body_field_always,
            #[cfg(feature = "quamina-matching")]
            len,
        };
        StubIndex {
            len,
            path,
            method,
            literal,
            regex,
            body,
            body_field,
        }
    }

    /// The number of stubs this index spans. Test-only: the serve path reads the bitsets
    /// directly, so this exists for dimension-level assertions (issue #1000).
    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.len
    }

    /// Intersect one dimension's bitset into the accumulator, seeding it on the first dimension
    /// that actually runs. Returns whether any candidate survives — `false` means the caller can
    /// stop, because intersection is monotone and no later dimension can put a bit back.
    ///
    /// The emptiness test is deliberately *inside* here, and only on the path where the dimension
    /// actually ran: `is_empty()` scans the whole bitset (16 words at 1000 stubs), so testing it
    /// after a dimension that was skipped is pure cost for an answer that cannot have changed.
    /// Returning `true` for a skipped dimension also means an unseeded (all-zeros) accumulator can
    /// never be mistaken for "everything was pruned" — the caller needs no `seeded` guard.
    ///
    /// Generic over the dimension rather than taking `&dyn Dimension`, so each call site
    /// monomorphizes to a static dispatch — see the module docs on why dimensions are concrete
    /// fields.
    fn fold_in<D: Dimension>(
        dimension: &D,
        request: &DimensionRequest<'_>,
        acc: &mut CandidateBits,
        seeded: &mut bool,
        len: usize,
    ) -> bool {
        if !dimension.prunes() {
            return true;
        }
        if *seeded {
            let mut scratch = CandidateBits::zeros(len);
            dimension.select(request, &mut scratch);
            acc.intersect_with(&scratch);
        } else {
            // `select` overwrites, so the first dimension seeds `acc` directly — no `all()` fill to
            // intersect against, and no scratch buffer.
            dimension.select(request, acc);
            *seeded = true;
        }
        !acc.is_empty()
    }

    /// Candidate stub ids for a request: the intersection of every dimension's bitset. A superset
    /// of the stubs that could match — Stage-2 does the real Mountebank evaluation on these, in the
    /// ascending (declaration) order [`CandidateBits::iter`] yields.
    /// Dimensions run cheapest-first, and only when they can actually prune:
    ///
    /// * a dimension no stub is indexed on is skipped ([`Dimension::prunes`]) — otherwise a corpus
    ///   that never constrains the method would pay the method dimension a full-width copy and
    ///   intersect to produce all-ones;
    /// * an empty accumulator short-circuits the rest. Dimensions run cheapest-first: method (a
    ///   slot lookup, no allocation) is both the cheapest and, on method-partitioned corpora, the
    ///   most selective, so its early exit can skip every later dimension's work entirely. Path
    ///   (a hashmap lookup) is next. Literal and regex both walk the haystack through an automaton,
    ///   so they run last and in that order: the literal dimension's Aho-Corasick pass is cheaper
    ///   per byte than the regex meta engine's, so it gets first crack at shrinking (or emptying)
    ///   the accumulator before the more expensive dimension has to run at all.
    ///
    /// Short-circuits through [`Self::fold_in`]'s return value rather than re-testing emptiness
    /// between dimensions: intersection is monotone, so once nothing survives no later dimension can
    /// put a bit back.
    pub(crate) fn candidates(&self, request: &DimensionRequest<'_>) -> CandidateBits {
        let mut acc = CandidateBits::zeros(self.len);
        let mut seeded = false;

        if Self::fold_in(&self.method, request, &mut acc, &mut seeded, self.len)
            && Self::fold_in(&self.path, request, &mut acc, &mut seeded, self.len)
            && Self::fold_in(&self.literal, request, &mut acc, &mut seeded, self.len)
            && Self::fold_in(&self.regex, request, &mut acc, &mut seeded, self.len)
        {
            // Body dimensions last: each touches the request body (hash / normalize+automaton), so
            // let the cheap path/method/automaton dimensions empty the accumulator first where they
            // can. The body-field automaton (#767) runs only if the hash dimension left survivors.
            if Self::fold_in(&self.body, request, &mut acc, &mut seeded, self.len) {
                Self::fold_in(&self.body_field, request, &mut acc, &mut seeded, self.len);
            }
        }

        // No dimension indexes anything (e.g. every stub is a body regex): everyone is a candidate.
        if seeded {
            acc
        } else {
            CandidateBits::all(self.len)
        }
    }
}

/// Does this predicate tree contain an `inject` predicate anywhere?
fn predicate_contains_inject(pred: &Predicate) -> bool {
    match &pred.operation {
        PredicateOperation::Inject(_) => true,
        PredicateOperation::Not(inner) => predicate_contains_inject(inner),
        PredicateOperation::And(children) | PredicateOperation::Or(children) => {
            children.iter().any(predicate_contains_inject)
        }
        _ => false,
    }
}

/// The unit of stub state the match hot path reads: the stubs, the index over *those exact* stubs,
/// and the snapshot-wide precomputed gates (issue #707).
///
/// Held behind a single `ArcSwap` in [`Imposter`](super::Imposter), so one wait-free `load()` per
/// request yields all of it. Before #707 the stubs and the index lived in two `ArcSwap`s kept in
/// sync only by convention inside `mutate_stubs`; bundling them makes that invariant type-enforced
/// — a reader cannot observe an index built for a different stub vector — and costs one atomic
/// instead of two.
pub(crate) struct StubSnapshot {
    stubs: Vec<Arc<StubState>>,
    index: StubIndex,
    /// Whether any stub's predicate tree contains an `inject` predicate, anywhere (including
    /// nested under `and`/`or`/`not`). Computed once per snapshot so the request hot path can
    /// gate the bounded (spawn_blocking) matching route on it for free (issue #476).
    has_inject: bool,
    /// Whether any stub is scenario-gated (`requiredScenarioState`). The eligibility gate reads
    /// flow state during matching; on a blocking backend (a networked store) that read must run off the tokio
    /// worker, so the bounded matcher offloads only when this is set — a scenario-free snapshot
    /// keeps the inline fast path even on a blocking backend (issue #475).
    has_scenario_gate: bool,
    /// `(index, scenario)` of every scenario-gated stub at or ahead of the last stub serving
    /// `_rift.conditional`, ascending (issue #1307). Only these gates can change which stub answers
    /// a conditional request, so only their transitions are stamped; usually empty or tiny.
    conditional_gates: Vec<(usize, Box<str>)>,
}

/// Whether `stub` has a response serving `_rift.conditional` (an `is` response; issue #1280).
fn serves_conditional(stub: &crate::imposter::types::Stub) -> bool {
    stub.responses.iter().any(|r| match r {
        crate::imposter::types::StubResponse::Is {
            rift: Some(rift), ..
        } => !matches!(
            rift.conditional,
            None | Some(crate::imposter::types::ConditionalGet::Enabled(false))
        ),
        _ => false,
    })
}

impl StubSnapshot {
    /// Build the index and the snapshot-wide gates for `stubs`.
    pub(crate) fn build(stubs: Vec<Arc<StubState>>) -> Self {
        let index = StubIndex::build(&stubs);
        let has_inject = stubs
            .iter()
            .any(|s| s.stub.predicates.iter().any(predicate_contains_inject));
        let has_scenario_gate = stubs
            .iter()
            .any(|s| s.stub.required_scenario_state.is_some());
        let conditional_gates = match stubs.iter().rposition(|s| serves_conditional(&s.stub)) {
            None => Vec::new(),
            Some(last) => stubs[..=last]
                .iter()
                .enumerate()
                .filter_map(|(i, s)| {
                    s.stub
                        .required_scenario_state
                        .as_ref()
                        .map(|_| (i, s.stub.scenario_name.as_deref().unwrap_or("").into()))
                })
                .collect(),
        };
        StubSnapshot {
            stubs,
            index,
            has_inject,
            has_scenario_gate,
            conditional_gates,
        }
    }

    /// Whether a transition of `scenario` can change which stub answers a conditional request
    /// (issue #1307).
    pub(crate) fn is_conditional_gate(&self, scenario: &str) -> bool {
        self.conditional_gates.iter().any(|(_, s)| &**s == scenario)
    }

    /// The scenarios gating a stub at or ahead of `index`, among those that matter to a
    /// conditional response (issue #1307).
    pub(crate) fn conditional_gates_through(&self, index: usize) -> impl Iterator<Item = &str> {
        self.conditional_gates
            .iter()
            .take_while(move |(i, _)| *i <= index)
            .map(|(_, s)| &**s)
    }

    /// The stubs this snapshot describes, in declaration order.
    pub(crate) fn stubs(&self) -> &[Arc<StubState>] {
        &self.stubs
    }

    /// Whether any stub in this snapshot uses an `inject` predicate (issue #476).
    pub(crate) fn has_inject(&self) -> bool {
        self.has_inject
    }

    /// Whether any stub in this snapshot is scenario-gated (`requiredScenarioState`, issue #475).
    pub(crate) fn has_scenario_gate(&self) -> bool {
        self.has_scenario_gate
    }

    /// Candidate stub ids for a request that carries no (or a non-JSON) body — see
    /// [`StubIndex::candidates`]. The body dimension then contributes only its `always` stubs.
    #[cfg(test)]
    pub(crate) fn candidates(&self, method: &str, path: &str) -> CandidateBits {
        self.candidates_with_body(method, path, &crate::behaviors::LazyJson::absent())
    }

    /// Candidate stub ids for a request, threading the request's lazily-parsed body (#290, #708,
    /// #1442) so the deepEquals-body dimension can prune; it is parsed only if a body dimension
    /// actually prunes.
    pub(crate) fn candidates_with_body(
        &self,
        method: &str,
        path: &str,
        body_json: &crate::behaviors::LazyJson<'_>,
    ) -> CandidateBits {
        self.index.candidates(&DimensionRequest {
            method,
            path,
            body: body_json,
        })
    }

    /// The index over these stubs (tests assert dimension-level behaviour through it).
    #[cfg(test)]
    pub(crate) fn index(&self) -> &StubIndex {
        &self.index
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::core::Imposter;
    use crate::imposter::types::ImposterConfig;
    use rand::rngs::StdRng;
    use rand::{RngExt, SeedableRng};
    use serde_json::{Value, json};
    use std::collections::HashMap;
    use tracing_test::traced_test;

    /// A stub over `preds`, built without the parse-time predicate check. Since #1221 the config
    /// doors refuse a `matches` pattern that does not compile, but `Stub`'s fields are public, so a
    /// stub built in code still reaches the index unchecked — and the index must stay sound for it.
    /// The invalid- and oversized-pattern fixtures below depend on this.
    fn unchecked_stub(preds: &Value) -> Stub {
        let mut stub: Stub =
            serde_json::from_value(json!({ "responses": [{ "is": { "statusCode": 200 } }] }))
                .expect("valid stub");
        stub.predicates = serde_json::from_value(preds.clone()).expect("valid predicates");
        stub
    }

    fn stub_states(preds: &[Value]) -> Vec<Arc<StubState>> {
        preds
            .iter()
            .map(|p| Arc::new(StubState::new(unchecked_stub(p))))
            .collect()
    }

    /// A snapshot over `preds`, for dimension-level assertions.
    fn snapshot(preds: &[Value]) -> StubSnapshot {
        StubSnapshot::build(stub_states(preds))
    }

    /// The candidate ids for a request, ascending — the pre-#707 `candidates()` shape, so the
    /// existing coverage/ordering assertions read unchanged.
    fn candidate_ids(snap: &StubSnapshot, method: &str, path: &str) -> Vec<usize> {
        snap.candidates(method, path).iter().collect()
    }

    /// The candidate ids for a request with a JSON body, ascending (#708 body dimension).
    fn candidate_ids_body(
        snap: &StubSnapshot,
        method: &str,
        path: &str,
        body: &Value,
    ) -> Vec<usize> {
        let text = body.to_string();
        snap.candidates_with_body(method, path, &crate::behaviors::LazyJson::new(Some(&text)))
            .iter()
            .collect()
    }

    fn imposter(preds: &[Value]) -> Imposter {
        let mut config: ImposterConfig =
            serde_json::from_value(json!({ "port": 9999, "protocol": "http" }))
                .expect("valid imposter config");
        config.stubs = preds.iter().map(unchecked_stub).collect();
        Imposter::new(config).expect("test imposter")
    }

    /// A diverse corpus exercising every anchor category AND every fallback category, in an order
    /// that makes first-match-wins meaningful (the `not`/empty stubs at the end catch anything).
    fn corpus() -> Vec<Value> {
        vec![
            json!([{"equals": {"path": "/exact"}}]),       // 0 exact
            json!([{"equals": {"path": "/EXACT"}}]),       // 1 exact, other case
            json!([{"startsWith": {"path": "/pre"}}]),     // 2 prefix
            json!([{"contains": {"path": "mid"}}]),        // 3 contains
            json!([{"matches": {"path": "^/re[0-9]+$"}}]), // 4 regex -> regex dimension (#709)
            json!([{"exists": {"query": true}}]),          // 5 exists -> fallback
            json!([{"equals": {"method": "POST"}}]),       // 6 method-only -> fallback
            json!([{"equals": {"body": "ping"}}]),         // 7 body -> fallback
            json!([{"or": [{"equals": {"path": "/o1"}}, {"equals": {"path": "/o2"}}]}]), // 8 or -> fallback
            json!([{"not": {"equals": {"path": "/nope"}}}]), // 9 not -> fallback
            json!([{"equals": {"path": "/cs"}, "caseSensitive": true}]), // 10 caseSensitive -> fallback
            json!([{"equals": {"method": "GET", "path": "/mp"}}]),       // 11 method+path exact
            json!([]),                                                   // 12 match-all -> fallback
        ]
    }

    fn idx(r: anyhow::Result<Option<(Arc<StubState>, usize)>>) -> Option<usize> {
        r.expect("no backend error").map(|(_, i)| i)
    }

    // AC2: the indexed path returns the SAME matched stub as the linear scan for every request —
    // the correctness guardrail. Covers case-insensitivity, prefix/contains, all fallback
    // categories, method+path, and first-match-wins ordering (the trailing not/empty stubs).
    #[test]
    fn indexed_matching_equals_linear() {
        let imp = imposter(&corpus());
        let no_headers: HashMap<String, String> = HashMap::new();

        // (method, path, query, body)
        let requests: &[(&str, &str, Option<&str>, Option<&str>)] = &[
            ("GET", "/exact", None, None),
            ("GET", "/EXACT", None, None),
            ("GET", "/eXaCt", None, None), // case-insensitive collides on both 0 and 1 -> 0 wins
            ("GET", "/prefixed/deep", None, None),
            ("GET", "/pre", None, None),
            ("GET", "/x-mid-y", None, None),
            ("GET", "/re12", None, None),
            ("GET", "/re", None, None), // regex requires digits -> no 4; falls to not(9)
            ("GET", "/mp", None, None),
            ("POST", "/mp", None, None), // method+path requires GET -> not 11; POST hits 6
            ("GET", "/nope", None, None), // not(/nope) excludes -> empty(12)
            ("GET", "/cs", None, None),  // caseSensitive lives in fallback
            ("GET", "/CS", None, None),
            ("GET", "/o1", None, None),
            ("GET", "/o2", None, None),
            ("GET", "/anything", Some("a=1"), None), // exists{query} -> 5
            ("GET", "/anything", None, Some("ping")), // body -> 7 (9 not also matches, order)
            ("GET", "/zzz", None, None),             // nothing anchored -> not(9)
            ("POST", "/zzz", None, None),
            ("GET", "/pre-mid-exact", None, None), // matches prefix(2) AND contains(3): first wins
        ];

        for (m, p, q, b) in requests {
            let linear = idx(imp.find_matching_stub_linear(m, p, &no_headers, *q, *b, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, *q, *b, None, None));
            assert_eq!(
                indexed, linear,
                "index diverged from linear for {m} {p} q={q:?} b={b:?}"
            );
        }
    }

    // AC2 edge cases: the fold/normalization boundary where the index (Unicode `to_lowercase`) and
    // the `equals` evaluator (ASCII `eq_ignore_ascii_case`) differ, plus a path predicate nested in
    // `and` (must be fallback), multiple path predicates, and a trailing slash. No greedy `not` stub
    // here, so anchored stubs are actually reached and the boundary is exercised, not shadowed.
    #[test]
    fn indexed_matching_equals_linear_edge_cases() {
        let imp = imposter(&[
            json!([{"equals": {"path": "/café"}}]),  // 0 unicode exact
            json!([{"startsWith": {"path": "/A"}}]), // 1 prefix, uppercase anchor
            json!([{"and": [{"equals": {"method": "GET"}}, {"equals": {"path": "/andp"}}]}]), // 2 and -> fallback
            json!([{"equals": {"path": "/exact"}}, {"startsWith": {"path": "/exa"}}]), // 3 two path preds
            json!([{"contains": {"path": "/seg"}}]),                                   // 4 contains
            json!([{"equals": {"path": "/pm2"}}, {"equals": {"method": "GET"}}]), // 5 path anchor + separate method predicate
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        let requests: &[(&str, &str)] = &[
            ("GET", "/café"),
            ("GET", "/CAFÉ"), // ASCII fold: É != é so equals rejects; index over-includes harmlessly
            ("GET", "/caFé"),
            ("GET", "/a1"),   // startsWith /A, case-insensitive
            ("GET", "/andp"), // and-nested path lives in fallback (stub 2)
            ("POST", "/andp"),
            ("GET", "/exact"), // stub 3: both path preds hold
            ("GET", "/exa"),   // startsWith /exa holds but equals /exact fails -> not stub 3
            ("GET", "/x/seg/y"),
            ("GET", "/exact/"), // trailing slash is not equal to /exact
            ("GET", "/andp/extra"),
            ("GET", "/pm2"), // stub 5: path anchor indexes it, separate method predicate holds
            ("POST", "/pm2"), // path-anchored candidate, but Stage-2 method predicate rejects -> None
        ];
        for (m, p) in requests {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }
    }

    // ── Body-field dimension (#767): differential gate + unit tests ──────────────────────────

    // The #767 gate: the indexed path (through the quamina body-field dimension) returns the SAME
    // matched stub as the linear scan for every JSON-body request — over a corpus mixing eligible
    // field-equals shapes with every carve-out that must fall to always_bits. This is the
    // executable soundness proof; a dimension that ever UNDER-approximates diverges here.
    #[test]
    fn body_field_dimension_matches_linear() {
        let imp = imposter(&[
            json!([{"equals": {"body": {"user": {"id": 5}}}}]), // 0 nested numeric
            json!([{"equals": {"body": {"user": {"id": 7}}}}]), // 1 nested numeric, other id
            json!([{"equals": {"body": {"name": "Alice"}}}]), // 2 string (case-insensitive default)
            json!([{"equals": {"body": {"active": true}}}]),  // 3 boolean
            json!([{"equals": {"body": {"a": 1, "b": 2}}}]),  // 4 multi-field
            json!([{"equals": {"body": {"tags": [1, 2]}}}]),  // 5 array leaf -> INELIGIBLE (always)
            json!([{"equals": {"body": {"x": null}}}]),       // 6 null leaf -> INELIGIBLE (always)
            json!([{"equals": {"body": {"n": 1.5}}}]), // 7 float leaf -> eligible (stringified)
            json!([{"equals": {"body": {"K": "V"}}, "caseSensitive": true}]), // 8 caseSensitive -> INELIGIBLE
            json!([{"equals": {"body": {"K": "v"}}, "keyCaseSensitive": true}]), // 9 keyCaseSensitive -> INELIGIBLE
            json!([{"deepEquals": {"body": {"whole": 1}}}]), // 10 deepEquals -> #708, not this dim
            json!([{"equals": {"body": {"u": {"id": 5}}}, "except": "x"}]), // 11 except -> INELIGIBLE
            json!([{"equals": {"body": {"deep": {"a": {"b": 3}}}}}]),       // 12 depth-3 nesting
            json!([{"equals": {"body": {"code": "5"}}}]), // 13 STRING "5" (cross-type vs numeric request)
            json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]), // 14 json-ish string leaf -> INELIGIBLE
            json!([{"equals": {"body": {"empt": ""}}}]), // 15 empty-string leaf -> INELIGIBLE (a missing field reads "")
            json!([]),                                   // 16 match-all trailer
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        // Bodies chosen to exercise the comparator's TYPE COERCION on both sides — the axis a
        // type-matching automaton gets wrong — plus mixed case, carve-outs, depth-3, and non-JSON.
        let bodies: &[&str] = &[
            r#"{"user":{"id":5}}"#,
            r#"{"user":{"id":7}}"#,
            r#"{"user":{"id":9}}"#,   // no matching id -> trailer
            r#"{"USER":{"ID":5}}"#,   // upper keys fold to stub 0
            r#"{"user":{"id":"5"}}"#, // STRING "5" still matches numeric stub 0 (coercion)
            r#"{"name":"Alice"}"#,
            r#"{"NAME":"ALICE"}"#, // key+value fold to stub 2
            r#"{"name":"bob"}"#,
            r#"{"active":true}"#,
            r#"{"active":"true"}"#, // STRING "true" matches bool stub 3 (coercion)
            r#"{"a":1,"b":2}"#,
            r#"{"a":1,"b":3}"#,  // partial -> trailer
            r#"{"tags":[1,2]}"#, // array-leaf stub is always; linear decides
            r#"{"x":null}"#,
            r#"{"n":1.5}"#,
            r#"{"n":"1.5"}"#, // STRING "1.5" matches float stub 7 (coercion)
            r#"{"whole":1}"#, // deepEquals stub 10
            r#"{"K":"V"}"#,   // caseSensitive/keyCaseSensitive stubs
            r#"{"deep":{"a":{"b":3}}}"#, // depth-3 stub 12
            r#"{"code":5}"#,  // NUMBER 5 matches string stub 13 (reverse coercion)
            r#"{"code":"5"}"#,
            r#"{"j":{"x":1}}"#, // container matches the json-ish-string stub 14 (widen path)
            r#"{"j":"{\"x\":1}"}"#, // the json-ish string itself
            r#"{"empt":""}"#,   // empty-string request matches empty-string stub 15
            r#"{"empt":null}"#, // null is not "" under equals (#1579) -> trailer
            r#"not json at all"#, // non-JSON body: every field reads "" -> stub 15
            r#"{}"#,            // missing field reads "" -> stub 15
            r#"{"user":{"id":5.0}}"#, // JS number spelling: 5.0 is 5 -> stub 0
            r#"{"n":1.50}"#,    // 1.50 is 1.5 -> stub 7
            r#"{"user":[{"id":9},{"id":7}]}"#, // an array of objects: any element -> stub 1
            r#"{"name":["bob","ALICE"]}"#, // an array field: any element -> stub 2
            r#"[{"name":"x"},{"name":"Alice"}]"#, // top-level array: any element (fail-open path)
            r#"[1,2]"#,
        ];
        for b in bodies {
            let linear = idx(imp.find_matching_stub_linear(
                "POST",
                "/x",
                &no_headers,
                None,
                Some(b),
                None,
                None,
            ));
            let indexed = idx(imp.find_matching_stub_with_client(
                "POST",
                "/x",
                &no_headers,
                None,
                Some(b),
                None,
                None,
            ));
            assert_eq!(
                indexed, linear,
                "body-field index diverged from linear for body {b}"
            );
        }
    }

    #[test]
    fn body_field_pattern_eligibility() {
        let pat = |p: Value| -> Option<String> {
            let stub: crate::imposter::types::Stub = serde_json::from_value(
                json!({"predicates": p, "responses": [{"is": {"statusCode": 200}}]}),
            )
            .expect("stub");
            stub.predicates.iter().find_map(body_field_pattern)
        };
        // Eligible → pattern of the comparator's folded STRING leaf form (every leaf a one-element
        // array of `leaf_text(leaf).to_ascii_lowercase()`), object keys lowercased.
        assert_eq!(
            pat(json!([{"equals": {"body": {"User": {"Id": 5}}}}])).as_deref(),
            Some(r#"{"user":{"id":["5"]}}"#)
        );
        assert_eq!(
            pat(json!([{"equals": {"body": {"Name": "Alice"}}}])).as_deref(),
            Some(r#"{"name":["alice"]}"#)
        );
        assert_eq!(
            pat(json!([{"equals": {"body": {"ok": true}}}])).as_deref(),
            Some(r#"{"ok":["true"]}"#)
        );
        assert_eq!(
            pat(json!([{"equals": {"body": {"n": 1.5}}}])).as_deref(),
            Some(r#"{"n":["1.5"]}"#) // floats eligible: stringified, not type-matched
        );
        assert_eq!(
            pat(json!([{"equals": {"body": {"n": 2.0}}}])).as_deref(),
            Some(r#"{"n":["2"]}"#) // in JS spelling (#1579)
        );
        // Ineligible → None (fall back to always_bits).
        for ineligible in [
            json!([{"equals": {"body": {"tags": [1, 2]}}}]), // array leaf
            json!([{"equals": {"body": {"x": null}}}]),      // null leaf
            json!([{"equals": {"body": {"x": ""}}}]), // empty-string leaf: matches a missing field
            json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]), // json-ish string leaf
            json!([{"equals": {"body": {}}}]),        // empty object
            json!([{"equals": {"body": "scalar"}}]),  // scalar body
            json!([{"equals": {"path": "/p"}}]),      // no body
            json!([{"deepEquals": {"body": {"a": 1}}}]), // deepEquals, not equals
            json!([{"equals": {"body": {"a": 1}}, "caseSensitive": true}]),
            json!([{"equals": {"body": {"a": 1}}, "keyCaseSensitive": true}]),
            json!([{"equals": {"body": {"a": 1}}, "except": "x"}]), // except
            json!([{"equals": {"body": {"a": 1}}, "jsonpath": {"selector": "$.a"}}]), // selector
        ] {
            assert!(
                pat(ineligible.clone()).is_none(),
                "should be ineligible: {ineligible}"
            );
        }
    }

    #[cfg(feature = "quamina-matching")]
    #[test]
    fn normalize_json_value_folds_to_comparator_string_form() {
        // Every scalar leaf becomes its folded `leaf_text` form (numbers/bools → strings) so the
        // event mirrors what the `equals` comparator compares on.
        let out = normalize_json_value(
            &json!({"User": {"Name": "ALICE", "Id": 5, "OK": true, "F": 5.0, "Z": null}}),
        );
        assert_eq!(
            out,
            json!({"user": {"name": "alice", "id": "5", "ok": "true", "f": "5", "z": "null"}})
        );
        // Non-ASCII passes through unfolded (matches eq_ignore_ascii_case).
        assert_eq!(normalize_json_value(&json!("CAFÉ")), json!("cafÉ"));
    }

    // #767: the automaton actually PRUNES (not merely doesn't-under-approximate), the sibling of
    // body_dimension_collapses_candidates (#708) / literal/regex collapse tests — the unit-speed
    // stand-in for the #719 recovery bench.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_collapses_candidates() {
        // 500 field-equals-on-body stubs, each a distinct nested id. A matching body probes down to
        // just that stub instead of an O(stubs) Stage-2 scan.
        let preds: Vec<Value> = (0..500)
            .map(|i| json!([{"equals": {"body": {"user": {"id": i}}}}]))
            .collect();
        let snap = snapshot(&preds);

        let target = 437usize;
        let ids = candidate_ids_body(&snap, "POST", "/x", &json!({"user": {"id": target}}));
        assert_eq!(
            ids,
            vec![target],
            "collapses to the single matching stub, got {ids:?}"
        );
        // A body equal to none prunes the whole dimension to empty.
        assert!(candidate_ids_body(&snap, "POST", "/x", &json!({"user": {"id": 9999}})).is_empty());
    }

    // ---- issue #792: the dimension deactivates when it provably cannot prune ---------------

    /// Whether the built snapshot will actually run the body-field automaton.
    #[cfg(feature = "quamina-matching")]
    fn body_field_active(preds: &[Value]) -> bool {
        snapshot(preds).index.body_field.prunes()
    }

    // #792 AC1: when every body-field stub owns a distinct (path, method), the path dimension has
    // already pruned to one stub before the body is consulted — the automaton can only re-derive
    // what is already known, at ~6.5% throughput. It must not be built.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_inactive_when_no_path_method_is_shared() {
        let preds: Vec<Value> = (0..50)
            .map(|i| json!([{"equals": {"path": format!("/p{i}"), "body": {"user": {"id": i}}}}]))
            .collect();
        assert!(
            !body_field_active(&preds),
            "distinct paths ⇒ the automaton cannot discriminate; it must be skipped"
        );
    }

    // The converse, so the test above cannot pass by disabling the dimension outright: stubs that
    // share one path are exactly the shape the dimension exists for (#779: +380% at 1000).
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_active_when_a_path_method_is_shared() {
        let preds: Vec<Value> = (0..50)
            .map(|i| json!([{"equals": {"path": "/shared", "body": {"user": {"id": i}}}}]))
            .collect();
        assert!(
            body_field_active(&preds),
            "stubs sharing a path are what the dimension prunes; it must stay active"
        );
    }

    // A body-field stub with no indexable path anchor is a candidate for EVERY path, so it can
    // co-occur with any other body-field stub. Unanchored ⇒ conservative ⇒ active. (This is the
    // shape `body_field_dimension_collapses_candidates` above relies on.)
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_active_when_a_stub_has_no_path_anchor() {
        let mut preds: Vec<Value> = (0..10)
            .map(|i| json!([{"equals": {"path": format!("/p{i}"), "body": {"user": {"id": i}}}}]))
            .collect();
        preds.push(json!([{"equals": {"body": {"user": {"id": 999}}}}]));
        assert!(
            body_field_active(&preds),
            "a path-unanchored body-field stub can share a path with any other; stay active"
        );
    }

    // Sharing a path is not enough to collide if the method dimension already separates the stubs:
    // one GET stub and one POST stub on /shared can never be candidates for the same request.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_inactive_when_a_shared_path_is_split_by_distinct_methods() {
        let preds = vec![
            json!([{"equals": {"path": "/shared", "method": "GET", "body": {"user": {"id": 1}}}}]),
            json!([{"equals": {"path": "/shared", "method": "POST", "body": {"user": {"id": 2}}}}]),
        ];
        assert!(
            !body_field_active(&preds),
            "distinct methods on one path cannot co-occur; the automaton cannot discriminate"
        );
    }

    // ...but a method-less stub on that same path matches every method, so it CAN co-occur with the
    // method-anchored ones. This is the case a naive (path, method) tuple count gets wrong: three
    // distinct keys, yet two of them are simultaneously reachable by one GET.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_active_when_a_shared_path_stub_has_no_method_anchor() {
        let preds = vec![
            json!([{"equals": {"path": "/shared", "method": "GET", "body": {"user": {"id": 1}}}}]),
            json!([{"equals": {"path": "/shared", "method": "POST", "body": {"user": {"id": 2}}}}]),
            json!([{"equals": {"path": "/shared", "body": {"user": {"id": 3}}}}]),
        ];
        assert!(
            body_field_active(&preds),
            "a method-unanchored stub co-occurs with every method on its path; stay active"
        );
    }

    // A lone body-field stub has no sibling to be told apart from, so the automaton buys nothing
    // even though the stub is path-unanchored — the wildcard branch alone would wrongly activate
    // here, since "co-occurs with everything" is vacuous when there is nothing to co-occur with.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_inactive_for_a_lone_stub_even_when_path_unanchored() {
        let preds = vec![
            json!([{"equals": {"body": {"user": {"id": 1}}}}]),
            json!([{"equals": {"path": "/other"}}]),
        ];
        assert!(
            !body_field_active(&preds),
            "one body-field stub has nothing to discriminate against; skip the automaton"
        );
    }

    // Only body-field stubs count toward a collision. A non-body-field sibling on the same path is
    // pruned by other dimensions and is never an argument for building the automaton.
    #[cfg(feature = "quamina-matching")]
    #[test]
    fn body_field_dimension_inactive_when_the_shared_path_sibling_has_no_body_predicate() {
        let preds = vec![
            json!([{"equals": {"path": "/shared", "body": {"user": {"id": 1}}}}]),
            json!([{"equals": {"path": "/shared"}}]),
            json!([{"equals": {"path": "/shared", "method": "PUT"}}]),
        ];
        assert!(
            !body_field_active(&preds),
            "a lone body-field stub on a shared path still has no body-field sibling"
        );
    }

    // #792 AC4: deactivating is a pure prefilter change, so matching results must be byte-identical
    // to the linear oracle on a corpus where the dimension goes INACTIVE. The existing
    // `differential_index_matches_linear_oracle` only covers the active shape (its body-field stubs
    // carry no path anchor), so it cannot see a deactivation bug — this is that corpus.
    #[test]
    fn distinct_path_body_field_corpus_matches_linear_oracle() {
        const BODIES: &[Option<&str>] = &[
            Some(r#"{"k":1}"#),
            Some(r#"{"k":"1"}"#),
            Some(r#"{"n":{"a":1}}"#),
            Some(r#"{"k":1,"z":9}"#),
            Some("ping"),
            None,
        ];
        // Each stub owns its own path, which is what deactivates the dimension. Paths, methods and
        // bodies are drawn from the same small pools the requests are, so requests hit real stubs.
        let preds: Vec<Value> = (0..24)
            .map(|i| match i % 4 {
                0 => json!([{"equals": {"path": format!("/p{i}"), "body": {"k": 1}}}]),
                1 => json!([{"equals": {"path": format!("/p{i}"), "body": {"n": {"a": 1}}}}]),
                2 => {
                    json!([{"equals": {"path": format!("/p{i}"), "method": "POST", "body": {"k": 1}}}])
                }
                _ => json!([{"equals": {"path": format!("/p{i}")}}]),
            })
            .collect();
        // Assert the premise, or the test silently stops testing what it claims: if a future change
        // made this corpus keep the dimension ACTIVE, every assertion below would still pass while
        // covering the shape the pre-existing oracle already covers.
        #[cfg(feature = "quamina-matching")]
        assert!(
            !body_field_active(&preds),
            "this corpus must deactivate the dimension — that is the shape under test"
        );

        let imp = imposter(&preds);
        let no_headers: HashMap<String, String> = HashMap::new();

        for i in 0..24 {
            for m in ["GET", "POST", "PUT"] {
                for body in BODIES {
                    let p = format!("/p{i}");
                    let linear = idx(imp.find_matching_stub_linear(
                        m,
                        &p,
                        &no_headers,
                        None,
                        *body,
                        None,
                        None,
                    ));
                    let indexed = idx(imp.find_matching_stub_with_client(
                        m,
                        &p,
                        &no_headers,
                        None,
                        *body,
                        None,
                        None,
                    ));
                    assert_eq!(
                        indexed, linear,
                        "index diverged from linear oracle with the body-field dimension inactive: {m} {p} b={body:?}"
                    );
                }
            }
        }
    }

    // The path dimension genuinely narrows (excludes non-matching anchored stubs) yet never drops a
    // stub the linear scan would consider (always-bits + matching anchors are all present).
    // Stub 6 is method-only (`equals {method: POST}`), so a GET request now prunes it on the method
    // dimension — the #707 pruning the path dimension alone could never do. Stub 4 is a path regex,
    // which #709's regex dimension prunes for a path its pattern cannot match.
    #[test]
    fn stub_index_narrows_and_covers() {
        let snap = snapshot(&corpus());
        let cands = candidate_ids(&snap, "GET", "/exact");

        // Narrowing: the prefix (2) and method+path-/mp (11) anchored stubs cannot match /exact,
        // so they are excluded.
        assert!(!cands.contains(&2), "prefix /pre stub excluded for /exact");
        assert!(
            !cands.contains(&11),
            "method+path /mp stub excluded for /exact"
        );
        assert!(
            !cands.contains(&6),
            "POST-only stub excluded for a GET request (method dimension, #707)"
        );
        assert!(
            !cands.contains(&4),
            "regex stub ^/re[0-9]+$ excluded for /exact (regex dimension, #709)"
        );

        // Coverage: both exact stubs (case-insensitive collision) and every stub no dimension can
        // index remain candidates.
        assert!(
            cands.contains(&0) && cands.contains(&1),
            "exact stubs present"
        );
        for fb in [5, 7, 8, 9, 10, 12] {
            assert!(
                cands.contains(&fb),
                "un-indexable stub {fb} must always be a candidate"
            );
        }
        // Ascending + deduped so Stage-2 preserves declaration order.
        let mut sorted = cands.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(cands, sorted, "candidates must be ascending and deduped");
    }

    // AC4: the method dimension collapses the candidate set — a request's method prunes every stub
    // anchored to a different one. This is the framework's proof: before #707 all four stubs were
    // candidates for every request, because the path dimension cannot see the method.
    #[test]
    fn method_dimension_collapses_candidates() {
        let snap = snapshot(&[
            json!([{"equals": {"method": "GET"}}]),
            json!([{"equals": {"method": "POST"}}]),
            json!([{"equals": {"method": "PUT"}}]),
            json!([{"equals": {"method": "DELETE"}}]),
        ]);
        for (i, m) in ["GET", "POST", "PUT", "DELETE"].iter().enumerate() {
            let c = snap.candidates(m, "/anything");
            assert_eq!(c.count(), 1, "{m}: exactly one candidate survives");
            assert!(c.contains(i), "{m}: the {m}-anchored stub is the survivor");
        }
        // A method no stub anchors prunes everything — and the early-exit path returns empty.
        assert_eq!(snap.candidates("PATCH", "/anything").count(), 0);
        // Case-insensitive, per Mountebank's default comparison.
        assert!(snap.candidates("get", "/anything").contains(0));
    }

    // AC6 (the soundness rule): a stub whose method constraint the dimension cannot index must stay
    // a candidate for EVERY method. A dimension may only exclude what it can prove cannot match —
    // anything else belongs in always_bits.
    #[test]
    fn ineligible_method_shapes_are_always_candidates() {
        let snap = snapshot(&[
            json!([{"equals": {"method": "GET"}}]), // 0 indexable
            json!([{"or": [{"equals": {"method": "GET"}}, {"equals": {"method": "POST"}}]}]), // 1 or
            json!([{"not": {"equals": {"method": "GET"}}}]), // 2 not
            json!([{"and": [{"equals": {"method": "GET"}}, {"equals": {"path": "/x"}}]}]), // 3 and
            json!([{"equals": {"method": "GET"}, "except": "X"}]), // 4 except rewrites the value
            json!([{"equals": {"method": "GET"}, "caseSensitive": true}]), // 5 caseSensitive
            json!([{"matches": {"method": "^G"}}]),          // 6 regex
            // 7: the evaluator stringifies a non-string value and compares it, so it IS a real
            // constraint — just not one this dimension indexes.
            json!([{"equals": {"method": 7}}]),
            json!([{"equals": {"method": "GET"}, "jsonpath": {"selector": "$.id"}}]), // 8 selector
            json!([]),                                                                // 9 match-all
        ]);
        // PATCH matches no indexable anchor, so only always-bits stubs may survive.
        let c = snap.candidates("PATCH", "/x");
        assert!(!c.contains(0), "the indexable GET stub must be pruned");
        for i in [1, 2, 3, 4, 5, 6, 7, 8, 9] {
            assert!(
                c.contains(i),
                "stub {i} is un-indexable → always a candidate"
            );
        }
    }

    // The `selector` arm of the shared `is_safely_indexable` gate, for the path dimension. Without
    // a test, inverting or dropping that check would be an *under*-approximation — a silently
    // pruned stub — which is the one failure mode the index must never have.
    #[test]
    fn selector_scoped_path_predicates_are_always_candidates() {
        let snap = snapshot(&[
            json!([{"equals": {"path": "/a"}, "jsonpath": {"selector": "$.id"}}]), // 0 selector
            json!([{"equals": {"path": "/a"}, "except": "X"}]),                    // 1 except
            json!([{"equals": {"path": "/a"}, "caseSensitive": true}]), // 2 caseSensitive
            json!([{"equals": {"path": "/a"}}]),                        // 3 indexable
        ]);
        // A path no anchor matches: only stubs the dimension cannot index may survive.
        let c = snap.candidates("GET", "/other");
        for i in [0, 1, 2] {
            assert!(
                c.contains(i),
                "stub {i} is un-indexable → always a candidate"
            );
        }
        assert!(!c.contains(3), "the indexable /a stub must be pruned");
    }

    // The index must fold case EXACTLY as the evaluator does (ASCII), not merely conservatively.
    // Unicode `to_lowercase` is length-changing and context-sensitive, so it breaks the prefix and
    // substring relations the path dimension relies on: the evaluator matches `startsWith "/ΟΣ"`
    // against `/ΟΣΑ` (its ASCII fold leaves Greek untouched), but a Unicode fold maps the anchor's
    // trailing Σ to a final sigma (`/ος`) that `"/οσα"` does not start with — pruning a stub that
    // does match. Regression test for that class of silent no-match.
    #[test]
    fn non_ascii_case_folding_matches_the_evaluator() {
        let imp = imposter(&[
            json!([{"startsWith": {"path": "/ΟΣ"}}]), // 0 Greek sigma: Unicode fold breaks the prefix
            json!([{"contains": {"path": "ΑΣ"}}]),    // 1 the same trap via contains
            json!([{"equals": {"path": "/İ"}}]),      // 2 dotted capital I lowercases to two chars
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [
            ("GET", "/ΟΣΑ"),
            ("GET", "/ΟΣ"),
            ("GET", "/οσα"),
            ("GET", "/xΑΣy"),
            ("GET", "/İ"),
            ("GET", "/i̇"),
        ] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }
    }

    // An unusual method shares the `Other` slot with every other unusual method. That is coarser,
    // not wrong: the dimension over-includes and verification decides. Guards against a slot scheme
    // that silently drops methods outside the named set.
    #[test]
    fn unnamed_methods_share_the_other_slot_soundly() {
        let snap = snapshot(&[
            json!([{"equals": {"method": "TRACE"}}]),
            json!([{"equals": {"method": "CONNECT"}}]),
            json!([{"equals": {"method": "GET"}}]),
        ]);
        // Both unusual stubs are candidates for either unusual method (over-approximation)...
        for m in ["TRACE", "CONNECT"] {
            let c = snap.candidates(m, "/x");
            assert!(c.contains(0) && c.contains(1), "{m}: Other-slot stubs kept");
            assert!(!c.contains(2), "{m}: the GET stub is still pruned");
        }
        // ...but full verification still returns only the truly matching one.
        let imp = imposter(&[
            json!([{"equals": {"method": "TRACE"}}]),
            json!([{"equals": {"method": "CONNECT"}}]),
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "CONNECT",
                "/x",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            Some(1)
        );
    }

    // AC1: one load yields the stubs and an index built over those exact stubs. The two cannot
    // diverge — there is no second ArcSwap to tear against — and that must survive mutation.
    #[test]
    fn snapshot_stubs_and_index_are_one_unit() {
        let imp = imposter(&[json!([{"equals": {"path": "/a"}}])]);
        for n in 1..6usize {
            let snap = imp.snapshot();
            assert_eq!(
                snap.stubs().len(),
                snap.index().len(),
                "index spans exactly the stubs it was loaded with"
            );
            // Every candidate id must be a valid index into the same load's stub vector.
            let c = snap.candidates("GET", "/a");
            assert!(c.iter().all(|i| i < snap.stubs().len()));
            drop(snap);

            let stub = serde_json::from_value(json!({
                "predicates": [{"equals": {"path": format!("/p{n}")}}],
                "responses": [{ "is": { "statusCode": 200 } }]
            }))
            .expect("valid stub");
            imp.add_stub(stub, None);
        }
        let snap = imp.snapshot();
        assert_eq!(snap.stubs().len(), 6);
        assert_eq!(snap.index().len(), 6);
    }

    // AC3: rebuilding on stub reload keeps the index consistent with the new stubs.
    #[test]
    fn index_rebuilt_on_replace_stubs() {
        let imp = imposter(&[json!([{"equals": {"path": "/old"}}])]);
        let no_headers: HashMap<String, String> = HashMap::new();
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "GET",
                "/old",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            Some(0)
        );

        let new_stub =
            serde_json::from_value(json!({ "predicates": [{"equals": {"path": "/new"}}], "responses": [{ "is": { "statusCode": 200 } }] }))
                .expect("valid stub");
        imp.replace_stubs(vec![new_stub]);

        // Old path no longer matches; new path does — proves the index was rebuilt, not stale.
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "GET",
                "/old",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            None
        );
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "GET",
                "/new",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            Some(0)
        );
    }

    // AC2: a match-all (empty-predicate) stub declared BEFORE an anchored stub must still win —
    // the index (fallback, low index) can never let a higher-index anchor jump declaration order.
    #[test]
    fn match_all_before_anchor_wins() {
        let imp = imposter(&[
            json!([]),                           // 0 match-all (fallback)
            json!([{"equals": {"path": "/a"}}]), // 1 exact anchor
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        // /a matches both; the earlier match-all (stub 0) wins in both the indexed and linear paths.
        assert_eq!(
            idx(imp.find_matching_stub_linear("GET", "/a", &no_headers, None, None, None, None)),
            Some(0)
        );
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "GET",
                "/a",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            Some(0),
            "the earlier match-all stub must win over the anchored stub"
        );
    }

    /// A randomized stub corpus spanning every dimension the index prunes on (method, path, and —
    /// since #709 — path regexes) and every shape it must *not* prune on (body/exists regexes,
    /// or/not/and, caseSensitive, except, selector, non-string patterns, invalid patterns, empty).
    /// Seeded, so a differential failure is reproducible from the seed alone.
    fn random_corpus(rng: &mut StdRng, n: usize) -> Vec<Value> {
        const METHODS: &[&str] = &["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "TRACE"];
        const SEGS: &[&str] = &["/a", "/b", "/api/v1", "/api/v2", "/x/y", "/mid"];
        (0..n)
            .map(|_| {
                let seg = SEGS[rng.random_range(0..SEGS.len())];
                let m = METHODS[rng.random_range(0..METHODS.len())];
                match rng.random_range(0..36) {
                    // Indexable on both dimensions (one predicate, two fields).
                    0 => json!([{"equals": {"method": m, "path": seg}}]),
                    // Indexable on both dimensions (two separate top-level predicates).
                    1 => json!([{"equals": {"method": m}}, {"equals": {"path": seg}}]),
                    // Method-only: prunable by method, always-candidate on path.
                    2 => json!([{"equals": {"method": m}}]),
                    // Path-only: prunable by path, always-candidate on method.
                    3 => json!([{"equals": {"path": seg}}]),
                    4 => json!([{"startsWith": {"path": seg}}]),
                    5 => json!([{"contains": {"path": seg}}]),
                    // Indexable on the regex dimension (#709): a top-level `matches` on `path`.
                    6 => json!([{"matches": {"path": format!("^{seg}[0-9]*$")}}]),
                    // Case-sensitive regex — the other automaton.
                    7 => json!([{"matches": {"path": format!("^{seg}$")}, "caseSensitive": true}]),
                    // Inline flags must override the automaton's default in both directions.
                    8 => json!([{"matches": {"path": format!("(?i)^{seg}[0-9]*$")}}]),
                    9 => json!([{"matches": {"path": format!("(?-i)^{seg}[0-9]*$")}}]),
                    // Unanchored regex — `which_overlapping_matches` must agree with `is_match`.
                    10 => json!([{"matches": {"path": "[0-9]+"}}]),
                    // Regex shapes the dimension must NOT index — all must stay always-candidates.
                    11 => json!([{"matches": {"path": format!("^{seg}$"), "except": "X"}}]),
                    12 => json!([{"matches": {"path": format!("^{seg}$")}, "jsonpath": {"selector": "$.id"}}]),
                    13 => json!([{"matches": {"path": 7}}]),
                    14 => json!([{"matches": {"path": "^/unclosed["}}]),
                    15 => json!([{"or": [{"equals": {"method": m}}, {"matches": {"path": format!("^{seg}$")}}]}]),
                    16 => json!([{"not": {"equals": {"path": seg}}}]),
                    17 => json!([{"equals": {"method": m}, "caseSensitive": true}]),
                    18 => json!([{"equals": {"method": m}, "except": "X"}]),
                    // Literal shapes (#710). `endsWith` was never indexed before it, and the
                    // case-sensitive and empty-literal shapes are the edges the issue names.
                    20 => json!([{"endsWith": {"path": seg}}]),
                    21 => json!([{"startsWith": {"path": seg}, "caseSensitive": true}]),
                    22 => json!([{"contains": {"path": seg}, "caseSensitive": true}]),
                    23 => json!([{"endsWith": {"path": seg}, "caseSensitive": true}]),
                    // An empty literal is an unconditional pass in the evaluator — it must never
                    // be pruned.
                    24 => json!([{"contains": {"path": ""}}]),
                    25 => json!([{"startsWith": {"path": ""}}]),
                    // A deliberately broad literal, drawn from the same SEGS as the anchored
                    // shapes so it frequently OVERLAPS one of them on the same path — the shape
                    // that distinguishes an all-reporting automaton from a single-winner one.
                    26 => json!([{"contains": {"path": "/"}}]),
                    27 => json!([{"startsWith": {"path": &seg[..2.min(seg.len())]}}]),
                    // A deliberately BROAD path regex, drawn from the same `SEGS` as the anchored
                    // shapes above so it frequently overlaps one of them on the same path. Two
                    // patterns matching one path is the only shape that can distinguish
                    // `MatchKind::All` from the meta engine's `LeftmostFirst` default, and without
                    // a shape that reliably produces it this oracle cannot see that whole class of
                    // under-approximation — it passed against exactly that bug during #709.
                    19 => json!([{"matches": {"path": format!("^{seg}")}}]),
                    // deepEquals-body (#708): eligible object/array bodies the body-hash dimension
                    // indexes, drawn from the same templates the request generator sends so they
                    // frequently match — the shape that exercises the dimension, not just its always
                    // set. `caseSensitive`/json-in-string are the carve-outs that must stay always.
                    28 => json!([{"deepEquals": {"body": {"k": 1}}}]),
                    29 => json!([{"deepEquals": {"body": [1, 2]}}]),
                    30 => json!([{"deepEquals": {"body": {"n": {"a": 1}}}}]),
                    31 => json!([{"deepEquals": {"body": {"k": 1}}, "caseSensitive": true}]),
                    // equals-on-body (#767): field-level equals the quamina dimension indexes,
                    // drawn from the same body templates the request generator sends so they
                    // frequently match. Case 32's numeric `{"k":1}` is deliberately hit by the
                    // request body `{"k":"1"}` too — the string-coercion axis the dimension must
                    // mirror (a type-matching automaton would under-approximate here). 34/35 are
                    // the carve-outs (caseSensitive, json-in-string leaf) that must stay `always`.
                    32 => json!([{"equals": {"body": {"k": 1}}}]),
                    33 => json!([{"equals": {"body": {"n": {"a": 1}}}}]),
                    34 => json!([{"equals": {"body": {"k": 1}}, "caseSensitive": true}]),
                    35 => json!([{"equals": {"body": {"j": "{\"x\":1}"}}}]),
                    _ => json!([]),
                }
            })
            .collect()
    }

    // AC2 (the load-bearing correctness gate): over a randomized corpus, the indexed path must
    // return exactly the stub the linear oracle returns — same index, same first-match-wins order —
    // for every request. This is a *characterization* gate: it holds for the pre-#707 index too, and
    // must keep holding through the snapshot/bitset refactor and every dimension added on top of it
    // (#708/#709/#710/#767). Any dimension that under-approximates (prunes a stub that could match)
    // fails here.
    #[test]
    fn differential_index_matches_linear_oracle() {
        const METHODS: &[&str] = &[
            "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "TRACE", "get",
        ];
        const PATHS: &[&str] = &[
            "/a",
            "/b",
            "/A",
            "/api/v1",
            "/api/v2",
            "/api/v1/deep",
            "/x/y",
            "/x-mid-y",
            "/mid",
            "/zzz",
            "/a0",
            "/GETX",
        ];
        let mut rng = StdRng::seed_from_u64(0x0707_5EED);
        let no_headers: HashMap<String, String> = HashMap::new();

        // Several independent corpora, so the assertion isn't hostage to one lucky stub layout.
        for corpus_n in 0..8 {
            let imp = imposter(&random_corpus(&mut rng, 40));
            for _ in 0..1250 {
                let m = METHODS[rng.random_range(0..METHODS.len())];
                let p = PATHS[rng.random_range(0..PATHS.len())];
                // Mix non-JSON, absent, and several JSON bodies — exact matches, a type-coercion
                // variant, an array, a JSON-in-string leaf (the bail path), a nested object, and a
                // superset body — so the body-hash (#708) AND body-field (#767) dimensions are both
                // exercised against the linear oracle. `{"k":"1"}` (string) must still match a
                // numeric equals stub; `{"k":1,"z":9}` matches the equals-subset stub but NOT the
                // length-exact deepEquals stub, so the two body dimensions diverge on it.
                let body = match rng.random_range(0..9) {
                    0 => Some("ping"),
                    1 => Some(r#"{"k":1}"#),
                    2 => Some(r#"{"k":"1"}"#),
                    3 => Some(r#"[1,2]"#),
                    4 => Some(r#"{"n":{"a":1}}"#),
                    5 => Some(r#"{"j":"{\"x\":1}"}"#),
                    6 => Some(r#"{"k":1,"z":9}"#),
                    7 => None,
                    // deepEquals compares arrays as multisets (#1579): stub 29's `[1,2]` matches.
                    _ => Some(r#"[2,1]"#),
                };
                let query = if rng.random_bool(0.25) {
                    Some("a=1")
                } else {
                    None
                };

                let linear =
                    idx(imp.find_matching_stub_linear(m, p, &no_headers, query, body, None, None));
                let indexed = idx(imp.find_matching_stub_with_client(
                    m,
                    p,
                    &no_headers,
                    query,
                    body,
                    None,
                    None,
                ));
                assert_eq!(
                    indexed, linear,
                    "index diverged from linear oracle: corpus {corpus_n}, {m} {p} q={query:?} b={body:?}"
                );
            }
        }
    }

    // ---- issue #710: the literal dimension -----------------------------------------------

    // AC1: one pass answers which of N literals match — a request targeting one stub out of many
    // literal-anchored stubs must leave a small candidate set, not all N. Before #710 the prefix
    // and contains buckets were walked linearly, so the prefilter itself scaled with the number of
    // distinct literals even though one stub matched.
    #[test]
    fn literal_dimension_collapses_candidates() {
        let mut preds: Vec<Value> = Vec::new();
        for i in 0..200 {
            preds.push(json!([{"startsWith": {"path": format!("/pre{i}/")}}]));
            preds.push(json!([{"contains": {"path": format!("~mid{i}~")}}]));
            preds.push(json!([{"endsWith": {"path": format!("/end{i}")}}]));
        }
        let snap = snapshot(&preds);

        // A startsWith target: only its own stub survives.
        let c = snap.candidates("GET", "/pre199/detail");
        assert_eq!(c.count(), 1, "one startsWith stub survives");
        assert!(c.contains(199 * 3));

        // A contains target.
        let c = snap.candidates("GET", "/x~mid150~y");
        assert_eq!(c.count(), 1, "one contains stub survives");
        assert!(c.contains(150 * 3 + 1));

        // An endsWith target — a kind the index could not see at all before #710.
        let c = snap.candidates("GET", "/whatever/end42");
        assert_eq!(c.count(), 1, "one endsWith stub survives");
        assert!(c.contains(42 * 3 + 2));

        // A path no literal matches prunes everything.
        assert_eq!(snap.candidates("GET", "/nothing").count(), 0);
    }

    // The #709 lesson, applied: a multi-pattern automaton must report EVERY matching pattern, not
    // just one. `MatchKind::LeftmostFirst`/`LeftmostLongest` + a non-overlapping search would
    // report a single winner per position and silently prune the others' stubs — an
    // under-approximation. Only `MatchKind::Standard` + an overlapping search reports all.
    // Every literal here is matched by the one path, in all three kinds and both nesting shapes.
    #[test]
    fn overlapping_literals_are_all_candidates() {
        let snap = snapshot(&[
            json!([{"startsWith": {"path": "/api"}}]), // 0 prefix of the path
            json!([{"startsWith": {"path": "/api/v1"}}]), // 1 longer prefix — overlaps 0
            json!([{"contains": {"path": "api"}}]),    // 2 substring — overlaps 0 and 1
            json!([{"contains": {"path": "api/v1/x"}}]), // 3 longer substring
            json!([{"endsWith": {"path": "/x"}}]),     // 4 suffix
            json!([{"endsWith": {"path": "v1/x"}}]),   // 5 longer suffix — overlaps 4
            json!([{"contains": {"path": "/"}}]),      // 6 occurs many times over
        ]);
        let c = snap.candidates("GET", "/api/v1/x");
        for i in 0..7 {
            assert!(
                c.contains(i),
                "stub {i}'s literal matches /api/v1/x and must survive — every overlapping \
                 pattern must be reported"
            );
        }
    }

    // The empty literal is an unconditional pass in the evaluator: `contains_ignore_ascii_case`
    // returns true on an empty needle, and starts/ends reduce to comparing an empty slice. The
    // case-sensitive side agrees (`"x".contains("") == true`). So an empty-literal stub must be a
    // candidate for EVERY path — the one edge the issue calls out by name.
    #[test]
    fn empty_literal_always_matches() {
        let imp = imposter(&[
            json!([{"contains": {"path": ""}}]),   // 0
            json!([{"startsWith": {"path": ""}}]), // 1
            json!([{"endsWith": {"path": ""}}]),   // 2
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [("GET", "/anything"), ("GET", "/"), ("POST", "/x/y/z")] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
            assert_eq!(
                linear,
                Some(0),
                "the empty contains stub matches everything"
            );
        }
        // All three stay candidates regardless of path.
        let snap = snapshot(&[
            json!([{"contains": {"path": ""}}]),
            json!([{"startsWith": {"path": ""}}]),
            json!([{"endsWith": {"path": ""}}]),
        ]);
        let c = snap.candidates("GET", "/zzz");
        for i in 0..3 {
            assert!(
                c.contains(i),
                "empty-literal stub {i} must always be a candidate"
            );
        }
    }

    // The case flag routes to the CS or CI automaton, and the fold must be the evaluator's:
    // byte-level ASCII (`eq_ignore_ascii_case`), which is exactly aho-corasick's
    // `ascii_case_insensitive`. Asserted against the linear oracle, including the non-ASCII
    // boundary where an ASCII fold deliberately does NOT fold (the Greek-sigma trap #707 documents).
    #[test]
    fn literal_case_semantics_match_the_evaluator() {
        let imp = imposter(&[
            json!([{"startsWith": {"path": "/Pre"}}]), // 0 default => ASCII case-insensitive
            json!([{"startsWith": {"path": "/Pre2"}, "caseSensitive": true}]), // 1 case-sensitive
            json!([{"contains": {"path": "MiD"}}]),    // 2 CI contains
            json!([{"contains": {"path": "MiD2"}, "caseSensitive": true}]), // 3 CS contains
            json!([{"endsWith": {"path": "/End"}}]),   // 4 CI endsWith
            json!([{"endsWith": {"path": "/End2"}, "caseSensitive": true}]), // 5 CS endsWith
            json!([{"startsWith": {"path": "/ΟΣ"}}]),  // 6 non-ASCII: ASCII fold leaves Greek alone
            json!([{"contains": {"path": "ΑΣ"}}]),     // 7 the same via contains
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [
            ("GET", "/pre/x"),
            ("GET", "/PRE/x"),
            ("GET", "/Pre2/x"),
            ("GET", "/pre2/x"),
            ("GET", "/a-mid-b"),
            ("GET", "/a-MiD-b"),
            ("GET", "/a-MiD2-b"),
            ("GET", "/a-mid2-b"),
            ("GET", "/x/end"),
            ("GET", "/x/END"),
            ("GET", "/x/End2"),
            ("GET", "/x/end2"),
            ("GET", "/ΟΣΑ"),
            ("GET", "/οσα"),
            ("GET", "/xΑΣy"),
        ] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }
    }

    // The soundness rule for the literal dimension: every shape it cannot index must stay a
    // candidate for EVERY request. `except` rewrites the compared value, `selector` re-scopes it,
    // a non-string literal is still a real constraint (the evaluator renders it), and or/not/and
    // nesting is not a required top-level constraint.
    #[test]
    fn ineligible_literal_shapes_are_always_candidates() {
        let snap = snapshot(&[
            json!([{"startsWith": {"path": "/idx"}}]), // 0 indexable
            json!([{"startsWith": {"path": "/x"}, "except": "Y"}]), // 1 except
            json!([{"contains": {"path": "/x"}, "jsonpath": {"selector": "$.id"}}]), // 2 selector
            json!([{"or": [{"startsWith": {"path": "/x"}}, {"equals": {"path": "/y"}}]}]), // 3 or
            json!([{"not": {"contains": {"path": "/x"}}}]), // 4 not
            json!([{"and": [{"endsWith": {"path": "/x"}}, {"equals": {"method": "GET"}}]}]), // 5 and
            json!([{"contains": {"body": "ping"}}]), // 6 non-path field
            json!([{"startsWith": {"path": 7}}]),    // 7 non-string literal
        ]);
        let c = snap.candidates("GET", "/other");
        assert!(!c.contains(0), "the indexable /idx stub must be pruned");
        for i in 1..8 {
            assert!(
                c.contains(i),
                "stub {i} is un-indexable → must always be a candidate"
            );
        }
    }

    // ---- issue #709: the regex dimension -------------------------------------------------

    // AC1: the dimension answers "which of these N patterns match" in one pass — a request that
    // targets one stub out of many regex-anchored stubs must leave exactly that one candidate.
    // Before #709 every regex stub was `always_bits`, so all N were candidates for every request
    // and Stage 2 ran N regex executions. This is the headline the `regex_anchored` bench measures.
    #[test]
    fn regex_dimension_collapses_candidates() {
        let preds: Vec<Value> = (0..100)
            .map(|i| json!([{"matches": {"path": format!("^/api/endpoint{i}$")}}]))
            .collect();
        let snap = snapshot(&preds);

        for target in [0usize, 42, 99] {
            let c = snap.candidates("GET", &format!("/api/endpoint{target}"));
            assert_eq!(
                c.count(),
                1,
                "exactly one regex stub survives for /api/endpoint{target}"
            );
            assert!(
                c.contains(target),
                "the {target}-anchored stub is the survivor"
            );
        }
        // A path no pattern matches prunes every stub.
        assert_eq!(snap.candidates("GET", "/nothing").count(), 0);
    }

    // #731: `MultiRegex::mark` reuses a thread-local `PatternSet` (grow-then-clear). Verify the
    // reuse is correct when (a) automata of different `pattern_len` run on the same thread — a
    // larger capacity must not leak stale pids into a smaller search — and (b) both regex case
    // classes run within one request's `select`, i.e. `mark` is called twice in a row.
    #[test]
    fn regex_scratch_reuse_is_correct() {
        // (a) Large automaton first — grows the thread-local scratch capacity to 100.
        let big: Vec<Value> = (0..100)
            .map(|i| json!([{"matches": {"path": format!("^/e{i}$")}}]))
            .collect();
        let big_snap = snapshot(&big);
        assert_eq!(candidate_ids(&big_snap, "GET", "/e42"), vec![42]);

        // (b) Then a small automaton on the same thread — reuses the larger scratch via `clear`;
        // `iter` must yield only this search's pids, none left over from the 100-pattern search.
        let small = snapshot(&[
            json!([{"matches": {"path": "^/only$"}}]),
            json!([{"matches": {"path": "^/other$"}}]),
        ]);
        assert_eq!(candidate_ids(&small, "GET", "/only"), vec![0]);
        assert!(candidate_ids(&small, "GET", "/nomatch").is_empty());

        // (c) Two case classes in one request → `mark` runs twice sequentially on this thread.
        let mixed = snapshot(&[
            json!([{"matches": {"path": "^/mix$"}}]), // 0 default (case-insensitive) class
            json!([{"matches": {"path": "^/MIX$"}, "caseSensitive": true}]), // 1 case-sensitive class
        ]);
        assert_eq!(candidate_ids(&mixed, "GET", "/mix"), vec![0]);
        assert_eq!(candidate_ids(&mixed, "GET", "/MIX"), vec![0, 1]);

        // (d) Back to the large automaton on the same thread — scratch already at capacity 100.
        assert_eq!(candidate_ids(&big_snap, "GET", "/e7"), vec![7]);
    }

    // #731: `PathDimension::select` probes the map with the borrowed `&str` when the request path
    // has no uppercase ASCII byte (no allocation) and folds only when one is present. Both branches
    // must resolve identically to the previous fold-always behavior.
    #[test]
    fn path_dimension_fast_path_matches_regardless_of_case() {
        let snap = snapshot(&[
            json!([{"equals": {"path": "/users"}}]), // 0 anchor folds to "/users"
            json!([{"equals": {"path": "/Admin"}}]), // 1 anchor folds to "/admin"
        ]);
        // Already-lowercase request → borrowed-&str fast path, matches stub 0.
        assert_eq!(candidate_ids(&snap, "GET", "/users"), vec![0]);
        // Uppercase in the request → folded, matches stub 1's folded anchor.
        assert_eq!(candidate_ids(&snap, "GET", "/ADMIN"), vec![1]);
        // Lowercase request equal to the folded anchor also matches via the fast path.
        assert_eq!(candidate_ids(&snap, "GET", "/admin"), vec![1]);
        assert!(candidate_ids(&snap, "GET", "/nope").is_empty());
    }

    // The regex dimension must report EVERY pattern that matches a path, not just the
    // leftmost-first winner. Two patterns in one case class that can both match the same path is
    // the ONLY shape that distinguishes `MatchKind::All` from the meta engine's default
    // (`LeftmostFirst`) — under the default, `which_overlapping_matches` reports one of them and
    // the other stub is silently pruned even though its regex matches. Regression test for exactly
    // that under-approximation, which every mutually-exclusive-pattern test above cannot see.
    #[test]
    fn overlapping_patterns_are_all_candidates() {
        let snap = snapshot(&[
            json!([{"matches": {"path": "^/api"}}]),      // 0 broad
            json!([{"matches": {"path": "^/api/v1$"}}]),  // 1 specific — both match /api/v1
            json!([{"matches": {"path": "[0-9]+"}}]),     // 2 unanchored — matches /a0
            json!([{"matches": {"path": "^/a[0-9]*$"}}]), // 3 anchored — also matches /a0
        ]);
        let c = snap.candidates("GET", "/api/v1");
        assert!(
            c.contains(0) && c.contains(1),
            "both overlapping /api patterns must survive (earlier masking later)"
        );
        let c = snap.candidates("GET", "/a0");
        assert!(
            c.contains(2) && c.contains(3),
            "both overlapping /a0 patterns must survive (later masking earlier)"
        );

        // ...and the end-to-end consequence: a stub whose pattern matches must stay reachable even
        // when an earlier stub's pattern also matches the same path but the earlier stub is
        // rejected by Stage 2 on another field.
        let imp = imposter(&[
            json!([{"matches": {"path": "^/api"}}, {"equals": {"method": "POST"}}]),
            json!([{"matches": {"path": "^/api/v1$"}}]),
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        assert_eq!(
            idx(imp.find_matching_stub_with_client(
                "GET",
                "/api/v1",
                &no_headers,
                None,
                None,
                None,
                None
            )),
            Some(1),
            "the GET must fall through the POST-gated stub to the stub that matches"
        );
    }

    // AC4 (the load-bearing semantics test): `matches` does NOT fold like the other operators.
    // `fields.rs:227` builds the regex as `cached_regex(pattern, !case_sensitive)`, i.e. the
    // default is `RegexBuilder::case_insensitive(true)` — the regex crate's *Unicode* fold, not
    // the ASCII `eq_ignore_ascii_case` the path dimension's `fold()` mirrors. The dimension must
    // reproduce the evaluator's fold exactly, for case-sensitive, case-insensitive, and
    // inline-flag patterns alike — so this asserts against the linear oracle, not against a
    // hand-written expectation.
    #[test]
    fn regex_dimension_case_semantics_match_the_evaluator() {
        let imp = imposter(&[
            json!([{"matches": {"path": "^/Case$"}}]), // 0 default => Unicode case-INsensitive
            json!([{"matches": {"path": "^/Case2$"}, "caseSensitive": true}]), // 1 case-sensitive
            json!([{"matches": {"path": "(?i)^/inline$"}, "caseSensitive": true}]), // 2 inline (?i) overrides CS
            json!([{"matches": {"path": "(?-i)^/noinline$"}}]), // 3 inline (?-i) overrides the CI default
            json!([{"matches": {"path": "^/ünï$"}}]), // 4 non-ASCII under the Unicode fold
            json!([{"matches": {"path": "^/STRASSE$"}}]), // 5 non-ASCII fold edge
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [
            ("GET", "/case"),
            ("GET", "/Case"),
            ("GET", "/CASE"),
            ("GET", "/case2"),
            ("GET", "/Case2"),
            ("GET", "/inline"),
            ("GET", "/INLINE"),
            ("GET", "/noinline"),
            ("GET", "/NOINLINE"),
            ("GET", "/ünï"),
            ("GET", "/ÜNÏ"),
            ("GET", "/strasse"),
            ("GET", "/STRASSE"),
            ("GET", "/straße"),
        ] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }
    }

    // AC2 + the soundness rule: every regex shape the dimension cannot index must stay a candidate
    // for EVERY request. `except` rewrites the compared value and `selector` re-scopes it, so
    // neither can be matched against the raw path; a non-string pattern is still a real constraint
    // (the evaluator renders it via `to_string`); and or/not/and nesting is not a *required*
    // top-level constraint. Under-approximating any of these is a silent no-match.
    #[test]
    fn ineligible_regex_shapes_are_always_candidates() {
        let snap = snapshot(&[
            json!([{"matches": {"path": "^/idx$"}}]), // 0 indexable
            json!([{"matches": {"path": "^/x$"}, "except": "Y"}]), // 1 except rewrites the value
            json!([{"matches": {"path": "^/x$"}, "jsonpath": {"selector": "$.id"}}]), // 2 selector
            json!([{"or": [{"matches": {"path": "^/x$"}}, {"equals": {"path": "/y"}}]}]), // 3 or
            json!([{"not": {"matches": {"path": "^/x$"}}}]), // 4 not
            json!([{"and": [{"matches": {"path": "^/x$"}}, {"equals": {"method": "GET"}}]}]), // 5 and
            json!([{"matches": {"body": "^ping$"}}]), // 6 non-path field
            json!([{"matches": {"path": 7}}]),        // 7 non-string pattern is still a constraint
            json!([{"matches": {"path": "^/unclosed["}}]), // 8 invalid pattern never compiles
        ]);
        // A path matching no indexable pattern: only stubs the dimension cannot index may survive.
        let c = snap.candidates("GET", "/other");
        assert!(!c.contains(0), "the indexable /idx stub must be pruned");
        for i in [1, 2, 3, 4, 5, 6, 7, 8] {
            assert!(
                c.contains(i),
                "stub {i} is un-indexable → must always be a candidate"
            );
        }
    }

    // AC2: an invalid pattern must not take the whole automaton down with it. `new_many` fails on
    // the first bad pattern in the set, so a single typo'd stub would otherwise cost every other
    // regex stub its pruning. The bad stub lands in always_bits (sound: the evaluator's
    // `build_regex` returns None → the predicate is false → it never matches anyway) while its
    // well-formed neighbours keep being indexed.
    #[test]
    fn invalid_pattern_does_not_disable_the_dimension() {
        let imp = imposter(&[
            json!([{"matches": {"path": "^/good1$"}}]),
            json!([{"matches": {"path": "^/unclosed["}}]), // never compiles
            json!([{"matches": {"path": "^/good2$"}}]),
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [
            ("GET", "/good1"),
            ("GET", "/good2"),
            ("GET", "/unclosed["),
            ("GET", "/other"),
        ] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }

        // The valid neighbours are still pruned by the dimension — the bad pattern only costs
        // itself.
        let snap = snapshot(&[
            json!([{"matches": {"path": "^/good1$"}}]),
            json!([{"matches": {"path": "^/unclosed["}}]),
            json!([{"matches": {"path": "^/good2$"}}]),
        ]);
        let c = snap.candidates("GET", "/good1");
        assert!(c.contains(0), "the matching stub survives");
        assert!(
            !c.contains(2),
            "the non-matching valid stub is still pruned"
        );
        assert!(c.contains(1), "the invalid-pattern stub stays a candidate");
    }

    // AC2: a pattern the many-build rejects on size lands its stub in always_bits and leaves
    // behaviour unchanged — the index degrades to the pre-#709 fallback for that stub rather than
    // pruning it or failing the build.
    #[test]
    fn oversized_regex_set_falls_back_to_always_bits() {
        // A bounded repeat of a large Unicode class explodes the NFA well past NFA_SIZE_LIMIT.
        let huge = format!("^/{}$", r"\p{L}{5000}".repeat(4));
        let imp = imposter(&[
            json!([{"matches": {"path": huge}}]),
            json!([{"matches": {"path": "^/small$"}}]),
        ]);
        let no_headers: HashMap<String, String> = HashMap::new();
        for (m, p) in [("GET", "/small"), ("GET", "/abc"), ("GET", "/other")] {
            let linear =
                idx(imp.find_matching_stub_linear(m, p, &no_headers, None, None, None, None));
            let indexed =
                idx(imp.find_matching_stub_with_client(m, p, &no_headers, None, None, None, None));
            assert_eq!(indexed, linear, "index diverged from linear for {m} {p}");
        }
        // The oversized stub is never pruned; its well-formed neighbour still is.
        let snap = snapshot(&[
            json!([{"matches": {"path": huge}}]),
            json!([{"matches": {"path": "^/small$"}}]),
        ]);
        let c = snap.candidates("GET", "/nothing-matches");
        assert!(
            c.contains(0),
            "the oversized-pattern stub must stay a candidate"
        );
        assert!(!c.contains(1), "the small-pattern stub is still pruned");
    }

    // AC2: the fallback is *logged* at build, naming the stub and the offending pattern. Without
    // this an operator whose stub quietly stopped being indexed (a latency regression, not a
    // behaviour change) has nothing to correlate against.
    #[traced_test]
    #[test]
    fn rejected_pattern_warns_at_build_naming_the_stub() {
        let huge = format!("^/{}$", r"\p{L}{5000}".repeat(4));
        let _snap = snapshot(&[
            json!([{"matches": {"path": "^/small$"}}]),
            json!([{"matches": {"path": huge}}]),
        ]);
        assert!(
            logs_contain("regex dimension: pattern rejected by the multi-pattern build"),
            "the rejected pattern must be warned about at build time"
        );
        assert!(
            logs_contain("stub=1"),
            "the warn must name which stub lost its index"
        );
    }

    // Issue #475: the has_scenario_gate flag — computed once at index build — detects a
    // `requiredScenarioState` stub so the bounded matcher offloads the gate's flow-store read to
    // spawn_blocking on a blocking backend, while a scenario-free set keeps the inline fast path.
    #[test]
    fn has_scenario_gate_detects_required_scenario_state() {
        let build = |v: Value| {
            let states: Vec<Arc<StubState>> = v
                .as_array()
                .expect("array")
                .iter()
                .map(|s| {
                    Arc::new(StubState::new(
                        serde_json::from_value(s.clone()).expect("stub"),
                    ))
                })
                .collect();
            StubSnapshot::build(states)
        };
        let ungated = build(json!([
            { "predicates": [{"equals": {"path": "/a"}}], "responses": [{"is": {"statusCode": 200}}] }
        ]));
        assert!(!ungated.has_scenario_gate());

        let gated = build(json!([
            {
                "predicates": [{"equals": {"path": "/a"}}],
                "scenarioName": "sc",
                "requiredScenarioState": "started",
                "responses": [{"is": {"statusCode": 200}}]
            }
        ]));
        assert!(gated.has_scenario_gate());
    }

    // Issue #476: the has_inject gate — computed once at index build — detects an inject
    // predicate anywhere in a stub's predicate tree, including nested under and/or/not, and
    // stays false for scriptless stub sets so they keep the inline matching fast path.
    #[test]
    fn has_inject_detects_top_level_and_nested() {
        let scriptless = StubSnapshot::build(stub_states(&[
            json!([{"equals": {"path": "/a"}}]),
            json!([{"and": [{"equals": {"path": "/b"}}, {"exists": {"query": {"q": true}}}]}]),
        ]));
        assert!(!scriptless.has_inject());

        let top_level = StubSnapshot::build(stub_states(&[
            json!([{"equals": {"path": "/a"}}]),
            json!([{"inject": "function (config) { return true; }"}]),
        ]));
        assert!(top_level.has_inject());

        let under_and = StubSnapshot::build(stub_states(&[json!([
            {"and": [{"equals": {"path": "/a"}}, {"inject": "function (config) { return true; }"}]}
        ])]));
        assert!(under_and.has_inject());

        let under_not_in_or = StubSnapshot::build(stub_states(&[json!([
            {"or": [{"equals": {"path": "/a"}}, {"not": {"inject": "function (config) { return true; }"}}]}
        ])]));
        assert!(under_not_in_or.has_inject());
    }

    // ---- issue #708: deepEquals body-hash dimension ----

    fn deep_body(expected: Value) -> Value {
        json!([{"deepEquals": {"body": expected}}])
    }

    #[test]
    fn body_dimension_collapses_candidates() {
        // 500 deepEquals-body stubs, each expecting a distinct object. A request equal to one must
        // probe down to just that stub — O(stubs) structural comparisons collapse to one hash probe.
        let preds: Vec<Value> = (0..500)
            .map(|i| deep_body(json!({"id": i, "kind": "order"})))
            .collect();
        let snap = snapshot(&preds);

        let target = 437usize;
        let ids = candidate_ids_body(&snap, "POST", "/x", &json!({"id": target, "kind": "order"}));
        assert_eq!(ids.len(), 1, "collapses to a single candidate, got {ids:?}");
        assert_eq!(ids, vec![target]);

        // A body equal to none of them prunes the whole dimension to empty.
        assert!(
            candidate_ids_body(&snap, "POST", "/x", &json!({"id": 9999, "kind": "order"}))
                .is_empty()
        );
    }

    #[test]
    fn body_dimension_matches_across_coercion_key_order_and_case() {
        let snap = snapshot(&[
            deep_body(json!({"a": 1, "b": "x"})), // 0
            deep_body(json!({"a": 2})),           // 1
        ]);
        // number↔string coercion, object key order, and ASCII key/value case all fold to stub 0.
        let ids = candidate_ids_body(&snap, "POST", "/p", &json!({"B": "X", "a": "1"}));
        assert_eq!(ids, vec![0]);
    }

    #[test]
    fn body_dimension_ineligible_stubs_are_never_pruned() {
        let snap = snapshot(&[
            json!([{"deepEquals": {"body": {"a": 1}}, "caseSensitive": true}]), // 0 caseSensitive
            json!([{"deepEquals": {"body": {"a": 1}}, "keyCaseSensitive": true}]), // 1 keyCaseSensitive
            json!([{"deepEquals": {"body": {"a": 1}}, "jsonpath": {"selector": "$.x"}}]), // 2 selector
            json!([{"deepEquals": {"body": "hello"}}]), // 3 scalar body (raw-string compare)
            json!([{"deepEquals": {"body": {"a": "{\"k\":1}"}}}]), // 4 JSON-in-string leaf in expected
            json!([{"deepEquals": {"body": {"a": 1}}, "except": "x"}]), // 5 except (rewrites the value)
            deep_body(json!({"eligible": true})),                       // 6 ELIGIBLE (indexed)
        ]);
        // A body matching only stub 6: the eligible stub is hit by the probe; the six ineligible
        // stubs are `always` and must all remain — none can be hash-pruned.
        let hit = candidate_ids_body(&snap, "POST", "/p", &json!({"eligible": true}));
        assert_eq!(hit, vec![0, 1, 2, 3, 4, 5, 6]);
        // A body matching none: only the eligible stub 6 is pruned; the carve-outs stay candidates.
        let miss = candidate_ids_body(&snap, "POST", "/p", &json!({"zzz": 0}));
        assert_eq!(miss, vec![0, 1, 2, 3, 4, 5]);
    }

    #[test]
    fn body_dimension_keeps_every_stub_a_reordered_body_matches() {
        // deepEquals compares arrays as multisets (#1579), so stubs that differ only in array
        // order all equal a reordered body; an order-sensitive hash would prune all but one.
        let orders = [
            json!({"t": ["a", "b", "c"]}),
            json!({"t": ["c", "b", "a"]}),
            json!({"t": ["b", "c", "a"]}),
            json!({"items": [{"id": 1}, {"id": 2}]}),
            json!({"items": [{"id": 2}, {"id": 1}]}),
            json!({"t": ["a", "b"]}), // 5 a different multiset
        ];
        let preds: Vec<Value> = orders.iter().cloned().map(deep_body).collect();
        let snap = snapshot(&preds);
        assert_eq!(
            candidate_ids_body(&snap, "POST", "/p", &json!({"t": ["c", "a", "b"]})),
            vec![0, 1, 2]
        );
        assert_eq!(
            candidate_ids_body(
                &snap,
                "POST",
                "/p",
                &json!({"items": [{"id": 2}, {"id": 1}]})
            ),
            vec![3, 4]
        );
        // And the stub that serves is the first one, as the linear scan picks it.
        let imp = imposter(&preds);
        let no_headers: HashMap<String, String> = HashMap::new();
        let body = Some(r#"{"t":["b","a","c"]}"#);
        let linear =
            idx(imp.find_matching_stub_linear("POST", "/p", &no_headers, None, body, None, None));
        let indexed = idx(imp.find_matching_stub_with_client(
            "POST",
            "/p",
            &no_headers,
            None,
            body,
            None,
            None,
        ));
        assert_eq!((linear, indexed), (Some(0), Some(0)));
    }

    #[test]
    fn body_dimension_non_json_body_excludes_indexed_stubs() {
        let snap = snapshot(&[
            deep_body(json!({"a": 1})),          // 0 indexed body stub
            json!([{"equals": {"path": "/p"}}]), // 1 path stub
        ]);
        // `candidate_ids` sends no body (the non-JSON/absent case): the indexed body stub cannot
        // match, so it is excluded; the path stub still matches /p.
        assert_eq!(candidate_ids(&snap, "GET", "/p"), vec![1]);
    }

    #[test]
    fn body_dimension_json_in_string_request_widens() {
        let snap = snapshot(&[
            deep_body(json!({"a": {"b": 1}})), // 0 expects a nested object
            deep_body(json!({"z": 9})),        // 1
        ]);
        // The request body carries a JSON-ish string leaf. deepEquals no longer reads it as the
        // object stub 0 expects (#1579), but the hash keeps its bail: the dimension widens to every
        // candidate and Stage-2 decides. (Soundness over precision.)
        let ids = candidate_ids_body(&snap, "POST", "/p", &json!({"a": "{\"b\":1}"}));
        assert_eq!(
            ids,
            vec![0, 1],
            "a JSON-ish string leaf disables pruning for the dimension"
        );
    }
}