1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
|
/**
Copyright (c) Scott Gasch
Module Name:
searchsup.c
Abstract:
Search support routines. See also search.c, root.c, and split.c.
Author:
Scott Gasch ([email protected]) 06 Oct 2005
Revision History:
**/
#include "chess.h"
#include <math.h> // log(), log10() -- _FhBasedExtraPliesF
extern SCORE g_iRootScore[2];
extern ULONG g_uHardExtendLimit;
extern ULONG g_uIterateDepth;
void
UpdatePV(SEARCHER_THREAD_CONTEXT *ctx, MOVE mv)
/**
Routine description:
Update the principle variation at this depth.
Parameters:
SEARCHER_THREAD_CONTEXT *ctx,
MOVE mv
Return value:
void
**/
{
PLY_INFO *this = &(ctx->sPlyInfo[ctx->uPly]);
PLY_INFO *next = (this + 1);
ULONG u = ctx->uPly;
ASSERT(u < MAX_PLY_PER_SEARCH);
this->PV[u] = mv;
u++;
// HASHMOVE/RECOGNMOVE/DRAWMOVE/MATEMOVE/EGTBMOVE are sentinels, not real
// moves -- WalkPV (util.c) treats any of them as a hard PV
// truncation point and asserts the slot right after one is
// always a zero terminator. Copying the child ply's PV tail
// forward below would instead leave whatever move happens to
// already be sitting in that reused sPlyInfo slot (sPlyInfo[] is
// shared across every node that ever occupies this ply, never
// zeroed between unrelated nodes) -- if some earlier, unrelated
// node at this same ply also once wrote the same sentinel there
// and nothing since overwrote it, that stale leftover reproduces
// the sentinel value a second time in a row and trips the assert
// (util.c:1093, found via debug_smoke_test.sh under MP). Hard-
// terminate immediately instead of inheriting the child's tail.
if ((mv.uMove == HASHMOVE.uMove) ||
(mv.uMove == RECOGNMOVE.uMove) ||
(mv.uMove == DRAWMOVE.uMove) ||
(mv.uMove == MATEMOVE.uMove) ||
(mv.uMove == EGTBMOVE.uMove))
{
if (u < MAX_PLY_PER_SEARCH)
{
this->PV[u].uMove = 0;
}
return;
}
while(u < MAX_PLY_PER_SEARCH)
{
this->PV[u] = next->PV[u];
if (0 == this->PV[u].uMove)
{
break;
}
u++;
}
}
FLAG
CheckInputAndTimers(IN SEARCHER_THREAD_CONTEXT *ctx)
/**
Routine description:
This code is called from search when the total number of nodes
searched is a multiple of g_MoveTimer.uNodeCheckMask. Its job is
to check for user input waiting on the input queue and to check to
see if we are over a time limit.
Parameters:
void
Return value:
static FLAG : TRUE if the search should terminate and unroll,
FALSE if the search can continue
**/
{
double dTimeStamp;
//
// See if there's user input to process.
//
if ((ctx->uThreadNumber == 0) && (NumberOfPendingInputEvents() != 0))
{
ParseUserInput(TRUE);
//
// If the user input can be handled in the middle of the
// search then it will have been. If it cannot be handled
// without stopping the search then ParseUserInput will flip
// this bit in the MoveTimer to tell us (any any other
// searcher threads) to stop and unroll.
//
if (WE_SHOULD_STOP_SEARCHING)
{
return(TRUE);
}
}
//
// Also check time limits now.
//
if (-1 != g_MoveTimer.dSoftTimeLimit)
{
dTimeStamp = SystemTimeStamp();
if ((g_MoveTimer.bvFlags & TIMER_CURRENT_OBVIOUS) ||
(g_MoveTimer.bvFlags & TIMER_CURRENT_WONT_UNBLOCK))
{
Trace("OBVIOUS MOVE / WON'T UNBLOCK --> stop searching now\n");
g_MoveTimer.bvFlags |= TIMER_STOPPING;
return(TRUE);
}
if (dTimeStamp > g_MoveTimer.dSoftTimeLimit)
{
//
// If we have exceeded the soft time limit, move now unless...
//
if ((!(g_MoveTimer.bvFlags & TIMER_JUST_OUT_OF_BOOK)) &&
(!(g_MoveTimer.bvFlags & TIMER_ROOT_POSITION_CRITICAL)) &&
(!(g_MoveTimer.bvFlags & TIMER_RESOLVING_ROOT_FL)) &&
(!(g_MoveTimer.bvFlags & TIMER_RESOLVING_ROOT_FH)) &&
(!(g_MoveTimer.bvFlags & TIMER_MANY_ROOT_FLS)) &&
(g_MoveTimer.bvFlags & TIMER_SEARCHING_FIRST_MOVE))
{
Trace("SOFT TIMER (%3.1f sec) --> "
"stop searching now\n",
dTimeStamp - g_MoveTimer.dStartTime);
g_MoveTimer.bvFlags |= TIMER_STOPPING;
return(TRUE);
}
}
//
// If we have exceeded the hard limit, we have to move no matter
// what.
//
if (dTimeStamp > g_MoveTimer.dHardTimeLimit)
{
Trace("HARD TIMER (%3.1f sec) --> "
"stop searching now\n",
dTimeStamp - g_MoveTimer.dStartTime);
g_MoveTimer.bvFlags |= TIMER_STOPPING;
return(TRUE);
}
}
//
// Also check raw node count limit here.
//
if (g_Options.u64MaxNodeCount != 0ULL &&
ctx->sCounters.tree.u64TotalNodeCount > g_Options.u64MaxNodeCount)
{
Trace("NODE COUNT LIMIT (limit %llu, searched %llu) "
"--> stop searching now\n", g_Options.u64MaxNodeCount,
ctx->sCounters.tree.u64TotalNodeCount);
g_MoveTimer.bvFlags |= TIMER_STOPPING;
return(TRUE);
}
return(FALSE);
}
FLAG
ThreadUnderTerminatingSplit(IN SEARCHER_THREAD_CONTEXT *ctx)
{
ULONG u;
//
// A thread can be nested in more than one split at once (a helper
// thread can itself call StartParallelSearch while inside
// HelpSearch for an outer split), so pSplitInfo[] is a stack, not
// a single slot -- slot 0 is the outermost split this thread is
// part of, later slots are progressively more nested ones. Any of
// them terminating means this thread's current work is moot, so
// all populated slots must be checked, not just the first one
// found.
//
for (u = 0; u < NUM_SPLIT_PTRS_IN_CONTEXT; u++)
{
if ((ctx->pSplitInfo[u] != NULL) &&
(ctx->pSplitInfo[u]->fTerminate == TRUE))
{
return(TRUE);
}
}
return(FALSE);
}
// 2026-10-02: moved here from search.c, along with the rest of the
// joint-table-driven graduated-LMR machinery below -- this used to be
// split across two files purely to minimize the original diff against
// HEAD's LMR (GetLMRReduction decided only the baseline -ONE_PLY,
// search.c's move loop did all the bucket/joint-table post-processing
// on top). That split made it easy to reduce FAR less than intended:
// the baseline decision and the "how much more" decision were made
// from two different, inconsistently-strict dynamic signals. Now one
// function makes the whole call.
//
// EstimateHangingMaterialCp/HangCpBucket/GapCpBucket/MoveNumBucket/
// DepthBucket are no longer file-static -- search.c's own joint-table
// COLLECTION instrumentation (the measurement block gated on
// fPruneReduceEligible alone, independent of whether uDepth>TWO_PLY or
// any reduction is actually applied -- this is what's still generating
// the next round of g_uJointFHThousandths data, a live, in-progress
// collection run as of this writing) still needs them, so they're
// declared in chess.h and shared rather than duplicated.
SCORE
EstimateHangingMaterialCp(IN SEARCHER_THREAD_CONTEXT *ctx,
IN MOVE mv,
IN ULONG uMoveNum,
IN BITBOARD bbMinorAttacksSnapshot[2],
IN BITBOARD bbRookAttacksSnapshot[2])
/**
Routine description:
Does this quiet (or losing-capture) move look like it hangs
material? Used as one axis ("dumb") of the joint fail-high
prediction table. "Strictly cheaper" only (an equal-value trade is
routinely fine, not a blunder) and generalized over every piece
type instead of hand-picking specific attacker/victim pairs.
Return value:
SCORE : estimated cp loss (>= 0), or 0 if nothing looks hung -- EXCEPT
for a capture/promotion scored under MOVE_SCORING_IID_RESCORED
(ctx->sPlyInfo[ctx->uPly - 1].eMoveScoringScheme), where the
result can be negative. fPruneReduceEligible only ever admits a
capture/promotion here when generate.c's own SEE sign flagged it
as a LOSING one, so ordinarily ComputeMoveScore's decoded value
is guaranteed negative and this just flips its sign into a
positive loss. But IID rescoring (searchsup.c's
RescoreMovesViaSearch, unconditionally live -- see chess.h's
unconditional `#define DO_IID`) overwrites iValue with a real,
searched eval-axis score for every move at that ply, which can
legitimately disagree with the cheap SEE-sign classification
that got mv into this eligible population in the first place --
a capture that LOOKS like a material-losing trade can still be
the actual best move in the position (a real tactic SEE can't
see), in which case the honest searched score is positive, not
negative, and this function will return a NEGATIVE number here.
2026-10-04: deliberately trust the searched score over the SEE
sign in that case rather than clamping it away -- IID's shallow
search genuinely knows more than a static material exchange
does, and a caller folding this value directly into a margin
calculation WANTS "this move turned out to actually be good" to
look like the opposite of "hung", not like "hung = 0" (this
historically mattered for EFP's margin check, search.c, now
removed -- the reasoning is preserved here in case a future
direct-margin consumer reappears). Callers that need a
true cp-loss-or-zero reading instead (the "dumb" axis feeding
the joint FH table) must go through HangCpBucket, which clamps
exactly this case to bucket 0 rather than asserting it away.
**/
{
POSITION *pos = &ctx->sPosition; // already reflects the position
// AFTER mv (MakeMove already ran)
ULONG uOpponent = pos->uToMove; // side to move now == opponent of
// whoever just moved
BITBOARD bbTo;
SCORE iMoveScore;
ASSERT(ctx->uPly >= 1);
if (IS_CAPTURE_OR_PROMOTION(mv))
{
#ifdef DEBUG
if (mv.pPromoted) {
ASSERT(pos->rgSquare[mv.cTo].pPiece == mv.pPromoted);
}
else
{
ASSERT(pos->rgSquare[mv.cTo].pPiece == mv.pMoved);
}
#endif
// No ASSERT(iMoveScore < 0) here -- see this function's own
// return-value comment above. It was true under every
// generate.c tier-encoded scoring scheme (the only ones in
// play when this ASSERT was written), but IID rescoring can
// legitimately make it false.
iMoveScore = ComputeMoveScore(ctx, mv, uMoveNum);
return -iMoveScore;
}
#ifdef DEBUG
else
{
ASSERT(pos->rgSquare[mv.cTo].pPiece == mv.pMoved);
}
#endif
// A king can't "hang material" in the sense this function measures
// -- it's never capturable, so PIECE_VALUE(KING) (== INFINITY_SCORE)
// has no business feeding into a cp-loss estimate at all. Likewise
// we don't care about "hung pawns", they are not worth enough and
// we can't tell if it's actually hung or not easily.
if (IS_KING(mv.pMoved) || IS_PAWN(mv.pMoved))
{
return 0;
}
// Any non-pawn moved onto a square an enemy pawn attacks --
// always unconditionally bad, a pawn is the cheapest possible
// attacker there is.
if (0 != (g_PawnAttackOriginBB[uOpponent][mv.cTo] & pos->bbPawns[uOpponent]))
{
return (SCORE)(PIECE_VALUE(mv.pMoved) - VALUE_PAWN);
}
// Enemy KING adjacency, checked fresh (real board state, no
// scratch-bitboard involved either way). A king can only capture
// on a square its own side doesn't leave it in check on, so king
// "attacking" our destination square means nothing by itself --
// only flag this when OUR side has zero defenders of the square.
// Pawns excluded, same reasoning as the pawn-attack check above.
if (0 != (g_KingAttacksBB[mv.cTo] & COOR_TO_BB(KingPosition(pos, uOpponent))))
{
ULONG uMover = FLIP(uOpponent);
BITBOARD bbOurDefenders =
_WhoAttacksSquareBB(pos, mv.cTo, uMover, pos->bbOccupied) |
(g_PawnAttackOriginBB[uMover][mv.cTo] & pos->bbPawns[uMover]);
if (0 == bbOurDefenders)
{
return (SCORE)PIECE_VALUE(mv.pMoved);
}
// Defended -- the king alone isn't a threat here. Fall through
// to the minor/rook checks below.
}
// If we're using NNUE eval, cTrapped, bbMinorAttacks, etc... will
// be unset.
if (FALSE == g_fUseNnueEval)
{
// But if we're using the HCE, consult the attack bitboards
// and trapped piece records too.
bbTo = COOR_TO_BB(mv.cTo);
if ((PIECE_VALUE(mv.pMoved) > VALUE_KNIGHT) &&
(0 != (bbMinorAttacksSnapshot[uOpponent] & bbTo)))
{
return (SCORE)(PIECE_VALUE(mv.pMoved) - VALUE_KNIGHT);
}
if ((PIECE_VALUE(mv.pMoved) > VALUE_ROOK) &&
(0 != (bbRookAttacksSnapshot[uOpponent] & bbTo)))
{
return (SCORE)(PIECE_VALUE(mv.pMoved) - VALUE_ROOK);
}
COOR cOwnTrapped = ctx->cTrapped[ctx->uPly - 1];
if (IS_ON_BOARD(cOwnTrapped) && (mv.cFrom != cOwnTrapped))
{
PIECE pTrapped = ctx->pTrapped[ctx->uPly - 1];
#ifdef DEBUG
ASSERT(GET_COLOR(pTrapped) == FLIP(uOpponent));
#endif
return (SCORE)(PIECE_VALUE(pTrapped) / 2);
}
}
return 0;
}
// See chess.h's HANG_CP_BUCKETS comment for the bucket shape.
//
// 2026-10-04: was ASSERT(iHangCp >= 0), on the belief that
// EstimateHangingMaterialCp (its only real producer) could never
// return a negative value. That ASSERT is wrong, not just stale -- see
// EstimateHangingMaterialCp's own return-value comment: IID rescoring
// can legitimately make it negative (a capture SEE-sign flagged as
// losing, but which a real shallow search found is actually the best
// move in the position). A negative input just means "even more
// definitely not hung" than 0 already does, so it belongs in the same
// bucket 0 -- clamp rather than assert.
ULONG
HangCpBucket(SCORE iHangCp)
{
ULONG u;
if (iHangCp <= 0)
{
return 0;
}
u = 1 + (((ULONG)iHangCp - 1) / HANG_CP_BUCKET_WIDTH);
return MINU(u, HANG_CP_BUCKETS - 1);
}
// See chess.h's GAP_CP_BUCKETS comment for the bucket shape. Unlike
// HangCpBucket, the input can legitimately be negative or zero (this
// node's own eval already meets or beats alpha) -- that whole
// non-positive range collapses into bucket 0, same as HANG's "not
// dumb".
ULONG
GapCpBucket(SCORE iGapCp)
{
ULONG u;
if (iGapCp <= 0)
{
return 0;
}
u = 1 + (((ULONG)iGapCp - 1) / GAP_CP_BUCKET_WIDTH);
return MINU(u, GAP_CP_BUCKETS - 1);
}
// See chess.h's IMPROVE_BUCKETS comment for the bucket shape. Unlike
// HangCpBucket/GapCpBucket, there is no single "safe/below-threshold"
// catchall here -- iImprovement is genuinely signed and two-sided (a
// node legitimately being worse than two plies ago is an expected,
// common outcome, not a degenerate corner case), so this buckets both
// tails symmetrically around a center "didn't really move" bucket
// instead of collapsing one whole sign onto bucket 0.
ULONG
ImproveBucket(SCORE iImprovement)
{
// Center bucket (index 5 of 11): "didn't really move" either way.
if ((iImprovement > -IMPROVE_CP_CENTER_WIDTH) &&
(iImprovement < IMPROVE_CP_CENTER_WIDTH))
{
return 5;
}
if (iImprovement > 0)
{
// 6..10: getting better, 100cp-wide bins, 10 is the 500cp+
// overflow.
ULONG u = 6 + (((ULONG)iImprovement - IMPROVE_CP_CENTER_WIDTH) /
IMPROVE_BUCKET_WIDTH);
return MINU(u, IMPROVE_BUCKETS - 1);
}
// 0..4: getting worse, 100cp-wide bins, 0 is the 500cp+ overflow
// (most negative == smallest index, mirroring 6..10's direction).
{
ULONG uMag = (ULONG)(-iImprovement) - IMPROVE_CP_CENTER_WIDTH;
ULONG u = 4 - (uMag / IMPROVE_BUCKET_WIDTH);
if (uMag / IMPROVE_BUCKET_WIDTH >= 5)
{
return 0;
}
return u;
}
}
// See chess.h's GAP_BETA_BUCKETS comment. Unlike ImproveBucket, this
// is called only where the caller has already gated iEval > iBeta
// (the static-NM/beta-table's own eligibility), so iGapBeta is always
// >= 0 here -- no symmetric/center bucket needed, just plain
// 100cp-wide bins from 0, wide enough (2000cp) to find where FH%
// actually saturates.
ULONG
GapBetaBucket(SCORE iGapBeta)
{
ULONG u = (ULONG)iGapBeta / GAP_BETA_BUCKET_WIDTH;
return MINU(u, GAP_BETA_BUCKETS - 1);
}
// See chess.h's MOVE_NUM_BUCKETS comment. uMoveNum is 1-based (the
// caller passes uLegalMoves, right after MakeMove succeeded) -- index
// 0 is never produced.
ULONG
MoveNumBucket(ULONG uMoveNum)
{
ASSERT(uMoveNum >= 1);
return MINU(uMoveNum, MOVE_NUM_BUCKETS - 1);
}
// See chess.h's SEARCH_DEPTH_BUCKETS comment. uCandDepth is uDepth /
// ONE_PLY, whole plies, legitimately 0 or above.
ULONG
DepthBucket(ULONG uCandDepth)
{
return MINU(uCandDepth, SEARCH_DEPTH_BUCKETS - 1);
}
// Maps this project's raw, marginal-resolution bucket indices (exactly
// what DepthBucket/MoveNumBucket produce, and what the 2026-09-28
// collection run counted against) down to the coarser, cache-shaped
// indices g_uJointFHThousandths was actually baked at. dumb and gap
// pass through unchanged (shipped shape kept them at full marginal
// resolution -- see the plan doc's table). Must stay in exact lockstep
// with bake_joint.py's ship_depth()/ship_late() -- these are the same
// mapping, just re-derived in C for the live lookup path. File-private
// -- only the prediction lookup just below needs the shipped shape;
// search.c's own collection instrumentation counts at full raw
// resolution and never calls these.
static ULONG
_ShipDepthBucket(ULONG uRawDepthBucket)
{
if (uRawDepthBucket <= 9) return uRawDepthBucket;
if (uRawDepthBucket <= 13) return 10;
return 11;
}
static ULONG
_ShipLateBucket(ULONG uRawLateBucket)
{
// 2026-10-21: rewritten to match dual_table_run{,_nnue}/dashboard.py's
// real, data-derived ship_late_17() exactly -- this function had
// drifted out of sync with the actual shipped shape baked into
// data.c (it still had the old 2026-09-30, pre-derive_late_buckets.py
// 15-bucket boundaries; the live table has been 16/17-bucket-shaped
// for a while). MUST stay in exact lockstep with ship_late_17() --
// see that function's own comment for the full raw-bucket story
// (why raw==0 gets its own dedicated slot now, why raw==1 is
// permanently unreachable and harmlessly lumped with raw==2).
if (0 == uRawLateBucket) return 0;
if (uRawLateBucket <= 1) return 1;
if (uRawLateBucket <= 11) return uRawLateBucket - 1;
if (uRawLateBucket <= 13) return 11;
if (uRawLateBucket <= 15) return 12;
if (uRawLateBucket <= 18) return 13;
if (uRawLateBucket <= 21) return 14;
if (uRawLateBucket <= 31) return 15;
return 16;
}
#define JOINT_TABLE_SENTINEL (0xFFFF)
// Decodes generate.c's _ScoreAllMoves packed iValue sort key back
// into one of the FH_COLLECT_TIER tiers (chess.h) -- moved here from
// fhcollect.c (2026-10-24) and made unconditional: fhmodel.c's
// production FH-regression inference needs this classification on
// every build, not just FH_REGRESSION_COLLECTION ones, and this
// function is pure/stateless (just decodes bits already in mv/iValue)
// so there's no reason to keep it gated or duplicated. Does NOT
// distinguish FHC_TIER_NULL -- the null-move probe isn't a real,
// generated move at all (no iValue, no mv to compare), so callers
// identify it directly rather than through this function.
FH_COLLECT_TIER
FhClassifyMoveTier(MOVE mv, MOVE mvHash, FLAG fIsCaptureOrPromotion,
SCORE iValue)
{
if (IS_SAME_MOVE(mv, mvHash))
{
return(FHC_TIER_HASH);
}
// NOT a `TRUE ==` comparison on purpose -- the caller passes
// IS_CAPTURE_OR_PROMOTION(mv) straight through, and that macro is
// `(mv.uMove & 0x0FF00000)`, a bitmask test that returns an
// arbitrary nonzero value, not literally 1/TRUE (confirmed by
// grepping every other real call site in generate.c/searchsup.c/
// search.c -- all plain truthiness, never `TRUE ==`).
if (0 != fIsCaptureOrPromotion)
{
// _ScoreAllMoves adds SORT_THESE_FIRST only to non-negative-SEE
// captures/promotions; a losing capture's iValue never reaches
// it.
return((iValue >= SORT_THESE_FIRST) ?
FHC_TIER_GOOD_CAPTURE : FHC_TIER_LOSING_CAPTURE);
}
// Quiet move. Killer bits take priority over the countermove bonus
// (matches _ScoreAllMoves' own documented priority list).
// COUNTERMOVE_TIER_BONUS shares its low bit with GOOD_MOVE
// (0x03000000 = 0x02000000 | 0x01000000), so it needs an exact
// match, not a bare AND-is-nonzero test, or a plain killer (whose
// bits are all numerically >= GOOD_MOVE too) could be misread as
// a countermove.
if (0 != (iValue & (FIRST_KILLER | SECOND_KILLER | THIRD_KILLER | FOURTH_KILLER)))
{
return(FHC_TIER_KILLER);
}
if (COUNTERMOVE_TIER_BONUS == (iValue & COUNTERMOVE_TIER_BONUS))
{
return(FHC_TIER_COUNTERMOVE);
}
return(FHC_TIER_LEFTOVER_QUIET);
}
// Looks up this move's predicted FH% (thousandths of a percent) from
// the baked joint table, given the four RAW bucket indices (as
// HangCpBucket/GapCpBucket/MoveNumBucket/DepthBucket produce them).
// Returns JOINT_TABLE_SENTINEL both for a genuine below-sample-floor
// cell AND for dumb bucket 1 (1-100cp "hung") -- traced to ~97%
// SEE-scored losing captures/underpromotions misfiled into the
// quiet-move axis (2026-09-28 plan doc), not a real "this move looks
// safe" signal. Treating it as "no data" rather than trusting its
// literal (low) value means it can never justify extra reduction, nor
// withhold it -- it just falls back to whatever the other checks say.
USHORT
_JointTablePredictedFHThousandths(IN ULONG uRawDepthBucket,
IN ULONG uRawDumbBucket,
IN ULONG uRawGapBucket,
IN ULONG uRawLateBucket,
IN ULONG uRawImproveBucket)
{
if (1 == uRawDumbBucket)
{
return JOINT_TABLE_SENTINEL;
}
// 2026-10-21: two tables compiled in (HCE-collected and NNUE-
// collected, see chess.h's g_uJointFHThousandths_NNUE comment) --
// runtime-selected, not a build-time #ifdef, since NNUE eval
// itself is already a runtime switch in this binary. Both flags
// checked (not just g_fUseNnueEval) for the same reason eval.c's
// own NNUE dispatch does: g_fUseNnueEval alone doesn't guarantee
// real weights are behind it.
if (g_fUseNnueEval && g_fNnueWeightsLoaded)
{
return g_uJointFHThousandths_NNUE[_ShipDepthBucket(uRawDepthBucket)]
[uRawDumbBucket]
[uRawGapBucket]
[_ShipLateBucket(uRawLateBucket)]
[uRawImproveBucket];
}
return g_uJointFHThousandths[_ShipDepthBucket(uRawDepthBucket)]
[uRawDumbBucket]
[uRawGapBucket]
[_ShipLateBucket(uRawLateBucket)]
[uRawImproveBucket];
}
// Looks up this node's predicted FH% (thousandths of a percent, i.e.
// 100000 == 100.0%) from g_uBetaFHThousandths, given the raw depth
// bucket (shipped via _ShipDepthBucket same as the alpha lookup
// above) and the gap/own-improve/enemy-improve buckets. Caller is
// responsible for eligibility (iEval > iBeta, etc.) -- this function
// does no gating of its own and returns JOINT_TABLE_SENTINEL (0xFFFF)
// for any below-floor cell regardless.
//
// g_uBetaFHThousandths itself stores the GAP TO 100% (thousandths of
// a percentage point), not FH% directly -- a USHORT can't hold
// FH%*1000 up to 100000, so the direct encoding would saturate every
// cell above FH%=65.534% into one bucket, right where this table is
// actually read. Storing the complement instead keeps full
// resolution across the near-100% range that matters. This function
// re-inverts back to a true FH%*1000 before returning, so callers get
// ordinary "bigger == more confident" semantics.
ULONG
_BetaTablePredictedFHThousandths(IN ULONG uRawDepthBucket,
IN ULONG uGapBetaBucket,
IN ULONG uOwnImproveBucket,
IN ULONG uEnemyImproveBucket)
{
USHORT uRawGap;
// Same runtime HCE/NNUE table selection as
// _JointTablePredictedFHThousandths above -- see its comment.
if (g_fUseNnueEval && g_fNnueWeightsLoaded)
{
uRawGap = g_uBetaFHThousandths_NNUE[_ShipDepthBucket(uRawDepthBucket)]
[uGapBetaBucket]
[uOwnImproveBucket]
[uEnemyImproveBucket];
}
else
{
uRawGap = g_uBetaFHThousandths[_ShipDepthBucket(uRawDepthBucket)]
[uGapBetaBucket]
[uOwnImproveBucket]
[uEnemyImproveBucket];
}
if (JOINT_TABLE_SENTINEL == uRawGap)
{
return JOINT_TABLE_SENTINEL;
}
return (ULONG)(100000 - uRawGap);
}
// Buckets a predicted-FH%-thousandths value (from either table above,
// or one of the two PLY_INFO.uParentMoveFHEstimate sentinels) into one
// of NODE_TYPE_FH_BANDS coarse bands for g_NodeTypeGuessTable's (data.c)
// lookup. MOVE_FH_ESTIMATE_NO_DATA and JOINT_TABLE_SENTINEL are the
// same numeric value (0xFFFF) on purpose -- see both macros' comments.
ULONG
FHThousandthsToBand(IN ULONG uFHThousandths)
{
if (MOVE_FH_ESTIMATE_NONLEFTOVER == uFHThousandths) return 1;
if (MOVE_FH_ESTIMATE_NO_DATA == uFHThousandths) return 0;
if (uFHThousandths < 50000) return 2;
if (uFHThousandths < 80000) return 3;
if (uFHThousandths < 96000) return 4;
if (uFHThousandths < 99900) return 5;
return 6;
}
// Refines CommonSearchInit's ancestor-only NODE_TYPE guess (above,
// this file) using two more signals that aren't available yet at
// CommonSearchInit time (before iEval is computed): this node's own
// predicted FH% (from whichever of the alpha/beta tables applies --
// the same two call sites Search()'s nullmove block already consults
// them from) and the PARENT's predicted FH% for the move that led
// here (PLY_INFO.uParentMoveFHEstimate, chess.h -- written by this
// file's SearchOneMove before it recursed into this node). See
// data.c's g_NodeTypeGuessTable for how the three signals combine and
// the measurement behind it (90.7% vs today's 72.3%, on the
// scope-limited population described there). Deliberately a no-op on
// PV nodes (not a CUT/ALL question) and not applied in QSearch (whose
// own eval/stand-pat timing differs enough to warrant its own look,
// if ever extended there).
//
// Returns the local (this-node, non-PV-only) predicted FH thousandths
// it just computed -- MOVE_FH_ESTIMATE_NO_DATA if neither the beta nor
// alpha branch applied (including the PV early-return). Search()'s own
// static-nullmove/LMR-skip blocks need the exact same table lookup,
// keyed off the exact same (iEval>iBeta) / (iEval<=iAlpha) branch and
// the exact same bucket inputs -- returning it here lets the caller
// reuse it instead of redoing the same data.c table consult a second
// time per node. This is the hottest function in the engine by
// profiler; don't reintroduce the duplicate lookup.
ULONG
_RefineNodeTypeGuess(SEARCHER_THREAD_CONTEXT *ctx,
SCORE iEval,
SCORE iAlpha,
SCORE iBeta,
ULONG uDepth,
SCORE iImprovement,
SCORE iEnemyImprovement,
ULONG uRawImproveB)
{
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
ULONG uAncestorGuess;
ULONG uLocalFH = MOVE_FH_ESTIMATE_NO_DATA;
ULONG uDepthInPlies;
#ifdef FH_USE_REGRESSION_MODEL
// Parent-derived guess, read BEFORE this function's own
// assignment below overwrites pi->eNodeType -- same leakage
// concern as search.c's eNodeTypeGuessParent capture (feeding the
// model's own refined output back in as one of its own inputs
// would be circular). ctx->sPosition is already reachable here,
// so material needs no new parameter either -- see eval.c's
// uArmyScaler for the same VALUE_KING-backout convention.
NODE_TYPE eNodeTypeGuessParent = pi->eNodeType;
ULONG uTotalNonPawnMaterial =
(ctx->sPosition.uNonPawnMaterial[WHITE] - VALUE_KING) +
(ctx->sPosition.uNonPawnMaterial[BLACK] - VALUE_KING);
#endif
if (NODE_PV == pi->eNodeType)
{
return(uLocalFH);
}
uAncestorGuess = (NODE_CUT == pi->eNodeType) ? 0 : 1;
uDepthInPlies = uDepth / ONE_PLY;
if (iEval > iBeta)
{
#ifdef FH_USE_REGRESSION_MODEL
uLocalFH = FhModelBetaPredictedFHThousandths(
iEval, iBeta, uDepth, iImprovement, iEnemyImprovement,
uTotalNonPawnMaterial, eNodeTypeGuessParent);
#else
uLocalFH = _BetaTablePredictedFHThousandths(
DepthBucket(uDepthInPlies),
GapBetaBucket((SCORE)(iEval - iBeta)),
uRawImproveB,
ImproveBucket(iEnemyImprovement));
#endif
}
else if (iEval <= iAlpha)
{
// The alpha side of this refinement is a WHOLE-NODE question
// (same as beta's) -- it's asked before any move is tried, so
// it must use the model's whole-node convention too (tier
// forced to NO_MOVE, not a real per-move tier guess). The
// actual per-move alpha prediction (SearchOneMove, below) is
// a separate, later call with real move-level values.
#ifdef FH_USE_REGRESSION_MODEL
{
FHM_NODE_BASE sBase = FhModelAlphaNodeBaseQ16(
iEval, iAlpha, uDepth, iImprovement, iEnemyImprovement,
uTotalNonPawnMaterial, eNodeTypeGuessParent);
uLocalFH = FhModelNodeBaseIsMateGated(sBase) ?
MOVE_FH_ESTIMATE_NO_DATA :
FhModelAlphaMoveThousandths(sBase, 0, 0, 0, 0, FHC_TIER_NO_MOVE);
}
#else
uLocalFH = _JointTablePredictedFHThousandths(
DepthBucket(uDepthInPlies),
0, // hang bucket: assume nothing hung
GapCpBucket((SCORE)(iAlpha - iEval)),
0, // late bucket: real whole-node sample
uRawImproveB);
#endif
}
pi->eNodeType = g_NodeTypeGuessTable
[uAncestorGuess]
[FHThousandthsToBand(uLocalFH)]
[FHThousandthsToBand(pi->uParentMoveFHEstimate)];
return(uLocalFH);
}
// 2026-10-02: reverted from the DELIBERATE EXTREME EXPERIMENT values
// (9000/8300/1000) back to the original p75/p25/p5-derived calibration
// (72/5/1) -- that experiment was measured while the dynamic gate
// below still had the old fake-100%-decaying-to-10% behavior, itself
// loose and slow to release. Now that the dynamic gate is honest,
// stacking the most aggressive static multiplier on top of it risks
// double-counting the same conservatism twice. Re-measure node
// savings/solve rate with both changes together before drawing any
// conclusion about either one in isolation.
// 2026-10-02: tried loosening to 150/20/5 (cap 4) in the hope that
// Crafty's much larger LMR magnitudes at comparable remaining depth
// (5-10 plies: see lmr_testing discussion) would translate here too.
// Measured sd10 ringers node count instead went UP (23.0M -> 27.7M,
// WORSE than even HEAD's 26.9M) with the tier-1 bucket specifically
// showing a re-search rate (4.13%) HIGHER than tier 0's (2.73%) --
// exactly the "distribution-shift failure" this file's own research-
// rate-calibration comment warns about (low-predicted-FH tiers should
// show a RISING research rate with tier, never an inversion at tier
// 1). Reverted to the original p75/p25/p5-derived 72/5/1/cap-3 --
// MAGNITUDE loosening hits a re-search-tax wall fast; the admission
// widening above (LMR_STATIC_ADMIT_PCT_THOUSANDTHS) is the lever that
// actually worked without this failure mode, because it answers "do
// we reduce at all" (base -1 ply, cheap even when wrong) rather than
// "how much" (large cuts, expensive when wrong).
#define JOINT_EXTRA_TIER1_PCT_THOUSANDTHS (72) // ~p75 of the live
// tries-weighted
// distribution: +1 ply
#define JOINT_EXTRA_TIER2_PCT_THOUSANDTHS (5) // ~p25: +2 plies
#define JOINT_EXTRA_TIER3_PCT_THOUSANDTHS (1) // ~p5: below this (the
// rare, best-predicted
// traffic), +3 plies --
// the max cut
// 2026-10-02: increasing MAGNITUDE again, but narrower than the
// 150/20/5 attempt above -- that one widened TIER1's ADMISSION
// boundary (which moves qualify at all) and broke (tier-1 research
// rate inverted above tier-0's). This time: leave all three admission
// boundaries (72/5/1) untouched, only raise the PAYOUT for tiers 2/3
// -- the stricter, already-proven-safe buckets (their research rate
// was LOWER than tier 0's even before this change, i.e. headroom, not
// a crack). Tier 1 keeps its original +1 payout unchanged since it's
// the bucket closest to the population that just proved fragile.
#define JOINT_EXTRA_MAX_PLIES (5)
// 2026-10-02: ADMISSION is a separate question from MAGNITUDE.
// JOINT_EXTRA_TIER1_PCT_THOUSANDTHS above was previously doing double duty
// as both "is the base -ONE_PLY even allowed" AND "does this move
// additionally earn +1 extra ply" -- a threshold calibrated for the
// latter (the top ~25% of traffic) is far too strict a gate for the
// former. The overnight self-play evidence (old dodgy thresholds,
// effectively a no-op admission gate at this layer) shipped even-or-
// better strength at 0.9-1.0 ply deeper than HEAD -- direct evidence
// that broad admission, not a narrow "only the provably safest moves"
// gate, is the right call here. Set this wide open: the static table
// only vetoes the base reduction when it has a real opinion AND that
// opinion is actively bad (worse than the whole-population baseline
// rate), never merely "not in the top tier."
// 2026-10-02: max-admission (1000, a no-op gate) measured a real,
// consistent sn5M solve-count loss on all three curated suites vs.
// HEAD (ringers -2, confident_quick -2, hard_quick -1) despite being
// deeper/lower-EBF than the 500 setting below -- unlike sd10 (where a
// solve dip from less search is expected and uninteresting), a dip at
// FIXED NODE BUDGET means the extra depth bought by over-wide
// admission isn't paying for itself yet. 500 was flat-to-noise on all
// three at sn5M while still gaining +0.1/+0.4/+0.5 ply over HEAD --
// this is the safer base to build further levers (e.g. LMP) on top of.
// 2026-10-03: LEFT AT 500 across the Wilson-upper-bound re-bake of
// g_uJointFHThousandths (see data.c's header). The re-bake raised
// 19,649 of 21,780 cells, which cut the admitting-CELL count at 500
// from 21,047 to 15,415 -- so it was briefly raised to 1000 to
// compensate. That was wrong: cell counts are not traffic-weighted.
// Measured against the real eligible population (87.8M tries from the
// 2026-10-03 sd10 collection), admit<500 on the NEW table admits
// 92.57% of LMR traffic versus 92.88% measured on the old one, while
// 1000 admits 95.62% -- i.e. 500 is the value that holds LMR behavior
// constant, and the raised cells turn out to be overwhelmingly
// low-traffic ones. Lesson: size any threshold change against
// tries-weighted traffic, never against cell counts.
#define LMR_STATIC_ADMIT_PCT_THOUSANDTHS (500) // 0.500%
#ifdef DEPTH_ONLY_EXTRA_REDUCTION
// See GNUmakefile's DEPTH_ONLY_EXTRA_REDUCTION comment -- the trigger
// threshold below (6 plies) already guarantees the full R=3 extra plus
// the base -1 ply (4 total cut) leaves at least this much remaining, so
// this floor is smaller than the axis-gated version's -- it's a pure
// safety net here, not doing the real gating work (the depth trigger
// is).
#define JOINT_EXTRA_MIN_REMAINING_DEPTH (TWO_PLY)
#define DEPTH_ONLY_TRIGGER_DEPTH (6 * ONE_PLY)
#else
// 2026-09-29: ONE_PLY -- the most aggressive floor. NEUTRALIZE_NULL_
// BAILOUT (GNUmakefile) showed the earlier FOUR_PLY floor's
// justification (a measured silent-miss rate) was overwhelmingly
// (80-99.8%) a measurement artifact of shadow-verification
// methodology, not genuine reduction danger -- the true false-negative
// rate at FOUR_PLY, once properly measured, was already near zero.
#define JOINT_EXTRA_MIN_REMAINING_DEPTH (ONE_PLY)
#endif
// 2026-10-02: g_iLMRQuietReduction (dynamic.c/InitLMRTable) is a
// Crafty/Ethereal-shaped flat log(depth)*log(moves) table, built at
// startup, that NOTHING has ever read -- a prior session built the
// simple mechanism and then went and built the joint-table/dynamic-FH
// system instead without ever wiring this in. It encodes the FULL
// reduction (not an "extra" on top of a base), in ONE_PLY-scaled
// ticks. Checked against Crafty's actual LMR[depth][order] table at
// the remaining-depth range our own suites exercise (5-10 plies):
// d=5,m=8 gives ~2.1 plies here vs Crafty's 2.3; d=10,m=8 gives ~2.7
// here vs Crafty's 3.0 -- same ballpark, same shape, no per-bucket
// static-table judgment to be selectively wrong about (the failure
// mode that just broke the joint-table magnitude tiers above). Used
// here ONLY for magnitude (how much EXTRA beyond the existing -ONE_PLY
// base) -- admission (whether to reduce at all) stays exactly as
// GetLMRReduction already computes it (static/dynamic agreement,
// killer/countermove vetoes); this only replaces the fragile tier
// payout with Crafty's actual mechanism.
static ULONG
_FlatTableExtraPlies(IN ULONG uRemainingDepth, IN ULONG uMoveNum)
{
ULONG uDepthIdx = MINU(uRemainingDepth / ONE_PLY, MAX_PLY_PER_SEARCH);
ULONG uMoveIdx = MINU(uMoveNum, LMR_TABLE_MAX_MOVES);
SCORE iTotalTicks = g_iLMRQuietReduction[uDepthIdx][uMoveIdx];
SCORE iExtraTicks = iTotalTicks - ONE_PLY;
if (iExtraTicks <= 0)
{
return 0;
}
return (ULONG)(iExtraTicks / ONE_PLY);
}
// 2026-10-23: replaces _FlatTableExtraPlies as GetLMRReduction's primary
// magnitude source (that function is kept as the JOINT_TABLE_SENTINEL
// fallback below, for buckets the joint table has no opinion on at all).
//
// Derived from a direct regression against Crafty's and Stockfish's own
// (independently play-tested) reduction schedules: at fixed remaining
// depth, both engines' actual reduction in plies is extremely well
// predicted (R^2=0.96 against Stockfish's own formula, checked across a
// depth 2-13 x move 2-32 grid) by a single term proportional to
// -log10(predictedFH%/100) -- i.e. both engines are implicitly already
// reducing in proportion to how unlikely a move is to fail high, using
// depth and move-number as cheap proxies for that probability. We have
// a materially richer, directly-measured estimate of the same quantity
// (uPredictedFH, 5 axes vs. their 2), so this leans on it directly
// rather than re-deriving the same signal through depth/move-number
// proxies -- the same way the existing admission gate already does.
//
// The proportionality constant itself (k) is NOT fixed -- it was also
// measured, in the same regression, to climb with remaining depth
// (k =~ 0.32*ln(depth) + 0.48 against Stockfish's schedule): both
// engines reduce more per unit of -log10(FH%) the deeper the search
// is. This isn't re-deriving something the FH% estimate already
// contains -- FH% itself already depends on depth, but evidently not
// with the magnitude a calibrated reduction schedule needs, so depth
// earns a second, explicit role here beyond whatever it contributed to
// uPredictedFH upstream.
//
// uRemainingDepth is deliberately capped at 13 plies before computing
// k -- not an arbitrary safety margin, but the exact point where the
// joint table's own raw collection data runs out (see the DEEPER_
// PRUNING.md "leftover-population question" discussion: tries per
// cell fall from 56,021 at depth 13 to low hundreds by depth 16-19 and
// to zero past depth 19). Freezing k's depth input here means k stops
// growing exactly where the data backing it stops being trustworthy --
// and since _ShipDepthBucket() independently freezes uPredictedFH's
// own depth axis at the same raw-13 boundary, both halves of this
// formula plateau together, automatically capping total reduction to
// a flat ceiling past this depth. That's the direct fix for the
// "deterministic re-pruning across iterations" failure mode discussed
// the same day: residual depth (nominal depth minus this flat cap)
// diverges without bound as nominal search depth grows past 13, so a
// move reduced this heavily is guaranteed to eventually receive a
// residual look deep enough to find whatever it was missing, no
// matter how deep the overall iterative-deepening search goes -- it
// is never reduced by a *growing* amount indefinitely.
//
// Normalized against LMR_FH_BASELINE_PCT_THOUSANDTHS (the same 0.400%
// whole-population baseline the dynamic-danger check already uses) so
// an exactly-average leftover move earns ~0 extra plies (just the
// existing flat -ONE_PLY base), and only moves predicted safer than
// that baseline earn positive extra, scaling up continuously with how
// much safer -- no threshold cliff, matching how neither reference
// engine's own formula has an admission cliff either.
// Relocated here (was originally right before CanWeReduceOrPruneMove)
// so _FhBasedExtraPliesF below can use it -- same single definition,
// just earlier in the file now. See its original comment, still in
// place further down, for the full "0.400%" provenance story.
#define LMR_FH_BASELINE_PCT_THOUSANDTHS (400) // 0.400%
// Returns the EXTRA reduction (beyond the base -ONE_PLY) in raw depth
// ticks, rounded to the nearest QUARTER_PLY -- the engine's actual
// reduction/extension resolution (chess.h: ONE_PLY=64, QUARTER_PLY=16,
// i.e. depth is fixed-point in quarter-ply units throughout the
// search, not whole plies). The regression this formula is built from
// was fit in continuous plies; truncating to whole plies here would
// throw away most of its resolution for no reason, so this returns
// ticks directly instead of letting the caller round first.
static ULONG
_FhBasedExtraPlyTicks(IN ULONG uRemainingDepth, IN ULONG uPredictedFHThousandths)
{
double dDepth = (double)(MINU(uRemainingDepth / ONE_PLY, 13));
double dK;
double dFhThousandths;
double dNegLogFh;
double dNegLogBaseline;
double dExtraPlies;
ULONG uTicks;
if (dDepth < 2.0)
{
dDepth = 2.0;
}
dK = 0.32 * log(dDepth) + 0.48;
dFhThousandths = (double)uPredictedFHThousandths;
if (dFhThousandths < 1.0)
{
dFhThousandths = 1.0; // avoid log(0); table has no real 0 cells anyway
}
dNegLogFh = -log10(dFhThousandths / 100000.0);
dNegLogBaseline =
-log10((double)LMR_FH_BASELINE_PCT_THOUSANDTHS / 100000.0);
dExtraPlies = dK * (dNegLogFh - dNegLogBaseline);
if (dExtraPlies <= 0.0)
{
return 0;
}
// Round to nearest quarter-ply tick (ONE_PLY=64, QUARTER_PLY=16).
uTicks = (ULONG)((dExtraPlies * (double)ONE_PLY / (double)QUARTER_PLY) + 0.5)
* QUARTER_PLY;
return uTicks;
}
// data.c:1209's "Overall eligible FH%: 0.400%" -- the tries-weighted
// fail-high rate of the WHOLE fPruneReduceEligible population across
// the 500B-node joint-table collection run. Used two ways: (1) as the
// universal backstop -- a move identity whose own honest observed
// rate already exceeds what an AVERAGE leftover move does is never
// reduction-safe, regardless of context; (2) folded into the same
// decision below, additionally compared against the joint table's own
// bucket-specific prediction for the exact (depth, hang, gap, late)
// situation this move is in right now -- a strictly tighter,
// context-aware version of the same idea.
// 2026-10-03 unit unification: was (4) in per-mille, which is the SAME
// nominal 0.4% this is now expressed as directly. Not quite a no-op
// though, and the difference is worth knowing: the old comparison was
// `floor(fh*1000/attempts) > 4`, which can only become true once
// fh/attempts >= 0.005 -- i.e. truncation made the old gate behave like
// 0.5%, not the 0.400% it documented. 400 here is faithful to the
// documented intent and is a hair stricter than what actually shipped.
// The affected band is fh/attempts in [0.401%, 0.5%), which requires
// >= 200 observations of one move identity to even express and is
// essentially unpopulated per chess.h's u64FHJointHist (the dynamic
// rate is bimodal -- ~71% at exactly 0, with the next real mass not
// starting until ~1%). So: intended behavior preserved, shipped
// behavior changed by an immeasurably small amount.
// (Defined earlier in this file now -- see _FhBasedExtraPliesF's use.)
// 2026-10-02, one-off diagnostic support for chess.h's u64FHJointHist:
// 8 attempts bands (0,1,2,3-4,5-9,10-24,25-99,100+) and 8 rate bands in
// thousandths (0,1,2-4,5-9,10-19,20-49,50-99,100+ -- the last band
// starts exactly at the old HEAD-style 10% ceiling).
FLAG
CanWeReduceOrPruneMove(IN SEARCHER_THREAD_CONTEXT *ctx,
IN MOVE mv,
IN ULONG x,
IN ULONG uLegalMoves,
IN SCORE iExtend,
IN SCORE iAlpha,
IN FLAG fThreat,
IN FLAG fIsLeftoverMove)
/**
Routine description:
2026-10-04: hoisted out of Search()'s move loop (search.c), where
this had grown into an inline block setting fPruneReduceEligible
plus two more exemption checks (killer-adjacency, countermove
match) immediately below it -- EFP (since removed), LMP and LMR all
gated on the combined result. Pulled into one function so the "is this move
even a candidate for pruning/reduction" question has a single,
named answer instead of three co-located but separately-maintained
checks.
Base eligibility (see search.c's original comment, preserved in
spirit): a move is a candidate only if (1) it isn't the first move
tried at this node (uLegalMoves > 1 -- there must be something to
compare it against), (2) this isn't a PV node (a PV node must
resolve every move exactly, not approximately), (3) it's already
in the leftover/late tier (fIsLeftoverMove), (4) it wasn't
independently extended (iExtend <= 0), (5) it isn't escaping check
or (6) giving check, (7) there's no node-wide threat in play
(fThreat), (8) alpha isn't already mate-magnitude, and (9) it's
either a non-capture/non-promotion or a losing one (SEE-negative;
a non-losing capture/promotion is excluded outright, matching the
population the joint fail-high table was actually trained on --
see lmr_testing/SPEC.md's "gate-1" section).
On top of that, two move-identity-specific exemptions withdraw
eligibility even if the base checks above all pass: a killer at
this ply or two plies back (killers already proved themselves
elsewhere in the tree and the table can change between visits, so
this is re-checked every call, not cached), and a bare countermove
match against the move played two plies ago (ctx->sPlyInfo[uPly-2]
-- mv has already been made by the time this runs, so the "move
immediately before mv" is two plies back from here, not one).
FOUND WHILE HOISTING, FIXED HERE: the countermove check in
search.c's inline version was `return FALSE;` -- inside Search(),
which returns SCORE, not FLAG. That silently returned a score of
0 for the entire node (abandoning the rest of the move loop, and
doing so without the matching UnmakeMove) the instant the current
move matched a countermove-table entry, rather than merely
excluding that one move from pruning/reduction eligibility the way
the killer check two lines above it does. Expressed here as an
ordinary `return FALSE;` from this FLAG-returning helper, which is
the behavior that was actually intended.
Parameters:
ctx : current searcher thread context. Reads uPly,
sPlyInfo (for eNodeType and the countermove key),
mvKiller, mvCounter, and the already-made move's
cached flags out of sMoveStack.
mv : the move just made (MakeMove has already returned
TRUE for it by the time this is called).
x : this move's 1-based index into ctx->sMoveStack,
i.e. the move loop's own loop variable -- used to
read sMoveStack.mvf[x - 1].bvFlags for the cached
MVF_SEE_NONNEGATIVE bit. x == 0 never reaches here
in practice (TRY_HASH_MOVE's single iteration is
always the first move, so uLegalMoves > 1 already
rules it out).
uLegalMoves : legal moves found at this node so far, including mv.
iExtend : this move's own per-move extension amount.
iAlpha : this node's current alpha.
fThreat : whether a node-wide threat extension is in play.
fIsLeftoverMove : whether mv already sorted into the leftover/late
move-ordering tier.
Return value:
FLAG : TRUE iff mv is eligible to be considered for pruning or
reduction (LMP/LMR still each apply their own further checks
on top of this).
**/
{
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
FLAG fPruneReduceEligible =
(NODE_PV != pi->eNodeType) &&
(uLegalMoves > 1) &&
(TRUE == fIsLeftoverMove) &&
(iExtend <= 0) &&
(!IS_ESCAPING_CHECK(mv)) &&
(!IS_CHECKING_MOVE(mv)) &&
(!fThreat) &&
(iAlpha < +NMATE) &&
((!IS_CAPTURE_OR_PROMOTION(mv)) ||
(!(ctx->sMoveStack.mvf[x - 1].bvFlags & MVF_SEE_NONNEGATIVE)));
if (FALSE == fPruneReduceEligible)
{
return FALSE;
}
ULONG uPly = ctx->uPly;
if (uPly >= 2)
{
// We have to check this every time too because the killers can
// change any time we search recursively.
if (IS_SAME_MOVE(mv, ctx->mvKiller[uPly - 1][0]) ||
IS_SAME_MOVE(mv, ctx->mvKiller[uPly - 1][1]))
{
return FALSE;
}
MOVE mvPrev = ctx->sPlyInfo[uPly - 2].mv;
if (0 != mvPrev.uMove)
{
ULONG uCounterIdx = MOVE_TO_INDEX(mvPrev);
if (IS_SAME_MOVE(mv, ctx->mvCounter[uCounterIdx][0]) ||
IS_SAME_MOVE(mv, ctx->mvCounter[uCounterIdx][1]))
{
return FALSE;
}
}
if (uPly >= 3)
{
if (IS_SAME_MOVE(mv, ctx->mvKiller[uPly - 3][0]) ||
IS_SAME_MOVE(mv, ctx->mvKiller[uPly - 3][1]))
{
return FALSE;
}
}
}
return TRUE;
}
INT FORCEINLINE
GetLMRReduction(IN SEARCHER_THREAD_CONTEXT *ctx,
IN ULONG uRemainingDepth,
IN ULONG uLegalMoves,
IN MOVE mv,
IN INT iExtend,
IN ULONG uAttempts,
IN ULONG uFHPctThousandths,
IN ULONG uPredictedFH,
OUT ULONG *puExtraTier)
/**
Routine description:
Decide how much (if any) to reduce the depth of the search below
this move. Note: the move has already been made by the time we
get here.
Parameters:
ctx : current searcher thread context.
uRemainingDepth : remaining depth below this move.
uLegalMoves : legal moves tried at this node so far.
mv : the move just made.
iExtend : this move's own per-move extension amount so far
(ASSERTed to be 0 when a reduction is applied).
uAttempts : this move identity's dynamic sample count.
uFHPctThousandths : this move identity's dynamic fail-high rate.
uPredictedFH : the joint table's static prediction for this
move's (depth, hang, gap, late) situation, or
JOINT_TABLE_SENTINEL if no data.
OUT ULONG *puExtraTier : optional (may be NULL, e.g. split.c, which
has no use for the joint-extra-tier re-search/calibration
instrumentation keyed on this). Receives the extra-ply tier
(0-3) actually applied, 0 whenever this function returns 0 OR
returns only the baseline -ONE_PLY.
Return value:
INT : 0 if no reduction, else a negative multiple of ONE_PLY (the
FULL combined baseline+extra reduction).
**/
{
ASSERT(ctx->uPly > 0);
ASSERT(mv.uMove);
ASSERT(!InCheck(&ctx->sPosition, ctx->sPosition.uToMove));
ULONG uExtraTicks = 0;
#ifdef DISABLE_LMR
// See GNUmakefile's DISABLE_LMR comment. Bail before any signal is
// consulted so the no-LMR arm is a clean control: no reduction, and
// also none of the table/history lookups that feed it.
return(0);
#endif
INT iLocalExtend;
ULONG uExtraTierForCounters;
// 2026-10-23: admission is no longer gated on the static table's
// opinion (LMR_STATIC_ADMIT_PCT_THOUSANDTHS retired from this
// function -- CanWeReduceOrPruneMove's base eligibility, i.e. "is
// this move even in the leftover tier," is still the only gate).
// Every eligible leftover move gets at least the base -ONE_PLY;
// uPredictedFH drives MAGNITUDE continuously via
// _FhBasedExtraPlyTicks below instead of gating whether to reduce
// at all -- matching how neither Crafty's nor Stockfish's own
// formula has an admission cliff either.
//
// 2026-10-23: the dynamic per-move-identity signal (this move's
// own observed fail-high history) no longer gets a separate
// veto-to-zero branch (the old fDynamicDanger check, removed).
// Deliberate, not an oversight -- discussed at length the same
// day: neither Crafty nor Stockfish exempts a move from reduction
// because of its own track record (Crafty has no dynamic signal
// in its reduction formula at all; Stockfish's analogous history-
// based term only ever feeds one continuous formula, never a
// separate exemption branch). A move's own real fail-high history
// is folded into the SAME formula's input instead, as a Wilson-
// score upper confidence bound (GetMoveFailHighWilsonUpperBoundThousandths,
// dynamic.c) on that move's true fail-high rate -- a tighter
// (lower) bound than the static table's prediction is real,
// sample-size-earned evidence of safety and is allowed to win;
// a looser (higher) bound -- including the "real history of
// failing high" case -- never overrides the static table's own
// reading, by construction: taking the minimum of two FH%
// estimates can only ever pick the smaller (safer) one, never
// push the effective rate up. (Deliberately NOT using this to
// justify reducing a dangerous-looking move LESS, either -- see
// the same discussion: the data argues searching a flagged-
// dangerous move deeper doesn't straightforwardly buy a safer
// read, since the table's own depth axis already shows shallower
// remaining depth correlates with HIGHER fail-high rates, not
// lower, so "reduce less" has no causal footing to stand on here.)
//
// Also 2026-10-23: works in raw depth ticks (QUARTER_PLY-rounded),
// not whole plies -- the engine's actual reduction/extension
// resolution is quarter-ply fixed-point throughout (chess.h:
// ONE_PLY=64, QUARTER_PLY=16), and the regression this formula
// comes from was fit in continuous plies, so truncating to whole
// plies here would throw away most of that precision for no
// reason. The old flat-table fallback (JOINT_TABLE_SENTINEL case)
// still only has whole-ply resolution, hence the *ONE_PLY there.
if (JOINT_TABLE_SENTINEL == uPredictedFH)
{
// No static data for this exact bucket -- fall back to the
// old flat Crafty-shaped (depth, moveNum) table rather than
// feeding a sentinel into the log formula. (Not blended with
// the Wilson bound either -- there's no static reading here
// to take a minimum against.)
uExtraTicks = _FlatTableExtraPlies(uRemainingDepth, uLegalMoves) * ONE_PLY;
}
else
{
ULONG uWilsonBound = GetMoveFailHighWilsonUpperBoundThousandths(mv);
ULONG uEffectiveFH = MINU(uPredictedFH, uWilsonBound);
uExtraTicks = _FhBasedExtraPlyTicks(uRemainingDepth, uEffectiveFH);
}
// Clamp. Combine with the baseline -ONE_PLY and floor the total
// so it never leaves less than JOINT_EXTRA_MIN_REMAINING_DEPTH
// remaining -- never rely on the move loop's own unsigned-
// wraparound clamp to do this implicitly.
//
// iExtend is guaranteed 0 here (see routine description; the sole
// caller asserts this itself at search.c:1416 right after a
// reduction comes back), so iLocalExtend is always exactly
// -ONE_PLY -- no need to fold a variable iExtend into it.
ASSERT(0 == iExtend);
iLocalExtend = -ONE_PLY;
uExtraTierForCounters = 0;
if (uExtraTicks > 0)
{
// MAX0 branchlessly floors the numerator at 0 before the
// divide (it can go negative when uRemainingDepth is small).
INT iExtraNumerator =
(INT)uRemainingDepth - 2 * (INT)ONE_PLY -
(INT)JOINT_EXTRA_MIN_REMAINING_DEPTH;
ULONG uMaxExtraTicks = (ULONG)MAX0(iExtraNumerator);
uExtraTicks = MINU(uExtraTicks, uMaxExtraTicks);
uExtraTicks = MINU(uExtraTicks, (ULONG)(JOINT_EXTRA_MAX_PLIES * ONE_PLY));
iLocalExtend -= (INT)uExtraTicks;
// The joint-extra-tier instrumentation (u64JointExtraTries[]
// etc, JOINT_EXTRA_TIER_COUNT=6 slots, see chess.h) predates
// fractional extra plies and indexes by whole extra plies --
// floor to that resolution for counter purposes only; the
// actual applied reduction above keeps full tick precision.
uExtraTierForCounters = uExtraTicks / ONE_PLY;
}
if (NULL != puExtraTier)
{
*puExtraTier = uExtraTierForCounters;
}
return(iLocalExtend);
}
// 2026-10-13: LMP_BASE_MOVENUM/LMP_PER_PLY_MOVENUM/LMP_MAX_REMAINING_DEPTH
// are NOT wired into ShouldLatePrune below -- there is no move-number
// floor and no depth ceiling in this function today, despite this
// comment block and the docstring below once describing four checks.
// uLegalMoves is still a parameter (kept for signature/call-site
// stability and because MoveNumBucket already folds move number into
// uPredictedFH upstream, in search.c, before this function ever sees
// it) but it is unread here. LMP_MAX_REMAINING_DEPTH never existed as
// code, only as a comment; LMP_BASE_MOVENUM/LMP_PER_PLY_MOVENUM are
// defined and then never referenced -- dead macros, not a disabled
// feature flag. Left defined rather than deleted only because a
// future re-introduction of an explicit floor/ceiling (e.g. if the
// table's move-number axis turns out too coarse near the root once
// EFP is folded into this function -- see the EFP/LMP merge
// discussion) would want exactly these names back. If that doesn't
// happen, delete them.
#define LMP_BASE_MOVENUM (8) // currently unused, see above
#define LMP_PER_PLY_MOVENUM (1) // currently unused, see above
#define LMP_DYNAMIC_MIN_SAMPLES (1) // well-evidenced, not a guess
#define LMP_DYNAMIC_MAX_PCT_THOUSANDTHS (10000)
FLAG
ShouldLatePrune(IN SEARCHER_THREAD_CONTEXT *ctx,
IN ULONG uRemainingDepth,
IN ULONG uLegalMoves,
IN ULONG uFHAttempts,
IN ULONG uFHPctThousandths,
IN ULONG uPredictedFH)
/**
Routine description:
2026-10-04: second gate, applied by the caller (search.c) only
after CanWeReduceOrPruneStatic has already passed -- so the
killer-adjacency and countermove-match exemptions that used to be
duplicated here are gone; the caller never reaches this function
for a move either of those would have exempted. Takes the FH-table
lookups (uFHAttempts, uFHPctThousandths, uPredictedFH) as inputs
rather than recomputing them -- search.c's move loop already looks
them up once per move for LMP/LMR to share.
2026-10-13: corrected from an earlier version of this comment that
claimed four checks including a move-number floor and a depth
ceiling -- neither exists in the body below (see the dead-macro
note above). As actually implemented, there are only two checks,
either of which refuses to prune:
1. Dynamic signal: real, well-evidenced fail-high history on
this exact move identity that isn't essentially zero -- the
ultra-safe tail, not "probably fine."
2. Static signal: the joint table's own prediction
(uPredictedFH) for this move's (depth, hang, gap, late,
improve) situation, checked against a per-remaining-depth
threshold (uLMPStaticMaxPctThousandths[]) that tightens as
remaining depth grows -- unlike GetLMRReduction's more
permissive treatment of missing data for mere reduction,
overt pruning requires a favorable prediction.
There is accordingly no explicit guard today against pruning the
8th move at the root the instant the table happens to look
favorable, nor any floor stopping this from firing arbitrarily
deep in the tree -- both are purely emergent from
uLMPStaticMaxPctThousandths[]'s own shape (very permissive near
remaining depth 0, essentially 0 by remaining depth 10) rather
than from any dedicated gate. If that turns out to be too loose in
practice (e.g. once EFP's margin-based alpha-side pruning is
folded into this same table-driven path and starts operating at
the 1-2-ply horizon EFP currently owns), re-introduce an explicit
floor/ceiling using the macros above rather than reshaping the
static-threshold array to fake one.
The uPredictedFH == JOINT_TABLE_SENTINEL check below is currently
unreachable in practice: g_uJointFHThousandths (data.c) is fully
backoff-smoothed (shrinkage to a coarser marginal rather than a
missing-data sentinel) as of the splice-dual bake that added the
improve axis -- "No 0xffff sentinels remain" per that table's own
header comment. Kept as a defensive check (cheap, and correct even
if the table is ever rebaked with real gaps again), not because
it's expected to fire today.
Parameters:
ctx : current searcher thread context (uPly only,
for the sanity ASSERT).
uRemainingDepth : remaining depth below this move.
uLegalMoves : legal moves tried at this node so far --
currently unused by this function (see the
dead-macro note above); kept in the
signature for call-site stability.
uFHAttempts : this move identity's dynamic sample count.
uFHPctThousandths : this move identity's dynamic fail-high rate.
uPredictedFH : the joint table's static prediction for this
move's (depth, hang, gap, late, improve)
situation, or JOINT_TABLE_SENTINEL if no data
(see note above on why this is effectively
dead today).
Return value:
FLAG : TRUE iff mv should be pruned outright (skipped, not merely
reduced). Live, not audit-only: search.c's move loop actually
`continue`s past mv when this returns TRUE (the check that
consumes fThisMoveLMPPruned), after INCrementing
u64LMPPruned for the script-summary "late-move pruning (overt
skip, not reduction)" line under PERF_COUNTERS.
**/
{
static ULONG uLMPStaticMaxPctThousandths[] = {
325, 300, 250, 200, 150, 100, 80, 25, 6, 1, 0
};
ASSERT(ctx->uPly > 0);
ASSERT(IS_VALID_DEPTH(uRemainingDepth));
ULONG uRemainingPlies = uRemainingDepth / ONE_PLY;
// Dynamic signal: if there's real, well-evidenced history on this
// exact move identity and it's not essentially zero, don't
// gamble -- this is the ultra-safe tail only, not "probably fine."
if ((uFHAttempts >= LMP_DYNAMIC_MIN_SAMPLES) &&
(uFHPctThousandths > LMP_DYNAMIC_MAX_PCT_THOUSANDTHS))
{
return FALSE;
}
if ((JOINT_TABLE_SENTINEL == uPredictedFH) ||
(uPredictedFH > uLMPStaticMaxPctThousandths[MINU(uRemainingPlies, 10)]))
{
return FALSE;
}
return TRUE;
}
SCORE
DecodeMoveValueEstimate(IN MOVE mv,
IN SCORE iRawValue,
IN MOVE_SCORING_SCHEME eScheme)
/**
Routine description:
generate.c has (at least) four distinct conventions for packing
sMoveStack[].iValue (see MOVE_SCORING_SCHEME's own comment, chess.h),
plus two more that aren't generate.c tier encodings at all
(RescoreMovesViaSearch's real eval-axis score, and root.c's node-
count/score composite). This function is the one place that knows
how to turn a raw iValue back into an eval-axis (100=1-pawn)
material estimate, given which scheme produced it -- every caller
that needs an actual value rather than just a tier/leftover
classification should go through here rather than inlining its own
guess at the encoding.
Parameters:
IN MOVE mv,
IN SCORE iRawValue,
IN MOVE_SCORING_SCHEME eScheme
Return value:
SCORE
**/
{
switch (eScheme)
{
case MOVE_SCORING_IID_RESCORED:
// Already a real, searched eval-axis score (reflects an
// entire subtree, not just the immediate exchange) --
// trust it exactly as-is.
return(iRawValue);
case MOVE_SCORING_NORMAL:
case MOVE_SCORING_QSEARCH_NO_CHECKS:
// Identical +120 flat move-ordering bias plus small
// MVV-LVA tie-break nudges for winning/even captures and
// promotions -- harmless for sorting, but wrong on the
// eval axis until backed out.
if ((iRawValue >= SORT_THESE_FIRST) && IS_CAPTURE_OR_PROMOTION(mv))
{
ASSERT(iRawValue > 0);
iRawValue &= STRIP_OFF_FLAGS;
iRawValue -= MOVE_SCORE_ORDERING_BIAS(mv);
return(iRawValue);
}
// All quiet moves (including killer/killer-mate quiet
// moves, which can reach SORT_THESE_FIRST or the killer-
// tier bits via generate.c's ordering bonuses with no
// relation to a move's real eval-axis value) collapse to
// 0 here -- correct, since a quiet move's ordering bonus
// carries no such estimate. A genuinely negative raw value
// (a losing capture, scored without any tier flag) passes
// through MIN0 unchanged, preserving its real (negative)
// material estimate.
//
// FUTURE WORK: 0 is uniform across every quiet move, which
// throws away signal we plausibly have. Two candidate
// refinements, deliberately not implemented yet (each needs
// its own isolated A/B, not bundled together):
// 1. A small flat bonus (tested at +10: net wash, moved
// solves from confident_quick to hard_quick rather than
// a clear win/loss -- see RESULTS.md) for killer/
// killer-mate moves, on the theory that a move which
// already caused a cutoff elsewhere in the tree is more
// likely to be good than an untested quiet shuffle.
// 2. eval.c square-delta scoring (e.g. PAWN_CENTRALITY_BONUS/
// KNIGHT_CENTRALITY_BONUS[cTo]-[cFrom]) for a directional,
// if not strictly accurate, signal on ordinary quiet
// moves -- eval.c's real value is far more than per-square
// tables (mobility, king safety, pawn structure), so this
// would only ever be directionally suggestive, not exact.
return(MIN0(iRawValue));
case MOVE_SCORING_QSEARCH_CHECKS:
// Same +120 convention, plus two QSearch-only ordering
// nudges baked into the same value by
// _ScoreQSearchMovesInclChecks: +4 for a checking move,
// +64 for a same-square recapture. The checking-move term
// is backed out here; the same-square-recapture term isn't
// (this function doesn't receive mvLast) -- a known,
// small (<=64, well under a minor piece) residual
// imprecision for that specific case, not silently wrong
// by an unbounded amount the way the pre-fix code was for
// escapes.
if ((iRawValue >= SORT_THESE_FIRST) && IS_CAPTURE_OR_PROMOTION(mv))
{
ASSERT(iRawValue > 0);
iRawValue &= STRIP_OFF_FLAGS;
iRawValue -= MOVE_SCORE_ORDERING_BIAS(mv);
if (IS_CHECKING_MOVE(mv))
{
iRawValue -= 4;
}
return(iRawValue);
}
return(MIN0(iRawValue));
case MOVE_SCORING_ESCAPE:
// _ScoreAllEscapes' winning-capture encoding uses a
// DIFFERENT bias than _ScoreAllMoves (no +120) plus an
// IS_KING(mv.pMoved) right-shift that's lossy -- can't be
// inverted exactly. Even captures are tagged FIRST_KILLER,
// not SORT_THESE_FIRST, so they would not even reach a
// capture-decode branch keyed on that bit. Rather than try
// to invert either packed encoding, just recompute the
// cheap raw material estimate directly from the move's own
// fields -- exactly what _ScoreAllEscapes itself computes
// as ITS OWN first-pass estimate before ever calling SEE
// (deliberately not re-invoking SEE here -- same axis,
// just cheaper and not dependent on reversing a lossy
// encoding).
if (IS_CAPTURE_OR_PROMOTION(mv))
{
return((SCORE)(PIECE_VALUE(mv.pCaptured) -
PIECE_VALUE(mv.pMoved)));
}
return(0);
case MOVE_SCORING_ROOT:
default:
// Not a generate.c tier encoding at all -- a node-count/
// score composite (root.c), only ever populates ply 0's
// move stack. No current caller asks to decode a root-ply
// move here; fail loudly rather than silently return a
// number that looks plausible but isn't.
ASSERT(FALSE);
return(0);
}
}
SCORE
ComputeMoveScore(IN SEARCHER_THREAD_CONTEXT *ctx,
IN MOVE mv,
IN ULONG uMoveNum)
{
SCORE iMoveScore = (PIECE_VALUE(mv.pCaptured) +
PIECE_VALUE(mv.pPromoted));
if (uMoveNum != (ULONG)-1)
{
ASSERT(uMoveNum < MAX_MOVE_STACK);
ASSERT(IS_SAME_MOVE(mv, ctx->sMoveStack.mvf[uMoveNum].mv));
ASSERT(ctx->uPly > 0);
// Every current caller (EstimateHangingMaterialCp above, and
// ComputeMoveExtension's own call site below) only
// reaches here after MakeMove(ctx, mv) has already succeeded, so
// ctx->uPly is always the *child's* ply here -- uMoveNum indexes
// the parent's move list, i.e. ctx->uPly - 1, not ctx->uPly. That's
// the ply whatever scoring pass ran (generate.c's scorers,
// RescoreMovesViaSearch) actually scored, so that's the ply
// whose eMoveScoringScheme is authoritative here.
iMoveScore = DecodeMoveValueEstimate(
mv,
ctx->sMoveStack.mvf[uMoveNum].iValue,
ctx->sPlyInfo[ctx->uPly - 1].eMoveScoringScheme);
}
return(iMoveScore);
}
SCORE
GetMoveSee(IN SEARCHER_THREAD_CONTEXT *ctx,
IN MOVE mv,
IN ULONG uMoveNum)
/**
Routine description:
SEE for a checking move or a non-pawn capture, used by
ComputeMoveExtension's callers (Search, HelpSearch, and eventually
QSearch) to decide how much to extend/reduce a check, and (as of
the recapture-extension soundness gate) to judge a recapture too.
One call site, one SEE per move regardless of how many of
ComputeMoveExtension's gates end up wanting it -- SEE is one of
the hottest routines in the tree, so callers compute this at most
once per move and pass the single result into ComputeMoveExtension
via iMoveSee, rather than each gate calling it independently. Must
be computed on the PRE-move position -- see.c's exchange walk needs
the piece still sitting on cFrom, and by the time
ComputeMoveExtension runs the move has already been played.
Move generation/scoring (_ScoreAllMoves, _ScoreAllEscapes in
generate.c) already runs a real SEE on this same (pos, mv) pair
whenever it scores an ambiguous capture or promotion, and stashes
the sign in the move's MVF_SEE_KNOWN/MVF_SEE_NONNEGATIVE flags.
Reuse that instead of walking the exchange (GetAttacks()) again.
Only the sign matters to any caller of ComputeMoveExtension, so the
cached value is coarsened to 0/-1.
On a cache miss, use SeeFastSign (see.c) instead of a real SEE()
call -- same reasoning as the cache-hit path above (only the sign
ever reaches ComputeMoveExtension, both of its own iMoveSee checks
are plain `< 0`/`>= 0`), but for the miss case there was no cached
value to fall back to at all, so this always used to pay for a
full SEE() exchange walk (list-build, heap, x-ray discovery) just
to throw away everything but the sign. SeeFastSign is
correctness-tested against real SEE()'s sign across thousands of
random positions (testsee.c's TestSeeFastSign) and measured at
0.40x-0.65x SEE()'s own cycles/call, coarsened to the same 0/-1
convention as the cache-hit path for consistency.
Parameters:
SEARCHER_THREAD_CONTEXT *ctx : searcher thread context
MOVE mv : the checking move or capture needing a soundness read
ULONG uMoveNum : mv's index in ctx->sMoveStack.mvf[], or (ULONG)-1
if mv did not come from the move stack (e.g. the hash move)
Return value:
SCORE
**/
{
BITV bvFlags;
ASSERT(IS_CHECKING_MOVE(mv) || (mv.pCaptured != NULL));
if (uMoveNum == (ULONG)-1)
{
return(SeeFastSign(&ctx->sPosition, mv) ? 0 : -1);
}
ASSERT(uMoveNum < MAX_MOVE_STACK);
ASSERT(IS_SAME_MOVE(mv, ctx->sMoveStack.mvf[uMoveNum].mv));
bvFlags = ctx->sMoveStack.mvf[uMoveNum].bvFlags;
if (bvFlags & MVF_SEE_KNOWN)
{
return((bvFlags & MVF_SEE_NONNEGATIVE) ? 0 : -1);
}
return(SeeFastSign(&ctx->sPosition, mv) ? 0 : -1);
}
void FORCEINLINE
ComputeMoveExtension(IN SEARCHER_THREAD_CONTEXT *ctx,
IN SCORE iAlpha,
IN SCORE iBeta,
IN ULONG uMoveNum,
IN SCORE iRoughEval,
IN ULONG uDepth,
IN SCORE iMoveSee,
IN FLAG fIsLeftoverMove,
IN OUT INT *piExtend)
/**
Routine description:
This routine is called by Search and by HelpSearch (in split.c).
It's job is to assign a move-based extension for the move mv.
This extension should be between -ONE_PLY (reduction) and +ONE_PLY
(extension).
Note: this code is executed after the move has already been played
on the board!
Parameters:
IN SEARCHER_THREAD_CONTEXT *ctx : the searcher thread's context
IN SCORE iAlpha : current alpha
IN SCORE iBeta : current beta
IN ULONG uMoveNum : move number in stack
IN ULONG uDepth : remaining depth
IN OUT INT *piExtend : extension amount (in/out)
Return value:
void
**/
{
static const SCORE _window[MAX_PLY_PER_SEARCH] = {
-1, -1, 500, 500, 425, 425, 350, 350, 275, 275, 200, 200, // 0..11
150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, // 12..23
150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, // 24..35
150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, // 36..47
150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, // 48..59
150, 150, 150, 150 // 60..63
};
POSITION *pos = &ctx->sPosition;
MOVE mvLast = ctx->sPlyInfo[ctx->uPly-2].mv;
MOVE mv = ctx->sPlyInfo[ctx->uPly-1].mv;
ULONG uColor = GET_COLOR(mv.pMoved);
SCORE iMoveScore;
#ifdef DEBUG
int iM;
//
// Preconditions
//
ASSERT(IS_VALID_SCORE(iAlpha));
ASSERT(IS_VALID_SCORE(iBeta));
ASSERT(iAlpha < iBeta);
ASSERT(ctx->uPly >= 2);
ASSERT(ctx->uPly < MAX_PLY_PER_SEARCH);
ASSERT(mv.uMove);
ASSERT(*piExtend >= 0);
#endif
// Checking move extension. Crafty-style soundness gate: a check
// that's really just a losing sacrifice (SEE < 0) still gets a small
// consolation extension rather than none at all -- SEE can't see
// multi-move combinations, so a "losing" sacrifice check is sometimes
// actually a winning sham sacrifice a few moves later, and giving it
// zero search priority risks missing exactly those. It just doesn't
// get to compound the way a materially sound check does.
if (IS_CHECKING_MOVE(mv))
{
ASSERT(InCheck(pos, pos->uToMove));
INC(ctx->sCounters.extension.uCheck);
if (iMoveSee < 0)
{
*piExtend += QUARTER_PLY;
INC(ctx->sCounters.extension.uCheckByQuarterPly[QUARTER_PLY / QUARTER_PLY]);
}
else
{
if (pos->uNonPawnMaterial[FLIP(pos->uToMove)] >
(VALUE_KING + VALUE_BISHOP))
{
*piExtend += ONE_PLY;
INC(ctx->sCounters.extension.uCheckByQuarterPly[ONE_PLY / QUARTER_PLY]);
}
else
{
*piExtend += QUARTER_PLY;
INC(ctx->sCounters.extension.uCheckByQuarterPly[QUARTER_PLY / QUARTER_PLY]);
}
}
}
// Pawn push extension. RANK7/RANK2 already mean "one step from
// promotion", so the pawn is a passer by definition -- no separate
// passed-pawn test needed. Two cheap, eval-independent refinements
// (both read only incrementally-maintained POSITION bitboards, no
// Eval()/pawn-hash dependency, no sig-check needed):
//
// 1. Skip entirely if the promotion square itself is already
// occupied (friend or foe) -- a push that can just be captured
// or that's blocked from ever queening isn't worth the ply.
// 2. The size of the bonus depends on whether the pawn's own
// king/rook/queen actually defends it on cTo, not just
// whether the king happens to be nearby (a king 2 squares
// away that can't recapture doesn't help this pawn at all).
if (IS_PAWN(mv.pMoved) && (RANK7(mv.cTo) || RANK2(mv.cTo)))
{
ULONG uPawnColor = GET_COLOR(mv.pMoved);
COOR cPromo = mv.cTo + ((uPawnColor == WHITE) ? 0x10 : -0x10);
if (!(pos->bbOccupied & COOR_TO_BB(cPromo)))
{
*piExtend += HALF_PLY;
if (!fIsLeftoverMove ||
((g_KingAttacksBB[mv.cTo] &
COOR_TO_BB(KingPosition(pos, uPawnColor))) ||
(_RookAttacksBB(mv.cTo, pos->bbOccupied) &
(pos->bbPieces[uPawnColor][ROOK] |
pos->bbPieces[uPawnColor][QUEEN])) ||
(_BishopAttacksBB(mv.cTo, pos->bbOccupied) &
pos->bbPieces[uPawnColor][QUEEN])))
{
*piExtend += QUARTER_PLY;
INC(ctx->sCounters.extension.uPawnPushByQuarterPly[THREE_QUARTERS_PLY / QUARTER_PLY]);
}
else
{
INC(ctx->sCounters.extension.uPawnPushByQuarterPly[HALF_PLY / QUARTER_PLY]);
}
INC(ctx->sCounters.extension.uPawnPush);
}
}
#if 0
// Responses to check extensions --- moved to search.c @ positional bonus
if (IS_CHECKING_MOVE(mvLast))
{
ASSERT(IS_ESCAPING_CHECK(mv));
iMoveScore = iRoughEval + ComputeMoveScore(ctx, mv, uMoveNum);
// This is forced and cheap (1 move at the parent node).
if (ONE_LEGAL_MOVE(ctx, ctx->uPly - 1) &&
CountKingSafetyDefects(&ctx->sPosition, uColor) > 2)
{
FLAG fBigBonus = (iMoveScore + VALUE_KNIGHT > iAlpha);
*piExtend += (QUARTER_PLY + HALF_PLY * fBigBonus);
INC(ctx->sCounters.extension.uOneLegalMoveByQuarterPly[
fBigBonus ?
(THREE_QUARTERS_PLY / QUARTER_PLY) :
(QUARTER_PLY / QUARTER_PLY)]);
}
// One "good" way to response to check --- dead code, kill it?
if (!fIsLeftoverMove &&
mv.pCaptured &&
(iRoughEval + 300 < iAlpha) &&
(iMoveScore + 50 > iAlpha))
{
*piExtend += ONE_PLY;
INC(ctx->sCounters.extension.uSingularReplyToCheck);
}
}
#endif
// These last ones only happen if we are close to the root score.
ASSERT(_window[ctx->uPly] > 0);
if ((iRoughEval >= (g_iRootScore[uColor] - _window[ctx->uPly] * 2)) &&
(iRoughEval <= (g_iRootScore[uColor] + _window[ctx->uPly] * 2)))
{
// Recapture extension. Own tighter (1x) window restored --
// measured on ECM.721 (ringers): sharing the outer 2x window
// grew this position's recapture-fire count 6.8x vs HEAD
// (17,569,874 -> 34,337,674 total nodes), far more than the
// ~2x growth every other extension category saw from stacking
// alone -- all in refuted alternative lines, not the winning
// PV (which has zero recaptures on it). The 2x window did
// recover ECM.735/ECM.443 by making trade-dense *correct*
// lines eligible, but it's a net loss on positions where the
// expensive trades are all in the lines being ruled out
// instead. Back to the tighter window as the better tradeoff.
if ((iRoughEval >= (g_iRootScore[uColor] - _window[ctx->uPly])) &&
(iRoughEval <= (g_iRootScore[uColor] + _window[ctx->uPly])) &&
(uDepth < THREE_PLY))
{
if (!fIsLeftoverMove &&
mv.pCaptured &&
!IS_PAWN(mv.pCaptured) &&
(iMoveSee >= 0) &&
((PIECE_VALUE(mv.pCaptured) == PIECE_VALUE(mvLast.pCaptured)) ||
((mvLast.pPromoted) && (mv.cTo == mvLast.cTo))))
{
*piExtend += HALF_PLY;
INC(ctx->sCounters.extension.uRecapture);
}
}
}
// Don't let extensions add up to > 1 ply
#ifdef DEBUG
iM = MIN(ONE_PLY, *piExtend);
#endif
ASSERT(!(*piExtend & 0x80000000));
*piExtend = MINU(ONE_PLY, *piExtend);
ASSERT(iM == *piExtend);
// Scale back extensions that are very far from the root. Table
// built in root.c from g_uIterateDepth (see its own construction
// there for the exact arithmetic -- this is just a summary, keep
// the two in sync):
//
// ┌─────────────────────────┬───────────┬────────────────────────────────┐
// │ ply range (× iterate │ reduction │ net effect │
// │ depth) │ │ │
// ├─────────────────────────┼───────────┼────────────────────────────────┤
// │ u < 1.5× │ 0 │ full extension kept │
// ├─────────────────────────┼───────────┼────────────────────────────────┤
// │ 1.5× ≤ u < 1.875× │ -1/4 ply │ │
// ├─────────────────────────┼───────────┼────────────────────────────────┤
// │ 1.875× ≤ u < 2.25× │ -1/2 ply │ │
// ├─────────────────────────┼───────────┼────────────────────────────────┤
// │ 2.25× ≤ u < 3× │ -3/4 ply │ only a +1 ply extension │
// │ │ │ can survive here │
// ├─────────────────────────┼───────────┼────────────────────────────────┤
// │ u ≥ 3× (hard limit) │ -all ply │ no extensions beyond here │
// └─────────────────────────┴───────────┴────────────────────────────────┘
//
// NOTE: check extension in qsearch is handled differently, see search.c.
//
ASSERT(ctx->uPly != 0);
ASSERT(ctx->uPly <= MAX_PLY_PER_SEARCH);
*piExtend -= g_uExtensionReduction[ctx->uPly-1];
#ifdef DEBUG
iM = MAX(0, *piExtend);
#endif
*piExtend = MAX0(*piExtend);
ASSERT(iM == *piExtend);
ctx->sPlyInfo[ctx->uPly-1].iExtensionAmount = *piExtend;
ASSERT((0 <= *piExtend) && (*piExtend <= ONE_PLY));
}
MOVE_KERNEL_RESULT FORCEINLINE
SearchOneMove(IN SEARCHER_THREAD_CONTEXT *ctx,
IN MOVE mv,
IN ULONG x,
IN FLAG fIsGeneratedMoveStage,
IN ULONG uDepth,
IN SCORE iAlpha,
IN SCORE iBeta,
IN SCORE iEval,
IN INT iPositionalExtend,
IN FLAG fIsLeftoverMove,
IN FLAG fThreat,
IN FLAG fFullWindow,
IN ULONG uRawDepthB,
IN ULONG uRawImproveB,
IN BITBOARD bbMinorAttacksSnapshot[2],
IN BITBOARD bbRookAttacksSnapshot[2],
#ifdef FH_USE_REGRESSION_MODEL
IN FHM_NODE_BASE sFhAlphaNodeBase,
#endif
#ifdef MOVE_ORDERING_EVIDENCE_COLLECTION
IN FLAG fThisMoveIsCountermoveMatch,
IN ULONG uCMEvidenceBucket,
#endif
#ifdef TEST_NULL
IN FLAG fNullCalibEligible,
IN ULONG uNullCalibBucket,
OUT UINT64 *puNullCalibFirstMoveNodeCost,
#endif
IN OUT ULONG *puLegalMoves,
OUT SCORE *piScore
#ifdef PERF_COUNTERS
, OUT FLAG *pfMoveIsPruneReduceEligible
, OUT ULONG *puThisMoveHangBucket
, OUT ULONG *puThisMoveGapBucket
, OUT ULONG *puThisMoveNumBucket
, OUT ULONG *puThisMoveDepthBucket
#endif
#ifdef FH_REGRESSION_COLLECTION
, OUT SCORE *piMoveValueForFhCollect
#endif
)
/**
Routine description:
The per-move kernel hoisted out of Search()'s move loop
(search.c): make the move, compute its extension, decide whether
to prune or reduce it, search it with a PVS window, re-search if
a reduced move fails high, unmake it. See UNIFY_SEARCH.md for the
full extraction rationale and a parameter-by-parameter accounting
of why each non-obvious one is here.
Deliberately NOT included (stays in each caller instead): move
acquisition (how mv was selected), result publication (iAlpha/
mvBest bookkeeping, UpdatePV, hash storage), and the split-launch
decision itself. See UNIFY_SEARCH.md's "What should NOT be
extracted" section.
Parameters:
See the prototype's own inline comments (chess.h) for the
non-obvious ones (x, uStage, fFullWindow, the node-level hoists).
Return value:
MOVE_KERNEL_RESULT -- see chess.h's enum comment.
**/
{
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
CUMULATIVE_SEARCH_FLAGS *pf = &ctx->sSearchFlags;
SCORE iMoveSee = 0;
INT iExtend;
ULONG uNextDepth;
FLAG fThisMoveLMPPruned;
FLAG fMoveIsPruneReduceEligible = FALSE;
SCORE iScore;
// This move's own predicted FH% (thousandths), to be stashed onto
// the CHILD ply's PLY_INFO before we recurse into it -- see
// chess.h's PLY_INFO.uParentMoveFHEstimate comment. A real table
// lookup only ever happens for a leftover move that also clears
// CanWeReduceOrPruneMove's eligibility gate (just below), so:
// non-leftover (hash move, good capture, killer, etc) defaults to
// MOVE_FH_ESTIMATE_NONLEFTOVER -- deliberately a high-confidence
// band, not "unknown" (see that macro's comment) -- while a
// leftover move defaults to MOVE_FH_ESTIMATE_NO_DATA (real
// "unknown"), overwritten with an actual value below if the table
// has one.
ULONG uThisMoveFHEstimate = (TRUE == fIsLeftoverMove) ?
MOVE_FH_ESTIMATE_NO_DATA :
MOVE_FH_ESTIMATE_NONLEFTOVER;
#ifdef PERF_COUNTERS
ULONG uThisMoveJointExtraTier = 0;
FLAG fThisMoveJointExtraEligible = FALSE;
ULONG uThisMoveHangBucket = 0;
ULONG uThisMoveGapBucket = 0;
ULONG uThisMoveNumBucket = 0;
ULONG uThisMoveDepthBucket = 0;
#endif
// SEE must be computed on the PRE-move position -- see.c's
// exchange walk needs the piece still sitting on cFrom.
// ComputeMoveExtension uses it for two soundness gates: the
// check extension (Crafty-style: don't extend a checking move
// that's really just a losing sacrifice) and the recapture
// extension (don't extend a "recapture" that actually loses
// material). uDepth <= THREE_PLY mirrors the recapture
// extension's own depth gate -- cheap to test here since
// uDepth is already loop-invariant, and it keeps this from
// computing a SEE on every single non-pawn capture at every
// depth. One call per move regardless of which gate(s) end up
// wanting it -- SEE is too hot a routine to pay for twice.
if (IS_CHECKING_MOVE(mv) ||
(mv.pCaptured && !IS_PAWN(mv.pCaptured) && (uDepth <= THREE_PLY)))
{
iMoveSee = GetMoveSee(ctx,
mv,
(TRUE == fIsGeneratedMoveStage) ?
(x - 1) : (ULONG)-1);
}
if (FALSE == MakeMove(ctx, mv))
{
return(MOVE_KERNEL_ILLEGAL);
}
(*puLegalMoves)++;
ASSERT((IS_CHECKING_MOVE(mv) && InCheck(&ctx->sPosition, ctx->sPosition.uToMove)) ||
(!IS_CHECKING_MOVE(mv) && !InCheck(&ctx->sPosition, ctx->sPosition.uToMove)));
#ifdef FH_REGRESSION_COLLECTION
// MUST happen here, inside this function's own Make/Unmake window
// -- EstimateHangingMaterialCp asserts the move is already applied
// on the board (DEBUG-only, but a real, silent-at-release-O3
// correctness bug otherwise: a caller computing this AFTER
// SearchOneMove has already returned -- and un-made the move --
// would be reading stale pre-move board state). Computed
// unconditionally for every move (not just the leftover-eligible
// population PERF_COUNTERS' own hang bucket below is restricted
// to) since every tier needs a move-value feature. The function
// itself branches internally for captures/promotions (returns
// -ComputeMoveScore(...), a SEE-plus-promotion material estimate)
// vs. quiet moves (real hang/attack-defense analysis) -- one call
// covers both, see its own routine comment.
*piMoveValueForFhCollect = EstimateHangingMaterialCp(
ctx, mv, (x - 1), bbMinorAttacksSnapshot, bbRookAttacksSnapshot);
#endif
// Compute per-move extension (as opposed to per-position
// extensions which are represented by iPositionalExtend).
iExtend = iPositionalExtend;
ComputeMoveExtension(ctx,
iAlpha,
iBeta,
(x - 1), // Note: x==0 if doing mvHash
iEval,
uDepth,
iMoveSee,
fIsLeftoverMove,
&iExtend);
ASSERT((*puLegalMoves > 1) ? (x != 0) : TRUE);
// Pruning on alpha... late move pruning / late move reduction.
fMoveIsPruneReduceEligible = CanWeReduceOrPruneMove(ctx,
mv,
x,
*puLegalMoves,
iExtend,
iAlpha,
fThreat,
fIsLeftoverMove);
fThisMoveLMPPruned = FALSE;
if (TRUE == fMoveIsPruneReduceEligible)
{
// In here we consider:
// - LMP (late move pruning), and
// - LMR (late move reduction).
//
// All of these have their own conditions for firing but they
// are based on dynamic signals about the move. Compute these
// once, here, at the top instead of N times, below.
// Dynamic move ordering FH attempt and FH/attempts:
ULONG uFHAttempts = 0;
ULONG uFHPctThousandths = GetMoveFailHighPctThousandths(mv, &uFHAttempts);
// Our 5D prediction table, given:
// - the gap from iEval to iAlpha here,
// - move lateness (number),
// - board material apparently hung by mv,
// - remaining depth to search, and
// - improvement...
//
// ...it will give us a predicted FH% for the move.
ULONG uRawGapB = GapCpBucket((SCORE)(iAlpha - iEval));
ULONG uRawLateB = MoveNumBucket(*puLegalMoves);
SCORE iHangCp = EstimateHangingMaterialCp(ctx, mv, (x - 1),
bbMinorAttacksSnapshot,
bbRookAttacksSnapshot);
ULONG uRawDumbB = HangCpBucket(iHangCp);
// Note: A normal fIsLeftoverMove move has a FH% rate
// of about 0.4% but this is misleading -- the
// population is actually bimodal, split between moves
// near 0% and moves legitimately much higher.
ULONG uPredictedFH;
#ifdef FH_USE_REGRESSION_MODEL
// sFhAlphaNodeBase was computed ONCE for this whole node
// (search.c, same point FhCollectNodeEntry is called) --
// every move in this loop just adds its own move-level terms
// to that same precomputed base, rather than recomputing the
// node-level terms (gap, depth, improve, material, node type)
// on every move. FhModelNodeBaseIsMateGated mirrors the old
// table's JOINT_TABLE_SENTINEL/MOVE_FH_ESTIMATE_NO_DATA "no
// data" convention -- callers below already handle that
// value gracefully, no new branching needed there.
if (TRUE == FhModelNodeBaseIsMateGated(sFhAlphaNodeBase))
{
uPredictedFH = MOVE_FH_ESTIMATE_NO_DATA;
}
else
{
FH_COLLECT_TIER eTier = FhModelTierForMove(
x, mv, ctx->sMoveStack.mvf[x - 1].iValue);
uPredictedFH = FhModelAlphaMoveThousandths(
sFhAlphaNodeBase, iHangCp, *puLegalMoves,
uFHPctThousandths, uFHAttempts, eTier);
}
#else
uPredictedFH = _JointTablePredictedFHThousandths(uRawDepthB,
uRawDumbB,
uRawGapB,
uRawLateB,
uRawImproveB);
#endif
// JOINT_TABLE_SENTINEL and MOVE_FH_ESTIMATE_NO_DATA are the
// same numeric value on purpose -- see both macros' comments.
uThisMoveFHEstimate = uPredictedFH;
// Late move pruning; skip searching under this move?
#ifndef FH_REGRESSION_COLLECTION
fThisMoveLMPPruned = ShouldLatePrune(
ctx,
uDepth,
*puLegalMoves,
uFHAttempts,
uFHPctThousandths,
uPredictedFH);
#else
// A collection build must not let LMP skip a move before
// FhCollectMoveTried (search.c's move loop) ever gets a chance
// to log it -- ShouldLatePrune is itself partly driven by
// uPredictedFH, i.e. the CURRENTLY LOADED (soon-to-be-replaced)
// data.c table, so leaving it live here would mean the old
// table decides which moves are "safe enough" to go
// unobserved by the new collection, silently censoring the
// population it's trying to measure. Force every eligible
// leftover move to actually be tried instead.
fThisMoveLMPPruned = FALSE;
#endif
// If LMP didn't fire, we are going to search below this
// move. But if the move is very late, we might reduce
// the depth of the search a bit. LMR = late move reductions.
// We never reduce a move such that it drops directly into
// QSearch though; hence the TWO_PLY requirement below.
if ((FALSE == fThisMoveLMPPruned) &&
(uDepth > TWO_PLY))
{
ULONG uExtraTier = 0;
INT iLMR = GetLMRReduction(ctx,
uDepth,
*puLegalMoves,
mv,
iExtend,
uFHAttempts,
uFHPctThousandths,
uPredictedFH,
&uExtraTier);
if (iLMR < 0)
{
ASSERT(iExtend == 0);
iExtend = iLMR;
#ifdef PERF_COUNTERS
uThisMoveJointExtraTier = uExtraTier;
fThisMoveJointExtraEligible = TRUE;
INC(ctx->sCounters.tree.u64JointExtraTries[uExtraTier]);
#endif
}
}
} // LMP, LMR -- move pruning and reduction
if (TRUE == fThisMoveLMPPruned)
{
#ifdef PERF_COUNTERS
INC(ctx->sCounters.tree.u64LMPPruned);
#endif
TDMove(ctx, uDepth, iAlpha, iBeta,
IS_CAPTURE_OR_PROMOTION(mv) ? "CAP" : "QUIET",
"LMP", 0.0, 0.0, 0, TRUE);
UnmakeMove(ctx, mv);
ASSERT(PositionsAreEquivalent(&ctx->sPosition, &pi->sPosition));
#ifdef PERF_COUNTERS
*pfMoveIsPruneReduceEligible = fMoveIsPruneReduceEligible;
#endif
return(MOVE_KERNEL_PRUNED);
}
#ifdef PERF_COUNTERS
if (TRUE == fIsLeftoverMove)
{
INC(ctx->sCounters.tree.u64LeftoverTries);
#ifdef HASHCAP_COLLECTION
INC(ctx->sCounters.tree.u64HashCapTries
[pi->fHashMoveIsCapture ? 1 : 0]
[(NODE_CUT == pi->eNodeType) ? 1 : 0]);
#endif
// FH_REGRESSION_COLLECTION needs no separate per-move "tries"
// log here, unlike the old FH_TABLE_COLLECTION design -- the
// new per-move record (tries AND outcome together) is
// emitted once, back in search.c's move loop, by
// FhCollectMoveTried once this move's real score is known;
// there's nothing for this pre-search eligibility site to log.
}
#endif // PERF_COUNTERS
#ifdef MOVE_ORDERING_EVIDENCE_COLLECTION
// Deliberately its own gate, not nested under PERF_COUNTERS
// above -- see MOI_INC/MOVE_ORDERING_EVIDENCE_COLLECTION
// comment (chess.h).
if (TRUE == fThisMoveIsCountermoveMatch)
{
MOI_INC(ctx->sCounters.tree.u64CMEvidenceTries[uCMEvidenceBucket]);
}
#endif
// Record the extension/reduction actually applied to
// THIS move, unconditionally -- not just when it's
// negative. Leaving this stale from whatever earlier
// move at this ply last happened to set it let a child
// node checking "was my parent's move reduced" via
// (pi-1)->iExtensionAmount < 0 read a leftover value
// from a completely different sibling move, not the
// one actually played.
pi->iExtensionAmount = iExtend;
pf->iCumulativeExtend += iExtend;
// Stash this move's predicted FH% on the CHILD ply (MakeMove above
// already incremented ctx->uPly) -- see chess.h's PLY_INFO.
// uParentMoveFHEstimate comment. Must happen before the recursive
// Search() calls below, and after any point where mv could still
// change (it can't past here).
ctx->sPlyInfo[ctx->uPly].uParentMoveFHEstimate = uThisMoveFHEstimate;
// Compute the next search depth for this move/subtree.
uNextDepth = uDepth - ONE_PLY + iExtend;
if (uNextDepth >= MAX_DEPTH_PER_SEARCH) {
uNextDepth = 0;
}
ASSERT(pf->fAvoidNullmove == FALSE);
if (TRUE == fFullWindow)
{
// First move, full a..b window.
ASSERT(*puLegalMoves == 1);
#ifdef TEST_NULL
// Cost side of the null-move calibration harness'
// try-vs-skip EV estimate: this is the "R=0"
// alternative the null probe (see above) is being
// weighed against -- the real first move's own
// full-depth subtree cost. uLegalMoves==1 guarantees
// this fires exactly once per node.
if (fNullCalibEligible)
{
UINT64 u64NodesBeforeFirstMove =
ctx->sCounters.tree.u64TotalNodeCount;
iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
*puNullCalibFirstMoveNodeCost =
ctx->sCounters.tree.u64TotalNodeCount -
u64NodesBeforeFirstMove;
}
else
#endif
iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
}
else
{
// Moves 2..N, try a minimal window search
iScore = -Search(ctx, -iAlpha - 1, -iAlpha, uNextDepth);
if ((iAlpha < iScore) && (iScore < iBeta))
{
iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
}
}
// Deeper verification search late move reduction FH.
if ((iExtend < 0) && (iScore >= iBeta))
{
#ifdef PERF_COUNTERS
// Calibration for the joint-extra-reduction tiers
// above: did the tier this move was assigned (0 ==
// GetLMRReduction's baseline only, 1-3 == extra
// plies the table added) actually predict a
// re-search here? If low-predicted-FH tiers show an
// ELEVATED research rate rather than a lower one,
// that's the distribution-shift failure this
// project's history keeps producing, caught here
// (a suite run) instead of in a self-play match.
if (TRUE == fThisMoveJointExtraEligible)
{
INC(ctx->sCounters.tree.u64JointExtraResearch[uThisMoveJointExtraTier]);
}
#endif
// Undo the full reduction, whatever its magnitude...
uNextDepth -= iExtend;
pi->iExtensionAmount = 0;
iScore = -Search(ctx, -iBeta, -iAlpha, uNextDepth);
}
#if defined(PERF_COUNTERS) && defined(JOINT_EXTRA_VERIFY)
// "Silent miss" shadow verification -- only reachable
// when the branch above did NOT fire, i.e. this move's
// extra-reduced score was < beta and so triggered no
// real re-search. Would removing just the EXTRA plies
// (restoring the depth HEAD's own baseline -ONE_PLY
// reduction alone would have used) have found a
// fail-high we're about to silently miss? Full
// coverage, every extra-reduced move that reaches here
// -- see GNUmakefile's JOINT_EXTRA_VERIFY comment for
// why this is calibration-only, never a normal build.
else if ((TRUE == fThisMoveJointExtraEligible) &&
(uThisMoveJointExtraTier > 0))
{
ULONG uShadowDepth =
uNextDepth + (uThisMoveJointExtraTier * ONE_PLY);
SCORE iShadowScore;
#ifdef NEUTRALIZE_NULL_BAILOUT
// 2026-09-29: searchsup.c's null-move "history-
// reduced bailout" branch (Tord Romstad idea) reads
// (pi-1)->iExtensionAmount -- OUR OWN reduction on
// mv -- to decide whether to fabricate a "please
// re-search me" placeholder score instead of a
// real one. In a real move-loop search that's
// correct: the fabricated score negates up to
// exactly iBeta+1 one level up, which search.c's
// own re-search-on-fail-high machinery correctly
// interprets and acts on. Our shadow verification
// is a bespoke one-off Search() call with no such
// wrapper, so we'd misread that signal as a
// genuinely-computed fail-high. Temporarily zero
// OUR OWN pi->iExtensionAmount so this one specific
// check can't fire for mv -- everything deeper in
// the shadow subtree still goes through the normal
// move loop (with its wrapper intact) if the same
// mechanism legitimately fires there for some
// other, unrelated reduced move.
INT iSavedExtensionAmount = pi->iExtensionAmount;
pi->iExtensionAmount = 0;
#endif
iShadowScore =
-Search(ctx, -iBeta, -iAlpha, uShadowDepth);
#ifdef NEUTRALIZE_NULL_BAILOUT
pi->iExtensionAmount = iSavedExtensionAmount;
#endif
#ifdef SILENT_MISS_TRACE
// pos is the POST-move position here (UnmakeMove
// has not run yet) -- same convention as the
// JOINT_EXTRA_VERIFY trace above.
// 2026-10-03: log the DYNAMIC signals alongside
// the static prediction, so a real miss can be
// interrogated for "what would have saved us, and
// at what threshold". Motivated by the band-0
// miss at
// 6k1/p4p1p/3p2q1/2p1rP2/2P3p1/P7/1P1Qn1PK/3R1R2,
// Qg6 -- a move whose queen only LOOKS hung
// (White is losing too badly to take it; best
// line grabs the e2 knight and White is -14 at
// depth 19), i.e. a genuine structural
// mispredict of the dumbness axis, which no
// amount of sampling conservatism in the static
// table can catch.
//
// fhpct/fhatt: this exact move identity's own
// observed rate and sample count
// (GetMoveFailHighPctThousandths) -- answers
// "what GetMoveFailHigh threshold would have
// vetoed this".
// cm: countermove-table level -- 0 none, 1 slot
// 0 match, 2 slot 1 match, against the move
// played two plies back (the index
// generate.c's _ScoreAllMoves uses).
// hist/cont: accumulated history and
// continuation-history evidence for this
// [piece][to].
// killer: 1 if this ply's killer, 2 if ply-3's.
CHAR szShadowPV[SMALL_STRING_LEN_CHAR] = "";
{
MOVE mvChain[8];
ULONG uChainLen = 0;
MOVE mvNext;
while ((uChainLen < 8) &&
(0 != (mvNext = GetPonderMove(&ctx->sPosition)).uMove))
{
strncat(szShadowPV, MoveToSan(mvNext, &ctx->sPosition),
ARRAY_LENGTH(szShadowPV) - strlen(szShadowPV) - 1);
strncat(szShadowPV, " ",
ARRAY_LENGTH(szShadowPV) - strlen(szShadowPV) - 1);
mvChain[uChainLen++] = mvNext;
if (FALSE == MakeMove(ctx, mvNext))
{
uChainLen--;
break;
}
}
while (uChainLen > 0)
{
UnmakeMove(ctx, mvChain[--uChainLen]);
}
}
#endif
// EFP-tier-aligned bucket for the FULLY (base +
// extra) reduced search's actual remaining depth --
// see _PostReduceDepthBucketEfpAligned's comment.
ULONG uPostReduceDepthBucket =
_PostReduceDepthBucketEfpAligned(uNextDepth);
INC(ctx->sCounters.tree.u64JointExtraVerifyTries
[uThisMoveJointExtraTier][uPostReduceDepthBucket]);
if (iShadowScore >= iBeta)
{
INC(ctx->sCounters.tree.u64JointExtraVerifySilentMiss
[uThisMoveJointExtraTier][uPostReduceDepthBucket]);
if (iShadowScore == (iBeta + 1))
{
INC(ctx->sCounters.tree.u64JointExtraVerifyNullBailoutSignature
[uThisMoveJointExtraTier]);
}
#ifdef SILENT_MISS_TRACE
Trace("SILENT_MISS_TRACE tier=%u bucket=%u "
"uNextDepth=%lu uShadowDepth=%lu "
"alpha=%d beta=%d "
"realScore=%d shadowScore=%d "
"move=%s postMoveFen=\"%s\" "
"shadowRefutation=\"%s\"\n",
uThisMoveJointExtraTier,
uPostReduceDepthBucket,
uNextDepth, uShadowDepth,
iAlpha, iBeta,
iScore, iShadowScore,
MoveToIcs(mv),
PositionToFen(&ctx->sPosition),
szShadowPV);
#endif
}
}
#endif
TDMove(ctx, uDepth, iAlpha, iBeta,
fFullWindow ? "FIRST" : IS_CAPTURE_OR_PROMOTION(mv) ? "CAP" : "QUIET",
(iExtend < 0) ? "LMR" : (iExtend > 0) ? "EXT" : "FULL",
(iExtend < 0) ? -(double)iExtend / ONE_PLY : 0.0,
(iExtend > 0) ? (double)iExtend / ONE_PLY : 0.0,
iScore, FALSE);
UnmakeMove(ctx, mv);
pf->iCumulativeExtend -= iExtend;
ASSERT(PositionsAreEquivalent(&ctx->sPosition, &pi->sPosition));
#ifdef PERF_COUNTERS
*pfMoveIsPruneReduceEligible = fMoveIsPruneReduceEligible;
*puThisMoveHangBucket = uThisMoveHangBucket;
*puThisMoveGapBucket = uThisMoveGapBucket;
*puThisMoveNumBucket = uThisMoveNumBucket;
*puThisMoveDepthBucket = uThisMoveDepthBucket;
#endif
*piScore = iScore;
if (WE_SHOULD_STOP_SEARCHING)
{
return(MOVE_KERNEL_ABORTED);
}
return(MOVE_KERNEL_SEARCHED);
}
#ifdef DO_IID
SCORE
RescoreMovesViaSearch(IN SEARCHER_THREAD_CONTEXT *ctx,
IN ULONG uDepth,
IN SCORE iAlpha,
IN SCORE iBeta)
/**
Routine description:
This is my implementation of "internal iterative deepening". It's
not really IID because it doesn't recurse on the same position.
This code is called when we are at a PV node and have no hash move
and no good capture from the generator. Instead of relying on
only history / killer heuristics to order the moves instead we
reduce the depth by two ply and search all the moves generated.
The scores that come out of the reduced-depth search are then used
to order the moves at the regular-depth search. This is somewhat
recursive because the first move considered by the reduced-depth
search may also have no hash move / good capture and invoke the
whole process again.
Parameters:
IN SEARCHER_THREAD_CONTEXT *ctx,
IN ULONG uDepth,
IN SCORE iAlpha,
IN SCORE iBeta
Return value:
SCORE
**/
{
ULONG x, uBegin, uEnd;
MOVE mv;
SCORE iScore;
SCORE iBestScore = -INFINITY_SCORE;
ULONG uBest;
FLAG fFailHigh = FALSE;
SCORE rgScores[MAX_MOVES_PER_PLY];
//
// Preconditions
//
ASSERT(IS_VALID_SCORE(iAlpha));
ASSERT(IS_VALID_SCORE(iBeta));
ASSERT(iAlpha < iBeta);
ASSERT(uDepth >= (IID_R_FACTOR + ONE_PLY));
//
// Compute next depth.
//
// This used to recurse here first (call itself at this same
// ctx->uPly, before the loop below), on the theory that an even
// shallower rescore's *side effects* -- hash/killer/history table
// population -- would help the loop below's own -Search() calls
// find cutoffs faster. Measured (see lmr_testing/RESULTS.md): removing
// it entirely produced a bit-identical result on all three test
// suites (ecm_ringers/confident_quick/hard_quick). Its own writes to
// iValue were always fully overwritten by this same call's loop
// right after it (same ctx->uPly, same move-stack range), so it had
// no way to help other than those side effects, and empirically it
// wasn't -- just wasted nodes. Removed.
uDepth -= (IID_R_FACTOR + ONE_PLY);
ASSERT(uDepth < MAX_DEPTH_PER_SEARCH);
//
// Search the moves and remember the scores in a scratch array, NOT
// directly into mvf[].iValue -- we don't yet know if we'll get an
// honest score for every move at this ply (a fail-high partway
// through means we stop early, deliberately, without searching the
// rest). Committing partial data into iValue and then patching the
// gaps with a sentinel (this function used to write -INFINITY_SCORE into
// every unsearched move) makes the whole ply look "rescored" to
// downstream code when it isn't really -- see the fail-high handling
// below for why that matters.
//
uBegin = ctx->sMoveStack.uBegin[ctx->uPly];
uEnd = ctx->sMoveStack.uEnd[ctx->uPly];
ASSERT((uEnd - uBegin) <= MAX_MOVES_PER_PLY);
for (x = uBest = uBegin; x < uEnd; x++)
{
SelectBestNoHistory(ctx, x);
mv = ctx->sMoveStack.mvf[x].mv;
mv.bvFlags |= WouldGiveCheck(ctx, mv);
ctx->sMoveStack.mvf[x].mv = mv; // <-- update the move's flags, WouldGiveCheck is slow
if (TRUE == MakeMove(ctx, mv))
{
// This loop recurses into Search() directly, not through
// SearchOneMove (which stashes this on every OTHER
// recursion -- see chess.h's PLY_INFO.uParentMoveFHEstimate
// comment). An IID rescore pass has no real leftover-move
// table lookup to report here -- MOVE_FH_ESTIMATE_NO_DATA
// ("unknown"), not MOVE_FH_ESTIMATE_NONLEFTOVER (which
// would falsely claim high confidence).
ctx->sPlyInfo[ctx->uPly].uParentMoveFHEstimate =
MOVE_FH_ESTIMATE_NO_DATA;
if (-INFINITY_SCORE == iBestScore)
{
iScore = -Search(ctx, -iBeta, -iAlpha, uDepth);
}
else
{
iScore = -Search(ctx, -iAlpha - 1, -iAlpha, uDepth);
if (iScore > iAlpha)
{
iScore = -Search(ctx, -iBeta, -iAlpha, uDepth);
}
}
UnmakeMove(ctx, mv);
rgScores[x - uBegin] = iScore;
if (iScore > iBestScore)
{
uBest = x;
iBestScore = iScore;
if (iScore >= iBeta)
{
fFailHigh = TRUE;
break;
}
}
}
else
{
// Genuinely illegal (pseudo-legal but leaves king in check)
// -- this isn't "unknown," we know for a fact it's worthless
// and the caller will skip it too when MakeMove fails again.
rgScores[x - uBegin] = -INFINITY_SCORE;
}
}
if (FALSE == fFailHigh)
{
// We have an honest, fully-searched score for every move at
// this ply -- commit them all and let downstream code
// (ComputeMoveScore, the main search loop's move-selection
// call) trust iValue as a real eval-axis score.
for (x = uBegin; x < uEnd; x++)
{
ctx->sMoveStack.mvf[x].iValue = rgScores[x - uBegin];
}
ctx->sPlyInfo[ctx->uPly].eMoveScoringScheme = MOVE_SCORING_IID_RESCORED;
}
else
{
// We only know one honest thing: uBest is good enough to have
// failed high at reduced depth. We do NOT have honest scores
// for the rest (deliberately -- searching them would burn nodes
// solely to confirm what we've already decided to do, which is
// play uBest). Rather than inventing eval-axis values for moves
// we never examined (the old code wrote -INFINITY_SCORE into all of
// them, including -- until fixed -- overwriting uBest's own
// just-computed score), leave every move's original generate.c
// ordering value completely untouched and just bump uBest into
// killer-tier territory so the normal (non-rescored) selection
// path -- SelectBestWithHistory/NoHistory -- picks it first, the
// same trick generate.c uses for a real killer move. Do NOT
// change eMoveScoringScheme: this ply's iValue is back to being
// whatever generate.c scheme originally scored it, not real
// scores, for every move including uBest (whose bump is itself
// just an ordering flag, not part of its own eval-axis value).
ctx->sMoveStack.mvf[uBest].iValue |= FIRST_KILLER;
}
ASSERT(IS_VALID_SCORE(iBestScore));
return(iBestScore);
}
#endif
FLAG
MateDistancePruningCutoff(IN ULONG uPly,
IN FLAG fInCheck,
IN OUT SCORE *piBestScore,
IN OUT SCORE *piAlpha,
IN OUT SCORE *piBeta)
/**
Routine description:
This idea (shamelessly?) "borrowed" from Fruit. The idea is that
the worst score we can return from any node in the tree is if we
are in checkmate right now (indeed, if we're not in check right
now than the worst score we can return is mated-in-2-ply).
Likewise the best score we can return from here is mate-in-1-ply.
Use these facts to attempt to narrow the alpha..beta window.
Indeed there are some cases where we can prune this entire tree
branch.
Parameters:
ULONG uPly : ply from root
FLAG InCheck : are we in check?
SCORE *piBestScore : pointer to bestscore
SCORE *piAlpha : pointer to alpha
SCORE *piBeta : pointer to beta
Return value:
FLAG : TRUE if we can prune the branch outright, FALSE otherwise
**/
{
SCORE iScore = MATED_SCORE(uPly + 2 * !fInCheck);
//
// Do the alpha side
//
if (*piAlpha < iScore)
{
*piAlpha = iScore;
if (iScore >= *piBeta)
{
*piBestScore = iScore;
return(TRUE);
}
}
//
// Do the beta side
//
iScore = -1 * MATED_SCORE(uPly + 1);
if (iScore < *piBeta)
{
*piBeta = iScore;
if (iScore <= *piAlpha)
{
*piBestScore = iScore;
return(TRUE);
}
}
return(FALSE);
}
void
DumpPlyInfoStack(IN SEARCHER_THREAD_CONTEXT *ctx,
IN SCORE iAlpha,
IN SCORE iBeta)
/**
Routine description:
Dump some information about the current search line; mainly here as
a debugging aide.
Note: this will not work on an MP searcher thread that is under a
split node.
Parameters:
SEARCHER_THREAD_CONTEXT *ctx : searcher context to dump
Return value:
void
**/
{
ULONG u, v;
POSITION *pos = GetRootPosition();
CUMULATIVE_SEARCH_FLAGS *pf = &ctx->sSearchFlags;
char *p = PositionToFen(pos);
PLY_INFO *q;
FLAG fSeenQ = FALSE;
SCORE iEval;
static SEARCHER_THREAD_CONTEXT temp;
InitializeSearcherContext(pos, &temp);
Trace("Iterate Depth: %2u\tCurrent Ply: %2u\n", g_uIterateDepth,
ctx->uPly);
Trace("Qsearch Check: %2u\tCurrent Qdepth: %2u\n", pf->uQsearchCheckDepth,
pf->uQsearchDepth);
Trace("Current a..b: %d .. %d\n", iAlpha, iBeta);
if (NULL != p)
{
Trace("Root: %s\n", p);
SystemFreeMemory(p);
}
Trace("\n");
Trace("move\t number\t exten\t eval b.keval w.keval Danger Squares\n"
"----------------------------------------------------------------------------\n");
ASSERT(ctx->uPly < MAX_PLY_PER_SEARCH);
for (u = 0; u < ctx->uPly; u++)
{
q = &ctx->sPlyInfo[u];
ASSERT(PositionsAreEquivalent(&q->sPosition, &temp.sPosition));
if ((FALSE == fSeenQ) && (q->fInQsearch == TRUE))
{
p = PositionToFen(&temp.sPosition);
if (NULL != p)
{
Trace("\nHorizon: %s\n\n", p);
SystemFreeMemory(p);
}
fSeenQ = TRUE;
}
Trace("%02u.%-6s ", u, MoveToSan(q->mv, &temp.sPosition));
for (v = ctx->sMoveStack.uBegin[u];
v < ctx->sMoveStack.uEnd[u];
v++)
{
if (IS_SAME_MOVE(q->mv, ctx->sMoveStack.mvf[v].mv))
{
Trace("%u/%u", v - ctx->sMoveStack.uBegin[u] + 1,
MOVE_COUNT(ctx, u));
}
}
Trace("\t");
if (FALSE == MakeMove(&temp, q->mv))
{
Trace("Illegal move?!\n");
return;
}
if (q->iExtensionAmount != 0)
{
Trace("%-3u\t", q->iExtensionAmount);
}
else
{
Trace(" \t");
}
iEval = Eval(&temp, -INFINITY_SCORE, +INFINITY_SCORE, NULL);
Trace("%5s (%+2d) | ", ScoreToString(iEval),
temp.sPosition.iMaterialBalance[temp.sPosition.uToMove] / 100);
Trace("%5s (%2u) | ",
ScoreToString(temp.sPlyInfo[temp.uPly].iKingScore[BLACK]),
CountKingSafetyDefects(&temp.sPosition, BLACK));
Trace("%5s (%2u) ",
ScoreToString(temp.sPlyInfo[temp.uPly].iKingScore[WHITE]),
CountKingSafetyDefects(&temp.sPosition, WHITE));
Trace("\n");
}
p = PositionToFen(&ctx->sPosition);
if (NULL != p)
{
Trace("\n");
Trace("Now: %s\n", p);
SystemFreeMemory(p);
}
}
FLAG FORCEINLINE
CommonSearchInit(IN SEARCHER_THREAD_CONTEXT *ctx,
IN OUT SCORE *piAlpha,
IN OUT SCORE *piBeta,
IN OUT SCORE *piScore)
/**
Routine description:
A set of common code that is called by Search and QSearch. It does
the following:
1. Increment the total node counter
2. Clears pi->mvBest and cDanger squares
3. Possibly check for user input or timer expiration
4. Checks to see if the position is a draw
5. Makes sure ctx->uPly is not too deep
6. Sets pi->fInCheck
7. Does mate-distance pruning
Parameters:
IN SEARCHER_THREAD_CONTEXT *ctx,
IN OUT SCORE *piAlpha,
IN OUT SCORE *piBeta,
IN OUT SCORE *piScore
Return value:
FLAG : TRUE if the search node should be aborted (return *piScore)
FALSE otherwise (*piAlpha, *piBeta possibly adjusted)
**/
{
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
FLAG fRet = TRUE;
ASSERT(*piAlpha < *piBeta);
//
// Increment node count and see if we need to check input / timer
//
ctx->sCounters.tree.u64TotalNodeCount++;
ASSERT(ctx->sCounters.tree.u64TotalNodeCount > 0);
if ((ctx->sCounters.tree.u64TotalNodeCount &
g_MoveTimer.uNodeCheckMask) == 0)
{
(void)CheckInputAndTimers(ctx);
}
//
// Make sure that the time allotted to search in has not expired
// and (if this is an MP search) that we are still doing relevant work.
//
if (WE_SHOULD_STOP_SEARCHING)
{
// 2026-09-18: same staleness hazard as the IsDraw/too-deep
// paths below -- clear this ply's own PV[] slot too, not just
// mvBest. See the IsDraw branch's comment for the full
// mechanism (an ancestor's UpdatePV blindly copies this row
// forward assuming it's fresh).
pi->mvBest.uMove = 0;
pi->PV[ctx->uPly].uMove = 0;
*piScore = INVALID_SCORE;
goto end;
}
//
// Set fInCheck in this ply info struct
//
pi->fInCheck = (IS_CHECKING_MOVE((pi-1)->mv) != 0);
ASSERT((pi->fInCheck &&
(InCheck(&ctx->sPosition, ctx->sPosition.uToMove))) ||
(!pi->fInCheck &&
(!InCheck(&ctx->sPosition, ctx->sPosition.uToMove))));
//
// See if this position is a draw -- checked before the too-deep
// bailout below on purpose: a position can be simultaneously
// "too deep" (hit the ply/qsearch-extend-limit ceiling) and
// genuinely drawn (repetition/50-move), and a draw is a known,
// exact fact about the position, not an estimate -- it would be
// strictly worse to throw that away for an alpha/Eval()
// approximation just because we also happened to run out of
// search room at the same node.
//
if (TRUE == IsDraw(ctx))
{
// Every early exit from this function must clear pi->mvBest
// itself, since the real reset further down is never reached
// from here. Found via a DEBUG-build assertion failure:
// TryNullmovePruning reading (pi+1)->mvBest as if it reflected
// the null-move probe's own search, when it was actually stale
// data left by a completely unrelated earlier node that once
// occupied the same ply slot and bailed out via this exact path
// without ever being cleared.
pi->mvBest.uMove = 0;
INC(ctx->sCounters.tree.u64LeafCount);
*piScore = g_iDrawScore[ctx->sPosition.uToMove];
// 2026-09-18: pi->PV[ctx->uPly] has the exact same staleness
// hazard as pi->mvBest above. That was fixed defensively back
// then (clear the row when the draw score misses the ambient
// (alpha, beta) window, rather than leave whatever an
// unrelated earlier node last wrote in this shared sPlyInfo[]
// slot) rather than at the root: a repetition/50-move draw is
// a known, exact fact about the position, not a bound, so
// there's no reason its PV record should depend on the
// window at all -- unconditionally recording it here (same
// reasoning now applied to MATEMOVE/RECOGNMOVE/EGTBMOVE in
// search.c) makes the staleness hazard this comment used to
// describe structurally unreachable from this site, not just
// defended against.
UpdatePV(ctx, DRAWMOVE);
goto end;
}
//
// Make sure we have not exceeded max ply; note that since this
// is checked at the beginning of search/qsearch and if we let
// the past they will call MakeMove this must cut off one ply
// before the hard limit.
//
if ((ctx->uPly >= (MAX_PLY_PER_SEARCH - 1)) ||
(ctx->sSearchFlags.uQsearchDepth >= g_uHardExtendLimit))
{
#ifdef PERF_COUNTERS
if (ctx->uPly >= (MAX_PLY_PER_SEARCH - 1))
{
INC(ctx->sCounters.tree.u64TooDeepPlyLimit);
}
else
{
INC(ctx->sCounters.tree.u64TooDeepQsearchExtendLimit);
}
#endif
// Was an unconditional *piScore = *piBeta -- an unearned
// fail-high claim ("this line is at least beta") with zero
// evidence behind it, right at the moment we're giving up
// because we ran out of room to actually determine anything.
// A fail-low (return alpha) is the honest "couldn't prove
// this helps" posture every other give-up path in this engine
// uses. When NOT in check we can do better than a bare
// fail-low, though: fall back to a real Eval() call, the same
// convention normal QSearch's own stand-pat uses at its
// horizon. NOT when in check -- IS_CHECKING_MOVE((pi-1)->mv)
// is the same cheap (no board scan) check pi->fInCheck itself
// uses a few lines below -- Eval() on an in-check position is
// exactly the thing QSearchFromCheckNoStandPat's entire
// design exists to avoid trusting (see its header comment):
// static material/positional terms can't tell "checked with a
// totally safe escape" from "checked and actually in danger."
if (pi->fInCheck)
{
*piScore = *piAlpha;
pi->iEval = INVALID_SCORE;
}
else
{
*piScore = Eval(ctx, *piAlpha, *piBeta, NULL);
pi->iEval = *piScore;
}
// See the IsDraw branch above -- same staleness hazard, same
// fix -- this path returns a live, legitimate score (either a
// real Eval() call or *piAlpha) that absolutely can raise an
// ancestor's alpha, and is reached constantly (any node
// against the ply ceiling or qsearch-extend limit), making it
// the most likely real source of the reproduced WalkPV
// staleness bug (see the IsDraw branch's comment for the full
// mechanism and the move.c:881 assert it produces).
pi->mvBest.uMove = 0;
pi->PV[ctx->uPly].uMove = 0;
goto end;
}
//
// Erase deeper killer moves
//
if (ctx->uPly + 2 < MAX_PLY_PER_SEARCH)
{
ctx->mvKiller[ctx->uPly + 2][0].uMove = 0;
ctx->mvKiller[ctx->uPly + 2][1].uMove = 0;
}
//
// This code is for a debug option where I dump paths from root
// to leaf along with extensions and evals at each node in the
// path for debugging/brainstorming purposes.
//
pi->PV[ctx->uPly].uMove = 0;
pi->mvBest.uMove = 0;
pi->iExtensionAmount = 0;
pi->iEval = INVALID_SCORE;
#if 0
if ((g_uIterateDepth > 5) &&
(ctx->uPly > 2.5 * g_uIterateDepth))
{
DumpPlyInfoStack(ctx, *piAlpha, *piBeta);
}
#endif
//
// Do mate-distance pruning
//
if (TRUE == MateDistancePruningCutoff(ctx->uPly,
pi->fInCheck,
piScore,
piAlpha,
piBeta))
{
ASSERT(*piScore != -INFINITY_SCORE);
ASSERT((*piScore <= *piAlpha) || (*piScore >= *piBeta));
goto end;
}
#ifdef DEBUG
pi->iAlpha = *piAlpha;
pi->iBeta = *piBeta;
#endif
// Classic PVS node typing (see NODE_TYPE's definition in chess.h).
// Centralized here rather than in each caller's move loop
// (search.c, root.c, split.c) since CommonSearchInit is the one
// place both Search() and QSearch() funnel through -- a wide
// window is unambiguously PV regardless of move number (this
// covers "first move of a PV node" for free, no need to track
// which move number got us here); a narrow window's type depends
// only on the PARENT's own type, not on move number either: a CUT
// parent's children are ALL (expected to fail low, must search
// everything to prove it), and both a PV parent's non-first
// children AND an ALL parent's children are CUT (expected to fail
// high). The ctx->uPly==0 guard is defensive only -- root is
// always called with a wide window in practice, so the width check
// above already handles it.
if (*piBeta != *piAlpha + 1)
{
pi->eNodeType = NODE_PV;
}
else if (ctx->uPly == 0)
{
pi->eNodeType = NODE_CUT;
}
else
{
NODE_TYPE eParentType = ctx->sPlyInfo[ctx->uPly - 1].eNodeType;
pi->eNodeType = (NODE_CUT == eParentType) ? NODE_ALL : NODE_CUT;
}
fRet = FALSE;
end:
ASSERT(IS_VALID_FLAG(fRet));
return(fRet);
}
ULONG
SelectNullmoveRFactor(SEARCHER_THREAD_CONTEXT *ctx,
INT uDepth)
{
ULONG u;
ULONG uMaxPiecesPerSide = MAXU(TotalNonPawnCount(&ctx->sPosition, WHITE),
TotalNonPawnCount(&ctx->sPosition, BLACK));
ASSERT(uMaxPiecesPerSide <= 16);
if (uMaxPiecesPerSide < 3)
{
// Sparse material on the mover's side: stay with the
// conservative, non-growing reduction rather than risk a
// zugzwang-prone position getting an aggressive R. (The
// TotalNonPawnCount < 4 verification search in
// TryNullmovePruning is the other half of this safety net.)
u = TWO_PLY;
}
else
{
// Crafty-style growth: R = 3 + depth / 6 (in whole plies),
// scaled into our fractional-ply depth units.
u = THREE_PLY + ((uDepth / (6 * ONE_PLY)) * ONE_PLY);
}
return(u);
}
FLAG WeShouldTryNullmovePruning(SEARCHER_THREAD_CONTEXT *ctx,
SCORE iAlpha,
SCORE iBeta,
SCORE iEval,
SCORE iImprovement,
ULONG uNullDepth)
/**
Routine description:
Two-stage try/skip decision, replacing the old flat >2-non-pawn-
piece gate plus per-depth eval-margin table. Calibrated from a
30K-position, sd-10, ~9-billion-attempt null-move precision/recall/
EV harness (2026-09-24, two revisions -- see
nullmove_calib/run_2026-09-24_sd10_30k_v2/, the second and
authoritative one). iImprovement and uNullDepth are currently
unused: the Stage 1 thresholds below are flat, not depth- or
improvement-scaled, and Stage 2 doesn't need its own gate at all
(see below). Kept in the signature to avoid touching call sites.
Stage 1 (safety): is a null-move fail-high here even trustworthy?
Gated on the MOVER's own non-pawn piece count -- TotalNonPawnCount
(pos, pos->uToMove), NOT MAX(white,black) as an earlier revision of
this gate (and of the calibration harness that measured it) used.
Zugzwang is a property of the side being given the free "pass", so
the opponent's material shouldn't matter -- confirmed empirically:
(maxMaterial=6+, moverMaterial=2) measured a 0.30% false-positive
rate, indistinguishable from the worst low-material cells overall,
despite "6+" sounding safe. A materially-heavier opponent does not
protect a mover that is itself thin on material.
Measured false-positive rate (a null fail-high the real search
didn't confirm) by mover's own material x eval-vs-beta deficit:
deficit<-300 -300..-100 -100..0 0..100 100..300 300+
mover 0-1 pcs: 5.57% 1.35% 0.82% 1.02% 0.28% 0.12%
mover 2 pcs: 3.73% 0.19% 0.31% 0.32% 0.02% 0.01%
mover 3-5 pcs: 0.91% 0.20% 0.09% 0.002% 0.001% 0.0005%
mover 6+ pcs: 0.02% 0.002% 0.001% 0.0002% 0.0001% 0.0001%
6+ pieces is safe (<=0.02%) at EVERY deficit measured, even the most
negative -- no deficit floor needed there at all. 2 pieces is
actually salvageable (0.01-0.02%, comparable to the safest cells
overall) once deficit >= 100, unlike a flatly-disabled <=2 rule
would assume -- but <=1 piece never gets safe (worst case 0.12% at
its *best* deficit band), so that tier is disabled outright rather
than deficit-gated.
Stage 2 (profitability/EV): given Stage 1 passes, is trying still
worth the reduced-depth probe's node cost? Checked directly against
the same run's EV data (EV = successRate*(realLoopCost-nullProbeCost)
- (1-successRate)*nullProbeCost, in nodes saved per attempt) across
every (depth, material) cell that survives the Stage 1 gate above:
EV was strongly positive everywhere measured, from low single digits
at shallow depth up to tens of thousands of nodes at deep probes,
never negative. Stage 1 is already doing essentially all the
discriminating work, so Stage 2 currently just returns TRUE
unconditionally once Stage 1 passes -- no separate EV threshold is
justified by this data. Revisit if a future, deeper or wider
calibration run finds a safe-but-unprofitable pocket this one
didn't sample.
Parameters:
SEARCHER_THREAD_CONTEXT *ctx,
SCORE iAlpha,
SCORE iBeta,
SCORE iEval,
SCORE iImprovement,
ULONG uNullDepth
Return value:
FLAG
**/
{
POSITION *pos = &ctx->sPosition;
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
CUMULATIVE_SEARCH_FLAGS *pf = &ctx->sSearchFlags;
ULONG uMoverPiecesPerSide;
SCORE iDeficit;
ASSERT(IS_VALID_SCORE(iAlpha) && IS_VALID_SCORE(iBeta));
ASSERT(iAlpha < iBeta);
ASSERT(IS_VALID_SCORE(iEval));
ASSERT(uNullDepth < MAX_PLY_PER_SEARCH * ONE_PLY);
if ((FALSE == pf->fAvoidNullmove) &&
(FALSE == pi->fInCheck) &&
(iBeta != +INFINITY_SCORE) &&
(NODE_PV != pi->eNodeType))
{
uMoverPiecesPerSide = TotalNonPawnCount(pos, pos->uToMove);
iDeficit = iEval - iBeta;
// ---- Stage 1: safety ----
if (uMoverPiecesPerSide <= 1)
{
return FALSE; // never measured safe, even at its best deficit
}
if ((uMoverPiecesPerSide == 2) && (iDeficit < 100))
{
return FALSE;
}
if ((uMoverPiecesPerSide <= 5) && (iDeficit < -100))
{
return FALSE;
}
// 6+ pieces: no deficit floor -- safe everywhere measured.
// ---- Stage 2: efficiency/EV ----
// EV is strongly positive at every depth/material cell that
// survives Stage 1 (see routine comment) -- nothing further to
// gate on here today.
return TRUE;
}
return FALSE;
}
FLAG
TryNullmovePruning(SEARCHER_THREAD_CONTEXT *ctx,
FLAG *pfThreat,
SCORE iAlpha,
SCORE iBeta,
ULONG uNullDepth,
INT *piOrigExtend,
SCORE *piNullScore,
ULONG uNullRBucket)
{
static INT _bm_by_piece[7] = {
-1, -1, QUARTER_PLY, QUARTER_PLY, HALF_PLY, HALF_PLY, -1
};
POSITION *pos = &ctx->sPosition;
PLY_INFO *pi = &ctx->sPlyInfo[ctx->uPly];
CUMULATIVE_SEARCH_FLAGS *pf = &ctx->sSearchFlags;
SCORE iVerifyScore;
MOVE mv;
MOVE mvRef;
ASSERT(IS_VALID_SCORE(iAlpha) && IS_VALID_SCORE(iBeta));
ASSERT(iAlpha < iBeta);
// TODO: more experiments with quick null
// Ok, do it.
ASSERT(!InCheck(pos, pos->uToMove));
VERIFY(MakeMove(ctx, NULLMOVE));
ASSERT(pos->u64NonPawnSig != pi->sPosition.u64NonPawnSig);
ASSERT(pos->uToMove != pi->sPosition.uToMove);
INC(ctx->sCounters.tree.u64NullMoves);
// This function recurses into Search() directly, not through this
// file's own SearchOneMove (which stashes this on every OTHER
// recursion -- see chess.h's PLY_INFO.uParentMoveFHEstimate
// comment). A null move has no per-move FH% table lookup to
// report -- MOVE_FH_ESTIMATE_NO_DATA ("unknown"), not
// MOVE_FH_ESTIMATE_NONLEFTOVER (which would falsely claim high
// confidence). Without this, the child ply's slot reads whatever
// was last left there -- caught by valgrind as a real
// uninitialised-value read inside search.c's _RefineNodeTypeGuess.
ctx->sPlyInfo[ctx->uPly].uParentMoveFHEstimate = MOVE_FH_ESTIMATE_NO_DATA;
// (Reduced depth) search under the nullmove; don't allow two
// nullmoves in a row.
ASSERT(pf->fAvoidNullmove == FALSE);
pf->fAvoidNullmove = TRUE;
*piNullScore = -Search(ctx, -iBeta, -iBeta + 1, uNullDepth);
pf->fAvoidNullmove = FALSE;
// depth=uNullDepth here (the already-reduced depth passed to the
// probe), not the pre-reduction parent depth, which this function
// never receives -- r is left 0.0 rather than faked.
TDMove(ctx, uNullDepth, iAlpha, iBeta, "NULL", "NMP", 0.0, 0.0,
*piNullScore, FALSE);
// Check the results
if (*piNullScore >= iBeta)
{
UnmakeMove(ctx, NULLMOVE);
ASSERT(PositionsAreEquivalent(pos, &pi->sPosition));
// If there are very few pieces on the board, launch a
// separate "verification search".
if ((TotalNonPawnCount(pos, pos->uToMove) < 4) &&
(pf->fVerifyNullmove == TRUE))
{
ASSERT(pf->fAvoidNullmove == FALSE);
uNullDepth -= ONE_PLY;
if (uNullDepth > MAX_DEPTH_PER_SEARCH) uNullDepth = 0;
pf->fVerifyNullmove = FALSE;
iVerifyScore = Search(ctx, iAlpha, iBeta, uNullDepth);
pf->fVerifyNullmove = TRUE;
if (iVerifyScore < iBeta)
{
// The nullmove failed high but the verify search
// did not; we are in zug so extend.
*piOrigExtend += ONE_PLY;
INC(ctx->sCounters.extension.uZugzwang);
return FALSE;
}
}
// Nullmove succeeded and either no need to verify or verify
// succeeded too.
INC(ctx->sCounters.tree.u64NullMoveSuccess);
#ifdef PERF_COUNTERS
INC(ctx->sCounters.tree.u64NullMoveSuccessByR[uNullRBucket]);
#endif
if (*piNullScore > +NMATE) *piNullScore = +NMATE;
return TRUE;
}
// Nullmove failed...
mv = (pi+1)->mvBest;
if (mv.uMove)
{
// See what we can learn from the move that refuted our nullmove.
ASSERT(SanityCheckMove(pos, mv));
ASSERT(GET_COLOR(mv.pMoved) == pos->uToMove);
ASSERT(ctx->uPly >= 2);
// If we make a nullmove that fails because we lose a
// piece, remember that the piece in question is in danger.
if ((mv.pCaptured) && !IS_PAWN(mv.pCaptured))
{
ASSERT(GET_COLOR(mv.pCaptured) == FLIP(pos->uToMove));
ASSERT(mv.pCaptured == pos->rgSquare[mv.cTo].pPiece);
// Victim belongs to FLIP(pos->uToMove) here, i.e. the
// mover at ctx->uPly - 1 (see RecordEnprisePieceAtPly).
RecordEnprisePieceAtPly(ctx, ctx->uPly - 1, mv.cTo);
#if 0
mvRef = ctx->mvNullmoveRefutations[ctx->uPly - 2];
if ((mvRef.uMove) &&
(mvRef.pCaptured == mv.pCaptured) &&
(mvRef.pMoved == mv.pMoved) &&
(mvRef.cTo != mv.cTo))
{
ASSERT(GET_COLOR(mvRef.pCaptured) == FLIP(pos->uToMove));
ASSERT(mvRef.pCaptured);
ASSERT(_bm_by_piece[PIECE_TYPE(mv.pCaptured)] > 0);
ASSERT(_bm_by_piece[PIECE_TYPE(mv.pCaptured)] <=
ONE_PLY);
*piOrigExtend += _bm_by_piece[PIECE_TYPE(mv.pCaptured)];
INC(ctx->sCounters.extension.uBotvinnikMarkoff);
}
#endif
ctx->mvNullmoveRefutations[ctx->uPly] = mv;
}
else if (!IS_CAPTURE_OR_PROMOTION(mv))
{
// A quiet move refuting our nullmove is itself decent
// evidence that the move is strong here -- not enough to
// extend on (that's the capture-only Botvinnik-Markoff
// case above), but worth remembering as a fallback guess
// for _NewKillerMove's empty-slot backfill, which is only
// useful when this is actually a quiet move: a killer
// slot only ever gets matched against generated quiet
// candidates (IS_SAME_MOVE compares the pCaptured/
// pPromoted bits too), so storing a capture there (the
// old unconditional behavior) could never match anything
// and was silently dead.
//
// Deliberately a *separate* array from mvNullmoveRefutations,
// not a shared slot -- that one is read two plies later
// (ctx->uPly - 2, above) expecting a capture, to detect the
// same-piece-two-different-squares Botvinnik-Markoff pattern.
// Writing a quiet move into that same slot would silently
// clobber the capture history the extension depends on.
ctx->mvNullmoveQuietRefutations[ctx->uPly] = mv;
}
// This is an idea from Tord Romstad on ccc: if we are below a
// history reduced node and we try a nullmove and the nullmove
// fails low and the move that refuted the nullmove involves
// the same piece moved in the reduced move at ply-1 then bail
// out of the reduced depth search now and research at full
// depth. The move that was reduced had some tactical
// significance.
ASSERT(IS_ON_BOARD(mv.cFrom));
if ((mv.cFrom == (pi-1)->mv.cTo) && ((pi-1)->iExtensionAmount < 0))
{
ASSERT(GET_COLOR(mv.pMoved) == GET_COLOR((pi-1)->mv.pMoved));
TDMove(ctx, uNullDepth, iAlpha, iBeta, "NULL", "NULLBAILOUT",
0.0, 0.0, iAlpha - 1, FALSE);
UnmakeMove(ctx, NULLMOVE);
ASSERT(PositionsAreEquivalent(pos, &pi->sPosition));
*piNullScore = iAlpha - 1;
return TRUE;
}
}
// If we do nothing we are mated-in-n, therefore this is a
// dangerous position so extend. This is Bruce Moreland's idea
// originally.
if (*piNullScore <= -NMATE)
{
if (mv.uMove && !IS_CAPTURE_OR_PROMOTION(mv))
{
ASSERT(SanityCheckMove(pos, mv));
ASSERT(GET_COLOR(mv.pMoved) == pos->uToMove);
UpdateDynamicMoveOrdering(ctx,
uNullDepth + TWO_PLY,
mv,
*piNullScore,
0);
}
*pfThreat = TRUE;
}
UnmakeMove(ctx, NULLMOVE);
ASSERT(PositionsAreEquivalent(pos, &pi->sPosition));
return FALSE;
}
#ifdef DEBUG
FLAG
SanityCheckMoves(IN SEARCHER_THREAD_CONTEXT *ctx,
IN ULONG uCurrent,
IN ULONG uType)
/**
Routine description:
Support routine to sanity check that:
1. The moves before uCurrent on the move stack were all marked
as searched (or pruned)
2. The moves after uCurrent on the move stack are all zero
value moves and not checking moves.
Parameters:
SEARCHER_THREAD_CONTEXT *ctx,
ULONG uCurrent,
ULONG uType
Return value:
FLAG
**/
{
ULONG x;
if (WE_SHOULD_STOP_SEARCHING)
{
return(TRUE);
}
//
// Check moves yet to be searched
//
if (uType & VERIFY_AFTER)
{
for (x = uCurrent; x < ctx->sMoveStack.uEnd[ctx->uPly]; x++)
{
ASSERT(ctx->sMoveStack.mvf[x].iValue <= 0);
ASSERT(!IS_CHECKING_MOVE(ctx->sMoveStack.mvf[x].mv));
}
}
//
// Check moves already searched
//
if (uType & VERIFY_BEFORE)
{
for (x = uCurrent - 1;
((x >= ctx->sMoveStack.uBegin[ctx->uPly]) && (x != (ULONG)-1));
x--)
{
ASSERT(ctx->sMoveStack.mvf[x].bvFlags & MVF_MOVE_SEARCHED);
}
}
return(TRUE);
}
#endif
|