hermit-detcore 0.5.2

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! The process-local portion of the Detcore Reverie-tool.

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::os::fd::BorrowedFd;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::time::Duration;

use detcore_model::pedigree::Pedigree;
use detcore_model::summary::TimesliceStats;
use nix::fcntl::OFlag;
use nix::sys::stat;
use nix::unistd::Pid;
use rand::Rng as _;
use rand::RngExt as _;
use rand::SeedableRng;
use rand_distr::Distribution;
use rand_distr::Exp;
use rand_pcg::Pcg64Mcg;
use reverie::Errno;
use reverie::Error;
use reverie::Guest;
use reverie::syscalls::CloneFlags;
use reverie::syscalls::Syscall;
use reverie::syscalls::Sysno;
use serde::Deserialize;
use serde::Serialize;
use sha2::Digest as _;
use sha2::Sha256;
use tracing::debug;
use tracing::info;

use crate::config::Config;
use crate::detlog;
use crate::fd::*;
use crate::memory::MemoryMetadata;
use crate::preemptions::ThreadHistoryIterator;
use crate::record_or_replay::NoopTool;
use crate::record_or_replay::RecordOrReplay;
use crate::resources::ChaosEpochTransition;
use crate::resources::Device;
use crate::resources::Permission;
use crate::resources::ResourceID;
use crate::resources::Resources;
use crate::scheduler::Priority;
use crate::stat::*;
use crate::types::*;

/// The detcore tool and its per-process state.
#[derive(Debug, Serialize, Deserialize)]
pub struct Detcore<T = NoopTool> {
    //
    // TODO:
    //  - Add Pid cache here.
    //
    /// The detpid of this process.
    pub(crate) detpid: DetPid,

    /// Cached copy of the tool Config.  Immutable over the lifetime of the program.
    pub(crate) cfg: Config,

    /// The record or replay sub-tool. Any events that cannot be made
    /// deterministic are forwarded to this tool. Thus, Detcore acts as a
    /// filter-map for syscalls.
    pub(crate) record_or_replay: T,
}

/// The metadata associated with the file system view of a particular *process*.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileMetadata {
    /// Identity of the Linux descriptor table represented by `file_handles`.
    pub(crate) files_id: FilesId,
    /// Sequence used to allocate open file descriptions observed through this table.
    next_open_file_sequence: u64,
    /// Socket-only sequence used for backend-independent socket cookies.
    #[serde(default)]
    next_socket_open_file_sequence: u64,
    /// A random-device or timerfd OFD from this table has been promoted.
    /// Retain this history after its final close so exec cannot reuse a
    /// canonical identity. (Serialized under its earlier name, which the
    /// field had while only random devices were promoted.)
    #[serde(default, rename = "has_promoted_random_files")]
    has_promoted_shared_files: bool,
    /// Track what file handles actually point to (e.g. after dup2).
    /// This includes both the identifying resource (usually inode) and the deterministic file handle.
    /// Deserialization restores aliasing (`crate::fd::intern_open_files`).
    #[serde(deserialize_with = "deserialize_interned_file_handles")]
    pub(crate) file_handles: HashMap<RawFd, DetFd>,
    /// Blocking accepts waiting in this table, each as (operation, listener):
    /// a `close` of a listener here is refused while an accept waits on it
    /// (`crate::syscalls::accept_in_turn`). Waits never cross a fork or an
    /// exec: a fork's child and an exec'd task start with none, and each wait
    /// removes only its own entry, from the table it registered in.
    // TODO-HUMAN-REVIEW(PR-3908)
    #[serde(skip)]
    accept_waits: Vec<(u64, RawFd)>,
    /// The next accept-wait operation number in this table.
    #[serde(skip)]
    next_accept_wait: u64,
    /// Whether the session renders `/proc/cpuinfo`, so that a memfd named as
    /// its placeholder may be one when this table rediscovers descriptors
    /// without a guest at hand (an in-guest backend's image after `exec`):
    /// the session's own answer (`Detcore::rendered_files`), taken at the
    /// image's first guest callback (`decide_cpuinfo_placeholders`), and kept
    /// by `fork_for` and `for_exec`. `None` until then, and when absent from
    /// an older serialized table. Detcore makes no such placeholder in a
    /// session that does not render the file, so there a memfd of that name
    /// stays an ordinary memfd.
    #[serde(default)]
    cpuinfo_placeholders: Option<bool>,
    /// Descriptors rediscovered before [`Self::cpuinfo_placeholders`] was
    /// decided whose memfd is named as a `/proc/cpuinfo` placeholder: kept as
    /// the ordinary descriptors they look like until the session's answer
    /// says whether they are placeholders (`decide_cpuinfo_placeholders`).
    #[serde(default)]
    pending_cpuinfo_placeholders: Vec<RawFd>,
}

/// Deserializes a descriptor table with its aliases restored, so a table
/// carried across fork (or any other state migration) keeps one open file
/// description object per `OpenFileId`.
fn deserialize_interned_file_handles<'de, D>(
    deserializer: D,
) -> Result<HashMap<RawFd, DetFd>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let mut handles = <HashMap<RawFd, DetFd> as Deserialize>::deserialize(deserializer)?;
    crate::fd::intern_open_files(&mut handles);
    Ok(handles)
}

/// A descriptor identity held across an awaited syscall.
///
/// The clone retains the source open-file description until the operation
/// finishes. `files_id` binds it to the table in which the syscall began.
#[derive(Debug)]
pub(crate) struct CapturedDetFd {
    files_id: FilesId,
    detfd: DetFd,
}

/// A captured descriptor could not be installed into the current descriptor
/// table. The capture is returned so the caller can release any resource held
/// alive solely by the in-flight operation.
#[derive(Debug)]
pub(crate) struct CapturedDetFdInstallError {
    pub(crate) expected_files_id: FilesId,
    pub(crate) actual_files_id: FilesId,
    returned_fd: RawFd,
    pub(crate) captured: CapturedDetFd,
}

/// Cleanup required after the kernel created a descriptor but Detcore could not
/// install its captured open-file-description identity in the current table.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct CapturedDetFdInstallCleanup {
    /// The exact kernel-returned descriptor that must be closed.
    pub(crate) close_fd: RawFd,
    /// A scheduler resource whose final modeled OFD reference was the capture.
    pub(crate) release_open_file: Option<OpenFileId>,
}

impl CapturedDetFdInstallError {
    /// Abandon the failed capture and preserve both cleanup obligations.
    pub(crate) fn into_cleanup(self) -> CapturedDetFdInstallCleanup {
        let release_open_file = (self.captured.detfd.open_file_alias_count() == 1)
            .then(|| self.captured.detfd.open_file_id());
        drop(self.captured);
        CapturedDetFdInstallCleanup {
            close_fd: self.returned_fd,
            release_open_file,
        }
    }
}

/// Whether a pidfd target is proven to use the caller's exact descriptor table.
///
/// Linux pidfds name a specific task, and `pidfd_open(2)` accepts a thread-group
/// leader. Equal TGIDs alone are not enough: a `CLONE_THREAD` child may omit
/// `CLONE_FILES` and therefore have a different `files_struct`. Restrict the
/// modeled path to the leader itself, where `target == getpid() == gettid()`
/// proves that the task named by the pidfd and the caller are identical.
pub(crate) fn pidfd_getfd_targets_calling_task(
    target: Option<DetPid>,
    current_tgid: DetPid,
    current_tid: DetTid,
) -> bool {
    target == Some(current_tgid) && current_tid == current_tgid
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1154): Review SaBRe exec descriptor-status handoff state.
/// Descriptor numbers that Detcore keeps physically nonblocking while presenting them as
/// blocking to the guest. SaBRe carries this narrow status set across an exec plugin reload.
pub type ExecFdBlockingOverrides = BTreeSet<RawFd>;

/// Metadata carried by the existing exec preparation/completion exchange.
/// Descriptor numbers are authorized by that exchange's process/image fence,
/// not by rediscovering whichever object later occupies a numeric stdio slot.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecFdState {
    pub(crate) blocking: ExecFdBlockingOverrides,
    pub(crate) inherited_reads: BTreeMap<RawFd, crate::fd::InheritedExternalRead>,
    /// Set only by the global first-image completion, never by a preparation.
    pub(crate) initialize_inherited_stdio: bool,
    /// Offered only to the registered root's initial image by its launcher.
    #[serde(default)]
    pub(crate) initial_input: Option<reverie::InheritedInputIdentity>,
    /// The owner-death wakes a successful exec makes Linux deliver, read
    /// before the exec where the backend runs the native execve outside
    /// Detcore's handler (DBT). The coordinator delivers them at the new
    /// image's reconnect, or when the caller's thread ends without one (an
    /// exec that ends its group), and drops them with an exec cancelled before
    /// its point of no return (<https://github.com/rrnewton/hermit/issues/4268>).
    #[serde(default)]
    pub(crate) robust_wakes: Vec<(DetTid, FutexID)>,
    /// Promoted random-device handles and allocator state of a reloaded tool.
    /// Nonrandom descriptors retain their existing exec restoration paths.
    #[serde(default)]
    pub(crate) open_files: Option<ExecOpenFiles>,
    /// Maps descriptions surviving a reload retain their opened target image,
    /// aliases and any cached bytes. Kernel EOF must not erase this authority.
    #[serde(default)]
    pub(crate) maps: Option<ExecMapsFiles>,
    /// Under `--pipe-wake-latency`, on a backend that rediscovers its
    /// descriptors after exec: the channel end each surviving descriptor is,
    /// reattached after rediscovery (`crate::pipe_wake`).
    #[serde(default)]
    pub(crate) channels: BTreeMap<RawFd, crate::pipe_wake::ChannelEnd>,
    /// Under `--pipe-wake-latency`, on such a backend, at every exec: the old
    /// table's open-file creator and next sequence, reserved before any
    /// rediscovery, so that no description of the new image reuses an id a
    /// channel elsewhere may still carry.
    #[serde(default)]
    pub(crate) open_file_namespace: Option<(DetTid, u64)>,
    /// The image the exec runs, as Detcore resolved it from the exec's
    /// arguments before the exec ([`crate::exec_record`]), or for the
    /// registered root's first image the one its launch named
    /// (`Config::launch_image`), once the coordinator checked it against the
    /// kernel's link. `None` leaves the new image without a record.
    #[serde(default)]
    pub(crate) exe: Option<crate::exec_record::ExecRecord>,
}

/// Written out, not derived, so that the `--pipe-wake-latency` fields are
/// printed only when set: an exec without the option traces as before.
impl std::fmt::Debug for ExecFdState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut debug = f.debug_struct("ExecFdState");
        debug
            .field("blocking", &self.blocking)
            .field("inherited_reads", &self.inherited_reads)
            .field(
                "initialize_inherited_stdio",
                &self.initialize_inherited_stdio,
            )
            .field("initial_input", &self.initial_input)
            .field("robust_wakes", &self.robust_wakes)
            .field("open_files", &self.open_files);
        if let Some(maps) = &self.maps {
            // Native authority tokens and kernel descriptor identities are
            // transport-only; they must not enter canonical guest logs.
            debug.field("maps_survivors", &maps.handles.len());
        }
        if !self.channels.is_empty() {
            debug.field("channels", &self.channels);
        }
        if let Some(namespace) = &self.open_file_namespace {
            debug.field("open_file_namespace", namespace);
        }
        if let Some(exe) = &self.exe {
            debug.field("exe", &exe.exe);
        }
        debug.finish()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ExecOpenFiles {
    pub(crate) creator: DetTid,
    next_sequence: u64,
    next_socket_sequence: u64,
    handles: BTreeMap<RawFd, ExecOpenFile>,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ExecMapsFiles {
    creator: DetTid,
    next_sequence: u64,
    handles: BTreeMap<RawFd, ExecMapsFile>,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct ExecMapsFile {
    identity: ExecOpenFile,
    procfs: crate::procfs::ProcfsFile,
    flags: i32,
    path: Option<std::path::PathBuf>,
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct ExecOpenFile {
    id: OpenFileId,
    dev: u64,
    ino: u64,
    rdev: u64,
    file_type: u32,
    access: i32,
}

impl std::fmt::Debug for ExecOpenFile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExecOpenFile")
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

impl ExecOpenFile {
    fn capture(fd: RawFd, id: OpenFileId) -> Result<Self, Errno> {
        let mut stat: libc::stat = unsafe { std::mem::zeroed() };
        // Runtime-owned read-only inspection of this process's descriptor table.
        let result = unsafe {
            crate::util::raw_syscall(
                libc::SYS_fstat,
                [fd as u64, (&raw mut stat) as u64, 0, 0, 0, 0],
            )
        };
        if result < 0 {
            return Err(Errno::new(-result as i32));
        }
        let flags = unsafe {
            crate::util::raw_syscall(
                libc::SYS_fcntl,
                [fd as u64, libc::F_GETFL as u64, 0, 0, 0, 0],
            )
        };
        if flags < 0 {
            return Err(Errno::new(-flags as i32));
        }
        Ok(Self {
            id,
            dev: stat.st_dev,
            ino: stat.st_ino,
            rdev: stat.st_rdev,
            file_type: stat.st_mode & libc::S_IFMT,
            access: flags as i32 & libc::O_ACCMODE,
        })
    }
}

impl ExecFdState {
    pub(crate) fn open_file_creator(&self) -> Option<DetTid> {
        self.open_files
            .as_ref()
            .map(|files| files.creator)
            .or_else(|| self.open_file_namespace.map(|(creator, _)| creator))
            .or_else(|| self.maps.as_ref().map(|maps| maps.creator))
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.blocking.is_empty()
            && self.inherited_reads.is_empty()
            && !self.initialize_inherited_stdio
            && self.initial_input.is_none()
            && self.open_files.is_none()
            && self.maps.is_none()
            && self.channels.is_empty()
            && self.open_file_namespace.is_none()
            && self.exe.is_none()
    }
}

impl From<ExecFdBlockingOverrides> for ExecFdState {
    fn from(blocking: ExecFdBlockingOverrides) -> Self {
        Self {
            blocking,
            ..Self::default()
        }
    }
}

/// The wakes an exec's walk of each owner's list found, in delivery order:
/// owners in walk order, each owner's words in futex-key order.
pub(crate) fn flatten_exec_robust_list_wakes(
    wakes: Vec<(DetTid, Vec<RobustListWake>)>,
) -> Vec<(DetTid, RobustListWake)> {
    wakes
        .into_iter()
        .flat_map(|(owner, mut wakes)| {
            wakes.sort_by_key(|wake| format!("{:?}", wake.futex));
            wakes.into_iter().map(move |wake| (owner, wake))
        })
        .collect()
}

/// A single POSIX per-process interval timer created by `timer_create(2)`.
///
/// Detcore records arming against virtual time and schedules supported
/// `SIGEV_SIGNAL` notifications through the deterministic scheduler.
// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(#869)
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PosixTimer {
    /// Reload interval for periodic timers, in nanoseconds (0 => one-shot).
    interval_ns: u64,
    /// Absolute virtual-time deadline of the next expiration, or `None` when the
    /// timer is disarmed (`it_value == 0`).
    deadline: Option<LogicalTime>,
    /// Signal number configured by `timer_create`, or `None` for notifications
    /// that Detcore cannot deliver through its scheduler.
    signal: Option<i32>,
    /// The thread a `SIGEV_THREAD_ID` timer notifies, or `None` for a
    /// process-directed one.
    #[serde(default)]
    thread: Option<DetTid>,
    /// The `si_value` of its signal: `sigev_value`, or `sival_int = id`
    /// for a timer created with no `sigevent` (`do_timer_create`).
    #[serde(default)]
    value: u64,
}

/// The set of POSIX timers owned by a *process*.
///
/// Timers are shared among all threads of a process and, per POSIX, are **not**
/// inherited across `fork(2)`. Detcore therefore shares this table on
/// `CLONE_THREAD` and starts a fresh, empty table for every new process (see
/// `init_thread_state`). Successful exec deletes the timers as well.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PosixTimers {
    /// Deterministic id allocator. Kernel `timer_t`s are opaque, so we hand out
    /// ids as 0, 1, 2, ... in creation order to keep them reproducible.
    next_id: i32,
    timers: HashMap<i32, PosixTimer>,
}

impl PosixTimers {
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#869)
    /// Allocate a new (disarmed) timer, returning its deterministic id.
    /// `thread` is the thread a `SIGEV_THREAD_ID` timer notifies, and
    /// `value` its `sigev_value`, or `None` for a timer created with no
    /// `sigevent`, whose `si_value` is its id.
    pub(crate) fn create(
        &mut self,
        signal: Option<i32>,
        thread: Option<DetTid>,
        value: Option<u64>,
    ) -> i32 {
        let id = self.next_id;
        self.next_id += 1;
        self.timers.insert(
            id,
            PosixTimer {
                interval_ns: 0,
                deadline: None,
                signal,
                thread,
                value: value.unwrap_or(id as u32 as u64),
            },
        );
        id
    }

    /// The `si_value` of timer `id`'s signal.
    pub(crate) fn value(&self, id: i32) -> Option<u64> {
        self.timers.get(&id).map(|timer| timer.value)
    }

    /// Arm or disarm timer `id`. `interval_ns` is the periodic reload and
    /// `deadline` the absolute virtual-time expiration (the caller derives it
    /// from the request flags and the current virtual clock; `None` disarms).
    /// Returns the previous `(remaining_ns, interval_ns)` for `old_value`, or
    /// `None` if the id is unknown.
    pub(crate) fn settime(
        &mut self,
        id: i32,
        interval_ns: u64,
        deadline: Option<LogicalTime>,
        now: LogicalTime,
    ) -> Option<(u64, u64)> {
        let timer = self.timers.get_mut(&id)?;
        let old = (
            remaining_ns(timer.deadline, timer.interval_ns, now),
            timer.interval_ns,
        );
        timer.interval_ns = interval_ns;
        timer.deadline = deadline;
        Some(old)
    }

    /// Report the current `(remaining_ns, interval_ns)` for `timer_gettime`, or
    /// `None` if the id is unknown.
    pub(crate) fn gettime(&self, id: i32, now: LogicalTime) -> Option<(u64, u64)> {
        let timer = self.timers.get(&id)?;
        Some((
            remaining_ns(timer.deadline, timer.interval_ns, now),
            timer.interval_ns,
        ))
    }

    /// Whether a timer with this id currently exists.
    pub(crate) fn contains(&self, id: i32) -> bool {
        self.timers.contains_key(&id)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#869)
    pub(crate) fn signal(&self, id: i32) -> Option<Option<i32>> {
        self.timers.get(&id).map(|timer| timer.signal)
    }

    /// The thread timer `id` notifies, if it is a `SIGEV_THREAD_ID` timer.
    pub(crate) fn thread(&self, id: i32) -> Option<DetTid> {
        self.timers.get(&id).and_then(|timer| timer.thread)
    }

    /// Remove a timer; returns whether it existed.
    pub(crate) fn remove(&mut self, id: i32) -> bool {
        self.timers.remove(&id).is_some()
    }

    /// Linux deletes all POSIX timers on successful exec. Keep the process's
    /// ID allocator, but invalidate armed, disarmed and non-notifying timers.
    pub(crate) fn clear_for_exec(&mut self) {
        self.timers.clear();
    }
}

/// One virtualized resource limit, represented in the `prlimit64` ABI's units.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct ResourceLimit {
    pub(crate) current: u64,
    pub(crate) maximum: u64,
}

/// Deterministic resource limits owned by one guest process.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ResourceLimits {
    limits: Vec<ResourceLimit>,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        let unlimited = ResourceLimit {
            current: libc::RLIM64_INFINITY,
            maximum: libc::RLIM64_INFINITY,
        };
        let mut limits = vec![unlimited; libc::RLIMIT_RTTIME as usize + 1];
        limits[libc::RLIMIT_STACK as usize] = ResourceLimit {
            current: 8 * 1024 * 1024,
            maximum: libc::RLIM64_INFINITY,
        };
        limits[libc::RLIMIT_NOFILE as usize] = ResourceLimit {
            current: 1_048_576,
            maximum: 1_048_576,
        };
        Self { limits }
    }
}

/// The limit every guest process starts with for `resource`, as
/// `(current, maximum)` in the `prlimit64` ABI's units, or `None` for an
/// invalid resource number.
///
/// A backend whose guest reads a limit before Detcore runs answers it with
/// this. SaBRe is one: its guest's dynamic loader and libc startup run before
/// the plugin is initialized, and libc sizes default thread stacks from
/// `RLIMIT_STACK` there.
pub fn initial_resource_limit(resource: u32) -> Option<(u64, u64)> {
    ResourceLimits::default()
        .get(resource)
        .map(|limit| (limit.current, limit.maximum))
}

impl ResourceLimits {
    /// Return a limit when `resource` is a valid Linux resource number.
    pub(crate) fn get(&self, resource: u32) -> Option<ResourceLimit> {
        self.limits.get(resource as usize).copied()
    }

    /// Replace a previously validated resource limit.
    pub(crate) fn set(&mut self, resource: u32, limit: ResourceLimit) {
        self.limits[resource as usize] = limit;
    }
}

/// Nanoseconds remaining until `deadline` relative to `now`, saturating at 0.
/// A disarmed timer (`None`) or an elapsed one-shot reports 0. Periodic timers
/// advance arithmetically to their next virtual deadline.
fn remaining_ns(deadline: Option<LogicalTime>, interval_ns: u64, now: LogicalTime) -> u64 {
    match deadline {
        Some(d) if d > now => d.as_nanos() - now.as_nanos(),
        Some(d) if interval_ns != 0 => {
            let elapsed = now.as_nanos() - d.as_nanos();
            interval_ns - (elapsed % interval_ns)
        }
        Some(_) => 0,
        None => 0,
    }
}

impl<T> Default for Detcore<T> {
    fn default() -> Self {
        // TODO(T77816673): eventually we want to remove this requirement.
        // In the meantime... just don't call this.
        // Instead see the new() method defined in lib.rs
        panic!("Detcore Default impl should not be called");
    }
}

impl<T: RecordOrReplay> AsRef<T> for Detcore<T> {
    fn as_ref(&self) -> &T {
        &self.record_or_replay
    }
}

impl<T: RecordOrReplay> AsMut<T> for Detcore<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.record_or_replay
    }
}

impl<T: RecordOrReplay> Detcore<T> {
    /// Delegate to the record/replay tool without collapsing a tool failure
    /// into a guest-visible errno. Syscall errors remain [`Error::Errno`], while
    /// failures of the record/replay machinery retain their non-errno variant.
    pub(crate) async fn record_or_replay_preserving_tool_errors<G, S>(
        &self,
        guest: &mut G,
        syscall: S,
    ) -> Result<i64, Error>
    where
        G: Guest<Self>,
        S: Into<Syscall>,
    {
        preserve_record_or_replay_error(
            self.translated_record_or_replay(guest, syscall.into())
                .await,
        )?
        .map_err(Error::from)
    }

    /// The record-or-replay tool's handling of `syscall`, with a `/proc`
    /// path that names a process or thread by the guest's number reaching
    /// the kernel's directory for it (DBT; see
    /// `syscalls::files::procfs_numbers`).
    async fn translated_record_or_replay<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Error> {
        let translated = Self::procfs_translated_call(guest, &syscall).await?;
        let result = self
            .record_or_replay
            .handle_syscall_event(
                &mut guest.into_guest(),
                translated
                    .as_ref()
                    .map_or(syscall, |translated| translated.call),
            )
            .await;
        if let Some(translated) = translated {
            Self::finish_translated_call(guest, translated).await;
        }
        result
    }

    /// Helper function for delegating the injection of a syscall to the
    /// record_or_replay tool.
    ///
    /// It is important to classify the cases where we need to call `inject`. We
    /// have three main choices to make when handling a syscall:
    ///  1. Fully determinize the syscall. In this case, it doesn't need to call
    ///     `inject` at all.
    ///  2. Partially determinize the syscall. In this case, it can't fully
    ///     determinize a syscall but only part of it. For example, a `stat` syscall
    ///     is ultimately non-deterministic because the file may not always exist.
    ///     However, the mtime or inode numbers can be made deterministic.
    ///  3. The syscall cannot be determinized at all. For example, a call to
    ///     `recvfrom` cannot be made deterministic.
    ///
    /// Thus, this is called whenever `inject` would be called for non-bookkeeping
    /// operations.
    pub(crate) async fn record_or_replay<G, S>(
        &self,
        guest: &mut G,
        syscall: S,
    ) -> Result<i64, Errno>
    where
        G: Guest<Self>,
        S: Into<Syscall>,
    {
        self.translated_record_or_replay(guest, syscall.into())
            .await
            // TODO: Get rid of this and make this whole function use the Error type.
            .map_err(|err| err.into_errno().unwrap())
    }
}

fn preserve_record_or_replay_error(
    result: Result<i64, Error>,
) -> Result<Result<i64, Errno>, Error> {
    match result {
        Ok(value) => Ok(Ok(value)),
        Err(Error::Errno(error)) => Ok(Err(error)),
        Err(error) => Err(error),
    }
}

/// Linux reports a positive byte count when a later guest-visible write error
/// follows partial progress. An error in the record/replay tool is different:
/// replay itself failed, so it must remain fatal even after earlier bytes were
/// accepted.
pub(crate) fn finish_partial_record_or_replay_write(
    written: i64,
    error: Error,
) -> Result<i64, Error> {
    match error {
        Error::Errno(_) if written > 0 => Ok(written),
        error => Err(error),
    }
}

#[cfg(test)]
mod record_or_replay_error_tests {
    use super::*;

    #[test]
    fn errno_remains_a_guest_syscall_result() {
        let result = preserve_record_or_replay_error(Err(Error::Errno(Errno::EBADF)))
            .expect("guest errno must not abort the tool");
        assert_eq!(result, Err(Errno::EBADF));
    }

    #[test]
    fn tool_failure_remains_an_outer_error() {
        let failure =
            preserve_record_or_replay_error(Err(Error::Tool(anyhow::anyhow!("restore failed"))))
                .expect_err("tool failure must abort replay");
        assert!(matches!(failure.into_errno(), Err(Error::Tool(_))));
    }

    #[test]
    fn partial_write_suppresses_only_guest_errno() {
        assert_eq!(
            finish_partial_record_or_replay_write(7, Error::Errno(Errno::EPIPE)).unwrap(),
            7
        );

        let io_failure = finish_partial_record_or_replay_write(
            7,
            Error::Io(std::io::Error::from_raw_os_error(libc::ENOSPC)),
        )
        .expect_err("host replay-output failure must not become a partial guest write");
        assert!(matches!(io_failure.into_errno(), Err(Error::Io(_))));

        let tool_failure = finish_partial_record_or_replay_write(
            7,
            Error::Tool(anyhow::anyhow!("replay endpoint disappeared")),
        )
        .expect_err("tool failure must not become a partial guest write");
        assert!(matches!(tool_failure.into_errno(), Err(Error::Tool(_))));

        let guest_failure = finish_partial_record_or_replay_write(0, Error::Errno(Errno::EPIPE))
            .expect_err("zero-progress guest failure must remain guest-visible");
        assert_eq!(guest_failure.into_errno().unwrap(), Errno::EPIPE);
    }
}

impl FileMetadata {
    /// create an empty file metadata
    pub(crate) fn new(owner: DetTid) -> Self {
        FileMetadata {
            files_id: FilesId::initial(owner),
            next_open_file_sequence: 0,
            next_socket_open_file_sequence: 0,
            has_promoted_shared_files: false,
            file_handles: HashMap::new(),
            accept_waits: Vec::new(),
            next_accept_wait: 0,
            cpuinfo_placeholders: None,
            pending_cpuinfo_placeholders: Vec::new(),
        }
    }

    /// Take the session's answer to whether it renders `/proc/cpuinfo`
    /// (`rendered`: `Detcore::rendered_files(guest).cpuinfo`), at the first
    /// guest callback of this image, before guest code runs. A descriptor
    /// rediscovered before it whose memfd is named as a `/proc/cpuinfo`
    /// placeholder becomes the placeholder it is where the session renders
    /// the file, and stays an ordinary memfd where it does not. Later answers
    /// of the same session are the same and change nothing.
    pub(crate) fn decide_cpuinfo_placeholders(&mut self, rendered: bool) -> Result<(), Errno> {
        if self.cpuinfo_placeholders.is_some() {
            return Ok(());
        }
        self.cpuinfo_placeholders = Some(rendered);
        let pending = std::mem::take(&mut self.pending_cpuinfo_placeholders);
        if !rendered {
            return Ok(());
        }
        for fd in pending {
            if !self.file_handles.contains_key(&fd) {
                continue;
            }
            let raw_stat =
                stat::fstat(unsafe { BorrowedFd::borrow_raw(fd) }).map_err(|_| Errno::last())?;
            let fd_flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
            if let Some((path, snapshot)) =
                placeholder_behind(fd, crate::procfs::RenderedFiles::ALL)
            {
                self.adopt_placeholder(fd, &raw_stat, fd_flags, path, snapshot)?;
            }
        }
        Ok(())
    }

    /// Register a blocking accept waiting on `listener` and return the
    /// operation number that removes it again.
    pub(crate) fn add_accept_wait(&mut self, listener: RawFd) -> u64 {
        let operation = self.next_accept_wait;
        self.next_accept_wait += 1;
        self.accept_waits.push((operation, listener));
        operation
    }

    /// Remove the accept wait registered as `operation`, if it is here.
    pub(crate) fn remove_accept_wait(&mut self, operation: u64) {
        self.accept_waits
            .retain(|(waiting, _)| *waiting != operation);
    }

    /// The lowest descriptor in `fds` that a blocking accept waits on.
    pub(crate) fn waited_listener_in(&self, fds: std::ops::RangeInclusive<u32>) -> Option<RawFd> {
        self.accept_waits
            .iter()
            .map(|(_, listener)| *listener)
            .filter(|listener| u32::try_from(*listener).is_ok_and(|fd| fds.contains(&fd)))
            .min()
    }

    fn allocate_open_file_id(&mut self, creator: DetTid, ty: FdType) -> OpenFileId {
        if ty == FdType::Socket {
            let id = OpenFileId::new_socket(creator, self.next_socket_open_file_sequence);
            self.next_socket_open_file_sequence += 1;
            id
        } else {
            let id = OpenFileId::new(creator, self.next_open_file_sequence);
            self.next_open_file_sequence += 1;
            id
        }
    }

    fn count_open_files_at_paths(&self, paths: &[&Path]) -> usize {
        self.file_handles
            .values()
            .filter(|fd| {
                fd.path()
                    .is_some_and(|path| paths.iter().any(|candidate| path == *candidate))
            })
            .map(DetFd::open_file_id)
            .collect::<BTreeSet<_>>()
            .len()
    }

    fn has_loopback_peer(&self) -> bool {
        self.file_handles.values().any(DetFd::is_loopback_peer)
    }

    // TODO-HUMAN-REVIEW(#2373)
    /// True when `vfork` must be refused because some open file description
    /// either holds a lock or carries a cached claim that may now be wrong.
    ///
    /// ⚠️ NEVER-OBSERVED IS DELIBERATELY NOT UNSAFE. The previous form refused
    /// on `!= Some(None)`, which also caught descriptors Detcore had simply
    /// never observed. stdin, stdout and stderr are marked unobserved at
    /// container setup because they predate Detcore, so that form refused
    /// `vfork` for EVERY guest that reached it -- measured: fds 0, 1 and 2 were
    /// the sole reason `run_dbt_virtualizes_process_identities` was refused,
    /// and that guest never calls `flock` at all. A guard that cannot pass is
    /// not conservative, it is broken.
    ///
    /// The hazard is a STALE CACHE: a copied runtime mutating a lock that this
    /// side still has a claim about. A description Detcore never observed
    /// carries no claim, so there is nothing about it that can go stale.
    fn has_unsafe_vfork_flock_state(&self) -> bool {
        self.file_handles.values().any(|detfd| {
            matches!(detfd.known_flock_mode(), Some(Some(_))) || detfd.flock_mode_may_be_stale()
        })
    }

    fn has_unsafe_vfork_ofd_state(&self) -> bool {
        self.file_handles
            .values()
            .any(|detfd| detfd.may_hold_ofd_lock())
    }

    fn forget_flock_modes(&self) {
        for detfd in self.file_handles.values() {
            detfd.forget_local_flock_mode_at_fork();
        }
    }

    // TODO-HUMAN-REVIEW(#2373)
    /// Fork the file table for `child`.
    ///
    /// Local flock caches retain the existing conservative invalidation.
    /// A promoted description has one canonical model, so copying a table
    /// neither invalidates that model nor contacts it before child admission.
    /// Same-process aliases keep their lock; a separately hosted runtime
    /// resets copied locks at its physical child boundary.
    pub(crate) fn fork_for(&self, child: DetTid) -> Self {
        self.forget_flock_modes();
        Self {
            files_id: FilesId::forked(child),
            next_open_file_sequence: self.next_open_file_sequence,
            next_socket_open_file_sequence: self.next_socket_open_file_sequence,
            has_promoted_shared_files: self.has_promoted_shared_files,
            file_handles: self.file_handles.clone(),
            accept_waits: Vec::new(),
            next_accept_wait: 0,
            cpuinfo_placeholders: self.cpuinfo_placeholders,
            pending_cpuinfo_placeholders: self.pending_cpuinfo_placeholders.clone(),
        }
    }

    pub(crate) fn for_exec(&self, task: DetTid) -> Self {
        Self {
            files_id: self.files_id.for_exec(task),
            next_open_file_sequence: self.next_open_file_sequence,
            next_socket_open_file_sequence: self.next_socket_open_file_sequence,
            has_promoted_shared_files: self.has_promoted_shared_files,
            file_handles: self
                .file_handles
                .iter()
                .filter_map(|(&fd, detfd)| (!detfd.is_cloexec()).then_some((fd, detfd.clone())))
                .collect(),
            accept_waits: Vec::new(),
            next_accept_wait: 0,
            cpuinfo_placeholders: self.cpuinfo_placeholders,
            pending_cpuinfo_placeholders: self.pending_cpuinfo_placeholders.clone(),
        }
    }

    /// Read the live table incarnation for an independently owned exec cut.
    pub fn native_exec_files_id(&self) -> FilesId {
        self.files_id
    }

    /// Validate before and after preparation: `for_exec` intentionally drops
    /// waits and CLOEXEC-only descriptions, so checking only its result would
    /// lose evidence about their skipped runtime capabilities.
    pub(crate) fn validate_native_exec_cut(
        &self,
        expected: FilesId,
        prepared: bool,
    ) -> Result<(), crate::native_exec::NativeExecCutError> {
        use crate::native_exec::NativeExecCutError;

        if self.files_id != expected {
            return Err(NativeExecCutError::Identity("files_id"));
        }
        if !self.accept_waits.is_empty() {
            return Err(NativeExecCutError::LiveCapability("accept_waits"));
        }
        if prepared && self.next_accept_wait != 0 {
            return Err(NativeExecCutError::PreparedState("next_accept_wait"));
        }
        // The native final cut repeats this check after freezing counters.
        // Compare prior descriptors directly so validation neither allocates a
        // scratch map nor changes the carried Tool heap. The state transport
        // separately bounds this first, quiescent single-thread domain.
        for (index, (&slot, fd)) in self.file_handles.iter().enumerate() {
            if slot < 0 || slot != fd.fd {
                return Err(NativeExecCutError::Descriptor("slot number"));
            }
            if prepared && fd.is_cloexec() {
                return Err(NativeExecCutError::PreparedState("CLOEXEC slot"));
            }
            let (id, owner) = fd.validate_native_exec_runtime_state()?;
            for (_, previous) in self.file_handles.iter().take(index) {
                let (previous_id, previous_owner) =
                    previous.validate_native_exec_runtime_state()?;
                if (id == previous_id) != (owner == previous_owner) {
                    return Err(NativeExecCutError::Descriptor("OFD alias identity"));
                }
            }
        }
        Ok(())
    }

    pub(crate) fn exec_blocking_overrides(&self) -> ExecFdBlockingOverrides {
        self.file_handles
            .iter()
            .filter_map(|(&fd, detfd)| {
                (!detfd.is_cloexec() && detfd.physically_nonblocking() && !detfd.is_nonblocking())
                    .then_some(fd)
            })
            .collect()
    }

    pub(crate) fn apply_exec_blocking_overrides(
        &mut self,
        owner: DetTid,
        overrides: ExecFdBlockingOverrides,
    ) {
        for fd in overrides {
            tracing::trace!(
                "[detcore, dtid {}] restoring descriptor {} as logically blocking after exec",
                owner,
                fd,
            );
            match self.discover_fd_from_current_process(owner, fd) {
                Ok(()) => {
                    self.with_detfd(fd, |detfd| detfd.set_logical_nonblocking(false))
                        .expect("a just-discovered descriptor must remain registered");
                }
                Err(error) => {
                    tracing::warn!(
                        "[detcore, dtid {}] unable to restore inherited descriptor {} after exec: {}",
                        owner,
                        fd,
                        error,
                    );
                }
            }
        }
    }

    fn inherited_reads_for_exec(&self) -> BTreeMap<RawFd, crate::fd::InheritedExternalRead> {
        self.file_handles
            .iter()
            .filter(|(_, detfd)| !detfd.is_cloexec())
            .filter_map(|(&fd, detfd)| {
                detfd
                    .inherited_external_read()
                    .map(|terminal| (fd, terminal))
            })
            .collect()
    }

    /// Called only in the actual shared guest descriptor table, after the
    /// global state confirms this is the container's first image. TCGETS is
    /// read-only: neither terminal settings nor OFD flags are changed.
    fn discover_inherited_terminals(&mut self, descriptors: impl IntoIterator<Item = RawFd>) {
        for fd in descriptors {
            let Some(detfd) = self.file_handles.get(&fd) else {
                continue;
            };
            let Some(stat) = detfd.stat() else { continue };
            if stat.mode & libc::S_IFMT != libc::S_IFCHR {
                continue;
            }
            let mut settings: libc::termios = unsafe { std::mem::zeroed() };
            // SAFETY: TCGETS writes only to this live, adequately sized buffer.
            if unsafe { libc::ioctl(fd, libc::TCGETS, &raw mut settings) } != 0 {
                continue;
            }
            detfd.set_inherited_external_read(crate::fd::InheritedExternalRead {
                origin: detfd.open_file_id(),
                dev: stat.dev,
                inode: stat.inode,
                rdev: stat.rdev,
                file_type: libc::S_IFCHR,
                access_mode: detfd.status_flags() & libc::O_ACCMODE,
                resource: detfd.resource(),
            });
        }
    }

    /// Called only in the actual shared guest descriptor table, after the
    /// global state confirms this is the container's first image, beside
    /// `discover_inherited_terminals`. The guest has not run yet, so a pipe
    /// end the first image holds came from outside the run: a readable one is
    /// an inherited external read, as a terminal or a launcher-bound input is
    /// (https://github.com/rrnewton/hermit/issues/4447), and its reads take
    /// the same external-input path theirs do. That holds even when the image
    /// also holds the pipe's write end: such a pipe was not made by Detcore's
    /// `pipe2`, so it is not physically nonblocking and cannot take the
    /// internal-pipe path, whose invariant (`record_or_replay_blocking`) a
    /// blocking read of it would otherwise trip. The decision reads only what
    /// discovery recorded for the descriptor (its type, the kernel's stat and
    /// its access mode), so no later probe can change it; a description a
    /// launcher already bound keeps its binding. Inherited descriptors above 2
    /// are not discovered here.
    fn discover_inherited_pipes(&mut self, descriptors: impl IntoIterator<Item = RawFd>) {
        for fd in descriptors {
            let Some(detfd) = self.file_handles.get(&fd) else {
                continue;
            };
            let access_mode = detfd.status_flags() & libc::O_ACCMODE;
            if detfd.ty() != FdType::Pipe
                || detfd.is_socketpair_endpoint()
                || access_mode == libc::O_WRONLY
                || detfd.inherited_external_read().is_some()
            {
                continue;
            }
            let Some(stat) = detfd.stat() else { continue };
            detfd.set_inherited_external_read(crate::fd::InheritedExternalRead {
                origin: detfd.open_file_id(),
                dev: stat.dev,
                inode: stat.inode,
                rdev: stat.rdev,
                file_type: libc::S_IFIFO,
                access_mode,
                resource: detfd.resource(),
            });
        }
    }

    /// Restore only external-read descriptions proven to survive the prepared exec. Unknown
    /// descriptors and guest-created PTYs are not promoted by rediscovery.
    fn restore_inherited_reads(
        &mut self,
        owner: DetTid,
        inherited_reads: BTreeMap<RawFd, crate::fd::InheritedExternalRead>,
    ) -> Result<(), Errno> {
        let mut aliases: HashMap<OpenFileId, DetFd> = HashMap::new();
        for (fd, terminal) in inherited_reads {
            self.discover_fd_from_current_process(owner, fd)?;
            let detfd = self.file_handles.get_mut(&fd).ok_or(Errno::EBADF)?;
            let stat =
                stat::fstat(unsafe { BorrowedFd::borrow_raw(fd) }).map_err(|_| Errno::last())?;
            if stat.st_mode & libc::S_IFMT != terminal.file_type
                || (stat.st_dev, stat.st_ino, stat.st_rdev)
                    != (terminal.dev, terminal.inode, terminal.rdev)
                || detfd.status_flags() & libc::O_ACCMODE != terminal.access_mode
            {
                return Err(Errno::EIO);
            }
            // Do not repeat TCGETS here: a hung-up terminal may return EIO
            // from that query while still being the inherited open file.
            if let Some(alias) = aliases.get(&terminal.origin) {
                if detfd.status_flags() != alias.status_flags() {
                    return Err(Errno::EIO);
                }
                detfd.share_open_file_with(alias);
            } else {
                detfd.set_resource(terminal.resource.clone());
                detfd.set_inherited_external_read(terminal.clone());
                aliases.insert(terminal.origin, detfd.clone());
            }
        }
        Ok(())
    }

    fn install_inherited_input(
        &mut self,
        owner: DetTid,
        input: reverie::InheritedInputIdentity,
    ) -> Result<(), Errno> {
        let fd = input.guest_fd();
        self.discover_fd_from_current_process(owner, fd)?;
        let stat = stat::fstat(unsafe { BorrowedFd::borrow_raw(fd) }).map_err(|_| Errno::last())?;
        let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
        let detfd = self.file_handles.get(&fd).ok_or(Errno::EBADF)?;
        if !input.matches(&stat, flags) || detfd.ty() != FdType::Pipe {
            return Err(Errno::EIO);
        }
        detfd.set_inherited_external_read(crate::fd::InheritedExternalRead {
            origin: detfd.open_file_id(),
            dev: input.dev(),
            inode: input.inode(),
            rdev: input.rdev(),
            file_type: libc::S_IFIFO,
            access_mode: input.access_mode(),
            resource: detfd.resource(),
        });
        Ok(())
    }

    pub(crate) fn apply_exec_fd_state(
        &mut self,
        owner: DetTid,
        state: ExecFdState,
        shared_guest_table: bool,
    ) -> Result<(), Errno> {
        if shared_guest_table && let Some(maps) = &state.maps {
            // The existing exec exchange authorizes these survivors. Validate
            // every slot before installing any carried maps authority, and
            // reserve its old ID space before lazy discovery allocates IDs.
            for (&fd, survivor) in &maps.handles {
                if ExecOpenFile::capture(fd, survivor.identity.id)? != survivor.identity {
                    return Err(Errno::EIO);
                }
            }
            if state
                .open_files
                .as_ref()
                .is_some_and(|files| files.creator != maps.creator)
                || state
                    .open_file_namespace
                    .is_some_and(|(creator, _)| creator != maps.creator)
            {
                return Err(Errno::EIO);
            }
            self.next_open_file_sequence = self.next_open_file_sequence.max(maps.next_sequence);
        }
        // Legacy discovery also allocates IDs. Reserve the complete old
        // namespace before it can create any nonrandom descriptions, including
        // same-leader exec where the creator did not change.
        let owner = if shared_guest_table && let Some(open_files) = &state.open_files {
            self.next_open_file_sequence =
                self.next_open_file_sequence.max(open_files.next_sequence);
            self.next_socket_open_file_sequence = self
                .next_socket_open_file_sequence
                .max(open_files.next_socket_sequence);
            open_files.creator
        } else if shared_guest_table
            && let Some((creator, next_sequence)) = state.open_file_namespace
        {
            // `--pipe-wake-latency`: no new description may take an id that a
            // carried channel names (`crate::pipe_wake`).
            self.next_open_file_sequence = self.next_open_file_sequence.max(next_sequence);
            creator
        } else if shared_guest_table && let Some(maps) = &state.maps {
            maps.creator
        } else {
            owner
        };
        self.apply_exec_blocking_overrides(owner, state.blocking);
        if !shared_guest_table {
            return Ok(());
        }
        if let Some(input) = state.initial_input {
            self.install_inherited_input(owner, input)?;
        }
        if state.initialize_inherited_stdio {
            self.discover_inherited_terminals(0..=2);
            self.discover_inherited_pipes(0..=2);
        } else {
            self.restore_inherited_reads(owner, state.inherited_reads)?;
        }
        if let Some(open_files) = state.open_files {
            let mut handles = HashMap::new();
            for (fd, survivor) in open_files.handles {
                if ExecOpenFile::capture(fd, survivor.id)? != survivor {
                    return Err(Errno::EIO);
                }
                handles.insert(fd, DetFd::shared_survivor(fd, survivor.id));
            }
            crate::fd::intern_open_files(&mut handles);
            // Replace only the authenticated random-device and timerfd survivors. Pipes,
            // sockets and other descriptors retain the legacy restoration above;
            // in particular, do not reconnect an old socket's port association.
            self.file_handles.extend(handles);
            self.has_promoted_shared_files = true;
        }
        // Last, so that no restoration above can replace a description after
        // its channel is set: every carried channel end, discovering a
        // descriptor not yet rediscovered (one the guest left `O_NONBLOCK`).
        for (fd, end) in state.channels {
            match self.discover_fd_from_current_process(owner, fd) {
                Ok(()) => {
                    self.with_detfd(fd, |detfd| detfd.set_channel(end))
                        .expect("a just-discovered descriptor must remain registered");
                }
                Err(error) => {
                    tracing::warn!(
                        "[detcore, dtid {}] descriptor {} carried a pipe channel across exec \
                         but cannot be rediscovered; it keeps none: {}",
                        owner,
                        fd,
                        error,
                    );
                }
            }
        }
        if let Some(maps) = state.maps {
            let mut handles = HashMap::new();
            for (fd, survivor) in maps.handles {
                let raw_stat = stat::fstat(unsafe { BorrowedFd::borrow_raw(fd) })
                    .map_err(|error| Errno::new(error as i32))?;
                let handle = DetFd::new(
                    fd,
                    OFlag::from_bits_truncate(survivor.flags),
                    FdType::Regular,
                    survivor.identity.id,
                )
                .with_stat(DetStat::from(raw_stat));
                if let Some(path) = survivor.path {
                    handle.set_path(path);
                }
                handle.set_procfs(survivor.procfs);
                handle.mark_flock_mode_unobserved();
                handles.insert(fd, handle);
            }
            // Aliases retain one old snapshot/cursor. Independent opens of the
            // same proc inode remain separate because their IDs differ.
            crate::fd::intern_open_files(&mut handles);
            self.file_handles.extend(handles);
        }
        Ok(())
    }

    pub(crate) fn open_files_closed_on_exec(&self, table_is_shared: bool) -> Vec<OpenFileId> {
        if table_is_shared {
            return Vec::new();
        }

        let mut open_files = HashMap::new();
        for detfd in self.file_handles.values() {
            let id = detfd.open_file_id();
            let total_aliases = detfd.open_file_alias_count();
            let entry = open_files.entry(id).or_insert((0, total_aliases, true));
            debug_assert_eq!(entry.1, total_aliases);
            entry.0 += 1;
            entry.2 &= detfd.is_cloexec();
        }

        let mut closed: Vec<_> = open_files
            .into_iter()
            .filter_map(|(id, (table_aliases, total_aliases, all_cloexec))| {
                (all_cloexec && table_aliases == total_aliases).then_some(id)
            })
            .collect();
        closed.sort();
        closed
    }

    /// set default fds
    fn setup_stdio(mut self, _pid: Pid, owner: DetTid) -> Self {
        // guest stdio can be a pipe, which make things difficult
        // hence use a dummy stat here.
        // The raw syscall, not libc's interposable fstat: this runs inside the
        // guest under in-guest LiteInst (see crate::util::raw_syscall).
        let mut metadata: libc::stat = unsafe { std::mem::zeroed() };
        // SAFETY: fstat writes only into `metadata`.
        let status = unsafe {
            crate::util::raw_syscall(libc::SYS_fstat, [0, (&raw mut metadata) as u64, 0, 0, 0, 0])
        };
        if let Err(error) = crate::util::raw_zero_result(status) {
            panic!(
                "fstat of the guest's stdin failed (errno {})",
                error.raw_os_error().unwrap_or(0)
            );
        }
        let stat: DetStat = metadata.into();
        let stdin = DetFd::new(
            0,
            OFlag::empty(),
            FdType::Regular,
            self.allocate_open_file_id(owner, FdType::Regular),
        )
        .with_stat(stat)
        .with_resource(ResourceID::Device(Device::ContainerStdin));
        let stdout = DetFd::new(
            1,
            OFlag::empty(),
            FdType::Regular,
            self.allocate_open_file_id(owner, FdType::Regular),
        )
        .with_stat(stat)
        .with_resource(ResourceID::Device(Device::ContainerStdout));
        let stderr = DetFd::new(
            2,
            OFlag::empty(),
            FdType::Regular,
            self.allocate_open_file_id(owner, FdType::Regular),
        )
        .with_stat(stat)
        .with_resource(ResourceID::Device(Device::ContainerStderr));

        // These descriptors existed before Detcore began observing the guest,
        // so they may already carry flock state that we cannot query.
        stdin.mark_flock_mode_unobserved();
        stdout.mark_flock_mode_unobserved();
        stderr.mark_flock_mode_unobserved();

        self.add_detfd(stdin);
        self.add_detfd(stdout);
        self.add_detfd(stderr);

        self
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-845): Review SaBRe on-demand inherited descriptor discovery.
    fn discover_fd_from_current_process(&mut self, owner: DetTid, fd: RawFd) -> Result<(), Errno> {
        if self.file_handles.contains_key(&fd) {
            return Ok(());
        }

        let fd_flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        let status_flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
        if fd_flags == -1 || status_flags == -1 {
            return Err(Errno::last());
        }
        let raw_stat =
            stat::fstat(unsafe { BorrowedFd::borrow_raw(fd) }).map_err(|_| Errno::last())?;
        let file_type = stat::SFlag::from_bits_truncate(raw_stat.st_mode);
        let ty = if file_type.contains(stat::SFlag::S_IFIFO) {
            FdType::Pipe
        } else if file_type.contains(stat::SFlag::S_IFSOCK) {
            FdType::Socket
        } else {
            FdType::Regular
        };
        let mut flags = OFlag::from_bits_truncate(status_flags);
        let physically_nonblocking = flags.contains(OFlag::O_NONBLOCK);
        // Discovered descriptors have unknown provenance, so an observed
        // O_NONBLOCK bit must remain guest-visible. Detcore-created scheduler
        // pipes are registered when created and do not reach this fallback.
        if fd_flags & libc::FD_CLOEXEC != 0 {
            flags.insert(OFlag::O_CLOEXEC);
        }
        self.add_fd(owner, fd, flags, ty, Some(raw_stat.into()))?;
        // This newly discovered description predates our observation. Its
        // kernel lock may be held, but no cached lock claim existed to go stale.
        self.with_detfd(fd, |detfd| detfd.mark_flock_mode_unobserved())?;
        // A placeholder for a procfs file Detcore renders, which the backend
        // rediscovers after `exec`: the file again, at the position the old
        // image left and with the snapshot it took, as a backend that keeps
        // Detcore's state across `exec` has them (`syscalls::files::rendered_procfs`).
        // The snapshot is the one its name carries (`procfs::placeholder_name`).
        // Only an empty regular file with no link can be one.
        let may_be_placeholder = raw_stat.st_mode & libc::S_IFMT == libc::S_IFREG
            && raw_stat.st_nlink == 0
            && raw_stat.st_size == 0;
        // A `/proc/cpuinfo` placeholder only once the session's answer says
        // it renders the file (`decide_cpuinfo_placeholders`); before that
        // answer, one waits for it as the ordinary descriptor it looks like.
        let decided = self.cpuinfo_placeholders;
        // A process's `mountinfo` or `mounts` has a placeholder only in a
        // session with a container mount table, the only one that renders it.
        let files = crate::procfs::RenderedFiles {
            cpuinfo: decided == Some(true),
            mounts: true,
        };
        let found = may_be_placeholder
            .then(|| placeholder_behind(fd, files))
            .flatten();
        if found.is_none()
            && decided.is_none()
            && may_be_placeholder
            && placeholder_behind(fd, crate::procfs::RenderedFiles::ALL)
                .is_some_and(|(path, _)| path == std::path::Path::new("/proc/cpuinfo"))
        {
            self.pending_cpuinfo_placeholders.push(fd);
        }
        if let Some((path, snapshot)) = found {
            if self.adopt_placeholder(fd, &raw_stat, fd_flags, path, snapshot)? {
                return Ok(());
            }
        }
        // A fixed procfs file the kernel opened (through a symbolic link),
        // which the old image read from Detcore's rendering: the file again,
        // at the position Detcore kept in the kernel
        // (`DetFd::procfs_keeps_kernel_position`), so the new image does not
        // read the host's file. procfs files report size 0.
        else if raw_stat.st_mode & libc::S_IFMT == libc::S_IFREG
            && raw_stat.st_size == 0
            && let Some(procfs) = fixed_procfs_behind(fd)
        {
            // SAFETY: lseek only reads the descriptor's position.
            let offset = unsafe {
                crate::util::raw_syscall(
                    libc::SYS_lseek,
                    [fd as u64, 0, libc::SEEK_CUR as u64, 0, 0, 0],
                )
            };
            let offset = usize::try_from(offset).unwrap_or(0);
            let path = procfs
                .rendered_path(crate::procfs::RenderedFiles::WITHOUT_CPUINFO)
                .expect("a fixed procfs file has a path");
            self.with_detfd(fd, |detfd| {
                detfd.set_path(path);
                detfd.set_procfs(procfs.clone());
                detfd.set_procfs_offset(offset);
            })?;
        }
        if let Some(resource) = stdio_resource(fd) {
            self.with_detfd(fd, |detfd| detfd.set_resource(resource.clone()))?;
        }
        if ty == FdType::Pipe && physically_nonblocking {
            self.with_detfd(fd, |detfd| detfd.set_physically_nonblocking())?;
        }
        Ok(())
    }

    /// Make descriptor `fd`, already in this table, the placeholder for the
    /// rendered file `path` that its memfd (`raw_stat`, descriptor flags
    /// `fd_flags`) is, with the snapshot its name carries. Returns whether it
    /// joined another descriptor's open file (an alias), whose state it then
    /// shares.
    fn adopt_placeholder(
        &mut self,
        fd: RawFd,
        raw_stat: &libc::stat,
        fd_flags: libc::c_int,
        path: &'static std::path::Path,
        snapshot: Vec<u8>,
    ) -> Result<bool, Errno> {
        crate::syscalls::rendered_procfs::register_placeholder(
            raw_stat.st_dev,
            raw_stat.st_ino,
            path,
        );
        // Every open makes its own placeholder, so another descriptor on
        // the same one is the same open file: one cursor, as before.
        if let Some(alias) = self.rendered_alias(fd, raw_stat.st_dev, raw_stat.st_ino) {
            let mut alias = alias.with_fd(fd);
            alias.set_cloexec(fd_flags & libc::FD_CLOEXEC != 0);
            self.add_detfd(alias);
            return Ok(true);
        }
        // SAFETY: lseek only reads the descriptor's position.
        let offset = unsafe {
            crate::util::raw_syscall(
                libc::SYS_lseek,
                [fd as u64, 0, libc::SEEK_CUR as u64, 0, 0, 0],
            )
        };
        let offset = usize::try_from(offset).unwrap_or(0);
        let procfs = crate::procfs::ProcfsFile::from_rendered_path(path)
            .expect("a rendered path is a procfs file")
            .into_rendered();
        let procfs = if snapshot.is_empty() {
            procfs
        } else {
            procfs.with_rendered_snapshot(snapshot)
        };
        self.with_detfd(fd, |detfd| {
            detfd.set_path(path);
            detfd.set_procfs(procfs.clone());
            detfd.set_procfs_offset(offset);
        })?;
        Ok(false)
    }

    /// Another descriptor of this process open on the placeholder `(dev,
    /// ino)`, which `fd` is too.
    fn rendered_alias(&self, fd: RawFd, dev: u64, ino: u64) -> Option<DetFd> {
        self.file_handles
            .iter()
            .filter(|(other, detfd)| **other != fd && detfd.procfs_rendered_path().is_some())
            .find(|(other, _)| {
                stat::fstat(unsafe { BorrowedFd::borrow_raw(**other) })
                    .is_ok_and(|stat| stat.st_dev == dev && stat.st_ino == ino)
            })
            .map(|(_, detfd)| detfd.clone())
    }

    /// get detfd from rawfd, rawfd must be added or dup-ed first.
    fn with_detfd<F, U>(&mut self, fd: RawFd, mut f: F) -> Result<U, Errno>
    where
        F: FnMut(&mut DetFd) -> U,
    {
        let detfd = self.file_handles.get_mut(&fd).ok_or(Errno::EBADF)?;
        Ok(f(detfd))
    }

    /// add a detfd
    fn add_detfd(&mut self, detfd: DetFd) {
        let fd = detfd.fd;
        self.file_handles.insert(fd, detfd);
    }

    /// add a raw fd
    fn add_fd(
        &mut self,
        creator: DetTid,
        fd: RawFd,
        flags: OFlag,
        ty: FdType,
        stat: Option<DetStat>,
    ) -> Result<(), Errno> {
        let id = self.allocate_open_file_id(creator, ty);
        let detfd = DetFd::new(fd, flags, ty, id).with_stat(stat);
        self.add_detfd(detfd);
        Ok(())
    }

    /// remove a rawfd
    fn remove_fd(&mut self, fd: RawFd) -> Option<OpenFileId> {
        let detfd = self.file_handles.remove(&fd)?;
        (detfd.open_file_alias_count() == 1).then(|| detfd.open_file_id())
    }

    /// Remove every modeled descriptor in an inclusive close_range interval.
    fn remove_fd_range(&mut self, first: u32, last: u32) -> Vec<OpenFileId> {
        let mut descriptors: Vec<_> = self
            .file_handles
            .keys()
            .copied()
            .filter(|fd| *fd >= 0 && first <= *fd as u32 && *fd as u32 <= last)
            .collect();
        descriptors.sort_unstable();
        descriptors
            .into_iter()
            .filter_map(|fd| self.remove_fd(fd))
            .collect()
    }

    /// dup raw fds.
    fn dup_fd(
        &mut self,
        oldfd: RawFd,
        newfd: RawFd,
        flags: OFlag,
    ) -> Result<Option<OpenFileId>, Errno> {
        if oldfd == newfd {
            self.with_detfd(oldfd, |_| ())?;
            return Ok(None);
        }

        let detfd = self.with_detfd(oldfd, |old_detfd| {
            old_detfd.clone().with_fd(newfd).with_fd_flags(flags)
        })?;
        let replaced = self.file_handles.insert(newfd, detfd);
        Ok(replaced
            .and_then(|detfd| (detfd.open_file_alias_count() == 1).then(|| detfd.open_file_id())))
    }

    /// Capture the exact open-file description currently named by `fd`.
    fn capture_fd(&mut self, fd: RawFd) -> Result<CapturedDetFd, Errno> {
        let detfd = self.with_detfd(fd, |detfd| detfd.clone())?;
        Ok(CapturedDetFd {
            files_id: self.files_id,
            detfd,
        })
    }

    /// Install a previously captured open-file description as `newfd`.
    ///
    /// Unlike [`Self::dup_fd`], this never resolves the source fd number again.
    /// It succeeds only if the destination still belongs to the descriptor
    /// table in which the source was captured.
    fn install_captured_fd(
        &mut self,
        captured: CapturedDetFd,
        newfd: RawFd,
        flags: OFlag,
    ) -> Result<Option<OpenFileId>, CapturedDetFdInstallError> {
        if captured.files_id != self.files_id {
            return Err(CapturedDetFdInstallError {
                expected_files_id: captured.files_id,
                actual_files_id: self.files_id,
                returned_fd: newfd,
                captured,
            });
        }

        let detfd = captured.detfd.with_fd(newfd).with_fd_flags(flags);
        let replaced = self.file_handles.insert(newfd, detfd);
        Ok(replaced
            .and_then(|detfd| (detfd.open_file_alias_count() == 1).then(|| detfd.open_file_id())))
    }

    /// Drop a capture that was not installed and report whether it retained the
    /// final reference to the open-file description.
    fn abandon_captured_fd(&mut self, captured: CapturedDetFd) -> Option<OpenFileId> {
        let release =
            (captured.detfd.open_file_alias_count() == 1).then(|| captured.detfd.open_file_id());
        drop(captured);
        release
    }
}

fn stdio_resource(fd: RawFd) -> Option<ResourceID> {
    match fd {
        0 => Some(ResourceID::Device(Device::ContainerStdin)),
        1 => Some(ResourceID::Device(Device::ContainerStdout)),
        2 => Some(ResourceID::Device(Device::ContainerStderr)),
        _ => None,
    }
}

#[cfg(test)]
mod posix_timers_tests {
    use super::*;

    fn t(ns: u64) -> LogicalTime {
        LogicalTime::from_nanos(ns)
    }

    #[test]
    fn ids_are_deterministic_and_sequential() {
        let mut timers = PosixTimers::default();
        assert_eq!(timers.create(None, None, None), 0);
        assert_eq!(timers.create(Some(libc::SIGALRM), None, None), 1);
        assert_eq!(timers.create(None, None, None), 2);
    }

    #[test]
    fn settime_reports_previous_arming_and_remaining_uses_virtual_clock() {
        let mut timers = PosixTimers::default();
        let id = timers.create(None, None, None);

        // Arm a one-shot timer for 100ns at t=0. A freshly created timer was
        // disarmed, so the reported old value is zero.
        let old = timers.settime(id, 0, Some(t(100)), t(0)).expect("known id");
        assert_eq!(old, (0, 0));

        // At t=40 there should be 60ns remaining and no interval.
        assert_eq!(timers.gettime(id, t(40)), Some((60, 0)));
        // Past the deadline the remaining time saturates at 0.
        assert_eq!(timers.gettime(id, t(150)), Some((0, 0)));
    }

    #[test]
    fn resetting_reports_old_remaining() {
        let mut timers = PosixTimers::default();
        let id = timers.create(None, None, None);
        timers.settime(id, 0, Some(t(100)), t(0));
        // Re-arm at t=30 (70ns remained) with a periodic 50ns timer.
        let old = timers
            .settime(id, 50, Some(t(200)), t(30))
            .expect("known id");
        assert_eq!(old, (70, 0));
        assert_eq!(timers.gettime(id, t(30)), Some((170, 50)));
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#869)
    #[test]
    fn periodic_remaining_advances_past_each_deadline() {
        let mut timers = PosixTimers::default();
        let id = timers.create(Some(libc::SIGALRM), None, None);
        timers.settime(id, 50, Some(t(100)), t(0));

        assert_eq!(timers.gettime(id, t(100)), Some((50, 50)));
        assert_eq!(timers.gettime(id, t(125)), Some((25, 50)));
        assert_eq!(timers.gettime(id, t(150)), Some((50, 50)));
        assert_eq!(timers.signal(id), Some(Some(libc::SIGALRM)));
    }

    #[test]
    fn disarm_and_unknown_ids() {
        let mut timers = PosixTimers::default();
        let id = timers.create(None, None, None);
        timers.settime(id, 0, Some(t(100)), t(0));
        // Disarm: value of 0 -> deadline None -> remaining 0.
        timers.settime(id, 0, None, t(10));
        assert_eq!(timers.gettime(id, t(10)), Some((0, 0)));

        // Unknown ids are rejected.
        assert_eq!(timers.settime(99, 0, Some(t(1)), t(0)), None);
        assert_eq!(timers.gettime(99, t(0)), None);
        assert!(!timers.contains(99));
    }

    #[test]
    fn delete_removes_timer() {
        let mut timers = PosixTimers::default();
        let id = timers.create(None, None, None);
        assert!(timers.contains(id));
        assert!(timers.remove(id));
        assert!(!timers.contains(id));
        // Deleting again fails.
        assert!(!timers.remove(id));
    }
}

#[cfg(test)]
mod resource_limits_tests {
    use super::*;

    #[test]
    fn defaults_are_fixed_and_cover_linux_resources() {
        let limits = ResourceLimits::default();
        assert_eq!(
            limits.get(libc::RLIMIT_STACK),
            Some(ResourceLimit {
                current: 8 * 1024 * 1024,
                maximum: libc::RLIM64_INFINITY,
            })
        );
        assert_eq!(
            limits.get(libc::RLIMIT_NOFILE),
            Some(ResourceLimit {
                current: 1_048_576,
                maximum: 1_048_576,
            })
        );
        assert_eq!(
            limits.get(libc::RLIMIT_CORE),
            Some(ResourceLimit {
                current: libc::RLIM64_INFINITY,
                maximum: libc::RLIM64_INFINITY,
            })
        );
        assert_eq!(limits.get(libc::RLIMIT_RTTIME + 1), None);
    }

    #[test]
    fn cloned_process_state_changes_independently() {
        let parent = ResourceLimits::default();
        let mut child = parent.clone();
        let lowered = ResourceLimit {
            current: 1024,
            maximum: 1_048_576,
        };
        child.set(libc::RLIMIT_NOFILE, lowered);

        assert_eq!(child.get(libc::RLIMIT_NOFILE), Some(lowered));
        assert_eq!(
            parent.get(libc::RLIMIT_NOFILE),
            Some(ResourceLimit {
                current: 1_048_576,
                maximum: 1_048_576,
            })
        );
    }
}

#[cfg(test)]
mod file_metadata_tests {
    mod inherited_input;
    use std::os::fd::AsRawFd;

    use super::*;
    use crate::pipe_wake::ChannelEnd;
    use crate::pipe_wake::ChannelId;

    #[test]
    fn maps_exec_survivors_keep_opened_target_aliases_and_cursor() {
        use crate::procfs::BoundTask;
        use crate::procfs::MapsTarget;
        use crate::procfs::ProcfsFile;
        use crate::procfs::ProcfsSnapshotContext;
        use crate::procfs::TaskIncarnation;

        let owner = DetTid::from_raw(9021);
        let config = Config::default();
        let mut parent = ThreadState::new(owner, &config, ());
        let maps = std::fs::File::open("/proc/self/maps").unwrap();
        let alias = maps.try_clone().unwrap();
        let closed = maps.try_clone().unwrap();
        let unread = std::fs::File::open("/proc/self/maps").unwrap();
        let fd = maps.as_raw_fd();
        let alias_fd = alias.as_raw_fd();
        let closed_fd = closed.as_raw_fd();
        let unread_fd = unread.as_raw_fd();
        let target = MapsTarget {
            task: BoundTask {
                process: 9021,
                thread: None,
            },
            incarnation: TaskIncarnation {
                process: 1,
                thread: None,
            },
            mm: MmId::initial(owner),
            private: reverie::RuntimePrivateMemorySnapshot {
                owner: [1, 2, 3, 4],
                version: 7,
                regions: vec![reverie::RuntimePrivateMemoryRegion {
                    start: 0x1000,
                    end: 0x2000,
                }],
            },
        };
        for number in [fd, unread_fd] {
            parent
                .add_fd(
                    number,
                    OFlag::O_RDONLY | OFlag::O_NONBLOCK,
                    FdType::Regular,
                    None,
                )
                .unwrap();
            let mut procfs = ProcfsFile::from_path(Path::new("/proc/self/maps")).unwrap();
            procfs.bind_maps_target(target.clone());
            parent
                .with_detfd(number, |handle| {
                    handle.set_path("/proc/self/maps");
                    handle.set_procfs(procfs.clone());
                })
                .unwrap();
        }
        parent.dup_fd(fd, alias_fd, OFlag::empty()).unwrap();
        parent.dup_fd(fd, closed_fd, OFlag::O_CLOEXEC).unwrap();
        parent
            .with_detfd(fd, |handle| {
                handle.initialize_procfs(
                    b"3000-4000 rw-p 00000000 00:00 0 \n".to_vec(),
                    ProcfsSnapshotContext::default(),
                );
                handle.commit_procfs_read(0, 7);
            })
            .unwrap();
        assert!(
            parent.maps_for_exec(None).unwrap().is_none(),
            "exec maps carry requires an advertised private-memory provider"
        );
        let transfer = parent
            .maps_for_exec(Some(&reverie::RuntimePrivateMemory::Unavailable))
            .unwrap()
            .unwrap();
        let ready_transfer = parent
            .maps_for_exec(Some(&reverie::RuntimePrivateMemory::Ready(
                target.private.clone(),
            )))
            .unwrap()
            .unwrap();
        assert!(ready_transfer == transfer);
        let original_preview = parent
            .with_detfd(fd, |h| h.preview_procfs(3))
            .unwrap()
            .unwrap();
        assert!(!transfer.handles.contains_key(&closed_fd));
        assert_eq!(
            transfer.handles[&fd].identity.id,
            transfer.handles[&alias_fd].identity.id
        );
        assert_ne!(
            transfer.handles[&fd].identity.id,
            transfer.handles[&unread_fd].identity.id
        );
        let old_id = transfer.handles[&fd].identity.id;
        let old_unread_id = transfer.handles[&unread_fd].identity.id;
        let next_sequence = transfer.next_sequence;
        let state = ExecFdState {
            maps: Some(transfer),
            ..ExecFdState::default()
        };
        assert!(!state.is_empty());
        // Exercise the actual serialized exec preparation/completion payload.
        let state: ExecFdState =
            serde_json::from_slice(&serde_json::to_vec(&state).unwrap()).unwrap();
        drop(state.clone()); // cancelled preparation leaves the original model alone
        assert_eq!(
            parent
                .with_detfd(fd, |h| h.procfs_position())
                .unwrap()
                .unwrap()
                .0,
            7
        );
        let receiving_tid = DetTid::from_raw(9022);
        let mut successor_thread = ThreadState::new(receiving_tid, &config, ());
        // The same creator choice used by the real exec-completion handler.
        assert_eq!(state.open_file_creator(), Some(owner));
        successor_thread.set_open_file_creator(state.open_file_creator().unwrap());
        let mut successor = successor_thread.metadata();
        successor
            .apply_exec_fd_state(receiving_tid, state.clone(), true)
            .unwrap();
        assert!(
            successor.file_handles.contains_key(&fd),
            "exec must retain maps provenance before lazy discovery"
        );
        assert!(!successor.file_handles.contains_key(&closed_fd));
        for number in [fd, alias_fd, unread_fd] {
            assert_eq!(
                successor.file_handles[&number].procfs_maps_target(),
                Some(target.clone())
            );
            assert!(successor.file_handles[&number].is_nonblocking());
        }
        assert_eq!(successor.file_handles[&fd].open_file_id(), old_id);
        assert_eq!(
            successor.file_handles[&unread_fd].open_file_id(),
            old_unread_id
        );
        assert_eq!(successor.file_handles[&fd].procfs_position().unwrap().0, 7);
        assert!(successor.file_handles[&unread_fd].procfs_needs_snapshot());
        let (offset, bytes) = successor.file_handles[&alias_fd].preview_procfs(3).unwrap();
        assert_eq!((offset, bytes.clone()), original_preview);
        successor.file_handles[&alias_fd].commit_procfs_read(offset, bytes.len());
        assert_eq!(successor.file_handles[&fd].procfs_position().unwrap().0, 10);
        assert_eq!(
            parent
                .with_detfd(fd, |h| h.procfs_position())
                .unwrap()
                .unwrap()
                .0,
            7
        );
        assert!(successor.next_open_file_sequence >= parent.metadata().next_open_file_sequence);
        drop(successor);
        let next = tempfile::tempfile().unwrap();
        successor_thread
            .add_fd(next.as_raw_fd(), OFlag::O_RDWR, FdType::Regular, None)
            .unwrap();
        assert_eq!(
            successor_thread
                .with_detfd(next.as_raw_fd(), |h| h.open_file_id())
                .unwrap(),
            OpenFileId::new(owner, next_sequence),
        );
        // A reused numeric slot cannot acquire the old target's authority.
        let replacement = tempfile::tempfile().unwrap();
        assert_eq!(
            unsafe { libc::dup2(replacement.as_raw_fd(), alias_fd) },
            alias_fd
        );
        assert_eq!(
            FileMetadata::new(owner).apply_exec_fd_state(owner, state, true),
            Err(Errno::EIO)
        );
    }

    #[test]
    fn shared_exec_survivors_keep_aliases_and_allocator_after_closed_high_ids() {
        crate::fd::install_test_shared_open_file_channel();
        let creator = DetTid::from_raw(9011);
        let leader = DetTid::from_raw(9012);
        let config = Config::default();
        let mut parent = ThreadState::new(creator, &config, ());
        parent.set_open_file_creator(creator);
        parent.metadata().file_handles.clear();
        let file = std::fs::File::open("/dev/urandom").unwrap();
        let alias = nix::unistd::dup(&file).unwrap();
        let distinct = std::fs::File::open("/dev/urandom").unwrap();
        let cloexec = nix::unistd::dup(&file).unwrap();
        let (socket, _peer) = std::os::unix::net::UnixStream::pair().unwrap();
        let (fd, alias_fd, distinct_fd, closed_fd, socket_fd) = (
            file.as_raw_fd(),
            alias.as_raw_fd(),
            distinct.as_raw_fd(),
            cloexec.as_raw_fd(),
            socket.as_raw_fd(),
        );
        for fd in [fd, alias_fd, distinct_fd, socket_fd] {
            assert_eq!(unsafe { libc::fcntl(fd, libc::F_SETFD, 0) }, 0);
        }
        parent
            .add_fd(fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        parent.dup_fd(fd, alias_fd, OFlag::empty()).unwrap();
        parent.dup_fd(fd, closed_fd, OFlag::O_CLOEXEC).unwrap();
        parent
            .add_fd(distinct_fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        parent
            .add_fd(socket_fd, OFlag::O_RDWR, FdType::Socket, None)
            .unwrap();
        let first_id = parent.metadata().file_handles[&fd].open_file_id();
        let distinct_id = parent.metadata().file_handles[&distinct_fd].open_file_id();
        let old_socket_id = parent.metadata().file_handles[&socket_fd].open_file_id();
        assert_ne!(
            first_id, distinct_id,
            "same inode does not identify one OFD"
        );
        parent.metadata().file_handles[&fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 0);
                Ok(7)
            })
            .unwrap();
        // Closed and CLOEXEC descriptions still consume allocator identities.
        let high = parent
            .metadata()
            .allocate_open_file_id(creator, FdType::Rng);
        let high_socket = parent
            .metadata()
            .allocate_open_file_id(creator, FdType::Socket);
        parent.promote_shared_open_files().unwrap();
        assert!(!parent.metadata().file_handles[&socket_fd].is_shared());
        let transfer = parent.shared_open_files_for_exec().unwrap().unwrap();
        assert_eq!(transfer.creator, creator);
        assert!(!transfer.handles.contains_key(&closed_fd));
        assert!(!transfer.handles.contains_key(&socket_fd));
        assert_eq!(transfer.handles[&fd].id, transfer.handles[&alias_fd].id);
        // Dropping a cancelled preparation cannot change any cursor.
        drop(transfer.clone());
        parent.metadata().file_handles[&fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 7);
                Ok(0)
            })
            .unwrap();

        // A genuinely replaced descriptor must not acquire a survivor's ID.
        // This owns only a duplicate, never one of the test process's stdio FDs.
        let replacement = tempfile::tempfile().unwrap();
        assert_eq!(
            unsafe { libc::dup2(replacement.as_raw_fd(), alias_fd) },
            alias_fd
        );
        assert_eq!(
            FileMetadata::new(leader).apply_exec_fd_state(
                leader,
                ExecFdState {
                    open_files: Some(transfer.clone()),
                    ..ExecFdState::default()
                },
                true,
            ),
            Err(Errno::EIO),
        );
        assert_eq!(unsafe { libc::dup2(fd, alias_fd) }, alias_fd);

        let mut successor = ThreadState::new(leader, &config, ());
        // Preserve the new image's existing nonrandom association. The handover
        // must not restore the old socket ID used by ReleasePort bookkeeping.
        successor
            .add_fd(socket_fd, OFlag::O_RDWR, FdType::Socket, None)
            .unwrap();
        let new_socket_id = successor.metadata().file_handles[&socket_fd].open_file_id();
        assert_ne!(old_socket_id, new_socket_id);
        let stdio_ids: Vec<_> = (0..=2)
            .map(|fd| successor.metadata().file_handles[&fd].open_file_id())
            .collect();
        successor.set_open_file_creator(transfer.creator);
        successor
            .metadata()
            .apply_exec_fd_state(
                creator,
                ExecFdState {
                    open_files: Some(transfer),
                    ..ExecFdState::default()
                },
                true,
            )
            .unwrap();
        assert!(!successor.metadata().file_handles.contains_key(&closed_fd));
        assert_eq!(
            successor.metadata().file_handles[&socket_fd].open_file_id(),
            new_socket_id
        );
        assert!(!successor.metadata().file_handles[&socket_fd].is_shared());
        assert_eq!(
            (0..=2)
                .map(|fd| successor.metadata().file_handles[&fd].open_file_id())
                .collect::<Vec<_>>(),
            stdio_ids
        );
        successor.metadata().file_handles[&alias_fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 7);
                Ok(5)
            })
            .unwrap();
        parent.metadata().file_handles[&fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 12);
                Ok(0)
            })
            .unwrap();
        successor.metadata().file_handles[&distinct_fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 0);
                Ok(0)
            })
            .unwrap();
        successor.remove_fd(fd);
        successor
            .add_fd(fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        let reopened = successor.metadata().file_handles[&fd].open_file_id();
        assert_ne!(reopened, first_id);
        assert_ne!(reopened, high);
        assert_eq!(
            reopened,
            OpenFileId::new(creator, successor.metadata().next_open_file_sequence - 1)
        );
        assert_ne!(
            successor
                .metadata()
                .allocate_open_file_id(creator, FdType::Socket),
            high_socket
        );
        successor.promote_shared_open_files().unwrap();
        let second = successor.shared_open_files_for_exec().unwrap().unwrap();
        assert_eq!(
            second.creator, creator,
            "nonleader creator survives repeated exec"
        );
        let mut again = FileMetadata::new(leader);
        again
            .apply_exec_fd_state(
                creator,
                ExecFdState {
                    open_files: Some(second),
                    ..ExecFdState::default()
                },
                true,
            )
            .unwrap();
        assert_eq!(again.file_handles[&fd].open_file_id(), reopened);
        again.file_handles[&alias_fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 12);
                Ok(0)
            })
            .unwrap();

        // No surviving RNG descriptor does not mean its old identities are free.
        for fd in [fd, alias_fd, distinct_fd] {
            successor.remove_fd(fd);
        }
        let empty = successor.shared_open_files_for_exec().unwrap().unwrap();
        assert!(empty.handles.is_empty());
        let next_sequence = empty.next_sequence;
        let mut after_close = ThreadState::new(leader, &config, ());
        after_close.set_open_file_creator(empty.creator);
        after_close
            .metadata()
            .apply_exec_fd_state(
                creator,
                ExecFdState {
                    open_files: Some(empty),
                    ..ExecFdState::default()
                },
                true,
            )
            .unwrap();
        after_close
            .add_fd(fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        assert_eq!(
            after_close.metadata().file_handles[&fd].open_file_id(),
            OpenFileId::new(creator, next_sequence)
        );
        // The canonical store still owns all old models: reusing an ID refuses.
        after_close.promote_shared_open_files().unwrap();
    }

    #[test]
    fn shared_random_promotion_leaves_nonrandom_tables_local() {
        let state = ThreadState::new(DetTid::from_raw(9013), &Config::default(), ());
        let regular = tempfile::tempfile().unwrap();
        let (socket, _peer) = std::os::unix::net::UnixStream::pair().unwrap();
        state
            .add_fd(regular.as_raw_fd(), OFlag::O_RDWR, FdType::Regular, None)
            .unwrap();
        state
            .add_fd(socket.as_raw_fd(), OFlag::O_RDWR, FdType::Socket, None)
            .unwrap();
        let before: HashMap<_, _> = state
            .metadata()
            .file_handles
            .iter()
            .map(|(&fd, handle)| (fd, handle.open_file_id()))
            .collect();
        state.promote_shared_open_files().unwrap();
        assert!(state.shared_open_files_for_exec().unwrap().is_none());
        for (fd, id) in before {
            let metadata = state.metadata();
            let handle = &metadata.file_handles[&fd];
            assert!(!handle.is_shared());
            assert_eq!(handle.open_file_id(), id);
        }
    }

    #[test]
    fn shared_exec_restores_allocator_before_legacy_pipe_discovery() {
        crate::fd::install_test_shared_open_file_channel();
        let owner = DetTid::from_raw(9014);
        let config = Config::default();
        let parent = ThreadState::new(owner, &config, ());
        let random = std::fs::File::open("/dev/random").unwrap();
        let fd = random.as_raw_fd();
        assert_eq!(unsafe { libc::fcntl(fd, libc::F_SETFD, 0) }, 0);
        parent
            .add_fd(fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        parent.promote_shared_open_files().unwrap();
        let transfer = parent.shared_open_files_for_exec().unwrap().unwrap();
        let random_id = transfer.handles[&fd].id;
        let old_next = transfer.next_sequence;
        let (pipe, _writer) = nix::unistd::pipe2(OFlag::O_NONBLOCK).unwrap();
        let pipe_fd = pipe.as_raw_fd();
        let successor = ThreadState::new(owner, &config, ());
        successor
            .metadata()
            .apply_exec_fd_state(
                owner,
                ExecFdState {
                    blocking: [pipe_fd].into_iter().collect(),
                    open_files: Some(transfer),
                    ..ExecFdState::default()
                },
                true,
            )
            .unwrap();
        let mut metadata = successor.metadata();
        let pipe_id = metadata.file_handles[&pipe_fd].open_file_id();
        assert_eq!(pipe_id, OpenFileId::new(owner, old_next));
        assert_ne!(pipe_id, random_id);
        assert_eq!(metadata.file_handles[&pipe_fd].ty(), FdType::Pipe);
        assert!(!metadata.file_handles[&pipe_fd].is_nonblocking());
        assert!(metadata.file_handles[&pipe_fd].physically_nonblocking());
        assert!(!metadata.file_handles[&pipe_fd].is_shared());
        assert_eq!(metadata.file_handles[&fd].open_file_id(), random_id);
        assert_ne!(
            metadata.allocate_open_file_id(owner, FdType::Regular),
            pipe_id
        );
        // Interning must never merge the unrelated restored pipe and RNG.
        crate::fd::intern_open_files(&mut metadata.file_handles);
        assert_eq!(metadata.file_handles[&pipe_fd].ty(), FdType::Pipe);
        assert_eq!(metadata.file_handles[&fd].ty(), FdType::Rng);
    }

    /// The channel end of a pipe made through `ThreadState::add_fd`, as
    /// `handle_pipe2` stores it on the read end under `--pipe-wake-latency`.
    fn pipe_with_channel(
        state: &ThreadState<()>,
    ) -> (std::os::fd::OwnedFd, std::os::fd::OwnedFd, ChannelEnd) {
        let (reader, writer) = nix::unistd::pipe2(OFlag::empty()).unwrap();
        state
            .add_fd(reader.as_raw_fd(), OFlag::O_RDONLY, FdType::Pipe, None)
            .unwrap();
        let id = state.metadata().file_handles[&reader.as_raw_fd()].open_file_id();
        let end = ChannelEnd {
            channel: ChannelId::Pipe(id),
            reads: true,
            writes: false,
        };
        state
            .with_detfd(reader.as_raw_fd(), |detfd| detfd.set_channel(end))
            .unwrap();
        (reader, writer, end)
    }

    /// A channel lives on the open file description, so a `dup` and a forked
    /// child's copy of the table carry it with no copy step, while a
    /// descriptor Detcore discovers afresh, as it does one it did not create
    /// (one received over `SCM_RIGHTS`), has none
    /// (<https://github.com/rrnewton/hermit/issues/4380>).
    #[test]
    fn a_pipe_channel_follows_its_description_through_dup_and_fork() {
        let owner = DetTid::from_raw(9018);
        let mut parent = FileMetadata::new(owner);
        let (reader, _writer) = nix::unistd::pipe2(OFlag::empty()).unwrap();
        let fd = reader.as_raw_fd();
        parent
            .add_fd(owner, fd, OFlag::empty(), FdType::Pipe, None)
            .unwrap();
        let end = ChannelEnd {
            channel: ChannelId::Pipe(parent.with_detfd(fd, |detfd| detfd.open_file_id()).unwrap()),
            reads: true,
            writes: false,
        };
        parent
            .with_detfd(fd, |detfd| detfd.set_channel(end))
            .unwrap();
        let alias = fd + 100;
        parent.dup_fd(fd, alias, OFlag::empty()).unwrap();
        assert_eq!(
            parent.with_detfd(alias, |detfd| detfd.channel()).unwrap(),
            Some(end)
        );
        let mut child = parent.fork_for(DetTid::from_raw(9019));
        for fd in [fd, alias] {
            assert_eq!(
                child.with_detfd(fd, |detfd| detfd.channel()).unwrap(),
                Some(end)
            );
        }
        let (received, _peer) = nix::unistd::pipe2(OFlag::empty()).unwrap();
        parent
            .discover_fd_from_current_process(owner, received.as_raw_fd())
            .unwrap();
        assert_eq!(
            parent
                .with_detfd(received.as_raw_fd(), |detfd| detfd.channel())
                .unwrap(),
            None
        );
    }

    /// Under `--pipe-wake-latency` a rediscovering exec carries each surviving
    /// descriptor's channel end and the old numbering. The same leader, whose
    /// new image restarts its open-file sequence, rediscovers pipe A with A's
    /// channel; a pipe B it then makes, past every id the old table allocated,
    /// has another channel value. A descriptor left `O_NONBLOCK`, outside the
    /// blocking set, gets its channel too
    /// (https://github.com/rrnewton/hermit/issues/4380).
    #[test]
    fn a_rediscovering_exec_keeps_pipe_channels_apart() {
        let leader = DetTid::from_raw(9015);
        let config = Config::default();
        let before = ThreadState::new(leader, &config, ());
        let (a_reader, _a_writer, a_end) = pipe_with_channel(&before);
        assert_eq!(
            unsafe { libc::fcntl(a_reader.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) },
            0
        );
        let channels = before.pipe_channels_for_exec();
        assert_eq!(channels, BTreeMap::from([(a_reader.as_raw_fd(), a_end)]));
        let namespace = before.open_file_namespace_for_exec();
        assert_eq!(
            namespace,
            (leader, before.metadata().next_open_file_sequence)
        );

        let after = ThreadState::new(leader, &config, ());
        after
            .metadata()
            .apply_exec_fd_state(
                leader,
                ExecFdState {
                    channels,
                    open_file_namespace: Some(namespace),
                    ..ExecFdState::default()
                },
                true,
            )
            .unwrap();
        assert_eq!(
            after
                .with_detfd(a_reader.as_raw_fd(), |detfd| detfd.channel())
                .unwrap(),
            Some(a_end),
            "the carried channel survives rediscovery"
        );
        let (b_reader, _b_writer, b_end) = pipe_with_channel(&after);
        assert_ne!(b_end.channel, a_end.channel);
        let metadata = after.metadata();
        assert_ne!(
            metadata.file_handles[&b_reader.as_raw_fd()].open_file_id(),
            metadata.file_handles[&a_reader.as_raw_fd()].open_file_id()
        );
    }

    /// A channel held by another process is kept apart too: the old image
    /// made pipe A, a child holds it, and the exec carries no channel at all;
    /// the old numbering is still reserved, so a pipe the new image makes
    /// cannot take A's id.
    #[test]
    fn an_exec_carrying_no_channel_still_reserves_the_old_numbering() {
        let leader = DetTid::from_raw(9016);
        let config = Config::default();
        let before = ThreadState::new(leader, &config, ());
        let (a_reader, _a_writer, a_end) = pipe_with_channel(&before);
        let namespace = before.open_file_namespace_for_exec();
        drop(a_reader);

        let after = ThreadState::new(leader, &config, ());
        let state = ExecFdState {
            open_file_namespace: Some(namespace),
            ..ExecFdState::default()
        };
        assert!(
            !state.is_empty(),
            "a namespace-only state survives reconnect"
        );
        after
            .metadata()
            .apply_exec_fd_state(leader, state, true)
            .unwrap();
        let (_b_reader, _b_writer, b_end) = pipe_with_channel(&after);
        assert_ne!(b_end.channel, a_end.channel);
    }

    /// With the option off the exec state carries neither field: nothing is
    /// reserved, the new image numbers as a fresh one does, and the state's
    /// trace prints as it did before the fields existed. A channel-only state
    /// is not empty.
    #[test]
    fn an_exec_without_the_pipe_wake_latency_is_unchanged() {
        let leader = DetTid::from_raw(9017);
        let config = Config::default();
        let after = ThreadState::new(leader, &config, ());
        let state = ExecFdState::default();
        assert!(state.is_empty());
        assert_eq!(
            format!("{state:?}"),
            "ExecFdState { blocking: {}, inherited_reads: {}, \
             initialize_inherited_stdio: false, initial_input: None, \
             robust_wakes: [], open_files: None }"
        );
        after
            .metadata()
            .apply_exec_fd_state(leader, state, true)
            .unwrap();
        let (reader, _writer, _) = pipe_with_channel(&after);
        let fresh = ThreadState::new(leader, &config, ());
        let (fresh_reader, _fresh_writer, _) = pipe_with_channel(&fresh);
        assert_eq!(
            after.metadata().file_handles[&reader.as_raw_fd()].open_file_id(),
            fresh.metadata().file_handles[&fresh_reader.as_raw_fd()].open_file_id()
        );
        let channel_only = ExecFdState {
            channels: BTreeMap::from([(
                reader.as_raw_fd(),
                ChannelEnd {
                    channel: ChannelId::Pipe(OpenFileId::new(leader, 0)),
                    reads: true,
                    writes: false,
                },
            )]),
            ..ExecFdState::default()
        };
        assert!(!channel_only.is_empty());
        assert!(format!("{channel_only:?}").contains("channels: {"));

        // A description prints its channel only when it has one.
        let (plain, _plain_writer) = nix::unistd::pipe2(OFlag::empty()).unwrap();
        after
            .add_fd(plain.as_raw_fd(), OFlag::O_RDONLY, FdType::Pipe, None)
            .unwrap();
        let printed = format!("{:?}", after.metadata().file_handles[&plain.as_raw_fd()]);
        assert!(!printed.contains(" channel:"), "{printed}");
        assert!(printed.contains("timerfd: None }"), "{printed}");
        let printed = format!("{:?}", after.metadata().file_handles[&reader.as_raw_fd()]);
        assert!(
            printed.contains("timerfd: None, channel: ChannelEnd {"),
            "{printed}"
        );
    }

    fn terminal_pair() -> (std::os::fd::OwnedFd, std::os::fd::OwnedFd) {
        use std::os::fd::FromRawFd;
        let (mut master, mut slave) = (-1, -1);
        assert_eq!(
            unsafe {
                libc::openpty(
                    &raw mut master,
                    &raw mut slave,
                    std::ptr::null_mut(),
                    std::ptr::null(),
                    std::ptr::null(),
                )
            },
            0
        );
        unsafe {
            (
                std::os::fd::OwnedFd::from_raw_fd(master),
                std::os::fd::OwnedFd::from_raw_fd(slave),
            )
        }
    }

    #[test]
    fn inherited_terminal_discovery_keeps_kernel_flags_and_nonterminal_types() {
        let owner = DetTid::from_raw(9);
        let (_master, slave) = terminal_pair();
        let regular = tempfile::tempfile().unwrap();
        let zero = std::fs::File::open("/dev/zero").unwrap();
        let null = std::fs::File::open("/dev/null").unwrap();
        let (pipe, _writer) = nix::unistd::pipe().unwrap();
        let fds = [
            slave.as_raw_fd(),
            regular.as_raw_fd(),
            zero.as_raw_fd(),
            null.as_raw_fd(),
            pipe.as_raw_fd(),
        ];
        let before: Vec<_> = fds
            .iter()
            .map(|fd| unsafe {
                (
                    libc::fcntl(*fd, libc::F_GETFL),
                    libc::fcntl(*fd, libc::F_GETFD),
                )
            })
            .collect();
        let mut metadata = FileMetadata::new(owner);
        for fd in fds {
            metadata
                .discover_fd_from_current_process(owner, fd)
                .unwrap();
        }
        metadata.discover_inherited_terminals(fds);
        for (index, fd) in fds.into_iter().enumerate() {
            let detfd = &metadata.file_handles[&fd];
            assert_eq!(detfd.inherited_external_read().is_some(), index == 0);
            assert_eq!(
                detfd.ty(),
                if index == 4 {
                    FdType::Pipe
                } else {
                    FdType::Regular
                }
            );
            assert_eq!(
                unsafe {
                    (
                        libc::fcntl(fd, libc::F_GETFL),
                        libc::fcntl(fd, libc::F_GETFD),
                    )
                },
                before[index]
            );
        }
    }

    /// A memfd named and sealed as a `/proc/cpuinfo` placeholder, met by a
    /// table that rediscovers descriptors before the session's answer (an
    /// in-guest backend's image after `exec`), is a placeholder only once the
    /// session says it renders the file. With CPUID virtualized but not
    /// intercepted (SaBRe), `Detcore::rendered_files` says it does not, and
    /// the memfd stays the ordinary memfd it is (Codex and
    /// deterministic-scheduling review of
    /// https://github.com/rrnewton/hermit/issues/4213).
    #[test]
    fn a_cpuinfo_placeholder_waits_for_the_sessions_answer() {
        let owner = DetTid::from_raw(9);
        let forged = || {
            // SAFETY: the name is NUL-terminated; the result is checked.
            let raw = unsafe {
                libc::memfd_create(
                    c"hermit-procfs:/proc/cpuinfo@".as_ptr(),
                    libc::MFD_ALLOW_SEALING,
                )
            };
            assert!(
                raw >= 0,
                "memfd_create: {}",
                std::io::Error::last_os_error()
            );
            // SAFETY: `raw` is a descriptor this test just made and owns.
            let fd = unsafe { <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(raw) };
            let seals = crate::syscalls::rendered_procfs::PLACEHOLDER_SEALS;
            assert_eq!(unsafe { libc::fcntl(raw, libc::F_ADD_SEALS, seals) }, 0);
            fd
        };
        let ordinary = |metadata: &FileMetadata, fd: RawFd| {
            metadata.file_handles[&fd].procfs_rendered_path().is_none()
        };
        // The session does not render /proc/cpuinfo (CPUID virtualized by
        // the configuration, but the backend delivers no CPUID to Detcore).
        let fd = forged();
        let mut metadata = FileMetadata::new(owner);
        metadata
            .discover_fd_from_current_process(owner, fd.as_raw_fd())
            .unwrap();
        assert!(ordinary(&metadata, fd.as_raw_fd()));
        metadata.decide_cpuinfo_placeholders(false).unwrap();
        assert!(ordinary(&metadata, fd.as_raw_fd()));
        // Once decided, a later descriptor is not one either.
        let later = forged();
        metadata
            .discover_fd_from_current_process(owner, later.as_raw_fd())
            .unwrap();
        assert!(ordinary(&metadata, later.as_raw_fd()));
        // A later answer of the same session changes nothing.
        metadata.decide_cpuinfo_placeholders(true).unwrap();
        assert!(ordinary(&metadata, fd.as_raw_fd()));
        // The session renders it: the waiting descriptor becomes the
        // placeholder, and so is one met after the answer.
        let mut metadata = FileMetadata::new(owner);
        metadata
            .discover_fd_from_current_process(owner, fd.as_raw_fd())
            .unwrap();
        assert!(ordinary(&metadata, fd.as_raw_fd()));
        metadata.decide_cpuinfo_placeholders(true).unwrap();
        assert_eq!(
            metadata.file_handles[&fd.as_raw_fd()].procfs_rendered_path(),
            Some(std::path::Path::new("/proc/cpuinfo"))
        );
        let after = forged();
        metadata
            .discover_fd_from_current_process(owner, after.as_raw_fd())
            .unwrap();
        assert_eq!(
            metadata.file_handles[&after.as_raw_fd()].procfs_rendered_path(),
            Some(std::path::Path::new("/proc/cpuinfo"))
        );
    }

    #[test]
    fn inherited_terminal_aliases_survive_fork_serialization_and_exec_handoff() {
        use std::os::fd::FromRawFd;
        let owner = DetTid::from_raw(9);
        let (_master, slave) = terminal_pair();
        let fd = slave.as_raw_fd();
        let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
        assert!(duplicate >= 0);
        let duplicate = unsafe { std::os::fd::OwnedFd::from_raw_fd(duplicate) };
        let alias = duplicate.as_raw_fd();
        // Make this alias survive the real descriptor boundary as the model does.
        assert_eq!(unsafe { libc::fcntl(alias, libc::F_SETFD, 0) }, 0);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .discover_fd_from_current_process(owner, fd)
            .unwrap();
        metadata.file_handles[&fd].set_resource(ResourceID::Device(Device::ContainerStdin));
        metadata.discover_inherited_terminals([fd]);
        metadata.dup_fd(fd, alias, OFlag::empty()).unwrap();
        metadata.dup_fd(fd, 100_000, OFlag::O_CLOEXEC).unwrap();
        let child = metadata.fork_for(DetTid::from_raw(10));
        let encoded = serde_json::to_vec(&child).unwrap();
        let child: FileMetadata = serde_json::from_slice(&encoded).unwrap();
        let state = ExecFdState {
            inherited_reads: child.inherited_reads_for_exec(),
            ..Default::default()
        };
        assert_eq!(
            state.inherited_reads.len(),
            2,
            "CLOEXEC alias is not transferred"
        );
        assert_eq!(state.inherited_reads[&fd], state.inherited_reads[&alias]);
        let mut restored = FileMetadata::new(owner);
        restored
            .apply_exec_fd_state(
                owner,
                serde_json::from_slice(&serde_json::to_vec(&state).unwrap()).unwrap(),
                true,
            )
            .unwrap();
        assert_eq!(
            restored.file_handles[&fd].open_file_id(),
            restored.file_handles[&alias].open_file_id()
        );
        assert_eq!(
            restored.file_handles[&alias].resource(),
            Some(ResourceID::Device(Device::ContainerStdin))
        );
        let flags = unsafe { libc::fcntl(alias, libc::F_GETFL) };
        assert_eq!(
            unsafe { libc::fcntl(alias, libc::F_SETFL, flags | libc::O_NONBLOCK) },
            0
        );
        restored.file_handles[&alias].set_status_flags(flags | libc::O_NONBLOCK);
        assert!(restored.file_handles[&fd].is_nonblocking());
        assert!(restored.file_handles[&fd].physically_nonblocking());
        assert_eq!(
            unsafe { libc::fcntl(fd, libc::F_GETFL) },
            flags | libc::O_NONBLOCK
        );
        let mut byte = 0_u8;
        assert_eq!(unsafe { libc::read(fd, (&raw mut byte).cast(), 1) }, -1);
        assert_eq!(Errno::last(), Errno::EAGAIN);
    }

    #[test]
    fn guest_created_terminal_and_reused_descriptor_do_not_gain_inherited_provenance() {
        let owner = DetTid::from_raw(9);
        let (_master, slave) = terminal_pair();
        let fd = slave.as_raw_fd();
        let mut guest_created = FileMetadata::new(owner);
        guest_created
            .discover_fd_from_current_process(owner, fd)
            .unwrap();
        guest_created.dup_fd(fd, 0, OFlag::empty()).unwrap();
        assert!(guest_created.inherited_reads_for_exec().is_empty());
        let mut fresh = FileMetadata::new(owner);
        fresh
            .apply_exec_fd_state(owner, ExecFdState::default(), true)
            .unwrap();
        fresh.discover_fd_from_current_process(owner, fd).unwrap();
        assert!(fresh.file_handles[&fd].inherited_external_read().is_none());

        guest_created.discover_inherited_terminals([fd]);
        let state = ExecFdState {
            inherited_reads: guest_created.inherited_reads_for_exec(),
            ..Default::default()
        };
        // Remove the synthetic slot; only the actual owned fd enters this check.
        let state = ExecFdState {
            inherited_reads: state
                .inherited_reads
                .into_iter()
                .filter(|(number, _)| *number == fd)
                .collect(),
            ..Default::default()
        };
        guest_created.remove_fd(fd);
        let zero = std::fs::File::open("/dev/zero").unwrap();
        assert_eq!(unsafe { libc::dup2(zero.as_raw_fd(), fd) }, fd);
        let mut reused = FileMetadata::new(owner);
        assert_eq!(
            reused.apply_exec_fd_state(owner, state, true),
            Err(Errno::EIO)
        );
        assert!(reused.file_handles[&fd].inherited_external_read().is_none());
    }

    #[test]
    fn on_demand_discovery_finds_a_live_descriptor() {
        let owner = DetTid::from_raw(9);
        let file = tempfile::NamedTempFile::new().expect("create test descriptor");
        let fd = file.as_raw_fd();
        assert_eq!(unsafe { libc::flock(fd, libc::LOCK_SH | libc::LOCK_NB) }, 0);
        let mut metadata = FileMetadata::new(owner);

        assert_eq!(metadata.with_detfd(fd, |_| ()), Err(Errno::EBADF));
        metadata
            .discover_fd_from_current_process(owner, fd)
            .expect("live descriptor should be discovered");
        assert_eq!(
            metadata
                .with_detfd(fd, |detfd| detfd.ty())
                .expect("discovered descriptor should be tracked"),
            FdType::Regular
        );
        assert_eq!(
            metadata
                .with_detfd(fd, |detfd| detfd.known_flock_mode())
                .expect("discovered descriptor should be tracked"),
            None,
            "a live descriptor may already hold a flock that Detcore did not observe"
        );
        assert!(
            !metadata
                .with_detfd(fd, |detfd| detfd.flock_mode_may_be_stale())
                .expect("discovered descriptor should be tracked"),
            "first discovery must not invent a previously known lock state"
        );
        assert!(
            !metadata.has_unsafe_vfork_flock_state(),
            "never-observed history is distinct from a held or invalidated cached claim"
        );

        // The metadata repair must not query by converting or dropping the
        // inherited lock. A separate open must still be excluded by it.
        let separate = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(file.path())
            .expect("open an independent file description");
        assert_eq!(
            unsafe { libc::flock(separate.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) },
            -1
        );
        assert_eq!(Errno::last(), Errno::EWOULDBLOCK);

        metadata
            .with_detfd(fd, |detfd| detfd.set_flock_mode(None))
            .expect("discovered descriptor should remain tracked");
        assert_eq!(metadata.file_handles[&fd].known_flock_mode(), None);
        assert!(!metadata.file_handles[&fd].flock_mode_may_be_stale());
    }

    #[test]
    fn rediscovery_preserves_known_and_invalidated_flock_history() {
        let owner = DetTid::from_raw(9);
        let file = tempfile::tempfile().expect("create test descriptor");
        let fd = file.as_raw_fd();
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, fd, OFlag::O_RDWR, FdType::Regular, None)
            .expect("register an observed open");
        let description = metadata.file_handles[&fd].open_file_id();
        assert_eq!(metadata.file_handles[&fd].known_flock_mode(), Some(None));
        metadata.file_handles[&fd].set_flock_mode(Some(libc::LOCK_SH));

        metadata
            .discover_fd_from_current_process(owner, fd)
            .expect("rediscover an existing descriptor");
        assert_eq!(metadata.file_handles[&fd].open_file_id(), description);
        assert_eq!(
            metadata.file_handles[&fd].known_flock_mode(),
            Some(Some(libc::LOCK_SH))
        );
        assert!(metadata.has_unsafe_vfork_flock_state());

        metadata.file_handles[&fd].forget_flock_mode();
        metadata
            .discover_fd_from_current_process(owner, fd)
            .expect("rediscover an invalidated descriptor");
        assert_eq!(metadata.file_handles[&fd].open_file_id(), description);
        assert_eq!(metadata.file_handles[&fd].known_flock_mode(), None);
        assert!(metadata.file_handles[&fd].flock_mode_may_be_stale());
        assert!(metadata.has_unsafe_vfork_flock_state());
    }

    /// A table carried through serialization (in-guest LiteInst's fork) keeps
    /// its aliases: two descriptors that shared one open file description
    /// before still share one object after, while a separate open stays
    /// separate and descriptor flags stay per descriptor.
    #[test]
    fn a_deserialized_table_keeps_dup_aliases_as_one_open_file() {
        let owner = DetTid::from_raw(9);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::empty(), FdType::Rng, None)
            .expect("register descriptor");
        metadata
            .dup_fd(3, 4, OFlag::O_CLOEXEC)
            .expect("dup the descriptor");
        metadata
            .add_fd(owner, 5, OFlag::empty(), FdType::Rng, None)
            .expect("register a separate open");
        let encoded = serde_json::to_string(&metadata).expect("serialize the table");
        let restored: FileMetadata = serde_json::from_str(&encoded).expect("deserialize the table");
        let three = restored.file_handles[&3].clone();
        let four = restored.file_handles[&4].clone();
        let five = restored.file_handles[&5].clone();
        assert_eq!(three.open_file_id(), four.open_file_id());
        assert_ne!(three.open_file_id(), five.open_file_id());
        // One object again: a read through one alias moves the other's cursor.
        four.advance_random_device_offset(50);
        assert_eq!(three.random_device_offset(), 50);
        assert_eq!(five.random_device_offset(), 0);
        // The table plus the two local handles above.
        assert_eq!(three.open_file_alias_count(), 4);
        // Descriptor flags stay per descriptor.
        assert!(!three.is_cloexec());
        assert!(four.is_cloexec());
    }

    #[test]
    fn fork_makes_inherited_flock_state_unknown_in_parent_and_child() {
        let owner = DetTid::from_raw(9);
        let child = DetTid::from_raw(10);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::empty(), FdType::Regular, None)
            .expect("register descriptor");
        metadata
            .with_detfd(3, |detfd| detfd.set_flock_mode(Some(libc::LOCK_SH)))
            .expect("registered descriptor");

        let mut child_metadata = metadata.fork_for(child);
        assert_eq!(
            metadata
                .with_detfd(3, |detfd| detfd.known_flock_mode())
                .expect("parent descriptor should remain tracked"),
            None,
            "parent cache must not become stale when the child changes the shared open file description"
        );
        assert_eq!(
            child_metadata
                .with_detfd(3, |detfd| detfd.known_flock_mode())
                .expect("child descriptor should be inherited"),
            None,
            "child starts with the same deliberately unknown shared state"
        );
    }

    #[test]
    fn exec_preserves_known_flock_mode_for_surviving_descriptors() {
        let owner = DetTid::from_raw(9);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::empty(), FdType::Regular, None)
            .expect("register descriptor");
        metadata
            .with_detfd(3, |detfd| detfd.set_flock_mode(Some(libc::LOCK_SH)))
            .expect("registered descriptor");

        let mut after_exec = metadata.for_exec(DetTid::from_raw(10));
        assert_eq!(
            after_exec
                .with_detfd(3, |detfd| detfd.known_flock_mode())
                .expect("non-cloexec descriptor should survive"),
            Some(Some(libc::LOCK_SH)),
            "exec must preserve known flock state for a surviving open file description"
        );
    }

    #[test]
    fn discovered_stdio_uses_container_wide_resources() {
        let owner = DetTid::from_raw(9);
        let mut metadata = FileMetadata::new(owner);

        metadata
            .discover_fd_from_current_process(owner, libc::STDOUT_FILENO)
            .expect("live stdout should be discovered");

        assert_eq!(
            metadata
                .with_detfd(libc::STDOUT_FILENO, |detfd| detfd.resource())
                .expect("discovered stdout should be tracked"),
            Some(ResourceID::Device(Device::ContainerStdout))
        );

        // Observe real metadata transitions without closing the test process's
        // stdio. The narrow repair preserves slot identities for inherited
        // resources and leaves aliases above fd 2 in the ordinary inode pool.
        use crate::syscalls::deterministic_stdio_inode_for_resource;

        let inherited_stat = metadata
            .with_detfd(libc::STDOUT_FILENO, |detfd| detfd.stat().unwrap())
            .unwrap();
        metadata.dup_fd(1, 7, OFlag::empty()).unwrap();
        assert_eq!(
            metadata.with_detfd(7, |detfd| detfd.resource()).unwrap(),
            Some(ResourceID::Device(Device::ContainerStdout))
        );
        assert_eq!(
            metadata
                .with_detfd(7, |detfd| {
                    deterministic_stdio_inode_for_resource(7, detfd.resource())
                })
                .unwrap(),
            None
        );
        for fd in 0..=2 {
            metadata.remove_fd(fd);
            let mut ordinary = inherited_stat;
            ordinary.inode = 123 + fd as u64;
            metadata
                .add_fd(owner, fd, OFlag::empty(), FdType::Regular, Some(ordinary))
                .unwrap();
            metadata.dup_fd(fd, 8, OFlag::empty()).unwrap();
            for ordinary_fd in [fd, 8] {
                assert_eq!(
                    metadata
                        .with_detfd(ordinary_fd, |detfd| {
                            deterministic_stdio_inode_for_resource(ordinary_fd, detfd.resource())
                        })
                        .unwrap(),
                    None
                );
            }
            assert_eq!(
                metadata
                    .with_detfd(fd, |detfd| detfd.open_file_id())
                    .unwrap(),
                metadata
                    .with_detfd(8, |detfd| detfd.open_file_id())
                    .unwrap()
            );
            metadata.dup_fd(7, fd, OFlag::empty()).unwrap();
            assert_eq!(
                metadata
                    .with_detfd(fd, |detfd| {
                        deterministic_stdio_inode_for_resource(fd, detfd.resource())
                    })
                    .unwrap(),
                Some(DetInode::mint(1000 + fd as u64)),
                "inherited streams retain the existing numeric-slot outcome"
            );
        }
        metadata.dup_fd(7, 9, OFlag::O_CLOEXEC).unwrap();
        let child = metadata.fork_for(DetTid::from_raw(10));
        let after_exec = child.for_exec(DetTid::from_raw(10));
        assert!(!after_exec.file_handles.contains_key(&9));
        assert!(after_exec.file_handles.contains_key(&7));
    }

    #[test]
    fn discovered_pipe_preserves_inherited_nonblocking() {
        let owner = DetTid::from_raw(9);
        let mut fds = [-1; 2];
        assert_eq!(
            unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK) },
            0
        );
        let mut metadata = FileMetadata::new(owner);

        metadata
            .discover_fd_from_current_process(owner, fds[0])
            .expect("live pipe should be discovered");
        let flags = metadata
            .with_detfd(fds[0], |detfd| {
                (detfd.is_nonblocking(), detfd.physically_nonblocking())
            })
            .expect("discovered pipe should be tracked");

        assert_eq!(flags, (true, true));
        unsafe {
            libc::close(fds[0]);
            libc::close(fds[1]);
        }
    }

    #[test]
    fn exec_handoff_restores_scheduler_pipe_as_logically_blocking() {
        let owner = DetTid::from_raw(9);
        let mut fds = [-1; 2];
        assert_eq!(
            unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK) },
            0
        );
        let mut before_exec = FileMetadata::new(owner);
        before_exec
            .add_fd(owner, fds[0], OFlag::empty(), FdType::Pipe, None)
            .expect("scheduler pipe should be registered");
        before_exec
            .with_detfd(fds[0], |detfd| detfd.set_physically_nonblocking())
            .expect("scheduler pipe should remain registered");

        let overrides = before_exec.exec_blocking_overrides();
        assert_eq!(overrides, BTreeSet::from([fds[0]]));

        let mut after_exec = FileMetadata::new(owner);
        after_exec.apply_exec_blocking_overrides(owner, overrides);
        assert_eq!(
            after_exec
                .with_detfd(fds[0], |detfd| {
                    (detfd.is_nonblocking(), detfd.physically_nonblocking())
                })
                .expect("inherited pipe should be rediscovered"),
            (false, true)
        );

        unsafe {
            libc::close(fds[0]);
            libc::close(fds[1]);
        }
    }

    #[test]
    fn fork_copies_slots_but_preserves_open_file_aliases() {
        let parent_tid = DetTid::from_raw(10);
        let child_tid = DetTid::from_raw(11);
        let mut parent = FileMetadata::new(parent_tid);
        parent
            .add_fd(parent_tid, 3, OFlag::O_NONBLOCK, FdType::Socket, None)
            .expect("parent fd should be inserted");
        parent
            .dup_fd(3, 4, OFlag::O_CLOEXEC)
            .expect("dup should succeed");

        let parent_open = parent
            .with_detfd(3, |fd| fd.open_file_id())
            .expect("parent fd should exist");
        let duplicate_open = parent
            .with_detfd(4, |fd| fd.open_file_id())
            .expect("duplicate fd should exist");
        assert_eq!(parent_open, duplicate_open);

        let initial_timestamp = LogicalTime::from_nanos(1_234_567_890);
        parent
            .with_detfd(3, |fd| fd.set_socket_receive_timestamp(initial_timestamp))
            .expect("parent socket should accept a receive timestamp");

        let mut child = parent.fork_for(child_tid);
        assert_ne!(parent.files_id, child.files_id);
        assert_ne!(
            FdSlot {
                files: parent.files_id,
                fd: 3,
            },
            FdSlot {
                files: child.files_id,
                fd: 3,
            }
        );
        assert_eq!(
            parent_open,
            child
                .with_detfd(3, |fd| fd.open_file_id())
                .expect("forked fd should retain its open file identity")
        );
        assert_eq!(
            child
                .with_detfd(3, |fd| fd.socket_receive_timestamp())
                .expect("forked fd should retain its receive timestamp"),
            Some(initial_timestamp)
        );
        let child_timestamp = LogicalTime::from_nanos(2_345_678_901);
        child
            .with_detfd(3, |fd| fd.set_socket_receive_timestamp(child_timestamp))
            .expect("child socket should update the shared receive timestamp");
        assert_eq!(
            parent
                .with_detfd(4, |fd| fd.socket_receive_timestamp())
                .expect("parent duplicate should see the child update"),
            Some(child_timestamp)
        );

        parent
            .add_fd(parent_tid, 5, OFlag::empty(), FdType::Regular, None)
            .expect("new parent fd should be inserted");
        child
            .add_fd(child_tid, 5, OFlag::empty(), FdType::Regular, None)
            .expect("new child fd should be inserted");
        assert_ne!(
            parent
                .with_detfd(5, |fd| fd.open_file_id())
                .expect("new parent fd should exist"),
            child
                .with_detfd(5, |fd| fd.open_file_id())
                .expect("new child fd should exist"),
            "separate opens after fork must not alias"
        );
    }

    #[test]
    fn pidfd_getfd_target_requires_the_calling_leader() {
        let leader = DetPid::from_raw(31);
        assert!(pidfd_getfd_targets_calling_task(
            Some(leader),
            leader,
            DetTid::from_raw(31),
        ));
        assert!(!pidfd_getfd_targets_calling_task(
            Some(leader),
            leader,
            DetTid::from_raw(32),
        ));
        assert!(!pidfd_getfd_targets_calling_task(
            Some(DetPid::from_raw(32)),
            leader,
            DetTid::from_raw(31),
        ));
    }

    #[test]
    fn captured_fd_installs_when_the_descriptor_table_is_unchanged() {
        let owner = DetTid::from_raw(32);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::empty(), FdType::Regular, None)
            .expect("source should be inserted");
        let source_id = metadata
            .with_detfd(3, |fd| fd.open_file_id())
            .expect("source should exist");
        let captured = metadata.capture_fd(3).expect("source should be captured");

        assert_eq!(
            metadata
                .install_captured_fd(captured, 4, OFlag::O_CLOEXEC)
                .expect("an unchanged table should accept the captured alias"),
            None
        );
        assert_eq!(
            metadata
                .with_detfd(4, |fd| (fd.open_file_id(), fd.is_cloexec()))
                .expect("captured alias should be installed"),
            (source_id, true)
        );
    }

    #[test]
    fn failed_captured_fd_install_preserves_cleanup_obligations() {
        let owner = DetTid::from_raw(36);
        let mut original = FileMetadata::new(owner);
        original
            .add_fd(owner, 3, OFlag::empty(), FdType::Socket, None)
            .expect("source should be inserted");
        let source_id = original
            .with_detfd(3, |fd| fd.open_file_id())
            .expect("source should exist");
        let captured = original.capture_fd(3).expect("source should be captured");
        assert_eq!(
            original.remove_fd(3),
            None,
            "the capture defers final-OFD cleanup while the syscall is in flight"
        );

        let mut replacement_table = FileMetadata::new(DetTid::from_raw(37));
        let failure = replacement_table
            .install_captured_fd(captured, 41, OFlag::O_CLOEXEC)
            .expect_err("a capture must not cross descriptor-table identity");
        assert_ne!(failure.expected_files_id, failure.actual_files_id);
        let cleanup = failure.into_cleanup();
        assert_eq!(cleanup.close_fd, 41);
        assert_eq!(cleanup.release_open_file, Some(source_id));
    }

    #[test]
    fn equal_fd_dup_preserves_descriptor_flags() {
        let owner = DetTid::from_raw(20);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::O_CLOEXEC, FdType::Regular, None)
            .expect("fd should be inserted");

        assert_eq!(
            metadata
                .dup_fd(3, 3, OFlag::empty())
                .expect("equal-fd dup should validate the source"),
            None
        );
        assert!(
            metadata
                .with_detfd(3, |fd| fd.is_cloexec())
                .expect("fd should remain present"),
            "dup2(fd, fd) must not clear close-on-exec"
        );
    }

    #[test]
    fn last_open_file_alias_survives_dup_and_fork() {
        let parent_tid = DetTid::from_raw(30);
        let child_tid = DetTid::from_raw(31);
        let mut parent = FileMetadata::new(parent_tid);
        parent
            .add_fd(parent_tid, 3, OFlag::empty(), FdType::Socket, None)
            .expect("socket should be inserted");
        let open_file_id = parent
            .with_detfd(3, |fd| fd.open_file_id())
            .expect("socket should exist");
        assert_eq!(
            parent
                .dup_fd(3, 4, OFlag::empty())
                .expect("dup should succeed"),
            None
        );
        assert_eq!(parent.remove_fd(3), None, "duplicate retains the OFD");

        let mut child = parent.fork_for(child_tid);
        assert_eq!(parent.remove_fd(4), None, "forked child retains the OFD");
        assert_eq!(
            child.remove_fd(4),
            Some(open_file_id),
            "only the final alias releases the OFD"
        );

        let mut replacement = FileMetadata::new(parent_tid);
        replacement
            .add_fd(parent_tid, 3, OFlag::empty(), FdType::Socket, None)
            .expect("source should be inserted");
        replacement
            .add_fd(parent_tid, 4, OFlag::empty(), FdType::Socket, None)
            .expect("target should be inserted");
        let target_id = replacement
            .with_detfd(4, |fd| fd.open_file_id())
            .expect("target should exist");
        assert_eq!(
            replacement
                .dup_fd(3, 4, OFlag::empty())
                .expect("dup replacement should succeed"),
            Some(target_id),
            "replacing the target must release its last OFD alias"
        );
    }

    #[test]
    fn close_range_removes_selected_slots_and_releases_final_aliases() {
        let owner = DetTid::from_raw(35);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::empty(), FdType::Regular, None)
            .expect("source should be inserted");
        metadata
            .dup_fd(3, 4, OFlag::empty())
            .expect("duplicate should be inserted");
        metadata
            .add_fd(owner, 100, OFlag::empty(), FdType::Regular, None)
            .expect("high fd should be inserted");
        let high_id = metadata
            .with_detfd(100, |fd| fd.open_file_id())
            .expect("high fd should exist");

        assert_eq!(metadata.remove_fd_range(4, 100), [high_id]);
        assert!(metadata.with_detfd(3, |_| ()).is_ok());
        assert_eq!(metadata.with_detfd(4, |_| ()), Err(Errno::EBADF));
        assert_eq!(metadata.with_detfd(100, |_| ()), Err(Errno::EBADF));
    }

    #[test]
    fn exec_reports_only_cloexec_open_files_with_no_other_aliases() {
        let owner = DetTid::from_raw(40);
        let child_tid = DetTid::from_raw(41);
        let mut metadata = FileMetadata::new(owner);
        metadata
            .add_fd(owner, 3, OFlag::O_CLOEXEC, FdType::Socket, None)
            .expect("socket should be inserted");
        let open_file_id = metadata
            .with_detfd(3, |fd| fd.open_file_id())
            .expect("socket should exist");

        assert_eq!(metadata.open_files_closed_on_exec(false), [open_file_id]);
        assert!(
            metadata.open_files_closed_on_exec(true).is_empty(),
            "a shared descriptor table retains the original slot"
        );

        let child = metadata.fork_for(child_tid);
        assert!(
            metadata.open_files_closed_on_exec(false).is_empty(),
            "a copied table retains an OFD alias"
        );
        drop(child);

        metadata
            .dup_fd(3, 4, OFlag::empty())
            .expect("non-CLOEXEC alias should be created");
        assert!(
            metadata.open_files_closed_on_exec(false).is_empty(),
            "a non-CLOEXEC alias keeps the OFD live across exec"
        );
    }
}

/// Various measurements of one guest thread's execution. This is useful for printing
/// context in logs as we go and printing a final summary.
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ThreadStats {
    /// A simple count of how many syscalls have been handled on this thread.
    pub syscall_count: u64,

    /// This thread's happens-before counting state: per (syscall, fd, futex
    /// operation) a syscall-occurrence anchor names, how many of this thread's
    /// syscall entries matched, and the origin of each relative anchor whose
    /// base this thread reached (`HappensBeforeProgram::count_syscall_occurrences`).
    /// Empty unless the run has such an anchor; empty for every new thread,
    /// like `syscall_count`.
    pub hb_occurrences: detcore_model::happens_before::HbThreadCounters,

    /// The posthook happens-before anchors the current syscall entry reached
    /// (`Anchor::fires_at_posthook`): counted at its prehook, they check in
    /// with the scheduler when the call completes. Empty between syscalls.
    pub hb_pending_posthook: Vec<String>,

    /// How many register-file samples this thread has CONSIDERED for `--detlog-regs`.
    ///
    /// This is the cadence index, and it exists because no pre-existing counter is a clean
    /// zero-based count of control points: the logged syscall ordinal starts at 2, and
    /// `syscall_count` also counts points this sampler never reaches. Keying the cadence on either
    /// let a short guest whose points never landed on a multiple of N emit ZERO samples while the
    /// run still reported PASS -- a spot-tier green backed by nothing. Counting the samples
    /// themselves makes index 0 the first control point of every thread, so a spot-tier run always
    /// samples at least once.
    pub regs_sample_index: u64,

    /// A count of how many signals have arrived at this thread, total.
    pub signal_count: u64,

    /// How many syscalls this time slice (since last preemption)?
    pub timeslice_syscall_count: u64,

    /// How many signals this time slice (since last preemption)?
    pub timeslice_signal_count: u64,

    /// How many logical timeslices have we completed before the current one?
    /// These correspond to when we are preempted at the `end_of_timeslice`.
    pub timeslice_count: u64,

    /// The timeslice_count for the timeslice which was the last one that had a recorded end time in
    /// the `--replay-preemptions-from` log.
    pub last_recorded_slice: Option<u64>,

    /// Distribution (min/max/sum/count) of completed timeslice durations for this
    /// thread, in virtual nanoseconds. A slice's duration is the delta of
    /// `thread_logical_time` between two consecutive `next_timeslice` resets.
    pub timeslice_stats: TimesliceStats,

    /// The per-thread logical time (virtual ns) at which the current timeslice
    /// began. `None` until the first slice is opened. Used to compute the
    /// duration of a slice when the next reset occurs.
    pub timeslice_start_ns: Option<LogicalTime>,
}

impl ThreadStats {
    /// Create a new thread stats with zero counters.
    pub fn new() -> Self {
        Default::default()
    }

    // TODO: this can evolve to keep a full histogram:
    /// Increment the count of system calls
    pub fn count_syscall(&mut self) {
        self.syscall_count += 1;
        self.timeslice_syscall_count += 1;
    }

    /// Increment the count of signals.
    pub fn count_signal(&mut self) {
        self.signal_count += 1;
        self.timeslice_signal_count += 1;
    }

    /// Reset counters for a new timeslice.
    /// Increases the count of completed timeslices.
    pub(crate) fn reset_timeslice(&mut self) {
        self.timeslice_syscall_count = 0;
        self.timeslice_signal_count = 0;
        self.timeslice_count += 1;
    }

    /// Close the final, in-progress timeslice at thread exit, recording its
    /// virtual-ns duration. This captures short-lived or I/O-bound threads that
    /// exit (or block until exit) before ever exhausting a slice, so they still
    /// contribute one sample. Idempotent: consumes `timeslice_start_ns`.
    pub fn close_final_timeslice(&mut self, now: LogicalTime) {
        if let Some(start) = self.timeslice_start_ns.take()
            && now >= start
        {
            self.timeslice_stats.record((now - start).as_nanos());
        }
    }
}

/// Information inherited by a `CLONE_VFORK` child so it can register itself
/// while its parent is blocked inside the kernel.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingVfork {
    pub parent_dettid: DetTid,
    pub parent_detpid: DetPid,
    pub child_tid_addr: usize,
    pub flags: CloneFlags,
    pub exit_signal: libc::c_int,
    pub child_priority_entropy: Option<u64>,
}

// TODO-HUMAN-REVIEW(#797): Review process-wide logical CPU aggregation.
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
pub(crate) struct ProcessCpuSnapshot {
    pub user: LogicalTime,
    pub system: LogicalTime,
    pub children_user: LogicalTime,
    pub children_system: LogicalTime,
}

/// Runtime-only readiness for one child birth. A retired or replaced token can
/// never be made ready again; cancelled waiters leave only weak references.
#[derive(Debug)]
pub(crate) struct ChildCpuPublication(Mutex<ChildCpuPublicationState>);

#[derive(Debug)]
enum ChildCpuPublicationState {
    Pending(Vec<std::sync::Weak<futures::task::AtomicWaker>>),
    Published,
    Invalidated,
}

impl ChildCpuPublication {
    fn pending() -> Arc<Self> {
        Arc::new(Self(Mutex::new(ChildCpuPublicationState::Pending(
            Vec::new(),
        ))))
    }

    fn finish(&self, published: bool) {
        let waiters = {
            let mut state = self.0.lock().expect("child CPU publication mutex poisoned");
            if matches!(*state, ChildCpuPublicationState::Invalidated)
                || published && matches!(*state, ChildCpuPublicationState::Published)
            {
                return;
            }
            let next = if published {
                ChildCpuPublicationState::Published
            } else {
                ChildCpuPublicationState::Invalidated
            };
            match std::mem::replace(&mut *state, next) {
                ChildCpuPublicationState::Pending(waiters) => waiters,
                _ => Vec::new(),
            }
        };
        // Do not call an arbitrary task waker under either accounting lock.
        for waiter in waiters.into_iter().filter_map(|waiter| waiter.upgrade()) {
            waiter.wake();
        }
    }

    async fn wait(&self) -> bool {
        let waiter = Arc::new(futures::task::AtomicWaker::new());
        {
            let mut state = self.0.lock().expect("child CPU publication mutex poisoned");
            match &mut *state {
                ChildCpuPublicationState::Pending(waiters) => {
                    waiters.retain(|waiter| waiter.strong_count() != 0);
                    waiters.push(Arc::downgrade(&waiter));
                }
                ChildCpuPublicationState::Published => return true,
                ChildCpuPublicationState::Invalidated => return false,
            }
        }
        futures::future::poll_fn(|cx| {
            waiter.register(cx.waker());
            let state = self.0.lock().expect("child CPU publication mutex poisoned");
            match *state {
                ChildCpuPublicationState::Pending(_) => std::task::Poll::Pending,
                ChildCpuPublicationState::Published => std::task::Poll::Ready(true),
                ChildCpuPublicationState::Invalidated => std::task::Poll::Ready(false),
            }
        })
        .await
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub(crate) struct ProcessCpuTime {
    snapshot: ProcessCpuSnapshot,
    exited_children: BTreeMap<DetPid, ProcessCpuSnapshot>,
    // Runtime ownership, not record-format state. ThreadState clones retain the
    // same parent accounting Arc; notification tokens also retain their identity.
    #[serde(skip)]
    child_cpu_publications: BTreeMap<DetPid, Arc<ChildCpuPublication>>,
}

impl ProcessCpuTime {
    fn validate_native_exec_cut(&self) -> Result<(), crate::native_exec::NativeExecCutError> {
        if !self.child_cpu_publications.is_empty() {
            return Err(crate::native_exec::NativeExecCutError::LiveCapability(
                "child_cpu_publications",
            ));
        }
        Ok(())
    }

    fn add_thread_delta(&mut self, user: LogicalTime, system: LogicalTime) {
        self.snapshot.user = self.snapshot.user + user;
        self.snapshot.system = self.snapshot.system + system;
    }

    fn record_exited_child(&mut self, pid: DetPid, child: ProcessCpuSnapshot) {
        self.exited_children
            .entry(pid)
            .and_modify(|previous| {
                previous.user = previous.user.max(child.user);
                previous.system = previous.system.max(child.system);
                previous.children_user = previous.children_user.max(child.children_user);
                previous.children_system = previous.children_system.max(child.children_system);
            })
            .or_insert(child);
    }

    fn reap_child(&mut self, pid: DetPid) {
        let Some(child) = self.exited_children.remove(&pid) else {
            return;
        };
        self.snapshot.children_user =
            self.snapshot.children_user + child.user + child.children_user;
        self.snapshot.children_system =
            self.snapshot.children_system + child.system + child.children_system;
    }

    fn prepare_child(&mut self, pid: DetPid) {
        self.exited_children.remove(&pid);
    }
}

/// Guest-visible logical clock shared by an entire process tree.
///
/// The scheduler's raw logical time already includes the configured epoch and
/// is the clock used to judge absolute deadlines. Guest time must therefore
/// track it directly: subtracting a per-process or per-exec origin can put a
/// newly computed absolute deadline in the scheduler's past. The shared floor
/// preserves monotonicity if a backend supplies a stale local observation.
#[derive(Debug, Default, Serialize, Deserialize)]
pub(crate) struct GuestClock {
    now: LogicalTime,
}

/// One modeled robust-futex wake that must wait until Linux has completed the
/// corresponding task-exit cleanup.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct RobustListWake {
    pub(crate) futex: FutexID,
}

/// The physical-exit condition under which staged robust-futex wakes become
/// safe to deliver.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum RobustListExit {
    ExitGroup,
    Signal(i32),
}

/// Wakes collected while guest memory is still readable, keyed by the owner
/// whose physical exit makes them safe.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PendingRobustListWakes {
    pub(crate) reason: RobustListExit,
    pub(crate) wakes: Vec<RobustListWake>,
}

impl PendingRobustListWakes {
    fn matches_exit(&self, exit_signal: Option<i32>) -> bool {
        match self.reason {
            RobustListExit::ExitGroup => true,
            RobustListExit::Signal(expected) => exit_signal == Some(expected),
        }
    }
}

/// How long a thread an exit_group killed waits for its robust-list walk
/// ([`ThreadState::wait_for_exit_group_robust_walk`]).
pub(crate) const EXIT_GROUP_ROBUST_WALK_WAIT: std::time::Duration =
    std::time::Duration::from_secs(10);

/// A registered robust list: its owner and head.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RobustListOwner {
    pub(crate) dettid: DetTid,
    pub(crate) head: usize,
}

/// Robust-list registrations and staged wakes shared by one Linux thread
/// group. A forked process starts with an empty instance; `CLONE_THREAD`
/// members share it.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub(crate) struct RobustListProcessState {
    heads: BTreeMap<DetTid, usize>,
    /// Threads whose own exit Detcore has already walked on DBT
    /// ([`crate::syscalls::threads`]'s `OwnerDeathPath::Barrier`).
    #[serde(default)]
    tool_walked: BTreeSet<DetTid>,
    /// An exit_group on DBT (`OwnerDeathPath::Barrier`) has been filed: an
    /// exiting thread keeps its head here for that exit_group's walk
    /// ([`ThreadState::drop_robust_list_head_at_exit`]).
    #[serde(default)]
    exit_group_filed: bool,
    /// The threads whose filed exit_group is still pending: filed, and
    /// neither granted nor cancelled by the thread's own death.
    #[serde(default)]
    exit_group_filers: BTreeSet<DetTid>,
    /// The thread whose filed exit_group was granted and is walking the
    /// group's lists ([`ThreadState::begin_exit_group_robust_walk`]).
    #[serde(default)]
    exit_group_walker: Option<DetTid>,
    /// That exit_group's walk has finished
    /// ([`ThreadState::finish_exit_group_robust_walk`]).
    #[serde(default)]
    exit_group_walked: bool,
    pending: BTreeMap<DetTid, PendingRobustListWakes>,
    matched_physical_exits: BTreeMap<DetTid, DetTime>,
    /// Wakes read at an `execve`'s entry, delivered only if it succeeds.
    exec_pending: Vec<(DetTid, RobustListWake)>,
}

impl GuestClock {
    fn observe(&mut self, raw: LogicalTime) -> LogicalTime {
        self.now = self.now.max(raw);
        self.now
    }
}

/// Linux's initial per-task timer slack, in nanoseconds.
///
/// Detcore uses the kernel default rather than inheriting the launcher's
/// physical timer slack.  Guest writes are kept in virtual per-thread state so
/// they cannot perturb the host-timed waits Detcore still uses internally.
pub(crate) const DEFAULT_TIMER_SLACK_NS: u64 = 50_000;

fn default_timer_slack_ns() -> u64 {
    DEFAULT_TIMER_SLACK_NS
}

/// The most deliveries in a row that continue their thread's own
/// `rt_sigreturn` (`ThreadState::consecutive_continuations`). A chosen,
/// bounded preference budget: as many as Linux has standard signals, so any
/// set of distinct standard signals pending when a run begins is delivered
/// before other threads run. A cap of 1 cut short a second pending signal
/// and restarted the cycle <https://github.com/rrnewton/hermit/issues/4505>
/// fixes (Claude re-check of https://github.com/rrnewton/hermit/pull/4509).
/// It is not a promise that every backlog drains first: realtime signals
/// queue several instances and a periodic timer can re-arm during a run
/// (v6.12 kernel/signal.c:1070 and :695). Reaching the cap only drops the
/// preference; no signal is lost, and the next delivery waits its turn.
pub(crate) const MAX_SIGRETURN_CONTINUATIONS: u8 = 32;

/// The Detcore per-thread state.
#[derive(Serialize, Deserialize, Clone)]
pub struct ThreadState<T> {
    /// The deterministic thread ID of the this thread.
    pub dettid: DetTid,
    /// The deterministic process ID of the this thread.
    pub detpid: Option<DetTid>,

    /// Whether the backend entered the thread-start callback. Construction
    /// alone does not imply that this thread was admitted to the scheduler.
    pub(crate) thread_start_entered: bool,

    /// Host thread ID supplied by a backend whose scheduler identity is
    /// virtual. `None` keeps the existing direct-ID behavior for other
    /// backends.
    #[serde(default)]
    pub physical_tid: Option<i32>,

    /// Backend lifetime retained for consuming signal effects after retirement.
    #[serde(default)]
    pub(crate) signal_task_identity: Option<reverie::SignalTaskIdentity>,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1063): Review backend-supplied open-file creator identity.
    /// Stable identity used when allocating deterministic open-file descriptions.
    #[serde(default)]
    pub(crate) open_file_creator: Option<DetTid>,

    /// Linux memory address space shared by tasks created with `CLONE_VM`.
    pub mm_id: MmId,

    /// Last acknowledged ownership publication. A new mm or changed provider
    /// result is published before ordinary RPC can transfer the turn.
    #[serde(skip)]
    pub(crate) published_runtime_private_memory: Option<(MmId, reverie::RuntimePrivateMemory)>,

    /// Shared memory mappings used to resolve process-shared futex keys.
    pub(crate) memory_metadata: Arc<Mutex<MemoryMetadata>>,

    /// This threads path within the thread/process ancestry tree. (The terminology comes from
    /// Cilk.)
    pub pedigree: Pedigree,

    /// Counting various events.
    pub stats: ThreadStats,

    /// In chaos mode with --replay-preemptions-from, we hold a list of our future preemption points.
    pub preemption_points: Option<ThreadHistoryIterator>,

    /// User defined interruption points
    pub interrupt_at: BTreeSet<u64>,

    /// clone flags when SYS_clone is called.
    ///
    /// This is just a place to stash the value temporarily, where it can be read out by
    /// the child thread upon `init_thread_state`.  After that point, it is consumed by
    /// the child and becomes `None` again.
    ///
    /// Stated differently, this is just for message-passing communication.
    pub clone_flags: Option<CloneFlags>,

    /// Registration metadata for a child whose parent cannot resume until the
    /// backend finishes the child. The child consumes this in
    /// `handle_thread_start`; the parent clears its copy when injection returns.
    pub pending_vfork: Option<PendingVfork>,

    /// Shared file metadata among all threads in the same process.
    /// Initialized for new threads (shared or fresh), and then overwritten again on `execve`.
    pub file_metadata: Arc<Mutex<FileMetadata>>,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-845): Review backend-gated live descriptor discovery state.
    /// Whether the tool runs in the guest's process and shares its descriptor
    /// table, so a descriptor detcore has not seen yet may be inspected live
    /// (copied from `BackendCapabilities::tool_shares_guest_descriptor_table`).
    #[serde(default)]
    pub(crate) tool_shares_guest_descriptor_table: bool,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-2150): Review the per-thread timer-slack state
    // and the creator-current-as-child-default inheritance rule.
    /// Virtualized Linux timer slack for this thread.  Both prctl(2) and the
    /// top-level `/proc/<tid>/timerslack_ns` interface use these fields; the
    /// physical tracee value remains untouched.
    #[serde(default = "default_timer_slack_ns")]
    pub(crate) timer_slack_ns: u64,
    /// Value restored by a zero timer-slack write.  Linux gives a new task the
    /// creating thread's current value as both its current and its default.
    #[serde(default = "default_timer_slack_ns")]
    pub(crate) default_timer_slack_ns: u64,

    /// This thread lives below the container's PID namespace: it, or an
    /// ancestor, was created with `CLONE_NEWPID`. Its pids are those of its
    /// own namespace, which Detcore translates
    /// (`scheduler::pid_namespaces`); at depth 0 nothing is asked.
    #[serde(default)]
    pub(crate) nested_pid_namespace: bool,

    /// This task's root directory may not be the container's: a task it shares
    /// its root with (`CLONE_FS`), or one it inherited the root from, changed
    /// it with `chroot`. Detcore then leaves whether a procfs file exists to
    /// the kernel (`rendered_procfs`). Shared like the root itself: every task
    /// that shares the creator's filesystem information shares this flag.
    #[serde(default)]
    pub(crate) changed_root: Arc<std::sync::atomic::AtomicBool>,

    /// The image this thread's process executes ([`crate::exec_record`]),
    /// which answers the process's `/proc/<pid>/exe` link; `None` leaves the
    /// link to the kernel. A new task starts with its creator's, and a
    /// successful exec replaces it (`tool_global::mark_past_first_execve`).
    #[serde(default)]
    pub(crate) exe: Option<Arc<crate::exec_record::ExecRecord>>,

    /// The identity of the descriptor table this thread's process holds:
    /// the one its thread-group leader holds now, which procfs reads for
    /// the process's descriptor links (`/proc/self/fd/N`, `/proc/<pid>/fd/N`,
    /// `/dev/fd/N`). A new process sets it to the table it starts with (its
    /// creator's under `CLONE_FILES`, a copy otherwise), and an exec to the
    /// table exec gives it; `unshare` is refused, so a leader's table
    /// changes at nothing else. A thread (`CLONE_THREAD`) copies its
    /// creator's. A plain copy suffices: it changes only where the group has
    /// one thread (a new process, a successful exec), and a failed exec
    /// restores the exec'ing thread's own copy. `None` where it is not
    /// known, which only a state serialized before this field restores.
    #[serde(default)]
    pub(crate) process_files: Option<FilesId>,

    /// POSIX per-process timers created via `timer_create(2)`. Shared among the
    /// threads of a process (`CLONE_THREAD`) and not inherited across `fork`.
    pub(crate) posix_timers: Arc<Mutex<PosixTimers>>,

    /// Resource limits shared by threads and copied when a new process forks.
    pub(crate) resource_limits: Arc<Mutex<ResourceLimits>>,

    /// Logical CPU accounting shared by all threads in this process.
    pub(crate) process_cpu_time: Arc<Mutex<ProcessCpuTime>>,

    /// Guest-visible logical clock shared by every task in this process tree.
    #[serde(default)]
    pub(crate) guest_clock: Arc<Mutex<GuestClock>>,

    /// Parent process accounting notified when this process leader exits.
    pub(crate) parent_process_cpu_time: Option<Arc<Mutex<ProcessCpuTime>>>,

    /// Actual sequential KVM child's birth-owned publication capability.
    #[serde(skip)]
    pub(crate) parent_cpu_publication: Option<Arc<ChildCpuPublication>>,

    /// The deadline of a wait this thread's last syscall ended with
    /// `ERESTART_RESTARTBLOCK`, for the `restart_syscall` that resumes it
    /// (`syscalls::helpers::RestartBlock`). The next syscall takes it
    /// (`Detcore::handle_syscall_event`).
    #[serde(skip)]
    pub(crate) restart_block: Option<crate::syscalls::helpers::RestartBlock>,

    /// Whether this thread's process has a guest handler for SIGALRM, so that
    /// signal phase 1's table (`sigalrm_phase1`) gates its syscalls. Set by the
    /// runtime's handler admission (phase 1 step I3), in the same turn it
    /// publishes the disposition to the scheduler's ledger; until then only
    /// tests set it.
    pub(crate) sigalrm_handled: bool,

    /// Detcore's own copy of this thread's signal dispositions and masks
    /// (audit step A5: recorded from the calls that change them, checked
    /// against the kernel where it can be read, and read by the decisions
    /// step 2 converted). `None` until the first image seeds it, and wherever it
    /// cannot be seeded: `None` means unknown, never default actions.
    #[serde(default)]
    pub(crate) signal_shadow: Option<crate::signal_state::SignalShadow>,

    /// Whether this thread, or the thread that created it, lost its signal
    /// state copy after a divergence: a lost copy is never seeded again.
    #[serde(default)]
    pub(crate) signal_shadow_lost: bool,

    /// What this thread was doing at its last guest event, for checking a
    /// signal delivery against the kernel's syscall registers (A5 step 3.2,
    /// `signal_shadow::check_delivery`): the syscall it entered, the result
    /// Detcore finished it with, a handler frame just approved, or no
    /// syscall. `None` is unknown (a new thread or image), and the check then
    /// takes the registers' own answer.
    #[serde(skip)]
    pub(crate) delivery_interruption: Option<reverie::Interruption>,

    /// With `delivery_interruption` `AfterFrame`, the handler address the
    /// kernel's frame jumps to: a further delivery at the same exit, before
    /// any guest instruction, stops with the instruction pointer there.
    #[serde(skip)]
    pub(crate) delivery_frame_handler: u64,

    /// This thread's counts of checked signal deliveries (A5 step 3.2),
    /// logged when it exits.
    #[serde(skip)]
    pub(crate) delivery_counters: crate::syscalls::signal_shadow::DeliveryCounters,

    /// The process's record of its dispositions publications (A5 step 2b,
    /// `signal_shadow::publish_dispositions`): what the scheduler holds, the
    /// latest generation used, and the latest one the scheduler took. Shared
    /// by the threads of a process, which publish one entry.
    #[serde(default)]
    pub(crate) published_dispositions:
        Arc<Mutex<crate::syscalls::signal_shadow::PublishedDispositions>>,

    /// What the scheduler holds as this thread's mask from Detcore's copy
    /// (A5 step 2b, `signal_shadow::publish_mask`): `Some(None)` nothing,
    /// `Some(Some(mask))` that mask; `None` when that is unknown (after an
    /// exec), so the next request publishes or withdraws.
    #[serde(default)]
    pub(crate) published_mask: Option<Option<u64>>,

    /// The SIGALRM blocked bit this thread last published to the scheduler's
    /// ledger (signal phase 1). A handler's return changes the virtual mask
    /// without a syscall; the next syscall's entry compares the runtime's
    /// virtual bit with this one and publishes a change.
    pub(crate) sigalrm_blocked_published: bool,

    /// The real-time signals this thread's process has already recorded as
    /// unblocked by a handler's restored mask
    /// (`Scheduler::handler_restore_unblocked`), so a delivery adds nothing
    /// new without asking the kernel or the scheduler.
    pub(crate) handler_restore_rt_reported: u64,

    /// While Detcore runs its signal pipeline for a SIGALRM it delivers at a
    /// syscall's completion: the registers as that completion leaves them
    /// (`completed_syscall_projection`), which the pipeline reads instead of
    /// the backend's, whose context still shows the syscall's entry. Never
    /// written back.
    #[serde(skip)]
    pub(crate) signal_register_projection: Option<libc::user_regs_struct>,

    /// Per-thread checkpoints used to add only new work to the process totals.
    pub(crate) last_accounted_user_time: LogicalTime,
    pub(crate) last_accounted_system_time: LogicalTime,

    /// Absolute logical-clock values at this thread's creation. Child clocks
    /// inherit the parent's absolute position for scheduler ordering, but Linux
    /// `RUSAGE_THREAD` starts accounting at the calling thread's own creation.
    pub(crate) thread_cpu_start_user_time: LogicalTime,
    pub(crate) thread_cpu_start_system_time: LogicalTime,

    /// pseudo random number state
    pub prng: Pcg64Mcg,

    /// One initial-image auxv write completed by an authenticated backend
    /// before libc initialization. Consumed by the first post-exec callback;
    /// normal construction and child derivation never manufacture this fact.
    #[serde(default)]
    /// The initial image whose AT_RANDOM a backend wrote before post-exec, the
    /// bytes it wrote and its getrandom fills, until post-exec emits their
    /// records.
    pub(crate) initialized_random_auxv: Option<(
        crate::random::InitialImage,
        [u8; 16],
        Vec<crate::random::EarlyRequest>,
    )>,

    /// RNG to drive chaos scheduling decisions, separate from other (guest) RNG.
    pub chaos_prng: Pcg64Mcg,

    /// logical time, measuring progress of this thread and only this thread.
    pub thread_logical_time: DetTime,

    /// the last RCB clock value committed to `thread_logical_time`
    pub committed_clock_value: u64,

    /// Syscalls this thread made in the current backend-runtime bootstrap
    /// window without charging their cost to `thread_logical_time`. Zero
    /// outside a window; see [`ThreadState::charge_syscall_time`].
    #[serde(default)]
    pub(crate) uncharged_bootstrap_syscalls: u32,

    /// True from the moment [`ThreadState::charge_syscall_time`] leaves the
    /// syscall this thread is handling uncharged until that syscall's handler
    /// finishes. Resource requests made meanwhile through
    /// `tool_global::resource_request` are marked
    /// [`Resources::backend_runtime_bootstrap`], so the scheduler withholds
    /// their turn time as well, except for an IO-polling retry, which still
    /// advances it. Requests that bypass `resource_request` (direct futex and
    /// thread-lifecycle requests) are not marked and advance it as usual.
    /// Cleared at the start of every handler and before the syscall handler's
    /// post-hook.
    #[serde(default)]
    pub(crate) in_uncharged_bootstrap_syscall: bool,

    /// Set by the syscall handler when a `FUTEX_WAKE` woke a waiter and
    /// [`Config::yields_after_futex_wake`] holds, so that the
    /// syscall's post-hook takes a yield turn. A logically killed waker gets
    /// `EINTR` (4) as its wake count and may set this although the scheduler
    /// did not requeue it; that thread is already being torn down. The other
    /// way round, the scheduler requeues the waker without a yield following
    /// when the wake is the robust-list owner-death wake of an exiting thread
    /// (which never sets this and skips the post-hook), and when the syscall
    /// handler returns an error after the wake and skips the post-hook. In
    /// both the thread is retiring or the run is failing, and the requeue
    /// alone only reorders the run queue deterministically. Cleared at the
    /// start of every handler and by that post-hook.
    #[serde(default)]
    pub(crate) yield_after_futex_wake: bool,
    /// Under `--pipe-wake-latency` (`crate::pipe_wake`): the thread time at
    /// which this thread hands the turn to the pollers its actions readied,
    /// set at the readying action that the scheduler says starts a window
    /// (`crate::pipe_wake::ReadyOutcome`), checked at syscall boundaries, and
    /// cleared by the hand-off or by a scheduler request of its own. Always
    /// `None` with the option unset.
    #[serde(default)]
    pub(crate) pipe_handoff_due: Option<LogicalTime>,
    /// A signal this thread sent to its own multi-threaded process, which it
    /// must dequeue before another thread runs: until its own delivery stop
    /// for that signal no timeslice of it ends, at the target, at the PMU
    /// maximum or in a timer callback (<https://github.com/rrnewton/hermit/issues/4034>).
    #[serde(default)]
    pub(crate) own_signal_turn_hold: Option<libc::c_int>,
    /// Set when this thread's `rt_sigreturn` passes through, cleared by its
    /// next event of any other kind (`pre_handler_hook`). A signal stop that
    /// finds it set is the thread's first Detcore event since that
    /// `rt_sigreturn`: usually the delivery Linux makes on that same return
    /// to user space of a signal the restored mask unblocks, and otherwise a
    /// fault or host signal its user code met with no intercepted event in
    /// between (`Resources::continues_sigreturn`,
    /// <https://github.com/rrnewton/hermit/issues/4505>).
    #[serde(default)]
    pub(crate) returned_from_sigreturn: bool,
    /// How many of this thread's latest scheduler requests in a row were
    /// deliveries marked `Resources::continues_sigreturn`; any other request
    /// resets it. A delivery is marked only while it is below
    /// [`MAX_SIGRETURN_CONTINUATIONS`]. That cap is what stops a handler that
    /// raises its own signal from holding the CPU for ever, in every mode: a
    /// timeslice end did not interrupt such a run in practice (7,773
    /// deliveries in 15 s without one), and under `--max-timeslice=disabled`
    /// there is none.
    #[serde(default)]
    pub(crate) consecutive_continuations: u8,

    /// Thread state associated with record/replay.
    pub record_or_replay: T,

    /// How much longer does this thread get to run before it must check-in with the
    /// scheduler?  Note that this notion of time slice can extend across a region of time
    /// that includes syscalls (and thus handlers).
    ///
    /// If set to `None`, the thread can run indefinitely without preemption.
    ///
    /// This is in units of virtual Nanoseconds.  And it is an exact time in the future,
    /// not a relative duration.
    pub end_of_timeslice: Option<LogicalTime>,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// Exact per-thread PMU RCB target for the active preemption-replay slice.
    /// `None` selects the legacy logical-time deadline path.
    #[serde(default)]
    pub replay_rcb_end: Option<u64>,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// Deterministic chaos epoch this thread was in at its last `next_timeslice`.
    /// Used only to detect epoch transitions for `CHAOSEPOCH` logging; the epoch
    /// itself is recomputed each slice from `thread_logical_time`. Sentinel
    /// `u64::MAX` guarantees the first slice always logs its initial epoch.
    #[serde(default = "chaos_epoch_sentinel")]
    pub chaos_epoch: u64,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// Exact multiplier currently used to convert this thread's RCBs to virtual time.
    #[serde(default)]
    pub chaos_slowdown_factor: RcbTimeMultiplier,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// True when live chaos configuration or a replay artifact supplies the factor.
    #[serde(default)]
    pub chaos_slowdown_active: bool,

    /// This thread claimed a `SIGCHLD` for a sleep (`SleepSignal::Claimed`),
    /// and the claimed copy's delivery stop has not come yet. That stop places
    /// the delivery (`ChildExitSigchldControl::ClaimedDelivery`) just before
    /// it asks for its turn, so the mark the scheduler keeps is bound to that
    /// copy. A system call, or a copy the ledger drops, clears this once
    /// SIGCHLD is no longer pending for the thread (the claimed copy was never
    /// delivered to it; `syscalls::signal::claim_still_pending`).
    #[serde(default)]
    pub(crate) claimed_sigchld: bool,

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// Transitions waiting to be committed into the preemption artifact.
    #[serde(default)]
    pub pending_chaos_epochs: Vec<ChaosEpochTransition>,

    /// Absolute deadline enforced by the PMU-backed `--max-timeslice` timer. This is separate from
    /// `end_of_timeslice` so syscall-heavy workloads can use a shorter, cheap target deadline.
    pub max_timeslice_end: Option<LogicalTime>,

    /// The deadline hint carried by the last scheduler reply this thread
    /// received (`ThreadState::cap_timeslice_at_deadline`). Applied when the
    /// reply arrives, and again by the two paths that then install a fresh
    /// slice end: thread start and the exec continuation.
    pub last_grant_deadline: Option<Duration>,

    /// Track what our last timer was set for, just to double check that RCB timers are behaving
    /// as expected and see if we went over.  (For exmaple, this behaves badly if threads are not
    /// pinned and our we migrate between cores.)
    pub last_rcb_timer: Option<u64>,

    /// Whether `last_rcb_timer` represents the maximum deadline rather than a manual interrupt.
    #[serde(default)]
    pub last_rcb_timer_is_max: bool,

    /// Are we past the global moment when the guest's first execve of its root binary completes
    /// (with a successful exit code).
    pub(crate) past_global_first_execve: bool,

    /// Guest address of this thread's `struct robust_list_head`, as last
    /// registered by a successful `set_robust_list(2)`.
    ///
    /// Linux clears `task->robust_list` in `copy_process()` and in `execve`, so
    /// this is never inherited: every thread re-registers its own head (glibc
    /// does so in `start_thread`). Detcore replays the kernel's
    /// `exit_robust_list()` walk from this address when the thread exits; see
    /// `crate::syscalls::robust_list`.
    #[serde(default)]
    pub(crate) robust_list_head: Option<usize>,

    /// Per-thread registrations are mirrored here while their shared address
    /// space is readable, so a group exit can walk every dying sibling's list.
    #[serde(default)]
    pub(crate) robust_list_process: Arc<Mutex<RobustListProcessState>>,
}

/// We cannot assume that the record_or_replay "subtool" is Debug, so it is handy to be able to
/// print the Detcore threadstate alone.
impl<T> std::fmt::Debug for ThreadState<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ThreadState")
            .field("dettid", &self.dettid)
            .field("detpid", &self.detpid)
            .field("physical_tid", &self.physical_tid)
            .field("mm_id", &self.mm_id)
            .field("memory_metadata", &self.memory_metadata)
            .field("stats", &self.stats)
            .field("clone_flags", &self.clone_flags)
            .field("file_metadata", &self.file_metadata)
            .field("process_files", &self.process_files)
            .field("posix_timers", &self.posix_timers)
            .field("resource_limits", &self.resource_limits)
            .field("process_cpu_time", &self.process_cpu_time)
            .field("prng", &self.prng)
            .field("chaos_prng", &self.chaos_prng)
            .field("thread_logical_time", &self.thread_logical_time)
            .field("committed_clock_value", &self.committed_clock_value)
            .field("end_of_timeslice", &self.end_of_timeslice)
            .field("replay_rcb_end", &self.replay_rcb_end)
            .field("chaos_epoch", &self.chaos_epoch)
            .field("chaos_slowdown_factor", &self.chaos_slowdown_factor)
            .field("chaos_slowdown_active", &self.chaos_slowdown_active)
            .field("max_timeslice_end", &self.max_timeslice_end)
            .field("last_rcb_timer", &self.last_rcb_timer)
            .field("last_rcb_timer_is_max", &self.last_rcb_timer_is_max)
            .finish()
    }
}

impl<T> Default for ThreadState<T> {
    fn default() -> Self {
        unreachable!()
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1151)
/// Sentinel for `ThreadState::chaos_epoch` before the first `next_timeslice`.
/// `u64::MAX` can never equal a real epoch (`current_ns / N`), so the first
/// chaos slice always emits its `CHAOSEPOCH` transition.
pub(crate) fn chaos_epoch_sentinel() -> u64 {
    u64::MAX
}

impl<T> AsRef<T> for ThreadState<T> {
    fn as_ref(&self) -> &T {
        &self.record_or_replay
    }
}

impl<T> AsMut<T> for ThreadState<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.record_or_replay
    }
}

// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1149)
/// RR-style stable per-thread slowdown factor for chaos scheduling.
///
/// Returns the multiplier applied to a thread's *mean* chaos timeslice length.
/// A factor `> 1.0` means the thread is preempted less often (runs "faster"
/// between preemptions — a slower relative wall-clock for its peers), `< 1.0`
/// means it is preempted more often. The factor is drawn log-uniformly from
/// `[1/max_factor, max_factor]`, so slow and fast are symmetric in log-space
/// and `1.0` is the geometric center.
///
/// The value is a **pure, deterministic function** of `(sched_seed, dettid)`:
/// it depends on no run-order, no wall-clock, and no shared PRNG state, so it
/// is stable for a thread across the whole run and reproducible under a fixed
/// seed (unlike the per-timeslice `chaos_prng` draw, which is redrawn every
/// slice and averages out over a long run). Threads are perturbed by a fixed
/// constant so the factor stream differs from other seed-derived streams (e.g.
/// `post_fork_prng`) that also start from `sched_seed`.
///
/// `max_factor <= 1.0` disables the spread and returns `1.0` (nominal) for
/// every thread; callers validate `max_factor >= 1.0`.
// AUTONOMOUS-BOT-IMPLEMENTED
// TODO-HUMAN-REVIEW(PR-1151)
/// `epoch` selects a deterministic chaos EPOCH: the factor is redrawn per
/// (thread, epoch) so a thread's bias changes in deterministic phases across a
/// long run instead of staying fixed. `epoch == 0` reproduces the epoch-less
/// per-thread-slowdown value EXACTLY (the epoch term is `0` and cancels out of
/// the mix), so enabling epochs never perturbs the first epoch's behavior.
pub(crate) fn chaos_per_thread_slowdown_factor(
    sched_seed: u64,
    dettid: DetTid,
    epoch: u64,
    max_factor: f64,
) -> RcbTimeMultiplier {
    // `<=` (rather than `!(max_factor > 1.0)`) keeps clippy's partial-ord lint
    // happy; validate_invariants already rejects non-finite factors upstream.
    if max_factor <= 1.0 {
        return RcbTimeMultiplier::ONE;
    }
    // Mix the seed with the (stable) deterministic thread id to give each
    // thread its own point in the factor distribution. The salt keeps this
    // stream distinct from other sched_seed-derived streams.
    const SLOWDOWN_SALT: u64 = 0x736c_6f77_646f_776e; // "slowdown"
    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    // Fold the epoch into the mix with its own golden-ratio multiplier. At
    // `epoch == 0` this term is 0, leaving `mixed` identical to the epoch-less
    // factor; each successive epoch decorrelates the draw deterministically.
    const EPOCH_GOLDEN: u64 = 0xbf58_476d_1ce4_e5b9;
    let mixed = sched_seed
        ^ SLOWDOWN_SALT
        ^ ((dettid.as_raw() as u32 as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15))
        ^ epoch.wrapping_mul(EPOCH_GOLDEN);
    let mut prng = Pcg64Mcg::seed_from_u64(mixed);
    // u in [0,1); map to exponent in [-1, 1) then factor = max_factor^exp,
    // i.e. a log-uniform draw over [1/max_factor, max_factor).
    let u: f64 = prng.random::<f64>();
    let exponent = 2.0 * u - 1.0;
    RcbTimeMultiplier::from_f64(max_factor.powf(exponent))
}

impl<T> ThreadState<T> {
    /// What `observe_guest_clock(raw)` would return, without raising the
    /// clock's floor: the guest clock as of a raw observation.
    pub(crate) fn peek_guest_clock(&self, raw: LogicalTime) -> LogicalTime {
        let clock = self.guest_clock.lock().expect("guest clock mutex poisoned");
        clock.now.max(raw)
    }

    /// Inspect the live per-thread cut. Physical task count, childlessness,
    /// coordinator leases and signal dispositions need their own admission;
    /// neither serde nor these lock probes establish those facts.
    pub(crate) fn validate_native_exec_cut(
        &self,
        binding: &crate::native_exec::NativeExecCutBinding,
        config: &Config,
    ) -> Result<(), crate::native_exec::NativeExecCutError> {
        use crate::native_exec::NativeExecCutError;
        use crate::native_exec::try_native_exec_lock;

        if self.dettid != binding.dettid
            || self.detpid != Some(binding.detpid)
            || self.physical_tid != Some(binding.physical_tid)
        {
            return Err(NativeExecCutError::Identity("ThreadState IDs"));
        }
        if !self.thread_start_entered || !self.past_global_first_execve {
            return Err(NativeExecCutError::PreparedState("initial lifecycle"));
        }
        if self.tool_shares_guest_descriptor_table
            != config.backend.tool_shares_guest_descriptor_table
        {
            return Err(NativeExecCutError::Identity("descriptor-table capability"));
        }
        if self.nested_pid_namespace {
            return Err(NativeExecCutError::LiveCapability("nested PID namespace"));
        }
        if self.signal_task_identity.is_some() {
            return Err(NativeExecCutError::LiveCapability("signal task identity"));
        }
        if self.parent_process_cpu_time.is_some() || self.parent_cpu_publication.is_some() {
            return Err(NativeExecCutError::LiveCapability("parent CPU ownership"));
        }
        if self.restart_block.is_some() || self.signal_register_projection.is_some() {
            return Err(NativeExecCutError::LiveCapability("restart/projection"));
        }
        if self.claimed_sigchld {
            return Err(NativeExecCutError::LiveCapability("claimed SIGCHLD"));
        }
        if self.clone_flags.is_some() || self.pending_vfork.is_some() {
            return Err(NativeExecCutError::LiveCapability("clone/vfork"));
        }
        if self.own_signal_turn_hold.is_some()
            || self.sigalrm_handled
            || self.handler_restore_rt_reported != 0
        {
            return Err(NativeExecCutError::LiveCapability("guest signal handler"));
        }
        if self.initialized_random_auxv.is_some() {
            return Err(NativeExecCutError::LiveCapability("initial random handoff"));
        }
        if self.uncharged_bootstrap_syscalls != 0
            || self.in_uncharged_bootstrap_syscall
            || self.yield_after_futex_wake
        {
            return Err(NativeExecCutError::LiveCapability(
                "bootstrap/yield transient",
            ));
        }
        if self.preemption_points.is_some()
            || !self.interrupt_at.is_empty()
            || self.replay_rcb_end.is_some()
            || self.last_rcb_timer.is_some()
            || self.last_rcb_timer_is_max
            || self.max_timeslice_end.is_some()
            || self.chaos_slowdown_active
            || !self.pending_chaos_epochs.is_empty()
        {
            return Err(NativeExecCutError::LiveCapability("RCB/replay/chaos state"));
        }
        let user = self.thread_logical_time.user_cpu_time();
        let system = self.thread_logical_time.system_cpu_time();
        if self.thread_cpu_start_user_time > self.last_accounted_user_time
            || self.last_accounted_user_time > user
            || self.thread_cpu_start_system_time > self.last_accounted_system_time
            || self.last_accounted_system_time > system
        {
            return Err(NativeExecCutError::PreparedState(
                "CPU accounting checkpoints",
            ));
        }
        try_native_exec_lock(&self.process_cpu_time, "process_cpu_time")?
            .validate_native_exec_cut()?;
        // Do not call observe/accounting routines: pending deltas and the
        // process-tree guest floor are continuing state, not a new epoch.
        drop(try_native_exec_lock(&self.guest_clock, "guest_clock")?);
        drop(try_native_exec_lock(
            &self.resource_limits,
            "resource_limits",
        )?);
        drop(try_native_exec_lock(&self.posix_timers, "posix_timers")?);
        Ok(())
    }

    pub(crate) fn validate_old_native_exec_robust_state(
        &self,
    ) -> Result<(), crate::native_exec::NativeExecCutError> {
        use crate::native_exec::NativeExecCutError;
        let process = crate::native_exec::try_native_exec_lock(
            &self.robust_list_process,
            "robust_list_process",
        )?;
        if process.heads.len() != usize::from(self.robust_list_head.is_some())
            || process.heads.get(&self.dettid).copied() != self.robust_list_head
            || !process.pending.is_empty()
            || !process.matched_physical_exits.is_empty()
            || !process.exec_pending.is_empty()
            || !process.tool_walked.is_empty()
            || process.exit_group_filed
            || !process.exit_group_filers.is_empty()
            || process.exit_group_walker.is_some()
            || process.exit_group_walked
        {
            return Err(NativeExecCutError::LiveCapability(
                "old robust process state",
            ));
        }
        Ok(())
    }

    pub(crate) fn validate_prepared_native_exec_cut(
        &self,
        binding: &crate::native_exec::NativeExecCutBinding,
    ) -> Result<(), crate::native_exec::NativeExecCutError> {
        use crate::native_exec::NativeExecCutError;
        use crate::native_exec::try_native_exec_lock;

        if self.mm_id != binding.prepared_mm() {
            return Err(NativeExecCutError::Identity("prepared mm"));
        }
        try_native_exec_lock(&self.file_metadata, "prepared file_metadata")?
            .validate_native_exec_cut(binding.prepared_files(), true)?;
        if !try_native_exec_lock(&self.memory_metadata, "memory_metadata")?
            .is_fresh_for_native_exec()
        {
            return Err(NativeExecCutError::PreparedState("memory_metadata"));
        }
        let process = try_native_exec_lock(&self.robust_list_process, "robust_list_process")?;
        if self.robust_list_head.is_some()
            || !process.heads.is_empty()
            || !process.pending.is_empty()
            || !process.matched_physical_exits.is_empty()
            || !process.tool_walked.is_empty()
            || process.exit_group_filed
            || !process.exit_group_filers.is_empty()
            || process.exit_group_walker.is_some()
            || process.exit_group_walked
        {
            return Err(NativeExecCutError::PreparedState("robust process state"));
        }
        // These wakes belong to the old image. Preserve their order and keys
        // for the actual successful post-exec hook; do not rebase or consume.
        for (owner, wake) in &process.exec_pending {
            if *owner != binding.dettid
                || matches!(wake.futex, FutexID::Private { mm, .. } if mm != binding.old_mm)
            {
                return Err(NativeExecCutError::PreparedState("staged robust wake"));
            }
        }
        Ok(())
    }

    pub(crate) fn observe_guest_clock(&self, raw: LogicalTime) -> LogicalTime {
        self.guest_clock
            .lock()
            .expect("guest clock mutex poisoned")
            .observe(raw)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1060): Review backend-stable child RNG reseeding.
    /// Replaces the host-TID-derived child streams with a backend-provided,
    /// deterministic identity before the thread enters its start hook.
    pub fn reseed_child_rngs(&mut self, parent: &Self, entropy: u128) {
        self.prng = thread_rng_from_parent_entropy("USER RAND", &parent.prng, entropy);
        self.chaos_prng = thread_rng_from_parent_entropy("CHAOSRAND", &parent.chaos_prng, entropy);
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-845): Review SaBRe orphan-thread memory identity recovery.
    /// Repair a thread state that a remote backend had to initialize without
    /// access to its parent's state.
    pub(crate) fn recover_process_mm_id(&mut self, detpid: DetPid) -> bool {
        if self.dettid == detpid || self.mm_id != MmId::initial(self.dettid) {
            return false;
        }

        self.mm_id = MmId::initial(detpid);
        true
    }

    pub(crate) fn account_process_cpu_time(&mut self) {
        let user = self.thread_logical_time.user_cpu_time();
        let system = self.thread_logical_time.system_cpu_time();
        let user_delta = user - self.last_accounted_user_time;
        let system_delta = system - self.last_accounted_system_time;
        self.process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned")
            .add_thread_delta(user_delta, system_delta);
        self.last_accounted_user_time = user;
        self.last_accounted_system_time = system;
    }

    /// Decide whether the syscall this thread is making now charges its cost
    /// to `thread_logical_time`. `in_backend_runtime_bootstrap` is the
    /// backend's `Guest::is_backend_runtime_bootstrap()` answer for this
    /// thread at this syscall.
    ///
    /// Outside a bootstrap window every syscall is charged, and the
    /// per-window count of uncharged syscalls goes back to zero. Inside a
    /// window a syscall that observes virtual time is always charged; any
    /// other syscall is left uncharged until
    /// [`syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS`] of them have been,
    /// and every syscall after that in the same window is charged. Reaching
    /// the cap logs one info line for the window.
    ///
    /// [`syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS`]: crate::syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS
    pub(crate) fn charge_syscall_time(
        &mut self,
        in_backend_runtime_bootstrap: bool,
        sysno: Sysno,
    ) -> bool {
        if !in_backend_runtime_bootstrap {
            if self.uncharged_bootstrap_syscalls != 0 {
                debug!(
                    "[dtid {}] backend runtime bootstrap window left {} syscalls uncharged",
                    self.dettid, self.uncharged_bootstrap_syscalls
                );
                self.uncharged_bootstrap_syscalls = 0;
            }
            return true;
        }
        if crate::syscall_time::observes_virtual_time(sysno) {
            return true;
        }
        if self.uncharged_bootstrap_syscalls < crate::syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS
        {
            self.uncharged_bootstrap_syscalls += 1;
            if self.uncharged_bootstrap_syscalls
                == crate::syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS
            {
                // Once per window: the count stays at the cap from here on.
                info!(
                    "[dtid {}] backend runtime bootstrap window reached its cap of {} uncharged syscalls; every further syscall in this window is charged",
                    self.dettid,
                    crate::syscall_time::MAX_UNCHARGED_BOOTSTRAP_SYSCALLS
                );
            }
            return false;
        }
        true
    }

    pub(crate) fn process_cpu_time(&mut self) -> ProcessCpuSnapshot {
        self.account_process_cpu_time();
        self.process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned")
            .snapshot
    }

    /// This thread's own logical (user, system) CPU time.
    ///
    /// `getrusage(RUSAGE_THREAD)` needs the per-thread counters, not the process aggregate
    /// that [`Self::process_cpu_time`] returns; for a multithreaded guest the two differ and
    /// reporting the aggregate would over-report every thread. Reads the same
    /// `thread_logical_time` counters that `account_process_cpu_time` folds into the process
    /// total, minus the absolute clock inherited when this thread was created.
    pub(crate) fn thread_cpu_time(&self) -> (LogicalTime, LogicalTime) {
        (
            self.thread_logical_time.user_cpu_time() - self.thread_cpu_start_user_time,
            self.thread_logical_time.system_cpu_time() - self.thread_cpu_start_system_time,
        )
    }

    pub(crate) fn record_exited_child_process_cpu_time(&mut self, pid: DetPid) -> bool {
        self.account_process_cpu_time();
        let Some(parent) = &self.parent_process_cpu_time else {
            return true;
        };
        let child = self
            .process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned")
            .snapshot;
        {
            let mut parent = parent
                .lock()
                .expect("parent process CPU time mutex poisoned");
            if let Some(publication) = &self.parent_cpu_publication
                && !parent
                    .child_cpu_publications
                    .get(&pid)
                    .is_some_and(|current| Arc::ptr_eq(current, publication))
            {
                return false;
            }
            parent.record_exited_child(pid, child);
        }
        if let Some(publication) = &self.parent_cpu_publication {
            publication.finish(true);
        }
        true
    }

    /// Called once at the process child's ThreadState birth. The later external
    /// registration's legacy prepare_child call must not replace this token.
    pub(crate) fn prepare_child_cpu_publication(&self, pid: DetPid) -> Arc<ChildCpuPublication> {
        let publication = ChildCpuPublication::pending();
        let previous = {
            let mut parent = self
                .process_cpu_time
                .lock()
                .expect("process CPU time mutex poisoned");
            parent.prepare_child(pid);
            parent
                .child_cpu_publications
                .insert(pid, Arc::clone(&publication))
        };
        if let Some(previous) = previous {
            previous.finish(false);
        }
        publication
    }

    pub(crate) async fn wait_for_child_cpu_publication(&self, pid: DetPid) -> bool {
        let publication = {
            let parent = self
                .process_cpu_time
                .lock()
                .expect("process CPU time mutex poisoned");
            let Some(publication) = parent.child_cpu_publications.get(&pid) else {
                return false;
            };
            Arc::clone(publication)
        };
        // Subscription and publication share the token mutex. Registration
        // followed by a state recheck cannot lose a publication wake. Neither
        // this mutex nor the accounting mutex survives a Pending return.
        if !publication.wait().await {
            return false;
        }
        let parent = self
            .process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned");
        parent
            .child_cpu_publications
            .get(&pid)
            .is_some_and(|current| Arc::ptr_eq(current, &publication))
            && parent.exited_children.contains_key(&pid)
    }

    pub(crate) fn has_exited_child_process_cpu_time(&self, pid: DetPid) -> bool {
        self.process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned")
            .exited_children
            .contains_key(&pid)
    }

    pub(crate) fn reap_child_process_cpu_time(&mut self, pid: DetPid) {
        self.account_process_cpu_time();
        let publication = {
            let mut parent = self
                .process_cpu_time
                .lock()
                .expect("process CPU time mutex poisoned");
            // Preserve legacy missing-snapshot behavior. The KVM waitid path
            // requires the snapshot before its irreversible completion.
            let had_snapshot = parent.exited_children.contains_key(&pid);
            parent.reap_child(pid);
            if had_snapshot {
                parent.child_cpu_publications.remove(&pid)
            } else {
                None
            }
        };
        if let Some(publication) = publication {
            publication.finish(false);
        }
    }

    pub(crate) fn prepare_child_process_cpu_time(&self, pid: DetPid) {
        let mut parent = self
            .process_cpu_time
            .lock()
            .expect("process CPU time mutex poisoned");
        // External registration may repeat preparation after ThreadState birth.
        // Only that birth replaces a KVM token; registration must preserve both
        // a pending token and any already-published snapshot for this birth.
        if !parent.child_cpu_publications.contains_key(&pid) {
            parent.prepare_child(pid);
        }
    }

    /// Create a fresh new thread state from nothing.  In practice this is only used for the thread
    /// state of the root thread of the container.
    pub fn new(pid: DetPid, cfg: &Config, record_or_replay: T) -> Self {
        detlog!(
            "USER RAND: seeding PRNG for root thread with seed {}",
            cfg.rng_seed()
        );
        detlog!(
            "CHAOSRAND: seeding chaos scheduler with seed {}",
            cfg.sched_seed()
        );
        let thread_logical_time = DetTime::new(cfg);
        let last_accounted_user_time = thread_logical_time.user_cpu_time();
        let last_accounted_system_time = thread_logical_time.system_cpu_time();
        let file_metadata = if cfg.backend.tool_shares_guest_descriptor_table {
            let mut metadata = FileMetadata::new(pid);
            for fd in 0..=2 {
                match metadata.discover_fd_from_current_process(pid, fd) {
                    Ok(()) | Err(Errno::EBADF) => {}
                    Err(error) => panic!("unable to discover guest stdio {fd}: {error}"),
                }
            }
            metadata
        } else {
            FileMetadata::new(pid).setup_stdio(pid.into(), pid)
        };
        let process_files = Some(file_metadata.files_id);
        ThreadState {
            dettid: pid,
            detpid: None, // Initialized later.
            thread_start_entered: false,
            physical_tid: None,
            signal_task_identity: None,
            open_file_creator: None,
            mm_id: MmId::initial(pid),
            memory_metadata: Arc::new(Mutex::new(MemoryMetadata::new())),
            pedigree: Pedigree::new(), // Root thread.
            stats: ThreadStats::new(),
            file_metadata: Arc::new(Mutex::new(file_metadata)),
            tool_shares_guest_descriptor_table: cfg.backend.tool_shares_guest_descriptor_table,
            timer_slack_ns: DEFAULT_TIMER_SLACK_NS,
            default_timer_slack_ns: DEFAULT_TIMER_SLACK_NS,
            nested_pid_namespace: false,
            changed_root: Default::default(),
            exe: None,
            process_files,
            posix_timers: Arc::new(Mutex::new(PosixTimers::default())),
            resource_limits: Arc::new(Mutex::new(ResourceLimits::default())),
            process_cpu_time: Arc::new(Mutex::new(ProcessCpuTime::default())),
            guest_clock: Arc::new(Mutex::new(GuestClock::default())),
            parent_process_cpu_time: None,
            parent_cpu_publication: None,
            restart_block: None,
            sigalrm_handled: false,
            signal_shadow: None,
            signal_shadow_lost: false,
            delivery_interruption: None,
            delivery_frame_handler: 0,
            delivery_counters: Default::default(),
            published_mask: Some(None),
            published_dispositions: Arc::default(),
            sigalrm_blocked_published: false,
            handler_restore_rt_reported: 0,
            signal_register_projection: None,
            last_accounted_user_time,
            last_accounted_system_time,
            thread_cpu_start_user_time: last_accounted_user_time,
            thread_cpu_start_system_time: last_accounted_system_time,
            clone_flags: None,
            pending_vfork: None,
            // For the root thread, we initialize from the seed in the config:
            prng: crate::random::root_prng(cfg.rng_seed()),
            initialized_random_auxv: None,
            chaos_prng: Pcg64Mcg::seed_from_u64(cfg.sched_seed()),
            thread_logical_time,
            committed_clock_value: 0,
            uncharged_bootstrap_syscalls: 0,
            in_uncharged_bootstrap_syscall: false,
            yield_after_futex_wake: false,
            pipe_handoff_due: None,
            own_signal_turn_hold: None,
            returned_from_sigreturn: false,
            consecutive_continuations: 0,
            end_of_timeslice: None, // Temporary/bogus.
            replay_rcb_end: None,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-1151)
            chaos_epoch: chaos_epoch_sentinel(),
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-1151)
            chaos_slowdown_factor: RcbTimeMultiplier::ONE,
            chaos_slowdown_active: false,
            claimed_sigchld: false,
            pending_chaos_epochs: Vec::new(),
            max_timeslice_end: None,
            last_grant_deadline: None,
            published_runtime_private_memory: None,
            last_rcb_timer: None,
            last_rcb_timer_is_max: false,
            record_or_replay,
            preemption_points: None,
            past_global_first_execve: false,
            interrupt_at: cfg.interrupts_for_thread(pid),
            robust_list_head: None,
            robust_list_process: Arc::new(Mutex::new(RobustListProcessState::default())),
        }
    }

    /// Apply a required, authenticated initial-image random handoff to the
    /// normal root. Errors are tool initialization failures, never guest errno.
    pub fn apply_initial_random_state(
        &mut self,
        bytes: &[u8],
        config: &Config,
        image: crate::random::InitialImage,
    ) -> Result<(), Errno> {
        if self.initialized_random_auxv.is_some()
            || self.past_global_first_execve
            || self.dettid.as_raw() != image.pid
            || self.clone_flags.is_some()
            || self.pedigree.raw() != Pedigree::new().raw()
        {
            return Err(Errno::EPROTO);
        }
        let (prng, at_random_value, early_requests) =
            crate::random::decode_initial_state(bytes, config, image)?;
        self.prng = prng;
        self.initialized_random_auxv = Some((image, at_random_value, early_requests));
        Ok(())
    }

    /// Consume the early auxv write's fact, returning the bytes it wrote and
    /// the requests served before post-exec, in order, or `None` when no
    /// backend wrote AT_RANDOM before post-exec.
    pub(crate) fn complete_initial_random_auxv(
        &mut self,
        pointer: Option<usize>,
    ) -> Result<Option<crate::random::EarlyRandomRecords>, Errno> {
        let Some((image, _, _)) = self.initialized_random_auxv.as_ref() else {
            return Ok(None);
        };
        if pointer != Some(image.at_random) || self.dettid.as_raw() != image.pid {
            return Err(Errno::EPROTO);
        }
        let (_, at_random_value, early_requests) =
            self.initialized_random_auxv.take().expect("checked above");
        Ok(Some((at_random_value, early_requests)))
    }

    pub(crate) fn record_robust_list_head(&mut self, head: Option<usize>) {
        self.robust_list_head = head;
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        if let Some(head) = head {
            process.heads.insert(self.dettid, head);
        } else {
            process.heads.remove(&self.dettid);
        }
    }

    /// Record that Detcore has walked this thread's own robust list at its
    /// exit (`OwnerDeathPath::Barrier`), so a later exit_group of its group
    /// does not walk the list again ([`exit_group_robust_list_owners`]).
    pub(crate) fn mark_robust_list_walked_by_tool(&self) {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .tool_walked
            .insert(self.dettid);
    }

    /// Note that an exit_group on DBT (`OwnerDeathPath::Barrier`) has been
    /// filed. From now on a thread the exit_group's grant kills waits for its
    /// walk before its native exit ([`Self::wait_for_exit_group_robust_walk`]),
    /// and a thread of the group that exits keeps its head registered for the
    /// walk, so the walk sees the registrations current at the grant even if
    /// an exit hook runs first. A registration, replacement or unregistration
    /// a thread makes still takes effect.
    ///
    /// Nothing clears the filing: the thread group ends with the exit_group.
    /// The one exception is an exec granted first, which kills the filer.
    /// Where exec keeps this shared state for the new image, killed threads'
    /// old heads would then stay listed for a later exit_group. Only DBT files,
    /// and there the exec replaces the in-guest runtime's memory, this state
    /// included; modeling exec on DBT
    /// (<https://github.com/rrnewton/hermit/issues/4268>) must keep it so.
    pub(crate) fn file_exit_group_for_robust_lists(&self) {
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        process.exit_group_filed = true;
        process.exit_group_filers.insert(self.dettid);
    }

    /// Note that this thread's exit_group was granted and that it now walks
    /// the group's lists. Only this thread does not wait for the walk: any
    /// other thread, including one that filed an exit_group of its own and
    /// was killed by this one's grant, waits.
    pub(crate) fn begin_exit_group_robust_walk(&self) {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .exit_group_walker = Some(self.dettid);
    }

    /// Note that this thread was killed, so any exit_group it filed can never
    /// be granted. Once every filing is cancelled this way with none granted
    /// (an exec ended the group first), no walk will come, and the threads
    /// waiting for one are released ([`Self::wait_for_exit_group_robust_walk`]).
    pub(crate) fn cancel_exit_group_filing(&self) {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .exit_group_filers
            .remove(&self.dettid);
    }

    /// Note that the filed exit_group's walk has finished, releasing the
    /// threads it killed ([`Self::wait_for_exit_group_robust_walk`]).
    pub(crate) fn finish_exit_group_robust_walk(&self) {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .exit_group_walked = true;
    }

    /// Where an exit_group of this thread's group is filed and this thread is
    /// not walking it, wait until that exit_group's walk has finished, or until
    /// every filing has been cancelled with none granted, at most `bound`.
    /// Returns false if the bound expired first, which the caller treats as a
    /// failure of the run, never as permission to go on.
    ///
    /// A thread the exit_group kills retires with a native exit. On DBT that
    /// exit first rewrites the thread's robust-list owner words to its host
    /// TID and then lets Linux mark them, which would race the walk: the walk
    /// could find a word that no longer names its owner, and could not tell
    /// whose it was. Waiting makes the walk see every word as the guest left
    /// it. That includes a thread that filed an exit_group of its own and was
    /// killed by another's grant; only the thread whose exit_group was granted
    /// ([`Self::begin_exit_group_robust_walk`]) does not wait. The wait is on
    /// host time, but nothing guest-visible depends on how long it takes: the
    /// thread is already logically dead. A walk that never comes, because an
    /// exec killed every filer first, is recognised when the last filing is
    /// cancelled ([`Self::cancel_exit_group_filing`]). Only DBT files an
    /// exit_group, and there each guest thread polls its own callbacks, so the
    /// blocking wait holds up only this thread.
    pub(crate) fn wait_for_exit_group_robust_walk(&self, bound: std::time::Duration) -> bool {
        let started = std::time::Instant::now();
        loop {
            {
                let process = self
                    .robust_list_process
                    .lock()
                    .expect("robust-list process state mutex poisoned");
                if !process.exit_group_filed
                    || process.exit_group_walked
                    || process.exit_group_walker == Some(self.dettid)
                    || (process.exit_group_walker.is_none() && process.exit_group_filers.is_empty())
                {
                    return true;
                }
            }
            if started.elapsed() >= bound {
                return false;
            }
            std::thread::sleep(std::time::Duration::from_micros(200));
        }
    }

    /// The exit hook's counterpart of `record_robust_list_head(None)`: the
    /// thread is gone, so its own head is cleared, but while an exit_group is
    /// filed ([`Self::file_exit_group_for_robust_lists`]) its registration
    /// stays in the group's index.
    pub(crate) fn drop_robust_list_head_at_exit(&mut self) {
        self.robust_list_head = None;
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        if !process.exit_group_filed {
            process.heads.remove(&self.dettid);
        }
    }

    /// The registrations an exit_group walks on DBT
    /// (`OwnerDeathPath::Barrier`), read at its grant: every registration current then, including
    /// those of threads the grant killed, less any thread whose own exit
    /// Detcore already replayed, so no list is walked twice.
    pub(crate) fn robust_list_owners_for_exit_group(&self) -> Vec<RobustListOwner> {
        let walked = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .tool_walked
            .clone();
        self.robust_list_owners()
            .into_iter()
            .filter(|owner| !walked.contains(&owner.dettid))
            .collect()
    }

    /// [`Self::robust_list_heads`] as [`RobustListOwner`]s.
    pub(crate) fn robust_list_owners(&self) -> Vec<RobustListOwner> {
        let process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        process
            .heads
            .iter()
            .map(|(&dettid, &head)| RobustListOwner { dettid, head })
            .collect()
    }

    #[cfg(test)]
    pub(crate) fn robust_list_heads(&self) -> Vec<(DetTid, usize)> {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .heads
            .iter()
            .map(|(&tid, &head)| (tid, head))
            .collect()
    }

    pub(crate) fn stage_robust_list_wakes(
        &self,
        reason: RobustListExit,
        wakes: Vec<(DetTid, Vec<RobustListWake>)>,
    ) {
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        process.pending = wakes
            .into_iter()
            .map(|(owner, wakes)| (owner, PendingRobustListWakes { reason, wakes }))
            .collect();
        process.matched_physical_exits.clear();
    }

    pub(crate) fn has_matching_robust_list_exit(&self, exit_signal: Option<i32>) -> bool {
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .pending
            .get(&self.dettid)
            .is_some_and(|pending| pending.matches_exit(exit_signal))
    }

    pub(crate) fn take_robust_list_wakes_after_exit(
        &self,
        exit_signal: Option<i32>,
        exit_time: DetTime,
    ) -> Option<(DetTime, Vec<(DetTid, RobustListWake)>)> {
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        if !process.exit_group_filed {
            process.heads.remove(&self.dettid);
        }
        let pending = process.pending.get(&self.dettid)?;
        if !pending.matches_exit(exit_signal) {
            return None;
        }

        process
            .matched_physical_exits
            .insert(self.dettid, exit_time);
        if process
            .pending
            .keys()
            .any(|owner| !process.matched_physical_exits.contains_key(owner))
        {
            return None;
        }

        let request_time = process
            .matched_physical_exits
            .values()
            .max()
            .expect("a completed robust-list exit group has a physical-exit time")
            .clone();
        process.matched_physical_exits.clear();
        let pending = std::mem::take(&mut process.pending);
        let mut ready = Vec::new();
        for (owner, mut pending) in pending {
            pending
                .wakes
                .sort_by_key(|wake| format!("{:?}", wake.futex));
            ready.extend(pending.wakes.into_iter().map(|wake| (owner, wake)));
        }
        Some((request_time, ready))
    }

    /// Hold the owner-death wakes a successful `execve` makes Linux deliver.
    ///
    /// Past exec's point of no return, `de_thread` kills every other thread,
    /// and each one's exit runs `futex_exit_release` with its own TID; then
    /// `exec_mm_release` runs `futex_exec_release` for the caller itself
    /// (kernel/fork.c `exit_mm_release`/`exec_mm_release`, kernel/futex/core.c
    /// `futex_cleanup`, Linux 7.1.3). Both walk the robust list with
    /// `exit_robust_list` before the old address space goes away. A caller that
    /// is not the group leader already holds the leader's TID by then
    /// (`exchange_tids` in `de_thread`), so its own list is walked with the
    /// thread group ID. The lists can only be read before the exec, and a
    /// failed exec never reaches that point, so the wakes wait here for
    /// `take_robust_list_wakes_for_exec`.
    pub(crate) fn stage_robust_list_wakes_for_exec(
        &self,
        wakes: Vec<(DetTid, Vec<RobustListWake>)>,
    ) {
        let mut process = self
            .robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned");
        process.exec_pending = flatten_exec_robust_list_wakes(wakes);
    }

    /// Take the wakes staged at the exec's entry: to deliver them once it has
    /// succeeded, or to drop them when it failed and left the old image running.
    pub(crate) fn take_robust_list_wakes_for_exec(&self) -> Vec<(DetTid, RobustListWake)> {
        std::mem::take(
            &mut self
                .robust_list_process
                .lock()
                .expect("robust-list process state mutex poisoned")
                .exec_pending,
        )
    }

    /// Clear the robust-list head for a candidate `execve` image, returning the
    /// previous value so a *failed* exec can put it back.
    ///
    /// Linux clears `task->robust_list` when `execve` succeeds, and doing the
    /// same is load-bearing rather than tidy: a head recorded against the old
    /// address space is a wild pointer in the new one, and consulting it at
    /// thread exit would walk unrelated guest memory and write
    /// `FUTEX_OWNER_DIED` into whatever happened to look like a futex word.
    pub(crate) fn take_robust_list_for_exec(&mut self) -> Option<usize> {
        let previous = self.robust_list_head.take();
        self.robust_list_process
            .lock()
            .expect("robust-list process state mutex poisoned")
            .heads
            .remove(&self.dettid);
        previous
    }

    /// Restore the head after an `execve` that failed and left the old address
    /// space intact.
    pub(crate) fn restore_robust_list_after_failed_exec(&mut self, previous: Option<usize>) {
        self.record_robust_list_head(previous);
    }

    /// Resolve a futex key from its opcode mode and virtual address.
    pub(crate) fn futex_id(&self, address: usize, is_private: bool) -> FutexID {
        if is_private {
            FutexID::private(self.mm_id, address)
        } else {
            self.memory_metadata
                .lock()
                .expect("memory metadata mutex poisoned")
                .futex_id(self.mm_id, address)
        }
    }

    /// Record an anonymous shared mapping.
    pub(crate) fn map_shared_anonymous(&self, start: usize, len: usize) {
        self.memory_metadata
            .lock()
            .expect("memory metadata mutex poisoned")
            .map_anonymous(self.mm_id, start, len);
    }

    /// Record a file-backed shared mapping.
    pub(crate) fn map_shared_object(
        &self,
        start: usize,
        len: usize,
        object: SharedMemoryObjectId,
        object_offset: u64,
    ) {
        self.memory_metadata
            .lock()
            .expect("memory metadata mutex poisoned")
            .map_object(start, len, object, object_offset);
    }

    /// Remove a range from the shared mapping model.
    pub(crate) fn unmap_memory(&self, start: usize, len: usize) {
        self.memory_metadata
            .lock()
            .expect("memory metadata mutex poisoned")
            .unmap(start, len);
    }

    /// Move or resize a range in the shared mapping model.
    pub(crate) fn remap_memory(
        &self,
        old_start: usize,
        old_len: usize,
        new_start: usize,
        new_len: usize,
        keep_source: bool,
    ) {
        self.memory_metadata
            .lock()
            .expect("memory metadata mutex poisoned")
            .remap(old_start, old_len, new_start, new_len, keep_source);
    }

    /// Build a singleton resource request from the current thread.
    pub fn mk_request(&self, rid: ResourceID, perm: Permission) -> Resources {
        let mut resources = HashMap::new();
        resources.insert(rid, perm);
        Resources {
            tid: self.dettid,
            resources,
            poll_attempt: 0,
            fyi: String::new(),
            signal_interrupt_errno: None,
            backend_runtime_bootstrap: false,
            blocked_signal_mask: None,
            blocked_signal_mask_unknown: false,
            replay_served_from_log: false,
            reads_signalfd: false,
            read_fd: None,
            polls_guest_state_only: false,
            waits_until_nothing_else_can_run: false,
            previous_attempt_made_progress: false,
            upgraded_from_attempt: 0,
            polls_channel: None,
            poll_deadline: None,
            in_guest_sleep_sigalrm: None,
            signal_state_task: None,
            decides_signal_interruption_itself: false,
            continues_sigreturn: false,
            private_sigchld_decides: false,
        }
    }

    /// Generate the next random number using the thread-local chaos_seed.
    pub fn chaos_prng_next_u64(&mut self, msg: &str) -> u64 {
        let r = self.chaos_prng.next_u64();
        detlog!("[dtid {}] CHAOSRAND({}): u64 => {}", self.dettid, msg, r);
        r
    }

    /// get file metadata
    fn metadata(&self) -> MutexGuard<'_, FileMetadata> {
        self.file_metadata.lock().unwrap()
    }

    /// Identity of this thread's descriptor table.
    pub(crate) fn files_id(&self) -> detcore_model::fd::FilesId {
        self.metadata().files_id
    }

    /// Whether this thread holds the descriptor table its process holds
    /// ([`ThreadState::process_files`]), the one procfs reads for the
    /// process's descriptor links. `false` where that is not known.
    pub(crate) fn holds_process_files(&self) -> bool {
        self.process_files == Some(self.files_id())
    }

    /// Make the descriptor table this thread holds its process's, for a new
    /// group: after a successful exec the exec'ing thread is its process's
    /// only thread, and leads it, whether or not it led it before.
    pub(crate) fn adopt_process_files(&mut self) {
        self.process_files = Some(self.files_id());
    }

    /// Add a new fd, with optional stat data, have side effects on other
    /// threads.
    ///
    /// If stat data is not available, then perform an extra stat ourselves to populate it.
    ///
    /// # Arguments
    ///
    /// * `fd` - file descriptor to add
    ///
    /// * `flags` - flags when creating `fd`
    ///
    /// * `ty` - fd type (regular file, socket, pipe, etc..)
    ///
    /// * `stat` - stat returned from fstat
    pub fn add_fd(
        &self,
        fd: RawFd,
        flags: OFlag,
        ty: FdType,
        stat: Option<DetStat>,
    ) -> Result<(), Errno> {
        self.metadata().add_fd(
            self.open_file_creator.unwrap_or(self.dettid),
            fd,
            flags,
            ty,
            stat,
        )
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1063): Review backend-supplied open-file creator identity.
    /// Overrides the task identity embedded in subsequently allocated open-file descriptions.
    pub fn set_open_file_creator(&mut self, creator: DetTid) {
        self.open_file_creator = Some(creator);
    }

    /// This process's timerfds that Detcore keeps on virtual time
    /// (`crate::fd::VirtualTimerfd`), one descriptor per open file
    /// description, lowest descriptor number first, so callers visit them in
    /// a deterministic order.
    pub(crate) fn virtual_timerfds(&self) -> Vec<(RawFd, DetFd)> {
        let mut timerfds: Vec<(RawFd, DetFd)> = self
            .metadata()
            .file_handles
            .iter()
            .filter(|(_, detfd)| detfd.ty() == FdType::Timerfd && detfd.virtual_timerfd().is_some())
            .map(|(&fd, detfd)| (fd, detfd.clone()))
            .collect();
        timerfds.sort_unstable_by_key(|(fd, _)| *fd);
        let mut descriptions = Vec::with_capacity(timerfds.len());
        timerfds.retain(|(_, detfd)| {
            let id = detfd.open_file_id();
            let first = !descriptions.contains(&id);
            descriptions.push(id);
            first
        });
        timerfds
    }

    /// Whether this thread's descriptor table holds a signalfd, as Detcore
    /// records its descriptors.
    pub(crate) fn holds_a_signalfd(&self) -> bool {
        self.metadata()
            .file_handles
            .values()
            .any(|detfd| matches!(detfd.ty(), FdType::Signalfd))
    }

    /// Whether this thread's descriptor table holds a procfs file Detcore
    /// renders (`syscalls::files::rendered_procfs`).
    pub(crate) fn holds_a_rendered_procfs_file(&self) -> bool {
        self.metadata()
            .file_handles
            .values()
            .any(|detfd| detfd.procfs_rendered_path().is_some())
    }

    /// Get a mutable reference of `DetFd` from a raw file descriptor, and
    /// run mutable function `f` on it (`&mut DetFd`).
    pub fn with_detfd<F, U>(&self, fd: RawFd, f: F) -> Result<U, Errno>
    where
        F: FnMut(&mut DetFd) -> U,
    {
        let mut metadata = self.metadata();
        if self.tool_shares_guest_descriptor_table {
            metadata.discover_fd_from_current_process(
                self.open_file_creator.unwrap_or(self.dettid),
                fd,
            )?;
        }
        metadata.with_detfd(fd, f)
    }

    /// Preserve logical blocking for scheduler-managed descriptors when exec
    /// replaces an in-process tool and its descriptor metadata.
    pub fn exec_blocking_overrides(&self) -> ExecFdBlockingOverrides {
        self.metadata().exec_blocking_overrides()
    }

    /// Promote the OFDs whose model must stay one copy -- random devices
    /// (their cursor) and timerfds (their virtual-time expirations,
    /// `crate::fd::VirtualTimerfd`) -- before a backend physically copies or
    /// replaces its in-process Tool. The shared model owns their full state;
    /// this does not promote sockets or other OFDs. Call only while this task
    /// owns its serial grant, before the native lifecycle operation can expose
    /// a child/new image. Ptrace's host-side Arc needs no promotion. See
    /// <https://github.com/rrnewton/hermit/issues/4381>.
    pub fn promote_shared_open_files(&self) -> Result<(), crate::fd::SharedOpenFileError> {
        let mut metadata = self.metadata();
        let mut fds: Vec<_> = metadata.file_handles.keys().copied().collect();
        fds.sort_unstable();
        for fd in fds {
            let handle = &metadata.file_handles[&fd];
            if matches!(handle.ty(), FdType::Rng | FdType::Timerfd) {
                handle.promote()?;
                // Keep history even if every promoted descriptor later closes.
                metadata.has_promoted_shared_files = true;
            }
        }
        Ok(())
    }

    /// Rebuild only process-local locks after a physical process copy. This
    /// is RPC-free and precedes the child's first scheduler admission. Ordinary
    /// same-process table clones retain their original shared locks.
    pub fn reset_copied_open_file_locks(&self) {
        let mut metadata = self.metadata();
        let mut handles = metadata
            .file_handles
            .iter()
            .map(|(&fd, handle)| (fd, handle.fork_shared_handle()))
            .collect();
        crate::fd::intern_open_files(&mut handles);
        metadata.file_handles = handles;
    }

    /// Under `--pipe-wake-latency`: the channel end each descriptor that
    /// survives exec is.
    pub(crate) fn pipe_channels_for_exec(&self) -> BTreeMap<RawFd, crate::pipe_wake::ChannelEnd> {
        self.metadata()
            .file_handles
            .iter()
            .filter(|(_, detfd)| !detfd.is_cloexec())
            .filter_map(|(&fd, detfd)| detfd.channel().map(|end| (fd, end)))
            .collect()
    }

    /// The open-file creator and next sequence of this thread's table.
    pub(crate) fn open_file_namespace_for_exec(&self) -> (DetTid, u64) {
        (
            self.open_file_creator.unwrap_or(self.dettid),
            self.metadata().next_open_file_sequence,
        )
    }

    pub(crate) fn shared_open_files_for_exec(&self) -> Result<Option<ExecOpenFiles>, Errno> {
        let metadata = self.metadata();
        if !metadata.has_promoted_shared_files {
            return Ok(None);
        }
        let mut handles = BTreeMap::new();
        for (&fd, handle) in &metadata.file_handles {
            if !handle.is_shared() || handle.is_cloexec() {
                continue;
            }
            assert!(
                matches!(handle.ty(), FdType::Rng | FdType::Timerfd),
                "only random and timerfd OFDs are promoted here"
            );
            handles.insert(fd, ExecOpenFile::capture(fd, handle.open_file_id())?);
        }
        Ok(Some(ExecOpenFiles {
            creator: self.open_file_creator.unwrap_or(self.dettid),
            next_sequence: metadata.next_open_file_sequence,
            next_socket_sequence: metadata.next_socket_open_file_sequence,
            handles,
        }))
    }

    pub(crate) fn maps_for_exec(
        &self,
        private_memory: Option<&reverie::RuntimePrivateMemory>,
    ) -> Result<Option<ExecMapsFiles>, Errno> {
        // An unavailable advertised provider still owns saved maps bindings.
        // Backends without a provider retain their existing exec behavior.
        if private_memory.is_none() {
            return Ok(None);
        }
        let metadata = self.metadata();
        let mut handles = BTreeMap::new();
        for (&fd, handle) in &metadata.file_handles {
            if handle.is_cloexec() {
                continue;
            }
            if let Some(procfs) = handle.maps_for_exec() {
                handles.insert(
                    fd,
                    ExecMapsFile {
                        identity: ExecOpenFile::capture(fd, handle.open_file_id())?,
                        procfs,
                        flags: handle.status_flags(),
                        path: handle.path(),
                    },
                );
            }
        }
        Ok((!handles.is_empty()).then_some(ExecMapsFiles {
            creator: self.open_file_creator.unwrap_or(self.dettid),
            next_sequence: metadata.next_open_file_sequence,
            handles,
        }))
    }

    pub(crate) fn inherited_reads_for_exec(
        &self,
    ) -> BTreeMap<RawFd, crate::fd::InheritedExternalRead> {
        self.metadata().inherited_reads_for_exec()
    }

    /// Descriptors in this table that Detcore manages as internal pipes: typed
    /// `Pipe`, physically nonblocking and logically blocking, which is how
    /// `handle_pipe2` leaves a guest-created pipe (and how exec restores it).
    /// On ptrace, a pipe inherited from the host is not in this set: stdio is
    /// typed `Regular`, and another inherited FIFO is physically nonblocking
    /// only when it is logically nonblocking too. On a backend whose tool
    /// shares the guest's descriptor table, a readable pipe inherited on fds
    /// 0-2 is an inherited external read (`discover_inherited_pipes`), so it is
    /// not here either, and a guest `F_SETFL` leaves its kernel status flags
    /// as the guest set them (`keeps_physically_nonblocking`).
    /// Sorted, so callers probe them in a deterministic order.
    pub(crate) fn scheduler_managed_pipe_fds(&self) -> Vec<RawFd> {
        let mut fds: Vec<RawFd> = self
            .metadata()
            .file_handles
            .iter()
            .filter(|(_, detfd)| {
                detfd.ty() == FdType::Pipe
                    && detfd.inherited_external_read().is_none()
                    && detfd.physically_nonblocking()
                    && !detfd.is_nonblocking()
            })
            .map(|(&fd, _)| fd)
            .collect();
        fds.sort_unstable();
        fds
    }

    /// Mark every listener in this table eligible for accept in turn as passed
    /// over `SCM_RIGHTS` (`DetFd::set_exported`), for a message whose
    /// descriptors Detcore could not read.
    // TODO-HUMAN-REVIEW(PR-3908)
    pub(crate) fn mark_accept_in_turn_listeners_exported(&self) {
        for detfd in self.metadata().file_handles.values() {
            if detfd.is_accept_in_turn_eligible() {
                detfd.set_exported();
            }
        }
    }

    /// Descriptors in this table that name a network record/replay channel,
    /// sorted.
    pub(crate) fn network_channel_fds(&self) -> Vec<RawFd> {
        let mut fds: Vec<RawFd> = self
            .metadata()
            .file_handles
            .iter()
            .filter(|(_, detfd)| detfd.is_network_channel())
            .map(|(&fd, _)| fd)
            .collect();
        fds.sort_unstable();
        fds
    }

    pub(crate) fn count_open_files_at_paths(&self, paths: &[&Path]) -> usize {
        self.metadata().count_open_files_at_paths(paths)
    }

    /// Whether this task owns a socket that attempted a loopback connection.
    pub(crate) fn has_loopback_peer(&self) -> bool {
        self.metadata().has_loopback_peer()
    }

    /// Whether any open file description is held or not proven unlocked.
    pub fn has_unsafe_vfork_flock_state(&self) -> bool {
        self.metadata().has_unsafe_vfork_flock_state()
    }

    /// Whether a description in this table may hold an OFD lock. A copied
    /// `vfork` child (DBT) runs its lock calls natively, so the
    /// `procfs::locks::LockLedger` entry of such a description could go stale
    /// and admit a host's identical `/proc/locks` row.
    pub fn has_unsafe_vfork_ofd_state(&self) -> bool {
        self.metadata().has_unsafe_vfork_ofd_state()
    }

    /// A new process can change every inherited open file description through
    /// a separately hosted tool state, so neither side may keep treating its
    /// cached flock mode as authoritative after fork.
    pub fn forget_flock_modes(&self) {
        self.metadata().forget_flock_modes();
    }

    /// remove a rawfd
    pub fn remove_fd(&self, fd: RawFd) -> Option<OpenFileId> {
        self.metadata().remove_fd(fd)
    }

    /// Remove every modeled descriptor in an inclusive close_range interval.
    pub(crate) fn remove_fd_range(&self, first: u32, last: u32) -> Vec<OpenFileId> {
        self.metadata().remove_fd_range(first, last)
    }

    /// How many slots of this thread's table name the open file description
    /// `open_file` (`procfs::locks::LockLedger`).
    pub(crate) fn slots_naming(&self, open_file: OpenFileId) -> u32 {
        let count = self
            .metadata()
            .file_handles
            .values()
            .filter(|detfd| detfd.open_file_id() == open_file)
            .count();
        u32::try_from(count).unwrap_or(u32::MAX)
    }

    /// The descriptions in this thread's table whose locks
    /// `procfs::locks::LockLedger` follows, each with how many slots name it,
    /// in description order.
    pub(crate) fn lock_tracked_slots(&self) -> Vec<(OpenFileId, u32)> {
        let mut slots: BTreeMap<OpenFileId, u32> = BTreeMap::new();
        for detfd in self.metadata().file_handles.values() {
            if detfd.is_lock_tracked() {
                *slots.entry(detfd.open_file_id()).or_default() += 1;
            }
        }
        slots.into_iter().collect()
    }

    /// The descriptors Detcore's table holds for this thread, in order.
    pub(crate) fn open_fds(&self) -> Vec<RawFd> {
        let mut fds: Vec<RawFd> = self.metadata().file_handles.keys().copied().collect();
        fds.sort_unstable();
        fds
    }

    /// dup raw fds.
    pub fn dup_fd(
        &mut self,
        oldfd: RawFd,
        newfd: RawFd,
        flags: OFlag,
    ) -> Result<Option<OpenFileId>, Errno> {
        let mut metadata = self.metadata();
        if self.tool_shares_guest_descriptor_table {
            metadata.discover_fd_from_current_process(
                self.open_file_creator.unwrap_or(self.dettid),
                oldfd,
            )?;
        }
        metadata.dup_fd(oldfd, newfd, flags)
    }

    /// Atomically validate a pidfd target and capture its source descriptor.
    ///
    /// Both lookups occur under the one descriptor-table mutex. The caller must
    /// hold the normal serialized Tool turn until the nonblocking kernel call
    /// returns and the captured alias is installed.
    pub(crate) fn capture_pidfd_getfd_source(
        &self,
        pidfd: RawFd,
        targetfd: RawFd,
        current_tgid: DetPid,
        current_tid: DetTid,
    ) -> Result<CapturedDetFd, Errno> {
        let mut metadata = self.metadata();
        if self.tool_shares_guest_descriptor_table {
            metadata.discover_fd_from_current_process(
                self.open_file_creator.unwrap_or(self.dettid),
                pidfd,
            )?;
        }
        let (is_pidfd, target) = metadata.with_detfd(pidfd, |detfd| {
            (matches!(detfd.ty(), FdType::Pidfd), detfd.pidfd_target())
        })?;
        if !is_pidfd {
            return Err(Errno::EBADF);
        }
        if !pidfd_getfd_targets_calling_task(target, current_tgid, current_tid) {
            return Err(Errno::EOPNOTSUPP);
        }
        if self.tool_shares_guest_descriptor_table {
            metadata.discover_fd_from_current_process(
                self.open_file_creator.unwrap_or(self.dettid),
                targetfd,
            )?;
        }
        metadata.capture_fd(targetfd)
    }

    /// Install an alias from a pre-syscall capture without resolving the source
    /// fd slot a second time.
    pub(crate) fn install_captured_fd(
        &mut self,
        captured: CapturedDetFd,
        newfd: RawFd,
        flags: OFlag,
    ) -> Result<Option<OpenFileId>, CapturedDetFdInstallError> {
        self.metadata().install_captured_fd(captured, newfd, flags)
    }

    /// Install `detfd`, which refers to an open file description Detcore
    /// models, as descriptor `detfd.fd` of this table: a descriptor that
    /// reached the description by a route Detcore does not model
    /// (`SCM_RIGHTS`), adopted when the guest first names it
    /// (`Detcore::adopt_received_placeholders`).
    pub(crate) fn install_alias(&self, detfd: DetFd) {
        self.metadata().add_detfd(detfd);
    }

    /// Abandon an uninstalled capture and identify a deferred final-OFD release.
    pub(crate) fn abandon_captured_fd(&self, captured: CapturedDetFd) -> Option<OpenFileId> {
        self.metadata().abandon_captured_fd(captured)
    }

    /// get thread prng, note this rng is deterministic and should not be used
    /// for crypto.
    pub fn thread_prng(&mut self) -> &mut Pcg64Mcg {
        &mut self.prng
    }

    /// Whether a trapped instruction (`rdtsc`, `cpuid`) should end the current
    /// timeslice.
    ///
    /// By default it ends an expired target, as a syscall does. A trapped
    /// instruction can sit inside a user-space spinlock critical section,
    /// though, and a thread that yields there leaves every thread that wants
    /// the lock spinning until the PMU maximum preempts it. QEMU's
    /// `cpu_get_ticks` reads the host TSC under its `vm_clock_lock` spinlock,
    /// so a multi-threaded TCG vCPU that yielded at every expired target while
    /// reading the TSC held that lock at every yield, and the other vCPU never
    /// acquired it. With `--target-timeslice-syscalls-only`, a trapped
    /// instruction ends the slice only at the PMU maximum, as a branch would.
    /// With no PMU maximum it is the only way out of a busy-wait on the TSC,
    /// and it still ends the expired target. Replay of recorded preemptions or
    /// schedules keeps its recorded boundaries.
    pub(crate) fn instruction_trap_ends_timeslice(&self, cfg: &Config) -> bool {
        let replaying = self.preemption_points.is_some() || cfg.replay_schedule_from.is_some();
        match self.max_timeslice_end {
            Some(max_end) if cfg.target_timeslice_syscalls_only && !replaying => {
                self.thread_logical_time.as_nanos() >= max_end
            }
            _ => self.timeslice_expired(),
        }
    }

    /// End the current slice no later than `remaining` from now: the virtual
    /// time that was left before the earliest pending deadline when this
    /// thread was granted its turn.
    ///
    /// Global time advances exactly as this thread's clock does while it runs
    /// alone, so its slice then ends, and it takes a turn, once global time has
    /// passed that deadline.
    ///
    /// The slice keeps at least `min_slice`, one scheduler turn charge, and
    /// at least one RCB's worth of time. Every cap-induced slice end is a turn
    /// charged that much, so a thread runs at least as long as the turn it
    /// pays for: the virtual time the cap adds is at most the thread's own
    /// work. With a shorter floor, a sibling sleeping just over one turn
    /// charge made each slice about 1 us of work per 1-1.5 ms of virtual time.
    ///
    /// Only the software slice end moves, which takes effect at the thread's
    /// next check-in: a syscall, signal or timer event. The PMU maximum keeps
    /// its value, so a thread that makes no syscalls still runs to it: a
    /// precise PMU stop at every deadline costs about 70 ms of host time each,
    /// and a fast timer would make them constant
    /// (<https://github.com/rrnewton/hermit/issues/4121>). A schedule replay follows
    /// its recorded turns, and a preemption replay its recorded slice ends,
    /// neither capped. Past the last recorded point a replay's slice end is
    /// `LogicalTime::MAX` (its PMU maximum stays bounded), and the cap may
    /// lower it; that need not reproduce the record's own slice ends.
    pub(crate) fn cap_timeslice_at_deadline(
        &mut self,
        remaining: Duration,
        clock_multiplier: f64,
        min_slice: Duration,
        schedule_replay: bool,
    ) {
        let recorded_slice =
            self.preemption_points.is_some() && self.stats.last_recorded_slice.is_none();
        if recorded_slice || schedule_replay {
            return;
        }
        let Some(end) = self.end_of_timeslice else {
            return;
        };
        let one_rcb =
            (NANOS_PER_RCB * clock_multiplier * self.rcb_time_multiplier().as_f64()).ceil() as u64;
        let current = self.thread_logical_time.as_nanos();
        let cap = current
            + remaining
                .max(min_slice)
                .max(Duration::from_nanos(one_rcb + 1));
        if cap < end {
            debug!(
                "[dtid {}] end of slice moved from {} to {}, the earliest pending deadline (current {})",
                self.dettid, end, cap, current
            );
            self.end_of_timeslice = Some(cap);
        }
    }

    /// Whether this thread has consumed its current logical timeslice.
    pub(crate) fn timeslice_expired(&self) -> bool {
        if let Some(replay_rcb_end) = self.replay_rcb_end {
            return self.committed_clock_value >= replay_rcb_end;
        }
        let current_time = self.thread_logical_time.as_nanos();
        self.end_of_timeslice
            .is_some_and(|end_of_timeslice| current_time >= end_of_timeslice)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    /// Current RCB virtual-time multiplier, including recorded replay state.
    pub(crate) fn rcb_time_multiplier(&self) -> RcbTimeMultiplier {
        if self.chaos_slowdown_active {
            self.chaos_slowdown_factor
        } else {
            RcbTimeMultiplier::ONE
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    pub(crate) fn take_pending_chaos_epochs(&mut self) -> Vec<ChaosEpochTransition> {
        std::mem::take(&mut self.pending_chaos_epochs)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    fn install_chaos_epoch(&mut self, transition: ChaosEpochTransition, record: bool) {
        self.chaos_epoch = transition.epoch;
        self.chaos_slowdown_factor = transition.factor;
        self.chaos_slowdown_active = true;
        if record {
            self.pending_chaos_epochs.push(transition);
        }
        detlog!(
            "[dtid {}] CHAOSEPOCH => epoch = {}, factor = {}, logical_time = {}",
            self.dettid,
            transition.epoch,
            transition.factor.as_f64(),
            transition.logical_time
        );
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    /// Choose the logical target and PMU maximum deadlines for the next timeslice.
    ///
    /// Effects:
    /// - Sets `end_of_timeslice` for the new timeslice.
    /// - Sets `max_timeslice_end` when PMU-backed preemption is enabled.
    /// - Resets the statistics for the timeslice.
    ///
    /// Returns: an optional new priority.
    pub fn next_timeslice(&mut self, cfg: &Config) -> Option<Priority> {
        let logical_timeslice = cfg.target_timeslice.or(cfg.max_timeslice);
        if let Some(timeout_ns) = logical_timeslice {
            let current_ns = self.thread_logical_time.as_nanos();

            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-1151)
            // Redraw only at scheduler commit boundaries, keyed to elapsed
            // deterministic logical time. Replay artifacts take precedence and
            // restore the exact recorded Q32 factor even without ambient flags.
            let replay_has_epochs = self
                .preemption_points
                .as_ref()
                .is_some_and(ThreadHistoryIterator::has_chaos_epochs);
            if replay_has_epochs {
                // Precise PMU replay deliberately checks in up to one RCB
                // before the recorded logical boundary. The new slice still
                // begins at that recorded boundary, so install its factor
                // against the prior slice's exact target rather than the
                // slightly-early observed clock. Otherwise a short epoch can
                // be skipped and the following RCBs receive the wrong weight.
                let transition_time = self.end_of_timeslice.unwrap_or(current_ns);
                let transition = self
                    .preemption_points
                    .as_mut()
                    .and_then(|history| history.advance_chaos_epoch(transition_time));
                if let Some(transition) = transition {
                    self.install_chaos_epoch(transition, false);
                }
            } else if cfg.chaos && cfg.chaos_per_thread_slowdown {
                let elapsed_ns = self.thread_logical_time.without_starting().as_nanos();
                let epoch = elapsed_ns
                    .checked_div(cfg.chaos_epoch_length_ns)
                    .unwrap_or(0);
                let factor = chaos_per_thread_slowdown_factor(
                    cfg.sched_seed(),
                    self.dettid,
                    epoch,
                    cfg.chaos_slowdown_max_factor,
                );
                if epoch != self.chaos_epoch {
                    self.install_chaos_epoch(
                        ChaosEpochTransition {
                            logical_time: current_ns,
                            epoch,
                            factor,
                        },
                        true,
                    );
                } else {
                    self.chaos_slowdown_factor = factor;
                    self.chaos_slowdown_active = true;
                }
            } else {
                self.chaos_slowdown_factor = RcbTimeMultiplier::ONE;
                self.chaos_slowdown_active = false;
                self.pending_chaos_epochs.clear();
            }

            let mut result = None;
            self.replay_rcb_end = None;
            let replay_controls_deadline =
                self.preemption_points.is_some() || cfg.replay_schedule_from.is_some();

            // Preemption-point replay from recorded --chaos configuration.
            if let Some(thi) = &mut self.preemption_points {
                if self.stats.last_recorded_slice.is_none() {
                    // We have not tapped out the recording yet.
                    if let Some((end_time, prio, replay_rcb_end)) = thi.next_with_rcbs() {
                        debug!(
                            "[dtid {}] next timeslice (T{}), set by recording to {:?} (current {}), priority {}",
                            self.dettid,
                            self.stats.timeslice_count + 1,
                            end_time,
                            current_ns,
                            prio
                        );
                        let current_rcbs = self.committed_clock_value;
                        if let Some(target_rcbs) = replay_rcb_end
                            && target_rcbs < current_rcbs
                        {
                            panic!(
                                "Cannot set RCB end of timeslice to {} for thread {}, when current RCB count is already {}.",
                                target_rcbs, self.dettid, current_rcbs
                            )
                        }
                        let exact_deadline_is_now =
                            replay_rcb_end.is_some_and(|target| target == current_rcbs);
                        if end_time <= current_ns && !exact_deadline_is_now {
                            // Records that store their epoch are reconciled with
                            // this run's epoch before any guest starts (see
                            // `adopt_replayed_schedule_epoch` in hermit-cli), so
                            // reaching this with such a record means the replay
                            // really diverged. A record without an epoch cannot
                            // be checked up front; say what usually causes it.
                            panic!(
                                "Cannot set end of timeslice to {} for thread {}, when current thread logical time is already {}. \
                                 The replayed preemption record's timeslice ends are absolute virtual times; if it was \
                                 recorded under a different virtual-time epoch, replay it with that --epoch \
                                 (https://github.com/rrnewton/hermit/issues/3413).",
                                end_time, self.dettid, current_ns
                            )
                        }
                        self.end_of_timeslice = Some(end_time);
                        self.replay_rcb_end = replay_rcb_end;
                        result = Some(prio);
                    } else {
                        let max = LogicalTime::MAX;
                        let prio = thi.final_priority();
                        debug!(
                            "[dtid {}] next timeslice (T{}) final slice after recorded preemption points... setting end_of_timeslice to max {}, final priority {}",
                            self.dettid,
                            self.stats.timeslice_count + 1,
                            max,
                            prio
                        );
                        self.stats.last_recorded_slice = Some(self.stats.timeslice_count);
                        self.end_of_timeslice = Some(max);
                        result = Some(prio)
                    }
                } else {
                    tracing::warn!(
                        "[dtid {}] next timeslice: timer expired beyond the last recorded preemption.  Not handled yet.",
                        self.dettid
                    );
                    self.end_of_timeslice = Some(LogicalTime::MAX);
                    result = Some(thi.final_priority())
                }
            } else if !cfg.chaos {
                if cfg.replay_schedule_from.is_some() {
                    if cfg.no_rcb_time {
                        let max_timeslice = cfg
                            .max_timeslice
                            .expect("schedule replay with PMU requires a maximum");
                        self.end_of_timeslice =
                            Some(current_ns + Duration::from_nanos(u64::from(max_timeslice)));
                    } else {
                        // Branch-event replay will overwrite this deadline when needed.
                        debug!(
                            "[dtid {}] next timeslice (T{}), in replay mode setting timeslice to max (current time {})",
                            self.dettid,
                            self.stats.timeslice_count + 1,
                            current_ns
                        );
                        self.end_of_timeslice = Some(LogicalTime::MAX);
                    }
                } else {
                    // In non-chaos mode, we only care about preemption for breaking busy-waits,
                    // and we can safely reset the clock every time we get control back from the
                    // guest.  This is our preemption-of-last-resort:
                    self.end_of_timeslice =
                        Some(current_ns + Duration::from_nanos(u64::from(timeout_ns)));
                    debug!(
                        "[dtid {}] next timeslice (T{}), end of slice set to {} (current {})",
                        self.dettid,
                        self.stats.timeslice_count + 1,
                        self.end_of_timeslice.unwrap(),
                        current_ns,
                    );
                }
            } else {
                // AUTONOMOUS-BOT-IMPLEMENTED
                // TODO-HUMAN-REVIEW(PR-1151)
                // The slowdown changes RCB-to-virtual-time progression. Converting
                // the sampled virtual duration back to RCBs with the SAME factor
                // keeps the deadline and guest-visible clock internally consistent.
                let slowdown = self.rcb_time_multiplier().as_f64();
                let nanos_per_rcb = NANOS_PER_RCB * cfg.clock_multiplier.unwrap_or(1.0) * slowdown;
                let target_timeout_rcbs = u64::from(timeout_ns) as f64 / nanos_per_rcb;
                if self.chaos_slowdown_active {
                    detlog!(
                        "[dtid {}] CHAOSSLOWDOWN => factor = {}, virtual ns/rcb = {}",
                        self.dettid,
                        slowdown,
                        nanos_per_rcb
                    );
                }
                let next_rcbs: u64 = if cfg.chaos {
                    // Average frequency of preemptions per nanosecond:
                    let lambda = 1.0 / target_timeout_rcbs;
                    let exp = Exp::new(lambda).unwrap();
                    // Add one to prevent generating a zero time slice:
                    let rcbs = 1 + exp.sample(&mut self.chaos_prng) as u64;
                    detlog!("[dtid {}] CHAOSRAND => next_rcbs = {}", self.dettid, rcbs);
                    rcbs
                } else {
                    target_timeout_rcbs as u64
                };
                assert!(next_rcbs > 0);
                self.last_rcb_timer = None;
                self.end_of_timeslice = Some(
                    current_ns
                        + Duration::from_nanos((next_rcbs as f64 * nanos_per_rcb).ceil() as u64),
                );
                debug!(
                    "[dtid {}] next timeslice (T{}) chosen as {} rcbs, end of slice = {} (current {})",
                    self.dettid,
                    self.stats.timeslice_count + 1,
                    next_rcbs,
                    self.end_of_timeslice.unwrap(),
                    current_ns
                );
            }

            let configured_max_end = cfg
                .max_timeslice
                .map(|max_timeslice| current_ns + Duration::from_nanos(u64::from(max_timeslice)));
            self.max_timeslice_end = if replay_controls_deadline {
                if cfg.max_timeslice.is_some() {
                    // A replay history uses `LogicalTime::MAX` after its last
                    // recorded preemption. Keep periodic PMU check-ins bounded
                    // instead of trying to program that sentinel as an RCB
                    // timer, which the kernel rejects with EINVAL.
                    self.end_of_timeslice
                        .filter(|end| *end != LogicalTime::MAX)
                        .or(configured_max_end)
                } else {
                    None
                }
            } else if cfg.target_timeslice.is_none() {
                match (self.end_of_timeslice, configured_max_end) {
                    (Some(logical_end), Some(configured_end)) => {
                        Some(logical_end.min(configured_end))
                    }
                    (_, configured_end) => configured_end,
                }
            } else {
                configured_max_end
            };

            if let (Some(target_end), Some(max_end)) =
                (self.end_of_timeslice, self.max_timeslice_end)
                && target_end > max_end
            {
                self.end_of_timeslice = Some(max_end);
            }

            self.last_rcb_timer = None;
            self.last_rcb_timer_is_max = false;
            self.reset_timeslice_stats(current_ns);
            result
        } else {
            self.end_of_timeslice = None;
            self.replay_rcb_end = None;
            self.max_timeslice_end = None;
            self.last_rcb_timer = None;
            self.last_rcb_timer_is_max = false;
            None
        }
    }

    /// Close the current logical-timeslice statistics without selecting a new
    /// preemption point. Used when preemption replay reaches a deterministic
    /// guest sched_yield boundary.
    pub fn reset_timeslice_for_explicit_yield(&mut self) {
        let current_ns = self.thread_logical_time.as_nanos();
        self.reset_timeslice_stats(current_ns);
    }

    fn reset_timeslice_stats(&mut self, current_ns: LogicalTime) {
        if let Some(start) = self.stats.timeslice_start_ns
            && current_ns >= start
        {
            self.stats
                .timeslice_stats
                .record((current_ns - start).as_nanos());
        }
        self.stats.timeslice_start_ns = Some(current_ns);
        self.stats.reset_timeslice();
    }

    /// Are we within the execution of the (first) guest binary or any child processes called by it?
    /// Returns false if we are in the very beginning of execution, when the hermit container has
    /// forked our process, but we have not yet executed the guest binary.  There are few guarantees
    /// during this early initialization period, and Detcore should make no assumptions, nor
    /// guarantee determinism!
    pub fn guest_past_first_execve(&self) -> bool {
        self.past_global_first_execve
    }
}

#[cfg(test)]
mod timeslice_tests {
    use std::num::NonZeroU64;

    use super::*;
    use crate::DEFAULT_PRIORITY;
    use crate::preemptions::ThreadHistory;

    /// Once an exit_group is filed on DBT (`OwnerDeathPath::Barrier`), an
    /// exiting thread's head stays registered for the exit_group's walk, but
    /// an unregistration still counts, a registration made after the filing
    /// is seen, and a thread whose own exit Detcore replayed is left out
    /// (https://github.com/rrnewton/hermit/issues/4238).
    #[test]
    fn an_exit_group_walks_the_registrations_current_at_its_grant() {
        let owner = |tid: i32, head: usize| RobustListOwner {
            dettid: DetTid::from_raw(tid),
            head,
        };
        let mut caller = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
        let sibling = |tid: i32| {
            let mut state = caller.clone();
            state.dettid = DetTid::from_raw(tid);
            state
        };
        let (mut killed, mut exited, mut late, mut replaced, mut unregistered) =
            (sibling(4), sibling(5), sibling(6), sibling(7), sibling(8));
        caller.record_robust_list_head(Some(0x3000));
        killed.record_robust_list_head(Some(0x4000));
        exited.record_robust_list_head(Some(0x5000));
        replaced.record_robust_list_head(Some(0x7000));
        unregistered.record_robust_list_head(Some(0x8000));

        caller.file_exit_group_for_robust_lists();
        // Before the grant: thread 5 makes its own exit, which Detcore
        // replays; thread 6 registers; thread 7 replaces its head; thread 8
        // unregisters.
        exited.mark_robust_list_walked_by_tool();
        exited.drop_robust_list_head_at_exit();
        late.record_robust_list_head(Some(0x6000));
        replaced.record_robust_list_head(Some(0x7700));
        unregistered.record_robust_list_head(None);
        // The grant kills thread 4, whose exit hook runs before the walk.
        killed.drop_robust_list_head_at_exit();
        assert_eq!(
            killed.take_robust_list_wakes_after_exit(None, DetTime::default()),
            None
        );

        assert_eq!(
            caller.robust_list_owners_for_exit_group(),
            vec![
                owner(3, 0x3000),
                owner(4, 0x4000),
                owner(6, 0x6000),
                owner(7, 0x7700)
            ]
        );
    }

    /// A thread an exit_group killed waits for that exit_group's walk before
    /// its native exit, including one that filed an exit_group of its own,
    /// whichever of two competing filings is granted; the walker does not
    /// wait, nor does a group with no filing.
    #[test]
    fn a_killed_thread_waits_for_the_exit_group_walk() {
        use std::sync::atomic::AtomicBool;
        use std::sync::atomic::Ordering;
        const BOUND: std::time::Duration = EXIT_GROUP_ROBUST_WALK_WAIT;

        for granted_first_filer in [true, false] {
            let first = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
            let mut second = first.clone();
            second.dettid = DetTid::from_raw(4);
            // Nothing filed: no wait.
            assert!(second.wait_for_exit_group_robust_walk(BOUND));

            first.file_exit_group_for_robust_lists();
            second.file_exit_group_for_robust_lists();
            let (walker, killed) = if granted_first_filer {
                (first, second)
            } else {
                (second, first)
            };
            walker.begin_exit_group_robust_walk();
            assert!(walker.wait_for_exit_group_robust_walk(BOUND));

            let released = Arc::new(AtomicBool::new(false));
            let entered = Arc::new(AtomicBool::new(false));
            let waiter = {
                let released = Arc::clone(&released);
                let entered = Arc::clone(&entered);
                std::thread::spawn(move || {
                    killed.cancel_exit_group_filing();
                    entered.store(true, Ordering::SeqCst);
                    let finished = killed.wait_for_exit_group_robust_walk(BOUND);
                    (finished, released.load(Ordering::SeqCst))
                })
            };
            // The killed thread is in the wait before the walk finishes, so the
            // check below is not passed by a waiter that started late (Claude
            // review of https://github.com/rrnewton/hermit/pull/4277, N6).
            while !entered.load(Ordering::SeqCst) {
                std::thread::yield_now();
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
            assert!(
                !waiter.is_finished(),
                "the killed filer did not wait for the walk"
            );
            released.store(true, Ordering::SeqCst);
            walker.finish_exit_group_robust_walk();
            assert_eq!(
                waiter.join().unwrap(),
                (true, true),
                "the killed filer went on before the walk finished (first filer granted: {granted_first_filer})"
            );
        }
    }

    /// A granted walk that has not finished keeps its killed threads waiting
    /// to the bound, which is reported, not taken as completion.
    #[test]
    fn an_unfinished_walk_is_never_released_by_the_bound() {
        let walker = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
        let mut killed = walker.clone();
        killed.dettid = DetTid::from_raw(4);
        walker.file_exit_group_for_robust_lists();
        walker.begin_exit_group_robust_walk();
        killed.cancel_exit_group_filing();
        assert!(!killed.wait_for_exit_group_robust_walk(std::time::Duration::from_millis(20)));
    }

    /// When every filing is cancelled by its filer's death and none was
    /// granted (an exec ended the group first), no walk will come, and the
    /// killed threads are released at once.
    #[test]
    fn a_wait_ends_when_every_filing_is_cancelled() {
        let filer = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
        let mut other = filer.clone();
        other.dettid = DetTid::from_raw(4);
        filer.file_exit_group_for_robust_lists();
        other.cancel_exit_group_filing();
        assert!(!other.wait_for_exit_group_robust_walk(std::time::Duration::from_millis(20)));
        filer.cancel_exit_group_filing();
        assert!(other.wait_for_exit_group_robust_walk(std::time::Duration::from_millis(20)));
    }

    /// Without a filed exit_group an exiting thread's head leaves the index.
    #[test]
    fn an_exit_drops_its_head_when_no_exit_group_is_filed() {
        let mut state = ThreadState::<()>::new(DetTid::from_raw(4), &Config::default(), ());
        state.record_robust_list_head(Some(0x4000));
        state.drop_robust_list_head_at_exit();
        assert!(state.robust_list_heads().is_empty());
        assert_eq!(state.robust_list_head, None);
    }

    /// A stale robust-list head must never survive into a new address space.
    /// `run_robust_list_owner_death` walks from whatever this field holds, so if
    /// `execve` left the old image's head here, thread exit would follow a wild
    /// pointer through the *new* image and write `FUTEX_OWNER_DIED` into
    /// whatever happened to sit at the computed word address.
    #[test]
    fn a_successful_exec_clears_the_robust_list_head() {
        let mut state = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
        assert_eq!(state.robust_list_head, None, "a fresh thread has no list");

        state.record_robust_list_head(Some(0x7ffff7bff920));
        assert_eq!(
            state.take_robust_list_for_exec(),
            Some(0x7ffff7bff920),
            "the previous head is handed back for the failure path"
        );
        assert_eq!(
            state.robust_list_head, None,
            "the candidate exec image starts with no robust list, as after copy_process"
        );
        assert!(
            state.robust_list_heads().is_empty(),
            "the old address-space registration must also leave the shared index"
        );
    }

    /// `execve` returns only on failure, and then the old address space -- and
    /// so the old head -- is still valid.
    #[test]
    fn a_failed_exec_restores_the_robust_list_head() {
        let mut state = ThreadState::<()>::new(DetTid::from_raw(3), &Config::default(), ());
        state.record_robust_list_head(Some(0x404100));

        let saved = state.take_robust_list_for_exec();
        state.restore_robust_list_after_failed_exec(saved);

        assert_eq!(state.robust_list_head, Some(0x404100));
        assert_eq!(
            state.robust_list_heads(),
            vec![(DetTid::from_raw(3), 0x404100)],
            "a failed exec keeps the old address-space registration indexed"
        );
    }

    fn two_owner_robust_list_state() -> (
        ThreadState<()>,
        ThreadState<()>,
        RobustListWake,
        RobustListWake,
        RobustListWake,
    ) {
        let first_owner = DetTid::from_raw(3);
        let second_owner = DetTid::from_raw(4);
        let mm = MmId::initial(first_owner);
        let lower = RobustListWake {
            futex: FutexID::private(mm, 0x4040),
        };
        let middle = RobustListWake {
            futex: FutexID::private(mm, 0x5050),
        };
        let higher = RobustListWake {
            futex: FutexID::private(mm, 0x6060),
        };
        let mut first = ThreadState::<()>::new(first_owner, &Config::default(), ());
        let mut second = first.clone();
        second.dettid = second_owner;
        first.record_robust_list_head(Some(0x404100));
        second.record_robust_list_head(Some(0x404200));
        first.stage_robust_list_wakes(
            RobustListExit::Signal(libc::SIGTERM),
            vec![
                (second_owner, vec![higher]),
                (first_owner, vec![middle, lower]),
            ],
        );
        (first, second, lower, middle, higher)
    }

    #[test]
    fn group_robust_list_wakes_wait_for_every_owner_and_sort_the_request() {
        let (first, second, lower, middle, higher) = two_owner_robust_list_state();
        let mut first_time = DetTime::default();
        first_time.add_syscall();
        let mut second_time = first_time.clone();
        second_time.add_syscall();

        assert_eq!(
            second.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), second_time.clone()),
            None,
            "the first physical exit must not release part of the group"
        );
        assert_eq!(
            first.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), first_time),
            Some((
                second_time,
                vec![
                    (DetTid::from_raw(3), lower),
                    (DetTid::from_raw(3), middle),
                    (DetTid::from_raw(4), higher),
                ],
            )),
            "the final matching exit releases one owner/futex-sorted request"
        );
    }

    #[test]
    fn group_robust_list_wake_request_is_independent_of_exit_arrival_order() {
        let release = |reverse: bool| {
            let (first, second, _, _, _) = two_owner_robust_list_state();
            let first_time = DetTime::default();
            let mut second_time = first_time.clone();
            second_time.add_syscall();
            if reverse {
                assert_eq!(
                    second.take_robust_list_wakes_after_exit(
                        Some(libc::SIGTERM),
                        second_time.clone(),
                    ),
                    None
                );
                first.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), first_time)
            } else {
                assert_eq!(
                    first.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), first_time),
                    None
                );
                second.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), second_time)
            }
        };

        assert_eq!(release(false), release(true));
    }

    #[test]
    fn mismatched_or_nonfatal_exit_does_not_release_group_robust_list_wakes() {
        let (first, second, _, _, _) = two_owner_robust_list_state();
        assert_eq!(
            first.take_robust_list_wakes_after_exit(Some(libc::SIGKILL), DetTime::default()),
            None
        );
        assert_eq!(
            second.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), DetTime::default()),
            None,
            "one matching owner cannot release a group whose peer exited for another reason"
        );

        let (first, second, _, _, _) = two_owner_robust_list_state();
        assert_eq!(
            first.take_robust_list_wakes_after_exit(None, DetTime::default()),
            None
        );
        assert_eq!(
            second.take_robust_list_wakes_after_exit(Some(libc::SIGTERM), DetTime::default()),
            None,
            "a normal exit must not satisfy a staged fatal-signal exit"
        );
    }

    #[test]
    fn regular_file_opens_do_not_shift_socket_cookie_identity() {
        let owner = DetTid::from_raw(3);
        let mut files = FileMetadata::new(owner);
        let first = files.allocate_open_file_id(owner, FdType::Socket);
        for _ in 0..4 {
            files.allocate_open_file_id(owner, FdType::Regular);
        }
        let second = files.allocate_open_file_id(owner, FdType::Socket);

        assert_eq!(first.deterministic_socket_cookie(), 3_u64 << 32);
        assert_eq!(second.deterministic_socket_cookie(), (3_u64 << 32) | 1);
    }

    #[test]
    fn guest_clock_tracks_raw_logical_time_without_lag() {
        let epoch = LogicalTime::from_secs(1_000);
        let mut clock = GuestClock::default();

        assert_eq!(
            clock.observe(epoch + Duration::from_nanos(41_000_000)),
            epoch + Duration::from_nanos(41_000_000)
        );
        assert_eq!(
            clock.observe(epoch + Duration::from_nanos(41_025_000)),
            epoch + Duration::from_nanos(41_025_000)
        );
        // A stale backend-local sample cannot move the process-tree clock back.
        assert_eq!(
            clock.observe(epoch + Duration::from_nanos(41_010_000)),
            epoch + Duration::from_nanos(41_025_000)
        );
    }

    #[test]
    fn guest_clock_absolute_deadline_stays_ahead_of_committed_time() {
        let committed_time = LogicalTime::from_secs(1_000) + Duration::from_millis(250);
        let mut clock = GuestClock::default();
        let guest_now = clock.observe(committed_time);
        let deadline = guest_now + Duration::from_millis(100);

        assert_eq!(guest_now, committed_time);
        assert!(deadline > committed_time);
    }

    #[test]
    fn guest_clock_process_tree_shares_one_monotonic_domain() {
        let epoch = LogicalTime::from_secs(1_000);
        let root = Arc::new(Mutex::new(GuestClock::default()));
        let forked_child = Arc::clone(&root);

        assert!(Arc::ptr_eq(&root, &forked_child));
        assert_eq!(
            root.lock().unwrap().observe(epoch + Duration::from_secs(1)),
            epoch + Duration::from_secs(1)
        );
        assert_eq!(
            forked_child
                .lock()
                .unwrap()
                .observe(epoch + Duration::from_secs(2)),
            epoch + Duration::from_secs(2)
        );

        // Exec retains the same clock object and does not rebase elapsed time.
        let execed_child = Arc::clone(&forked_child);
        assert!(Arc::ptr_eq(&root, &execed_child));
        assert_eq!(
            execed_child
                .lock()
                .unwrap()
                .observe(epoch + Duration::from_secs(9)),
            epoch + Duration::from_secs(9)
        );
    }

    #[test]
    fn unparented_thread_recovers_process_memory_identity() {
        let detpid = DetPid::from_raw(4);
        let dettid = DetTid::from_raw(7);
        let mut state = ThreadState::new(dettid, &Config::default(), ());

        assert!(state.recover_process_mm_id(detpid));
        assert_eq!(state.mm_id, MmId::initial(detpid));
        assert!(!state.recover_process_mm_id(detpid));
    }

    #[test]
    fn inherited_thread_keeps_existing_memory_identity() {
        let detpid = DetPid::from_raw(4);
        let dettid = DetTid::from_raw(7);
        let inherited_mm = MmId::initial(detpid).for_exec(detpid);
        let mut state = ThreadState::new(dettid, &Config::default(), ());
        state.mm_id = inherited_mm;

        assert!(!state.recover_process_mm_id(detpid));
        assert_eq!(state.mm_id, inherited_mm);
    }

    #[test]
    fn backend_can_override_open_file_creator_identity() {
        let host_tid = DetTid::from_raw(10_003);
        let virtual_tid = DetTid::from_raw(3);
        let mut state = ThreadState::new(host_tid, &Config::default(), ());

        assert_eq!(state.open_file_creator, None);
        state.set_open_file_creator(virtual_tid);
        assert_eq!(state.open_file_creator, Some(virtual_tid));
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1149)
    #[test]
    fn chaos_per_thread_slowdown_factor_is_stable_and_deterministic() {
        let seed = 0xdead_beef_u64;
        let max_factor: f64 = 10.0;
        // Deterministic: same (seed, dettid) -> identical factor, every call.
        for raw in 1..=64 {
            let tid = DetTid::from_raw(raw);
            let a = chaos_per_thread_slowdown_factor(seed, tid, 0, max_factor);
            let b = chaos_per_thread_slowdown_factor(seed, tid, 0, max_factor);
            assert_eq!(
                a, b,
                "factor must be a pure function of (seed, dettid, epoch)"
            );
            // Log-uniform in [1/R, R].
            let a = a.as_f64();
            assert!(
                a >= 1.0 / max_factor - 1e-9 && a <= max_factor + 1e-9,
                "factor {} out of [1/{max_factor}, {max_factor}] for tid {raw}",
                a
            );
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1149)
    #[test]
    fn chaos_per_thread_slowdown_factor_varies_across_threads_and_seeds() {
        let max_factor = 10.0;
        // Different threads (same seed) get a spread of factors, not all equal.
        let factors: Vec<f64> = (1..=32)
            .map(|raw| {
                chaos_per_thread_slowdown_factor(1234, DetTid::from_raw(raw), 0, max_factor)
                    .as_f64()
            })
            .collect();
        let first = factors[0];
        assert!(
            factors.iter().any(|&f| (f - first).abs() > 1e-6),
            "per-thread factors should differ across threads"
        );
        // Different seeds give a different factor for the same thread.
        let tid = DetTid::from_raw(7);
        let f_a = chaos_per_thread_slowdown_factor(1, tid, 0, max_factor).as_f64();
        let f_b = chaos_per_thread_slowdown_factor(2, tid, 0, max_factor).as_f64();
        assert!(
            (f_a - f_b).abs() > 1e-12,
            "different seeds should yield different factors for the same thread"
        );
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1149)
    #[test]
    fn chaos_per_thread_slowdown_factor_disabled_when_max_factor_at_most_one() {
        // max_factor <= 1.0 disables the spread: every thread is nominal (1.0).
        for raw in 1..=16 {
            let tid = DetTid::from_raw(raw);
            assert_eq!(
                chaos_per_thread_slowdown_factor(99, tid, 0, 1.0),
                RcbTimeMultiplier::ONE
            );
            assert_eq!(
                chaos_per_thread_slowdown_factor(99, tid, 0, 0.5),
                RcbTimeMultiplier::ONE
            );
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn chaos_epoch_zero_reproduces_epochless_factor() {
        // Enabling epochs must never perturb the FIRST epoch: epoch 0 has to
        // yield exactly the value the epoch-less #1149 code produced (the epoch
        // term folds to 0 in the mix).
        use rand::RngExt as _;
        use rand::SeedableRng as _;
        let max_factor: f64 = 10.0;
        for raw in 1..=64 {
            let tid = DetTid::from_raw(raw);
            for &seed in &[0u64, 1, 7, 0xdead_beef, u64::MAX] {
                let epochless = {
                    // Reconstruct the exact epoch-less mix inline to pin the
                    // invariant independent of the production function body.
                    const SLOWDOWN_SALT: u64 = 0x736c_6f77_646f_776e;
                    let mixed = seed
                        ^ SLOWDOWN_SALT
                        ^ ((tid.as_raw() as u32 as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15));
                    let mut prng = Pcg64Mcg::seed_from_u64(mixed);
                    let u: f64 = prng.random::<f64>();
                    max_factor.powf(2.0 * u - 1.0)
                };
                assert_eq!(
                    chaos_per_thread_slowdown_factor(seed, tid, 0, max_factor),
                    RcbTimeMultiplier::from_f64(epochless),
                    "epoch 0 must reproduce the epoch-less factor for seed {seed}, tid {raw}"
                );
            }
        }
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn chaos_epoch_factor_varies_deterministically_across_epochs() {
        let max_factor = 10.0;
        let seed = 0x1234_5678_u64;
        let tid = DetTid::from_raw(3);
        // Each epoch draws a fresh factor for the same thread; the sequence is
        // a pure function of (seed, dettid, epoch), hence replayable.
        let factors: Vec<f64> = (0..16)
            .map(|epoch| chaos_per_thread_slowdown_factor(seed, tid, epoch, max_factor).as_f64())
            .collect();
        // Purity: recomputing any epoch yields the identical value.
        for (epoch, &f) in factors.iter().enumerate() {
            assert_eq!(
                chaos_per_thread_slowdown_factor(seed, tid, epoch as u64, max_factor).as_f64(),
                f,
                "factor must be pure in epoch"
            );
            // Stays in the log-uniform range.
            assert!(f >= 1.0 / max_factor - 1e-9 && f <= max_factor + 1e-9);
        }
        // The factor actually changes across epochs (not a constant stream).
        let first = factors[0];
        assert!(
            factors.iter().any(|&f| (f - first).abs() > 1e-6),
            "per-epoch factors should differ across epochs"
        );
    }

    fn cpu_snapshot(
        user: u64,
        system: u64,
        children_user: u64,
        children_system: u64,
    ) -> ProcessCpuSnapshot {
        ProcessCpuSnapshot {
            user: LogicalTime::from_nanos(user),
            system: LogicalTime::from_nanos(system),
            children_user: LogicalTime::from_nanos(children_user),
            children_system: LogicalTime::from_nanos(children_system),
        }
    }

    #[test]
    fn child_cpu_time_is_hidden_until_reap() {
        let pid = DetPid::from_raw(2);
        let mut parent = ProcessCpuTime::default();
        parent.record_exited_child(pid, cpu_snapshot(10, 20, 3, 4));

        assert_eq!(parent.snapshot.children_user, LogicalTime::ZERO);
        assert_eq!(parent.snapshot.children_system, LogicalTime::ZERO);

        parent.reap_child(pid);
        assert_eq!(parent.snapshot.children_user, LogicalTime::from_nanos(13));
        assert_eq!(parent.snapshot.children_system, LogicalTime::from_nanos(24));
    }

    #[test]
    fn reaping_nonexited_child_does_not_change_accounting() {
        let pid = DetPid::from_raw(2);
        let mut parent = ProcessCpuTime::default();

        parent.reap_child(pid);
        assert_eq!(parent.snapshot.children_user, LogicalTime::ZERO);
        assert_eq!(parent.snapshot.children_system, LogicalTime::ZERO);
    }

    #[test]
    fn child_cpu_time_uses_final_thread_snapshot_and_drops_reaped_state() {
        let pid = DetPid::from_raw(2);
        let mut parent = ProcessCpuTime::default();

        parent.record_exited_child(pid, cpu_snapshot(10, 20, 3, 4));
        parent.record_exited_child(pid, cpu_snapshot(12, 25, 4, 5));

        parent.reap_child(pid);
        assert_eq!(parent.snapshot.children_user, LogicalTime::from_nanos(16));
        assert_eq!(parent.snapshot.children_system, LogicalTime::from_nanos(30));
        assert!(parent.exited_children.is_empty());

        parent.reap_child(pid);
        assert_eq!(parent.snapshot.children_user, LogicalTime::from_nanos(16));
        assert_eq!(parent.snapshot.children_system, LogicalTime::from_nanos(30));
    }

    #[tokio::test]
    async fn child_cpu_publication_replacement_rejects_stale_owner_and_snapshot() {
        use std::future::Future;
        use std::task::Context;

        let cfg = Config::default();
        let child = DetPid::from_raw(7);
        let mut parent = ThreadState::new(DetPid::from_raw(3), &cfg, ());
        assert!(!parent.wait_for_child_cpu_publication(child).await);
        let before = serde_json::to_value(&*parent.process_cpu_time.lock().unwrap()).unwrap();
        let first = parent.prepare_child_cpu_publication(child);
        let mut old_child = ThreadState::new(child, &cfg, ());
        old_child.parent_process_cpu_time = Some(Arc::clone(&parent.process_cpu_time));
        old_child.parent_cpu_publication = Some(Arc::clone(&first));
        let mut old_wait = Box::pin(parent.wait_for_child_cpu_publication(child));
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        assert!(old_wait.as_mut().poll(&mut cx).is_pending());
        let second = parent.prepare_child_cpu_publication(child);
        assert!(!Arc::ptr_eq(&first, &second));
        assert!(!old_wait.await);
        assert!(!old_child.record_exited_child_process_cpu_time(child));
        assert!(!parent.has_exited_child_process_cpu_time(child));
        // Neither runtime notification state nor host wakers enter recordings.
        {
            let cpu = parent.process_cpu_time.lock().unwrap();
            assert_eq!(serde_json::to_value(&*cpu).unwrap(), before);
            let clone = cpu.clone();
            assert!(Arc::ptr_eq(
                clone.child_cpu_publications.get(&child).unwrap(),
                &second
            ));
            let restored: ProcessCpuTime = serde_json::from_value(before).unwrap();
            assert!(restored.child_cpu_publications.is_empty());
        }

        let mut current_child = ThreadState::new(child, &cfg, ());
        current_child.parent_process_cpu_time = Some(Arc::clone(&parent.process_cpu_time));
        current_child.parent_cpu_publication = Some(Arc::clone(&second));
        assert!(current_child.record_exited_child_process_cpu_time(child));
        parent.prepare_child_process_cpu_time(child);
        assert!(parent.has_exited_child_process_cpu_time(child));
        assert!(parent.wait_for_child_cpu_publication(child).await);
        // ThreadState clones retain the same process identity.
        assert!(Arc::ptr_eq(
            current_child
                .clone()
                .parent_cpu_publication
                .as_ref()
                .unwrap(),
            &second
        ));
        parent.reap_child_process_cpu_time(child);
        assert!(!parent.wait_for_child_cpu_publication(child).await);
        assert!(!current_child.record_exited_child_process_cpu_time(child));
        assert!(!parent.has_exited_child_process_cpu_time(child));
    }

    fn nz(value: u64) -> Option<NonZeroU64> {
        NonZeroU64::new(value)
    }

    /// The cap of hermit#4121 only lowers the software slice end, keeps one
    /// RCB of room (10 ns at the default clock) plus one nanosecond, and
    /// leaves the PMU maximum alone.
    #[test]
    fn a_deadline_cap_lowers_the_slice_end_and_keeps_one_rcb() {
        let config = Config {
            max_timeslice: nz(200_000_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        state.next_timeslice(&config);
        let now = state.thread_logical_time.as_nanos();
        let end = state.end_of_timeslice.unwrap();
        assert_eq!(end, now + Duration::from_nanos(200_000_000));
        assert_eq!(state.max_timeslice_end, Some(end));

        state.cap_timeslice_at_deadline(
            Duration::from_nanos(5_000_000),
            1.0,
            Duration::ZERO,
            false,
        );
        let capped = now + Duration::from_nanos(5_000_000);
        assert_eq!(state.end_of_timeslice, Some(capped));
        assert_eq!(state.max_timeslice_end, Some(end));

        // A later deadline never raises the end.
        state.cap_timeslice_at_deadline(
            Duration::from_nanos(9_000_000),
            1.0,
            Duration::ZERO,
            false,
        );
        assert_eq!(state.end_of_timeslice, Some(capped));

        // A deadline already due leaves one RCB and a nanosecond.
        state.cap_timeslice_at_deadline(Duration::ZERO, 1.0, Duration::ZERO, false);
        assert_eq!(state.end_of_timeslice, Some(now + Duration::from_nanos(11)));
        assert_eq!(state.max_timeslice_end, Some(end));
    }

    /// The cap never ends a slice sooner than one scheduler turn charge
    /// (`min_slice`) after it is applied, so the turn it causes costs no more
    /// virtual time than the work the thread did.
    #[test]
    fn a_deadline_cap_keeps_at_least_one_turn_charge() {
        let config = Config {
            max_timeslice: nz(200_000_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        state.next_timeslice(&config);
        let now = state.thread_logical_time.as_nanos();
        let turn = Duration::from_nanos(500_000);
        state.cap_timeslice_at_deadline(Duration::from_nanos(1_000), 1.0, turn, false);
        assert_eq!(state.end_of_timeslice, Some(now + turn));
        state.cap_timeslice_at_deadline(Duration::ZERO, 1.0, turn, false);
        assert_eq!(state.end_of_timeslice, Some(now + turn));
        state.cap_timeslice_at_deadline(Duration::from_nanos(700_000), 1.0, turn, false);
        assert_eq!(state.end_of_timeslice, Some(now + turn));
    }

    /// Schedule replay follows its recorded turns: the cap leaves its slices
    /// alone.
    #[test]
    fn schedule_replay_takes_no_deadline_cap() {
        let config = Config {
            max_timeslice: nz(200_000_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        state.next_timeslice(&config);
        let end = state.end_of_timeslice;
        state.cap_timeslice_at_deadline(Duration::from_nanos(5_000), 1.0, Duration::ZERO, true);
        assert_eq!(state.end_of_timeslice, end);
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn constant_slowdown_is_the_single_epoch_case() {
        let config = Config {
            chaos: true,
            chaos_per_thread_slowdown: true,
            chaos_epoch_length_ns: 0,
            target_timeslice: nz(10_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        state.next_timeslice(&config);
        let first = state.take_pending_chaos_epochs().pop().unwrap();
        assert_eq!(first.epoch, 0);
        assert_eq!(state.chaos_epoch, 0);

        state
            .thread_logical_time
            .add_rcbs_with_multiplier(10_000, first.factor);
        state.next_timeslice(&config);
        assert_eq!(state.chaos_epoch, 0);
        assert_eq!(state.chaos_slowdown_factor, first.factor);
        assert!(state.take_pending_chaos_epochs().is_empty());
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn epoch_redraw_uses_elapsed_logical_time_at_commit_boundaries() {
        let config = Config {
            chaos: true,
            chaos_per_thread_slowdown: true,
            chaos_epoch_length_ns: 100,
            target_timeslice: nz(10_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let tid = DetPid::from_raw(5);
        let mut state = ThreadState::new(tid, &config, ());
        state.next_timeslice(&config);
        let first = state.pending_chaos_epochs[0];

        state
            .thread_logical_time
            .add_rcbs_with_multiplier(1_000, first.factor);
        let expected_epoch =
            state.thread_logical_time.without_starting().as_nanos() / config.chaos_epoch_length_ns;
        assert!(expected_epoch > 0);

        state.next_timeslice(&config);
        let transitions = state.take_pending_chaos_epochs();
        assert_eq!(transitions.len(), 2);
        assert_eq!(transitions[0], first);
        let redraw = transitions[1];
        assert_eq!(redraw.epoch, expected_epoch);
        assert_eq!(
            redraw.factor,
            chaos_per_thread_slowdown_factor(
                config.sched_seed(),
                tid,
                expected_epoch,
                config.chaos_slowdown_max_factor,
            )
        );
        assert!(redraw.logical_time > first.logical_time);
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn replay_installs_recorded_epoch_without_ambient_chaos_flags() {
        let config = Config {
            target_timeslice: nz(10_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let transition = ChaosEpochTransition {
            logical_time: LogicalTime::ZERO,
            epoch: 7,
            factor: RcbTimeMultiplier::from_f64(3.25),
        };
        let mut state = ThreadState::new(DetPid::from_raw(5), &config, ());
        state.preemption_points = Some(
            ThreadHistory::new()
                .with_chaos_epochs(vec![transition])
                .into_iter(),
        );

        state.next_timeslice(&config);

        assert!(state.chaos_slowdown_active);
        assert_eq!(state.chaos_epoch, transition.epoch);
        assert_eq!(state.chaos_slowdown_factor, transition.factor);
        assert!(state.take_pending_chaos_epochs().is_empty());
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn replay_installs_boundary_epoch_when_pmu_checks_in_early() {
        let config = Config {
            target_timeslice: nz(10_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(5), &config, ());
        let now = state.thread_logical_time.as_nanos();
        let first = ChaosEpochTransition {
            logical_time: now,
            epoch: 0,
            factor: RcbTimeMultiplier::from_f64(2.0),
        };
        let second = ChaosEpochTransition {
            logical_time: now + Duration::from_nanos(100),
            epoch: 1,
            factor: RcbTimeMultiplier::from_f64(3.0),
        };
        let history = ThreadHistory::new()
            .with_prio_changes(vec![
                (now + Duration::from_nanos(100), DEFAULT_PRIORITY),
                (now + Duration::from_nanos(200), DEFAULT_PRIORITY),
            ])
            .with_preemption_rcbs(vec![4, 8])
            .with_chaos_epochs(vec![first, second]);
        state.preemption_points = Some(history.into_iter());

        state.next_timeslice(&config);
        assert_eq!(state.chaos_slowdown_factor, first.factor);
        assert_eq!(
            state.end_of_timeslice,
            Some(now + Duration::from_nanos(100))
        );

        // Four 2x RCBs advance to 80ns: within one RCB of the exact 100ns
        // boundary, matching the early check-in path in post_handler_hook.
        state
            .thread_logical_time
            .add_rcbs_with_multiplier(4, first.factor);
        state.committed_clock_value = 4;
        assert!(state.timeslice_expired());
        state.next_timeslice(&config);

        assert_eq!(
            state.thread_logical_time.as_nanos(),
            now + Duration::from_nanos(80)
        );
        assert_eq!(state.chaos_epoch, second.epoch);
        assert_eq!(state.chaos_slowdown_factor, second.factor);
        assert_eq!(
            state.end_of_timeslice,
            Some(now + Duration::from_nanos(200))
        );
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(PR-1151)
    #[test]
    fn replay_preserves_adjacent_zero_rcb_slices() {
        let config = Config {
            target_timeslice: nz(10_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(5), &config, ());
        let now = state.thread_logical_time.as_nanos();
        let history = ThreadHistory::new()
            .with_prio_changes(vec![
                (now + Duration::from_nanos(70), DEFAULT_PRIORITY),
                (now + Duration::from_nanos(80), DEFAULT_PRIORITY),
            ])
            .with_preemption_rcbs(vec![4, 4]);
        state.preemption_points = Some(history.into_iter());

        state.next_timeslice(&config);
        state.thread_logical_time.add_rcbs(4);
        state.committed_clock_value = 4;
        assert!(state.timeslice_expired());

        state.next_timeslice(&config);
        assert_eq!(state.replay_rcb_end, Some(4));
        assert!(state.timeslice_expired());
    }

    #[test]
    fn target_and_pmu_deadlines_are_independent() {
        let config = Config {
            target_timeslice: nz(20_000),
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();

        state.next_timeslice(&config);

        assert_eq!(
            state.end_of_timeslice,
            Some(now + Duration::from_nanos(20_000))
        );
        assert_eq!(
            state.max_timeslice_end,
            Some(now + Duration::from_nanos(100_000))
        );
    }

    #[test]
    fn target_only_mode_does_not_create_a_pmu_deadline() {
        let config = Config {
            target_timeslice: nz(20_000),
            max_timeslice: None,
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();

        state.next_timeslice(&config);

        assert_eq!(
            state.end_of_timeslice,
            Some(now + Duration::from_nanos(20_000))
        );
        assert_eq!(state.max_timeslice_end, None);
    }

    #[test]
    fn max_timeslice_caps_a_larger_target() {
        let config = Config {
            target_timeslice: nz(100_000),
            max_timeslice: nz(20_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();

        state.next_timeslice(&config);

        let max_end = now + Duration::from_nanos(20_000);
        assert_eq!(state.end_of_timeslice, Some(max_end));
        assert_eq!(state.max_timeslice_end, Some(max_end));
    }

    #[test]
    fn chaos_without_target_caps_randomized_deadline_at_maximum() {
        let config = Config {
            chaos: true,
            target_timeslice: None,
            max_timeslice: nz(100_000),
            clock_multiplier: Some(1.05),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();
        let configured_max = now + Duration::from_nanos(100_000);
        let minimum_progress = now + Duration::from_nanos(11);

        state.next_timeslice(&config);

        assert_eq!(state.max_timeslice_end, state.end_of_timeslice);
        assert!(state.max_timeslice_end.unwrap() <= configured_max);
        assert!(state.max_timeslice_end.unwrap() >= minimum_progress);
    }

    #[test]
    fn schedule_replay_without_rcb_time_arms_pmu_maximum() {
        let config = Config {
            no_rcb_time: true,
            max_timeslice: nz(100_000),
            replay_schedule_from: Some(std::path::PathBuf::from("schedule.json")),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();

        state.next_timeslice(&config);

        let expected = now + Duration::from_nanos(100_000);
        assert_eq!(state.end_of_timeslice, Some(expected));
        assert_eq!(state.max_timeslice_end, Some(expected));
    }

    #[test]
    fn exhausted_preemption_replay_uses_bounded_pmu_maximum() {
        let config = Config {
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        state.preemption_points = Some(ThreadHistory::new().into_iter());
        let now = state.thread_logical_time.as_nanos();

        state.next_timeslice(&config);

        let bounded_end = Some(now + Duration::from_nanos(100_000));
        assert_eq!(state.end_of_timeslice, bounded_end);
        assert_eq!(state.max_timeslice_end, bounded_end);
    }

    /// A preemption replay keeps a recorded slice end uncapped. Once the
    /// recording runs out its slice end is `LogicalTime::MAX`, which the cap
    /// may lower.
    #[test]
    fn preemption_replay_caps_only_past_its_recording() {
        let config = Config {
            max_timeslice: nz(100_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(3), &config, ());
        let now = state.thread_logical_time.as_nanos();
        let recorded_end = now + Duration::from_nanos(50_000);
        let history = ThreadHistory::new()
            .with_prio_changes(vec![(recorded_end, DEFAULT_PRIORITY)])
            .with_preemption_rcbs(vec![5_000]);
        state.preemption_points = Some(history.into_iter());

        state.next_timeslice(&config);
        assert_eq!(state.end_of_timeslice, Some(recorded_end));
        state.cap_timeslice_at_deadline(Duration::from_nanos(1_000), 1.0, Duration::ZERO, false);
        assert_eq!(state.end_of_timeslice, Some(recorded_end));

        let mut exhausted = ThreadState::new(DetPid::from_raw(3), &config, ());
        exhausted.preemption_points = Some(ThreadHistory::new().into_iter());
        exhausted.next_timeslice(&config);
        exhausted.cap_timeslice_at_deadline(
            Duration::from_nanos(1_000),
            1.0,
            Duration::ZERO,
            false,
        );
        let capped = Some(now + Duration::from_nanos(1_000));
        assert_eq!(exhausted.end_of_timeslice, capped);
        assert_eq!(
            exhausted.max_timeslice_end,
            Some(now + Duration::from_nanos(100_000))
        );
    }

    #[test]
    fn timeslice_expiry_is_inclusive() {
        let config = Config::default();
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        let now = state.thread_logical_time.as_nanos();

        state.end_of_timeslice = Some(now + Duration::from_nanos(1));
        assert!(!state.timeslice_expired());
        state.end_of_timeslice = Some(now);
        assert!(state.timeslice_expired());
    }

    #[test]
    fn instruction_trap_ends_an_expired_target_only_at_the_pmu_maximum() {
        let config = Config {
            target_timeslice: nz(1_000),
            target_timeslice_syscalls_only: true,
            max_timeslice: nz(20_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        state.next_timeslice(&config);

        // Past the target: a syscall would end the slice, an rdtsc must not.
        state.thread_logical_time.add_rcbs(500);
        assert!(state.timeslice_expired());
        assert!(!state.instruction_trap_ends_timeslice(&config));

        // At the PMU maximum the trap ends it, as a branch would.
        state.thread_logical_time.add_rcbs(1_500);
        assert!(state.instruction_trap_ends_timeslice(&config));
    }

    #[test]
    fn instruction_trap_ends_an_expired_target_by_default() {
        let config = Config {
            target_timeslice: nz(1_000),
            max_timeslice: nz(20_000),
            ..Default::default()
        };
        assert!(!config.target_timeslice_syscalls_only);
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        state.next_timeslice(&config);
        state.thread_logical_time.add_rcbs(99);
        assert!(!state.instruction_trap_ends_timeslice(&config));
        state.thread_logical_time.add_rcbs(1);
        assert!(state.instruction_trap_ends_timeslice(&config));
    }

    #[test]
    fn instruction_trap_ends_an_expired_target_without_a_pmu_maximum() {
        // With PMU preemption disabled nothing else can break a busy-wait on
        // the TSC, so the trap keeps ending the expired target.
        let config = Config {
            target_timeslice: nz(1_000),
            target_timeslice_syscalls_only: true,
            max_timeslice: None,
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &config, ());
        state.next_timeslice(&config);
        assert_eq!(state.max_timeslice_end, None);

        // 1,000 ns is 100 RCBs at the default 10 ns per RCB.
        state.thread_logical_time.add_rcbs(99);
        assert!(!state.instruction_trap_ends_timeslice(&config));
        state.thread_logical_time.add_rcbs(1);
        assert!(state.instruction_trap_ends_timeslice(&config));
    }

    #[test]
    fn instruction_trap_keeps_replayed_and_untargeted_boundaries() {
        // Without a target the slice end is the PMU maximum itself, and a
        // replayed preemption record keeps its recorded boundaries: in both
        // cases a trap ends exactly the slices it ended before.
        let untargeted = Config {
            max_timeslice: nz(20_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &untargeted, ());
        state.next_timeslice(&untargeted);
        state.thread_logical_time.add_rcbs(1_999);
        assert_eq!(
            state.instruction_trap_ends_timeslice(&untargeted),
            state.timeslice_expired()
        );
        state.thread_logical_time.add_rcbs(1);
        assert!(state.instruction_trap_ends_timeslice(&untargeted));

        let targeted = Config {
            target_timeslice: nz(1_000),
            target_timeslice_syscalls_only: true,
            max_timeslice: nz(20_000),
            ..Default::default()
        };
        let mut state = ThreadState::new(DetPid::from_raw(1), &targeted, ());
        state.next_timeslice(&targeted);
        state.preemption_points = Some(ThreadHistory::new().into_iter());
        state.thread_logical_time.add_rcbs(500);
        assert!(state.timeslice_expired());
        assert!(state.instruction_trap_ends_timeslice(&targeted));
    }

    #[test]
    fn child_rng_distinguishes_adjacent_thread_ids() {
        let parent = Pcg64Mcg::seed_from_u64(0);
        let mut even = thread_rng_from_parent("test", &parent, DetTid::from_raw(8));
        let mut odd = thread_rng_from_parent("test", &parent, DetTid::from_raw(9));

        let even_values: [u64; 4] = std::array::from_fn(|_| even.next_u64());
        let odd_values: [u64; 4] = std::array::from_fn(|_| odd.next_u64());
        assert_ne!(even_values, odd_values);
    }

    #[test]
    fn child_rng_uses_high_entropy_bits() {
        let parent = Pcg64Mcg::seed_from_u64(0);
        let mut low = thread_rng_from_parent_entropy("test", &parent, 1);
        let mut high = thread_rng_from_parent_entropy("test", &parent, (1_u128 << 64) | 1);

        let low_values: [u64; 4] = std::array::from_fn(|_| low.next_u64());
        let high_values: [u64; 4] = std::array::from_fn(|_| high.next_u64());
        assert_ne!(low_values, high_values);
    }

    #[test]
    fn child_rng_pedigree_uses_the_full_unbounded_path() {
        let parent_rng = Pcg64Mcg::seed_from_u64(0);
        let mut long_path = Pedigree::new();
        for index in 0..2_048 {
            let (parent, child) = long_path.fork();
            long_path = if index % 2 == 0 { child } else { parent };
        }
        let (left, right) = long_path.fork();
        let mut left_rng =
            thread_rng_from_parent_pedigree("test", &parent_rng, &left, ChildRngStream::User);
        let mut right_rng =
            thread_rng_from_parent_pedigree("test", &parent_rng, &right, ChildRngStream::User);

        let left_values: [u64; 4] = std::array::from_fn(|_| left_rng.next_u64());
        let right_values: [u64; 4] = std::array::from_fn(|_| right_rng.next_u64());
        assert_ne!(left_values, right_values);
    }

    #[test]
    fn child_rng_pedigree_separates_user_and_chaos_streams() {
        let parent_rng = Pcg64Mcg::seed_from_u64(0);
        let (_, child) = Pedigree::new().fork();
        let mut user_rng = thread_rng_from_parent_pedigree(
            "same logging label",
            &parent_rng,
            &child,
            ChildRngStream::User,
        );
        let mut chaos_rng = thread_rng_from_parent_pedigree(
            "same logging label",
            &parent_rng,
            &child,
            ChildRngStream::Chaos,
        );

        let user_values: [u64; 4] = std::array::from_fn(|_| user_rng.next_u64());
        let chaos_values: [u64; 4] = std::array::from_fn(|_| chaos_rng.next_u64());
        assert_ne!(user_values, chaos_values);
    }
}

/// Generate a new thread-local PRNG from the parent's PRNG state, mixing in the
/// new DetTid for some deterministic entropy. This ensures sequentially-spawned
/// threads get distinct PRNG states.
// TODO-HUMAN-REVIEW(PR-1052): Review collision-free child-thread PRNG seeding.
pub fn thread_rng_from_parent(msg: &str, parent: &Pcg64Mcg, child: DetTid) -> Pcg64Mcg {
    thread_rng_from_parent_entropy_labeled(msg, parent, child.as_raw() as u32 as u128, "tid")
}

#[derive(Clone, Copy, Debug)]
pub(crate) enum ChildRngStream {
    User,
    Chaos,
}

impl ChildRngStream {
    fn domain(self) -> &'static [u8] {
        match self {
            Self::User => b"user",
            Self::Chaos => b"chaos",
        }
    }
}

// TODO-HUMAN-REVIEW(PR-1052): Review pedigree-derived child-thread PRNG seeding.
pub(crate) fn thread_rng_from_parent_pedigree(
    msg: &str,
    parent: &Pcg64Mcg,
    child: &Pedigree,
    stream: ChildRngStream,
) -> Pcg64Mcg {
    let bits = child.raw();
    let mut packed = Vec::with_capacity(bits.len().div_ceil(8));
    let mut byte = 0_u8;
    for (index, bit) in bits.iter().enumerate() {
        if *bit {
            byte |= 1 << (index % 8);
        }
        if index % 8 == 7 {
            packed.push(byte);
            byte = 0;
        }
    }
    if !bits.len().is_multiple_of(8) {
        packed.push(byte);
    }

    // Pedigrees are unbounded, while Pcg64Mcg has a 128-bit state. Hash the
    // complete, length-delimited path instead of using the fallible compressed
    // virtual-PID encoding, so child RNG identity has no artificial tree-depth
    // boundary. The domain string prevents this digest from being confused
    // with another future use of the same pedigree serialization. Pcg64Mcg
    // forces its low state bit, so this retains 127 effective digest bits.
    let mut hasher = Sha256::new();
    hasher.update(b"hermit-child-rng-pedigree-v1\0");
    hasher.update(stream.domain());
    hasher.update([0]);
    hasher.update((bits.len() as u64).to_le_bytes());
    hasher.update(&packed);
    let digest = hasher.finalize();

    let mut seed = <Pcg64Mcg as SeedableRng>::Seed::default();
    parent.clone().fill_bytes(seed.as_mut());
    for (seed_byte, pedigree_byte) in seed.iter_mut().zip(digest) {
        *seed_byte ^= pedigree_byte;
    }
    detlog!(
        "RNG {} seeding child {:?} pedigree {}: {:?} from parent {:?}",
        msg,
        stream,
        child,
        seed,
        parent
    );
    let mut rng = Pcg64Mcg::from_seed(seed);
    rng.next_u64();
    rng.next_u64();
    rng.next_u64();
    rng.next_u64();
    rng
}

#[cfg(test)]
mod native_exec_cut_tests {
    use super::*;
    use crate::native_exec::NativeExecCutError;
    use crate::native_exec::capture_prepared_native_exec;
    use crate::native_exec::tests::fixture;
    use crate::native_exec::tests::prepare;
    use crate::native_exec::tests::state_bytes;
    use crate::native_exec::validate_old_native_exec_cut;

    #[test]
    fn native_exec_child_publications_refuse_every_runtime_token_state() {
        for completion in [None, Some(true), Some(false)] {
            let (tool, thread, binding) = fixture();
            let before = state_bytes(&thread);
            let child = DetPid::from_raw(43);
            let token = thread.prepare_child_cpu_publication(child);
            if let Some(published) = completion {
                token.finish(published);
            }
            // The map is genuinely invisible to serde in all three states.
            assert_eq!(state_bytes(&thread), before);
            assert!(matches!(
                validate_old_native_exec_cut(&tool, &thread, &binding),
                Err(NativeExecCutError::LiveCapability("child_cpu_publications"))
            ));
            assert!(Arc::ptr_eq(
                thread
                    .process_cpu_time
                    .lock()
                    .unwrap()
                    .child_cpu_publications
                    .get(&child)
                    .unwrap(),
                &token
            ));
        }
    }

    #[test]
    fn native_exec_historical_cpu_accounting_survives_without_live_publications() {
        let (tool, mut thread, binding) = fixture();
        {
            let mut cpu = thread.process_cpu_time.lock().unwrap();
            cpu.add_thread_delta(LogicalTime::from_nanos(17), LogicalTime::from_nanos(31));
            cpu.record_exited_child(
                DetPid::from_raw(43),
                ProcessCpuSnapshot {
                    user: LogicalTime::from_nanos(19),
                    system: LogicalTime::from_nanos(23),
                    children_user: LogicalTime::from_nanos(29),
                    children_system: LogicalTime::from_nanos(37),
                },
            );
            cpu.reap_child(DetPid::from_raw(43));
            cpu.record_exited_child(
                DetPid::from_raw(44),
                ProcessCpuSnapshot {
                    user: LogicalTime::from_nanos(41),
                    system: LogicalTime::from_nanos(47),
                    ..ProcessCpuSnapshot::default()
                },
            );
        }
        let before = serde_json::to_value(&*thread.process_cpu_time.lock().unwrap()).unwrap();
        let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
        prepare(&mut thread, &binding);
        let bytes = bincode::serde::encode_to_vec(
            capture_prepared_native_exec(&tool, &thread, &binding, &receipt).unwrap(),
            bincode::config::legacy(),
        )
        .unwrap();
        let (payload, used): (crate::native_exec::DetcoreExecSnapshotV2, _) =
            bincode::serde::decode_from_slice(&bytes, bincode::config::legacy()).unwrap();
        assert_eq!(used, bytes.len());
        let (_, restored) = payload.into_validated_parts(&binding, &tool.cfg).unwrap();
        assert_eq!(
            serde_json::to_value(&*restored.process_cpu_time.lock().unwrap()).unwrap(),
            before
        );
        let cpu = restored.process_cpu_time.lock().unwrap();
        assert_eq!(cpu.snapshot.children_user, LogicalTime::from_nanos(48));
        assert_eq!(cpu.snapshot.children_system, LogicalTime::from_nanos(60));
        assert_eq!(cpu.exited_children.len(), 1);
        assert!(cpu.child_cpu_publications.is_empty());
    }

    #[test]
    fn native_exec_old_accept_waits_and_invalid_table_slots_refuse() {
        let (tool, thread, binding) = fixture();
        let operation = {
            let mut table = thread.file_metadata.lock().unwrap();
            table
                .add_fd(binding.dettid, 33, OFlag::O_CLOEXEC, FdType::Socket, None)
                .unwrap();
            table.add_accept_wait(33)
        };
        assert!(matches!(
            validate_old_native_exec_cut(&tool, &thread, &binding),
            Err(NativeExecCutError::LiveCapability("accept_waits"))
        ));
        let mut table = thread.file_metadata.lock().unwrap();
        assert!(table.for_exec(binding.dettid).accept_waits.is_empty());
        assert_eq!(table.accept_waits, [(operation, 33)]);
        table.remove_accept_wait(operation);
        // An old operation counter is historical, but the existing prepared
        // table has a fresh counter. Neither validation path resets it.
        assert_eq!(table.next_accept_wait, operation + 1);
        table
            .validate_native_exec_cut(binding.old_files, false)
            .unwrap();
        let mut prepared = table.for_exec(binding.dettid);
        prepared
            .validate_native_exec_cut(binding.prepared_files(), true)
            .unwrap();
        prepared.next_accept_wait = 1;
        assert_eq!(
            prepared.validate_native_exec_cut(binding.prepared_files(), true),
            Err(NativeExecCutError::PreparedState("next_accept_wait"))
        );
        let only = table.file_handles.remove(&33).unwrap();
        table.file_handles.insert(34, only);
        assert_eq!(
            table.validate_native_exec_cut(binding.old_files, false),
            Err(NativeExecCutError::Descriptor("slot number"))
        );
        table.file_handles.clear();
        table.file_handles.insert(
            -1,
            DetFd::new(
                -1,
                OFlag::empty(),
                FdType::Rng,
                OpenFileId::new(binding.dettid, 1),
            ),
        );
        assert_eq!(
            table.validate_native_exec_cut(binding.old_files, false),
            Err(NativeExecCutError::Descriptor("slot number"))
        );
    }

    #[test]
    fn native_exec_each_skipped_or_live_thread_transient_refuses() {
        for field in 0..26 {
            let (tool, mut thread, binding) = fixture();
            match field {
                0 => {
                    thread.parent_process_cpu_time =
                        Some(Arc::new(Mutex::new(ProcessCpuTime::default())))
                }
                1 => thread.parent_cpu_publication = Some(ChildCpuPublication::pending()),
                2 => {
                    thread.restart_block = Some(crate::syscalls::helpers::RestartBlock {
                        rip: 0x1234,
                        deadline: None,
                        call: crate::syscalls::helpers::RestartCall::Poll(
                            reverie::syscalls::Poll::new(),
                        ),
                    })
                }
                3 => thread.signal_register_projection = Some(unsafe { std::mem::zeroed() }),
                4 => thread.clone_flags = Some(CloneFlags::empty()),
                5 => {
                    thread.pending_vfork = Some(PendingVfork {
                        parent_dettid: binding.dettid,
                        parent_detpid: binding.detpid,
                        child_tid_addr: 0,
                        flags: CloneFlags::CLONE_VFORK,
                        exit_signal: libc::SIGCHLD,
                        child_priority_entropy: None,
                    })
                }
                6 => thread.own_signal_turn_hold = Some(libc::SIGALRM),
                7 => thread.sigalrm_handled = true,
                8 => thread.handler_restore_rt_reported = 1,
                9 => {
                    thread.initialized_random_auxv = Some((
                        crate::random::InitialImage {
                            pid: binding.physical_tid,
                            start_time_ticks: 1,
                            at_random: 0x234000,
                        },
                        [7; 16],
                        Vec::new(),
                    ))
                }
                10 => thread.uncharged_bootstrap_syscalls = 1,
                11 => thread.in_uncharged_bootstrap_syscall = true,
                12 => thread.yield_after_futex_wake = true,
                13 => {
                    thread.interrupt_at.insert(1);
                }
                14 => thread.replay_rcb_end = Some(1),
                15 => thread.last_rcb_timer = Some(1),
                16 => thread.last_rcb_timer_is_max = true,
                17 => thread.max_timeslice_end = Some(LogicalTime::from_nanos(1)),
                18 => thread.chaos_slowdown_active = true,
                19 => thread.nested_pid_namespace = true,
                20 => thread.thread_start_entered = false,
                21 => thread.past_global_first_execve = false,
                22 => {
                    thread.last_accounted_system_time =
                        thread.thread_logical_time.system_cpu_time() + Duration::from_nanos(1)
                }
                23 => {
                    thread.preemption_points =
                        Some(crate::preemptions::ThreadHistory::new().into_iter())
                }
                24 => thread.pending_chaos_epochs.push(ChaosEpochTransition {
                    logical_time: LogicalTime::from_nanos(1),
                    epoch: 1,
                    factor: RcbTimeMultiplier::from_f64(1.5),
                }),
                25 => {
                    thread.signal_task_identity = Some(reverie::SignalTaskIdentity {
                        process: reverie::SignalProcessId {
                            tgid: reverie::Pid::from_raw(binding.physical_tid),
                            generation: 0,
                        },
                        tid: reverie::Pid::from_raw(binding.physical_tid),
                        task_generation: 0,
                    })
                }
                _ => unreachable!(),
            }
            assert!(
                validate_old_native_exec_cut(&tool, &thread, &binding).is_err(),
                "field {field}"
            );
        }
    }

    #[test]
    fn native_exec_robust_and_prepared_memory_must_match_the_actual_cut() {
        for field in 0..4 {
            let (tool, mut thread, binding) = fixture();
            thread.record_robust_list_head(Some(0x1000));
            {
                let mut robust = thread.robust_list_process.lock().unwrap();
                match field {
                    0 => {
                        robust.heads.insert(DetTid::from_raw(43), 0x2000);
                    }
                    1 => {
                        robust.pending.insert(
                            binding.dettid,
                            PendingRobustListWakes {
                                reason: RobustListExit::ExitGroup,
                                wakes: Vec::new(),
                            },
                        );
                    }
                    2 => {
                        robust
                            .matched_physical_exits
                            .insert(binding.dettid, thread.thread_logical_time.clone());
                    }
                    3 => robust.exec_pending.push((
                        binding.dettid,
                        RobustListWake {
                            futex: FutexID::private(binding.old_mm, 0x3000),
                        },
                    )),
                    _ => unreachable!(),
                }
            }
            assert!(
                validate_old_native_exec_cut(&tool, &thread, &binding).is_err(),
                "old field {field}"
            );
        }
        for field in 0..8 {
            let (tool, mut thread, binding) = fixture();
            let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
            prepare(&mut thread, &binding);
            match field {
                0 => thread.memory_metadata.lock().unwrap().observe_brk(0x4000),
                1 => thread.memory_metadata.lock().unwrap().map_anonymous(
                    binding.prepared_mm(),
                    0x5000,
                    0x1000,
                ),
                2 => thread.record_robust_list_head(Some(0x1000)),
                3 => thread.stage_robust_list_wakes_for_exec(vec![(
                    binding.dettid,
                    vec![RobustListWake {
                        futex: FutexID::private(binding.prepared_mm(), 0x3000),
                    }],
                )]),
                4 => thread.stage_robust_list_wakes_for_exec(vec![(
                    DetTid::from_raw(43),
                    vec![RobustListWake {
                        futex: FutexID::private(binding.old_mm, 0x3000),
                    }],
                )]),
                5 => thread.file_metadata.lock().unwrap().files_id = binding.old_files,
                6 => {
                    thread.file_metadata.lock().unwrap().file_handles.insert(
                        3,
                        DetFd::new(
                            3,
                            OFlag::O_CLOEXEC,
                            FdType::Rng,
                            OpenFileId::new(binding.dettid, 1),
                        ),
                    );
                }
                7 => thread.mm_id = binding.old_mm,
                _ => unreachable!(),
            }
            assert!(
                capture_prepared_native_exec(&tool, &thread, &binding, &receipt).is_err(),
                "prepared field {field}"
            );
        }
    }

    #[test]
    fn native_exec_model_lock_contention_is_a_refusal_without_mutation() {
        let (tool, thread, binding) = fixture();
        let before = state_bytes(&thread);
        macro_rules! locked {
            ($field:ident) => {{
                let guard = thread.$field.lock().unwrap();
                assert!(matches!(
                    validate_old_native_exec_cut(&tool, &thread, &binding),
                    Err(NativeExecCutError::LockUnavailable(_))
                ));
                drop(guard);
                assert_eq!(state_bytes(&thread), before);
            }};
        }
        locked!(file_metadata);
        locked!(process_cpu_time);
        locked!(guest_clock);
        locked!(resource_limits);
        locked!(posix_timers);
        locked!(robust_list_process);
        validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
    }
}

fn thread_rng_from_parent_entropy(msg: &str, parent: &Pcg64Mcg, entropy: u128) -> Pcg64Mcg {
    thread_rng_from_parent_entropy_labeled(msg, parent, entropy, "entropy")
}

fn thread_rng_from_parent_entropy_labeled(
    msg: &str,
    parent: &Pcg64Mcg,
    entropy: u128,
    identity_kind: &str,
) -> Pcg64Mcg {
    // Perform the default SeedableRng::from_seed procedure
    let mut seed = <Pcg64Mcg as SeedableRng>::Seed::default();
    // Generate a seed from the parent:
    parent.clone().fill_bytes(seed.as_mut());
    detlog!("RNG {} Generated new seed {:?}", msg, seed);
    // Pcg64Mcg forces its internal state odd, so seed bit zero carries no
    // entropy. DBT uses 96 bits for a stable process/thread sequence; mix those
    // bytes after the forced bit while retaining the existing DetTid layout.
    let entropy_bytes = entropy.to_le_bytes();
    for (seed_byte, entropy_byte) in seed[4..].iter_mut().zip(entropy_bytes) {
        *seed_byte ^= entropy_byte;
    }
    detlog!(
        "RNG {} seeding child {} {}: {:?} from parent {:?}",
        msg,
        identity_kind,
        entropy,
        seed,
        parent
    );
    let mut rng = Pcg64Mcg::from_seed(seed);
    // Pcg64Mcg integrates flipped bits across the state quickly. Some PRNGs don't.
    // Defensively ensure flipped bits "propagate":
    rng.next_u64();
    rng.next_u64();
    rng.next_u64();
    rng.next_u64();
    rng
}

/// The procfs path that descriptor `fd` of the calling process is a
/// placeholder for, which this image of the process has not seen: a memfd
/// named for it and sealed as Detcore seals its placeholders, which a guest
/// could imitate (a known limitation, see
/// <https://github.com/rrnewton/hermit/issues/4263>). Read with raw
/// system calls (under in-guest backends the tool shares the guest's C
/// library).
/// The fixed procfs file the kernel opened at `fd`, if its descriptor link
/// names one (`ProcfsFile::snapshot_is_fixed`).
fn fixed_procfs_behind(fd: RawFd) -> Option<crate::procfs::ProcfsFile> {
    // The calling thread's own table: `/proc/self/fd` is the leader's.
    let link = std::ffi::CString::new(format!("/proc/thread-self/fd/{fd}")).ok()?;
    let mut target = [0_u8; 256];
    // SAFETY: the path is NUL-terminated and `target` is writable.
    let length = unsafe {
        crate::util::raw_syscall(
            libc::SYS_readlinkat,
            [
                libc::AT_FDCWD as u64,
                link.as_ptr() as u64,
                target.as_mut_ptr() as u64,
                target.len() as u64,
                0,
                0,
            ],
        )
    };
    let length = usize::try_from(length)
        .ok()
        .filter(|length| *length < target.len())?;
    let path = std::path::Path::new(
        <std::ffi::OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(&target[..length]),
    );
    crate::procfs::ProcfsFile::from_path(path).filter(crate::procfs::ProcfsFile::snapshot_is_fixed)
}

fn placeholder_behind(
    fd: RawFd,
    files: crate::procfs::RenderedFiles,
) -> Option<(&'static std::path::Path, Vec<u8>)> {
    // SAFETY: F_GET_SEALS only reads the descriptor's seals.
    let seals = unsafe {
        crate::util::raw_syscall(
            libc::SYS_fcntl,
            [fd as u64, libc::F_GET_SEALS as u64, 0, 0, 0, 0],
        )
    };
    // An `O_PATH` descriptor cannot show its seals (EBADF); its name decides.
    let wanted = i64::from(crate::syscalls::rendered_procfs::PLACEHOLDER_SEALS);
    if seals != -i64::from(libc::EBADF) && (seals < 0 || seals & wanted != wanted) {
        return None;
    }
    // The calling thread's own table: `/proc/self/fd` is the leader's.
    let link = std::ffi::CString::new(format!("/proc/thread-self/fd/{fd}")).ok()?;
    let mut target = [0_u8; crate::procfs::PLACEHOLDER_LINK_CAPACITY];
    // SAFETY: the path is NUL-terminated and `target` is writable.
    let length = unsafe {
        crate::util::raw_syscall(
            libc::SYS_readlinkat,
            [
                libc::AT_FDCWD as u64,
                link.as_ptr() as u64,
                target.as_mut_ptr() as u64,
                target.len() as u64,
                0,
                0,
            ],
        )
    };
    let length = usize::try_from(length).ok()?.min(target.len());
    crate::procfs::placeholder_link(&target[..length], files)
}

#[cfg(test)]
mod native_main_state_tests {
    use super::*;
    use crate::native_exec::capture_prepared_native_exec;
    use crate::native_exec::tests::fixture;
    use crate::native_exec::tests::prepare;
    use crate::native_exec::tests::state_bytes;
    use crate::native_exec::validate_old_native_exec_cut;
    fn snapshot(
        tool: &crate::Detcore<crate::native_exec::NoopTool>,
        thread: &ThreadState<()>,
        binding: &crate::native_exec::NativeExecCutBinding,
        receipt: &crate::native_exec::NativeExecPreparationReceipt,
    ) -> crate::native_exec::DetcoreExecSnapshotV2 {
        let bytes = bincode::serde::encode_to_vec(
            capture_prepared_native_exec(tool, thread, binding, receipt).unwrap(),
            bincode::config::legacy(),
        )
        .unwrap();
        crate::native_exec::tests::decoded(&bytes)
    }

    #[test]
    fn native_main_claimed_sigchld_refuses_live_and_decoded_without_reset() {
        let (tool, mut thread, binding) = fixture();
        thread.claimed_sigchld = true;
        let before = state_bytes(&thread);
        assert!(matches!(
            validate_old_native_exec_cut(&tool, &thread, &binding),
            Err(crate::native_exec::NativeExecCutError::LiveCapability(
                "claimed SIGCHLD"
            ))
        ));
        assert_eq!(state_bytes(&thread), before);
        thread.claimed_sigchld = false;
        let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
        prepare(&mut thread, &binding);
        let mut payload = snapshot(&tool, &thread, &binding, &receipt);
        crate::native_exec::tests::thread_for_test(&mut payload).claimed_sigchld = true;
        assert!(matches!(
            payload.validate(&binding, &tool.cfg),
            Err(crate::native_exec::NativeExecCutError::LiveCapability(
                "claimed SIGCHLD"
            ))
        ));
        assert!(crate::native_exec::tests::thread_for_test(&mut payload).claimed_sigchld);
    }

    fn mark_barrier(process: &mut RobustListProcessState, field: usize, owner: DetTid) {
        match field {
            0 => {
                process.tool_walked.insert(owner);
            }
            1 => process.exit_group_filed = true,
            2 => {
                process.exit_group_filers.insert(owner);
            }
            3 => process.exit_group_walker = Some(owner),
            4 => process.exit_group_walked = true,
            _ => unreachable!(),
        }
    }

    #[test]
    fn native_main_robust_barrier_state_refuses_old_prepared_and_decoded() {
        for field in 0..5 {
            let (tool, thread, binding) = fixture();
            mark_barrier(
                &mut thread.robust_list_process.lock().unwrap(),
                field,
                binding.dettid,
            );
            let before = state_bytes(&thread);
            assert!(
                validate_old_native_exec_cut(&tool, &thread, &binding).is_err(),
                "old {field}"
            );
            assert_eq!(state_bytes(&thread), before);

            let (tool, mut thread, binding) = fixture();
            let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
            prepare(&mut thread, &binding);
            let mut payload = snapshot(&tool, &thread, &binding, &receipt);
            mark_barrier(
                &mut thread.robust_list_process.lock().unwrap(),
                field,
                binding.dettid,
            );
            let before = state_bytes(&thread);
            assert!(
                capture_prepared_native_exec(&tool, &thread, &binding, &receipt).is_err(),
                "prepared {field}"
            );
            assert_eq!(state_bytes(&thread), before);
            let decoded = crate::native_exec::tests::thread_for_test(&mut payload);
            mark_barrier(
                &mut decoded.robust_list_process.lock().unwrap(),
                field,
                binding.dettid,
            );
            let before = state_bytes(decoded);
            assert!(
                payload.validate(&binding, &tool.cfg).is_err(),
                "decoded {field}"
            );
            assert_eq!(
                state_bytes(crate::native_exec::tests::thread_for_test(&mut payload)),
                before
            );
        }
    }

    #[test]
    fn native_main_nanosleep_restart_refuses_even_when_serde_skips_it() {
        for deadline in [None, Some(crate::types::LogicalTime::from_nanos(4567))] {
            let (tool, mut thread, binding) = fixture();
            let before = state_bytes(&thread);
            thread.restart_block = Some(crate::syscalls::helpers::RestartBlock {
                rip: 0x1234,
                deadline,
                call: crate::syscalls::helpers::RestartCall::Nanosleep(
                    reverie::syscalls::Nanosleep::new().into(),
                ),
            });
            assert_eq!(state_bytes(&thread), before);
            assert!(matches!(
                validate_old_native_exec_cut(&tool, &thread, &binding),
                Err(crate::native_exec::NativeExecCutError::LiveCapability(
                    "restart/projection"
                ))
            ));
            assert!(thread.restart_block.is_some());
        }
    }

    #[test]
    fn native_main_rng_promotion_history_survives_snapshot_and_some_empty() {
        use std::os::fd::AsRawFd;
        crate::fd::install_test_shared_open_file_channel();
        {
            let (tool, mut thread, binding) = fixture();
            let local = std::fs::File::open("/dev/urandom").unwrap();
            thread
                .add_fd(local.as_raw_fd(), OFlag::O_RDONLY, FdType::Rng, None)
                .unwrap();
            assert!(thread.shared_open_files_for_exec().unwrap().is_none());
            let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
            prepare(&mut thread, &binding);
            let (_, restored) = snapshot(&tool, &thread, &binding, &receipt)
                .into_validated_parts(&binding, &tool.cfg)
                .unwrap();
            assert!(restored.shared_open_files_for_exec().unwrap().is_none());
        }
        let (tool, mut thread, binding) = fixture();
        let creator = DetTid::from_raw(930001);
        thread.set_open_file_creator(creator);
        let file = std::fs::File::open("/dev/urandom").unwrap();
        let alias = nix::unistd::dup(&file).unwrap();
        let cloexec = nix::unistd::dup(&file).unwrap();
        let distinct = std::fs::File::open("/dev/urandom").unwrap();
        let (fd, alias_fd, cloexec_fd, distinct_fd) = (
            file.as_raw_fd(),
            alias.as_raw_fd(),
            cloexec.as_raw_fd(),
            distinct.as_raw_fd(),
        );
        thread
            .add_fd(fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        thread.dup_fd(fd, alias_fd, OFlag::empty()).unwrap();
        thread.dup_fd(fd, cloexec_fd, OFlag::O_CLOEXEC).unwrap();
        thread
            .add_fd(distinct_fd, OFlag::O_RDONLY, FdType::Rng, None)
            .unwrap();
        assert!(
            thread.shared_open_files_for_exec().unwrap().is_none(),
            "local RNG is not promotion"
        );
        let high = thread
            .metadata()
            .allocate_open_file_id(creator, FdType::Rng);
        let high_socket = thread
            .metadata()
            .allocate_open_file_id(creator, FdType::Socket);
        thread.promote_shared_open_files().unwrap();
        let expected = thread.shared_open_files_for_exec().unwrap().unwrap();
        assert_eq!(expected.creator, creator);
        assert_eq!(expected.handles[&fd].id, expected.handles[&alias_fd].id);
        assert_ne!(expected.handles[&fd].id, expected.handles[&distinct_fd].id);
        assert!(!expected.handles.contains_key(&cloexec_fd));
        let old_table = Arc::clone(&thread.file_metadata);
        let receipt = validate_old_native_exec_cut(&tool, &thread, &binding).unwrap();
        prepare(&mut thread, &binding);
        assert!(
            old_table
                .lock()
                .unwrap()
                .file_handles
                .contains_key(&cloexec_fd)
        );
        let (_, restored) = snapshot(&tool, &thread, &binding, &receipt)
            .into_validated_parts(&binding, &tool.cfg)
            .unwrap();
        assert_eq!(
            restored.shared_open_files_for_exec().unwrap(),
            Some(expected)
        );
        assert_eq!(restored.open_file_creator, Some(creator));
        assert_eq!(
            restored.metadata().next_open_file_sequence,
            thread.metadata().next_open_file_sequence
        );
        assert_eq!(
            restored.metadata().next_socket_open_file_sequence,
            thread.metadata().next_socket_open_file_sequence
        );
        restored.metadata().file_handles[&alias_fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 0);
                Ok(11)
            })
            .unwrap();
        thread.metadata().file_handles[&fd]
            .with_random_device_stream::<Errno>(|offset| {
                assert_eq!(offset, 11);
                Ok(0)
            })
            .unwrap();
        // Both tables retain the same canonical shared ID, not a copied cursor.
        for slot in [fd, alias_fd, distinct_fd] {
            thread.remove_fd(slot);
        }
        let empty = thread.shared_open_files_for_exec().unwrap().unwrap();
        assert!(empty.handles.is_empty());
        assert_eq!(empty.creator, creator);
        assert_ne!(OpenFileId::new(creator, empty.next_sequence), high);
        assert_ne!(
            OpenFileId::new_socket(creator, empty.next_socket_sequence),
            high_socket
        );
        // Drop the test-owned metadata guard before the validator probes it.
        let old_files = thread.metadata().files_id;
        let binding2 = crate::native_exec::NativeExecCutBinding {
            old_mm: thread.mm_id,
            old_files,
            ..binding
        };
        let receipt2 = validate_old_native_exec_cut(&tool, &thread, &binding2).unwrap();
        prepare(&mut thread, &binding2);
        let (_, again) = snapshot(&tool, &thread, &binding2, &receipt2)
            .into_validated_parts(&binding2, &tool.cfg)
            .unwrap();
        assert_eq!(again.shared_open_files_for_exec().unwrap(), Some(empty));
    }
}