frankensearch-index 0.2.2

FSVI vector index, SIMD dot product, and top-k search for frankensearch
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
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
//! Descriptor-owned admission for composite search-index generation roots.
//!
//! This module is deliberately narrower than the generation publisher. It
//! qualifies an existing private root, admits existing immutable regular
//! files into retained descriptors plus exact owned bytes, exposes fail-closed
//! durability barriers, and provides non-blocking kernel `flock` guards.
//! Publication, renames, unlinks, truncation, garbage collection, recovery,
//! and consumer activation do not belong here.
//!
//! # Supported targets and process binding
//!
//! Linux admits path-opened roots and final files only on locally qualified,
//! writable ext4 or Btrfs. Apple Silicon admits path-opened local writable APFS
//! roots, but every final artifact/control/lock file must arrive as an owned
//! already-open descriptor from the trusted provider documented by the
//! preopened APIs. Every other target returns
//! [`GenerationRootErrorKind::UnsupportedPlatform`] before route parsing or
//! filesystem I/O. Root, file, control, and lock capabilities are bound to the
//! process that created them; using any operation that revalidates or acts on
//! those capabilities after `fork` returns
//! [`GenerationRootErrorKind::ForkedProcess`].
//!
//! # Synchronous execution and resource boundary
//!
//! Every operation in this module is synchronous. Each exact-name component
//! proof accepts up to [`GENERATION_ROOT_MAX_DIRECTORY_ENTRIES`] names and
//! [`GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES`] aggregate name bytes, and may
//! inspect one overflow entry/name to reject it; one route can require up to
//! [`GENERATION_ROOT_MAX_COMPONENTS`] such proofs.
//! A route walk can invoke more than one exact-name proof per component, and
//! one public operation can walk the same route several times. The component
//! ceiling bounds depth, not the aggregate number of directory scans.
//! Linux mount qualification stores at most
//! [`GENERATION_ROOT_MAX_MOUNTINFO_BYTES`] from the calling thread's
//! task-scoped mount table and may read one overflow sentinel byte.
//! Immutable artifacts can read/hash up to [`GENERATION_ROOT_MAX_FILE_BYTES`]
//! bytes; repeatedly checked control anchors have the smaller
//! [`GENERATION_ROOT_MAX_CONTROL_FILE_BYTES`] ceiling. Explicit immutable
//! durability performs two full-file reads, while control admission, locking,
//! and locked durability can perform multiple exact hash passes around route,
//! lock, and kernel-barrier checkpoints. These functions are neither async nor
//! cancellation-aware. Async consumers must run them in a bounded blocking
//! pool, propagate cancellation only at operation boundaries, and admit only
//! trusted local generation roots whose total work is independently budgeted.
//! The per-proof ceilings below bound individual work and memory; they are not
//! aggregate admission budgets or latency promises.
//!
//! # Linux retained-capability reopen
//!
//! Linux has one intentional, tightly bounded magic-link exception. After the
//! original route has produced and fully qualified a retained `O_PATH`
//! regular-file capability, the module opens a separately verified procfs root,
//! proves that its `self` link names the calling process and its `thread-self`
//! link names the calling thread, and preflights the exact final
//! `/proc/thread-self/fd/<held-O_PATH-fd>` magic link as a symlink on the same
//! procfs mount before and after deriving the data descriptor. Resolving
//! `thread-self` and the numeric fd entry in the data-open syscall binds the
//! reopen to the accessing thread's descriptor table even after
//! `unshare(CLONE_FILES)`; process-identity checks still reject child-side use
//! after `fork()`.
//! This bridge never re-resolves the original generation route. Descriptor-
//! bound directory traversal performs each final-file route revalidation with
//! an `O_PATH`-only final probe, and the retained probe, derived data
//! descriptor, final procfs probe, and final route probe must retain their
//! respective identities. As with every `/proc`-based capability protocol, the
//! calling mount namespace must be trusted against concurrent `CAP_SYS_ADMIN`
//! remounts; a process able to rewrite that namespace is outside this
//! substrate's authority boundary.

#![forbid(unsafe_code)]

use std::fmt;
use std::path::Path;
use std::sync::Arc;

/// Maximum accepted absolute or relative route length.
pub const GENERATION_ROOT_MAX_ROUTE_BYTES: usize = 4096;
/// Maximum accepted component length.
pub const GENERATION_ROOT_MAX_COMPONENT_BYTES: usize = 255;
/// Maximum accepted component count.
pub const GENERATION_ROOT_MAX_COMPONENTS: usize = 64;
/// Hard ceiling for one owned immutable artifact image.
pub const GENERATION_ROOT_MAX_FILE_BYTES: u64 = 16 * 1024 * 1024 * 1024;
/// Hard ceiling for one repeatedly hashed mutable control anchor.
pub const GENERATION_ROOT_MAX_CONTROL_FILE_BYTES: u64 = 1024 * 1024;
/// Maximum names inspected while proving one exact directory entry.
pub const GENERATION_ROOT_MAX_DIRECTORY_ENTRIES: usize = 1_000_000;
/// Maximum aggregate name bytes inspected during one exact-name proof.
pub const GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES: usize = 64 * 1024 * 1024;
/// Maximum bytes read from Linux task-scoped procfs `mountinfo` for one qualification.
pub const GENERATION_ROOT_MAX_MOUNTINFO_BYTES: usize = 4 * 1024 * 1024;
/// Required mode for the qualified generation root and its directories.
pub const GENERATION_ROOT_DIRECTORY_MODE: u32 = 0o700;
/// Required sealed mode for immutable generation artifacts.
pub const GENERATION_ROOT_IMMUTABLE_FILE_MODE: u32 = 0o400;
/// Required mode for mutable generation control files.
pub const GENERATION_ROOT_CONTROL_FILE_MODE: u32 = 0o600;
/// Exact top-level name of the persistent generation-root lock anchor.
pub const GENERATION_ROOT_LOCK_FILE_NAME: &str = "LOCK";
/// Exact top-level name of the persistent generation-root authority anchor.
pub const GENERATION_ROOT_AUTHORITY_FILE_NAME: &str = "AUTHORITY";
/// Frozen physical length of the two-slot AUTHORITY inode.
///
/// Slot interpretation belongs to the authority codec. The platform layer
/// enforces only this immutable physical-layout fact.
pub const GENERATION_ROOT_AUTHORITY_FILE_BYTES: u64 = 8192;

/// Operation stage attached to every bounded generation-root failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GenerationRootStage {
    /// Reject an unsupported target before any filesystem access.
    PlatformGate,
    /// Parse and bound an absolute generation-root route.
    ParseRootRoute,
    /// Parse and bound a confined relative route.
    ParseRelativeRoute,
    /// Open the absolute route one component at a time.
    OpenRootRoute,
    /// Qualify root ownership and permissions.
    QualifyRootSecurity,
    /// Qualify the root filesystem and mount.
    QualifyFilesystem,
    /// Inspect an extended ACL through a retained descriptor.
    InspectAcl,
    /// Re-resolve and fence the absolute route.
    RevalidateRootRoute,
    /// Open and qualify a relative directory component.
    OpenRelativeDirectory,
    /// Open and qualify the final regular file.
    OpenRegularFile,
    /// Read one regular file into a bounded owned image.
    ReadRegularFile,
    /// Re-open and fence a relative file route.
    RevalidateRegularFile,
    /// Execute the platform's file durability barrier.
    SyncRegularFile,
    /// Execute the platform's directory durability barrier.
    SyncDirectory,
    /// Acquire a non-blocking kernel file lock.
    AcquireLock,
    /// Explicitly release a kernel file lock.
    ReleaseLock,
}

impl GenerationRootStage {
    const fn code(self) -> &'static str {
        match self {
            Self::PlatformGate => "platform_gate",
            Self::ParseRootRoute => "parse_root_route",
            Self::ParseRelativeRoute => "parse_relative_route",
            Self::OpenRootRoute => "open_root_route",
            Self::QualifyRootSecurity => "qualify_root_security",
            Self::QualifyFilesystem => "qualify_filesystem",
            Self::InspectAcl => "inspect_acl",
            Self::RevalidateRootRoute => "revalidate_root_route",
            Self::OpenRelativeDirectory => "open_relative_directory",
            Self::OpenRegularFile => "open_regular_file",
            Self::ReadRegularFile => "read_regular_file",
            Self::RevalidateRegularFile => "revalidate_regular_file",
            Self::SyncRegularFile => "sync_regular_file",
            Self::SyncDirectory => "sync_directory",
            Self::AcquireLock => "acquire_lock",
            Self::ReleaseLock => "release_lock",
        }
    }
}

/// Stable failure class for generation-root admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GenerationRootErrorKind {
    /// This architecture/OS combination is intentionally unsupported.
    UnsupportedPlatform,
    /// A path is empty, ambiguous, unbounded, absolute where relative was
    /// required, or contains a forbidden component.
    InvalidRoute,
    /// A required kernel primitive is unavailable or filtered.
    UnsupportedKernelFeature,
    /// Apple Silicon final-file admission requires a caller/provider-owned
    /// already-open descriptor so this library never invokes a vnode open
    /// callback before proving the object type.
    PreopenedDescriptorRequired,
    /// A symbolic or magic link was encountered.
    SymbolicLink,
    /// An ancestor or requested root is not a directory.
    NotDirectory,
    /// The final object is not a regular file.
    NotRegularFile,
    /// A regular file has more than one hard link.
    HardLinked,
    /// An object is not owned by the effective user.
    WrongOwner,
    /// An object's permission mode is not the exact private mode.
    WrongMode,
    /// A provider-owned descriptor is not opened with the exact data access
    /// mode required by the API, or carries a metadata/event-only access flag.
    InvalidDescriptorAccess,
    /// A provider-owned descriptor is missing close-on-exec.
    CloseOnExecRequired,
    /// Per-object immutable, append-only, or other write-restricting flags
    /// make the object incompatible with the qualified writable-root profile.
    WriteRestrictedObject,
    /// Apple object flags are nonzero and therefore outside the deliberately
    /// narrow zero-flags APFS admission profile.
    UnsupportedObjectFlags,
    /// A platform extended ACL is present or cannot be inspected exactly
    /// through the retained descriptor.
    AclRejected,
    /// A descendant crossed the qualified root's mount.
    CrossDevice,
    /// The filesystem is remote, synthetic, unknown, or not allowlisted.
    UnsupportedFilesystem,
    /// The filesystem is read-only or ignores ownership.
    ReadOnlyFilesystem,
    /// A retained object or its canonical route changed during admission.
    ObjectChanged,
    /// A file length differs from its exact expected value.
    SizeMismatch,
    /// An immutable-artifact API received a control-file expectation or the
    /// reverse.
    WrongRole,
    /// A caller or on-disk value exceeds a resource ceiling.
    ResourceLimit,
    /// The exact owned bytes do not match the expected SHA-256.
    HashMismatch,
    /// The required durability primitive failed; no weaker barrier was used.
    DurabilityUnavailable,
    /// A non-blocking shared or exclusive kernel lock is contended.
    LockContended,
    /// Admission or a lock operation crossed a `fork()` process-identity
    /// boundary and cannot continue in the child process.
    ForkedProcess,
    /// A bounded operating-system error not covered by a more specific class.
    Io,
}

impl GenerationRootErrorKind {
    /// Stable, machine-readable reason code.
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::UnsupportedPlatform => "unsupported_platform",
            Self::InvalidRoute => "invalid_route",
            Self::UnsupportedKernelFeature => "unsupported_kernel_feature",
            Self::PreopenedDescriptorRequired => "preopened_descriptor_required",
            Self::SymbolicLink => "symbolic_link",
            Self::NotDirectory => "not_directory",
            Self::NotRegularFile => "not_regular_file",
            Self::HardLinked => "hard_linked",
            Self::WrongOwner => "wrong_owner",
            Self::WrongMode => "wrong_mode",
            Self::InvalidDescriptorAccess => "invalid_descriptor_access",
            Self::CloseOnExecRequired => "close_on_exec_required",
            Self::WriteRestrictedObject => "write_restricted_object",
            Self::UnsupportedObjectFlags => "unsupported_object_flags",
            Self::AclRejected => "acl_rejected",
            Self::CrossDevice => "cross_device",
            Self::UnsupportedFilesystem => "unsupported_filesystem",
            Self::ReadOnlyFilesystem => "read_only_filesystem",
            Self::ObjectChanged => "object_changed",
            Self::SizeMismatch => "size_mismatch",
            Self::WrongRole => "wrong_role",
            Self::ResourceLimit => "resource_limit",
            Self::HashMismatch => "hash_mismatch",
            Self::DurabilityUnavailable => "durability_unavailable",
            Self::LockContended => "lock_contended",
            Self::ForkedProcess => "forked_process",
            Self::Io => "io",
        }
    }
}

/// Bounded, path-redacted generation-root failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GenerationRootError {
    kind: GenerationRootErrorKind,
    stage: GenerationRootStage,
    component_index: Option<u16>,
    raw_os_error: Option<i32>,
    expected: Option<u64>,
    observed: Option<u64>,
}

impl GenerationRootError {
    const fn new(kind: GenerationRootErrorKind, stage: GenerationRootStage) -> Self {
        Self {
            kind,
            stage,
            component_index: None,
            raw_os_error: None,
            expected: None,
            observed: None,
        }
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    fn at_component(mut self, component_index: usize) -> Self {
        self.component_index = Some(u16::try_from(component_index).unwrap_or(u16::MAX));
        self
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    const fn with_raw_os_error(mut self, raw_os_error: i32) -> Self {
        self.raw_os_error = Some(raw_os_error);
        self
    }

    const fn with_counts(mut self, expected: u64, observed: u64) -> Self {
        self.expected = Some(expected);
        self.observed = Some(observed);
        self
    }

    /// Stable failure class.
    #[must_use]
    pub const fn kind(&self) -> GenerationRootErrorKind {
        self.kind
    }

    /// Operation stage at which the failure was observed.
    #[must_use]
    pub const fn stage(&self) -> GenerationRootStage {
        self.stage
    }

    /// Zero-based path component index, when applicable.
    #[must_use]
    pub const fn component_index(&self) -> Option<u16> {
        self.component_index
    }

    /// Raw OS error number, when retaining it is useful and bounded.
    #[must_use]
    pub const fn raw_os_error(&self) -> Option<i32> {
        self.raw_os_error
    }

    /// Expected bounded numeric value, ceiling, count, or bitmask, when
    /// applicable.
    #[must_use]
    pub const fn expected(&self) -> Option<u64> {
        self.expected
    }

    /// Observed bounded numeric value, count, or bitmask, when applicable.
    #[must_use]
    pub const fn observed(&self) -> Option<u64> {
        self.observed
    }
}

impl fmt::Display for GenerationRootError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "generation-root {} failed: {}",
            self.stage.code(),
            self.kind.code()
        )?;
        if let Some(component_index) = self.component_index {
            write!(formatter, " (component {component_index})")?;
        }
        if let Some(raw_os_error) = self.raw_os_error {
            write!(formatter, " (os error {raw_os_error})")?;
        }
        if let (Some(expected), Some(observed)) = (self.expected, self.observed) {
            write!(formatter, " (expected {expected}, observed {observed})")?;
        }
        if self.kind == GenerationRootErrorKind::AclRejected {
            write!(
                formatter,
                " (only the descriptor-bound absence of a platform extended ACL \
                 is admissible; presence or inspection uncertainty fails closed)"
            )?;
        }
        if self.kind == GenerationRootErrorKind::PreopenedDescriptorRequired {
            write!(
                formatter,
                " (Apple Silicon requires a trusted external provider to supply an owned \
                 already-open regular-file descriptor; use the preopened admission/lock API)"
            )?;
        }
        Ok(())
    }
}

impl std::error::Error for GenerationRootError {}

/// Result alias for this platform substrate.
pub type GenerationRootResult<T> = Result<T, GenerationRootError>;

/// Filesystem profile admitted for generation-root durability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum QualifiedFilesystem {
    /// Linux ext4.
    LinuxExt4,
    /// Linux Btrfs.
    LinuxBtrfs,
    /// Local writable APFS on Apple Silicon.
    AppleApfs,
}

/// Stable metadata snapshot retained for one admitted filesystem object.
///
/// This is an object/metadata witness, not a content authority. Derived
/// equality and hashing compare the raw snapshot, including access time;
/// regular-file admission uses a narrower mutation-stable comparison that
/// deliberately excludes access time on every admitted platform. Root and
/// directory route revalidation is narrower again: it attests only
/// device/inode, mode, owner/group, mount identity, and filesystem profile,
/// because contained publication may legitimately change directory contents,
/// link count, size, and timestamps. Use the owning qualified
/// file/control/lock capability's SHA-256 accessor when content identity is
/// required; never interpret a root/directory revalidation as an attestation
/// of directory contents or timestamps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GenerationRootObjectWitness {
    device: u64,
    inode: u64,
    mode: u32,
    hard_links: u64,
    uid: u32,
    gid: u32,
    byte_len: u64,
    modified_seconds: i64,
    modified_nanoseconds: i64,
    changed_seconds: i64,
    changed_nanoseconds: i64,
    accessed_seconds: i64,
    accessed_nanoseconds: i64,
    mount_identity: [u8; 32],
    filesystem: QualifiedFilesystem,
}

impl GenerationRootObjectWitness {
    /// Device identifier.
    #[must_use]
    pub const fn device(&self) -> u64 {
        self.device
    }

    /// Inode identifier.
    #[must_use]
    pub const fn inode(&self) -> u64 {
        self.inode
    }

    /// Full persisted mode word.
    #[must_use]
    pub const fn mode(&self) -> u32 {
        self.mode
    }

    /// Hard-link count.
    #[must_use]
    pub const fn hard_links(&self) -> u64 {
        self.hard_links
    }

    /// Owner user id.
    #[must_use]
    pub const fn uid(&self) -> u32 {
        self.uid
    }

    /// Owner group id.
    #[must_use]
    pub const fn gid(&self) -> u32 {
        self.gid
    }

    /// Exact byte length at admission.
    #[must_use]
    pub const fn byte_len(&self) -> u64 {
        self.byte_len
    }

    /// Opaque, descriptor-derived filesystem namespace identity.
    ///
    /// On Btrfs this binds both the VFS mount and the containing subvolume.
    #[must_use]
    pub const fn mount_identity(&self) -> [u8; 32] {
        self.mount_identity
    }

    /// Qualified filesystem profile.
    #[must_use]
    pub const fn filesystem(&self) -> QualifiedFilesystem {
        self.filesystem
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    fn same_object(self, other: Self) -> bool {
        self.device == other.device && self.inode == other.inode
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    fn same_directory_security_identity(self, other: Self) -> bool {
        self.same_object(other)
            && self.mode == other.mode
            && self.uid == other.uid
            && self.gid == other.gid
            && self.mount_identity == other.mount_identity
            && self.filesystem == other.filesystem
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    fn same_file_security_identity(self, other: Self) -> bool {
        self.same_directory_security_identity(other) && self.hard_links == other.hard_links
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    fn same_control_anchor_identity(self, other: Self) -> bool {
        self.same_file_security_identity(other) && self.byte_len == other.byte_len
    }

    #[cfg(target_os = "linux")]
    fn mutation_stable_eq(self, other: Self) -> bool {
        self.same_file_security_identity(other)
            && self.byte_len == other.byte_len
            && self.modified_seconds == other.modified_seconds
            && self.modified_nanoseconds == other.modified_nanoseconds
            && self.changed_seconds == other.changed_seconds
            && self.changed_nanoseconds == other.changed_nanoseconds
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn mutation_stable_eq(self, other: Self) -> bool {
        self.same_file_security_identity(other)
            && self.byte_len == other.byte_len
            && self.modified_seconds == other.modified_seconds
            && self.modified_nanoseconds == other.modified_nanoseconds
            && self.changed_seconds == other.changed_seconds
            && self.changed_nanoseconds == other.changed_nanoseconds
    }
}

/// Fixed physical layout of the named generation-root control anchors.
///
/// The authority length is frozen by the generation-root protocol. The LOCK
/// length is supplied by the separately versioned owner/attempt-frame codec;
/// this platform layer neither parses nor authenticates those frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GenerationRootAnchorLayout {
    lock_byte_len: u64,
}

impl GenerationRootAnchorLayout {
    /// Construct a bounded, non-empty named-anchor layout.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::ResourceLimit`] when the LOCK image
    /// is empty or exceeds [`GENERATION_ROOT_MAX_CONTROL_FILE_BYTES`].
    pub fn new(lock_byte_len: u64) -> GenerationRootResult<Self> {
        if lock_byte_len == 0 || lock_byte_len > GENERATION_ROOT_MAX_CONTROL_FILE_BYTES {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ResourceLimit,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(GENERATION_ROOT_MAX_CONTROL_FILE_BYTES, lock_byte_len));
        }
        Ok(Self { lock_byte_len })
    }

    /// Exact LOCK byte length supplied by the owner/attempt-frame codec.
    #[must_use]
    pub const fn lock_byte_len(&self) -> u64 {
        self.lock_byte_len
    }

    /// Frozen physical AUTHORITY byte length.
    #[must_use]
    pub const fn authority_byte_len(&self) -> u64 {
        GENERATION_ROOT_AUTHORITY_FILE_BYTES
    }
}

/// One descriptor-derived root/LOCK/AUTHORITY identity tuple.
///
/// This attests the retained physical objects, not the semantic validity of
/// either mutable control image. Content authority is exposed only through a
/// live read or writer guard.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GenerationRootAnchorWitness {
    root: GenerationRootObjectWitness,
    lock: GenerationRootObjectWitness,
    authority: GenerationRootObjectWitness,
}

impl GenerationRootAnchorWitness {
    const fn new(
        root: GenerationRootObjectWitness,
        lock: GenerationRootObjectWitness,
        authority: GenerationRootObjectWitness,
    ) -> Self {
        Self {
            root,
            lock,
            authority,
        }
    }

    /// Qualified generation-root directory witness.
    #[must_use]
    pub const fn root(&self) -> GenerationRootObjectWitness {
        self.root
    }

    /// Retained named LOCK witness.
    #[must_use]
    pub const fn lock(&self) -> GenerationRootObjectWitness {
        self.lock
    }

    /// Retained named AUTHORITY witness.
    #[must_use]
    pub const fn authority(&self) -> GenerationRootObjectWitness {
        self.authority
    }
}

/// Sealed role for an admitted generation file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GenerationFileRole {
    /// Immutable artifact, sealed read-only for its owner.
    ImmutableArtifact,
    /// Fixed-size control anchor whose future in-place writes require a
    /// publisher API that advances the admitted witness while holding the
    /// kernel lock.
    ///
    /// This qualification substrate exposes no write operation and rejects
    /// ambient mutation fail-closed.
    MutableControl,
}

/// Exact expected generation-file identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GenerationFileExpectation {
    byte_len: u64,
    sha256: Option<[u8; 32]>,
    role: GenerationFileRole,
}

impl GenerationFileExpectation {
    /// Expect an exact length and SHA-256, subject to the global ceiling.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::ResourceLimit`] when `byte_len`
    /// exceeds [`GENERATION_ROOT_MAX_FILE_BYTES`].
    pub fn immutable(byte_len: u64, sha256: [u8; 32]) -> GenerationRootResult<Self> {
        Self::new(
            byte_len,
            Some(sha256),
            GenerationFileRole::ImmutableArtifact,
        )
    }

    /// Expect the current exact control-file length without precommitting its
    /// content.
    ///
    /// This substrate admits and locks the unchanged image only. A later
    /// publisher must use a witness-advancing mutation API rather than changing
    /// the file through an ambient descriptor.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::ResourceLimit`] when `byte_len`
    /// exceeds [`GENERATION_ROOT_MAX_CONTROL_FILE_BYTES`].
    pub fn control(byte_len: u64) -> GenerationRootResult<Self> {
        Self::new(byte_len, None, GenerationFileRole::MutableControl)
    }

    /// Expect an exact control-file length and SHA-256 at lock acquisition.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::ResourceLimit`] when `byte_len`
    /// exceeds [`GENERATION_ROOT_MAX_CONTROL_FILE_BYTES`].
    pub fn control_with_sha256(byte_len: u64, sha256: [u8; 32]) -> GenerationRootResult<Self> {
        Self::new(byte_len, Some(sha256), GenerationFileRole::MutableControl)
    }

    fn new(
        byte_len: u64,
        sha256: Option<[u8; 32]>,
        role: GenerationFileRole,
    ) -> GenerationRootResult<Self> {
        let max_byte_len = match role {
            GenerationFileRole::ImmutableArtifact => GENERATION_ROOT_MAX_FILE_BYTES,
            GenerationFileRole::MutableControl => GENERATION_ROOT_MAX_CONTROL_FILE_BYTES,
        };
        if byte_len > max_byte_len {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ResourceLimit,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(max_byte_len, byte_len));
        }
        Ok(Self {
            byte_len,
            sha256,
            role,
        })
    }

    /// Exact expected byte length.
    #[must_use]
    pub const fn byte_len(&self) -> u64 {
        self.byte_len
    }

    /// Optional expected SHA-256.
    #[must_use]
    pub const fn sha256(&self) -> Option<[u8; 32]> {
        self.sha256
    }

    /// Sealed file role.
    #[must_use]
    pub const fn role(&self) -> GenerationFileRole {
        self.role
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    const fn max_byte_len(self) -> u64 {
        match self.role {
            GenerationFileRole::ImmutableArtifact => GENERATION_ROOT_MAX_FILE_BYTES,
            GenerationFileRole::MutableControl => GENERATION_ROOT_MAX_CONTROL_FILE_BYTES,
        }
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    const fn expected_mode(self) -> u32 {
        match self.role {
            GenerationFileRole::ImmutableArtifact => GENERATION_ROOT_IMMUTABLE_FILE_MODE,
            GenerationFileRole::MutableControl => GENERATION_ROOT_CONTROL_FILE_MODE,
        }
    }
}

/// A bounded, strictly relative path under a qualified generation root.
#[derive(Clone)]
pub struct ConfinedGenerationPath {
    inner: platform::RelativePath,
}

impl ConfinedGenerationPath {
    /// Parse a non-empty relative path without dot, dot-dot, root, prefix,
    /// empty, oversized, or NUL-containing components.
    ///
    /// Unsupported targets return
    /// [`GenerationRootErrorKind::UnsupportedPlatform`] before filesystem I/O.
    ///
    /// # Errors
    ///
    /// Returns a bounded route or platform error.
    pub fn parse(path: &Path) -> GenerationRootResult<Self> {
        platform::parse_relative(path).map(|inner| Self { inner })
    }

    /// Number of relative components.
    #[must_use]
    pub fn component_count(&self) -> usize {
        platform::relative_component_count(&self.inner)
    }
}

impl fmt::Debug for ConfinedGenerationPath {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ConfinedGenerationPath")
            .field("component_count", &self.component_count())
            .finish_non_exhaustive()
    }
}

/// Internal qualified directory capability used while atomically binding the
/// named LOCK and AUTHORITY anchors.
struct QualifiedGenerationDirectory {
    inner: platform::RootHandle,
}

impl QualifiedGenerationDirectory {
    /// Admit an existing absolute private generation-root route.
    ///
    /// The route is walked component-by-component without following links,
    /// then independently re-resolved before this function returns.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed error for any route, security, mount,
    /// filesystem, ACL, kernel-feature, or identity uncertainty. Unsupported
    /// targets fail with [`GenerationRootErrorKind::UnsupportedPlatform`]
    /// before route parsing or filesystem I/O.
    fn admit(path: &Path) -> GenerationRootResult<Self> {
        platform::admit_root(path).map(|inner| Self { inner })
    }

    /// Root descriptor witness.
    #[must_use]
    fn witness(&self) -> GenerationRootObjectWitness {
        platform::root_witness(&self.inner)
    }

    /// Re-resolve the canonical route and require it to name the retained
    /// private root.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::ObjectChanged`] or the precise
    /// qualification failure when the route no longer resolves identically.
    #[cfg(all(test, target_os = "linux"))]
    fn revalidate_route(&self) -> GenerationRootResult<()> {
        platform::revalidate_root(&self.inner)
    }

    /// Admit one exact regular-file image below this root.
    ///
    /// The returned owner retains the qualified data descriptor and one immutable
    /// `Arc<[u8]>`; header validation and search consumers can therefore use
    /// the same allocation after route replacement. On Linux the data
    /// descriptor is derived from a retained, fully qualified `O_PATH`
    /// capability through the verified `/proc/thread-self/fd` bridge
    /// documented at module level; it is not opened from the generation route
    /// before the final object is proven regular.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed error for any route, mount, type, owner,
    /// mode, link-count, length, content, or before/after identity mismatch.
    /// On Apple Silicon this path-only API always returns
    /// [`GenerationRootErrorKind::PreopenedDescriptorRequired`]; use
    /// [`Self::admit_preopened_file`].
    #[cfg_attr(
        all(target_os = "macos", target_arch = "aarch64"),
        allow(clippy::unused_self)
    )]
    fn admit_file(
        &self,
        path: &ConfinedGenerationPath,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationFile> {
        if expectation.role != GenerationFileRole::ImmutableArtifact {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::WrongRole,
                GenerationRootStage::OpenRegularFile,
            ));
        }
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            let _ = path;
            Err(GenerationRootError::new(
                GenerationRootErrorKind::PreopenedDescriptorRequired,
                GenerationRootStage::OpenRegularFile,
            ))
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        {
            let admission = platform::admit_file(&self.inner, &path.inner, expectation)?;
            Ok(QualifiedGenerationFile {
                handle: admission.handle,
                bytes: admission.bytes,
                witness: admission.witness,
                sha256: admission.sha256,
            })
        }
    }

    /// Admit an exact Apple Silicon generation artifact from a descriptor
    /// already opened by a trusted external provider.
    ///
    /// The provider owns the proof that descriptor acquisition itself had no
    /// vnode/device side effects and attests that the descriptor is fresh,
    /// solely transferred, and has no retained duplicate or separately opened
    /// writable alias; POSIX descriptor inspection cannot verify those facts.
    /// This library first rejects non-regular descriptors and proves exact
    /// access status plus `FD_CLOEXEC`; it then qualifies the retained
    /// descriptor's mount, owner, permissions, link count, flags, ACL, and
    /// size before binding the canonical route and reading the exact content.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed error for any descriptor, route, security,
    /// identity, content, or resource uncertainty.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn admit_preopened_file(
        &self,
        path: &ConfinedGenerationPath,
        descriptor: std::os::fd::OwnedFd,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationFile> {
        if expectation.role != GenerationFileRole::ImmutableArtifact {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::WrongRole,
                GenerationRootStage::OpenRegularFile,
            ));
        }
        let admission =
            platform::admit_preopened_file(&self.inner, &path.inner, descriptor, expectation)?;
        Ok(QualifiedGenerationFile {
            handle: admission.handle,
            bytes: admission.bytes,
            witness: admission.witness,
            sha256: admission.sha256,
        })
    }

    /// Apply the platform's strongest required directory durability barrier.
    ///
    /// Linux uses `fsync`; Apple Silicon uses `F_FULLFSYNC` and never
    /// downgrades to `fsync`.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::DurabilityUnavailable`] when the
    /// required primitive fails.
    fn sync_directory_durable(&self) -> GenerationRootResult<()> {
        platform::sync_root_directory(&self.inner)
    }

    /// Admit an existing fixed-size private control anchor as a persistent
    /// descriptor-owned capability.
    ///
    /// This foundation API deliberately exposes no mutation operation.
    /// Ambient content or metadata changes invalidate the capability. The
    /// publisher layer must add a lock-owned, witness-advancing write protocol
    /// for AUTHORITY/LOCK frames.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed error for any route, mount, type, owner,
    /// mode, link-count, length, or identity mismatch. On Apple Silicon this
    /// path-only API always returns
    /// [`GenerationRootErrorKind::PreopenedDescriptorRequired`]; use
    /// [`Self::admit_preopened_control_file`].
    #[cfg_attr(
        all(target_os = "macos", target_arch = "aarch64"),
        allow(clippy::unused_self)
    )]
    fn admit_control_file(
        &self,
        path: &ConfinedGenerationPath,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationControlFile> {
        if expectation.role != GenerationFileRole::MutableControl {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::WrongRole,
                GenerationRootStage::OpenRegularFile,
            ));
        }
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            let _ = path;
            Err(GenerationRootError::new(
                GenerationRootErrorKind::PreopenedDescriptorRequired,
                GenerationRootStage::OpenRegularFile,
            ))
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        {
            platform::admit_control_file(&self.inner, &path.inner, expectation)
                .map(|inner| QualifiedGenerationControlFile { inner })
        }
    }

    /// Admit an Apple Silicon control anchor from a provider-owned descriptor.
    ///
    /// The provider owns no-side-effect acquisition provenance. The supplied
    /// descriptor must be a fresh read-write, close-on-exec open description;
    /// future lock acquisition requires another independently opened
    /// descriptor through [`QualifiedGenerationControlFile::try_lock_preopened`].
    /// Freshness and sole ownership are trusted provider attestations: POSIX
    /// descriptor inspection cannot detect an unseen `dup`.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed error for any descriptor, route, security,
    /// identity, content, or resource uncertainty.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn admit_preopened_control_file(
        &self,
        path: &ConfinedGenerationPath,
        descriptor: std::os::fd::OwnedFd,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationControlFile> {
        if expectation.role != GenerationFileRole::MutableControl {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::WrongRole,
                GenerationRootStage::OpenRegularFile,
            ));
        }
        platform::admit_preopened_control_file(&self.inner, &path.inner, descriptor, expectation)
            .map(|inner| QualifiedGenerationControlFile { inner })
    }
}

/// Provider-owned Apple Silicon descriptors for the two fixed control
/// anchors.
///
/// The trusted provider must transfer fresh, solely owned, read-write,
/// close-on-exec descriptors for the exact top-level LOCK and AUTHORITY files.
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
pub struct PreopenedGenerationRootAnchors {
    lock: std::os::fd::OwnedFd,
    authority: std::os::fd::OwnedFd,
}

#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
impl PreopenedGenerationRootAnchors {
    /// Bind provider-labelled LOCK and AUTHORITY descriptors without exposing
    /// an order-dependent tuple at the root-admission call site.
    #[must_use]
    pub fn new(lock: std::os::fd::OwnedFd, authority: std::os::fd::OwnedFd) -> Self {
        Self { lock, authority }
    }
}

/// Qualified generation root with retained exact-name LOCK and AUTHORITY
/// descriptors.
///
/// Construction returns only after the root and both anchors have passed a
/// combined anti-mix fence. Mutable control content is deliberately not frozen
/// into this long-lived capability: each shared or exclusive guard captures a
/// fresh exact owned image while holding the named LOCK flock.
pub struct QualifiedGenerationRoot {
    directory: QualifiedGenerationDirectory,
    lock: QualifiedGenerationControlFile,
    authority: QualifiedGenerationControlFile,
    layout: GenerationRootAnchorLayout,
}

impl QualifiedGenerationRoot {
    /// Admit an existing private root and its exact top-level LOCK and
    /// AUTHORITY anchors.
    ///
    /// Linux opens both anchors descriptor-relatively. Apple Silicon returns
    /// [`GenerationRootErrorKind::PreopenedDescriptorRequired`]; use
    /// [`Self::admit_preopened`]. Unsupported targets fail before path parsing
    /// or filesystem I/O.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed platform, route, security, filesystem,
    /// anchor-identity, length, or content-admission error.
    pub fn admit(path: &Path, layout: GenerationRootAnchorLayout) -> GenerationRootResult<Self> {
        let directory = QualifiedGenerationDirectory::admit(path)?;
        let lock_path = ConfinedGenerationPath::parse(Path::new(GENERATION_ROOT_LOCK_FILE_NAME))?;
        let authority_path =
            ConfinedGenerationPath::parse(Path::new(GENERATION_ROOT_AUTHORITY_FILE_NAME))?;
        let lock = directory.admit_control_file(
            &lock_path,
            GenerationFileExpectation::control(layout.lock_byte_len())?,
        )?;
        let authority = directory.admit_control_file(
            &authority_path,
            GenerationFileExpectation::control(layout.authority_byte_len())?,
        )?;
        let admitted = Self {
            directory,
            lock,
            authority,
            layout,
        };
        admitted.revalidate()?;
        Ok(admitted)
    }

    /// Admit Apple Silicon named anchors from trusted provider-owned
    /// descriptors.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed descriptor, route, security, filesystem,
    /// anchor-identity, length, or content-admission error.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn admit_preopened(
        path: &Path,
        layout: GenerationRootAnchorLayout,
        anchors: PreopenedGenerationRootAnchors,
    ) -> GenerationRootResult<Self> {
        let directory = QualifiedGenerationDirectory::admit(path)?;
        let lock_path = ConfinedGenerationPath::parse(Path::new(GENERATION_ROOT_LOCK_FILE_NAME))?;
        let authority_path =
            ConfinedGenerationPath::parse(Path::new(GENERATION_ROOT_AUTHORITY_FILE_NAME))?;
        let lock = directory.admit_preopened_control_file(
            &lock_path,
            anchors.lock,
            GenerationFileExpectation::control(layout.lock_byte_len())?,
        )?;
        let authority = directory.admit_preopened_control_file(
            &authority_path,
            anchors.authority,
            GenerationFileExpectation::control(layout.authority_byte_len())?,
        )?;
        let admitted = Self {
            directory,
            lock,
            authority,
            layout,
        };
        admitted.revalidate()?;
        Ok(admitted)
    }

    /// Root descriptor witness.
    #[must_use]
    pub fn witness(&self) -> GenerationRootObjectWitness {
        self.directory.witness()
    }

    /// Descriptor-derived identity tuple retained by this root capability.
    #[must_use]
    pub fn anchor_witnesses(&self) -> GenerationRootAnchorWitness {
        GenerationRootAnchorWitness::new(
            self.directory.witness(),
            self.lock.witness(),
            self.authority.witness(),
        )
    }

    /// Frozen physical named-anchor layout.
    #[must_use]
    pub const fn anchor_layout(&self) -> GenerationRootAnchorLayout {
        self.layout
    }

    /// Revalidate the canonical root plus both retained named anchors as one
    /// anti-mix tuple.
    ///
    /// Mutable bytes, mtime, and ctime may advance between guards; object,
    /// route, mount, security, link, and fixed-length identity may not.
    ///
    /// # Errors
    ///
    /// Returns the precise fail-closed route or identity error.
    pub fn revalidate(&self) -> GenerationRootResult<()> {
        platform::revalidate_anchor_set(
            &self.directory.inner,
            &self.lock.inner,
            &self.authority.inner,
        )
    }

    /// Admit one exact immutable regular-file image below this root.
    ///
    /// # Errors
    ///
    /// Returns the same typed errors as descriptor-owned file admission.
    pub fn admit_file(
        &self,
        path: &ConfinedGenerationPath,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationFile> {
        self.directory.admit_file(path, expectation)
    }

    /// Admit one exact Apple Silicon immutable artifact from a provider-owned
    /// descriptor.
    ///
    /// # Errors
    ///
    /// Returns the same typed errors as preopened file admission.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn admit_preopened_file(
        &self,
        path: &ConfinedGenerationPath,
        descriptor: std::os::fd::OwnedFd,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<QualifiedGenerationFile> {
        self.directory
            .admit_preopened_file(path, descriptor, expectation)
    }

    /// Apply the platform's strongest required directory durability barrier.
    ///
    /// # Errors
    ///
    /// Returns a typed route, identity, or durability error.
    pub fn sync_directory_durable(&self) -> GenerationRootResult<()> {
        self.directory.sync_directory_durable()
    }

    /// Acquire a non-blocking shared guard on the exact named LOCK anchor and
    /// capture fresh stable LOCK and AUTHORITY images.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::LockContended`] instead of blocking,
    /// or the precise tuple/content failure. Apple Silicon requires
    /// [`Self::read_guard_preopened`].
    pub fn read_guard(&self) -> GenerationRootResult<GenerationRootReadGuard<'_>> {
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::PreopenedDescriptorRequired,
                GenerationRootStage::AcquireLock,
            ))
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        {
            let flock =
                platform::try_anchor_lock(&self.lock.inner, GenerationRootLockMode::Shared)?;
            self.finish_read_guard(flock)
        }
    }

    /// Acquire an Apple Silicon shared guard using a fresh provider-owned LOCK
    /// open description.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed descriptor, contention, tuple, or content
    /// error.
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub fn read_guard_preopened(
        &self,
        fresh_lock_descriptor: std::os::fd::OwnedFd,
    ) -> GenerationRootResult<GenerationRootReadGuard<'_>> {
        let flock = platform::try_anchor_lock_preopened(
            &self.lock.inner,
            fresh_lock_descriptor,
            GenerationRootLockMode::Shared,
        )?;
        self.finish_read_guard(flock)
    }

    fn finish_read_guard(
        &self,
        flock: platform::LockHandle,
    ) -> GenerationRootResult<GenerationRootReadGuard<'_>> {
        let (lock_image, authority_image) = self.capture_stable_anchor_images()?;
        Ok(GenerationRootReadGuard {
            root: self,
            flock,
            lock_image,
            authority_image,
        })
    }

    fn capture_stable_anchor_images(
        &self,
    ) -> GenerationRootResult<(platform::AnchorImage, platform::AnchorImage)> {
        self.revalidate()?;
        let first_lock = platform::capture_anchor_image(&self.lock.inner)?;
        let first_authority = platform::capture_anchor_image(&self.authority.inner)?;
        self.revalidate()?;
        let second_lock = platform::capture_anchor_image(&self.lock.inner)?;
        let second_authority = platform::capture_anchor_image(&self.authority.inner)?;
        self.revalidate()?;
        if !platform::anchor_images_match(&first_lock, &second_lock)
            || !platform::anchor_images_match(&first_authority, &second_authority)
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        Ok((second_lock, second_authority))
    }

    // This deliberately lands one bead before the writer-lease consumer.
    #[allow(dead_code)]
    #[cfg_attr(
        all(target_os = "macos", target_arch = "aarch64"),
        allow(clippy::unused_self)
    )]
    pub(crate) fn try_exclusive_anchor_guard(
        &self,
    ) -> GenerationRootResult<GenerationRootExclusiveAnchorGuard<'_>> {
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::PreopenedDescriptorRequired,
                GenerationRootStage::AcquireLock,
            ))
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        {
            let flock =
                platform::try_anchor_lock(&self.lock.inner, GenerationRootLockMode::Exclusive)?;
            let (lock_image, authority_image) = self.capture_stable_anchor_images()?;
            Ok(GenerationRootExclusiveAnchorGuard {
                root: self,
                flock,
                lock_image,
                authority_image,
            })
        }
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    #[allow(dead_code)]
    pub(crate) fn try_exclusive_anchor_guard_preopened(
        &self,
        fresh_lock_descriptor: std::os::fd::OwnedFd,
    ) -> GenerationRootResult<GenerationRootExclusiveAnchorGuard<'_>> {
        let flock = platform::try_anchor_lock_preopened(
            &self.lock.inner,
            fresh_lock_descriptor,
            GenerationRootLockMode::Exclusive,
        )?;
        let (lock_image, authority_image) = self.capture_stable_anchor_images()?;
        Ok(GenerationRootExclusiveAnchorGuard {
            root: self,
            flock,
            lock_image,
            authority_image,
        })
    }
}

impl fmt::Debug for QualifiedGenerationRoot {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QualifiedGenerationRoot")
            .field("anchors", &self.anchor_witnesses())
            .finish_non_exhaustive()
    }
}

/// Shared named-anchor guard carrying fresh exact control images.
///
/// The guard cannot outlive the qualified root that owns the retained anchor
/// descriptors:
///
/// ```compile_fail
/// use frankensearch_index::generation_root::{
///     GenerationRootReadGuard, QualifiedGenerationRoot,
/// };
///
/// fn impossible(root: &QualifiedGenerationRoot) -> GenerationRootReadGuard<'static> {
///     root.read_guard().expect("type-checking must reject this lifetime")
/// }
/// ```
#[must_use = "dropping the guard releases the shared generation-root lock"]
pub struct GenerationRootReadGuard<'root> {
    root: &'root QualifiedGenerationRoot,
    flock: platform::LockHandle,
    lock_image: platform::AnchorImage,
    authority_image: platform::AnchorImage,
}

impl GenerationRootReadGuard<'_> {
    /// Root and fresh LOCK/AUTHORITY witnesses captured under the shared lock.
    #[must_use]
    pub fn witnesses(&self) -> GenerationRootAnchorWitness {
        GenerationRootAnchorWitness::new(
            self.root.witness(),
            self.lock_image.witness,
            self.authority_image.witness,
        )
    }

    /// Borrow the exact named LOCK image.
    #[must_use]
    pub fn lock_bytes(&self) -> &[u8] {
        &self.lock_image.bytes
    }

    /// Clone the exact named LOCK allocation.
    #[must_use]
    pub fn lock_bytes_arc(&self) -> Arc<[u8]> {
        Arc::clone(&self.lock_image.bytes)
    }

    /// SHA-256 of the exact named LOCK image.
    #[must_use]
    pub const fn lock_sha256(&self) -> [u8; 32] {
        self.lock_image.sha256
    }

    /// Borrow the exact named AUTHORITY image.
    #[must_use]
    pub fn authority_bytes(&self) -> &[u8] {
        &self.authority_image.bytes
    }

    /// Clone the exact named AUTHORITY allocation.
    #[must_use]
    pub fn authority_bytes_arc(&self) -> Arc<[u8]> {
        Arc::clone(&self.authority_image.bytes)
    }

    /// SHA-256 of the exact named AUTHORITY image.
    #[must_use]
    pub const fn authority_sha256(&self) -> [u8; 32] {
        self.authority_image.sha256
    }

    /// Validate both captured images and explicitly release the shared flock.
    ///
    /// Unlock is attempted even when validation detects ambient mutation.
    ///
    /// # Errors
    ///
    /// Returns a typed content, route, process, or unlock error.
    pub fn release(self) -> GenerationRootResult<()> {
        let validation = platform::validate_anchor_image(&self.root.lock.inner, &self.lock_image)
            .and_then(|()| {
                platform::validate_anchor_image(&self.root.authority.inner, &self.authority_image)
            });
        let unlock = platform::unlock(self.flock);
        validation.and(unlock)
    }
}

impl fmt::Debug for GenerationRootReadGuard<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GenerationRootReadGuard")
            .field("witnesses", &self.witnesses())
            .finish_non_exhaustive()
    }
}

/// Crate-private kernel primitive consumed by the later shared-index writer
/// lease. This is not itself a lease and exposes no mutation operation.
#[must_use = "dropping the guard releases the exclusive generation-root lock"]
#[allow(dead_code)]
pub(crate) struct GenerationRootExclusiveAnchorGuard<'root> {
    root: &'root QualifiedGenerationRoot,
    flock: platform::LockHandle,
    lock_image: platform::AnchorImage,
    authority_image: platform::AnchorImage,
}

impl GenerationRootExclusiveAnchorGuard<'_> {
    #[allow(dead_code)]
    pub(crate) fn release(self) -> GenerationRootResult<()> {
        platform::unlock(self.flock)
    }
}

impl fmt::Debug for GenerationRootExclusiveAnchorGuard<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GenerationRootExclusiveAnchorGuard")
            .field("root", &self.root.anchor_witnesses())
            .field("lock_sha256", &self.lock_image.sha256)
            .field("authority_sha256", &self.authority_image.sha256)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for QualifiedGenerationDirectory {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QualifiedGenerationDirectory")
            .field("witness", &self.witness())
            .finish_non_exhaustive()
    }
}

/// Retained descriptor plus the exact bytes admitted from it.
pub struct QualifiedGenerationFile {
    handle: platform::FileHandle,
    bytes: Arc<[u8]>,
    witness: GenerationRootObjectWitness,
    sha256: [u8; 32],
}

impl QualifiedGenerationFile {
    /// Borrow the exact owned byte image.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Clone the exact owned byte allocation for a descriptor-independent
    /// consumer such as `ValidatedFsviBytes::from_arc`.
    #[must_use]
    pub fn bytes(&self) -> Arc<[u8]> {
        Arc::clone(&self.bytes)
    }

    /// Descriptor witness captured after complete admission.
    #[must_use]
    pub const fn witness(&self) -> GenerationRootObjectWitness {
        self.witness
    }

    /// SHA-256 of the exact owned byte image.
    #[must_use]
    pub const fn sha256(&self) -> [u8; 32] {
        self.sha256
    }

    /// Apply the platform's strongest required regular-file durability
    /// barrier to the retained descriptor.
    ///
    /// The descriptor is read and SHA-256 checked against the admitted exact
    /// image both before and after the barrier. This explicit operation
    /// therefore performs two full-file reads.
    ///
    /// # Errors
    ///
    /// Returns a typed route, identity, or durability error. A required
    /// durability primitive never falls back to a weaker barrier.
    pub fn sync_durable(&self) -> GenerationRootResult<()> {
        platform::sync_file(&self.handle, self.witness)
    }
}

impl fmt::Debug for QualifiedGenerationFile {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QualifiedGenerationFile")
            .field("witness", &self.witness)
            .finish_non_exhaustive()
    }
}

/// Internal qualified capability for one mutable private control anchor.
struct QualifiedGenerationControlFile {
    inner: platform::ControlHandle,
}

impl QualifiedGenerationControlFile {
    /// Object/metadata witness captured when this control file was admitted.
    ///
    /// This does not attest mutable content; the fixed named-anchor guards
    /// capture a fresh exact image while holding the kernel flock.
    #[must_use]
    fn witness(&self) -> GenerationRootObjectWitness {
        platform::control_witness(&self.inner)
    }

    /// Clone the exact descriptor-admitted control-file image.
    #[must_use]
    #[cfg(test)]
    fn bytes(&self) -> Arc<[u8]> {
        platform::control_bytes(&self.inner)
    }

    /// SHA-256 of the exact descriptor-admitted control-file image.
    #[must_use]
    #[cfg(test)]
    fn sha256(&self) -> [u8; 32] {
        platform::control_sha256(&self.inner)
    }

    /// Attempt a shared or exclusive non-blocking kernel lock on this exact
    /// qualified control-file identity.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationRootErrorKind::LockContended`] rather than
    /// blocking. Route replacement, process-identity drift, and all normal
    /// file-admission errors remain fail-closed.
    #[cfg(test)]
    #[cfg_attr(
        all(target_os = "macos", target_arch = "aarch64"),
        allow(clippy::unused_self)
    )]
    fn try_lock(&self, mode: GenerationRootLockMode) -> GenerationRootResult<GenerationRootLock> {
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        {
            let _ = mode;
            Err(GenerationRootError::new(
                GenerationRootErrorKind::PreopenedDescriptorRequired,
                GenerationRootStage::AcquireLock,
            ))
        }
        #[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
        {
            platform::try_lock(&self.inner, mode).map(|inner| GenerationRootLock { inner })
        }
    }

    /// Attempt an Apple Silicon lock using a fresh provider-owned open
    /// description for the exact admitted control object.
    ///
    /// A duplicated descriptor is not sufficient: `flock` state is attached
    /// to the open description. The external provider owns acquisition
    /// provenance; this method verifies descriptor type, access, route, and
    /// security before the non-blocking flock, then verifies the candidate's
    /// bound content only after flock succeeds. Exact Darwin status validation
    /// also rejects the persistent `FWASLOCKED` history bit left by a prior
    /// successful flock, but that defense does not prove the absence of unseen
    /// aliases. The provider must transfer the sole live reference and retain
    /// no duplicate. A surviving alias could convert or unlock the flock while
    /// this guard is live; creator-process drop and explicit unlock
    /// nevertheless issue `LOCK_UN` so an inherited alias cannot prolong the
    /// guard after release.
    ///
    /// # Errors
    ///
    /// Returns a typed fail-closed descriptor/admission error or
    /// [`GenerationRootErrorKind::LockContended`].
    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    fn try_lock_preopened(
        &self,
        descriptor: std::os::fd::OwnedFd,
        mode: GenerationRootLockMode,
    ) -> GenerationRootResult<GenerationRootLock> {
        platform::try_lock_preopened(&self.inner, descriptor, mode)
            .map(|inner| GenerationRootLock { inner })
    }
}

impl fmt::Debug for QualifiedGenerationControlFile {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("QualifiedGenerationControlFile")
            .field("witness", &self.witness())
            .finish_non_exhaustive()
    }
}

/// Internal requested kernel lock mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum GenerationRootLockMode {
    /// Reader/shared lock.
    Shared,
    /// Writer/exclusive lock.
    #[allow(dead_code)]
    Exclusive,
}

/// Owned non-blocking kernel lock guard.
///
/// In the creator process, dropping the guard issues a best-effort explicit
/// `LOCK_UN` before closing the descriptor. This releases the open-description
/// lock even when a forked child still retains an inherited descriptor.
/// A child-side drop never unlocks the creator's guard. [`Self::unlock`]
/// reports explicit validation or unlock failures.
///
/// Applications must not continue normal multithreaded library execution
/// across `fork()`: the child may only close inherited capabilities or `exec`.
/// Operations that revalidate, synchronize, or unlock in a child fail with
/// [`GenerationRootErrorKind::ForkedProcess`].
#[must_use = "holding this guard keeps the kernel lock acquired"]
#[cfg(test)]
struct GenerationRootLock {
    inner: platform::LockHandle,
}

#[cfg(test)]
impl GenerationRootLock {
    /// Object/metadata witness bound to this lock.
    ///
    /// This does not attest content. Use [`Self::sha256`] or [`Self::bytes`]
    /// for the exact locked image.
    #[must_use]
    fn witness(&self) -> GenerationRootObjectWitness {
        platform::lock_witness(&self.inner)
    }

    /// Clone the exact control-file image validated while the lock was held.
    #[must_use]
    fn bytes(&self) -> Arc<[u8]> {
        platform::lock_bytes(&self.inner)
    }

    /// SHA-256 of the exact control-file image validated while the lock was
    /// held.
    #[must_use]
    fn sha256(&self) -> [u8; 32] {
        platform::lock_sha256(&self.inner)
    }

    /// Lock mode bound to this guard.
    #[must_use]
    fn mode(&self) -> GenerationRootLockMode {
        platform::lock_mode(&self.inner)
    }

    /// Explicitly release this lock.
    ///
    /// # Errors
    ///
    /// Returns a typed process, content, route, or OS error. Explicit
    /// creator-process `LOCK_UN` is the primary release boundary; creator-side
    /// drop retries it best-effort after a reported failure. Closing the owned
    /// descriptor is only a fallback when no inherited or duplicated
    /// open-description reference survives.
    fn unlock(self) -> GenerationRootResult<()> {
        platform::unlock(self.inner)
    }

    /// Apply the required file durability barrier to the locked control file.
    ///
    /// This synchronizes the unchanged admitted image. It neither authorizes
    /// nor absorbs an ambient mutation.
    ///
    /// # Errors
    ///
    /// Returns a typed process, content, route, identity, or durability error.
    /// A required durability primitive never falls back to a weaker barrier.
    fn sync_durable(&self) -> GenerationRootResult<()> {
        platform::sync_lock_file(&self.inner)
    }
}

#[cfg(test)]
impl fmt::Debug for GenerationRootLock {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GenerationRootLock")
            .field("held", &true)
            .finish_non_exhaustive()
    }
}

#[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
mod platform {
    #[cfg(target_os = "linux")]
    use super::GENERATION_ROOT_MAX_MOUNTINFO_BYTES;
    use super::{
        GENERATION_ROOT_AUTHORITY_FILE_NAME, GENERATION_ROOT_DIRECTORY_MODE,
        GENERATION_ROOT_LOCK_FILE_NAME, GENERATION_ROOT_MAX_COMPONENT_BYTES,
        GENERATION_ROOT_MAX_COMPONENTS, GENERATION_ROOT_MAX_DIRECTORY_ENTRIES,
        GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES, GENERATION_ROOT_MAX_ROUTE_BYTES,
        GenerationFileExpectation, GenerationRootError, GenerationRootErrorKind,
        GenerationRootLockMode, GenerationRootObjectWitness, GenerationRootResult,
        GenerationRootStage, QualifiedFilesystem,
    };
    use rustix::fd::{AsFd, OwnedFd};
    use rustix::fs::{FileType, Mode, OFlags, fstat, fstatfs, fstatvfs};
    use rustix::io::{Errno, pread};
    use sha2::{Digest, Sha256};
    use std::ffi::{OsStr, OsString};
    use std::fmt;
    use std::os::unix::ffi::OsStrExt;
    use std::path::Path;
    use std::sync::Arc;

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    use rustix::fs::openat;
    #[cfg(target_os = "linux")]
    use std::os::fd::{AsRawFd, RawFd};

    const MODE_PERMISSIONS_MASK: u32 = 0o7777;
    #[cfg(target_os = "linux")]
    const LINUX_STATX_SUBVOLUME_MASK: u32 = 0x0000_8000;

    #[cfg(target_os = "linux")]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) enum ProcSelfBindingPhase {
        RootQualification,
        MountInfoRead,
        BeforeDataOpen,
        AfterDataOpen,
    }

    #[cfg(target_os = "linux")]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) enum ProcBridgeProbePhase {
        BeforeDataOpen,
        AfterDataOpen,
    }

    #[cfg(test)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) enum TestBoundary {
        AfterFirstRootQualification,
        BeforeAbsoluteAncestorAclRead {
            index: Option<usize>,
        },
        AfterAbsoluteAncestorAclRead {
            index: Option<usize>,
        },
        BeforeRootComponentOpen {
            index: usize,
        },
        AfterRootComponentOpen {
            index: usize,
        },
        BeforeRelativeDirectoryOpen {
            index: usize,
        },
        AfterRelativeDirectoryOpen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        BeforeRegularFileOpen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        AfterRegularFileOpen {
            index: usize,
            cloexec: bool,
        },
        BeforeRootDescriptorDuplicate,
        AfterRootDescriptorDuplicate,
        #[cfg(target_os = "linux")]
        AfterQualifiedFileOpen,
        BeforeRead {
            offset: u64,
        },
        AfterRead {
            offset: u64,
            byte_count: usize,
        },
        BeforeTrailingByteProbe,
        AfterTrailingByteProbe {
            byte_count: usize,
        },
        AfterExactRead,
        #[cfg(target_os = "linux")]
        BeforeFileRouteReopen,
        #[cfg(target_os = "linux")]
        AfterFileRouteReopen,
        #[cfg(target_os = "linux")]
        BeforeFinalRootRevalidation,
        BeforeFilesystemQualification,
        AfterFilesystemQualification,
        BeforeRouteMountIdentity,
        AfterRouteMountIdentity,
        BeforeObjectWitness,
        AfterObjectWitness,
        #[cfg(target_os = "linux")]
        BeforeMountInfoOpen,
        #[cfg(target_os = "linux")]
        AfterMountInfoOpen,
        #[cfg(target_os = "linux")]
        BeforeMountInfoRead,
        #[cfg(target_os = "linux")]
        AfterMountInfoRead {
            byte_count: usize,
        },
        #[cfg(target_os = "linux")]
        BeforeFinalProbeOpen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        AfterFinalProbeOpen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        AfterProbeQualified {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        BeforeProcCapabilityRootOpen,
        #[cfg(target_os = "linux")]
        AfterProcCapabilityRootOpen,
        #[cfg(target_os = "linux")]
        BeforeProcSelfReadlink {
            phase: ProcSelfBindingPhase,
        },
        #[cfg(target_os = "linux")]
        AfterProcSelfReadlink {
            phase: ProcSelfBindingPhase,
        },
        #[cfg(target_os = "linux")]
        BeforeProcThreadSelfReadlink {
            phase: ProcSelfBindingPhase,
        },
        #[cfg(target_os = "linux")]
        AfterProcThreadSelfReadlink {
            phase: ProcSelfBindingPhase,
        },
        #[cfg(target_os = "linux")]
        BeforeProcBridgeProbe {
            index: usize,
            phase: ProcBridgeProbePhase,
        },
        #[cfg(target_os = "linux")]
        AfterProcBridgeProbe {
            index: usize,
            phase: ProcBridgeProbePhase,
        },
        #[cfg(target_os = "linux")]
        BeforeProcFdReopen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        AfterProcFdReopen {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        BeforeFinalRouteProbe {
            index: usize,
        },
        #[cfg(target_os = "linux")]
        AfterFinalRouteProbe {
            index: usize,
        },
        BeforeLock,
        AfterLock,
        BeforeUnlock,
        AfterUnlock,
        BeforeFileSync,
        AfterFileSync,
        BeforeDirectorySync,
        AfterDirectorySync,
        BeforeExactNameEnumeration,
        AfterExactNameEnumeration,
        BeforeAclRead,
        AfterAclRead,
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        BeforePreopenedQualification,
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        AfterPreopenedQualification,
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        BeforeFinalRouteStat,
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        AfterFinalRouteStat,
    }

    #[cfg(test)]
    type TestHook = Box<dyn FnMut(TestBoundary) -> GenerationRootResult<()>>;

    #[cfg(test)]
    std::thread_local! {
        static TEST_HOOK: std::cell::RefCell<Option<TestHook>> =
            const { std::cell::RefCell::new(None) };
    }

    #[cfg(test)]
    pub(super) struct TestHookGuard;

    #[cfg(test)]
    impl Drop for TestHookGuard {
        fn drop(&mut self) {
            TEST_HOOK.with(|slot| {
                slot.borrow_mut().take();
            });
        }
    }

    #[cfg(test)]
    pub(super) fn install_test_hook(
        hook: impl FnMut(TestBoundary) -> GenerationRootResult<()> + 'static,
    ) -> TestHookGuard {
        TEST_HOOK.with(|slot| {
            let replaced = slot.borrow_mut().replace(Box::new(hook));
            assert!(
                replaced.is_none(),
                "only one test hook may be active per thread"
            );
        });
        TestHookGuard
    }

    #[cfg(test)]
    fn test_boundary(boundary: TestBoundary) -> GenerationRootResult<()> {
        TEST_HOOK.with(|slot| {
            let mut slot = slot.borrow_mut();
            slot.as_mut().map_or(Ok(()), |hook| hook(boundary))
        })
    }

    #[derive(Clone)]
    pub(super) struct RelativePath {
        components: Arc<[OsString]>,
    }

    #[derive(Clone)]
    pub(super) struct RootHandle {
        state: Arc<RootState>,
    }

    struct RootState {
        route: AbsoluteRoute,
        descriptor: OwnedFd,
        witness: GenerationRootObjectWitness,
        route_identities: Arc<[BasicObjectIdentity]>,
        creator_process_id: u32,
    }

    pub(super) struct FileHandle {
        descriptor: OwnedFd,
        root: RootHandle,
        path: RelativePath,
        expectation: GenerationFileExpectation,
        content_witness: ExactContentWitness,
        component_identities: Arc<[BasicObjectIdentity]>,
    }

    pub(super) struct FileAdmission {
        pub(super) handle: FileHandle,
        pub(super) bytes: Arc<[u8]>,
        pub(super) witness: GenerationRootObjectWitness,
        pub(super) sha256: [u8; 32],
    }

    pub(super) struct ControlHandle {
        descriptor: OwnedFd,
        #[cfg(test)]
        bytes: Arc<[u8]>,
        root: RootHandle,
        path: RelativePath,
        expectation: GenerationFileExpectation,
        witness: GenerationRootObjectWitness,
        #[cfg(test)]
        content_witness: ExactContentWitness,
        component_identities: Arc<[BasicObjectIdentity]>,
    }

    pub(super) struct AnchorImage {
        pub(super) bytes: Arc<[u8]>,
        pub(super) witness: GenerationRootObjectWitness,
        pub(super) sha256: [u8; 32],
    }

    pub(super) struct LockHandle {
        descriptor: OwnedFd,
        #[cfg(test)]
        bytes: Arc<[u8]>,
        witness: GenerationRootObjectWitness,
        content_witness: ExactContentWitness,
        root: RootHandle,
        path: RelativePath,
        expectation: GenerationFileExpectation,
        component_identities: Arc<[BasicObjectIdentity]>,
        creator_process_id: u32,
        lock_held: bool,
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        descriptor_status_flags: OFlags,
        #[cfg(test)]
        mode: GenerationRootLockMode,
    }

    struct AcquiredFlockDescriptor {
        descriptor: Option<OwnedFd>,
        creator_process_id: u32,
    }

    impl AcquiredFlockDescriptor {
        fn new(descriptor: OwnedFd, creator_process_id: u32) -> Self {
            Self {
                descriptor: Some(descriptor),
                creator_process_id,
            }
        }

        fn descriptor(&self) -> &OwnedFd {
            let Some(descriptor) = self.descriptor.as_ref() else {
                unreachable!("an armed flock descriptor always owns its descriptor")
            };
            descriptor
        }

        fn into_descriptor(mut self) -> OwnedFd {
            let Some(descriptor) = self.descriptor.take() else {
                unreachable!("an armed flock descriptor transfers exactly once")
            };
            descriptor
        }
    }

    impl Drop for AcquiredFlockDescriptor {
        fn drop(&mut self) {
            if self.creator_process_id == std::process::id()
                && let Some(descriptor) = self.descriptor.as_ref()
            {
                let _ = rustix::fs::flock(descriptor, rustix::fs::FlockOperation::Unlock);
            }
        }
    }

    #[derive(Clone)]
    struct AbsoluteRoute {
        components: Arc<[OsString]>,
    }

    struct OpenedRoute {
        descriptor: OwnedFd,
        route_identities: Vec<BasicObjectIdentity>,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct BasicObjectIdentity {
        device: u64,
        inode: u64,
        mode: u32,
        uid: u32,
        gid: u32,
        mount_identity: [u8; 32],
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct AbsoluteAncestorSecurityWitness {
        identity: BasicObjectIdentity,
        changed_seconds: i64,
        changed_nanoseconds: i64,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct ExactContentWitness {
        sha256: [u8; 32],
    }

    impl fmt::Debug for RootHandle {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter
                .debug_struct("RootHandle")
                .field("witness", &self.state.witness)
                .finish_non_exhaustive()
        }
    }

    pub(super) fn parse_relative(path: &Path) -> GenerationRootResult<RelativePath> {
        let components = parse_route_bytes(
            path.as_os_str(),
            false,
            GenerationRootStage::ParseRelativeRoute,
        )?;
        Ok(RelativePath {
            components: Arc::from(components),
        })
    }

    pub(super) fn relative_component_count(path: &RelativePath) -> usize {
        path.components.len()
    }

    pub(super) fn admit_root(path: &Path) -> GenerationRootResult<RootHandle> {
        let creator_process_id = std::process::id();
        let route = AbsoluteRoute {
            components: Arc::from(parse_route_bytes(
                path.as_os_str(),
                true,
                GenerationRootStage::ParseRootRoute,
            )?),
        };
        let first = open_absolute_route(&route, GenerationRootStage::OpenRootRoute)?;
        let (filesystem, mount_identity) =
            qualify_filesystem(&first.descriptor, GenerationRootStage::QualifyFilesystem)?;
        let first_witness = object_witness(
            &first.descriptor,
            filesystem,
            mount_identity,
            GenerationRootStage::QualifyRootSecurity,
        )?;
        validate_private_directory(
            &first.descriptor,
            first_witness,
            GenerationRootStage::QualifyRootSecurity,
        )?;
        validate_root_writable(
            &first.descriptor,
            first_witness.filesystem,
            GenerationRootStage::QualifyFilesystem,
        )?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFirstRootQualification)?;

        let second = open_absolute_route(&route, GenerationRootStage::RevalidateRootRoute)?;
        if first.route_identities != second.route_identities {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRootRoute,
            ));
        }
        let (second_filesystem, second_mount_identity) =
            qualify_filesystem(&second.descriptor, GenerationRootStage::RevalidateRootRoute)?;
        let second_witness = object_witness(
            &second.descriptor,
            second_filesystem,
            second_mount_identity,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        validate_private_directory(
            &second.descriptor,
            second_witness,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        validate_root_writable(
            &second.descriptor,
            second_witness.filesystem,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        if !first_witness.same_directory_security_identity(second_witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRootRoute,
            ));
        }
        validate_process_identity(creator_process_id, GenerationRootStage::RevalidateRootRoute)?;

        Ok(RootHandle {
            state: Arc::new(RootState {
                route,
                descriptor: first.descriptor,
                witness: first_witness,
                route_identities: Arc::from(first.route_identities),
                creator_process_id,
            }),
        })
    }

    pub(super) fn root_witness(root: &RootHandle) -> GenerationRootObjectWitness {
        root.state.witness
    }

    pub(super) fn revalidate_root(root: &RootHandle) -> GenerationRootResult<()> {
        validate_process_identity(
            root.state.creator_process_id,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        let retained = object_witness(
            &root.state.descriptor,
            root.state.witness.filesystem,
            root.state.witness.mount_identity,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        if !retained.same_directory_security_identity(root.state.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRootRoute,
            ));
        }
        validate_private_directory(
            &root.state.descriptor,
            retained,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        validate_root_writable(
            &root.state.descriptor,
            retained.filesystem,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        let reopened =
            open_absolute_route(&root.state.route, GenerationRootStage::RevalidateRootRoute)?;
        if reopened.route_identities.as_slice() != root.state.route_identities.as_ref() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRootRoute,
            ));
        }
        let (filesystem, mount_identity) = qualify_filesystem(
            &reopened.descriptor,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        let reopened_witness = object_witness(
            &reopened.descriptor,
            filesystem,
            mount_identity,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        validate_private_directory(
            &reopened.descriptor,
            reopened_witness,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        validate_root_writable(
            &reopened.descriptor,
            reopened_witness.filesystem,
            GenerationRootStage::RevalidateRootRoute,
        )?;
        if !retained.same_directory_security_identity(reopened_witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRootRoute,
            ));
        }
        validate_process_identity(
            root.state.creator_process_id,
            GenerationRootStage::RevalidateRootRoute,
        )
    }

    #[cfg(target_os = "linux")]
    pub(super) fn admit_file(
        root: &RootHandle,
        path: &RelativePath,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<FileAdmission> {
        revalidate_root(root)?;
        let opened = open_relative_file(
            root,
            path,
            expectation,
            false,
            GenerationRootStage::OpenRelativeDirectory,
            GenerationRootStage::OpenRegularFile,
        )?;
        let (bytes, after_read) =
            read_exact_owned(&opened.descriptor, opened.witness, expectation)?;
        let sha256: [u8; 32] = Sha256::digest(&bytes).into();
        if let Some(expected_sha256) = expectation.sha256 {
            if sha256 != expected_sha256 {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::HashMismatch,
                    GenerationRootStage::ReadRegularFile,
                ));
            }
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFileRouteReopen)?;
        let reopened = open_relative_probe(
            root,
            path,
            expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFileRouteReopen)?;
        if !after_read.mutation_stable_eq(reopened.witness)
            || opened.component_identities != reopened.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFinalRootRevalidation)?;
        revalidate_root(root)?;
        Ok(FileAdmission {
            handle: FileHandle {
                descriptor: opened.descriptor,
                root: root.clone(),
                path: path.clone(),
                expectation,
                content_witness: ExactContentWitness { sha256 },
                component_identities: opened.component_identities,
            },
            bytes: Arc::from(bytes),
            witness: after_read,
            sha256,
        })
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn admit_preopened_file(
        root: &RootHandle,
        path: &RelativePath,
        descriptor: OwnedFd,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<FileAdmission> {
        validate_process_identity(
            root.state.creator_process_id,
            GenerationRootStage::OpenRegularFile,
        )?;
        validate_preopened_regular_descriptor(
            &descriptor,
            PreopenedAccess::ReadOnly,
            GenerationRootStage::OpenRegularFile,
        )?;
        revalidate_root(root)?;
        let opened = qualify_preopened_file(
            root,
            path,
            descriptor,
            expectation,
            PreopenedAccess::ReadOnly,
            GenerationRootStage::OpenRegularFile,
        )?;
        let (bytes, after_read) =
            read_exact_owned(&opened.descriptor, opened.witness, expectation)?;
        let sha256: [u8; 32] = Sha256::digest(&bytes).into();
        if expectation
            .sha256
            .is_some_and(|expected_sha256| sha256 != expected_sha256)
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::HashMismatch,
                GenerationRootStage::ReadRegularFile,
            ));
        }
        revalidate_preopened_file_route(
            root,
            path,
            expectation,
            &opened.descriptor,
            after_read,
            &opened.component_identities,
            OFlags::RDONLY,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        revalidate_root(root)?;
        Ok(FileAdmission {
            handle: FileHandle {
                descriptor: opened.descriptor,
                root: root.clone(),
                path: path.clone(),
                expectation,
                content_witness: ExactContentWitness { sha256 },
                component_identities: opened.component_identities,
            },
            bytes: Arc::from(bytes),
            witness: after_read,
            sha256,
        })
    }

    pub(super) fn sync_root_directory(root: &RootHandle) -> GenerationRootResult<()> {
        revalidate_root(root)?;
        sync_directory_descriptor(&root.state.descriptor)?;
        revalidate_root(root)
    }

    pub(super) fn sync_file(
        file: &FileHandle,
        expected: GenerationRootObjectWitness,
    ) -> GenerationRootResult<()> {
        revalidate_file_route(file, expected)?;
        let (before_content, before) = read_exact_sha256(
            &file.descriptor,
            expected,
            file.expectation,
            GenerationRootStage::SyncRegularFile,
        )?;
        validate_bound_content(
            before_content,
            file.content_witness,
            GenerationRootStage::SyncRegularFile,
        )?;
        sync_file_descriptor(&file.descriptor)?;
        let (after_content, _) = read_exact_sha256(
            &file.descriptor,
            before,
            file.expectation,
            GenerationRootStage::SyncRegularFile,
        )?;
        validate_bound_content(
            after_content,
            file.content_witness,
            GenerationRootStage::SyncRegularFile,
        )?;
        revalidate_file_route(file, expected)
    }

    #[cfg(target_os = "linux")]
    pub(super) fn admit_control_file(
        root: &RootHandle,
        path: &RelativePath,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<ControlHandle> {
        revalidate_root(root)?;
        let opened = open_relative_file(
            root,
            path,
            expectation,
            true,
            GenerationRootStage::OpenRelativeDirectory,
            GenerationRootStage::OpenRegularFile,
        )?;
        let (bytes, after_read) =
            read_exact_owned(&opened.descriptor, opened.witness, expectation)?;
        let content_witness = ExactContentWitness {
            sha256: Sha256::digest(&bytes).into(),
        };
        let reopened = open_relative_probe(
            root,
            path,
            expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !after_read.mutation_stable_eq(reopened.witness)
            || opened.component_identities != reopened.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let (revalidated_content, revalidated_after) = read_exact_sha256(
            &opened.descriptor,
            after_read,
            expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        validate_bound_content(
            revalidated_content,
            content_witness,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        revalidate_root(root)?;
        Ok(ControlHandle {
            descriptor: opened.descriptor,
            #[cfg(test)]
            bytes: Arc::from(bytes),
            root: root.clone(),
            path: path.clone(),
            expectation,
            witness: revalidated_after,
            #[cfg(test)]
            content_witness: revalidated_content,
            component_identities: opened.component_identities,
        })
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn admit_preopened_control_file(
        root: &RootHandle,
        path: &RelativePath,
        descriptor: OwnedFd,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<ControlHandle> {
        validate_process_identity(
            root.state.creator_process_id,
            GenerationRootStage::OpenRegularFile,
        )?;
        validate_preopened_regular_descriptor(
            &descriptor,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::OpenRegularFile,
        )?;
        revalidate_root(root)?;
        let opened = qualify_preopened_file(
            root,
            path,
            descriptor,
            expectation,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::OpenRegularFile,
        )?;
        let (bytes, after_read) =
            read_exact_owned(&opened.descriptor, opened.witness, expectation)?;
        let content_witness = ExactContentWitness {
            sha256: Sha256::digest(&bytes).into(),
        };
        revalidate_preopened_file_route(
            root,
            path,
            expectation,
            &opened.descriptor,
            after_read,
            &opened.component_identities,
            OFlags::RDWR,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        let (revalidated_content, revalidated_after) = read_exact_sha256(
            &opened.descriptor,
            after_read,
            expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        validate_bound_content(
            revalidated_content,
            content_witness,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        revalidate_root(root)?;
        Ok(ControlHandle {
            descriptor: opened.descriptor,
            #[cfg(test)]
            bytes: Arc::from(bytes),
            root: root.clone(),
            path: path.clone(),
            expectation,
            witness: revalidated_after,
            #[cfg(test)]
            content_witness: revalidated_content,
            component_identities: opened.component_identities,
        })
    }

    pub(super) fn control_witness(control: &ControlHandle) -> GenerationRootObjectWitness {
        control.witness
    }

    #[cfg(test)]
    pub(super) fn control_bytes(control: &ControlHandle) -> Arc<[u8]> {
        Arc::clone(&control.bytes)
    }

    #[cfg(test)]
    pub(super) fn control_sha256(control: &ControlHandle) -> [u8; 32] {
        control.content_witness.sha256
    }

    pub(super) fn revalidate_anchor_set(
        root: &RootHandle,
        lock: &ControlHandle,
        authority: &ControlHandle,
    ) -> GenerationRootResult<()> {
        revalidate_root(root)?;
        if !Arc::ptr_eq(&root.state, &lock.root.state)
            || !Arc::ptr_eq(&root.state, &authority.root.state)
            || !relative_path_is_exact_name(&lock.path, GENERATION_ROOT_LOCK_FILE_NAME)
            || !relative_path_is_exact_name(&authority.path, GENERATION_ROOT_AUTHORITY_FILE_NAME)
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_anchor_route(lock)?;
        revalidate_anchor_route(authority)?;
        let root_witness = root.state.witness;
        if lock.witness.same_object(authority.witness)
            || lock.witness.device != root_witness.device
            || authority.witness.device != root_witness.device
            || lock.witness.mount_identity != root_witness.mount_identity
            || authority.witness.mount_identity != root_witness.mount_identity
            || lock.witness.filesystem != root_witness.filesystem
            || authority.witness.filesystem != root_witness.filesystem
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_anchor_route(lock)?;
        revalidate_anchor_route(authority)?;
        revalidate_root(root)
    }

    fn relative_path_is_exact_name(path: &RelativePath, expected: &str) -> bool {
        path.components.len() == 1 && path.components[0].as_os_str() == OsStr::new(expected)
    }

    pub(super) fn capture_anchor_image(
        control: &ControlHandle,
    ) -> GenerationRootResult<AnchorImage> {
        revalidate_anchor_route(control)?;
        let before = object_witness(
            &control.descriptor,
            control.witness.filesystem,
            control.witness.mount_identity,
            GenerationRootStage::AcquireLock,
        )?;
        if !before.same_control_anchor_identity(control.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        let (bytes, witness) = read_exact_owned(&control.descriptor, before, control.expectation)?;
        let sha256: [u8; 32] = Sha256::digest(&bytes).into();
        if control
            .expectation
            .sha256
            .is_some_and(|expected| expected != sha256)
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::HashMismatch,
                GenerationRootStage::AcquireLock,
            ));
        }
        revalidate_anchor_route(control)?;
        Ok(AnchorImage {
            bytes: Arc::from(bytes),
            witness,
            sha256,
        })
    }

    pub(super) fn anchor_images_match(left: &AnchorImage, right: &AnchorImage) -> bool {
        left.sha256 == right.sha256
            && left.bytes == right.bytes
            && left.witness.mutation_stable_eq(right.witness)
    }

    pub(super) fn validate_anchor_image(
        control: &ControlHandle,
        expected: &AnchorImage,
    ) -> GenerationRootResult<()> {
        let observed = capture_anchor_image(control)?;
        if anchor_images_match(&observed, expected) {
            Ok(())
        } else {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::ReleaseLock,
            ))
        }
    }

    #[cfg(target_os = "linux")]
    pub(super) fn try_anchor_lock(
        control: &ControlHandle,
        mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        let creator_process_id = std::process::id();
        revalidate_anchor_route(control)?;
        let opened = open_relative_file(
            &control.root,
            &control.path,
            control.expectation,
            true,
            GenerationRootStage::AcquireLock,
            GenerationRootStage::AcquireLock,
        )?;
        if !opened.witness.same_control_anchor_identity(control.witness)
            || opened.component_identities != control.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        let operation = match mode {
            GenerationRootLockMode::Shared => rustix::fs::FlockOperation::NonBlockingLockShared,
            GenerationRootLockMode::Exclusive => {
                rustix::fs::FlockOperation::NonBlockingLockExclusive
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeLock)?;
        let acquired = match rustix::fs::flock(&opened.descriptor, operation) {
            Ok(()) => AcquiredFlockDescriptor::new(opened.descriptor, creator_process_id),
            Err(error) if error == Errno::WOULDBLOCK => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::LockContended,
                    GenerationRootStage::AcquireLock,
                ));
            }
            Err(error) => return Err(os_error(GenerationRootStage::AcquireLock, error)),
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterLock)?;
        validate_process_identity(creator_process_id, GenerationRootStage::AcquireLock)?;

        let (first_bytes, first_after) =
            read_exact_owned(acquired.descriptor(), opened.witness, control.expectation)?;
        let first_content = ExactContentWitness {
            sha256: Sha256::digest(&first_bytes).into(),
        };
        validate_expected_sha256(
            first_content,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_anchor_route(control)?;
        let (second_bytes, second_after) =
            read_exact_owned(acquired.descriptor(), first_after, control.expectation)?;
        let second_content = ExactContentWitness {
            sha256: Sha256::digest(&second_bytes).into(),
        };
        if first_bytes != second_bytes || first_content != second_content {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        revalidate_anchor_route(control)?;
        let descriptor = acquired.into_descriptor();
        Ok(LockHandle {
            descriptor,
            #[cfg(test)]
            bytes: Arc::from(second_bytes),
            witness: second_after,
            content_witness: second_content,
            root: control.root.clone(),
            path: control.path.clone(),
            expectation: control.expectation,
            component_identities: opened.component_identities,
            creator_process_id,
            lock_held: true,
            #[cfg(test)]
            mode,
        })
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn try_anchor_lock_preopened(
        control: &ControlHandle,
        descriptor: OwnedFd,
        mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        let creator_process_id = std::process::id();
        validate_process_identity(
            control.root.state.creator_process_id,
            GenerationRootStage::AcquireLock,
        )?;
        validate_preopened_regular_descriptor(
            &descriptor,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_anchor_route(control)?;
        let opened = qualify_preopened_file(
            &control.root,
            &control.path,
            descriptor,
            control.expectation,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::AcquireLock,
        )?;
        if !opened.witness.same_control_anchor_identity(control.witness)
            || opened.component_identities != control.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        let operation = match mode {
            GenerationRootLockMode::Shared => rustix::fs::FlockOperation::NonBlockingLockShared,
            GenerationRootLockMode::Exclusive => {
                rustix::fs::FlockOperation::NonBlockingLockExclusive
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeLock)?;
        let acquired = match rustix::fs::flock(&opened.descriptor, operation) {
            Ok(()) => AcquiredFlockDescriptor::new(opened.descriptor, creator_process_id),
            Err(error) if error == Errno::WOULDBLOCK => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::LockContended,
                    GenerationRootStage::AcquireLock,
                ));
            }
            Err(error) => return Err(os_error(GenerationRootStage::AcquireLock, error)),
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterLock)?;
        validate_process_identity(creator_process_id, GenerationRootStage::AcquireLock)?;
        let descriptor_status_flags = rustix::fs::fcntl_getfl(acquired.descriptor())
            .map_err(|error| os_error(GenerationRootStage::AcquireLock, error))?;

        let (first_bytes, first_after) =
            read_exact_owned(acquired.descriptor(), opened.witness, control.expectation)?;
        let first_content = ExactContentWitness {
            sha256: Sha256::digest(&first_bytes).into(),
        };
        validate_expected_sha256(
            first_content,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_anchor_route(control)?;
        let (second_bytes, second_after) =
            read_exact_owned(acquired.descriptor(), first_after, control.expectation)?;
        let second_content = ExactContentWitness {
            sha256: Sha256::digest(&second_bytes).into(),
        };
        if first_bytes != second_bytes || first_content != second_content {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        revalidate_anchor_route(control)?;
        let descriptor = acquired.into_descriptor();
        Ok(LockHandle {
            descriptor,
            #[cfg(test)]
            bytes: Arc::from(second_bytes),
            witness: second_after,
            content_witness: second_content,
            root: control.root.clone(),
            path: control.path.clone(),
            expectation: control.expectation,
            component_identities: opened.component_identities,
            creator_process_id,
            lock_held: true,
            descriptor_status_flags,
            #[cfg(test)]
            mode,
        })
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn try_lock(
        control: &ControlHandle,
        mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        let creator_process_id = std::process::id();
        revalidate_control_route(control)?;
        let opened = open_relative_file(
            &control.root,
            &control.path,
            control.expectation,
            true,
            GenerationRootStage::AcquireLock,
            GenerationRootStage::AcquireLock,
        )?;
        if !opened.witness.mutation_stable_eq(control.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        if opened.component_identities != control.component_identities {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        let operation = match mode {
            GenerationRootLockMode::Shared => rustix::fs::FlockOperation::NonBlockingLockShared,
            GenerationRootLockMode::Exclusive => {
                rustix::fs::FlockOperation::NonBlockingLockExclusive
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeLock)?;
        let acquired = match rustix::fs::flock(&opened.descriptor, operation) {
            Ok(()) => AcquiredFlockDescriptor::new(opened.descriptor, creator_process_id),
            Err(error) if error == Errno::WOULDBLOCK => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::LockContended,
                    GenerationRootStage::AcquireLock,
                ));
            }
            Err(error) => return Err(os_error(GenerationRootStage::AcquireLock, error)),
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterLock)?;
        if creator_process_id != std::process::id() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                GenerationRootStage::AcquireLock,
            ));
        }
        let (observed_content, after) = read_exact_sha256(
            acquired.descriptor(),
            opened.witness,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        validate_bound_content(
            observed_content,
            control.content_witness,
            GenerationRootStage::AcquireLock,
        )?;
        validate_expected_sha256(
            observed_content,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_control_route(control)?;
        let (revalidated_content, revalidated_after) = read_exact_sha256(
            acquired.descriptor(),
            after,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        validate_bound_content(
            revalidated_content,
            control.content_witness,
            GenerationRootStage::AcquireLock,
        )?;
        let descriptor = acquired.into_descriptor();
        Ok(LockHandle {
            descriptor,
            #[cfg(test)]
            bytes: Arc::clone(&control.bytes),
            witness: revalidated_after,
            content_witness: revalidated_content,
            root: control.root.clone(),
            path: control.path.clone(),
            expectation: control.expectation,
            component_identities: opened.component_identities,
            creator_process_id,
            lock_held: true,
            #[cfg(test)]
            mode,
        })
    }

    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn try_lock_preopened(
        control: &ControlHandle,
        descriptor: OwnedFd,
        mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        let creator_process_id = std::process::id();
        validate_process_identity(
            control.root.state.creator_process_id,
            GenerationRootStage::AcquireLock,
        )?;
        validate_preopened_regular_descriptor(
            &descriptor,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_control_route(control)?;
        let opened = qualify_preopened_file(
            &control.root,
            &control.path,
            descriptor,
            control.expectation,
            PreopenedAccess::ReadWrite,
            GenerationRootStage::AcquireLock,
        )?;
        if !opened.witness.mutation_stable_eq(control.witness)
            || opened.component_identities != control.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::AcquireLock,
            ));
        }
        let operation = match mode {
            GenerationRootLockMode::Shared => rustix::fs::FlockOperation::NonBlockingLockShared,
            GenerationRootLockMode::Exclusive => {
                rustix::fs::FlockOperation::NonBlockingLockExclusive
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeLock)?;
        let acquired = match rustix::fs::flock(&opened.descriptor, operation) {
            Ok(()) => AcquiredFlockDescriptor::new(opened.descriptor, creator_process_id),
            Err(error) if error == Errno::WOULDBLOCK => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::LockContended,
                    GenerationRootStage::AcquireLock,
                ));
            }
            Err(error) => return Err(os_error(GenerationRootStage::AcquireLock, error)),
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterLock)?;
        if creator_process_id != std::process::id() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                GenerationRootStage::AcquireLock,
            ));
        }
        let descriptor_status_flags = rustix::fs::fcntl_getfl(acquired.descriptor())
            .map_err(|error| os_error(GenerationRootStage::AcquireLock, error))?;
        let (locked_content, locked_after) = read_exact_sha256(
            acquired.descriptor(),
            opened.witness,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        validate_bound_content(
            locked_content,
            control.content_witness,
            GenerationRootStage::AcquireLock,
        )?;
        validate_expected_sha256(
            locked_content,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        revalidate_control_route(control)?;
        let (revalidated_content, revalidated_after) = read_exact_sha256(
            acquired.descriptor(),
            locked_after,
            control.expectation,
            GenerationRootStage::AcquireLock,
        )?;
        validate_bound_content(
            revalidated_content,
            control.content_witness,
            GenerationRootStage::AcquireLock,
        )?;
        let descriptor = acquired.into_descriptor();
        Ok(LockHandle {
            descriptor,
            #[cfg(test)]
            bytes: Arc::clone(&control.bytes),
            witness: revalidated_after,
            content_witness: revalidated_content,
            root: control.root.clone(),
            path: control.path.clone(),
            expectation: control.expectation,
            component_identities: opened.component_identities,
            creator_process_id,
            lock_held: true,
            descriptor_status_flags,
            #[cfg(test)]
            mode,
        })
    }

    #[cfg(test)]
    pub(super) fn lock_witness(lock: &LockHandle) -> GenerationRootObjectWitness {
        lock.witness
    }

    #[cfg(test)]
    pub(super) fn lock_bytes(lock: &LockHandle) -> Arc<[u8]> {
        Arc::clone(&lock.bytes)
    }

    #[cfg(test)]
    pub(super) fn lock_sha256(lock: &LockHandle) -> [u8; 32] {
        lock.content_witness.sha256
    }

    #[cfg(test)]
    pub(super) fn lock_mode(lock: &LockHandle) -> GenerationRootLockMode {
        lock.mode
    }

    #[cfg(all(
        test,
        any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64"))
    ))]
    pub(super) fn set_root_creator_process_id_for_test(root: &mut RootHandle, process_id: u32) {
        Arc::get_mut(&mut root.state)
            .expect("test root must have sole state ownership")
            .creator_process_id = process_id;
    }

    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn set_control_root_creator_process_id_for_test(
        control: &mut ControlHandle,
        process_id: u32,
    ) {
        Arc::get_mut(&mut control.root.state)
            .expect("test control root must have sole state ownership")
            .creator_process_id = process_id;
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn set_lock_creator_process_id_for_test(lock: &mut LockHandle, process_id: u32) {
        lock.creator_process_id = process_id;
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn duplicate_lock_descriptor_for_inheritance_for_test(
        lock: &LockHandle,
    ) -> GenerationRootResult<OwnedFd> {
        rustix::io::dup(&lock.descriptor)
            .map_err(|error| os_error(GenerationRootStage::AcquireLock, error))
    }

    pub(super) fn unlock(mut lock: LockHandle) -> GenerationRootResult<()> {
        if lock.creator_process_id != std::process::id() {
            drop(lock);
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                GenerationRootStage::ReleaseLock,
            ));
        }
        let validation_result = revalidate_lock_route(&lock)
            .and_then(|()| validate_lock_content(&lock, GenerationRootStage::ReleaseLock));
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeUnlock)?;
        let unlock_result = rustix::fs::flock(&lock.descriptor, rustix::fs::FlockOperation::Unlock)
            .map_err(|error| os_error(GenerationRootStage::ReleaseLock, error));
        if unlock_result.is_ok() {
            lock.lock_held = false;
        }
        #[cfg(test)]
        let unlock_result = unlock_result.and_then(|()| test_boundary(TestBoundary::AfterUnlock));
        drop(lock);
        validation_result.and(unlock_result)
    }

    impl Drop for LockHandle {
        fn drop(&mut self) {
            if self.lock_held && self.creator_process_id == std::process::id() {
                let _ = rustix::fs::flock(&self.descriptor, rustix::fs::FlockOperation::Unlock);
                self.lock_held = false;
            }
        }
    }

    #[cfg(test)]
    pub(super) fn sync_lock_file(lock: &LockHandle) -> GenerationRootResult<()> {
        validate_lock_process(lock, GenerationRootStage::SyncRegularFile)?;
        revalidate_lock_route(lock)?;
        let (before_content, before) = read_exact_sha256(
            &lock.descriptor,
            lock.witness,
            lock.expectation,
            GenerationRootStage::SyncRegularFile,
        )?;
        validate_bound_content(
            before_content,
            lock.content_witness,
            GenerationRootStage::SyncRegularFile,
        )?;
        sync_file_descriptor(&lock.descriptor)?;
        let (after_content, after) = read_exact_sha256(
            &lock.descriptor,
            before,
            lock.expectation,
            GenerationRootStage::SyncRegularFile,
        )?;
        validate_bound_content(
            after_content,
            lock.content_witness,
            GenerationRootStage::SyncRegularFile,
        )?;
        revalidate_lock_route(lock)?;
        let (revalidated_content, _) = read_exact_sha256(
            &lock.descriptor,
            after,
            lock.expectation,
            GenerationRootStage::SyncRegularFile,
        )?;
        validate_bound_content(
            revalidated_content,
            lock.content_witness,
            GenerationRootStage::SyncRegularFile,
        )
    }

    fn validate_lock_process(
        lock: &LockHandle,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        validate_process_identity(lock.creator_process_id, stage)
    }

    fn validate_process_identity(
        expected_process_id: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        if expected_process_id == std::process::id() {
            Ok(())
        } else {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                stage,
            ))
        }
    }

    #[cfg(target_os = "linux")]
    fn revalidate_anchor_route(control: &ControlHandle) -> GenerationRootResult<()> {
        revalidate_root(&control.root)?;
        let retained = object_witness(
            &control.descriptor,
            control.witness.filesystem,
            control.witness.mount_identity,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        validate_private_regular_file(
            &control.descriptor,
            retained,
            control.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !retained.same_control_anchor_identity(control.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let reopened = open_relative_probe(
            &control.root,
            &control.path,
            control.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !reopened
            .witness
            .same_control_anchor_identity(control.witness)
            || reopened.component_identities != control.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_root(&control.root)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn revalidate_anchor_route(control: &ControlHandle) -> GenerationRootResult<()> {
        revalidate_root(&control.root)?;
        validate_preopened_regular_descriptor_status(
            &control.descriptor,
            OFlags::RDWR,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        let retained = object_witness(
            &control.descriptor,
            control.witness.filesystem,
            control.witness.mount_identity,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        validate_private_regular_file(
            &control.descriptor,
            retained,
            control.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !retained.same_control_anchor_identity(control.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let observed_components = bind_preopened_route(
            &control.root,
            &control.path,
            retained,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if observed_components.as_ref() != control.component_identities.as_ref() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_root(&control.root)
    }

    #[cfg(target_os = "linux")]
    #[cfg(test)]
    fn revalidate_control_route(control: &ControlHandle) -> GenerationRootResult<()> {
        revalidate_root(&control.root)?;
        let retained = object_witness(
            &control.descriptor,
            control.witness.filesystem,
            control.witness.mount_identity,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !retained.mutation_stable_eq(control.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let reopened = open_relative_probe(
            &control.root,
            &control.path,
            control.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !reopened.witness.mutation_stable_eq(control.witness)
            || reopened.component_identities != control.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_root(&control.root)
    }

    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    fn revalidate_control_route(control: &ControlHandle) -> GenerationRootResult<()> {
        revalidate_preopened_file_route(
            &control.root,
            &control.path,
            control.expectation,
            &control.descriptor,
            control.witness,
            &control.component_identities,
            OFlags::RDWR,
            GenerationRootStage::RevalidateRegularFile,
        )
    }

    #[cfg(target_os = "linux")]
    fn revalidate_lock_route(lock: &LockHandle) -> GenerationRootResult<()> {
        validate_lock_process(lock, GenerationRootStage::RevalidateRegularFile)?;
        revalidate_root(&lock.root)?;
        let retained = object_witness(
            &lock.descriptor,
            lock.witness.filesystem,
            lock.witness.mount_identity,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !retained.mutation_stable_eq(lock.witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let reopened = open_relative_probe(
            &lock.root,
            &lock.path,
            lock.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !reopened.witness.mutation_stable_eq(lock.witness)
            || reopened.component_identities != lock.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_root(&lock.root)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn revalidate_lock_route(lock: &LockHandle) -> GenerationRootResult<()> {
        validate_lock_process(lock, GenerationRootStage::RevalidateRegularFile)?;
        revalidate_preopened_file_route(
            &lock.root,
            &lock.path,
            lock.expectation,
            &lock.descriptor,
            lock.witness,
            &lock.component_identities,
            lock.descriptor_status_flags,
            GenerationRootStage::RevalidateRegularFile,
        )
    }

    fn validate_lock_content(
        lock: &LockHandle,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let (observed, _) =
            read_exact_sha256(&lock.descriptor, lock.witness, lock.expectation, stage)?;
        validate_bound_content(observed, lock.content_witness, stage)
    }

    struct OpenedFile {
        descriptor: OwnedFd,
        witness: GenerationRootObjectWitness,
        component_identities: Arc<[BasicObjectIdentity]>,
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    #[derive(Clone, Copy)]
    enum PreopenedAccess {
        ReadOnly,
        ReadWrite,
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn qualify_preopened_file(
        root: &RootHandle,
        path: &RelativePath,
        descriptor: OwnedFd,
        expectation: GenerationFileExpectation,
        access: PreopenedAccess,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OpenedFile> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforePreopenedQualification)?;
        validate_preopened_regular_descriptor(&descriptor, access, stage)?;
        let witness = object_witness(
            &descriptor,
            root.state.witness.filesystem,
            root.state.witness.mount_identity,
            stage,
        )?;
        validate_private_regular_file(&descriptor, witness, expectation, stage)?;
        let component_identities = bind_preopened_route(root, path, witness, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterPreopenedQualification)?;
        Ok(OpenedFile {
            descriptor,
            witness,
            component_identities,
        })
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn validate_preopened_regular_descriptor(
        descriptor: &OwnedFd,
        expected_access: PreopenedAccess,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let expected_status_flags = match expected_access {
            PreopenedAccess::ReadOnly => OFlags::RDONLY,
            PreopenedAccess::ReadWrite => OFlags::RDWR,
        };
        validate_preopened_regular_descriptor_status(descriptor, expected_status_flags, stage)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn validate_preopened_regular_descriptor_status(
        descriptor: &OwnedFd,
        expected_status_flags: OFlags,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::NotRegularFile,
                stage,
            ));
        }
        let observed_flags =
            rustix::fs::fcntl_getfl(descriptor).map_err(|error| os_error(stage, error))?;
        if observed_flags != expected_status_flags {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::InvalidDescriptorAccess,
                stage,
            ));
        }
        let descriptor_flags =
            rustix::io::fcntl_getfd(descriptor).map_err(|error| os_error(stage, error))?;
        if !descriptor_flags.contains(rustix::io::FdFlags::CLOEXEC) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::CloseOnExecRequired,
                stage,
            ));
        }
        Ok(())
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn bind_preopened_route(
        root: &RootHandle,
        path: &RelativePath,
        witness: GenerationRootObjectWitness,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<Arc<[BasicObjectIdentity]>> {
        use rustix::fs::{AtFlags, statat};

        let (final_name, ancestors) = path.components.split_last().ok_or_else(|| {
            GenerationRootError::new(
                GenerationRootErrorKind::InvalidRoute,
                GenerationRootStage::ParseRelativeRoute,
            )
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRootDescriptorDuplicate)?;
        let mut parent = rustix::io::fcntl_dupfd_cloexec(&root.state.descriptor, 0)
            .map_err(|error| os_error(stage, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRootDescriptorDuplicate)?;
        let mut component_identities = Vec::new();
        component_identities
            .try_reserve(path.components.len())
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        for (index, component) in ancestors.iter().enumerate() {
            parent = open_relative_directory_component(
                &parent,
                component,
                index,
                root.state.witness,
                stage,
            )?;
            component_identities.push(basic_identity(&parent, stage)?);
        }
        let index = ancestors.len();
        verify_exact_directory_entry(&parent, final_name, stage, index)?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFinalRouteStat)?;
        let route_stat = statat(&parent, final_name, AtFlags::SYMLINK_NOFOLLOW)
            .map_err(|error| macos_open_error(stage, error).at_component(index))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFinalRouteStat)?;
        verify_exact_directory_entry(&parent, final_name, stage, index)?;
        let route_file_type = FileType::from_raw_mode(route_stat.st_mode);
        if route_file_type == FileType::Symlink {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::SymbolicLink, stage)
                    .at_component(index),
            );
        }
        if route_file_type != FileType::RegularFile {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::NotRegularFile, stage)
                    .at_component(index),
            );
        }
        if !macos_route_stat_matches_witness(&route_stat, witness) {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index),
            );
        }
        component_identities.push(BasicObjectIdentity {
            device: witness.device,
            inode: witness.inode,
            mode: witness.mode,
            uid: witness.uid,
            gid: witness.gid,
            mount_identity: witness.mount_identity,
        });
        Ok(Arc::from(component_identities))
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn macos_route_stat_matches_witness(
        stat: &rustix::fs::Stat,
        witness: GenerationRootObjectWitness,
    ) -> bool {
        let Ok(byte_len) = u64::try_from(stat.st_size) else {
            return false;
        };
        stat.st_flags == 0
            && stat_device_as_u64(stat.st_dev) == witness.device
            && stat_inode_as_u64(stat.st_ino) == witness.inode
            && stat_mode_as_u32(stat.st_mode) == witness.mode
            && stat_link_count_as_u64(stat.st_nlink) == witness.hard_links
            && stat.st_uid == witness.uid
            && stat.st_gid == witness.gid
            && byte_len == witness.byte_len
            && stat_seconds_as_i64(stat.st_mtime) == witness.modified_seconds
            && stat.st_mtime_nsec == witness.modified_nanoseconds
            && stat_seconds_as_i64(stat.st_ctime) == witness.changed_seconds
            && stat.st_ctime_nsec == witness.changed_nanoseconds
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn revalidate_preopened_file_route(
        root: &RootHandle,
        path: &RelativePath,
        expectation: GenerationFileExpectation,
        descriptor: &OwnedFd,
        expected: GenerationRootObjectWitness,
        component_identities: &[BasicObjectIdentity],
        expected_status_flags: OFlags,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        revalidate_root(root)?;
        validate_preopened_regular_descriptor_status(descriptor, expected_status_flags, stage)?;
        let retained = object_witness(
            descriptor,
            expected.filesystem,
            expected.mount_identity,
            stage,
        )?;
        validate_private_regular_file(descriptor, retained, expectation, stage)?;
        if !retained.mutation_stable_eq(expected) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        let observed_components = bind_preopened_route(root, path, retained, stage)?;
        if observed_components.as_ref() != component_identities {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        revalidate_root(root)
    }

    #[cfg(target_os = "linux")]
    fn revalidate_file_route(
        file: &FileHandle,
        expected: GenerationRootObjectWitness,
    ) -> GenerationRootResult<()> {
        revalidate_root(&file.root)?;
        let retained = object_witness(
            &file.descriptor,
            expected.filesystem,
            expected.mount_identity,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !retained.mutation_stable_eq(expected) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        let reopened = open_relative_probe(
            &file.root,
            &file.path,
            file.expectation,
            GenerationRootStage::RevalidateRegularFile,
        )?;
        if !reopened.witness.mutation_stable_eq(expected)
            || reopened.component_identities != file.component_identities
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::RevalidateRegularFile,
            ));
        }
        revalidate_root(&file.root)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn revalidate_file_route(
        file: &FileHandle,
        expected: GenerationRootObjectWitness,
    ) -> GenerationRootResult<()> {
        revalidate_preopened_file_route(
            &file.root,
            &file.path,
            file.expectation,
            &file.descriptor,
            expected,
            &file.component_identities,
            OFlags::RDONLY,
            GenerationRootStage::RevalidateRegularFile,
        )
    }

    #[cfg(target_os = "linux")]
    fn open_relative_file(
        root: &RootHandle,
        path: &RelativePath,
        expectation: GenerationFileExpectation,
        writable: bool,
        directory_stage: GenerationRootStage,
        regular_stage: GenerationRootStage,
    ) -> GenerationRootResult<OpenedFile> {
        let (final_name, ancestors) = path.components.split_last().ok_or_else(|| {
            GenerationRootError::new(
                GenerationRootErrorKind::InvalidRoute,
                GenerationRootStage::ParseRelativeRoute,
            )
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRootDescriptorDuplicate)?;
        let mut parent = rustix::io::fcntl_dupfd_cloexec(&root.state.descriptor, 0)
            .map_err(|error| os_error(directory_stage, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRootDescriptorDuplicate)?;
        let mut component_identities = Vec::new();
        component_identities
            .try_reserve(path.components.len())
            .map_err(|_| {
                GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, directory_stage)
            })?;
        for (index, component) in ancestors.iter().enumerate() {
            parent = open_relative_directory_component(
                &parent,
                component,
                index,
                root.state.witness,
                directory_stage,
            )?;
            component_identities.push(basic_identity(&parent, directory_stage)?);
        }
        let descriptor = open_regular_component(
            &parent,
            final_name,
            ancestors.len(),
            root.state.witness,
            expectation,
            writable,
            root.state.creator_process_id,
            regular_stage,
        )?;
        let witness = object_witness(
            &descriptor,
            root.state.witness.filesystem,
            root.state.witness.mount_identity,
            regular_stage,
        )?;
        validate_private_regular_file(&descriptor, witness, expectation, regular_stage)?;
        component_identities.push(basic_identity(&descriptor, regular_stage)?);
        #[cfg(test)]
        test_boundary(TestBoundary::AfterQualifiedFileOpen)?;
        Ok(OpenedFile {
            descriptor,
            witness,
            component_identities: Arc::from(component_identities),
        })
    }

    #[cfg(target_os = "linux")]
    fn open_relative_probe(
        root: &RootHandle,
        path: &RelativePath,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OpenedFile> {
        let (final_name, ancestors) = path.components.split_last().ok_or_else(|| {
            GenerationRootError::new(
                GenerationRootErrorKind::InvalidRoute,
                GenerationRootStage::ParseRelativeRoute,
            )
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRootDescriptorDuplicate)?;
        let mut parent = rustix::io::fcntl_dupfd_cloexec(&root.state.descriptor, 0)
            .map_err(|error| os_error(stage, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRootDescriptorDuplicate)?;
        let mut component_identities = Vec::new();
        component_identities
            .try_reserve(path.components.len())
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        for (index, component) in ancestors.iter().enumerate() {
            parent = open_relative_directory_component(
                &parent,
                component,
                index,
                root.state.witness,
                stage,
            )?;
            component_identities.push(basic_identity(&parent, stage)?);
        }
        let index = ancestors.len();
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFinalRouteProbe { index })?;
        let (descriptor, witness) = probe_regular_component(
            &parent,
            final_name,
            index,
            root.state.witness,
            expectation,
            stage,
        )?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFinalRouteProbe { index })?;
        component_identities.push(basic_identity(&descriptor, stage)?);
        Ok(OpenedFile {
            descriptor,
            witness,
            component_identities: Arc::from(component_identities),
        })
    }

    fn read_exact_owned(
        descriptor: &OwnedFd,
        before: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<(Vec<u8>, GenerationRootObjectWitness)> {
        let max_byte_len = expectation.max_byte_len();
        if expectation.byte_len > max_byte_len {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ResourceLimit,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(max_byte_len, expectation.byte_len));
        }
        let byte_len = usize::try_from(expectation.byte_len).map_err(|_| {
            GenerationRootError::new(
                GenerationRootErrorKind::ResourceLimit,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(usize_as_u64(usize::MAX), expectation.byte_len)
        })?;
        let mut bytes = Vec::new();
        bytes.try_reserve_exact(byte_len).map_err(|_| {
            GenerationRootError::new(
                GenerationRootErrorKind::ResourceLimit,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(max_byte_len, expectation.byte_len)
        })?;
        bytes.resize(byte_len, 0);
        let mut offset = 0_usize;
        while offset < bytes.len() {
            let file_offset = usize_as_u64(offset);
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeRead {
                offset: file_offset,
            })?;
            match pread(descriptor, &mut bytes[offset..], file_offset) {
                Ok(0) => {
                    return Err(GenerationRootError::new(
                        GenerationRootErrorKind::SizeMismatch,
                        GenerationRootStage::ReadRegularFile,
                    )
                    .with_counts(expectation.byte_len, file_offset));
                }
                Ok(read) => {
                    #[cfg(test)]
                    test_boundary(TestBoundary::AfterRead {
                        offset: file_offset,
                        byte_count: read,
                    })?;
                    offset += read;
                }
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(os_error(GenerationRootStage::ReadRegularFile, error));
                }
            }
        }
        let mut probe = [0_u8; 1];
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeTrailingByteProbe)?;
        let probe_read = pread(descriptor, &mut probe, expectation.byte_len)
            .map_err(|error| os_error(GenerationRootStage::ReadRegularFile, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterTrailingByteProbe {
            byte_count: probe_read,
        })?;
        if probe_read != 0 {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::SizeMismatch,
                GenerationRootStage::ReadRegularFile,
            )
            .with_counts(expectation.byte_len, expectation.byte_len.saturating_add(1)));
        }
        #[cfg(test)]
        test_boundary(TestBoundary::AfterExactRead)?;
        let after = object_witness(
            descriptor,
            before.filesystem,
            before.mount_identity,
            GenerationRootStage::ReadRegularFile,
        )?;
        if !before.mutation_stable_eq(after) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::ReadRegularFile,
            ));
        }
        Ok((bytes, after))
    }

    fn read_exact_sha256(
        descriptor: &OwnedFd,
        before: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<(ExactContentWitness, GenerationRootObjectWitness)> {
        const HASH_BUFFER_BYTES: usize = 64 * 1024;

        let max_byte_len = expectation.max_byte_len();
        if expectation.byte_len > max_byte_len {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                    .with_counts(max_byte_len, expectation.byte_len),
            );
        }
        let mut digest = Sha256::new();
        let mut buffer = Vec::new();
        buffer
            .try_reserve_exact(HASH_BUFFER_BYTES)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        buffer.resize(HASH_BUFFER_BYTES, 0_u8);
        let mut offset = 0_u64;
        while offset < expectation.byte_len {
            let remaining = expectation.byte_len.saturating_sub(offset);
            let requested = usize::try_from(remaining)
                .unwrap_or(usize::MAX)
                .min(buffer.len());
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeRead { offset })?;
            match pread(descriptor, &mut buffer[..requested], offset) {
                Ok(0) => {
                    return Err(GenerationRootError::new(
                        GenerationRootErrorKind::SizeMismatch,
                        stage,
                    )
                    .with_counts(expectation.byte_len, offset));
                }
                Ok(read) => {
                    #[cfg(test)]
                    test_boundary(TestBoundary::AfterRead {
                        offset,
                        byte_count: read,
                    })?;
                    digest.update(&buffer[..read]);
                    offset = offset.saturating_add(usize_as_u64(read));
                }
                Err(error) if error == Errno::INTR => {}
                Err(error) => return Err(os_error(stage, error)),
            }
        }
        let mut probe = [0_u8; 1];
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeTrailingByteProbe)?;
        let probe_read = pread(descriptor, &mut probe, expectation.byte_len)
            .map_err(|error| os_error(stage, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterTrailingByteProbe {
            byte_count: probe_read,
        })?;
        if probe_read != 0 {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::SizeMismatch, stage)
                    .with_counts(expectation.byte_len, expectation.byte_len.saturating_add(1)),
            );
        }
        #[cfg(test)]
        test_boundary(TestBoundary::AfterExactRead)?;
        let after = object_witness(descriptor, before.filesystem, before.mount_identity, stage)?;
        if !before.mutation_stable_eq(after) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        Ok((
            ExactContentWitness {
                sha256: digest.finalize().into(),
            },
            after,
        ))
    }

    fn validate_bound_content(
        observed: ExactContentWitness,
        expected: ExactContentWitness,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        if observed == expected {
            Ok(())
        } else {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ))
        }
    }

    fn validate_expected_sha256(
        observed: ExactContentWitness,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        if expectation
            .sha256
            .is_some_and(|expected| expected != observed.sha256)
        {
            Err(GenerationRootError::new(
                GenerationRootErrorKind::HashMismatch,
                stage,
            ))
        } else {
            Ok(())
        }
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_bound_control_content_for_test(
        observed: [u8; 32],
        expected: [u8; 32],
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        validate_bound_content(
            ExactContentWitness { sha256: observed },
            ExactContentWitness { sha256: expected },
            stage,
        )
    }

    fn parse_route_bytes(
        value: &OsStr,
        absolute: bool,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<Vec<OsString>> {
        let bytes = value.as_bytes();
        if bytes.is_empty() || bytes.len() > GENERATION_ROOT_MAX_ROUTE_BYTES || bytes.contains(&0) {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::InvalidRoute, stage).with_counts(
                    usize_as_u64(GENERATION_ROOT_MAX_ROUTE_BYTES),
                    usize_as_u64(bytes.len()),
                ),
            );
        }
        if absolute != bytes.starts_with(b"/") {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::InvalidRoute,
                stage,
            ));
        }
        let body = if absolute { &bytes[1..] } else { bytes };
        if body.is_empty() || body.starts_with(b"/") || body.ends_with(b"/") {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::InvalidRoute,
                stage,
            ));
        }
        let mut components = Vec::new();
        components
            .try_reserve(GENERATION_ROOT_MAX_COMPONENTS)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        for (index, component) in body.split(|byte| *byte == b'/').enumerate() {
            if component.is_empty()
                || component == b"."
                || component == b".."
                || component.len() > GENERATION_ROOT_MAX_COMPONENT_BYTES
            {
                return Err(
                    GenerationRootError::new(GenerationRootErrorKind::InvalidRoute, stage)
                        .at_component(index)
                        .with_counts(
                            usize_as_u64(GENERATION_ROOT_MAX_COMPONENT_BYTES),
                            usize_as_u64(component.len()),
                        ),
                );
            }
            if index >= GENERATION_ROOT_MAX_COMPONENTS {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::ResourceLimit,
                    stage,
                )
                .at_component(index)
                .with_counts(
                    usize_as_u64(GENERATION_ROOT_MAX_COMPONENTS),
                    usize_as_u64(index.saturating_add(1)),
                ));
            }
            components.push(OsStr::from_bytes(component).to_os_string());
        }
        Ok(components)
    }

    fn basic_identity(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<BasicObjectIdentity> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        let mount_identity = route_mount_identity(descriptor, stage)?;
        Ok(BasicObjectIdentity {
            device: stat_device_as_u64(stat.st_dev),
            inode: stat_inode_as_u64(stat.st_ino),
            mode: stat_mode_as_u32(stat.st_mode),
            uid: stat.st_uid,
            gid: stat.st_gid,
            mount_identity,
        })
    }

    fn absolute_ancestor_security_witness(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<AbsoluteAncestorSecurityWitness> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        #[cfg(target_os = "linux")]
        let changed_nanoseconds = i64::try_from(stat.st_ctime_nsec)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
        let changed_nanoseconds = stat.st_ctime_nsec;
        Ok(AbsoluteAncestorSecurityWitness {
            identity: basic_identity(descriptor, stage)?,
            changed_seconds: stat_seconds_as_i64(stat.st_ctime),
            changed_nanoseconds,
        })
    }

    fn validate_absolute_ancestor_owner_mode(
        uid: u32,
        mode: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let effective_uid = rustix::process::geteuid().as_raw();
        if uid != effective_uid && uid != 0 {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::WrongOwner, stage)
                    .with_counts(u64::from(effective_uid), u64::from(uid)),
            );
        }
        let writable_by_non_owner = mode & 0o022;
        if writable_by_non_owner != 0 {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::WrongMode, stage)
                    .with_counts(0, u64::from(writable_by_non_owner)),
            );
        }
        Ok(())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_absolute_ancestor_owner_mode_for_test(
        uid: u32,
        mode: u32,
    ) -> GenerationRootResult<()> {
        validate_absolute_ancestor_owner_mode(uid, mode, GenerationRootStage::QualifyRootSecurity)
    }

    fn at_absolute_component(
        error: GenerationRootError,
        index: Option<usize>,
    ) -> GenerationRootError {
        index.map_or(error, |index| error.at_component(index))
    }

    fn qualify_absolute_ancestor(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
        index: Option<usize>,
    ) -> GenerationRootResult<BasicObjectIdentity> {
        let result = (|| {
            let before = absolute_ancestor_security_witness(descriptor, stage)?;
            #[cfg(target_os = "linux")]
            let raw_mode = before.identity.mode;
            #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
            let raw_mode = u16::try_from(before.identity.mode).map_err(|_| {
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
            })?;
            if FileType::from_raw_mode(raw_mode) != FileType::Directory {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::NotDirectory,
                    stage,
                ));
            }
            validate_absolute_ancestor_owner_mode(
                before.identity.uid,
                before.identity.mode,
                stage,
            )?;
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeAbsoluteAncestorAclRead { index })?;
            let acl_presence =
                crate::fd_acl::extended_acl_presence(descriptor.as_fd()).map_err(|error| {
                    GenerationRootError::new(GenerationRootErrorKind::AclRejected, stage)
                        .with_raw_os_error(error.raw_os_error().unwrap_or(libc::EIO))
                })?;
            #[cfg(test)]
            test_boundary(TestBoundary::AfterAbsoluteAncestorAclRead { index })?;
            match acl_presence {
                crate::fd_acl::ExtendedAclPresence::Absent => {}
                crate::fd_acl::ExtendedAclPresence::Present => {
                    return Err(GenerationRootError::new(
                        GenerationRootErrorKind::AclRejected,
                        stage,
                    ));
                }
            }
            let after = absolute_ancestor_security_witness(descriptor, stage)?;
            if before != after {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::ObjectChanged,
                    stage,
                ));
            }
            Ok(after.identity)
        })();
        result.map_err(|error| at_absolute_component(error, index))
    }

    fn validate_private_directory(
        descriptor: &OwnedFd,
        witness: GenerationRootObjectWitness,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::NotDirectory,
                stage,
            ));
        }
        validate_owner_mode(witness, GENERATION_ROOT_DIRECTORY_MODE, stage)?;
        inspect_acl_if_required(descriptor, witness, stage)
    }

    fn validate_private_regular_file(
        descriptor: &OwnedFd,
        witness: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        validate_private_regular_file_metadata(descriptor, witness, expectation, stage)?;
        inspect_acl_if_required(descriptor, witness, stage)
    }

    /// Validate only metadata available through either a data descriptor or a
    /// Linux `O_PATH` probe. ACL inspection is deliberately excluded: Linux
    /// `fgetxattr` rejects `O_PATH` descriptors with `EBADF`, so callers must
    /// invoke [`validate_private_regular_file`] on the proc-derived RDONLY or
    /// RDWR descriptor before content I/O.
    fn validate_private_regular_file_metadata(
        descriptor: &OwnedFd,
        witness: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::NotRegularFile,
                stage,
            ));
        }
        if witness.hard_links != 1 {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::HardLinked, stage)
                    .with_counts(1, witness.hard_links),
            );
        }
        validate_owner_mode(witness, expectation.expected_mode(), stage)?;
        if witness.byte_len != expectation.byte_len {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::SizeMismatch, stage)
                    .with_counts(expectation.byte_len, witness.byte_len),
            );
        }
        Ok(())
    }

    fn validate_owner_mode(
        witness: GenerationRootObjectWitness,
        expected_mode: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let effective_uid = rustix::process::geteuid().as_raw();
        if witness.uid != effective_uid {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::WrongOwner, stage)
                    .with_counts(u64::from(effective_uid), u64::from(witness.uid)),
            );
        }
        let actual_mode = witness.mode & MODE_PERMISSIONS_MASK;
        if actual_mode != expected_mode {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::WrongMode, stage)
                    .with_counts(u64::from(expected_mode), u64::from(actual_mode)),
            );
        }
        Ok(())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_owner_mode_for_test(
        witness: GenerationRootObjectWitness,
        expected_mode: u32,
    ) -> GenerationRootResult<()> {
        validate_owner_mode(
            witness,
            expected_mode,
            GenerationRootStage::QualifyRootSecurity,
        )
    }

    fn os_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        GenerationRootError::new(GenerationRootErrorKind::Io, stage)
            .with_raw_os_error(error.raw_os_error())
    }

    fn usize_as_u64(value: usize) -> u64 {
        u64::try_from(value).unwrap_or(u64::MAX)
    }

    pub(super) fn stat_mode_as_u32<T>(mode: T) -> u32
    where
        u32: From<T>,
    {
        u32::from(mode)
    }

    pub(super) fn stat_inode_as_u64<T>(inode: T) -> u64
    where
        u64: From<T>,
    {
        u64::from(inode)
    }

    pub(super) fn stat_link_count_as_u64<T>(link_count: T) -> u64
    where
        u64: From<T>,
    {
        u64::from(link_count)
    }

    pub(super) fn stat_seconds_as_i64<T>(seconds: T) -> i64
    where
        i64: From<T>,
    {
        i64::from(seconds)
    }

    #[cfg(target_os = "linux")]
    fn open_absolute_route(
        route: &AbsoluteRoute,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OpenedRoute> {
        use rustix::fs::{CWD, ResolveFlags, openat2};

        let flags = OFlags::RDONLY
            | OFlags::DIRECTORY
            | OFlags::NOFOLLOW
            | OFlags::CLOEXEC
            | OFlags::NONBLOCK;
        let mut descriptor = openat2(
            CWD,
            Path::new("/"),
            flags,
            Mode::empty(),
            ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
        )
        .map_err(|error| linux_open_error(stage, error))?;
        let mut route_identities = Vec::new();
        route_identities
            .try_reserve(route.components.len() + 1)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        route_identities.push(qualify_absolute_ancestor(&descriptor, stage, None)?);
        for (index, component) in route.components.iter().enumerate() {
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeRootComponentOpen { index })?;
            verify_exact_directory_entry(&descriptor, component, stage, index)?;
            let next = openat2(
                &descriptor,
                component,
                flags,
                Mode::empty(),
                ResolveFlags::BENEATH | ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
            )
            .map_err(|error| {
                linux_component_open_error(&descriptor, component, stage, index, error)
            })?;
            verify_exact_directory_entry(&descriptor, component, stage, index)?;
            descriptor = next;
            let stat = fstat(&descriptor).map_err(|error| os_error(stage, error))?;
            if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
                return Err(
                    GenerationRootError::new(GenerationRootErrorKind::NotDirectory, stage)
                        .at_component(index),
                );
            }
            let identity = if index + 1 == route.components.len() {
                basic_identity(&descriptor, stage)?
            } else {
                qualify_absolute_ancestor(&descriptor, stage, Some(index))?
            };
            #[cfg(test)]
            test_boundary(TestBoundary::AfterRootComponentOpen { index })?;
            route_identities.push(identity);
        }
        Ok(OpenedRoute {
            descriptor,
            route_identities,
        })
    }

    #[cfg(target_os = "linux")]
    fn open_relative_directory_component(
        parent: &OwnedFd,
        component: &OsStr,
        index: usize,
        root: GenerationRootObjectWitness,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OwnedFd> {
        use rustix::fs::{ResolveFlags, openat2};

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRelativeDirectoryOpen { index })?;
        verify_exact_directory_entry(parent, component, stage, index)?;
        let descriptor = openat2(
            parent,
            component,
            OFlags::RDONLY
                | OFlags::DIRECTORY
                | OFlags::NOFOLLOW
                | OFlags::CLOEXEC
                | OFlags::NONBLOCK,
            Mode::empty(),
            ResolveFlags::BENEATH
                | ResolveFlags::NO_SYMLINKS
                | ResolveFlags::NO_MAGICLINKS
                | ResolveFlags::NO_XDEV,
        )
        .map_err(|error| linux_component_open_error(parent, component, stage, index, error))?;
        verify_exact_directory_entry(parent, component, stage, index)?;
        let witness = object_witness(&descriptor, root.filesystem, root.mount_identity, stage)?;
        if witness.mount_identity != root.mount_identity {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::CrossDevice, stage)
                    .at_component(index),
            );
        }
        validate_private_directory(&descriptor, witness, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRelativeDirectoryOpen { index })?;
        Ok(descriptor)
    }

    #[cfg(target_os = "linux")]
    fn open_regular_component(
        parent: &OwnedFd,
        component: &OsStr,
        index: usize,
        root: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
        writable: bool,
        creator_process_id: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OwnedFd> {
        use rustix::fs::openat;

        let access = if writable {
            OFlags::RDWR
        } else {
            OFlags::RDONLY
        };
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRegularFileOpen { index })?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFinalProbeOpen { index })?;
        let (probe, probe_witness) =
            probe_regular_component(parent, component, index, root, expectation, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProbeQualified { index })?;
        validate_process_identity(creator_process_id, stage)?;
        let (proc_root, proc_mount_id) = open_verified_proc_root(creator_process_id, stage)?;
        let probe_route = proc_thread_fd_route(probe.as_raw_fd());
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeProcFdReopen { index })?;
        validate_proc_bridge_entry(
            &proc_root,
            &probe_route,
            proc_mount_id,
            index,
            ProcBridgeProbePhase::BeforeDataOpen,
            stage,
        )?;
        validate_proc_self_binding(
            &proc_root,
            creator_process_id,
            ProcSelfBindingPhase::BeforeDataOpen,
            stage,
        )?;
        let descriptor = loop {
            match openat(
                &proc_root,
                &probe_route,
                access | OFlags::CLOEXEC | OFlags::NONBLOCK | OFlags::NOATIME,
                Mode::empty(),
            ) {
                Ok(descriptor) => break descriptor,
                Err(error) if error == Errno::INTR => {}
                Err(error) if error == Errno::PERM || error == Errno::ACCESS => {
                    validate_process_identity(creator_process_id, stage)
                        .map_err(|process_error| process_error.at_component(index))?;
                    let retained_probe =
                        object_witness(&probe, root.filesystem, root.mount_identity, stage)
                            .map_err(|witness_error| witness_error.at_component(index))?;
                    if !probe_witness.mutation_stable_eq(retained_probe) {
                        return Err(GenerationRootError::new(
                            GenerationRootErrorKind::ObjectChanged,
                            stage,
                        )
                        .at_component(index));
                    }
                    return Err(proc_bridge_error(stage, error).at_component(index));
                }
                Err(error) => {
                    return Err(proc_bridge_error(stage, error).at_component(index));
                }
            }
        };
        validate_proc_self_binding(
            &proc_root,
            creator_process_id,
            ProcSelfBindingPhase::AfterDataOpen,
            stage,
        )
        .map_err(|error| error.at_component(index))?;
        validate_proc_bridge_entry(
            &proc_root,
            &probe_route,
            proc_mount_id,
            index,
            ProcBridgeProbePhase::AfterDataOpen,
            stage,
        )?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProcFdReopen { index })?;
        let reopened_witness =
            object_witness(&descriptor, root.filesystem, root.mount_identity, stage)?;
        validate_private_regular_file(&descriptor, reopened_witness, expectation, stage)?;
        if !probe_witness.mutation_stable_eq(reopened_witness) {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index),
            );
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFinalRouteProbe { index })?;
        let (_final_probe, final_probe_witness) =
            probe_regular_component(parent, component, index, root, expectation, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFinalRouteProbe { index })?;
        if !probe_witness.mutation_stable_eq(final_probe_witness)
            || !reopened_witness.mutation_stable_eq(final_probe_witness)
        {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index),
            );
        }
        #[cfg(test)]
        {
            let cloexec = rustix::io::fcntl_getfd(&descriptor)
                .map_err(|error| os_error(stage, error).at_component(index))?
                .contains(rustix::io::FdFlags::CLOEXEC);
            test_boundary(TestBoundary::AfterRegularFileOpen { index, cloexec })?;
        }
        validate_process_identity(creator_process_id, stage)?;
        Ok(descriptor)
    }

    #[cfg(target_os = "linux")]
    fn proc_thread_fd_route(raw_fd: RawFd) -> String {
        format!("thread-self/fd/{raw_fd}")
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn proc_thread_fd_route_for_test(raw_fd: RawFd) -> String {
        proc_thread_fd_route(raw_fd)
    }

    #[cfg(target_os = "linux")]
    fn probe_regular_component(
        parent: &OwnedFd,
        component: &OsStr,
        index: usize,
        root: GenerationRootObjectWitness,
        expectation: GenerationFileExpectation,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<(OwnedFd, GenerationRootObjectWitness)> {
        use rustix::fs::{ResolveFlags, openat2};

        verify_exact_directory_entry(parent, component, stage, index)?;
        let probe = openat2(
            parent,
            component,
            OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
            Mode::empty(),
            ResolveFlags::BENEATH
                | ResolveFlags::NO_SYMLINKS
                | ResolveFlags::NO_MAGICLINKS
                | ResolveFlags::NO_XDEV,
        )
        .map_err(|error| linux_open_error(stage, error).at_component(index))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFinalProbeOpen { index })?;
        verify_exact_directory_entry(parent, component, stage, index)?;
        validate_regular_descriptor_type(&probe, stage, index)?;
        let witness = object_witness(&probe, root.filesystem, root.mount_identity, stage)?;
        if witness.mount_identity != root.mount_identity {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::CrossDevice, stage)
                    .at_component(index),
            );
        }
        validate_private_regular_file_metadata(&probe, witness, expectation, stage)?;
        Ok((probe, witness))
    }

    #[cfg(target_os = "linux")]
    pub(super) fn validate_regular_descriptor_type(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
        index: usize,
    ) -> GenerationRootResult<()> {
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error).at_component(index))?;
        match FileType::from_raw_mode(stat.st_mode) {
            FileType::RegularFile => Ok(()),
            FileType::Symlink => Err(GenerationRootError::new(
                GenerationRootErrorKind::SymbolicLink,
                stage,
            )
            .at_component(index)),
            _ => Err(
                GenerationRootError::new(GenerationRootErrorKind::NotRegularFile, stage)
                    .at_component(index),
            ),
        }
    }

    #[cfg(target_os = "linux")]
    fn open_verified_proc_root(
        process_id: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<(OwnedFd, u64)> {
        use rustix::fs::{CWD, ResolveFlags, openat2};

        validate_process_identity(process_id, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeProcCapabilityRootOpen)?;
        let descriptor = loop {
            match openat2(
                CWD,
                Path::new("/proc"),
                OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
                ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
            ) {
                Ok(descriptor) => break descriptor,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_root_error(stage, error));
                }
            }
        };
        let filesystem = loop {
            match fstatfs(&descriptor) {
                Ok(filesystem) => break filesystem,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_root_error(stage, error));
                }
            }
        };
        if i128::from(filesystem.f_type) != i128::from(libc::PROC_SUPER_MAGIC) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedKernelFeature,
                stage,
            ));
        }
        let stat = loop {
            match fstat(&descriptor) {
                Ok(stat) => break stat,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_root_error(stage, error));
                }
            }
        };
        if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedKernelFeature,
                stage,
            ));
        }
        let proc_mount_id = proc_mount_id(&descriptor, stage)?;
        validate_proc_self_binding(
            &descriptor,
            process_id,
            ProcSelfBindingPhase::RootQualification,
            stage,
        )?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProcCapabilityRootOpen)?;
        validate_process_identity(process_id, stage)?;
        Ok((descriptor, proc_mount_id))
    }

    #[cfg(target_os = "linux")]
    fn validate_proc_self_binding(
        proc_root: &OwnedFd,
        process_id: u32,
        phase: ProcSelfBindingPhase,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        use rustix::fs::readlinkat;

        let _ = phase;

        if process_id != std::process::id() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                stage,
            ));
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeProcSelfReadlink { phase })?;
        let target = loop {
            match readlinkat(proc_root, "self", Vec::new()) {
                Ok(target) => break target,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error));
                }
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProcSelfReadlink { phase })?;
        if process_id != std::process::id() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                stage,
            ));
        }
        if target.as_bytes() != process_id.to_string().as_bytes() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        let thread_id = rustix::thread::gettid();
        let expected_thread_target = format!("{process_id}/task/{thread_id}");
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeProcThreadSelfReadlink { phase })?;
        let thread_target = loop {
            match readlinkat(proc_root, "thread-self", Vec::new()) {
                Ok(target) => break target,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error));
                }
            }
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProcThreadSelfReadlink { phase })?;
        if process_id != std::process::id() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ForkedProcess,
                stage,
            ));
        }
        if thread_target.as_bytes() != expected_thread_target.as_bytes() {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn validate_proc_bridge_entry(
        proc_root: &OwnedFd,
        probe_route: &str,
        expected_proc_mount_id: u64,
        index: usize,
        phase: ProcBridgeProbePhase,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        use rustix::fs::{ResolveFlags, openat2};

        let _ = phase;

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeProcBridgeProbe { index, phase })?;
        let descriptor = loop {
            match openat2(
                proc_root,
                probe_route,
                OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
                ResolveFlags::NO_XDEV,
            ) {
                Ok(descriptor) => break descriptor,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error).at_component(index));
                }
            }
        };
        let stat = loop {
            match fstat(&descriptor) {
                Ok(stat) => break stat,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error).at_component(index));
                }
            }
        };
        if FileType::from_raw_mode(stat.st_mode) != FileType::Symlink {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index),
            );
        }
        let filesystem = loop {
            match fstatfs(&descriptor) {
                Ok(filesystem) => break filesystem,
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error).at_component(index));
                }
            }
        };
        if i128::from(filesystem.f_type) != i128::from(libc::PROC_SUPER_MAGIC) {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index),
            );
        }
        let observed_mount_id =
            proc_mount_id(&descriptor, stage).map_err(|error| error.at_component(index))?;
        if observed_mount_id != expected_proc_mount_id {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index)
                    .with_counts(expected_proc_mount_id, observed_mount_id),
            );
        }
        #[cfg(test)]
        test_boundary(TestBoundary::AfterProcBridgeProbe { index, phase })?;
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn proc_mount_id(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<u64> {
        let extended = proc_statx(descriptor, stage)?;
        validate_proc_mount_id_mask(
            rustix::fs::StatxFlags::from_bits_retain(extended.stx_mask),
            extended.stx_mnt_id,
            stage,
        )
    }

    #[cfg(target_os = "linux")]
    fn proc_statx(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<rustix::fs::Statx> {
        use rustix::fs::{AtFlags, StatxFlags, statx};

        loop {
            match statx(
                descriptor,
                "",
                AtFlags::EMPTY_PATH | AtFlags::NO_AUTOMOUNT,
                StatxFlags::BASIC_STATS | StatxFlags::MNT_ID,
            ) {
                Ok(extended) => return Ok(extended),
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(proc_bridge_error(stage, error));
                }
            }
        }
    }

    #[cfg(target_os = "linux")]
    fn validate_proc_mount_id_mask(
        returned_mask: rustix::fs::StatxFlags,
        mount_id: u64,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<u64> {
        if returned_mask.contains(rustix::fs::StatxFlags::MNT_ID) {
            Ok(mount_id)
        } else {
            Err(
                GenerationRootError::new(GenerationRootErrorKind::UnsupportedKernelFeature, stage)
                    .with_counts(
                        u64::from(rustix::fs::StatxFlags::MNT_ID.bits()),
                        u64::from(returned_mask.bits() & rustix::fs::StatxFlags::MNT_ID.bits()),
                    ),
            )
        }
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_proc_mount_id_mask_for_test(
        returned_mask: rustix::fs::StatxFlags,
        mount_id: u64,
    ) -> GenerationRootResult<u64> {
        validate_proc_mount_id_mask(
            returned_mask,
            mount_id,
            GenerationRootStage::OpenRegularFile,
        )
    }

    #[cfg(target_os = "linux")]
    fn proc_bridge_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        let kind = if error == Errno::MFILE || error == Errno::NFILE || error == Errno::NOMEM {
            GenerationRootErrorKind::ResourceLimit
        } else if error == Errno::NOSYS || error == Errno::PERM || error == Errno::ACCESS {
            GenerationRootErrorKind::UnsupportedKernelFeature
        } else if error == Errno::NOENT
            || error == Errno::NOTDIR
            || error == Errno::LOOP
            || error == Errno::XDEV
            || error == Errno::STALE
        {
            GenerationRootErrorKind::ObjectChanged
        } else {
            GenerationRootErrorKind::Io
        };
        GenerationRootError::new(kind, stage).with_raw_os_error(error.raw_os_error())
    }

    #[cfg(target_os = "linux")]
    fn proc_root_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        let kind = if error == Errno::MFILE || error == Errno::NFILE || error == Errno::NOMEM {
            GenerationRootErrorKind::ResourceLimit
        } else if error == Errno::NOSYS
            || error == Errno::PERM
            || error == Errno::ACCESS
            || error == Errno::NOENT
            || error == Errno::NOTDIR
            || error == Errno::LOOP
            || error == Errno::XDEV
        {
            GenerationRootErrorKind::UnsupportedKernelFeature
        } else {
            GenerationRootErrorKind::Io
        };
        GenerationRootError::new(kind, stage).with_raw_os_error(error.raw_os_error())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn proc_bridge_error_for_test(error: Errno) -> GenerationRootError {
        proc_bridge_error(GenerationRootStage::OpenRegularFile, error)
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn proc_root_error_for_test(error: Errno) -> GenerationRootError {
        proc_root_error(GenerationRootStage::OpenRegularFile, error)
    }

    #[cfg(target_os = "linux")]
    fn route_mount_identity(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<[u8; 32]> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRouteMountIdentity)?;
        let filesystem_stat = fstatfs(descriptor).map_err(|error| os_error(stage, error))?;
        let extended = linux_statx(
            descriptor,
            stage,
            linux_filesystem_is_btrfs(filesystem_stat.f_type),
        )?;
        let identity =
            linux_filesystem_namespace_identity(filesystem_stat.f_type, &extended, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRouteMountIdentity)?;
        Ok(identity)
    }

    #[cfg(target_os = "linux")]
    fn qualify_filesystem(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<(QualifiedFilesystem, [u8; 32])> {
        use rustix::fs::StatVfsMountFlags;

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFilesystemQualification)?;
        let filesystem_stat = fstatfs(descriptor).map_err(|error| os_error(stage, error))?;
        let mount_stat = fstatvfs(descriptor).map_err(|error| os_error(stage, error))?;
        if mount_stat.f_flag.contains(StatVfsMountFlags::RDONLY) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ReadOnlyFilesystem,
                stage,
            ));
        }
        let extended = linux_statx(
            descriptor,
            stage,
            linux_filesystem_is_btrfs(filesystem_stat.f_type),
        )?;
        let filesystem =
            linux_filesystem_profile_at_stage(filesystem_stat.f_type, extended.stx_mnt_id, stage)?;
        let mount_identity =
            linux_filesystem_namespace_identity(filesystem_stat.f_type, &extended, stage)?;
        let qualified = (filesystem, mount_identity);
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFilesystemQualification)?;
        Ok(qualified)
    }

    #[cfg(target_os = "linux")]
    fn object_witness(
        descriptor: &OwnedFd,
        expected_filesystem: QualifiedFilesystem,
        expected_mount_identity: [u8; 32],
        stage: GenerationRootStage,
    ) -> GenerationRootResult<GenerationRootObjectWitness> {
        use rustix::fs::StatxFlags;

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeObjectWitness)?;
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        let filesystem_stat = fstatfs(descriptor).map_err(|error| os_error(stage, error))?;
        let extended = linux_statx(
            descriptor,
            stage,
            linux_filesystem_is_btrfs(filesystem_stat.f_type),
        )?;
        let mask = StatxFlags::from_bits_retain(extended.stx_mask);
        if !mask.contains(StatxFlags::BASIC_STATS) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedKernelFeature,
                stage,
            ));
        }
        validate_linux_writable_attributes(
            extended.stx_attributes,
            extended.stx_attributes_mask,
            stage,
        )?;
        if !linux_filesystem_type_matches(expected_filesystem, filesystem_stat.f_type) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::CrossDevice,
                stage,
            ));
        }
        let mount_identity =
            linux_filesystem_namespace_identity(filesystem_stat.f_type, &extended, stage)?;
        if mount_identity != expected_mount_identity {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::CrossDevice,
                stage,
            ));
        }
        let size = u64::try_from(stat.st_size)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        let mode = stat_mode_as_u32(stat.st_mode);
        let inode = stat_inode_as_u64(stat.st_ino);
        let hard_links = stat_link_count_as_u64(stat.st_nlink);
        let modified_seconds = stat_seconds_as_i64(stat.st_mtime);
        let changed_seconds = stat_seconds_as_i64(stat.st_ctime);
        let accessed_seconds = stat_seconds_as_i64(stat.st_atime);
        let modified_nanoseconds = i64::try_from(stat.st_mtime_nsec)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        let changed_nanoseconds = i64::try_from(stat.st_ctime_nsec)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        let accessed_nanoseconds = i64::try_from(stat.st_atime_nsec)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        let stat_device_major = rustix::fs::major(stat.st_dev);
        let stat_device_minor = rustix::fs::minor(stat.st_dev);
        if !linux_device_components_match(
            stat_device_major,
            stat_device_minor,
            extended.stx_dev_major,
            extended.stx_dev_minor,
        ) || u32::from(extended.stx_mode) != mode
            || u64::from(extended.stx_nlink) != hard_links
            || extended.stx_uid != stat.st_uid
            || extended.stx_gid != stat.st_gid
            || extended.stx_ino != inode
            || extended.stx_size != size
            || extended.stx_mtime.tv_sec != modified_seconds
            || i64::from(extended.stx_mtime.tv_nsec) != modified_nanoseconds
            || extended.stx_ctime.tv_sec != changed_seconds
            || i64::from(extended.stx_ctime.tv_nsec) != changed_nanoseconds
            || extended.stx_atime.tv_sec != accessed_seconds
            || i64::from(extended.stx_atime.tv_nsec) != accessed_nanoseconds
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        let witness = GenerationRootObjectWitness {
            device: stat_device_as_u64(stat.st_dev),
            inode,
            mode,
            hard_links,
            uid: stat.st_uid,
            gid: stat.st_gid,
            byte_len: size,
            modified_seconds,
            modified_nanoseconds,
            changed_seconds,
            changed_nanoseconds,
            accessed_seconds,
            accessed_nanoseconds,
            mount_identity,
            filesystem: expected_filesystem,
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterObjectWitness)?;
        Ok(witness)
    }

    #[cfg(target_os = "linux")]
    const fn linux_device_components_match(
        legacy_device_major: u32,
        legacy_device_minor: u32,
        extended_device_major: u32,
        extended_device_minor: u32,
    ) -> bool {
        legacy_device_major == extended_device_major && legacy_device_minor == extended_device_minor
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) const fn linux_device_components_match_for_test(
        legacy_device_major: u32,
        legacy_device_minor: u32,
        extended_device_major: u32,
        extended_device_minor: u32,
    ) -> bool {
        linux_device_components_match(
            legacy_device_major,
            legacy_device_minor,
            extended_device_major,
            extended_device_minor,
        )
    }

    #[cfg(target_os = "linux")]
    fn validate_linux_writable_attributes(
        attributes: rustix::fs::StatxAttributes,
        attributes_mask: rustix::fs::StatxAttributes,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        use rustix::fs::StatxAttributes;

        let required = StatxAttributes::IMMUTABLE | StatxAttributes::APPEND;
        if !attributes_mask.contains(required) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedKernelFeature,
                stage,
            )
            .with_counts(required.bits(), attributes_mask.bits() & required.bits()));
        }
        let observed = attributes & required;
        if observed.is_empty() {
            Ok(())
        } else {
            Err(
                GenerationRootError::new(GenerationRootErrorKind::WriteRestrictedObject, stage)
                    .with_counts(0, observed.bits()),
            )
        }
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_linux_writable_attributes_for_test(
        attributes: rustix::fs::StatxAttributes,
        attributes_mask: rustix::fs::StatxAttributes,
    ) -> GenerationRootResult<()> {
        validate_linux_writable_attributes(
            attributes,
            attributes_mask,
            GenerationRootStage::QualifyFilesystem,
        )
    }

    #[cfg(target_os = "linux")]
    fn linux_statx(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
        request_subvolume: bool,
    ) -> GenerationRootResult<rustix::fs::Statx> {
        use rustix::fs::{AtFlags, StatxFlags, statx};

        let mut requested = StatxFlags::BASIC_STATS | StatxFlags::MNT_ID;
        if request_subvolume {
            requested |= StatxFlags::from_bits_retain(LINUX_STATX_SUBVOLUME_MASK);
        }
        loop {
            match statx(
                descriptor,
                "",
                AtFlags::EMPTY_PATH | AtFlags::NO_AUTOMOUNT,
                requested,
            ) {
                Ok(extended) => return Ok(extended),
                Err(error) if error == Errno::INTR => {}
                Err(error) => {
                    return Err(
                        if error == Errno::NOSYS
                            || error == Errno::PERM
                            || (request_subvolume && error == Errno::INVAL)
                        {
                            GenerationRootError::new(
                                GenerationRootErrorKind::UnsupportedKernelFeature,
                                stage,
                            )
                            .with_raw_os_error(error.raw_os_error())
                        } else if error == Errno::MFILE
                            || error == Errno::NFILE
                            || error == Errno::NOMEM
                        {
                            GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                                .with_raw_os_error(error.raw_os_error())
                        } else {
                            os_error(stage, error)
                        },
                    );
                }
            }
        }
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn linux_filesystem_profile(
        raw_type: rustix::fs::FsWord,
        mount_id: u64,
    ) -> GenerationRootResult<QualifiedFilesystem> {
        linux_filesystem_profile_at_stage(
            raw_type,
            mount_id,
            GenerationRootStage::QualifyFilesystem,
        )
    }

    #[cfg(target_os = "linux")]
    fn linux_filesystem_profile_at_stage(
        raw_type: rustix::fs::FsWord,
        mount_id: u64,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<QualifiedFilesystem> {
        let raw = i128::from(raw_type);
        let (expected_name, profile) = if raw == i128::from(libc::EXT4_SUPER_MAGIC) {
            (b"ext4".as_slice(), QualifiedFilesystem::LinuxExt4)
        } else if raw == i128::from(libc::BTRFS_SUPER_MAGIC) {
            (b"btrfs".as_slice(), QualifiedFilesystem::LinuxBtrfs)
        } else {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        };
        let observed_name = linux_mountinfo_filesystem(mount_id, stage)?;
        if observed_name.as_slice() != expected_name {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        }
        Ok(profile)
    }

    #[cfg(target_os = "linux")]
    fn linux_filesystem_type_matches(
        expected: QualifiedFilesystem,
        raw_type: rustix::fs::FsWord,
    ) -> bool {
        let raw = i128::from(raw_type);
        match expected {
            QualifiedFilesystem::LinuxExt4 => raw == i128::from(libc::EXT4_SUPER_MAGIC),
            QualifiedFilesystem::LinuxBtrfs => raw == i128::from(libc::BTRFS_SUPER_MAGIC),
            QualifiedFilesystem::AppleApfs => false,
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_filesystem_is_btrfs(raw_type: rustix::fs::FsWord) -> bool {
        i128::from(raw_type) == i128::from(libc::BTRFS_SUPER_MAGIC)
    }

    #[cfg(target_os = "linux")]
    fn linux_filesystem_namespace_identity(
        raw_type: rustix::fs::FsWord,
        extended: &rustix::fs::Statx,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<[u8; 32]> {
        use rustix::fs::StatxFlags;

        let mask = StatxFlags::from_bits_retain(extended.stx_mask);
        if !mask.contains(StatxFlags::MNT_ID) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedKernelFeature,
                stage,
            ));
        }
        let subvolume_id = if linux_filesystem_is_btrfs(raw_type) {
            let subvolume_mask = StatxFlags::from_bits_retain(LINUX_STATX_SUBVOLUME_MASK);
            if !mask.contains(subvolume_mask) {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::UnsupportedKernelFeature,
                    stage,
                ));
            }
            // This is the kernel-authenticated value for the already-open
            // descriptor (`AT_EMPTY_PATH`), not a pathname re-resolution.
            // Keeping it as the sole source of truth also avoids imposing
            // consumer-side bindgen and libclang prerequisites for Btrfs.
            Some(extended.stx_subvol)
        } else {
            None
        };
        Ok(linux_filesystem_namespace_digest(
            raw_type,
            extended.stx_mnt_id,
            subvolume_id,
        ))
    }

    #[cfg(target_os = "linux")]
    fn validate_root_writable(
        descriptor: &OwnedFd,
        filesystem: QualifiedFilesystem,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        use rustix::fs::{Access, AtFlags, accessat};

        if filesystem != QualifiedFilesystem::LinuxBtrfs {
            return Ok(());
        }
        match accessat(
            descriptor,
            ".",
            Access::WRITE_OK,
            AtFlags::EACCESS | AtFlags::SYMLINK_NOFOLLOW,
        ) {
            Ok(()) => Ok(()),
            Err(error) if error == Errno::ROFS => Err(GenerationRootError::new(
                GenerationRootErrorKind::ReadOnlyFilesystem,
                stage,
            )
            .with_raw_os_error(error.raw_os_error())),
            Err(error) if error == Errno::NOSYS || error == Errno::PERM => Err(
                GenerationRootError::new(GenerationRootErrorKind::UnsupportedKernelFeature, stage)
                    .with_raw_os_error(error.raw_os_error()),
            ),
            Err(error) => Err(os_error(stage, error)),
        }
    }

    #[cfg(target_os = "linux")]
    fn linux_mountinfo_filesystem(
        mount_id: u64,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<Vec<u8>> {
        use rustix::fs::{ResolveFlags, openat2};
        use rustix::io::read;

        let process_id = std::process::id();
        let thread_id = rustix::thread::gettid();
        let path = linux_task_mountinfo_route(process_id, thread_id.as_raw_pid());
        validate_process_identity(process_id, stage)?;
        let (proc_root, _proc_mount_id) = open_verified_proc_root(process_id, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeMountInfoOpen)?;
        let descriptor = openat2(
            &proc_root,
            &path,
            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC | OFlags::NONBLOCK,
            Mode::empty(),
            ResolveFlags::BENEATH
                | ResolveFlags::NO_SYMLINKS
                | ResolveFlags::NO_MAGICLINKS
                | ResolveFlags::NO_XDEV,
        )
        .map_err(|error| linux_mountinfo_error(stage, error))?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterMountInfoOpen)?;
        validate_process_identity(process_id, stage)?;
        if rustix::thread::gettid() != thread_id {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                stage,
            ));
        }
        let filesystem_stat =
            fstatfs(&descriptor).map_err(|error| linux_mountinfo_error(stage, error))?;
        if i128::from(filesystem_stat.f_type) != i128::from(libc::PROC_SUPER_MAGIC) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        }
        let stat = fstat(&descriptor).map_err(|error| linux_mountinfo_error(stage, error))?;
        if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        }
        let mut bytes = Vec::new();
        bytes
            .try_reserve(64 * 1024)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        let mut chunk = [0_u8; 8192];
        loop {
            let requested = mountinfo_read_request(bytes.len());
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeMountInfoRead)?;
            let count = match read(&descriptor, &mut chunk[..requested]) {
                Ok(count) => count,
                Err(error) if error == Errno::INTR => continue,
                Err(error) => return Err(linux_mountinfo_error(stage, error)),
            };
            #[cfg(test)]
            test_boundary(TestBoundary::AfterMountInfoRead { byte_count: count })?;
            validate_process_identity(process_id, stage)?;
            if rustix::thread::gettid() != thread_id {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::ObjectChanged,
                    stage,
                ));
            }
            if count == 0 {
                break;
            }
            validate_mountinfo_append(bytes.len(), count, stage)?;
            bytes.extend_from_slice(&chunk[..count]);
        }
        validate_proc_self_binding(
            &proc_root,
            process_id,
            ProcSelfBindingPhase::MountInfoRead,
            stage,
        )?;
        parse_mountinfo_filesystem_at_stage(&bytes, mount_id, stage)
    }

    #[cfg(target_os = "linux")]
    fn linux_mountinfo_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        let kind = if error == Errno::MFILE || error == Errno::NFILE || error == Errno::NOMEM {
            GenerationRootErrorKind::ResourceLimit
        } else {
            GenerationRootErrorKind::Io
        };
        GenerationRootError::new(kind, stage).with_raw_os_error(error.raw_os_error())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn linux_mountinfo_error_for_test(error: Errno) -> GenerationRootError {
        linux_mountinfo_error(GenerationRootStage::QualifyFilesystem, error)
    }

    #[cfg(target_os = "linux")]
    fn linux_task_mountinfo_route(process_id: u32, thread_id: i32) -> std::path::PathBuf {
        std::path::PathBuf::from(process_id.to_string())
            .join("task")
            .join(thread_id.to_string())
            .join("mountinfo")
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn linux_task_mountinfo_route_for_test(
        process_id: u32,
        thread_id: i32,
    ) -> std::path::PathBuf {
        linux_task_mountinfo_route(process_id, thread_id)
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn linux_mountinfo_filesystem_for_test(
        mount_id: u64,
    ) -> GenerationRootResult<Vec<u8>> {
        linux_mountinfo_filesystem(mount_id, GenerationRootStage::QualifyFilesystem)
    }

    #[cfg(target_os = "linux")]
    fn mountinfo_read_request(stored_bytes: usize) -> usize {
        GENERATION_ROOT_MAX_MOUNTINFO_BYTES
            .saturating_sub(stored_bytes)
            .saturating_add(1)
            .min(8192)
    }

    #[cfg(target_os = "linux")]
    fn validate_mountinfo_append(
        stored_bytes: usize,
        incoming_bytes: usize,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let observed = stored_bytes.saturating_add(incoming_bytes);
        if observed > GENERATION_ROOT_MAX_MOUNTINFO_BYTES {
            Err(
                GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                    .with_counts(
                        usize_as_u64(GENERATION_ROOT_MAX_MOUNTINFO_BYTES),
                        usize_as_u64(observed),
                    ),
            )
        } else {
            Ok(())
        }
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_mountinfo_bound_for_test(
        stored_bytes: usize,
        incoming_bytes: usize,
    ) -> (usize, GenerationRootResult<()>) {
        (
            mountinfo_read_request(stored_bytes),
            validate_mountinfo_append(
                stored_bytes,
                incoming_bytes,
                GenerationRootStage::QualifyFilesystem,
            ),
        )
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn parse_mountinfo_filesystem(
        bytes: &[u8],
        mount_id: u64,
    ) -> GenerationRootResult<Vec<u8>> {
        parse_mountinfo_filesystem_at_stage(bytes, mount_id, GenerationRootStage::QualifyFilesystem)
    }

    #[cfg(target_os = "linux")]
    fn parse_mountinfo_filesystem_at_stage(
        bytes: &[u8],
        mount_id: u64,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<Vec<u8>> {
        let mut matched = None;
        for line in bytes.split(|byte| *byte == b'\n') {
            let mut fields = line.split(|byte| *byte == b' ');
            let Some(observed_mount_id) = fields.next() else {
                continue;
            };
            if parse_ascii_u64(observed_mount_id) != Some(mount_id) {
                continue;
            }
            let filesystem = loop {
                let field = fields.next().ok_or_else(|| {
                    GenerationRootError::new(GenerationRootErrorKind::UnsupportedFilesystem, stage)
                })?;
                if field == b"-" {
                    break fields.next().ok_or_else(|| {
                        GenerationRootError::new(
                            GenerationRootErrorKind::UnsupportedFilesystem,
                            stage,
                        )
                    })?;
                }
            };
            let mount_source = fields.next().ok_or_else(|| {
                GenerationRootError::new(GenerationRootErrorKind::UnsupportedFilesystem, stage)
            })?;
            let super_options = fields.next().ok_or_else(|| {
                GenerationRootError::new(GenerationRootErrorKind::UnsupportedFilesystem, stage)
            })?;
            if filesystem.is_empty() || mount_source.is_empty() || super_options.is_empty() {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::UnsupportedFilesystem,
                    stage,
                ));
            }
            let mut owned_filesystem = Vec::new();
            owned_filesystem
                .try_reserve_exact(filesystem.len())
                .map_err(|_| {
                    GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                })?;
            owned_filesystem.extend_from_slice(filesystem);
            if matched.replace(owned_filesystem).is_some() {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::UnsupportedFilesystem,
                    stage,
                ));
            }
        }
        matched.ok_or_else(|| {
            GenerationRootError::new(GenerationRootErrorKind::UnsupportedFilesystem, stage)
        })
    }

    #[cfg(target_os = "linux")]
    fn parse_ascii_u64(bytes: &[u8]) -> Option<u64> {
        if bytes.is_empty() {
            return None;
        }
        let mut value = 0_u64;
        for byte in bytes {
            let digit = byte.checked_sub(b'0')?;
            if digit > 9 {
                return None;
            }
            value = value.checked_mul(10)?.checked_add(u64::from(digit))?;
        }
        Some(value)
    }

    #[cfg(target_os = "linux")]
    pub(super) fn linux_filesystem_namespace_digest(
        raw_type: rustix::fs::FsWord,
        mount_id: u64,
        subvolume_id: Option<u64>,
    ) -> [u8; 32] {
        let mut digest = Sha256::new();
        digest.update(b"frankensearch.generation-root.linux-namespace.v2");
        digest.update(i128::from(raw_type).to_le_bytes());
        digest.update(mount_id.to_le_bytes());
        match subvolume_id {
            Some(subvolume_id) => {
                digest.update([1]);
                digest.update(subvolume_id.to_le_bytes());
            }
            None => digest.update([0]),
        }
        digest.finalize().into()
    }

    #[cfg(target_os = "linux")]
    const fn stat_device_as_u64(device: u64) -> u64 {
        device
    }

    #[cfg(target_os = "linux")]
    fn linux_component_open_error(
        parent: &OwnedFd,
        component: &OsStr,
        stage: GenerationRootStage,
        index: usize,
        error: Errno,
    ) -> GenerationRootError {
        use rustix::fs::{AtFlags, statat};

        if error == Errno::NOTDIR
            && statat(parent, component, AtFlags::SYMLINK_NOFOLLOW)
                .is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) == FileType::Symlink)
        {
            return GenerationRootError::new(GenerationRootErrorKind::SymbolicLink, stage)
                .at_component(index)
                .with_raw_os_error(error.raw_os_error());
        }
        linux_open_error(stage, error).at_component(index)
    }

    #[cfg(target_os = "linux")]
    fn linux_open_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        let kind = if error == Errno::LOOP {
            GenerationRootErrorKind::SymbolicLink
        } else if error == Errno::NOTDIR {
            GenerationRootErrorKind::NotDirectory
        } else if error == Errno::XDEV {
            GenerationRootErrorKind::CrossDevice
        } else if error == Errno::NOSYS || error == Errno::PERM {
            GenerationRootErrorKind::UnsupportedKernelFeature
        } else if error == Errno::MFILE || error == Errno::NFILE || error == Errno::NOMEM {
            GenerationRootErrorKind::ResourceLimit
        } else {
            GenerationRootErrorKind::Io
        };
        GenerationRootError::new(kind, stage).with_raw_os_error(error.raw_os_error())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn linux_open_error_for_test(error: Errno) -> GenerationRootError {
        linux_open_error(GenerationRootStage::OpenRegularFile, error)
    }

    #[cfg(target_os = "linux")]
    fn inspect_acl_if_required(
        descriptor: &OwnedFd,
        witness: GenerationRootObjectWitness,
        _stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let before = object_witness(
            descriptor,
            witness.filesystem,
            witness.mount_identity,
            GenerationRootStage::InspectAcl,
        )?;
        if !before.mutation_stable_eq(witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::InspectAcl,
            ));
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeAclRead)?;
        let presence =
            crate::fd_acl::extended_acl_presence(descriptor.as_fd()).map_err(|error| {
                GenerationRootError::new(
                    GenerationRootErrorKind::AclRejected,
                    GenerationRootStage::InspectAcl,
                )
                .with_raw_os_error(error.raw_os_error().unwrap_or(libc::EIO))
            })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterAclRead)?;
        match presence {
            crate::fd_acl::ExtendedAclPresence::Absent => {}
            crate::fd_acl::ExtendedAclPresence::Present => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::AclRejected,
                    GenerationRootStage::InspectAcl,
                ));
            }
        }
        let after = object_witness(
            descriptor,
            witness.filesystem,
            witness.mount_identity,
            GenerationRootStage::InspectAcl,
        )?;
        if !witness.mutation_stable_eq(after) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::InspectAcl,
            ));
        }
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn sync_file_descriptor(descriptor: &OwnedFd) -> GenerationRootResult<()> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFileSync)?;
        rustix::fs::fsync(descriptor).map_err(|error| {
            GenerationRootError::new(
                GenerationRootErrorKind::DurabilityUnavailable,
                GenerationRootStage::SyncRegularFile,
            )
            .with_raw_os_error(error.raw_os_error())
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFileSync)?;
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn sync_directory_descriptor(descriptor: &OwnedFd) -> GenerationRootResult<()> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeDirectorySync)?;
        rustix::fs::fsync(descriptor).map_err(|error| {
            GenerationRootError::new(
                GenerationRootErrorKind::DurabilityUnavailable,
                GenerationRootStage::SyncDirectory,
            )
            .with_raw_os_error(error.raw_os_error())
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterDirectorySync)?;
        Ok(())
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn open_absolute_route(
        route: &AbsoluteRoute,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OpenedRoute> {
        use rustix::fs::CWD;

        let flags = OFlags::RDONLY
            | OFlags::DIRECTORY
            | OFlags::NOFOLLOW
            | OFlags::CLOEXEC
            | OFlags::NONBLOCK;
        let mut descriptor = openat(CWD, Path::new("/"), flags, Mode::empty())
            .map_err(|error| macos_open_error(stage, error))?;
        let mut route_identities = Vec::new();
        route_identities
            .try_reserve(route.components.len() + 1)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage))?;
        route_identities.push(qualify_absolute_ancestor(&descriptor, stage, None)?);
        for (index, component) in route.components.iter().enumerate() {
            #[cfg(test)]
            test_boundary(TestBoundary::BeforeRootComponentOpen { index })?;
            verify_exact_directory_entry(&descriptor, component, stage, index)?;
            let next = openat(&descriptor, component, flags, Mode::empty()).map_err(|error| {
                macos_component_open_error(&descriptor, component, stage, index, error)
            })?;
            verify_exact_directory_entry(&descriptor, component, stage, index)?;
            descriptor = next;
            let stat = fstat(&descriptor).map_err(|error| os_error(stage, error))?;
            if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
                return Err(
                    GenerationRootError::new(GenerationRootErrorKind::NotDirectory, stage)
                        .at_component(index),
                );
            }
            let identity = if index + 1 == route.components.len() {
                basic_identity(&descriptor, stage)?
            } else {
                qualify_absolute_ancestor(&descriptor, stage, Some(index))?
            };
            #[cfg(test)]
            test_boundary(TestBoundary::AfterRootComponentOpen { index })?;
            route_identities.push(identity);
        }
        Ok(OpenedRoute {
            descriptor,
            route_identities,
        })
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn open_relative_directory_component(
        parent: &OwnedFd,
        component: &OsStr,
        index: usize,
        root: GenerationRootObjectWitness,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<OwnedFd> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRelativeDirectoryOpen { index })?;
        verify_exact_directory_entry(parent, component, stage, index)?;
        let descriptor = openat(
            parent,
            component,
            OFlags::RDONLY
                | OFlags::DIRECTORY
                | OFlags::NOFOLLOW
                | OFlags::CLOEXEC
                | OFlags::NONBLOCK,
            Mode::empty(),
        )
        .map_err(|error| macos_component_open_error(parent, component, stage, index, error))?;
        verify_exact_directory_entry(parent, component, stage, index)?;
        let witness = object_witness(&descriptor, root.filesystem, root.mount_identity, stage)?;
        if witness.mount_identity != root.mount_identity {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::CrossDevice, stage)
                    .at_component(index),
            );
        }
        validate_private_directory(&descriptor, witness, stage)?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRelativeDirectoryOpen { index })?;
        Ok(descriptor)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn route_mount_identity(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<[u8; 32]> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeRouteMountIdentity)?;
        let filesystem_stat = fstatfs(descriptor).map_err(|error| os_error(stage, error))?;
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        let identity = macos_mount_identity(&filesystem_stat, stat_device_as_u64(stat.st_dev));
        #[cfg(test)]
        test_boundary(TestBoundary::AfterRouteMountIdentity)?;
        Ok(identity)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn qualify_filesystem(
        descriptor: &OwnedFd,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<(QualifiedFilesystem, [u8; 32])> {
        use rustix::fs::StatVfsMountFlags;

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFilesystemQualification)?;
        let filesystem_stat = fstatfs(descriptor).map_err(|error| os_error(stage, error))?;
        if macos_fixed_name(&filesystem_stat.f_fstypename) != b"apfs" {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        }
        let flags = i64::from(filesystem_stat.f_flags);
        if flags & i64::from(libc::MNT_LOCAL) == 0 {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::UnsupportedFilesystem,
                stage,
            ));
        }
        if flags & i64::from(libc::MNT_RDONLY) != 0
            || flags & i64::from(libc::MNT_IGNORE_OWNERSHIP) != 0
        {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ReadOnlyFilesystem,
                stage,
            ));
        }
        let mount_stat = fstatvfs(descriptor).map_err(|error| os_error(stage, error))?;
        if mount_stat.f_flag.contains(StatVfsMountFlags::RDONLY) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ReadOnlyFilesystem,
                stage,
            ));
        }
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        let qualified = (
            QualifiedFilesystem::AppleApfs,
            macos_mount_identity(&filesystem_stat, stat_device_as_u64(stat.st_dev)),
        );
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFilesystemQualification)?;
        Ok(qualified)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn validate_root_writable(
        descriptor: &OwnedFd,
        filesystem: QualifiedFilesystem,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let (observed, _) = qualify_filesystem(descriptor, stage)?;
        if observed != filesystem {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::CrossDevice,
                stage,
            ));
        }
        Ok(())
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn object_witness(
        descriptor: &OwnedFd,
        expected_filesystem: QualifiedFilesystem,
        expected_mount_identity: [u8; 32],
        stage: GenerationRootStage,
    ) -> GenerationRootResult<GenerationRootObjectWitness> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeObjectWitness)?;
        let stat = fstat(descriptor).map_err(|error| os_error(stage, error))?;
        let (filesystem, mount_identity) = qualify_filesystem(descriptor, stage)?;
        if filesystem != expected_filesystem || mount_identity != expected_mount_identity {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::CrossDevice,
                stage,
            ));
        }
        validate_macos_object_flags(stat.st_flags, stage)?;
        let size = u64::try_from(stat.st_size)
            .map_err(|_| GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage))?;
        let witness = GenerationRootObjectWitness {
            device: stat_device_as_u64(stat.st_dev),
            inode: stat_inode_as_u64(stat.st_ino),
            mode: stat_mode_as_u32(stat.st_mode),
            hard_links: stat_link_count_as_u64(stat.st_nlink),
            uid: stat.st_uid,
            gid: stat.st_gid,
            byte_len: size,
            modified_seconds: stat_seconds_as_i64(stat.st_mtime),
            modified_nanoseconds: stat.st_mtime_nsec,
            changed_seconds: stat_seconds_as_i64(stat.st_ctime),
            changed_nanoseconds: stat.st_ctime_nsec,
            accessed_seconds: stat_seconds_as_i64(stat.st_atime),
            accessed_nanoseconds: stat.st_atime_nsec,
            mount_identity,
            filesystem,
        };
        #[cfg(test)]
        test_boundary(TestBoundary::AfterObjectWitness)?;
        Ok(witness)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn validate_macos_object_flags(
        flags: u32,
        stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        if flags == 0 {
            Ok(())
        } else {
            Err(
                GenerationRootError::new(GenerationRootErrorKind::UnsupportedObjectFlags, stage)
                    .with_counts(0, u64::from(flags)),
            )
        }
    }

    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn validate_macos_object_flags_for_test(flags: u32) -> GenerationRootResult<()> {
        validate_macos_object_flags(flags, GenerationRootStage::OpenRegularFile)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn inspect_acl_if_required(
        descriptor: &OwnedFd,
        witness: GenerationRootObjectWitness,
        _stage: GenerationRootStage,
    ) -> GenerationRootResult<()> {
        let before = object_witness(
            descriptor,
            witness.filesystem,
            witness.mount_identity,
            GenerationRootStage::InspectAcl,
        )?;
        if !before.mutation_stable_eq(witness) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::InspectAcl,
            ));
        }
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeAclRead)?;
        let presence =
            crate::fd_acl::extended_acl_presence(descriptor.as_fd()).map_err(|error| {
                GenerationRootError::new(
                    GenerationRootErrorKind::AclRejected,
                    GenerationRootStage::InspectAcl,
                )
                .with_raw_os_error(error.raw_os_error().unwrap_or(libc::EIO))
            })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterAclRead)?;
        match presence {
            crate::fd_acl::ExtendedAclPresence::Absent => {}
            crate::fd_acl::ExtendedAclPresence::Present => {
                return Err(GenerationRootError::new(
                    GenerationRootErrorKind::AclRejected,
                    GenerationRootStage::InspectAcl,
                ));
            }
        }
        let after = object_witness(
            descriptor,
            witness.filesystem,
            witness.mount_identity,
            GenerationRootStage::InspectAcl,
        )?;
        if !witness.mutation_stable_eq(after) {
            return Err(GenerationRootError::new(
                GenerationRootErrorKind::ObjectChanged,
                GenerationRootStage::InspectAcl,
            ));
        }
        Ok(())
    }

    pub(super) fn verify_exact_directory_entry(
        parent: &OwnedFd,
        component: &OsStr,
        stage: GenerationRootStage,
        index: usize,
    ) -> GenerationRootResult<()> {
        use rustix::fs::Dir;

        #[cfg(test)]
        test_boundary(TestBoundary::BeforeExactNameEnumeration)?;
        let mut directory = Dir::read_from(parent).map_err(|error| {
            GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                .at_component(index)
                .with_raw_os_error(error.raw_os_error())
        })?;
        let expected = component.as_bytes();
        let mut entry_count = 0_usize;
        let mut name_bytes = 0_usize;
        let mut exact_matches = 0_u8;
        while let Some(entry) = directory.read() {
            let entry = entry.map_err(|error| {
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index)
                    .with_raw_os_error(error.raw_os_error())
            })?;
            entry_count = entry_count.saturating_add(1);
            let name = entry.file_name().to_bytes();
            name_bytes = name_bytes.saturating_add(name.len());
            validate_directory_scan_counts(entry_count, name_bytes, stage, index)?;
            if name == expected {
                exact_matches = exact_matches.saturating_add(1);
            }
        }
        #[cfg(test)]
        test_boundary(TestBoundary::AfterExactNameEnumeration)?;
        if exact_matches != 1 {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ObjectChanged, stage)
                    .at_component(index)
                    .with_counts(1, u64::from(exact_matches)),
            );
        }
        Ok(())
    }

    fn validate_directory_scan_counts(
        entry_count: usize,
        name_bytes: usize,
        stage: GenerationRootStage,
        index: usize,
    ) -> GenerationRootResult<()> {
        if entry_count > GENERATION_ROOT_MAX_DIRECTORY_ENTRIES {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                    .at_component(index)
                    .with_counts(
                        usize_as_u64(GENERATION_ROOT_MAX_DIRECTORY_ENTRIES),
                        usize_as_u64(entry_count),
                    ),
            );
        }
        if name_bytes > GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES {
            return Err(
                GenerationRootError::new(GenerationRootErrorKind::ResourceLimit, stage)
                    .at_component(index)
                    .with_counts(
                        usize_as_u64(GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES),
                        usize_as_u64(name_bytes),
                    ),
            );
        }
        Ok(())
    }

    #[cfg(all(test, target_os = "linux"))]
    pub(super) fn validate_directory_scan_counts_for_test(
        entry_count: usize,
        name_bytes: usize,
    ) -> GenerationRootResult<()> {
        validate_directory_scan_counts(
            entry_count,
            name_bytes,
            GenerationRootStage::OpenRelativeDirectory,
            7,
        )
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn macos_fixed_name<const N: usize>(value: &[libc::c_char; N]) -> Vec<u8> {
        value
            .iter()
            .map(|character| character.to_ne_bytes()[0])
            .take_while(|byte| *byte != 0)
            .collect()
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn macos_mount_identity(stat: &rustix::fs::StatFs, device: u64) -> [u8; 32] {
        let mut digest = Sha256::new();
        digest.update(b"frankensearch.generation-root.macos-mount.v1");
        digest.update(device.to_le_bytes());
        for character in &stat.f_fstypename {
            digest.update(character.to_ne_bytes());
        }
        for character in &stat.f_mntonname {
            digest.update(character.to_ne_bytes());
        }
        for character in &stat.f_mntfromname {
            digest.update(character.to_ne_bytes());
        }
        digest.finalize().into()
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn stat_device_as_u64(device: i32) -> u64 {
        u64::from_ne_bytes(i64::from(device).to_ne_bytes())
    }

    #[cfg(all(test, target_os = "macos", target_arch = "aarch64"))]
    pub(super) fn stat_device_as_u64_for_test(device: i32) -> u64 {
        stat_device_as_u64(device)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn macos_open_error(stage: GenerationRootStage, error: Errno) -> GenerationRootError {
        let kind = if error == Errno::LOOP {
            GenerationRootErrorKind::SymbolicLink
        } else if error == Errno::NOTDIR {
            GenerationRootErrorKind::NotDirectory
        } else {
            GenerationRootErrorKind::Io
        };
        GenerationRootError::new(kind, stage).with_raw_os_error(error.raw_os_error())
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn macos_component_open_error(
        parent: &OwnedFd,
        component: &OsStr,
        stage: GenerationRootStage,
        index: usize,
        error: Errno,
    ) -> GenerationRootError {
        use rustix::fs::{AtFlags, statat};

        if matches!(error, Errno::NOTDIR)
            && statat(parent, component, AtFlags::SYMLINK_NOFOLLOW)
                .is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) == FileType::Symlink)
        {
            return GenerationRootError::new(GenerationRootErrorKind::SymbolicLink, stage)
                .at_component(index)
                .with_raw_os_error(error.raw_os_error());
        }
        macos_open_error(stage, error).at_component(index)
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn sync_file_descriptor(descriptor: &OwnedFd) -> GenerationRootResult<()> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeFileSync)?;
        rustix::fs::fcntl_fullfsync(descriptor).map_err(|error| {
            GenerationRootError::new(
                GenerationRootErrorKind::DurabilityUnavailable,
                GenerationRootStage::SyncRegularFile,
            )
            .with_raw_os_error(error.raw_os_error())
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterFileSync)?;
        Ok(())
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    fn sync_directory_descriptor(descriptor: &OwnedFd) -> GenerationRootResult<()> {
        #[cfg(test)]
        test_boundary(TestBoundary::BeforeDirectorySync)?;
        rustix::fs::fcntl_fullfsync(descriptor).map_err(|error| {
            GenerationRootError::new(
                GenerationRootErrorKind::DurabilityUnavailable,
                GenerationRootStage::SyncDirectory,
            )
            .with_raw_os_error(error.raw_os_error())
        })?;
        #[cfg(test)]
        test_boundary(TestBoundary::AfterDirectorySync)?;
        Ok(())
    }
}

#[cfg(not(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64"))))]
#[allow(dead_code)] // Typed zero-I/O stubs intentionally have no native consumers yet.
mod platform {
    use super::{
        GenerationFileExpectation, GenerationRootError, GenerationRootErrorKind,
        GenerationRootLockMode, GenerationRootObjectWitness, GenerationRootResult,
        GenerationRootStage,
    };
    use std::path::Path;

    #[derive(Clone)]
    pub(super) enum RelativePath {}
    pub(super) enum RootHandle {}
    pub(super) enum FileHandle {}
    pub(super) enum ControlHandle {}
    pub(super) enum LockHandle {}

    pub(super) struct AnchorImage {
        pub(super) bytes: std::sync::Arc<[u8]>,
        pub(super) witness: GenerationRootObjectWitness,
        pub(super) sha256: [u8; 32],
    }

    pub(super) struct FileAdmission {
        pub(super) handle: FileHandle,
        pub(super) bytes: std::sync::Arc<[u8]>,
        pub(super) witness: GenerationRootObjectWitness,
        pub(super) sha256: [u8; 32],
    }

    const fn unsupported<T>() -> GenerationRootResult<T> {
        Err(GenerationRootError::new(
            GenerationRootErrorKind::UnsupportedPlatform,
            GenerationRootStage::PlatformGate,
        ))
    }

    pub(super) fn parse_relative(_path: &Path) -> GenerationRootResult<RelativePath> {
        unsupported()
    }

    pub(super) const fn relative_component_count(path: &RelativePath) -> usize {
        match *path {}
    }

    pub(super) fn admit_root(_path: &Path) -> GenerationRootResult<RootHandle> {
        unsupported()
    }

    pub(super) const fn root_witness(root: &RootHandle) -> GenerationRootObjectWitness {
        match *root {}
    }

    pub(super) fn revalidate_root(root: &RootHandle) -> GenerationRootResult<()> {
        match *root {}
    }

    pub(super) fn admit_file(
        root: &RootHandle,
        _path: &RelativePath,
        _expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<FileAdmission> {
        match *root {}
    }

    pub(super) fn sync_root_directory(root: &RootHandle) -> GenerationRootResult<()> {
        match *root {}
    }

    pub(super) fn sync_file(
        file: &FileHandle,
        _expected: GenerationRootObjectWitness,
    ) -> GenerationRootResult<()> {
        match *file {}
    }

    pub(super) fn admit_control_file(
        root: &RootHandle,
        _path: &RelativePath,
        _expectation: GenerationFileExpectation,
    ) -> GenerationRootResult<ControlHandle> {
        match *root {}
    }

    pub(super) const fn control_witness(control: &ControlHandle) -> GenerationRootObjectWitness {
        match *control {}
    }

    pub(super) fn control_bytes(control: &ControlHandle) -> std::sync::Arc<[u8]> {
        match *control {}
    }

    pub(super) const fn control_sha256(control: &ControlHandle) -> [u8; 32] {
        match *control {}
    }

    pub(super) fn revalidate_anchor_set(
        root: &RootHandle,
        _lock: &ControlHandle,
        _authority: &ControlHandle,
    ) -> GenerationRootResult<()> {
        match *root {}
    }

    pub(super) fn capture_anchor_image(
        control: &ControlHandle,
    ) -> GenerationRootResult<AnchorImage> {
        match *control {}
    }

    pub(super) fn anchor_images_match(left: &AnchorImage, right: &AnchorImage) -> bool {
        left.sha256 == right.sha256 && left.bytes == right.bytes && left.witness == right.witness
    }

    pub(super) fn validate_anchor_image(
        control: &ControlHandle,
        _expected: &AnchorImage,
    ) -> GenerationRootResult<()> {
        match *control {}
    }

    pub(super) fn try_anchor_lock(
        control: &ControlHandle,
        _mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        match *control {}
    }

    pub(super) fn try_lock(
        control: &ControlHandle,
        _mode: GenerationRootLockMode,
    ) -> GenerationRootResult<LockHandle> {
        match *control {}
    }

    pub(super) const fn lock_witness(lock: &LockHandle) -> GenerationRootObjectWitness {
        match *lock {}
    }

    pub(super) fn lock_bytes(lock: &LockHandle) -> std::sync::Arc<[u8]> {
        match *lock {}
    }

    pub(super) const fn lock_sha256(lock: &LockHandle) -> [u8; 32] {
        match *lock {}
    }

    pub(super) const fn lock_mode(lock: &LockHandle) -> GenerationRootLockMode {
        match *lock {}
    }

    pub(super) fn unlock(lock: LockHandle) -> GenerationRootResult<()> {
        match lock {}
    }

    pub(super) fn sync_lock_file(lock: &LockHandle) -> GenerationRootResult<()> {
        match *lock {}
    }
}

#[cfg(test)]
mod tests {
    use super::{
        GENERATION_ROOT_MAX_CONTROL_FILE_BYTES, GENERATION_ROOT_MAX_FILE_BYTES,
        GenerationFileExpectation, GenerationRootErrorKind, GenerationRootStage,
    };

    #[test]
    fn file_expectation_enforces_roles_digests_and_role_specific_limits() {
        let exact = GenerationFileExpectation::immutable(7, [0x5a; 32])
            .expect("small immutable expectation should be admitted");
        assert_eq!(exact.byte_len(), 7);
        assert_eq!(exact.sha256(), Some([0x5a; 32]));
        assert_eq!(exact.role(), super::GenerationFileRole::ImmutableArtifact);

        let control = GenerationFileExpectation::control(8)
            .expect("small control-file expectation should be admitted");
        assert_eq!(control.byte_len(), 8);
        assert_eq!(control.sha256(), None);
        assert_eq!(control.role(), super::GenerationFileRole::MutableControl);

        GenerationFileExpectation::control(GENERATION_ROOT_MAX_CONTROL_FILE_BYTES)
            .expect("the exact control repeated-hash ceiling must be accepted");
        GenerationFileExpectation::immutable(GENERATION_ROOT_MAX_FILE_BYTES, [0; 32])
            .expect("the exact immutable owned-image ceiling must be accepted");

        let control_limit = GenerationFileExpectation::control(
            GENERATION_ROOT_MAX_CONTROL_FILE_BYTES.saturating_add(1),
        )
        .expect_err("control length above its repeated-hash ceiling must fail");
        assert_eq!(control_limit.kind(), GenerationRootErrorKind::ResourceLimit);
        assert_eq!(
            control_limit.expected(),
            Some(GENERATION_ROOT_MAX_CONTROL_FILE_BYTES)
        );

        let artifact_limit = GenerationFileExpectation::immutable(
            GENERATION_ROOT_MAX_FILE_BYTES.saturating_add(1),
            [0; 32],
        )
        .expect_err("immutable length above the owned-image ceiling must fail");
        assert_eq!(
            artifact_limit.kind(),
            GenerationRootErrorKind::ResourceLimit
        );
        assert_eq!(
            artifact_limit.expected(),
            Some(GENERATION_ROOT_MAX_FILE_BYTES)
        );
    }

    #[cfg(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64")))]
    #[test]
    fn confined_routes_are_bounded_unambiguous_and_non_utf8_safe() {
        use super::{
            ConfinedGenerationPath, GENERATION_ROOT_MAX_COMPONENT_BYTES,
            GENERATION_ROOT_MAX_COMPONENTS, GENERATION_ROOT_MAX_ROUTE_BYTES,
            QualifiedGenerationDirectory as QualifiedGenerationRoot,
        };
        use std::ffi::OsStr;
        use std::os::unix::ffi::OsStrExt;
        use std::path::{Path, PathBuf};

        for invalid in ["", ".", "..", "/absolute", "a/", "a//b", "a/./b", "a/../b"] {
            let error = ConfinedGenerationPath::parse(Path::new(invalid))
                .expect_err("ambiguous confined route must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::InvalidRoute);
            assert_eq!(error.stage(), GenerationRootStage::ParseRelativeRoute);
        }

        let nul = Path::new(OsStr::from_bytes(b"a\0b"));
        assert_eq!(
            ConfinedGenerationPath::parse(nul)
                .expect_err("NUL-containing route must fail")
                .kind(),
            GenerationRootErrorKind::InvalidRoute
        );

        let max_component = PathBuf::from("x".repeat(GENERATION_ROOT_MAX_COMPONENT_BYTES));
        assert_eq!(
            ConfinedGenerationPath::parse(&max_component)
                .expect("maximum component length should be accepted")
                .component_count(),
            1
        );
        let oversized_component =
            PathBuf::from("x".repeat(GENERATION_ROOT_MAX_COMPONENT_BYTES.saturating_add(1)));
        assert_eq!(
            ConfinedGenerationPath::parse(&oversized_component)
                .expect_err("oversized component must fail")
                .kind(),
            GenerationRootErrorKind::InvalidRoute
        );

        let max_components = std::iter::repeat_n("x", GENERATION_ROOT_MAX_COMPONENTS)
            .collect::<Vec<_>>()
            .join("/");
        assert_eq!(
            ConfinedGenerationPath::parse(Path::new(&max_components))
                .expect("maximum component count should be accepted")
                .component_count(),
            GENERATION_ROOT_MAX_COMPONENTS
        );
        let too_many_components =
            std::iter::repeat_n("x", GENERATION_ROOT_MAX_COMPONENTS.saturating_add(1))
                .collect::<Vec<_>>()
                .join("/");
        assert_eq!(
            ConfinedGenerationPath::parse(Path::new(&too_many_components))
                .expect_err("too many components must fail")
                .kind(),
            GenerationRootErrorKind::ResourceLimit
        );

        let non_utf8 = Path::new(OsStr::from_bytes(&[0xff, b'x']));
        assert_eq!(
            ConfinedGenerationPath::parse(non_utf8)
                .expect("non-UTF-8 bytes are valid Unix component bytes")
                .component_count(),
            1
        );

        let exact_relative = [
            std::iter::repeat_n("x".repeat(255), 15).collect::<Vec<_>>(),
            vec!["x".repeat(254), "x".to_owned()],
        ]
        .concat()
        .join("/");
        assert_eq!(exact_relative.len(), GENERATION_ROOT_MAX_ROUTE_BYTES);
        assert_eq!(
            ConfinedGenerationPath::parse(Path::new(&exact_relative))
                .expect("the exact relative-route byte ceiling must be accepted")
                .component_count(),
            17
        );
        let oversized_relative = format!("{exact_relative}x");
        let relative_error = ConfinedGenerationPath::parse(Path::new(&oversized_relative))
            .expect_err("one byte above the relative-route ceiling must fail");
        assert_eq!(relative_error.kind(), GenerationRootErrorKind::InvalidRoute);
        assert_eq!(
            relative_error.stage(),
            GenerationRootStage::ParseRelativeRoute
        );
        assert_eq!(
            relative_error.expected(),
            Some(GENERATION_ROOT_MAX_ROUTE_BYTES as u64)
        );
        assert_eq!(
            relative_error.observed(),
            Some(GENERATION_ROOT_MAX_ROUTE_BYTES.saturating_add(1) as u64)
        );

        let exact_absolute_body = [
            std::iter::repeat_n("x".repeat(255), 15).collect::<Vec<_>>(),
            vec!["x".repeat(253), "x".to_owned()],
        ]
        .concat()
        .join("/");
        let exact_absolute = format!("/{exact_absolute_body}");
        assert_eq!(exact_absolute.len(), GENERATION_ROOT_MAX_ROUTE_BYTES);
        let exact_absolute_error = QualifiedGenerationRoot::admit(Path::new(&exact_absolute))
            .expect_err("the parsed but nonexistent exact-limit route must fail during open");
        assert_eq!(
            exact_absolute_error.stage(),
            GenerationRootStage::OpenRootRoute,
            "the exact absolute-route ceiling must pass parsing"
        );
        let oversized_absolute = format!("{exact_absolute}x");
        let absolute_error = QualifiedGenerationRoot::admit(Path::new(&oversized_absolute))
            .expect_err("one byte above the absolute-route ceiling must fail during parsing");
        assert_eq!(absolute_error.kind(), GenerationRootErrorKind::InvalidRoute);
        assert_eq!(absolute_error.stage(), GenerationRootStage::ParseRootRoute);
        assert_eq!(
            absolute_error.expected(),
            Some(GENERATION_ROOT_MAX_ROUTE_BYTES as u64)
        );
        assert_eq!(
            absolute_error.observed(),
            Some(GENERATION_ROOT_MAX_ROUTE_BYTES.saturating_add(1) as u64)
        );
    }

    #[cfg(not(any(target_os = "linux", all(target_os = "macos", target_arch = "aarch64"))))]
    #[test]
    fn unsupported_targets_return_typed_platform_errors_without_path_access() {
        use super::{
            ConfinedGenerationPath, GenerationRootAnchorLayout, GenerationRootReadGuard,
            GenerationRootResult, QualifiedGenerationDirectory,
            QualifiedGenerationRoot as NamedGenerationRoot,
        };
        use std::path::Path;

        let missing = Path::new("this-path-must-never-be-opened");
        let confined = ConfinedGenerationPath::parse(missing)
            .expect_err("unsupported target must fail before parsing or I/O");
        assert_eq!(
            confined.kind(),
            GenerationRootErrorKind::UnsupportedPlatform
        );
        assert_eq!(confined.stage(), GenerationRootStage::PlatformGate);

        let absolute_missing = Path::new("/this-path-must-never-be-opened");
        let directory = QualifiedGenerationDirectory::admit(absolute_missing)
            .expect_err("unsupported target must fail before opening the path");
        assert_eq!(
            directory.kind(),
            GenerationRootErrorKind::UnsupportedPlatform
        );
        assert_eq!(directory.stage(), GenerationRootStage::PlatformGate);

        let layout = GenerationRootAnchorLayout::new(8)
            .expect("the public named-root layout should remain platform-independent");
        let named = NamedGenerationRoot::admit(absolute_missing, layout)
            .expect_err("the public named-root wrapper must fail before anchor path access");
        assert_eq!(named.kind(), GenerationRootErrorKind::UnsupportedPlatform);
        assert_eq!(named.stage(), GenerationRootStage::PlatformGate);

        let _read_guard_surface: for<'root> fn(
            &'root NamedGenerationRoot,
        ) -> GenerationRootResult<
            GenerationRootReadGuard<'root>,
        > = NamedGenerationRoot::read_guard;
    }

    #[cfg(target_os = "linux")]
    mod linux {
        use super::super::platform::{
            ProcBridgeProbePhase, ProcSelfBindingPhase, TestBoundary,
            duplicate_lock_descriptor_for_inheritance_for_test, install_test_hook,
            linux_device_components_match_for_test, linux_filesystem_namespace_digest,
            linux_filesystem_profile, linux_mountinfo_error_for_test,
            linux_mountinfo_filesystem_for_test, linux_open_error_for_test,
            linux_task_mountinfo_route_for_test, parse_mountinfo_filesystem,
            proc_bridge_error_for_test, proc_root_error_for_test, proc_thread_fd_route_for_test,
            set_lock_creator_process_id_for_test, set_root_creator_process_id_for_test,
            stat_inode_as_u64, stat_link_count_as_u64, stat_mode_as_u32, stat_seconds_as_i64,
            validate_absolute_ancestor_owner_mode_for_test,
            validate_bound_control_content_for_test, validate_directory_scan_counts_for_test,
            validate_linux_writable_attributes_for_test, validate_mountinfo_bound_for_test,
            validate_owner_mode_for_test, validate_proc_mount_id_mask_for_test,
            validate_regular_descriptor_type, verify_exact_directory_entry,
        };
        use super::super::{
            ConfinedGenerationPath, GENERATION_ROOT_AUTHORITY_FILE_BYTES,
            GENERATION_ROOT_MAX_DIRECTORY_ENTRIES, GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES,
            GENERATION_ROOT_MAX_MOUNTINFO_BYTES, GenerationFileExpectation,
            GenerationRootAnchorLayout, GenerationRootError, GenerationRootErrorKind,
            GenerationRootLockMode, GenerationRootStage,
            QualifiedGenerationDirectory as QualifiedGenerationRoot,
            QualifiedGenerationRoot as NamedGenerationRoot,
        };
        use sha2::{Digest, Sha256};
        use std::ffi::OsStr;
        use std::fs::{self, DirBuilder, File, OpenOptions};
        use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
        use std::os::fd::{AsFd, AsRawFd};
        use std::os::unix::fs::{
            DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt, symlink,
        };
        use std::path::{Path, PathBuf};
        use std::process::{Command, Stdio};
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::sync::{Arc, Mutex, OnceLock};
        use std::time::{SystemTime, UNIX_EPOCH};

        static FIXTURE_SERIAL: AtomicU64 = AtomicU64::new(0);
        static FIXTURE_SLOT_SERIAL: AtomicU64 = AtomicU64::new(0);
        static FIXTURE_BASE: OnceLock<PathBuf> = OnceLock::new();
        const FIXTURE_SLOT_COUNT: u64 = 512;

        fn fixture_root(label: &str) -> PathBuf {
            let slot = FIXTURE_SLOT_SERIAL.fetch_add(1, Ordering::Relaxed);
            assert!(
                slot < FIXTURE_SLOT_COUNT,
                "the retained fixture-slot pool must cover every test root"
            );
            let slot_path = secure_fixture_base().join(format!("slot-{slot:03}"));
            fixture_root_under(&slot_path, label)
        }

        fn secure_fixture_base() -> &'static Path {
            FIXTURE_BASE
                .get_or_init(|| {
                    let home = std::env::var_os("HOME")
                        .map(PathBuf::from)
                        .expect("HOME must identify the process-private fixture ancestor");
                    assert!(home.is_absolute(), "HOME must be an absolute route");

                    // bd-54h2l LOW A: the per-run base still embeds pid + epoch
                    // nanos (route qualification requires an ancestor chain this
                    // user owns privately, so these fixtures cannot move to a
                    // shared scratch root — see the note below), but it now nests
                    // under ONE stable private parent instead of littering $HOME
                    // with a fresh top-level entry per test process. Per-run
                    // isolation is unchanged and no directory is deleted here;
                    // the sprawl is simply confined to a single, purgeable place.
                    //
                    // Rooting these under `std::env::temp_dir()` was tried and
                    // REVERTED: it fails route qualification with
                    // `WrongOwner` at component_index 0, because a shared temp
                    // root is not owned by this user. $HOME is load-bearing.
                    let parent = home.join(".frankensearch-generation-root-tests");
                    match DirBuilder::new().mode(0o700).create(&parent) {
                        Ok(()) => {
                            fs::set_permissions(&parent, fs::Permissions::from_mode(0o700))
                                .expect("fixture parent mode should be settable");
                        }
                        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                            // Adopting a directory left by an earlier run is
                            // fine, but only after proving it is still the thing
                            // we created: a real directory (never a symlink),
                            // owned by whoever owns HOME, and private.
                            let existing = fs::symlink_metadata(&parent)
                                .expect("the retained fixture parent should be stattable");
                            assert!(
                                existing.is_dir(),
                                "the retained fixture parent must be a directory"
                            );
                            let home_owner = fs::symlink_metadata(&home)
                                .expect("HOME should be stattable")
                                .uid();
                            assert_eq!(
                                existing.uid(),
                                home_owner,
                                "the retained fixture parent must be owned by the HOME owner"
                            );
                            assert_eq!(
                                existing.permissions().mode() & 0o777,
                                0o700,
                                "the retained fixture parent must stay private"
                            );
                        }
                        Err(error) => {
                            panic!("failed to create the retained fixture parent: {error}")
                        }
                    }
                    let epoch_nanos = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .map_or(0, |duration| duration.as_nanos());
                    for attempt in 0_u64..64 {
                        let candidate =
                            parent.join(format!("{}-{epoch_nanos}-{attempt}", std::process::id()));
                        match DirBuilder::new().mode(0o700).create(&candidate) {
                            Ok(()) => {
                                fs::set_permissions(&candidate, fs::Permissions::from_mode(0o700))
                                    .expect("fixture base mode should be settable");
                                for slot in 0..FIXTURE_SLOT_COUNT {
                                    let slot_path = candidate.join(format!("slot-{slot:03}"));
                                    DirBuilder::new()
                                        .mode(0o700)
                                        .create(&slot_path)
                                        .expect("each retained fixture slot should be creatable");
                                    fs::set_permissions(
                                        &slot_path,
                                        fs::Permissions::from_mode(0o700),
                                    )
                                    .expect("each retained fixture slot mode should be private");
                                }
                                return candidate;
                            }
                            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                            Err(error) => panic!("failed to create retained fixture base: {error}"),
                        }
                    }
                    panic!("failed to allocate a retained process fixture base");
                })
                .as_path()
        }

        fn fixture_root_under(base: &Path, label: &str) -> PathBuf {
            let epoch_nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_or(0, |duration| duration.as_nanos());
            for attempt in 0_u64..64 {
                let serial = FIXTURE_SERIAL.fetch_add(1, Ordering::Relaxed);
                let candidate = base.join(format!(
                    "{}-{}-{epoch_nanos}-{serial}-{attempt}",
                    std::process::id(),
                    label
                ));
                match DirBuilder::new().mode(0o700).create(&candidate) {
                    Ok(()) => {
                        fs::set_permissions(&candidate, fs::Permissions::from_mode(0o700))
                            .expect("fixture root mode should be settable");
                        return candidate;
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                    Err(error) => panic!("failed to create persistent test fixture: {error}"),
                }
            }
            panic!("failed to allocate a unique persistent test fixture");
        }

        fn run_btrfs_fixture_command(arguments: &[&OsStr]) {
            let output = Command::new("btrfs")
                .args(arguments)
                .output()
                .expect("the physical Btrfs receipt requires the btrfs utility");
            assert!(
                output.status.success(),
                "Btrfs fixture command failed: status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
        }

        fn run_bind_mount_fixture_command(program: &str, arguments: &[&OsStr]) {
            let output = Command::new(program)
                .args(arguments)
                .output()
                .expect("the physical absolute-route receipt requires mount utilities");
            assert!(
                output.status.success(),
                "bind-mount fixture command failed: program={program}, status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
        }

        struct BindMountFixture {
            source: PathBuf,
            target: PathBuf,
            mounted: bool,
        }

        impl BindMountFixture {
            fn new(source: &Path, target: &Path) -> Self {
                run_bind_mount_fixture_command(
                    "mount",
                    &[OsStr::new("--bind"), source.as_os_str(), target.as_os_str()],
                );
                Self {
                    source: source.to_path_buf(),
                    target: target.to_path_buf(),
                    mounted: true,
                }
            }

            fn remount_same_source(&mut self) {
                if self.mounted {
                    run_bind_mount_fixture_command(
                        "umount",
                        &[OsStr::new("--lazy"), self.target.as_os_str()],
                    );
                    self.mounted = false;
                }
                run_bind_mount_fixture_command(
                    "mount",
                    &[
                        OsStr::new("--bind"),
                        self.source.as_os_str(),
                        self.target.as_os_str(),
                    ],
                );
                self.mounted = true;
            }
        }

        impl Drop for BindMountFixture {
            fn drop(&mut self) {
                if self.mounted {
                    let _ = Command::new("umount").arg(&self.target).status();
                    self.mounted = false;
                }
            }
        }

        fn run_chattr_fixture_command(flag: &str, path: &Path) {
            let output = Command::new("chattr")
                .arg(flag)
                .arg(path)
                .output()
                .expect("the physical attribute receipt requires the chattr utility");
            assert!(
                output.status.success(),
                "chattr fixture command failed: flag={flag}, status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
        }

        struct ChattrReset {
            flag: &'static str,
            path: PathBuf,
            armed: bool,
        }

        impl ChattrReset {
            fn new(flag: &'static str, path: &Path) -> Self {
                Self {
                    flag,
                    path: path.to_path_buf(),
                    armed: true,
                }
            }

            fn clear(&mut self) {
                if self.armed {
                    run_chattr_fixture_command(self.flag, &self.path);
                    self.armed = false;
                }
            }
        }

        impl Drop for ChattrReset {
            fn drop(&mut self) {
                if self.armed {
                    let _ = Command::new("chattr")
                        .arg(self.flag)
                        .arg(&self.path)
                        .status();
                }
            }
        }

        fn private_dir(parent: &Path, name: &str) -> PathBuf {
            let path = parent.join(name);
            DirBuilder::new()
                .mode(0o700)
                .create(&path)
                .expect("private directory should be creatable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
                .expect("private directory mode should be settable");
            path
        }

        fn private_file(parent: &Path, name: &str, bytes: &[u8]) -> PathBuf {
            let path = parent.join(name);
            let mut file = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path)
                .expect("private file should be creatable");
            file.write_all(bytes)
                .expect("fixture bytes should be writable");
            file.sync_all().expect("fixture bytes should be durable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o400))
                .expect("immutable fixture should be sealed read-only");
            path
        }

        fn control_file(parent: &Path, name: &str, bytes: &[u8]) -> PathBuf {
            let path = parent.join(name);
            let mut file = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path)
                .expect("control file should be creatable");
            file.write_all(bytes)
                .expect("control bytes should be writable");
            file.sync_all().expect("control bytes should be durable");
            path
        }

        fn named_root_fixture(
            label: &str,
            lock_bytes: &[u8],
            authority_fill: u8,
        ) -> (PathBuf, PathBuf, GenerationRootAnchorLayout) {
            let root = fixture_root(label);
            control_file(&root, "LOCK", lock_bytes);
            let authority = authority_image(authority_fill);
            let authority_path = control_file(&root, "AUTHORITY", &authority);
            let layout = GenerationRootAnchorLayout::new(
                u64::try_from(lock_bytes.len()).expect("the lock fixture length fits u64"),
            )
            .expect("the named lock fixture length is bounded");
            (root, authority_path, layout)
        }

        fn authority_image(fill: u8) -> Vec<u8> {
            vec![
                fill;
                usize::try_from(GENERATION_ROOT_AUTHORITY_FILE_BYTES)
                    .expect("the frozen authority length fits usize")
            ]
        }

        fn rewrite_control_file(path: &Path, bytes: &[u8]) {
            let expected_len = u64::try_from(bytes.len()).expect("fixture length fits u64");
            assert_eq!(
                fs::metadata(path)
                    .expect("control metadata should be readable")
                    .len(),
                expected_len,
                "in-place control rewrites must retain the frozen physical length"
            );
            let mut file = OpenOptions::new()
                .write(true)
                .open(path)
                .expect("the mutable control anchor should be writable");
            file.seek(SeekFrom::Start(0))
                .expect("the control anchor should seek to its first byte");
            file.write_all(bytes)
                .expect("the complete in-place control image should be writable");
            file.sync_all()
                .expect("the in-place control rewrite should be durable");
        }

        fn install_linux_acl_xattr(
            descriptor: &File,
            name: &str,
            owner_permissions: u16,
            named_permissions: u16,
            group_permissions: u16,
            mask_permissions: u16,
            other_permissions: u16,
        ) {
            const ACL_UNDEFINED_ID: u32 = u32::MAX;
            const ACL_USER_OBJ: u16 = 0x01;
            const ACL_USER: u16 = 0x02;
            const ACL_GROUP_OBJ: u16 = 0x04;
            const ACL_MASK: u16 = 0x10;
            const ACL_OTHER: u16 = 0x20;

            let mut bytes = Vec::with_capacity(44);
            bytes.extend_from_slice(&2_u32.to_le_bytes());
            for (tag, permissions, id) in [
                (ACL_USER_OBJ, owner_permissions, ACL_UNDEFINED_ID),
                (ACL_USER, named_permissions, 424_242),
                (ACL_GROUP_OBJ, group_permissions, ACL_UNDEFINED_ID),
                (ACL_MASK, mask_permissions, ACL_UNDEFINED_ID),
                (ACL_OTHER, other_permissions, ACL_UNDEFINED_ID),
            ] {
                bytes.extend_from_slice(&tag.to_le_bytes());
                bytes.extend_from_slice(&permissions.to_le_bytes());
                bytes.extend_from_slice(&id.to_le_bytes());
            }
            rustix::fs::fsetxattr(
                descriptor.as_fd(),
                name,
                &bytes,
                rustix::fs::XattrFlags::empty(),
            )
            .expect("raw Linux ACL fixture must install without an external utility");
        }

        fn mapped_control_file(parent: &Path, name: &str) -> (PathBuf, crate::VectorIndex) {
            let path = parent.join(name);
            let mut writer = crate::VectorIndex::create(&path, "generation-root-test", 1)
                .expect("mapped control fixture writer should be creatable");
            writer
                .write_record("control", &[1.0])
                .expect("mapped control fixture record should be valid");
            writer
                .finish()
                .expect("mapped control fixture should be durable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
                .expect("mapped control fixture should use the control mode");
            let mapping = crate::VectorIndex::open(&path)
                .expect("mapped control fixture should retain a shared writable mapping");
            (path, mapping)
        }

        fn mapped_immutable_file(parent: &Path, name: &str) -> (PathBuf, crate::VectorIndex) {
            let (path, mapping) = mapped_control_file(parent, name);
            fs::set_permissions(&path, fs::Permissions::from_mode(0o400))
                .expect("pre-held mapped fixture should seal as an immutable artifact");
            (path, mapping)
        }

        fn mutate_mapping(mapping: &mut crate::VectorIndex) {
            let crate::VectorIndexData::Mutable(bytes) = &mut mapping.data else {
                panic!("legacy VectorIndex::open must retain a writable mapping");
            };
            let byte = bytes
                .last_mut()
                .expect("mapped control fixture must contain at least one byte");
            *byte ^= 0x01;
        }

        fn digest(bytes: &[u8]) -> [u8; 32] {
            Sha256::digest(bytes).into()
        }

        fn immutable_expectation(bytes: &[u8]) -> GenerationFileExpectation {
            GenerationFileExpectation::immutable(
                u64::try_from(bytes.len()).expect("fixture length should fit u64"),
                digest(bytes),
            )
            .expect("small fixture expectation should be accepted")
        }

        fn confined(path: &str) -> ConfinedGenerationPath {
            ConfinedGenerationPath::parse(Path::new(path))
                .expect("static relative fixture path should parse")
        }

        fn injected(stage: GenerationRootStage) -> GenerationRootError {
            GenerationRootError::new(GenerationRootErrorKind::Io, stage)
        }

        #[test]
        fn exact_file_admission_retains_bytes_identity_and_durability() {
            let root_path = fixture_root("happy");
            let generation = private_dir(&root_path, "generation");
            let contents = b"immutable generation image";
            private_file(&generation, "vector.fsvi", contents);

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("ext4 root should qualify");
            assert_eq!(root.witness().mode() & 0o7777, 0o700);
            let admitted = root
                .admit_file(
                    &confined("generation/vector.fsvi"),
                    immutable_expectation(contents),
                )
                .expect("exact immutable file should be admitted");
            assert_eq!(admitted.as_bytes(), contents);
            assert_eq!(admitted.bytes().as_ref(), contents);
            assert_eq!(admitted.sha256(), digest(contents));
            assert_eq!(admitted.witness().byte_len(), contents.len() as u64);
            assert_eq!(admitted.witness().hard_links(), 1);
            assert_eq!(admitted.witness().mode() & 0o7777, 0o400);
            admitted
                .sync_durable()
                .expect("retained regular-file fsync should succeed");
            root.sync_directory_durable()
                .expect("retained root fsync should succeed");

            let debug_root = format!("{root:?}");
            let debug_file = format!("{admitted:?}");
            assert!(!debug_root.contains(root_path.to_string_lossy().as_ref()));
            assert!(!debug_file.contains("vector.fsvi"));
            assert!(!debug_file.contains("immutable generation image"));
        }

        #[test]
        fn route_and_error_diagnostics_never_disclose_path_bytes() {
            let root_path = fixture_root("redaction");
            let secret_component = "secret-customer-generation";
            let path = confined(secret_component);
            let error = QualifiedGenerationRoot::admit(Path::new("relative-root"))
                .expect_err("relative root route must fail");
            let display = error.to_string();
            let debug = format!("{error:?}");
            let path_debug = format!("{path:?}");
            assert!(!display.contains("relative-root"));
            assert!(!debug.contains("relative-root"));
            assert!(!path_debug.contains(secret_component));
            assert!(!path_debug.contains(root_path.to_string_lossy().as_ref()));
        }

        #[test]
        fn exact_directory_enumeration_rejects_case_distinct_component_bytes() {
            use rustix::fs::{Mode, OFlags, open};

            let root_path = fixture_root("exact-component-bytes");
            private_file(&root_path, "ExactName", b"x");
            let descriptor = open(
                &root_path,
                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
                Mode::empty(),
            )
            .expect("fixture directory should open");
            verify_exact_directory_entry(
                &descriptor,
                OsStr::new("ExactName"),
                GenerationRootStage::OpenRegularFile,
                0,
            )
            .expect("the exact component bytes should be present once");
            assert_eq!(
                verify_exact_directory_entry(
                    &descriptor,
                    OsStr::new("exactname"),
                    GenerationRootStage::OpenRegularFile,
                    0,
                )
                .expect_err("case-distinct bytes must never count as the exact route")
                .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn root_and_descendant_modes_are_exactly_private() {
            let bad_root = fixture_root("bad-root-mode");
            fs::set_permissions(&bad_root, fs::Permissions::from_mode(0o750))
                .expect("fixture mode should change");
            assert_eq!(
                QualifiedGenerationRoot::admit(&bad_root)
                    .expect_err("non-private root must fail")
                    .kind(),
                GenerationRootErrorKind::WrongMode
            );

            let root_path = fixture_root("bad-descendant-mode");
            let directory = private_dir(&root_path, "generation");
            fs::set_permissions(&directory, fs::Permissions::from_mode(0o750))
                .expect("fixture mode should change");
            private_file(&directory, "artifact", b"x");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            assert_eq!(
                root.admit_file(
                    &confined("generation/artifact"),
                    immutable_expectation(b"x")
                )
                .expect_err("non-private descendant directory must fail")
                .kind(),
                GenerationRootErrorKind::WrongMode
            );

            let root_path = fixture_root("bad-file-mode");
            let artifact = private_file(&root_path, "artifact", b"x");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o640))
                .expect("fixture mode should change");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(b"x"))
                    .expect_err("non-private regular file must fail")
                    .kind(),
                GenerationRootErrorKind::WrongMode
            );
        }

        #[test]
        fn linux_rejects_a_granting_default_acl_on_the_root() {
            let root_path = fixture_root("root-default-acl");
            let retained = File::open(&root_path).expect("private root should open");
            install_linux_acl_xattr(&retained, "system.posix_acl_default", 0o7, 0o4, 0, 0o4, 0);
            assert_eq!(
                crate::fd_acl::extended_acl_presence(retained.as_fd())
                    .expect("descriptor-bound default ACL probe should succeed"),
                crate::fd_acl::ExtendedAclPresence::Present
            );
            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("a granting default ACL must fail root admission");
            assert_eq!(error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(error.stage(), GenerationRootStage::InspectAcl);
        }

        #[test]
        fn linux_rejects_acl_bearing_artifact_control_and_lock_descriptors_before_content_io() {
            let artifact_root = fixture_root("artifact-access-acl");
            let artifact_path = private_file(&artifact_root, "artifact", b"sealed");
            let artifact_acl =
                File::open(&artifact_path).expect("immutable artifact should open for ACL setup");
            install_linux_acl_xattr(&artifact_acl, "system.posix_acl_access", 0o4, 0, 0, 0, 0);
            let artifact_generation = QualifiedGenerationRoot::admit(&artifact_root)
                .expect("the ACL-free root should qualify");
            let artifact_boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_artifact_boundaries = Arc::clone(&artifact_boundaries);
            let artifact_hook = install_test_hook(move |boundary| {
                hook_artifact_boundaries
                    .lock()
                    .expect("artifact boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let artifact_error = artifact_generation
                .admit_file(&confined("artifact"), immutable_expectation(b"sealed"))
                .expect_err("an ACL-bearing artifact must fail");
            assert_eq!(artifact_error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(artifact_error.stage(), GenerationRootStage::InspectAcl);
            let artifact_observed = artifact_boundaries
                .lock()
                .expect("artifact boundary log should lock");
            assert!(artifact_observed.contains(&TestBoundary::BeforeAclRead));
            let after_data_reopen = artifact_observed
                .iter()
                .position(|boundary| *boundary == (TestBoundary::AfterProcFdReopen { index: 0 }))
                .expect("Linux ACL inspection requires the real proc-derived data descriptor");
            let before_acl = artifact_observed
                .iter()
                .enumerate()
                .skip(after_data_reopen.saturating_add(1))
                .find_map(|(index, boundary)| {
                    (*boundary == TestBoundary::BeforeAclRead).then_some(index)
                })
                .expect("ACL inspection boundary should be recorded");
            assert!(
                before_acl > after_data_reopen,
                "the O_PATH probe must complete without fgetxattr; ACL inspection belongs only \
                 to the real proc-derived data descriptor"
            );
            assert!(
                !artifact_observed
                    .iter()
                    .any(|boundary| matches!(boundary, TestBoundary::BeforeRead { .. })),
                "ACL rejection must precede the first content read"
            );
            drop(artifact_observed);
            drop(artifact_hook);

            let control_root = fixture_root("control-access-acl");
            let control_path = control_file(&control_root, "LOCK", b"lock-v1!");
            let control_acl =
                File::open(&control_path).expect("control file should open for ACL setup");
            install_linux_acl_xattr(&control_acl, "system.posix_acl_access", 0o6, 0, 0, 0, 0);
            let control_generation = QualifiedGenerationRoot::admit(&control_root)
                .expect("the ACL-free root should qualify");
            let control_error = control_generation
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect_err("an ACL-bearing control descriptor must fail");
            assert_eq!(control_error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(control_error.stage(), GenerationRootStage::InspectAcl);

            let lock_root = fixture_root("lock-access-acl");
            let lock_path = control_file(&lock_root, "LOCK", b"lock-v1!");
            let lock_generation = QualifiedGenerationRoot::admit(&lock_root)
                .expect("the ACL-free root should qualify");
            let control = lock_generation
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("the ACL-free control should qualify before target mutation");
            let reached_flock = Arc::new(Mutex::new(false));
            let hook_reached_flock = Arc::clone(&reached_flock);
            let acl_mutated = Arc::new(Mutex::new(false));
            let hook_acl_mutated = Arc::clone(&acl_mutated);
            let hook_lock_path = lock_path.clone();
            let mut after_data_reopen = false;
            let _hook = install_test_hook(move |boundary| {
                if boundary == (TestBoundary::AfterProcFdReopen { index: 0 }) {
                    after_data_reopen = true;
                }
                if after_data_reopen
                    && boundary == TestBoundary::BeforeAclRead
                    && !*hook_acl_mutated.lock().expect("hook state should lock")
                {
                    let descriptor = File::open(&hook_lock_path)
                        .expect("lock target should open for injected ACL mutation");
                    install_linux_acl_xattr(
                        &descriptor,
                        "system.posix_acl_access",
                        0o6,
                        0,
                        0,
                        0,
                        0,
                    );
                    *hook_acl_mutated.lock().expect("hook state should lock") = true;
                }
                if boundary == TestBoundary::BeforeLock {
                    *hook_reached_flock.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            let lock_error = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("an ACL-bearing lock descriptor must fail before flock");
            assert_eq!(lock_error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(lock_error.stage(), GenerationRootStage::InspectAcl);
            assert!(
                *acl_mutated.lock().expect("hook state should lock"),
                "the lock candidate ACL must be injected after the real data reopen"
            );
            assert!(
                !*reached_flock.lock().expect("hook state should lock"),
                "ACL rejection must precede flock"
            );
        }

        #[test]
        fn ancestor_and_final_symlinks_fail_without_touching_decoys() {
            let root_path = fixture_root("symlink");
            let decoy = fixture_root("decoy");
            let decoy_file = private_file(&decoy, "artifact", b"decoy stays exact");
            symlink(&decoy, root_path.join("jump")).expect("ancestor symlink should be creatable");
            symlink(&decoy_file, root_path.join("final"))
                .expect("final symlink should be creatable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");

            for route in ["jump/artifact", "final"] {
                let error = root
                    .admit_file(
                        &confined(route),
                        GenerationFileExpectation::immutable(17, [0; 32])
                            .expect("small expectation should be accepted"),
                    )
                    .expect_err("symlink route must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::SymbolicLink);
            }
            assert_eq!(
                fs::read(&decoy_file).expect("decoy should remain readable"),
                b"decoy stays exact"
            );
        }

        #[test]
        fn hardlinks_and_special_files_are_never_admitted() {
            use std::os::unix::net::UnixListener;

            let root_path = fixture_root("special");
            let linked = private_file(&root_path, "linked", b"linked");
            fs::hard_link(&linked, root_path.join("linked-alias"))
                .expect("fixture hardlink should be creatable");
            private_dir(&root_path, "directory-final");
            rustix::fs::mkfifoat(
                rustix::fs::CWD,
                root_path.join("fifo-final"),
                rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
            )
            .expect("fixture FIFO should be creatable");
            let root_descriptor =
                File::open(&root_path).expect("fixture root descriptor should open");
            let short_socket_route =
                format!("/proc/self/fd/{}/socket-final", root_descriptor.as_raw_fd());
            let _socket = UnixListener::bind(&short_socket_route)
                .expect("fixture socket should be creatable through a short retained-fd route");

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            assert_eq!(
                root.admit_file(&confined("linked"), immutable_expectation(b"linked"))
                    .expect_err("hardlinked file must fail")
                    .kind(),
                GenerationRootErrorKind::HardLinked
            );
            assert_eq!(
                root.admit_file(
                    &confined("directory-final"),
                    GenerationFileExpectation::immutable(0, digest(b""))
                        .expect("zero-length expectation should be accepted"),
                )
                .expect_err("directory must not be admitted as a regular file")
                .kind(),
                GenerationRootErrorKind::NotRegularFile
            );
            for route in ["fifo-final", "socket-final"] {
                assert!(
                    root.admit_file(
                        &confined(route),
                        GenerationFileExpectation::immutable(0, digest(b""))
                            .expect("zero-length expectation should be accepted"),
                    )
                    .is_err(),
                    "special file {route} must fail closed"
                );
            }
        }

        #[test]
        fn linux_final_probe_rejects_fifo_before_endpoint_io_procfd_reopen_or_read() {
            let root_path = fixture_root("fifo-preflight");
            let fifo_path = root_path.join("fifo-final");
            rustix::fs::mkfifoat(
                rustix::fs::CWD,
                &fifo_path,
                rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
            )
            .expect("fixture FIFO should be creatable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let hook_fifo = fifo_path.clone();
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if boundary == (TestBoundary::AfterFinalProbeOpen { index: 0 }) {
                    let error = OpenOptions::new()
                        .write(true)
                        .custom_flags(libc::O_NONBLOCK)
                        .open(&hook_fifo)
                        .expect_err("O_PATH preflight must not establish a FIFO reader endpoint");
                    assert_eq!(
                        error.raw_os_error(),
                        Some(libc::ENXIO),
                        "a nonblocking FIFO writer must still observe no reader endpoint"
                    );
                }
                Ok(())
            });

            for error in [
                root.admit_file(
                    &confined("fifo-final"),
                    GenerationFileExpectation::immutable(0, digest(b""))
                        .expect("zero-length expectation should be accepted"),
                )
                .expect_err("immutable FIFO must fail at type preflight"),
                root.admit_control_file(
                    &confined("fifo-final"),
                    GenerationFileExpectation::control(0)
                        .expect("zero-length control expectation should be accepted"),
                )
                .expect_err("control FIFO must fail at type preflight"),
            ] {
                assert_eq!(error.kind(), GenerationRootErrorKind::NotRegularFile);
                assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
            }
            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(
                observed.contains(&TestBoundary::AfterFinalProbeOpen { index: 0 }),
                "the no-I/O O_PATH probe should be observable"
            );
            // Root revalidation legitimately opens the verified procfs root
            // to bind task-scoped mountinfo before inspecting the final
            // component. `BeforeProcFdReopen` is the distinct boundary that
            // would reopen this probed FIFO as a data descriptor.
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::BeforeProcFdReopen { .. }
                        | TestBoundary::BeforeRead { .. }
                        | TestBoundary::BeforeLock
                        | TestBoundary::BeforeFileSync
                )),
                "special nodes must fail before final-capability reopen or any content operation"
            );
            drop(observed);
        }

        #[test]
        fn linux_final_probe_rejects_a_real_device_descriptor_without_io_reopen() {
            use rustix::fs::{CWD, ResolveFlags, openat2};

            let descriptor = openat2(
                CWD,
                Path::new("/dev/null"),
                rustix::fs::OFlags::PATH
                    | rustix::fs::OFlags::NOFOLLOW
                    | rustix::fs::OFlags::CLOEXEC,
                rustix::fs::Mode::empty(),
                ResolveFlags::NO_SYMLINKS | ResolveFlags::NO_MAGICLINKS,
            )
            .expect("the physical device should support a side-effect-free O_PATH reference");
            let error = validate_regular_descriptor_type(
                &descriptor,
                GenerationRootStage::OpenRegularFile,
                0,
            )
            .expect_err("the real device must fail the production type gate");
            assert_eq!(error.kind(), GenerationRootErrorKind::NotRegularFile);
            assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
        }

        #[test]
        fn linux_regular_to_fifo_swap_after_probe_never_touches_the_replacement() {
            let root_path = fixture_root("regular-to-fifo-after-probe");
            private_file(&root_path, "artifact", b"sealed");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let writer_probe = Arc::new(Mutex::new(None));
            let hook_writer_probe = Arc::clone(&writer_probe);
            let hook_root = root_path.clone();
            let mut swapped = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !swapped && boundary == (TestBoundary::AfterProbeQualified { index: 0 }) {
                    fs::rename(
                        hook_root.join("artifact"),
                        hook_root.join("artifact-original"),
                    )
                    .expect("the probed regular file should move without invalidating its fd");
                    rustix::fs::mkfifoat(
                        rustix::fs::CWD,
                        hook_root.join("artifact"),
                        rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
                    )
                    .expect("the canonical route should be replaceable with a FIFO fixture");
                    swapped = true;
                }
                if boundary == (TestBoundary::AfterProcFdReopen { index: 0 }) {
                    let observed_errno = match OpenOptions::new()
                        .write(true)
                        .custom_flags(libc::O_NONBLOCK)
                        .open(hook_root.join("artifact"))
                    {
                        Ok(writer) => {
                            drop(writer);
                            None
                        }
                        Err(error) => error.raw_os_error(),
                    };
                    *hook_writer_probe
                        .lock()
                        .expect("writer probe state should lock") = Some(observed_errno);
                }
                Ok(())
            });
            let error = root
                .admit_file(&confined("artifact"), immutable_expectation(b"sealed"))
                .expect_err("the final route reprobe must reject a special-node substitution");
            assert!(
                matches!(
                    error.kind(),
                    GenerationRootErrorKind::NotRegularFile
                        | GenerationRootErrorKind::ObjectChanged
                ),
                "the substitution must fail as a type or identity change"
            );
            assert_eq!(
                *writer_probe.lock().expect("writer probe state should lock"),
                Some(Some(libc::ENXIO)),
                "after the proc-derived data reopen, a nonblocking FIFO writer must still observe \
                 no reader; otherwise the retained descriptor touched the replacement FIFO"
            );
            assert!(
                !boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .iter()
                    .any(|boundary| matches!(boundary, TestBoundary::BeforeRead { .. })),
                "the replacement FIFO must never reach the content reader"
            );
        }

        #[test]
        fn linux_filtered_procfd_capability_reopen_is_typed_unsupported() {
            let root_path = fixture_root("filtered-procfd");
            private_file(&root_path, "artifact", b"sealed");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let _guard = install_test_hook(|boundary| {
                if boundary == TestBoundary::BeforeProcCapabilityRootOpen {
                    return Err(GenerationRootError::new(
                        GenerationRootErrorKind::UnsupportedKernelFeature,
                        GenerationRootStage::OpenRegularFile,
                    ));
                }
                Ok(())
            });
            let error = root
                .admit_file(&confined("artifact"), immutable_expectation(b"sealed"))
                .expect_err("a filtered procfd capability bridge must fail closed");
            assert_eq!(
                error.kind(),
                GenerationRootErrorKind::UnsupportedKernelFeature
            );
            assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
        }

        #[test]
        fn size_hash_grow_and_shrink_fail_closed() {
            let root_path = fixture_root("content");
            let contents = b"abcdefgh";
            let artifact = private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");

            let wrong_size = GenerationFileExpectation::immutable(7, digest(b"abcdefg"))
                .expect("small expectation should be accepted");
            assert_eq!(
                root.admit_file(&confined("artifact"), wrong_size)
                    .expect_err("wrong exact size must fail")
                    .kind(),
                GenerationRootErrorKind::SizeMismatch
            );
            let wrong_hash = GenerationFileExpectation::immutable(8, [0x31; 32])
                .expect("small expectation should be accepted");
            assert_eq!(
                root.admit_file(&confined("artifact"), wrong_hash)
                    .expect_err("wrong exact digest must fail")
                    .kind(),
                GenerationRootErrorKind::HashMismatch
            );

            for grow in [true, false] {
                fs::set_permissions(&artifact, fs::Permissions::from_mode(0o600))
                    .expect("fixture should become writable for the retained test fd");
                let mut mutation_file = OpenOptions::new()
                    .write(true)
                    .open(&artifact)
                    .expect("retained mutation fd should open");
                fs::set_permissions(&artifact, fs::Permissions::from_mode(0o400))
                    .expect("fixture should be resealed before admission");
                let guard = install_test_hook(move |boundary| {
                    if boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                        if grow {
                            mutation_file
                                .seek(SeekFrom::End(0))
                                .expect("fixture should be seekable");
                            mutation_file.write_all(b"+").expect("fixture should grow");
                        } else {
                            mutation_file.set_len(0).expect("fixture should shrink");
                        }
                        mutation_file
                            .sync_all()
                            .expect("size mutation should be durable");
                    }
                    Ok(())
                });
                assert!(
                    root.admit_file(&confined("artifact"), immutable_expectation(contents))
                        .is_err(),
                    "mid-read size drift must fail closed"
                );
                drop(guard);
                fs::set_permissions(&artifact, fs::Permissions::from_mode(0o600))
                    .expect("fixture should become writable for reset");
                let mut file = OpenOptions::new()
                    .write(true)
                    .truncate(true)
                    .open(&artifact)
                    .expect("fixture should be resettable");
                file.write_all(contents).expect("fixture should reset");
                file.sync_all().expect("reset should be durable");
                fs::set_permissions(&artifact, fs::Permissions::from_mode(0o400))
                    .expect("fixture should be resealed after reset");
            }
        }

        #[test]
        fn same_size_rewrite_and_hardlink_race_fail_after_initial_validation() {
            let contents = b"original";

            let root_path = fixture_root("rewrite-race");
            let artifact = private_file(&root_path, "artifact", contents);
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o600))
                .expect("fixture should become writable for the retained test fd");
            let mut rewrite_file = OpenOptions::new()
                .write(true)
                .open(&artifact)
                .expect("retained rewrite fd should open");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o400))
                .expect("fixture should be resealed before admission");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeFileRouteReopen {
                    rewrite_file
                        .seek(SeekFrom::Start(0))
                        .expect("fixture should be seekable");
                    rewrite_file
                        .write_all(b"rewrite!")
                        .expect("same-size rewrite should succeed");
                    rewrite_file.sync_all().expect("rewrite should be durable");
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect_err("same-size post-read rewrite must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            drop(guard);

            let root_path = fixture_root("nlink-race");
            let artifact = private_file(&root_path, "artifact", contents);
            let alias = root_path.join("late-alias");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let _guard = install_test_hook(move |boundary| {
                if boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    fs::hard_link(&artifact, &alias).expect("late hardlink should be creatable");
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect_err("post-open hardlink must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn file_and_root_path_swaps_are_detected_while_retained_bytes_survive() {
            let contents = b"retained exact bytes";
            let root_path = fixture_root("retained");
            let artifact = private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(contents))
                .expect("exact file should be admitted");

            let retained_artifact = root_path.join("artifact-retained");
            fs::rename(&artifact, &retained_artifact)
                .expect("fixture file should move to a fresh retained name");
            private_file(&root_path, "artifact", b"x");
            assert_eq!(admitted.as_bytes(), contents);
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect_err("replacement file must not satisfy original digest")
                    .kind(),
                GenerationRootErrorKind::SizeMismatch
            );

            let retained_root = root_path.with_extension("retained-root");
            fs::rename(&root_path, &retained_root)
                .expect("fixture root should move to a fresh retained name");
            DirBuilder::new()
                .mode(0o700)
                .create(&root_path)
                .expect("attacker root should be creatable");
            fs::set_permissions(&root_path, fs::Permissions::from_mode(0o700))
                .expect("attacker root mode should be settable");
            assert_eq!(
                root.revalidate_route()
                    .expect_err("root pathname replacement must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            assert_eq!(admitted.as_bytes(), contents);
        }

        #[test]
        fn root_swap_during_initial_double_resolution_is_rejected() {
            let root_path = fixture_root("root-admission-race");
            let retained_root = root_path.with_extension("first");
            let swap_source = root_path.clone();
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::AfterFirstRootQualification {
                    fs::rename(&swap_source, &retained_root)
                        .expect("first root should move to a fresh name");
                    DirBuilder::new()
                        .mode(0o700)
                        .create(&swap_source)
                        .expect("replacement root should be creatable");
                    fs::set_permissions(&swap_source, fs::Permissions::from_mode(0o700))
                        .expect("replacement root mode should be settable");
                }
                Ok(())
            });
            assert_eq!(
                QualifiedGenerationRoot::admit(&root_path)
                    .expect_err("mid-admission root swap must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn intermediate_ancestor_substitution_is_detected_when_final_root_inode_is_unchanged() {
            let base = fixture_root("ancestor-chain");
            let ancestor = private_dir(&base, "ancestor");
            let root_path = private_dir(&ancestor, "root");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted_root_witness = root.witness();

            let displaced_ancestor = base.join("displaced-ancestor");
            fs::rename(&ancestor, &displaced_ancestor)
                .expect("original ancestor should move to a fresh retained name");
            let replacement_ancestor = private_dir(&base, "ancestor");
            fs::rename(
                displaced_ancestor.join("root"),
                replacement_ancestor.join("root"),
            )
            .expect("the same admitted root inode should move under the replacement ancestor");

            assert_eq!(
                fs::metadata(&root_path)
                    .expect("canonical root route should resolve again")
                    .ino(),
                admitted_root_witness.inode()
            );
            assert_eq!(
                root.revalidate_route()
                    .expect_err(
                        "whole-route validation must reject a replaced intermediate ancestor"
                    )
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn relative_ancestor_substitution_is_detected_when_final_file_inode_is_unchanged() {
            let root_path = fixture_root("relative-ancestor-chain");
            let ancestor = private_dir(&root_path, "ancestor");
            let nested = private_dir(&ancestor, "nested");
            let contents = b"same retained file";
            private_file(&nested, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(
                    &confined("ancestor/nested/artifact"),
                    immutable_expectation(contents),
                )
                .expect("immutable file should qualify");
            let admitted_inode = admitted.witness().inode();

            let displaced_ancestor = root_path.join("displaced-ancestor");
            fs::rename(&ancestor, &displaced_ancestor)
                .expect("original relative ancestor should move to a fresh retained name");
            let replacement_ancestor = private_dir(&root_path, "ancestor");
            fs::rename(
                displaced_ancestor.join("nested"),
                replacement_ancestor.join("nested"),
            )
            .expect("the original final subtree should move below the replacement ancestor");

            assert_eq!(
                fs::metadata(root_path.join("ancestor/nested/artifact"))
                    .expect("canonical final file route should resolve again")
                    .ino(),
                admitted_inode
            );
            assert_eq!(
                admitted
                    .sync_durable()
                    .expect_err("the full relative identity chain must reject a replaced ancestor")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn control_ancestor_substitution_fails_before_flock_when_final_inode_is_unchanged() {
            let root_path = fixture_root("control-ancestor-chain");
            let ancestor = private_dir(&root_path, "ancestor");
            let nested = private_dir(&ancestor, "nested");
            control_file(&nested, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("ancestor/nested/LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("control file should qualify");
            let admitted_inode = control.witness().inode();

            let displaced_ancestor = root_path.join("displaced-ancestor");
            fs::rename(&ancestor, &displaced_ancestor)
                .expect("original relative ancestor should move to a fresh retained name");
            let replacement_ancestor = private_dir(&root_path, "ancestor");
            fs::rename(
                displaced_ancestor.join("nested"),
                replacement_ancestor.join("nested"),
            )
            .expect("the original control subtree should move below the replacement ancestor");

            assert_eq!(
                fs::metadata(root_path.join("ancestor/nested/LOCK"))
                    .expect("canonical final control route should resolve again")
                    .ino(),
                admitted_inode
            );
            let lock_boundary_reached = Arc::new(Mutex::new(false));
            let hook_lock_boundary_reached = Arc::clone(&lock_boundary_reached);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_lock_boundary_reached
                        .lock()
                        .expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("relative ancestor replacement must fail before flock")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            assert!(
                !*lock_boundary_reached
                    .lock()
                    .expect("hook state should lock"),
                "relative route validation must precede flock"
            );
        }

        #[test]
        fn lock_modes_contend_release_sync_and_validate_optional_digest() {
            let root_path = fixture_root("locks");
            let contents = b"lock-v1!";
            control_file(&root_path, "LOCK", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let route = confined("LOCK");
            let expectation = GenerationFileExpectation::control(8)
                .expect("small control-file expectation should be accepted");
            let control = root
                .admit_control_file(&route, expectation)
                .expect("control file should be admitted once");
            assert_eq!(control.bytes().as_ref(), contents);
            assert_eq!(control.sha256(), digest(contents));

            let shared_one = control
                .try_lock(GenerationRootLockMode::Shared)
                .expect("first shared lock should succeed");
            let shared_two = control
                .try_lock(GenerationRootLockMode::Shared)
                .expect("second shared lock should succeed");
            assert_eq!(
                control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("exclusive lock must contend with shared locks")
                    .kind(),
                GenerationRootErrorKind::LockContended
            );
            shared_one.unlock().expect("shared unlock should succeed");
            shared_two.unlock().expect("shared unlock should succeed");

            let exclusive = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("exclusive lock should succeed after release");
            assert_eq!(exclusive.witness(), control.witness());
            assert_eq!(exclusive.bytes().as_ref(), contents);
            assert_eq!(exclusive.sha256(), control.sha256());
            assert_eq!(exclusive.mode(), GenerationRootLockMode::Exclusive);
            assert_eq!(
                control
                    .try_lock(GenerationRootLockMode::Shared)
                    .expect_err("shared lock must contend with exclusive lock")
                    .kind(),
                GenerationRootErrorKind::LockContended
            );
            exclusive
                .sync_durable()
                .expect("locked control-file fsync should succeed");
            exclusive.unlock().expect("exclusive unlock should succeed");

            let exact_control = root
                .admit_control_file(
                    &route,
                    GenerationFileExpectation::control_with_sha256(8, digest(contents))
                        .expect("small expectation should be accepted"),
                )
                .expect("digest-qualified control capability should be admitted");
            let exact = exact_control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("digest-qualified lock should succeed");
            exact
                .unlock()
                .expect("digest-qualified unlock should succeed");
            let wrong = GenerationFileExpectation::control_with_sha256(8, [0xa5; 32])
                .expect("small expectation should be accepted");
            assert_eq!(
                root.admit_control_file(&route, wrong)
                    .expect("wrong digest is checked only while acquiring the lock")
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("wrong lock-file digest must fail after acquisition")
                    .kind(),
                GenerationRootErrorKind::HashMismatch
            );
        }

        #[test]
        fn immutable_content_drift_fences_sync_before_durability() {
            let root_path = fixture_root("mapped-immutable-before-sync");
            let (artifact_path, mapping) = mapped_immutable_file(&root_path, "artifact");
            let admitted_bytes =
                fs::read(&artifact_path).expect("mapped immutable fixture must be readable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(
                    &confined("artifact"),
                    immutable_expectation(&admitted_bytes),
                )
                .expect("mapped immutable fixture should qualify before ambient mutation");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared immutable mapping should remain retained by the hook"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = admitted
                .sync_durable()
                .expect_err("pre-durability immutable content drift must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            assert!(
                !boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .contains(&TestBoundary::BeforeFileSync),
                "immutable content validation must fail before the durability syscall"
            );
        }

        #[test]
        fn immutable_content_drift_during_durability_is_detected_after_barrier() {
            let root_path = fixture_root("mapped-immutable-during-sync");
            let (artifact_path, mapping) = mapped_immutable_file(&root_path, "artifact");
            let admitted_bytes =
                fs::read(&artifact_path).expect("mapped immutable fixture must be readable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(
                    &confined("artifact"),
                    immutable_expectation(&admitted_bytes),
                )
                .expect("mapped immutable fixture should qualify before ambient mutation");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == TestBoundary::BeforeFileSync {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared immutable mapping should remain retained by the hook"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = admitted
                .sync_durable()
                .expect_err("immutable mutation at durability must fail after the barrier");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            let observed = boundaries.lock().expect("boundary log should lock");
            let after_sync = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::AfterFileSync)
                .expect("the durability barrier should complete before post-check failure");
            assert!(
                observed.iter().enumerate().any(|(index, boundary)| {
                    index > after_sync && *boundary == (TestBoundary::BeforeRead { offset: 0 })
                }),
                "a second exact immutable content read must follow the durability barrier"
            );
            drop(observed);
        }

        #[test]
        fn control_writer_mapping_is_lock_contended() {
            let root_path = fixture_root("mapped-control-after-flock");
            let (lock_path, _mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let expectation = GenerationFileExpectation::control(byte_len)
                .expect("mapped control fixture length should be accepted");
            let control = root
                .admit_control_file(&confined("LOCK"), expectation)
                .expect("mapped control fixture should qualify before lock acquisition");
            let error = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("retained FSVI writer mapping must block a second exclusive lock");
            assert_eq!(error.kind(), GenerationRootErrorKind::LockContended);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
        }

        #[test]
        fn control_content_drift_fences_sync_before_durability() {
            let root_path = fixture_root("mapped-control-before-sync");
            let (lock_path, mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let error = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(byte_len)
                        .expect("mapped control fixture length should be accepted"),
                )
                .expect("mapped control fixture should qualify")
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("retained FSVI writer mapping must block the durability lock");
            assert_eq!(error.kind(), GenerationRootErrorKind::LockContended);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            drop(mapping);
        }

        #[test]
        fn control_content_drift_during_durability_is_detected_after_barrier() {
            let root_path = fixture_root("mapped-control-during-sync");
            let (lock_path, mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let error = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(byte_len)
                        .expect("mapped control fixture length should be accepted"),
                )
                .expect("mapped control fixture should qualify")
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("retained FSVI writer mapping must block the durability lock");
            assert_eq!(error.kind(), GenerationRootErrorKind::LockContended);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            drop(mapping);
        }

        #[test]
        fn bound_content_mismatch_is_object_changed_even_when_metadata_is_not_consulted() {
            let error = validate_bound_control_content_for_test(
                [0x11; 32],
                [0x22; 32],
                GenerationRootStage::AcquireLock,
            )
            .expect_err("different content witnesses must fail independently of metadata");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            validate_bound_control_content_for_test(
                [0x33; 32],
                [0x33; 32],
                GenerationRootStage::SyncRegularFile,
            )
            .expect("identical content witnesses should validate");
        }

        #[test]
        fn inherited_lock_guard_never_issues_unlock_from_a_different_process_identity() {
            let root_path = fixture_root("forked-lock");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            let mut inherited = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("exclusive lock should succeed");
            set_lock_creator_process_id_for_test(
                &mut inherited.inner,
                std::process::id().wrapping_add(1),
            );
            let unlock_boundary_reached = Arc::new(Mutex::new(false));
            let hook_boundary_reached = Arc::clone(&unlock_boundary_reached);
            let guard = install_test_hook(move |boundary| {
                if matches!(
                    boundary,
                    TestBoundary::BeforeUnlock | TestBoundary::AfterUnlock
                ) {
                    *hook_boundary_reached
                        .lock()
                        .expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                inherited
                    .unlock()
                    .expect_err("simulated fork child must refuse explicit unlock")
                    .kind(),
                GenerationRootErrorKind::ForkedProcess
            );
            assert!(
                !*unlock_boundary_reached
                    .lock()
                    .expect("hook state should lock"),
                "process identity must be checked before the explicit LOCK_UN path"
            );
            drop(guard);

            control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("descriptor close should leave the control file lockable")
                .unlock()
                .expect("fresh same-process lock should unlock");
        }

        #[test]
        fn inherited_root_capability_fails_before_proc_bridge_and_regular_file_io() {
            let root_path = fixture_root("forked-root");
            private_file(&root_path, "artifact", b"fork");
            let mut root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            set_root_creator_process_id_for_test(
                &mut root.inner,
                std::process::id().wrapping_add(1),
            );
            let boundary_reached = Arc::new(Mutex::new(false));
            let hook_boundary_reached = Arc::clone(&boundary_reached);
            let _guard = install_test_hook(move |_| {
                *hook_boundary_reached
                    .lock()
                    .expect("hook state should lock") = true;
                Ok(())
            });

            let file_error = root
                .admit_file(&confined("artifact"), immutable_expectation(b"fork"))
                .expect_err("simulated fork child must reject before the proc-fd bridge");
            assert_eq!(file_error.kind(), GenerationRootErrorKind::ForkedProcess);
            assert_eq!(file_error.stage(), GenerationRootStage::RevalidateRootRoute);
            let route_error = root
                .revalidate_route()
                .expect_err("simulated fork child must reject the retained root");
            assert_eq!(route_error.kind(), GenerationRootErrorKind::ForkedProcess);
            assert_eq!(
                route_error.stage(),
                GenerationRootStage::RevalidateRootRoute
            );
            assert!(
                !*boundary_reached.lock().expect("hook state should lock"),
                "process identity must be checked before proc-root qualification, proc-fd \
                 resolution, reads, flock, sync, or route work"
            );
        }

        #[test]
        #[ignore = "requires native Linux, python3, fork, and procfs"]
        fn physical_linux_proc_bridge_fork_receipt_separates_child_self_from_parent_fd_number() {
            let root_path = fixture_root("physical-fork-proc-bridge");
            let inherited_path = private_file(&root_path, "inherited", b"inherited");
            let parent_decoy_path = private_file(&root_path, "parent-decoy", b"parent-decoy");
            let script = r#"
import json
import os
import sys

inherited_path = os.path.realpath(sys.argv[1])
parent_decoy_path = os.path.realpath(sys.argv[2])
parent_pid = os.getpid()
probe = os.open(inherited_path, os.O_PATH | os.O_CLOEXEC)
probe_number = probe
ready_read, ready_write = os.pipe()
continue_read, continue_write = os.pipe()
child = os.fork()
if child == 0:
    os.close(ready_read)
    os.close(continue_write)
    os.write(ready_write, b"r")
    os.close(ready_write)
    if os.read(continue_read, 1) != b"c":
        os._exit(3)
    os.close(continue_read)
    child_self_route = os.readlink(f"/proc/self/fd/{probe_number}")
    parent_same_number_route = os.readlink(
        f"/proc/{parent_pid}/fd/{probe_number}"
    )
    child_ok = (
        child_self_route == inherited_path
        and parent_same_number_route == parent_decoy_path
    )
    print(json.dumps({
        "role": "child",
        "probe_number": probe_number,
        "self_route": child_self_route,
        "parent_same_number_route": parent_same_number_route,
        "self_is_inherited": child_self_route == inherited_path,
        "parent_same_number_is_decoy": (
            parent_same_number_route == parent_decoy_path
        ),
    }), flush=True)
    os._exit(0 if child_ok else 4)

os.close(ready_write)
os.close(continue_read)
if os.read(ready_read, 1) != b"r":
    raise SystemExit(5)
os.close(ready_read)
os.close(probe)
decoy = os.open(parent_decoy_path, os.O_PATH | os.O_CLOEXEC)
if decoy != probe_number:
    os.dup2(decoy, probe_number, inheritable=False)
    os.close(decoy)
parent_self_route = os.readlink(f"/proc/self/fd/{probe_number}")
os.write(continue_write, b"c")
os.close(continue_write)
_, status = os.waitpid(child, 0)
child_exit = os.waitstatus_to_exitcode(status)
print(json.dumps({
    "role": "parent",
    "probe_number": probe_number,
    "self_route": parent_self_route,
    "self_is_decoy": parent_self_route == parent_decoy_path,
    "child_exit": child_exit,
}), flush=True)
if parent_self_route != parent_decoy_path or child_exit != 0:
    raise SystemExit(6)
"#;
            let output = Command::new("python3")
                .arg("-c")
                .arg(script)
                .arg(&inherited_path)
                .arg(&parent_decoy_path)
                .output()
                .expect("native proc-bridge fork receipt requires python3");
            assert!(
                output.status.success(),
                "proc-bridge fork receipt failed: status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            let stdout = String::from_utf8(output.stdout).expect("fork receipt JSON must be UTF-8");
            let mut records = stdout.lines().map(|line| {
                serde_json::from_str::<serde_json::Value>(line)
                    .expect("each fork receipt line must be JSON")
            });
            let child = records.next().expect("child receipt must be present");
            let parent = records.next().expect("parent receipt must be present");
            assert!(
                records.next().is_none(),
                "fork receipt must contain exactly child and parent records"
            );
            assert_eq!(child["role"], "child");
            assert_eq!(child["self_is_inherited"], true);
            assert_eq!(child["parent_same_number_is_decoy"], true);
            assert_eq!(parent["role"], "parent");
            assert_eq!(parent["self_is_decoy"], true);
            assert_eq!(parent["child_exit"], 0);
            assert_eq!(
                child["probe_number"], parent["probe_number"],
                "the receipt must compare the exact same numeric descriptor in both processes"
            );
            assert_ne!(
                child["self_route"], child["parent_same_number_route"],
                "the child's self route must remain bound to its inherited probe while the \
                 parent's same-number route names the decoy"
            );
        }

        #[test]
        #[ignore = "requires native Linux, python3, and fork/flock process support"]
        fn physical_linux_fork_receipt_proves_close_vs_explicit_unlock_with_inherited_ofd() {
            let root_path = fixture_root("physical-fork-ofd");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let script = r#"
import fcntl
import json
import os
import sys

path = sys.argv[1]

def open_lock():
    return os.open(path, os.O_RDWR | os.O_CLOEXEC)

held = open_lock()
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
read_end, write_end = os.pipe()
child = os.fork()
if child == 0:
    os.close(write_end)
    os.read(read_end, 1)
    os.close(held)
    os._exit(0)
os.close(read_end)
os.close(held)
probe = open_lock()
close_only_contended = False
try:
    fcntl.flock(probe, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    close_only_contended = True
os.write(write_end, b"x")
os.close(write_end)
os.waitpid(child, 0)
fcntl.flock(probe, fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(probe, fcntl.LOCK_UN)
os.close(probe)

held = open_lock()
fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)
read_end, write_end = os.pipe()
child = os.fork()
if child == 0:
    os.close(write_end)
    os.read(read_end, 1)
    os.close(held)
    os._exit(0)
os.close(read_end)
fcntl.flock(held, fcntl.LOCK_UN)
os.close(held)
probe = open_lock()
fcntl.flock(probe, fcntl.LOCK_EX | fcntl.LOCK_NB)
explicit_unlock_released = True
fcntl.flock(probe, fcntl.LOCK_UN)
os.close(probe)
os.write(write_end, b"x")
os.close(write_end)
os.waitpid(child, 0)

print(json.dumps({
    "close_only_contended_while_child_retained_ofd": close_only_contended,
    "explicit_unlock_released_while_child_retained_ofd": explicit_unlock_released,
}))
if not close_only_contended or not explicit_unlock_released:
    raise SystemExit(2)
"#;
            let output = Command::new("python3")
                .arg("-c")
                .arg(script)
                .arg(&lock_path)
                .output()
                .expect("native fork receipt requires python3");
            assert!(
                output.status.success(),
                "native fork/OFD receipt failed: status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
            let stdout = String::from_utf8(output.stdout)
                .expect("native fork/OFD receipt must emit UTF-8 JSON");
            assert!(stdout.contains("\"close_only_contended_while_child_retained_ofd\": true"));
            assert!(stdout.contains("\"explicit_unlock_released_while_child_retained_ofd\": true"));
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_LINUX_LOCK_FORK_TEST_ROOT on native ext4/Btrfs plus python3"]
        fn physical_generation_lock_drop_and_unlock_release_while_child_retains_same_ofd() {
            struct FdHolder {
                child: Option<std::process::Child>,
            }

            impl FdHolder {
                fn assert_alive(&mut self) {
                    assert!(
                        self.child
                            .as_mut()
                            .expect("fd-holder child must be present")
                            .try_wait()
                            .expect("fd-holder liveness should be observable")
                            .is_none(),
                        "child must still retain the guard OFD"
                    );
                }

                fn release(mut self) {
                    let mut child = self.child.take().expect("fd-holder child must be present");
                    child
                        .stdin
                        .take()
                        .expect("fd-holder stdin must be piped")
                        .write_all(b"x")
                        .expect("fd-holder release byte must be writable");
                    let output = child
                        .wait_with_output()
                        .expect("fd-holder process must be waitable");
                    assert!(
                        output.status.success(),
                        "fd-holder failed: status={:?}, stderr={}",
                        output.status.code(),
                        String::from_utf8_lossy(&output.stderr)
                    );
                }
            }

            impl Drop for FdHolder {
                fn drop(&mut self) {
                    let Some(mut child) = self.child.take() else {
                        return;
                    };
                    if let Some(mut stdin) = child.stdin.take() {
                        let _ = stdin.write_all(b"x");
                    }
                    match child.try_wait() {
                        Ok(Some(_)) => {}
                        Ok(None) | Err(_) => {
                            let _ = child.kill();
                            let _ = child.wait();
                        }
                    }
                }
            }

            fn spawn_inherited_fd_holder(alias: &rustix::fd::OwnedFd) -> FdHolder {
                let mut child = Command::new("python3")
                    .arg("-c")
                    .arg(
                        "import os,sys; fd=int(sys.argv[1]); os.fstat(fd); \
                         print('READY', flush=True); sys.stdin.buffer.read(1)",
                    )
                    .arg(alias.as_raw_fd().to_string())
                    .stdin(Stdio::piped())
                    .stdout(Stdio::piped())
                    .stderr(Stdio::piped())
                    .spawn()
                    .expect("native inherited-OFD receipt requires python3");
                let stdout = child.stdout.take().expect("fd-holder stdout must be piped");
                let mut ready = String::new();
                BufReader::new(stdout)
                    .read_line(&mut ready)
                    .expect("fd-holder readiness must be readable");
                assert_eq!(ready.trim(), "READY", "child must retain the exact alias");
                FdHolder { child: Some(child) }
            }

            let base = std::env::var_os("FRANKENSEARCH_LINUX_LOCK_FORK_TEST_ROOT")
                .map(PathBuf::from)
                .expect("set FRANKENSEARCH_LINUX_LOCK_FORK_TEST_ROOT to native ext4/Btrfs");
            let filesystem =
                rustix::fs::statfs(&base).expect("physical lock fixture base must be statable");
            assert!(
                i128::from(filesystem.f_type) == i128::from(libc::EXT4_SUPER_MAGIC)
                    || i128::from(filesystem.f_type) == i128::from(libc::BTRFS_SUPER_MAGIC),
                "physical inherited-OFD receipt requires ext4 or Btrfs"
            );
            let root_path = fixture_root_under(&base, "physical-generation-lock-fork");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("control file should qualify");

            let dropped = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("Rust guard should acquire for Drop receipt");
            let drop_alias = duplicate_lock_descriptor_for_inheritance_for_test(&dropped.inner)
                .expect("test should duplicate the private guard descriptor");
            let mut drop_child = spawn_inherited_fd_holder(&drop_alias);
            drop(drop_alias);
            drop_child.assert_alive();
            drop(dropped);
            control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("creator Drop must LOCK_UN while the child alias survives")
                .unlock()
                .expect("fresh lock after creator Drop should release");
            drop_child.release();

            let explicit = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("Rust guard should acquire for explicit-unlock receipt");
            let explicit_alias =
                duplicate_lock_descriptor_for_inheritance_for_test(&explicit.inner)
                    .expect("test should duplicate the explicit guard descriptor");
            let mut explicit_child = spawn_inherited_fd_holder(&explicit_alias);
            drop(explicit_alias);
            explicit_child.assert_alive();
            explicit
                .unlock()
                .expect("creator explicit LOCK_UN should succeed");
            control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("explicit LOCK_UN must release while the child alias survives")
                .unlock()
                .expect("fresh lock after explicit unlock should release");
            explicit_child.release();
        }

        #[test]
        fn control_route_replacement_fences_lock_acquisition_and_locked_sync() {
            let root_path = fixture_root("control-route-replacement-before-lock");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            fs::rename(&lock_path, root_path.join("retained-LOCK"))
                .expect("original control file should move to a fresh retained route");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let before_lock_reached = Arc::new(Mutex::new(false));
            let hook_before_lock_reached = Arc::clone(&before_lock_reached);
            let guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_before_lock_reached
                        .lock()
                        .expect("hook state should lock") = true;
                }
                Ok(())
            });
            let lock_error = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("replacement route must fence lock acquisition");
            assert_eq!(lock_error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                lock_error.stage(),
                GenerationRootStage::RevalidateRegularFile
            );
            assert!(
                !*before_lock_reached.lock().expect("hook state should lock"),
                "route identity must be checked before flock"
            );
            drop(guard);

            let root_path = fixture_root("control-route-replacement-after-lock");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            let lock = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("exclusive lock should succeed");
            let retained_lock_path = root_path.join("retained-LOCK");
            fs::rename(&lock_path, &retained_lock_path)
                .expect("locked file should move to a fresh retained route");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let sync_boundary_reached = Arc::new(Mutex::new(false));
            let hook_sync_boundary_reached = Arc::clone(&sync_boundary_reached);
            let unlock_boundary_reached = Arc::new(Mutex::new(false));
            let hook_unlock_boundary_reached = Arc::clone(&unlock_boundary_reached);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeFileSync {
                    *hook_sync_boundary_reached
                        .lock()
                        .expect("hook state should lock") = true;
                }
                if boundary == TestBoundary::BeforeUnlock {
                    *hook_unlock_boundary_reached
                        .lock()
                        .expect("hook state should lock") = true;
                }
                Ok(())
            });
            let sync_error = lock
                .sync_durable()
                .expect_err("replacement route must fence locked sync");
            assert_eq!(sync_error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                sync_error.stage(),
                GenerationRootStage::RevalidateRegularFile
            );
            assert!(
                !*sync_boundary_reached
                    .lock()
                    .expect("hook state should lock"),
                "route identity must be checked before the durability syscall"
            );
            let unlock_error = lock
                .unlock()
                .expect_err("route replacement remains visible during explicit unlock");
            assert_eq!(unlock_error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                unlock_error.stage(),
                GenerationRootStage::RevalidateRegularFile
            );
            assert!(
                *unlock_boundary_reached
                    .lock()
                    .expect("hook state should lock"),
                "route-validation failure must not skip the explicit LOCK_UN path"
            );
            let retained_lock = OpenOptions::new()
                .read(true)
                .write(true)
                .open(&retained_lock_path)
                .expect("retained lock inode should reopen after failed validation");
            rustix::fs::flock(
                &retained_lock,
                rustix::fs::FlockOperation::NonBlockingLockExclusive,
            )
            .expect("failed validation must still release the retained inode lock");
            rustix::fs::flock(&retained_lock, rustix::fs::FlockOperation::Unlock)
                .expect("test lock cleanup should succeed");
        }

        #[test]
        fn unsupported_linux_filesystems_fail_before_admission() {
            let tmpfs_base = Path::new("/dev/shm");
            let tmpfs_stat =
                rustix::fs::statfs(tmpfs_base).expect("physical tmpfs fixture must be statable");
            assert_eq!(
                i128::from(tmpfs_stat.f_type),
                i128::from(libc::TMPFS_MAGIC),
                "unsupported-filesystem receipt requires a real tmpfs mount"
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(tmpfs_base)
                    .expect_err("the tmpfs mount itself must fail the physical allowlist")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(Path::new("/proc"))
                    .expect_err("procfs root must fail the physical filesystem allowlist")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
        }

        #[test]
        fn xfs_remains_fail_closed_until_its_native_receipt_bead_closes() {
            let raw_type: rustix::fs::FsWord = libc::XFS_SUPER_MAGIC;
            assert_eq!(
                linux_filesystem_profile(raw_type, 1)
                    .expect_err("an unreceipted XFS profile must not reach mountinfo admission")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
        }

        #[test]
        fn statx_writable_truth_requires_and_rejects_immutable_and_append_attributes() {
            use rustix::fs::StatxAttributes;

            let required = StatxAttributes::IMMUTABLE | StatxAttributes::APPEND;
            validate_linux_writable_attributes_for_test(StatxAttributes::empty(), required)
                .expect("a reported writable object should pass");

            let missing_mask = validate_linux_writable_attributes_for_test(
                StatxAttributes::empty(),
                StatxAttributes::IMMUTABLE,
            )
            .expect_err("an unreported append attribute must fail closed");
            assert_eq!(
                missing_mask.kind(),
                GenerationRootErrorKind::UnsupportedKernelFeature
            );
            assert_eq!(missing_mask.stage(), GenerationRootStage::QualifyFilesystem);

            for attribute in [StatxAttributes::IMMUTABLE, StatxAttributes::APPEND] {
                let error = validate_linux_writable_attributes_for_test(attribute, required)
                    .expect_err("immutable or append-only objects are not writable truth");
                assert_eq!(error.kind(), GenerationRootErrorKind::WriteRestrictedObject);
                assert_eq!(error.stage(), GenerationRootStage::QualifyFilesystem);
            }
        }

        #[test]
        fn stat_and_statx_device_components_must_match_exactly() {
            assert!(linux_device_components_match_for_test(8, 1, 8, 1));
            assert!(!linux_device_components_match_for_test(8, 1, 9, 1));
            assert!(!linux_device_components_match_for_test(8, 1, 8, 2));
        }

        #[test]
        fn proc_bridge_errno_classes_distinguish_limits_policy_and_identity_drift() {
            for error in [
                rustix::io::Errno::MFILE,
                rustix::io::Errno::NFILE,
                rustix::io::Errno::NOMEM,
            ] {
                assert_eq!(
                    proc_bridge_error_for_test(error).kind(),
                    GenerationRootErrorKind::ResourceLimit
                );
                assert_eq!(
                    linux_open_error_for_test(error).kind(),
                    GenerationRootErrorKind::ResourceLimit
                );
                let mountinfo_error = linux_mountinfo_error_for_test(error);
                assert_eq!(
                    mountinfo_error.kind(),
                    GenerationRootErrorKind::ResourceLimit
                );
                assert_eq!(mountinfo_error.raw_os_error(), Some(error.raw_os_error()));
            }
            let mountinfo_io = linux_mountinfo_error_for_test(rustix::io::Errno::IO);
            assert_eq!(mountinfo_io.kind(), GenerationRootErrorKind::Io);
            assert_eq!(
                mountinfo_io.raw_os_error(),
                Some(rustix::io::Errno::IO.raw_os_error())
            );
            for error in [rustix::io::Errno::PERM, rustix::io::Errno::ACCESS] {
                assert_eq!(
                    proc_bridge_error_for_test(error).kind(),
                    GenerationRootErrorKind::UnsupportedKernelFeature
                );
            }
            for error in [
                rustix::io::Errno::NOENT,
                rustix::io::Errno::NOTDIR,
                rustix::io::Errno::LOOP,
                rustix::io::Errno::XDEV,
                rustix::io::Errno::STALE,
            ] {
                assert_eq!(
                    proc_bridge_error_for_test(error).kind(),
                    GenerationRootErrorKind::ObjectChanged
                );
            }
            for error in [
                rustix::io::Errno::NOENT,
                rustix::io::Errno::NOTDIR,
                rustix::io::Errno::LOOP,
                rustix::io::Errno::XDEV,
            ] {
                assert_eq!(
                    proc_root_error_for_test(error).kind(),
                    GenerationRootErrorKind::UnsupportedKernelFeature
                );
            }
        }

        #[test]
        fn proc_bridge_requires_kernel_attestation_of_the_mount_id_field() {
            use rustix::fs::StatxFlags;

            assert_eq!(
                validate_proc_mount_id_mask_for_test(StatxFlags::MNT_ID, 47)
                    .expect("reported mount identity should pass"),
                47
            );
            let error = validate_proc_mount_id_mask_for_test(StatxFlags::BASIC_STATS, 47)
                .expect_err("an unreported mount-id value must never be trusted");
            assert_eq!(
                error.kind(),
                GenerationRootErrorKind::UnsupportedKernelFeature
            );
            assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
            assert_eq!(error.expected(), Some(u64::from(StatxFlags::MNT_ID.bits())));
            assert_eq!(error.observed(), Some(0));
        }

        #[test]
        fn proc_thread_self_binding_and_bridge_route_name_the_current_thread_table() {
            let process_id = std::process::id();
            let thread_id = rustix::thread::gettid();
            assert_eq!(
                fs::read_link("/proc/thread-self")
                    .expect("the kernel thread-self binding must be readable"),
                PathBuf::from(format!("{process_id}/task/{thread_id}"))
            );
            assert_eq!(
                proc_thread_fd_route_for_test(47),
                "thread-self/fd/47",
                "the production bridge must never route through the leader's self/fd table"
            );
            assert_eq!(
                linux_task_mountinfo_route_for_test(process_id, thread_id.as_raw_pid()),
                PathBuf::from(format!("{process_id}/task/{thread_id}/mountinfo")),
                "the verified proc-root-relative route must name the accessing thread namespace"
            );
        }

        #[test]
        #[ignore = "physical Linux CLONE_FILES regression must run as an exact isolated test"]
        #[allow(deprecated)]
        fn physical_linux_thread_self_bridge_survives_an_unshared_fd_table_collision() {
            use rustix::thread::UnshareFlags;
            use std::sync::mpsc;

            let root_path = fixture_root("thread-self-unshared-files");
            let artifact_path = private_file(&root_path, "artifact", b"thread-local capability");
            let (descriptor_sender, descriptor_receiver) = mpsc::sync_channel(0);
            let (continue_sender, continue_receiver) = mpsc::sync_channel(0);
            let worker = std::thread::spawn(move || {
                // rustix 1.1.4 retains this deprecated safe wrapper. This
                // worker owns every descriptor it opens after unsharing and
                // terminates immediately after the receipt, satisfying the
                // API's no-cross-table-descriptor-use invariant.
                rustix::thread::unshare(UnshareFlags::FILES)
                    .expect("the worker file table must unshare without privilege");
                let retained =
                    File::open(&artifact_path).expect("the worker-local artifact must open");
                let raw_fd = retained.as_raw_fd();
                descriptor_sender
                    .send(raw_fd)
                    .expect("the leader must receive the collision descriptor number");
                continue_receiver
                    .recv()
                    .expect("the leader must establish its decoy at the same fd number");

                assert_eq!(
                    fs::read_link(format!("/proc/self/fd/{raw_fd}"))
                        .expect("the leader-table proc route must resolve"),
                    PathBuf::from("/dev/null"),
                    "self/fd must demonstrate the unrelated leader-table collision"
                );
                assert_eq!(
                    fs::read_link(format!("/proc/thread-self/fd/{raw_fd}"))
                        .expect("the worker-table proc route must resolve"),
                    artifact_path,
                    "thread-self/fd must remain bound to the worker-local capability"
                );

                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("the private root must qualify after CLONE_FILES");
                let admitted = root
                    .admit_file(
                        &confined("artifact"),
                        immutable_expectation(b"thread-local capability"),
                    )
                    .expect("production admission must reopen through the worker descriptor table");
                assert_eq!(
                    admitted.bytes().as_ref(),
                    b"thread-local capability",
                    "the admitted bytes must come from the worker-local retained capability"
                );
            });

            let worker_fd = descriptor_receiver
                .recv()
                .expect("the worker must report its retained fd number");
            let leader_decoy = File::open("/dev/null").expect("the leader decoy must open");
            assert_eq!(
                leader_decoy.as_raw_fd(),
                worker_fd,
                "the isolated receipt requires an exact leader/worker fd-number collision"
            );
            continue_sender
                .send(())
                .expect("the worker must be released after collision setup");
            worker
                .join()
                .expect("the unshared-table worker must complete without panic");
        }

        #[test]
        #[ignore = "physical Linux CLONE_NEWNS receipt requires root and exact isolated execution"]
        #[allow(deprecated)]
        fn physical_linux_task_mountinfo_observes_the_calling_threads_private_mount_namespace() {
            use rustix::fs::{AtFlags, CWD, StatxFlags, statx};
            use rustix::thread::UnshareFlags;

            assert!(
                rustix::process::geteuid().is_root(),
                "the task-scoped mountinfo receipt requires CAP_SYS_ADMIN"
            );
            let mountpoint = private_dir(
                &fixture_root("task-mountinfo-private-namespace"),
                "bind-mount",
            );
            let worker = std::thread::spawn(move || {
                // NEWNS does not split the descriptor table. This isolated
                // worker performs all namespace-sensitive work itself and
                // exits immediately, so the private mounts disappear with
                // the last task holding the namespace.
                rustix::thread::unshare(UnshareFlags::NEWNS)
                    .expect("the worker must acquire a private mount namespace");
                let private_output = Command::new("mount")
                    .args(["--make-rprivate", "/"])
                    .output()
                    .expect("the physical receipt requires util-linux mount");
                assert!(
                    private_output.status.success(),
                    "making the worker namespace private failed: status={:?}, stdout={}, stderr={}",
                    private_output.status.code(),
                    String::from_utf8_lossy(&private_output.stdout),
                    String::from_utf8_lossy(&private_output.stderr)
                );
                let bind_output = Command::new("mount")
                    .arg("--bind")
                    .arg(&mountpoint)
                    .arg(&mountpoint)
                    .output()
                    .expect("the physical receipt requires util-linux mount");
                assert!(
                    bind_output.status.success(),
                    "worker-private bind mount failed: status={:?}, stdout={}, stderr={}",
                    bind_output.status.code(),
                    String::from_utf8_lossy(&bind_output.stdout),
                    String::from_utf8_lossy(&bind_output.stderr)
                );

                let extended = statx(
                    CWD,
                    &mountpoint,
                    AtFlags::NO_AUTOMOUNT,
                    StatxFlags::BASIC_STATS | StatxFlags::MNT_ID,
                )
                .expect("the worker-private bind mount must expose statx identity");
                assert!(
                    StatxFlags::from_bits_retain(extended.stx_mask).contains(StatxFlags::MNT_ID),
                    "the kernel must attest the worker-private mount id"
                );
                let filesystem = rustix::fs::statfs(&mountpoint)
                    .expect("the worker-private bind mount must be statable");
                let expected =
                    if i128::from(filesystem.f_type) == i128::from(libc::EXT4_SUPER_MAGIC) {
                        b"ext4".as_slice()
                    } else if i128::from(filesystem.f_type) == i128::from(libc::BTRFS_SUPER_MAGIC) {
                        b"btrfs".as_slice()
                    } else {
                        panic!("the physical receipt requires ext4 or Btrfs");
                    };

                let leader_bytes = fs::read("/proc/self/mountinfo")
                    .expect("the leader mount table must remain readable");
                assert!(
                    parse_mountinfo_filesystem(&leader_bytes, extended.stx_mnt_id).is_err(),
                    "the leader table must not contain the worker-private bind mount"
                );
                let task_path = linux_task_mountinfo_route_for_test(
                    std::process::id(),
                    rustix::thread::gettid().as_raw_pid(),
                );
                let task_bytes = fs::read(Path::new("/proc").join(&task_path))
                    .expect("the worker task mount table must be readable");
                assert_eq!(
                    parse_mountinfo_filesystem(&task_bytes, extended.stx_mnt_id)
                        .expect("the worker task table must contain its private bind mount"),
                    expected
                );
                assert_eq!(
                    linux_mountinfo_filesystem_for_test(extended.stx_mnt_id)
                        .expect("production mountinfo lookup must use the worker task table"),
                    expected,
                    "the production route must attest the accessing thread's mount namespace"
                );
            });
            worker
                .join()
                .expect("the private-mount-namespace worker must complete without panic");
        }

        #[test]
        #[ignore = "physical nested-PID receipt requires root, util-linux unshare, and exact isolated execution"]
        fn physical_linux_foreign_procfs_pid_namespace_fails_before_mountinfo_open() {
            const CHILD_FLAG: &str = "FRANKENSEARCH_FOREIGN_PROCFS_PIDNS_CHILD";
            const ROOT_PATH: &str = "FRANKENSEARCH_FOREIGN_PROCFS_PIDNS_ROOT";
            const TEST_NAME: &str = "generation_root::tests::linux::physical_linux_foreign_procfs_pid_namespace_fails_before_mountinfo_open";

            assert!(
                rustix::process::geteuid().is_root(),
                "the foreign-procfs PID-namespace receipt requires root"
            );
            if std::env::var_os(CHILD_FLAG).is_none() {
                let root_path = fixture_root("foreign-procfs-pid-namespace");
                let executable =
                    std::env::current_exe().expect("the current test ELF path must be available");
                let output = Command::new("unshare")
                    .args(["--pid", "--fork"])
                    .arg(executable)
                    .args(["--exact", TEST_NAME, "--ignored", "--nocapture"])
                    .env(CHILD_FLAG, "1")
                    .env(ROOT_PATH, &root_path)
                    .output()
                    .expect("the physical receipt requires util-linux unshare");
                assert!(
                    output.status.success(),
                    "nested-PID child failed: status={:?}, stdout={}, stderr={}",
                    output.status.code(),
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
                return;
            }

            assert_eq!(
                std::process::id(),
                1,
                "the nested PID-namespace test process must be namespace PID 1"
            );
            assert_ne!(
                fs::read_link("/proc/self")
                    .expect("the inherited outer procfs self link must read"),
                PathBuf::from("1"),
                "the receipt must retain a procfs mounted for the outer PID namespace"
            );
            let root_path = PathBuf::from(
                std::env::var_os(ROOT_PATH)
                    .expect("the parent must pass the persistent root fixture"),
            );
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("foreign PID-namespace procfs must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::QualifyFilesystem);
            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(
                observed.contains(&TestBoundary::BeforeProcCapabilityRootOpen),
                "the verified proc-root qualification must be attempted"
            );
            assert!(
                !observed.contains(&TestBoundary::BeforeMountInfoOpen),
                "foreign procfs must fail binding before the mountinfo file is opened"
            );
            drop(observed);
        }

        #[test]
        #[ignore = "run the test ELF as root with FRANKENSEARCH_LINUX_PROC_OVERMOUNT_TEST_ROOT on native ext4/Btrfs"]
        fn physical_linux_proc_fd_overmount_is_rejected_before_data_open() {
            const CHILD_FLAG: &str = "FRANKENSEARCH_PROC_OVERMOUNT_CHILD";
            const TEST_NAME: &str = "generation_root::tests::linux::physical_linux_proc_fd_overmount_is_rejected_before_data_open";

            assert!(
                rustix::process::geteuid().is_root(),
                "physical procfs overmount receipt must run as root"
            );
            let base = std::env::var_os("FRANKENSEARCH_LINUX_PROC_OVERMOUNT_TEST_ROOT")
                .map(PathBuf::from)
                .expect(
                    "FRANKENSEARCH_LINUX_PROC_OVERMOUNT_TEST_ROOT must identify native ext4/Btrfs",
                );
            if std::env::var_os(CHILD_FLAG).is_none() {
                let executable =
                    std::env::current_exe().expect("the current test ELF path must be available");
                let output = Command::new("unshare")
                    .args(["--mount", "--fork", "--propagation", "private"])
                    .arg(executable)
                    .args(["--exact", TEST_NAME, "--ignored", "--nocapture"])
                    .env(CHILD_FLAG, "1")
                    .output()
                    .expect("the physical receipt requires util-linux unshare");
                assert!(
                    output.status.success(),
                    "mount-namespace child failed: status={:?}, stdout={}, stderr={}",
                    output.status.code(),
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
                return;
            }

            let filesystem =
                rustix::fs::statfs(&base).expect("physical procfs fixture base must be statable");
            assert!(
                i128::from(filesystem.f_type) == i128::from(libc::EXT4_SUPER_MAGIC)
                    || i128::from(filesystem.f_type) == i128::from(libc::BTRFS_SUPER_MAGIC),
                "physical procfs receipt requires ext4 or Btrfs"
            );
            let root_path = fixture_root_under(&base, "proc-fd-overmount");
            private_file(&root_path, "artifact", b"sealed");
            let fifo = root_path.join("proc-fd-overmount-fifo");
            rustix::fs::mkfifoat(
                rustix::fs::CWD,
                &fifo,
                rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
            )
            .expect("the hostile overmount fixture FIFO must be creatable");
            let decoy = private_dir(&root_path, "forged-proc-fd-decoy");
            for descriptor in 0_u32..=1024 {
                symlink(&fifo, decoy.join(descriptor.to_string()))
                    .expect("each likely descriptor route must have a forged FIFO symlink");
            }
            let before_error = OpenOptions::new()
                .write(true)
                .custom_flags(libc::O_NONBLOCK)
                .open(&fifo)
                .expect_err("the hostile FIFO must have no reader before the bridge attempt");
            assert_eq!(
                before_error.raw_os_error(),
                Some(libc::ENXIO),
                "the hostile FIFO fixture must prove its no-reader precondition"
            );
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let process_id = std::process::id();
            let thread_id = rustix::thread::gettid();
            let proc_fd = PathBuf::from(format!("/proc/{process_id}/task/{thread_id}/fd"));
            let mount = Command::new("mount")
                .args(["--bind"])
                .arg(&decoy)
                .arg(&proc_fd)
                .output()
                .expect("the physical receipt requires mount");
            assert!(
                mount.status.success(),
                "proc-fd bind overmount failed: status={:?}, stdout={}, stderr={}",
                mount.status.code(),
                String::from_utf8_lossy(&mount.stdout),
                String::from_utf8_lossy(&mount.stderr)
            );

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let error = root
                .admit_file(&confined("artifact"), immutable_expectation(b"sealed"))
                .expect_err("an overmounted proc-fd bridge must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(
                observed.contains(&TestBoundary::BeforeProcBridgeProbe {
                    index: 0,
                    phase: ProcBridgeProbePhase::BeforeDataOpen,
                }),
                "the exact proc-fd bridge preflight must be attempted"
            );
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::AfterProcBridgeProbe { .. }
                        | TestBoundary::AfterProcFdReopen { .. }
                        | TestBoundary::BeforeRead { .. }
                )),
                "the overmount must fail before the data descriptor or content path"
            );
            drop(observed);
            let after_error = OpenOptions::new()
                .write(true)
                .custom_flags(libc::O_NONBLOCK)
                .open(&fifo)
                .expect_err("the hostile FIFO must still have no reader after bridge rejection");
            assert_eq!(
                after_error.raw_os_error(),
                Some(libc::ENXIO),
                "bridge rejection must not establish a reader on any forged numeric fd route"
            );
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_LINUX_CHATTR_TEST_ROOT on native ext4/Btrfs, chattr, and CAP_LINUX_IMMUTABLE"]
        fn physical_statx_immutable_and_append_attributes_fail_before_data_open_or_lock() {
            use rustix::fs::{AtFlags, StatxAttributes, StatxFlags, statx};

            let base = std::env::var_os("FRANKENSEARCH_LINUX_CHATTR_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_LINUX_CHATTR_TEST_ROOT must identify native ext4 or Btrfs");
            assert!(
                base.is_absolute(),
                "the physical attribute fixture route must be absolute"
            );
            let filesystem =
                rustix::fs::statfs(&base).expect("physical attribute mount must be statable");
            assert!(
                i128::from(filesystem.f_type) == i128::from(libc::EXT4_SUPER_MAGIC)
                    || i128::from(filesystem.f_type) == i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on native ext4 or Btrfs"
            );

            let root_path = fixture_root_under(&base, "physical-statx-attributes");
            let immutable_contents = b"immutable physical attribute";
            let immutable_path = private_file(&root_path, "immutable", immutable_contents);
            let append_path = control_file(&root_path, "append-control", b"lock-v1!");
            let root = QualifiedGenerationRoot::admit(&root_path)
                .expect("the writable native root must qualify before object attributes are set");

            run_chattr_fixture_command("+i", &immutable_path);
            let mut immutable_reset = ChattrReset::new("-i", &immutable_path);
            run_chattr_fixture_command("+a", &append_path);
            let mut append_reset = ChattrReset::new("-a", &append_path);

            for (path, attribute) in [
                (&immutable_path, StatxAttributes::IMMUTABLE),
                (&append_path, StatxAttributes::APPEND),
            ] {
                let descriptor =
                    File::open(path).expect("attributed fixture must remain readable for proof");
                let observed = statx(
                    &descriptor,
                    "",
                    AtFlags::EMPTY_PATH | AtFlags::NO_AUTOMOUNT,
                    StatxFlags::BASIC_STATS,
                )
                .expect("physical attributed descriptor must support statx");
                assert!(
                    observed.stx_attributes_mask.contains(attribute),
                    "the kernel must report support for the tested physical attribute"
                );
                assert!(
                    observed.stx_attributes.contains(attribute),
                    "the physical attribute must be set before the rejection receipt"
                );
            }

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let immutable_error = root
                .admit_file(
                    &confined("immutable"),
                    immutable_expectation(immutable_contents),
                )
                .expect_err("a physically immutable artifact must fail writable qualification");
            assert_eq!(
                immutable_error.kind(),
                GenerationRootErrorKind::WriteRestrictedObject
            );
            assert_eq!(
                immutable_error.stage(),
                GenerationRootStage::OpenRegularFile
            );
            let append_error = root
                .admit_control_file(
                    &confined("append-control"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation must be accepted"),
                )
                .expect_err("a physically append-only control file must fail qualification");
            assert_eq!(
                append_error.kind(),
                GenerationRootErrorKind::WriteRestrictedObject
            );
            assert_eq!(append_error.stage(), GenerationRootStage::OpenRegularFile);
            let observed = boundaries.lock().expect("boundary log should lock");
            // Root revalidation legitimately opens the verified procfs root
            // to bind task-scoped mountinfo before inspecting the attributed
            // component. `BeforeProcFdReopen` is the distinct boundary that
            // would derive a data descriptor from the qualified `O_PATH`
            // probe.
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::BeforeProcFdReopen { .. }
                        | TestBoundary::BeforeRead { .. }
                        | TestBoundary::BeforeLock
                )),
                "physical immutable/append rejection must precede data-fd derivation, reads, and \
                 flock; observed={observed:?}"
            );
            drop(observed);
            drop(guard);

            immutable_reset.clear();
            append_reset.clear();
            root.admit_file(
                &confined("immutable"),
                immutable_expectation(immutable_contents),
            )
            .expect("the same artifact must qualify after the immutable attribute is cleared");
            root.admit_control_file(
                &confined("append-control"),
                GenerationFileExpectation::control(8)
                    .expect("small control expectation must be accepted"),
            )
            .expect("the same control must qualify after the append-only attribute is cleared")
            .try_lock(GenerationRootLockMode::Exclusive)
            .expect("the cleared control file must reach flock")
            .unlock()
            .expect("the cleared control lock must release");
        }

        #[test]
        fn stat_field_normalization_is_lossless_across_32_and_64_bit_abi_widths() {
            assert_eq!(stat_mode_as_u32(u16::MAX), u32::from(u16::MAX));
            assert_eq!(stat_mode_as_u32(u32::MAX), u32::MAX);
            assert_eq!(stat_inode_as_u64(u32::MAX), u64::from(u32::MAX));
            assert_eq!(stat_inode_as_u64(u64::MAX), u64::MAX);
            assert_eq!(stat_link_count_as_u64(u32::MAX), u64::from(u32::MAX));
            assert_eq!(stat_link_count_as_u64(u64::MAX), u64::MAX);
            assert_eq!(stat_seconds_as_i64(i32::MIN), i64::from(i32::MIN));
            assert_eq!(stat_seconds_as_i64(i32::MAX), i64::from(i32::MAX));
            assert_eq!(stat_seconds_as_i64(i64::MIN), i64::MIN);
            assert_eq!(stat_seconds_as_i64(i64::MAX), i64::MAX);
        }

        #[test]
        fn btrfs_namespace_identity_binds_mount_and_subvolume() {
            let raw_type: rustix::fs::FsWord = libc::BTRFS_SUPER_MAGIC;
            let top_level = linux_filesystem_namespace_digest(raw_type, 41, Some(5));
            let nested = linux_filesystem_namespace_digest(raw_type, 41, Some(256));
            let other_mount = linux_filesystem_namespace_digest(raw_type, 42, Some(5));

            assert_ne!(
                top_level, nested,
                "one VFS mount must not collapse distinct Btrfs subvolumes"
            );
            assert_ne!(
                top_level, other_mount,
                "the namespace identity must continue to bind the VFS mount"
            );
            assert_eq!(
                top_level,
                linux_filesystem_namespace_digest(raw_type, 41, Some(5)),
                "the namespace identity must be deterministic"
            );
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_LINUX_ABSOLUTE_MOUNT_TEST_ROOT plus mount, umount, and CAP_SYS_ADMIN"]
        fn physical_absolute_route_accepts_bind_transition_and_rejects_same_source_remount() {
            let base = std::env::var_os("FRANKENSEARCH_LINUX_ABSOLUTE_MOUNT_TEST_ROOT")
                .map(PathBuf::from)
                .expect(
                    "FRANKENSEARCH_LINUX_ABSOLUTE_MOUNT_TEST_ROOT must identify a secure native ext4/Btrfs ancestor",
                );
            assert!(
                base.is_absolute(),
                "the physical absolute-route receipt must use an absolute trusted ancestor"
            );

            let receipt_root = fixture_root_under(&base, "physical-absolute-bind-transition");
            let source = private_dir(&receipt_root, "source");
            let source_root = private_dir(&source, "qualified");
            let lock_bytes = b"lock-v1!";
            control_file(&source_root, "LOCK", lock_bytes);
            control_file(&source_root, "AUTHORITY", &authority_image(0x5a));
            let layout = GenerationRootAnchorLayout::new(
                u64::try_from(lock_bytes.len()).expect("the lock fixture length fits u64"),
            )
            .expect("the named lock fixture length is bounded");
            let target = private_dir(&receipt_root, "mountpoint");
            let bind_mount = BindMountFixture::new(&source, &target);
            let mounted_root = target.join("qualified");

            let direct = QualifiedGenerationRoot::admit(&source_root)
                .expect("the source root should independently qualify");
            let through_bind = QualifiedGenerationRoot::admit(&mounted_root)
                .expect("an absolute route may cross into a qualified adjacent bind mount");
            assert_eq!(
                direct.witness().inode(),
                through_bind.witness().inode(),
                "the bind route must resolve the same underlying final directory"
            );
            assert_ne!(
                direct.witness().mount_identity(),
                through_bind.witness().mount_identity(),
                "the route witness must distinguish the adjacent bind mount"
            );
            let named = NamedGenerationRoot::admit(&mounted_root, layout)
                .expect("fixed anchors should qualify through the adjacent bind mount");
            named
                .read_guard()
                .expect("the named LOCK should acquire through the qualified mount transition")
                .release()
                .expect("the unchanged mounted guard should release");
            drop(named);
            drop(through_bind);
            drop(direct);

            let swapped = Arc::new(Mutex::new(false));
            let hook_swapped = Arc::clone(&swapped);
            let mut hook_mount = bind_mount;
            let hook = install_test_hook(move |boundary| {
                if !*hook_swapped.lock().expect("mount-swap state should lock")
                    && boundary == TestBoundary::AfterFirstRootQualification
                {
                    hook_mount.remount_same_source();
                    *hook_swapped.lock().expect("mount-swap state should lock") = true;
                }
                Ok(())
            });
            let error = NamedGenerationRoot::admit(&mounted_root, layout)
                .expect_err("a new mount identity between the two absolute walks must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::RevalidateRootRoute);
            assert!(
                *swapped.lock().expect("mount-swap state should lock"),
                "the physical receipt must execute the remount boundary"
            );
            drop(hook);
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_LINUX_NETWORK_TEST_ROOT on a writable native NFS mount"]
        fn physical_linux_network_mount_fails_before_data_open_or_mutation() {
            let network_root = std::env::var_os("FRANKENSEARCH_LINUX_NETWORK_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_LINUX_NETWORK_TEST_ROOT must identify the native NFS mount");
            assert!(
                network_root.is_absolute(),
                "the physical network receipt must use an absolute provider route"
            );
            let filesystem = rustix::fs::statfs(&network_root)
                .expect("the physical network mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::NFS_SUPER_MAGIC),
                "the provider route must be a real NFS mount"
            );
            let mount = rustix::fs::statvfs(&network_root)
                .expect("the physical network mount flags must be readable");
            assert!(
                !mount.f_flag.contains(rustix::fs::StatVfsMountFlags::RDONLY),
                "the provider NFS mount must be writable so this receipt isolates filesystem-type rejection"
            );

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _hook = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("network boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&network_root)
                .expect_err("a network filesystem must fail qualification");
            assert_eq!(error.kind(), GenerationRootErrorKind::UnsupportedFilesystem);
            assert_eq!(error.stage(), GenerationRootStage::QualifyFilesystem);

            let observed = boundaries.lock().expect("network boundary log should lock");
            assert!(
                observed.contains(&TestBoundary::BeforeFilesystemQualification),
                "the receipt must reach the descriptor-bound filesystem classifier"
            );
            assert!(
                !observed.contains(&TestBoundary::AfterFilesystemQualification),
                "an NFS root must not cross the qualification boundary"
            );
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::BeforeRegularFileOpen { .. }
                        | TestBoundary::BeforeRead { .. }
                        | TestBoundary::BeforeLock
                        | TestBoundary::BeforeFileSync
                        | TestBoundary::BeforeDirectorySync
                )),
                "NFS rejection must precede every regular-file, content, lock, and durability boundary"
            );
            drop(observed);
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_BTRFS_TEST_ROOT on a writable native Btrfs mount"]
        fn physical_btrfs_retained_files_locks_and_durability_succeed() {
            let base = std::env::var_os("FRANKENSEARCH_BTRFS_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_BTRFS_TEST_ROOT must identify the native Btrfs mount");
            assert!(
                base.is_absolute(),
                "the physical Btrfs mount route must be absolute"
            );
            let filesystem =
                rustix::fs::statfs(&base).expect("physical Btrfs mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on a real Btrfs mount"
            );

            let root_path = fixture_root_under(&base, "physical-btrfs");
            let generation = private_dir(&root_path, "generation");
            let contents = b"physical Btrfs generation";
            private_file(&generation, "vector.fsvi", contents);
            control_file(&root_path, "LOCK", b"lock-v1!");

            let root = QualifiedGenerationRoot::admit(&root_path)
                .expect("writable Btrfs root must qualify");
            assert_eq!(
                root.witness().filesystem(),
                super::super::QualifiedFilesystem::LinuxBtrfs
            );
            let admitted = root
                .admit_file(
                    &confined("generation/vector.fsvi"),
                    immutable_expectation(contents),
                )
                .expect("exact immutable Btrfs file must qualify");
            assert_eq!(admitted.as_bytes(), contents);
            admitted
                .sync_durable()
                .expect("retained Btrfs regular-file fsync must succeed");

            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation must be accepted"),
                )
                .expect("Btrfs control file must qualify");
            let lock = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("Btrfs control-file flock must succeed");
            lock.sync_durable()
                .expect("locked Btrfs control-file fsync must succeed");
            lock.unlock()
                .expect("Btrfs control-file unlock must succeed");
            root.sync_directory_durable()
                .expect("retained Btrfs directory fsync must succeed");
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_BTRFS_TEST_ROOT, btrfs-progs, and CAP_SYS_ADMIN"]
        fn physical_btrfs_nested_subvolume_is_a_confined_namespace_boundary() {
            let base = std::env::var_os("FRANKENSEARCH_BTRFS_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_BTRFS_TEST_ROOT must identify the native Btrfs mount");
            let filesystem =
                rustix::fs::statfs(&base).expect("physical Btrfs mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on a real Btrfs mount"
            );

            let root_path = fixture_root_under(&base, "physical-btrfs-nested-subvolume");
            let nested_path = root_path.join("nested");
            run_btrfs_fixture_command(&[
                OsStr::new("subvolume"),
                OsStr::new("create"),
                nested_path.as_os_str(),
            ]);
            fs::set_permissions(&nested_path, fs::Permissions::from_mode(0o700))
                .expect("nested Btrfs subvolume mode must be private");
            let contents = b"nested subvolume must not cross the root namespace";
            private_file(&nested_path, "vector.fsvi", contents);

            let root = QualifiedGenerationRoot::admit(&root_path)
                .expect("the containing writable Btrfs root must qualify");
            assert_eq!(
                root.admit_file(
                    &confined("nested/vector.fsvi"),
                    immutable_expectation(contents),
                )
                .expect_err("a nested Btrfs subvolume must be a confinement boundary")
                .kind(),
                GenerationRootErrorKind::CrossDevice
            );
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_BTRFS_TEST_ROOT, btrfs-progs, and CAP_SYS_ADMIN"]
        fn physical_btrfs_snapshot_substitution_invalidates_the_retained_route() {
            let base = std::env::var_os("FRANKENSEARCH_BTRFS_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_BTRFS_TEST_ROOT must identify the native Btrfs mount");
            let filesystem =
                rustix::fs::statfs(&base).expect("physical Btrfs mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on a real Btrfs mount"
            );

            let parent_path = fixture_root_under(&base, "physical-btrfs-snapshot-substitution");
            let live_path = parent_path.join("live");
            run_btrfs_fixture_command(&[
                OsStr::new("subvolume"),
                OsStr::new("create"),
                live_path.as_os_str(),
            ]);
            fs::set_permissions(&live_path, fs::Permissions::from_mode(0o700))
                .expect("live Btrfs subvolume mode must be private");
            private_file(&live_path, "manifest", b"sealed generation");

            let retained = QualifiedGenerationRoot::admit(&live_path)
                .expect("the original Btrfs subvolume must qualify");
            let retained_path = parent_path.join("retained");
            fs::rename(&live_path, &retained_path)
                .expect("the original subvolume must move to an unused persistent route");
            run_btrfs_fixture_command(&[
                OsStr::new("subvolume"),
                OsStr::new("snapshot"),
                retained_path.as_os_str(),
                live_path.as_os_str(),
            ]);

            let replacement = QualifiedGenerationRoot::admit(&live_path)
                .expect("the replacement snapshot is independently well-formed");
            assert_ne!(
                retained.witness().mount_identity(),
                replacement.witness().mount_identity(),
                "snapshot and source must have distinct namespace identities"
            );
            assert_eq!(
                retained
                    .revalidate_route()
                    .expect_err("snapshot substitution must invalidate the retained route")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_BTRFS_TEST_ROOT, btrfs-progs, and CAP_SYS_ADMIN"]
        fn physical_read_only_btrfs_subvolume_fails_on_a_writable_mount() {
            use rustix::fs::StatVfsMountFlags;

            let base = std::env::var_os("FRANKENSEARCH_BTRFS_TEST_ROOT")
                .map(PathBuf::from)
                .expect("FRANKENSEARCH_BTRFS_TEST_ROOT must identify the native Btrfs mount");
            let filesystem =
                rustix::fs::statfs(&base).expect("physical Btrfs mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on a real Btrfs mount"
            );

            let parent_path = fixture_root_under(&base, "physical-btrfs-read-only-subvolume");
            let readonly_path = parent_path.join("readonly");
            run_btrfs_fixture_command(&[
                OsStr::new("subvolume"),
                OsStr::new("create"),
                readonly_path.as_os_str(),
            ]);
            fs::set_permissions(&readonly_path, fs::Permissions::from_mode(0o700))
                .expect("read-only fixture mode must be private before sealing");
            run_btrfs_fixture_command(&[
                OsStr::new("property"),
                OsStr::new("set"),
                OsStr::new("-t"),
                OsStr::new("subvol"),
                readonly_path.as_os_str(),
                OsStr::new("ro"),
                OsStr::new("true"),
            ]);
            let readonly_descriptor =
                File::open(&readonly_path).expect("read-only fixture must be openable");
            let write_error = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(readonly_path.join("writability-probe"))
                .expect_err("the receipt requires a genuinely read-only Btrfs subvolume");
            assert_eq!(
                write_error.raw_os_error(),
                Some(libc::EROFS),
                "the read-only proof must be the kernel EROFS result"
            );
            let mount = rustix::fs::fstatvfs(&readonly_descriptor)
                .expect("Btrfs mount flags must be readable");
            assert!(
                !mount.f_flag.contains(StatVfsMountFlags::RDONLY),
                "the enclosing VFS mount must remain writable so this proves subvolume handling"
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(&readonly_path)
                    .expect_err("read-only Btrfs subvolume must fail admission")
                    .kind(),
                GenerationRootErrorKind::ReadOnlyFilesystem
            );
        }

        #[test]
        #[ignore = "requires FRANKENSEARCH_BTRFS_READ_ONLY_TEST_ROOT on a native read-only Btrfs mount"]
        fn physical_read_only_btrfs_fails_before_security_admission() {
            use rustix::fs::StatVfsMountFlags;

            let base = std::env::var_os("FRANKENSEARCH_BTRFS_READ_ONLY_TEST_ROOT")
                .map(PathBuf::from)
                .expect(
                    "FRANKENSEARCH_BTRFS_READ_ONLY_TEST_ROOT must identify the native Btrfs mount",
                );
            assert!(
                base.is_absolute(),
                "the physical read-only Btrfs mount route must be absolute"
            );
            let filesystem =
                rustix::fs::statfs(&base).expect("physical read-only Btrfs mount must be statable");
            assert_eq!(
                i128::from(filesystem.f_type),
                i128::from(libc::BTRFS_SUPER_MAGIC),
                "the receipt must execute on a real Btrfs mount"
            );
            let descriptor =
                File::open(&base).expect("physical read-only Btrfs root must be openable");
            let mount = rustix::fs::fstatvfs(&descriptor)
                .expect("physical read-only Btrfs mount flags must be readable");
            assert!(
                mount.f_flag.contains(StatVfsMountFlags::RDONLY),
                "the receipt requires a genuinely read-only mount"
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(&base)
                    .expect_err("read-only Btrfs must fail before owner or mode admission")
                    .kind(),
                GenerationRootErrorKind::ReadOnlyFilesystem
            );
        }

        #[test]
        fn mountinfo_parser_requires_one_exact_well_formed_mount_record() {
            let fixture = b"41 1 8:1 / /other rw,relatime - xfs /dev/other rw\n\
                            42 1 8:2 / /target rw,relatime shared:7 - ext4 /dev/root rw\n";
            assert_eq!(
                parse_mountinfo_filesystem(fixture, 42)
                    .expect("one exact mount-id record should qualify"),
                b"ext4"
            );

            for malformed in [
                b"42 1 8:2 / /target rw,relatime ext4 /dev/root rw\n".as_slice(),
                b"42 1 8:2 / /target rw,relatime -  /dev/root rw\n".as_slice(),
                b"42 1 8:2 / /target rw,relatime - ext4  rw\n".as_slice(),
                b"42 1 8:2 / /target rw,relatime - ext4 /dev/root \n".as_slice(),
            ] {
                assert_eq!(
                    parse_mountinfo_filesystem(malformed, 42)
                        .expect_err("malformed matching mountinfo record must fail")
                        .kind(),
                    GenerationRootErrorKind::UnsupportedFilesystem
                );
            }

            let duplicate = b"42 1 8:2 / /a rw - ext4 /dev/a rw\n\
                              42 1 8:2 / /b rw - ext4 /dev/b rw\n";
            assert_eq!(
                parse_mountinfo_filesystem(duplicate, 42)
                    .expect_err("duplicate mount-id records must fail")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
            assert_eq!(
                parse_mountinfo_filesystem(
                    b"18446744073709551616 1 8:2 / /target rw - ext4 /dev/root rw\n",
                    u64::MAX,
                )
                .expect_err("overflowing mount ids must never alias a valid u64")
                .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
            assert_eq!(
                parse_mountinfo_filesystem(fixture, 99)
                    .expect_err("missing mount-id record must fail")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
        }

        #[test]
        fn directory_and_mountinfo_resource_boundaries_report_exact_numeric_counts() {
            validate_directory_scan_counts_for_test(
                GENERATION_ROOT_MAX_DIRECTORY_ENTRIES,
                GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES,
            )
            .expect("both exact directory-scan ceilings should be accepted");

            let entry_overflow = validate_directory_scan_counts_for_test(
                GENERATION_ROOT_MAX_DIRECTORY_ENTRIES.saturating_add(1),
                0,
            )
            .expect_err("one overflow entry must fail");
            assert_eq!(
                entry_overflow.kind(),
                GenerationRootErrorKind::ResourceLimit
            );
            assert_eq!(
                entry_overflow.expected(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_DIRECTORY_ENTRIES)
                        .expect("entry ceiling fits u64")
                )
            );
            assert_eq!(
                entry_overflow.observed(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_DIRECTORY_ENTRIES.saturating_add(1))
                        .expect("entry sentinel fits u64")
                )
            );

            let name_overflow = validate_directory_scan_counts_for_test(
                1,
                GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES.saturating_add(1),
            )
            .expect_err("one overflow name byte must fail");
            assert_eq!(name_overflow.kind(), GenerationRootErrorKind::ResourceLimit);
            assert_eq!(
                name_overflow.expected(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES)
                        .expect("name-byte ceiling fits u64")
                )
            );
            assert_eq!(
                name_overflow.observed(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_DIRECTORY_NAME_BYTES.saturating_add(1))
                        .expect("name-byte sentinel fits u64")
                )
            );

            let (last_request, accepted) =
                validate_mountinfo_bound_for_test(GENERATION_ROOT_MAX_MOUNTINFO_BYTES - 1, 1);
            assert_eq!(last_request, 2, "one accepted byte plus one sentinel");
            accepted.expect("the exact mountinfo storage ceiling should be accepted");
            let (sentinel_request, overflow) =
                validate_mountinfo_bound_for_test(GENERATION_ROOT_MAX_MOUNTINFO_BYTES, 1);
            assert_eq!(sentinel_request, 1, "only an overflow sentinel may be read");
            let overflow = overflow.expect_err("the mountinfo sentinel byte must fail");
            assert_eq!(overflow.kind(), GenerationRootErrorKind::ResourceLimit);
            assert_eq!(
                overflow.expected(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_MOUNTINFO_BYTES)
                        .expect("mountinfo ceiling fits u64")
                )
            );
            assert_eq!(
                overflow.observed(),
                Some(
                    u64::try_from(GENERATION_ROOT_MAX_MOUNTINFO_BYTES.saturating_add(1))
                        .expect("mountinfo sentinel fits u64")
                )
            );
        }

        #[test]
        fn every_linux_open_read_lock_and_sync_boundary_is_fault_injectable() {
            for target in [
                TestBoundary::BeforeRootComponentOpen { index: 0 },
                TestBoundary::AfterRootComponentOpen { index: 0 },
                TestBoundary::BeforeExactNameEnumeration,
                TestBoundary::AfterExactNameEnumeration,
                TestBoundary::BeforeRouteMountIdentity,
                TestBoundary::AfterRouteMountIdentity,
                TestBoundary::BeforeFilesystemQualification,
                TestBoundary::AfterFilesystemQualification,
                TestBoundary::BeforeObjectWitness,
                TestBoundary::AfterObjectWitness,
                TestBoundary::BeforeProcCapabilityRootOpen,
                TestBoundary::AfterProcCapabilityRootOpen,
                TestBoundary::BeforeProcSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::AfterProcSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::BeforeProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::AfterProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::BeforeMountInfoOpen,
                TestBoundary::AfterMountInfoOpen,
                TestBoundary::BeforeMountInfoRead,
                TestBoundary::BeforeProcSelfReadlink {
                    phase: ProcSelfBindingPhase::MountInfoRead,
                },
                TestBoundary::AfterProcSelfReadlink {
                    phase: ProcSelfBindingPhase::MountInfoRead,
                },
                TestBoundary::BeforeProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::MountInfoRead,
                },
                TestBoundary::AfterProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::MountInfoRead,
                },
                TestBoundary::AfterFirstRootQualification,
                TestBoundary::BeforeAclRead,
                TestBoundary::AfterAclRead,
            ] {
                let root_path = fixture_root("root-boundary");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::OpenRootRoute));
                    }
                    Ok(())
                });
                let error = QualifiedGenerationRoot::admit(&root_path)
                    .expect_err("injected root-open boundary must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::Io);
            }

            let contents = b"boundary";
            for target in [
                TestBoundary::BeforeRootDescriptorDuplicate,
                TestBoundary::AfterRootDescriptorDuplicate,
                TestBoundary::BeforeRelativeDirectoryOpen { index: 0 },
                TestBoundary::AfterRelativeDirectoryOpen { index: 0 },
                TestBoundary::BeforeRegularFileOpen { index: 1 },
                TestBoundary::BeforeFinalProbeOpen { index: 1 },
                TestBoundary::AfterFinalProbeOpen { index: 1 },
                TestBoundary::AfterProbeQualified { index: 1 },
                TestBoundary::BeforeProcCapabilityRootOpen,
                TestBoundary::AfterProcCapabilityRootOpen,
                TestBoundary::BeforeProcSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::AfterProcSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::BeforeProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::AfterProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::RootQualification,
                },
                TestBoundary::BeforeProcBridgeProbe {
                    index: 1,
                    phase: ProcBridgeProbePhase::BeforeDataOpen,
                },
                TestBoundary::AfterProcBridgeProbe {
                    index: 1,
                    phase: ProcBridgeProbePhase::BeforeDataOpen,
                },
                TestBoundary::BeforeProcSelfReadlink {
                    phase: ProcSelfBindingPhase::BeforeDataOpen,
                },
                TestBoundary::AfterProcSelfReadlink {
                    phase: ProcSelfBindingPhase::BeforeDataOpen,
                },
                TestBoundary::BeforeProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::BeforeDataOpen,
                },
                TestBoundary::AfterProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::BeforeDataOpen,
                },
                TestBoundary::BeforeProcFdReopen { index: 1 },
                TestBoundary::BeforeProcSelfReadlink {
                    phase: ProcSelfBindingPhase::AfterDataOpen,
                },
                TestBoundary::AfterProcSelfReadlink {
                    phase: ProcSelfBindingPhase::AfterDataOpen,
                },
                TestBoundary::BeforeProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::AfterDataOpen,
                },
                TestBoundary::AfterProcThreadSelfReadlink {
                    phase: ProcSelfBindingPhase::AfterDataOpen,
                },
                TestBoundary::BeforeProcBridgeProbe {
                    index: 1,
                    phase: ProcBridgeProbePhase::AfterDataOpen,
                },
                TestBoundary::AfterProcBridgeProbe {
                    index: 1,
                    phase: ProcBridgeProbePhase::AfterDataOpen,
                },
                TestBoundary::AfterProcFdReopen { index: 1 },
                TestBoundary::BeforeFinalRouteProbe { index: 1 },
                TestBoundary::AfterFinalRouteProbe { index: 1 },
                TestBoundary::AfterRegularFileOpen {
                    index: 1,
                    cloexec: true,
                },
                TestBoundary::AfterQualifiedFileOpen,
                TestBoundary::BeforeAclRead,
                TestBoundary::AfterAclRead,
                TestBoundary::BeforeRead { offset: 0 },
                TestBoundary::AfterRead {
                    offset: 0,
                    byte_count: contents.len(),
                },
                TestBoundary::BeforeTrailingByteProbe,
                TestBoundary::AfterTrailingByteProbe { byte_count: 0 },
                TestBoundary::AfterExactRead,
                TestBoundary::BeforeFileRouteReopen,
                TestBoundary::AfterFileRouteReopen,
                TestBoundary::BeforeFinalRootRevalidation,
            ] {
                let root_path = fixture_root("file-boundary");
                let generation = private_dir(&root_path, "generation");
                private_file(&generation, "artifact", contents);
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("private root should qualify before injection");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::ReadRegularFile));
                    }
                    Ok(())
                });
                let error = root
                    .admit_file(
                        &confined("generation/artifact"),
                        immutable_expectation(contents),
                    )
                    .expect_err("injected file boundary must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::Io);
            }

            {
                let root_path = fixture_root("mountinfo-read-complete-boundary");
                let _guard = install_test_hook(|boundary| {
                    if matches!(boundary, TestBoundary::AfterMountInfoRead { .. }) {
                        return Err(injected(GenerationRootStage::QualifyFilesystem));
                    }
                    Ok(())
                });
                assert_eq!(
                    QualifiedGenerationRoot::admit(&root_path)
                        .expect_err("completed mountinfo read boundary must be injectable")
                        .kind(),
                    GenerationRootErrorKind::Io
                );
            }

            for target in [TestBoundary::BeforeLock, TestBoundary::AfterLock] {
                let root_path = fixture_root("lock-boundary");
                control_file(&root_path, "LOCK", b"lock-v1!");
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("private root should qualify before injection");
                let control = root
                    .admit_control_file(
                        &confined("LOCK"),
                        GenerationFileExpectation::control(8)
                            .expect("small expectation should be accepted"),
                    )
                    .expect("control file should qualify before lock injection");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::AcquireLock));
                    }
                    Ok(())
                });
                let error = control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("injected lock boundary must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::Io);
            }

            for target in [TestBoundary::BeforeUnlock, TestBoundary::AfterUnlock] {
                let root_path = fixture_root("unlock-boundary");
                control_file(&root_path, "LOCK", b"lock-v1!");
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("private root should qualify before injection");
                let control = root
                    .admit_control_file(
                        &confined("LOCK"),
                        GenerationFileExpectation::control(8)
                            .expect("small expectation should be accepted"),
                    )
                    .expect("control file should qualify before unlock injection");
                let lock = control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect("exclusive lock should succeed before unlock injection");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::ReleaseLock));
                    }
                    Ok(())
                });
                assert_eq!(
                    lock.unlock()
                        .expect_err("injected unlock boundary must fail")
                        .kind(),
                    GenerationRootErrorKind::Io
                );
            }

            for target in [TestBoundary::BeforeFileSync, TestBoundary::AfterFileSync] {
                let root_path = fixture_root("file-sync-boundary");
                private_file(&root_path, "artifact", contents);
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("private root should qualify before injection");
                let file = root
                    .admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect("file should qualify before sync injection");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::SyncRegularFile));
                    }
                    Ok(())
                });
                assert_eq!(
                    file.sync_durable()
                        .expect_err("injected file-sync boundary must fail")
                        .kind(),
                    GenerationRootErrorKind::Io
                );
            }

            for target in [
                TestBoundary::BeforeDirectorySync,
                TestBoundary::AfterDirectorySync,
            ] {
                let root_path = fixture_root("directory-sync-boundary");
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("private root should qualify before injection");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::SyncDirectory));
                    }
                    Ok(())
                });
                assert_eq!(
                    root.sync_directory_durable()
                        .expect_err("injected directory-sync boundary must fail")
                        .kind(),
                    GenerationRootErrorKind::Io
                );
            }
        }

        #[test]
        fn exact_path_reopen_detects_same_size_inode_substitution() {
            let root_path = fixture_root("inode-substitution");
            let original = private_file(&root_path, "artifact", b"original");
            let replacement_source = private_file(&root_path, "replacement", b"attacker");
            let retained = root_path.join("retained-original");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let observed = Arc::new(Mutex::new(false));
            let hook_observed = Arc::clone(&observed);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeFileRouteReopen {
                    fs::rename(&original, &retained)
                        .expect("original should move to a fresh retained path");
                    fs::rename(&replacement_source, &original)
                        .expect("replacement should move into the original path");
                    *hook_observed.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(b"original"))
                    .expect_err("same-size inode substitution must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            assert!(*observed.lock().expect("hook state should lock"));
        }

        #[test]
        fn root_open_fault_does_not_modify_decoy_tree() {
            let root_path = fixture_root("root-fault-decoy");
            let decoy_path = private_file(&root_path, "decoy", b"unchanged");
            let _guard = install_test_hook(|boundary| {
                if boundary == (TestBoundary::BeforeRootComponentOpen { index: 0 }) {
                    return Err(injected(GenerationRootStage::OpenRootRoute));
                }
                Ok(())
            });
            assert!(QualifiedGenerationRoot::admit(&root_path).is_err());
            assert_eq!(
                fs::read(decoy_path).expect("decoy should remain readable"),
                b"unchanged"
            );
        }

        #[test]
        fn existing_file_descriptor_is_never_replaced_by_ambient_path_changes() {
            let root_path = fixture_root("retained-descriptor");
            let contents = b"descriptor-owned";
            let artifact = private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(contents))
                .expect("file should qualify");
            let moved = root_path.join("artifact-moved");
            fs::rename(&artifact, &moved).expect("artifact should move to a fresh path");
            private_file(&root_path, "artifact", b"ambient-changed!");
            assert_eq!(admitted.as_bytes(), contents);
            assert_eq!(admitted.sha256(), digest(contents));
            assert_eq!(
                admitted
                    .sync_durable()
                    .expect_err("same-size route substitution must fence retained-file sync")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn regular_file_open_rejects_missing_path_without_path_disclosure() {
            let root_path = fixture_root("missing");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let error = root
                .admit_file(
                    &confined("sensitive-missing-name"),
                    GenerationFileExpectation::immutable(0, digest(b""))
                        .expect("zero-length expectation should be accepted"),
                )
                .expect_err("missing file must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert!(!error.to_string().contains("sensitive-missing-name"));
            assert!(!format!("{error:?}").contains("sensitive-missing-name"));
        }

        #[test]
        fn retained_descriptor_sync_detects_post_admission_content_change() {
            let root_path = fixture_root("sync-drift");
            let artifact = private_file(&root_path, "artifact", b"before!!");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o600))
                .expect("fixture should become writable for the retained test fd");
            let mut mutation_file = OpenOptions::new()
                .write(true)
                .open(&artifact)
                .expect("retained mutation fd should open");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o400))
                .expect("fixture should be resealed before admission");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(b"before!!"))
                .expect("file should qualify");
            mutation_file
                .write_all(b"after!!!")
                .expect("same-size mutation should succeed");
            mutation_file
                .sync_all()
                .expect("mutation should be durable");
            assert_eq!(
                admitted
                    .sync_durable()
                    .expect_err("post-admission mutation must fence durability")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn linux_atime_only_drift_is_excluded_without_restoring_metadata() {
            let root_path = fixture_root("atime-drift");
            let artifact = private_file(&root_path, "artifact", b"atime");
            let timestamp_owner = File::open(&artifact).expect("fixture should open for timestamp");
            let modified = timestamp_owner
                .metadata()
                .and_then(|metadata| metadata.modified())
                .expect("fixture mtime should be readable");
            timestamp_owner
                .set_times(
                    std::fs::FileTimes::new()
                        .set_accessed(UNIX_EPOCH)
                        .set_modified(modified),
                )
                .expect("fixture atime should become observably old before admission");

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(b"atime"))
                .expect("file should qualify while O_NOATIME preserves the old atime");
            let before = fs::metadata(&artifact)
                .expect("fixture metadata should load")
                .accessed()
                .expect("fixture atime should be readable");
            let mut ambient_reader = File::open(&artifact).expect("ambient reader should open");
            let mut byte = [0_u8; 1];
            ambient_reader
                .read_exact(&mut byte)
                .expect("ambient read should advance atime");
            let after = fs::metadata(&artifact)
                .expect("fixture metadata should reload")
                .accessed()
                .expect("advanced atime should be readable");
            assert!(
                after > before,
                "fixture must prove an atime-only advancement"
            );
            admitted
                .sync_durable()
                .expect("Linux atime-only drift is not a content mutation");
            assert_eq!(
                fs::metadata(&artifact)
                    .expect("fixture metadata should remain readable")
                    .accessed()
                    .expect("fixture atime should remain readable"),
                after,
                "validation must never restore attacker-observed atime"
            );
        }

        #[test]
        fn open_control_file_requires_write_access_and_private_regular_identity() {
            let root_path = fixture_root("lock-mode");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            fs::set_permissions(&lock_path, fs::Permissions::from_mode(0o400))
                .expect("fixture lock mode should change");
            let error = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect_err("non-private writable control file must fail");
            assert!(
                matches!(
                    error.kind(),
                    GenerationRootErrorKind::WrongMode | GenerationRootErrorKind::Io
                ),
                "write denial must fail before lock ownership"
            );
        }

        #[test]
        fn sealed_file_role_mismatch_precedes_disk_access() {
            let root_path = fixture_root("role-mismatch");
            private_file(&root_path, "artifact", b"01234567");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            assert_eq!(
                root.admit_file(
                    &confined("artifact"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect_err("control role must not enter immutable admission")
                .kind(),
                GenerationRootErrorKind::WrongRole
            );
            assert_eq!(
                root.admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::immutable(8, digest(b"lock-v1!"))
                        .expect("small expectation should be accepted"),
                )
                .expect_err("immutable role must not enter control admission")
                .kind(),
                GenerationRootErrorKind::WrongRole
            );
        }

        #[test]
        fn file_sync_failure_never_falls_back_to_a_weaker_barrier() {
            let root_path = fixture_root("no-sync-fallback");
            private_file(&root_path, "artifact", b"barrier");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(b"barrier"))
                .expect("file should qualify");
            let calls = Arc::new(Mutex::new(Vec::new()));
            let hook_calls = Arc::clone(&calls);
            let _guard = install_test_hook(move |boundary| {
                if matches!(
                    boundary,
                    TestBoundary::BeforeFileSync | TestBoundary::AfterFileSync
                ) {
                    hook_calls
                        .lock()
                        .expect("hook calls should lock")
                        .push(boundary);
                }
                if boundary == TestBoundary::BeforeFileSync {
                    return Err(GenerationRootError::new(
                        GenerationRootErrorKind::DurabilityUnavailable,
                        GenerationRootStage::SyncRegularFile,
                    ));
                }
                Ok(())
            });
            assert_eq!(
                admitted
                    .sync_durable()
                    .expect_err("required barrier failure must propagate")
                    .kind(),
                GenerationRootErrorKind::DurabilityUnavailable
            );
            assert_eq!(
                calls.lock().expect("hook calls should lock").as_slice(),
                &[TestBoundary::BeforeFileSync]
            );
        }

        #[test]
        fn fixture_files_use_single_link_private_modes() {
            let root_path = fixture_root("fixture-self-check");
            let file_path = private_file(&root_path, "artifact", b"x");
            let root_metadata = fs::metadata(&root_path).expect("root metadata should load");
            let file_metadata = fs::metadata(file_path).expect("file metadata should load");
            assert_eq!(root_metadata.permissions().mode() & 0o7777, 0o700);
            assert_eq!(file_metadata.permissions().mode() & 0o7777, 0o400);
        }

        #[test]
        fn root_admission_rejects_non_directory_final_component() {
            let container = fixture_root("root-not-directory");
            let file_path = private_file(&container, "not-a-root", b"x");
            let error = QualifiedGenerationRoot::admit(&file_path)
                .expect_err("regular file cannot be a generation root");
            assert!(
                matches!(
                    error.kind(),
                    GenerationRootErrorKind::NotDirectory | GenerationRootErrorKind::Io
                ),
                "non-directory final route must fail closed"
            );
        }

        #[test]
        fn root_revalidation_detects_security_identity_drift() {
            let root_path = fixture_root("root-security-drift");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            fs::set_permissions(&root_path, fs::Permissions::from_mode(0o750))
                .expect("fixture mode should change");
            assert_eq!(
                root.revalidate_route()
                    .expect_err("root mode drift must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn caller_control_hash_is_checked_only_after_lock_acquisition() {
            let root_path = fixture_root("lock-hash-order");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            let first = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("first exclusive lock should succeed");
            let wrong_hash = GenerationFileExpectation::control_with_sha256(8, [0x11; 32])
                .expect("small expectation should be accepted");
            let wrong_control = root
                .admit_control_file(&confined("LOCK"), wrong_hash)
                .expect("digest-qualified control file should qualify structurally");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            assert_eq!(
                wrong_control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("content must not be inspected through a contended lock")
                    .kind(),
                GenerationRootErrorKind::LockContended
            );
            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(observed.contains(&TestBoundary::BeforeLock));
            assert!(
                !observed
                    .iter()
                    .any(|boundary| matches!(boundary, TestBoundary::BeforeRead { .. })),
                "a contended lock must return before post-admission content or caller-digest reads"
            );
            drop(observed);
            drop(guard);
            first.unlock().expect("exclusive unlock should succeed");
            assert_eq!(
                wrong_control
                    .try_lock(GenerationRootLockMode::Exclusive)
                    .expect_err("wrong hash must fail after lock acquisition")
                    .kind(),
                GenerationRootErrorKind::HashMismatch
            );
        }

        #[test]
        fn explicit_file_creation_does_not_replace_existing_data() {
            let root_path = fixture_root("create-new");
            let path = private_file(&root_path, "artifact", b"first");
            let result = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path);
            assert!(
                result.is_err(),
                "fixture and production doctrine require create-new semantics"
            );
            assert_eq!(
                fs::read(path).expect("original bytes should remain readable"),
                b"first"
            );
        }

        #[test]
        fn retained_root_directory_sync_revalidates_before_and_after_barrier() {
            let root_path = fixture_root("root-sync-fence");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let moved = root_path.with_extension("moved-before-sync");
            fs::rename(&root_path, &moved).expect("root should move to a fresh path");
            DirBuilder::new()
                .mode(0o700)
                .create(&root_path)
                .expect("replacement root should be creatable");
            fs::set_permissions(&root_path, fs::Permissions::from_mode(0o700))
                .expect("replacement root mode should be settable");
            let error = root
                .sync_directory_durable()
                .expect_err("root route replacement must fail before sync");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::RevalidateRootRoute);
        }

        #[test]
        fn root_component_replacement_during_walk_is_fault_detectable() {
            let root_path = fixture_root("ancestor-walk-race");
            let components = root_path
                .components()
                .filter(|component| !matches!(component, std::path::Component::RootDir))
                .count();
            assert!(components > 0);
            let observed = Arc::new(Mutex::new(false));
            let hook_observed = Arc::clone(&observed);
            let last_index = components.saturating_sub(1);
            let _guard = install_test_hook(move |boundary| {
                if boundary == (TestBoundary::AfterRootComponentOpen { index: last_index }) {
                    *hook_observed.lock().expect("hook state should lock") = true;
                    return Err(injected(GenerationRootStage::OpenRootRoute));
                }
                Ok(())
            });
            assert!(QualifiedGenerationRoot::admit(&root_path).is_err());
            assert!(*observed.lock().expect("hook state should lock"));
        }

        #[test]
        fn read_fault_is_bounded_and_does_not_return_partial_bytes() {
            let root_path = fixture_root("read-fault");
            let contents = b"no partial publication";
            private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let _guard = install_test_hook(|boundary| {
                if boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    return Err(injected(GenerationRootStage::ReadRegularFile));
                }
                Ok(())
            });
            let error = root
                .admit_file(&confined("artifact"), immutable_expectation(contents))
                .expect_err("injected read failure must return no owner");
            assert_eq!(error.kind(), GenerationRootErrorKind::Io);
            assert_eq!(error.stage(), GenerationRootStage::ReadRegularFile);
        }

        #[test]
        fn file_length_probe_rejects_growth_beyond_expected_end() {
            let root_path = fixture_root("end-probe");
            let artifact = private_file(&root_path, "artifact", b"12345678");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o600))
                .expect("fixture should become writable for the retained test fd");
            let mut mutation_file = OpenOptions::new()
                .write(true)
                .open(&artifact)
                .expect("retained mutation fd should open");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o400))
                .expect("fixture should be resealed before admission");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let mutated = Arc::new(Mutex::new(false));
            let hook_mutated = Arc::clone(&mutated);
            let _guard = install_test_hook(move |boundary| {
                if boundary
                    == (TestBoundary::AfterRead {
                        offset: 0,
                        byte_count: 8,
                    })
                    && !*hook_mutated.lock().expect("hook state should lock")
                {
                    mutation_file
                        .seek(SeekFrom::End(0))
                        .expect("fixture should be seekable");
                    mutation_file.write_all(b"9").expect("fixture should grow");
                    mutation_file.sync_all().expect("growth should be durable");
                    *hook_mutated.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(b"12345678"),)
                    .expect_err("one-byte end growth must fail")
                    .kind(),
                GenerationRootErrorKind::SizeMismatch
            );
        }

        #[test]
        fn wrong_owner_witness_is_rejected_without_requiring_privileged_chown() {
            let root_path = fixture_root("owner-contract");
            let root = QualifiedGenerationRoot::admit(&root_path)
                .expect("current-user root should qualify");
            let mut wrong_owner = root.witness();
            wrong_owner.uid = rustix::process::geteuid().as_raw().wrapping_add(1);
            assert_eq!(
                validate_owner_mode_for_test(
                    wrong_owner,
                    super::super::GENERATION_ROOT_DIRECTORY_MODE,
                )
                .expect_err("a non-effective owner witness must fail")
                .kind(),
                GenerationRootErrorKind::WrongOwner
            );
        }

        #[test]
        fn opened_file_descriptor_witness_is_stable_across_arc_clones() {
            let root_path = fixture_root("arc-owner");
            let contents = b"one allocation";
            private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(contents))
                .expect("file should qualify");
            let first = admitted.bytes();
            let second = admitted.bytes();
            assert!(Arc::ptr_eq(&first, &second));
            assert_eq!(first.as_ref(), contents);
        }

        #[test]
        fn file_mode_change_after_admission_fences_sync() {
            let root_path = fixture_root("file-mode-drift");
            let artifact = private_file(&root_path, "artifact", b"mode");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("artifact"), immutable_expectation(b"mode"))
                .expect("file should qualify");
            fs::set_permissions(&artifact, fs::Permissions::from_mode(0o640))
                .expect("fixture mode should change");
            assert_eq!(
                admitted
                    .sync_durable()
                    .expect_err("file mode drift must fence sync")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn open_file_missing_write_permission_never_acquires_lock() {
            let root_path = fixture_root("lock-permission");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            fs::set_permissions(&lock_path, fs::Permissions::from_mode(0o400))
                .expect("fixture lock mode should change");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let observed = Arc::new(Mutex::new(false));
            let hook_observed = Arc::clone(&observed);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_observed.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert!(
                root.admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .is_err()
            );
            assert!(
                !*observed.lock().expect("hook state should lock"),
                "mode validation must precede the flock syscall"
            );
        }

        #[test]
        fn root_filesystem_profile_exposes_only_qualified_local_type() {
            let root_path = fixture_root("filesystem-profile");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("ext4 root should qualify");
            assert_eq!(
                root.witness().filesystem(),
                super::super::QualifiedFilesystem::LinuxExt4
            );
            assert_ne!(root.witness().mount_identity(), [0; 32]);
        }

        #[test]
        fn explicit_private_file_is_not_mutated_by_failed_hash_admission() {
            let root_path = fixture_root("hash-decoy");
            let artifact = private_file(&root_path, "artifact", b"unchanged");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let expectation = GenerationFileExpectation::immutable(9, [0xff; 32])
                .expect("small expectation should be accepted");
            assert_eq!(
                root.admit_file(&confined("artifact"), expectation)
                    .expect_err("wrong digest must fail")
                    .kind(),
                GenerationRootErrorKind::HashMismatch
            );
            assert_eq!(
                fs::read(artifact).expect("artifact should remain readable"),
                b"unchanged"
            );
        }

        #[test]
        fn opened_root_requires_absolute_route() {
            let error = QualifiedGenerationRoot::admit(Path::new("relative"))
                .expect_err("relative root must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::InvalidRoute);
            assert_eq!(error.stage(), GenerationRootStage::ParseRootRoute);
        }

        #[test]
        fn root_path_with_repeated_separator_is_rejected_before_open() {
            let error = QualifiedGenerationRoot::admit(Path::new("/data//forbidden"))
                .expect_err("repeated separator must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::InvalidRoute);
            assert_eq!(error.stage(), GenerationRootStage::ParseRootRoute);
        }

        #[test]
        fn lock_file_hardlink_is_rejected_before_flock() {
            let root_path = fixture_root("lock-hardlink");
            let lock = control_file(&root_path, "LOCK", b"lock-v1!");
            fs::hard_link(&lock, root_path.join("LOCK-alias"))
                .expect("fixture hardlink should be creatable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let observed = Arc::new(Mutex::new(false));
            let hook_observed = Arc::clone(&observed);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_observed.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                root.admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect_err("hardlinked lock file must fail")
                .kind(),
                GenerationRootErrorKind::HardLinked
            );
            assert!(!*observed.lock().expect("hook state should lock"));
        }

        #[test]
        fn lock_sync_rechecks_identity_after_barrier() {
            let root_path = fixture_root("lock-sync-fence");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            let lock = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("exclusive lock should succeed");
            let _guard = install_test_hook(|boundary| {
                if boundary == TestBoundary::AfterFileSync {
                    return Err(injected(GenerationRootStage::SyncRegularFile));
                }
                Ok(())
            });
            assert_eq!(
                lock.sync_durable()
                    .expect_err("post-barrier fault must propagate")
                    .kind(),
                GenerationRootErrorKind::Io
            );
            lock.unlock()
                .expect("lock should still be explicitly releasable");
        }

        #[test]
        fn persistent_test_fixtures_never_use_automatic_cleanup() {
            let root_path = fixture_root("persistent");
            private_file(&root_path, "evidence", b"retained");
            assert!(root_path.exists());
            assert_eq!(
                fs::read(root_path.join("evidence")).expect("evidence should persist"),
                b"retained"
            );
        }

        #[test]
        fn root_qualification_rejects_symlink_final_component() {
            let container = fixture_root("root-symlink-container");
            let target = fixture_root("root-symlink-target");
            let link = container.join("root-link");
            symlink(&target, &link).expect("root symlink should be creatable");
            assert_eq!(
                QualifiedGenerationRoot::admit(&link)
                    .expect_err("root symlink must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
        }

        /// Linux half of the cross-platform symlink error-kind parity contract
        /// (bd-54h2l LOW B).
        ///
        /// The macOS arm
        /// `macos_absolute_root_route_rejects_ancestor_and_final_symlinks`
        /// asserts [`GenerationRootErrorKind::SymbolicLink`] for an absolute
        /// route whose ANCESTOR is a symlink and for one whose FINAL component
        /// is, but it lives in a `cfg(all(target_os = "macos", target_arch =
        /// "aarch64"))` module that never compiles on a Linux host. Linux
        /// previously covered only the final component at root admission
        /// (`root_qualification_rejects_symlink_final_component`) and the
        /// confined-route case
        /// (`ancestor_and_final_symlinks_fail_without_touching_decoys`), so the
        /// ancestor-of-an-absolute-route shape had no Linux twin and the parity
        /// claim rested on nothing measurable here.
        ///
        /// This pins the Linux side of that claim on the identical input shape.
        /// The macOS side remains an ENCODED EXPECTATION, not a live proof:
        /// confirming both platforms agree still needs an arm64 macOS run, and
        /// that residual is named on bd-54h2l.
        #[test]
        fn absolute_root_route_rejects_ancestor_and_final_symlinks() {
            let container = fixture_root("absolute-symlink-container");
            let target_parent = fixture_root("absolute-symlink-target-parent");
            let target_root = private_dir(&target_parent, "qualified-root");
            let ancestor_link = container.join("ancestor-link");
            let final_link = container.join("final-link");
            symlink(&target_parent, &ancestor_link)
                .expect("absolute-route ancestor symlink should be creatable");
            symlink(&target_root, &final_link)
                .expect("absolute-route final symlink should be creatable");

            assert_eq!(
                QualifiedGenerationRoot::admit(&ancestor_link.join("qualified-root"))
                    .expect_err("an absolute-route ancestor symlink must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(&final_link)
                    .expect_err("an absolute-route final symlink must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
        }

        #[test]
        fn file_reopen_fault_occurs_after_exact_hashing() {
            let root_path = fixture_root("reopen-order");
            let contents = b"hash-before-reopen";
            private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if boundary == TestBoundary::BeforeFileRouteReopen {
                    return Err(injected(GenerationRootStage::RevalidateRegularFile));
                }
                Ok(())
            });
            assert!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .is_err()
            );
            let observed = boundaries.lock().expect("boundary log should lock");
            let exact_read = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::AfterExactRead)
                .expect("exact read boundary should be observed");
            let reopen = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::BeforeFileRouteReopen)
                .expect("reopen boundary should be observed");
            drop(observed);
            assert!(exact_read < reopen);
        }

        #[test]
        fn zero_length_file_is_admitted_without_partial_read_state() {
            let root_path = fixture_root("zero-length");
            private_file(&root_path, "empty", b"");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let admitted = root
                .admit_file(&confined("empty"), immutable_expectation(b""))
                .expect("exact zero-length file should qualify");
            assert!(admitted.as_bytes().is_empty());
            assert_eq!(admitted.sha256(), digest(b""));
        }

        #[test]
        fn lock_guard_debug_never_exposes_descriptor_or_path() {
            let root_path = fixture_root("lock-debug");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect("control file should qualify");
            let lock = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect("exclusive lock should succeed");
            let debug = format!("{lock:?}");
            assert_eq!(debug, "GenerationRootLock { held: true, .. }");
            assert!(!debug.contains("LOCK"));
            assert!(!debug.contains(root_path.to_string_lossy().as_ref()));
            lock.unlock().expect("lock should release");
        }

        #[test]
        fn file_admission_revalidates_root_after_file_reopen() {
            let root_path = fixture_root("final-root-fence");
            let contents = b"root fence";
            private_file(&root_path, "artifact", contents);
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let moved = root_path.with_extension("moved-at-final-fence");
            let swap_path = root_path.clone();
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeFinalRootRevalidation {
                    fs::rename(&swap_path, &moved).expect("root should move to a fresh path");
                    DirBuilder::new()
                        .mode(0o700)
                        .create(&swap_path)
                        .expect("replacement root should be creatable");
                    fs::set_permissions(&swap_path, fs::Permissions::from_mode(0o700))
                        .expect("replacement root mode should be settable");
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect_err("final root replacement must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn regular_file_descriptor_is_opened_cloexec() {
            let root_path = fixture_root("cloexec");
            private_file(&root_path, "artifact", b"cloexec");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let observed = Arc::new(Mutex::new(None));
            let hook_observed = Arc::clone(&observed);
            let _guard = install_test_hook(move |boundary| {
                if let TestBoundary::AfterRegularFileOpen { index: 0, cloexec } = boundary {
                    *hook_observed.lock().expect("hook state should lock") = Some(cloexec);
                }
                Ok(())
            });
            root.admit_file(&confined("artifact"), immutable_expectation(b"cloexec"))
                .expect("file should qualify");
            assert_eq!(
                *observed.lock().expect("hook state should lock"),
                Some(true),
                "the retained descriptor must carry FD_CLOEXEC"
            );
        }

        #[test]
        fn fixture_file_open_is_create_new_not_truncating() {
            let root_path = fixture_root("fixture-create-new");
            let path = private_file(&root_path, "artifact", b"original");
            let error = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path)
                .expect_err("create-new should reject an existing fixture");
            assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
            assert_eq!(
                fs::read(path).expect("original should remain readable"),
                b"original"
            );
        }

        #[test]
        fn error_counts_are_bounded_numeric_not_content_bearing() {
            let observed = super::super::GENERATION_ROOT_MAX_CONTROL_FILE_BYTES.saturating_add(1);
            let error = GenerationFileExpectation::control(observed)
                .expect_err("control-file ceiling must fail");
            assert_eq!(
                error.expected(),
                Some(super::super::GENERATION_ROOT_MAX_CONTROL_FILE_BYTES)
            );
            assert_eq!(error.observed(), Some(observed));
            assert!(!error.to_string().contains("artifact"));
        }

        #[test]
        fn file_admission_does_not_reopen_through_symlink_substitution() {
            let root_path = fixture_root("symlink-substitution");
            let contents = b"original";
            let original = private_file(&root_path, "artifact", contents);
            let decoy = private_file(&root_path, "decoy", contents);
            let retained = root_path.join("retained");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeFileRouteReopen {
                    fs::rename(&original, &retained).expect("original should move to a fresh path");
                    symlink(&decoy, &original).expect("attacker symlink should be creatable");
                }
                Ok(())
            });
            assert_eq!(
                root.admit_file(&confined("artifact"), immutable_expectation(contents))
                    .expect_err("symlink substitution must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
        }

        #[test]
        fn direct_root_and_file_operations_leave_existing_siblings_unchanged() {
            let root_path = fixture_root("siblings");
            let sibling = private_file(&root_path, "sibling", b"sibling bytes");
            private_file(&root_path, "artifact", b"artifact bytes");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            root.admit_file(
                &confined("artifact"),
                immutable_expectation(b"artifact bytes"),
            )
            .expect("artifact should qualify");
            assert_eq!(
                fs::read(sibling).expect("sibling should remain readable"),
                b"sibling bytes"
            );
        }

        #[test]
        fn opened_root_has_single_effective_owner() {
            let root_path = fixture_root("owner");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            assert_eq!(root.witness().uid(), rustix::process::geteuid().as_raw());
            assert_eq!(root.witness().gid(), rustix::process::getegid().as_raw());
        }

        #[test]
        fn exact_control_file_size_is_checked_before_flock() {
            let root_path = fixture_root("lock-size");
            control_file(&root_path, "LOCK", b"short");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let observed = Arc::new(Mutex::new(false));
            let hook_observed = Arc::clone(&observed);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_observed.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            assert_eq!(
                root.admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small expectation should be accepted"),
                )
                .expect_err("wrong lock size must fail")
                .kind(),
                GenerationRootErrorKind::SizeMismatch
            );
            assert!(!*observed.lock().expect("hook state should lock"));
        }

        #[test]
        fn lock_candidate_open_faults_are_reported_as_acquire_lock() {
            let root_path = fixture_root("lock-candidate-stage");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("private root should qualify");
            let control = root
                .admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("control should qualify before the injected drift");
            let reached_flock = Arc::new(Mutex::new(false));
            let hook_reached_flock = Arc::clone(&reached_flock);
            let mut changed = false;
            let _guard = install_test_hook(move |boundary| {
                if !changed && boundary == (TestBoundary::BeforeRegularFileOpen { index: 0 }) {
                    fs::set_permissions(&lock_path, fs::Permissions::from_mode(0o644))
                        .expect("lock candidate mode drift should be injectable");
                    changed = true;
                }
                if boundary == TestBoundary::BeforeLock {
                    *hook_reached_flock.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            let error = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("the drifted lock candidate must fail before flock");
            assert_eq!(error.kind(), GenerationRootErrorKind::WrongMode);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            assert!(
                !*reached_flock.lock().expect("hook state should lock"),
                "candidate qualification must precede flock"
            );
        }

        #[test]
        fn root_security_error_identifies_stage_without_path() {
            let root_path = fixture_root("root-stage");
            fs::set_permissions(&root_path, fs::Permissions::from_mode(0o755))
                .expect("fixture mode should change");
            let error =
                QualifiedGenerationRoot::admit(&root_path).expect_err("public root mode must fail");
            assert_eq!(error.stage(), GenerationRootStage::QualifyRootSecurity);
            assert_eq!(error.kind(), GenerationRootErrorKind::WrongMode);
            assert!(
                !error
                    .to_string()
                    .contains(root_path.to_string_lossy().as_ref())
            );
        }

        #[test]
        fn absolute_ancestor_owner_and_mode_policy_is_fail_closed() {
            let effective_uid = rustix::process::geteuid().as_raw();
            for owner in [0, effective_uid] {
                for mode in [0o700, 0o750, 0o755, 0o500, 0o555] {
                    validate_absolute_ancestor_owner_mode_for_test(owner, mode)
                        .expect("root-owned or euid-owned non-writable ancestors are trusted");
                }
            }
            for mode in [0o720, 0o702, 0o770, 0o707, 0o1777] {
                let error = validate_absolute_ancestor_owner_mode_for_test(effective_uid, mode)
                    .expect_err("sticky or non-sticky group/world writable ancestors must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::WrongMode);
            }
            let wrong_owner = if effective_uid == 0 {
                1
            } else {
                effective_uid + 1
            };
            assert_eq!(
                validate_absolute_ancestor_owner_mode_for_test(wrong_owner, 0o755)
                    .expect_err("an unrelated owner must fail")
                    .kind(),
                GenerationRootErrorKind::WrongOwner
            );
        }

        #[test]
        fn absolute_route_qualifies_slash_and_every_non_final_component() {
            let root_path = fixture_root("absolute-ancestor-boundaries");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            QualifiedGenerationRoot::admit(&root_path)
                .expect("the secure retained fixture route should qualify");
            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(
                observed.contains(&TestBoundary::BeforeAbsoluteAncestorAclRead { index: None })
            );
            assert!(observed.contains(&TestBoundary::AfterAbsoluteAncestorAclRead { index: None }));
            let final_index = root_path.components().count().saturating_sub(2);
            assert!(
                observed.contains(&TestBoundary::BeforeRootComponentOpen { index: final_index })
            );
            assert!(
                !observed.contains(&TestBoundary::BeforeAbsoluteAncestorAclRead {
                    index: Some(final_index),
                }),
                "the final root uses the stricter private-root qualifier, not ancestor policy"
            );
            drop(observed);
        }

        #[test]
        fn group_world_and_sticky_writable_absolute_ancestors_are_rejected() {
            for (label, mode) in [("group", 0o770), ("world", 0o707), ("sticky", 0o1777)] {
                let ancestor = fixture_root(&format!("writable-ancestor-{label}"));
                let root_path = private_dir(&ancestor, "root");
                fs::set_permissions(&ancestor, fs::Permissions::from_mode(mode))
                    .expect("hostile ancestor mode should be settable");
                let error = QualifiedGenerationRoot::admit(&root_path)
                    .expect_err("an attacker-writable absolute ancestor must fail");
                assert_eq!(error.kind(), GenerationRootErrorKind::WrongMode);
                assert!(error.component_index().is_some());
            }
        }

        #[test]
        fn access_and_default_acls_on_absolute_ancestors_are_rejected() {
            for (label, xattr_name) in [
                ("access", "system.posix_acl_access"),
                ("default", "system.posix_acl_default"),
            ] {
                let ancestor = fixture_root(&format!("acl-ancestor-{label}"));
                let root_path = private_dir(&ancestor, "root");
                let retained = File::open(&ancestor).expect("ancestor descriptor should open");
                install_linux_acl_xattr(&retained, xattr_name, 0o7, 0o4, 0, 0o4, 0);
                assert_eq!(
                    QualifiedGenerationRoot::admit(&root_path)
                        .expect_err("an ancestor extended ACL must fail")
                        .kind(),
                    GenerationRootErrorKind::AclRejected
                );
            }
        }

        #[test]
        fn ancestor_mutation_inside_the_acl_sandwich_is_rejected() {
            let ancestor = fixture_root("ancestor-acl-sandwich");
            let root_path = private_dir(&ancestor, "root");
            let ancestor_index = ancestor.components().count().saturating_sub(2);
            let mut mutated = false;
            let hook_ancestor = ancestor.clone();
            let _guard = install_test_hook(move |boundary| {
                if !mutated
                    && boundary
                        == (TestBoundary::BeforeAbsoluteAncestorAclRead {
                            index: Some(ancestor_index),
                        })
                {
                    fs::set_permissions(&hook_ancestor, fs::Permissions::from_mode(0o710))
                        .expect("the ancestor security mutation should be injectable");
                    mutated = true;
                }
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("ctime drift inside the ACL sandwich must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                error.component_index(),
                Some(u16::try_from(ancestor_index).expect("fixture depth fits u16"))
            );
        }

        #[test]
        fn ancestor_acl_added_between_full_route_walks_is_rejected() {
            let ancestor = fixture_root("ancestor-acl-between-walks");
            let root_path = private_dir(&ancestor, "root");
            let hook_ancestor = ancestor.clone();
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                if !mutated && boundary == TestBoundary::AfterFirstRootQualification {
                    let retained =
                        File::open(&hook_ancestor).expect("ancestor descriptor should reopen");
                    install_linux_acl_xattr(
                        &retained,
                        "system.posix_acl_default",
                        0o7,
                        0o4,
                        0,
                        0o4,
                        0,
                    );
                    mutated = true;
                }
                Ok(())
            });
            assert_eq!(
                QualifiedGenerationRoot::admit(&root_path)
                    .expect_err("an ACL added before the second route walk must fail")
                    .kind(),
                GenerationRootErrorKind::AclRejected
            );
        }

        #[test]
        fn absolute_ancestor_substitution_is_rejected_but_sibling_churn_is_allowed() {
            let parent = fixture_root("ancestor-substitution-parent");
            let live = private_dir(&parent, "live");
            let live_root = private_dir(&live, "root");
            let decoy = private_dir(&parent, "decoy");
            private_dir(&decoy, "root");
            let retained = parent.join("retained-live");
            let hook_live = live.clone();
            let hook_decoy = decoy.clone();
            let mut swapped = false;
            let swap_guard = install_test_hook(move |boundary| {
                if !swapped && boundary == TestBoundary::AfterFirstRootQualification {
                    fs::rename(&hook_live, &retained)
                        .expect("the original ancestor should move to a fresh retained name");
                    fs::rename(&hook_decoy, &hook_live)
                        .expect("the decoy ancestor should move into the live route");
                    swapped = true;
                }
                Ok(())
            });
            assert_eq!(
                QualifiedGenerationRoot::admit(&live_root)
                    .expect_err("an absolute ancestor substitution must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            drop(swap_guard);

            let churn_parent = fixture_root("ancestor-sibling-churn");
            let churn_root = private_dir(&churn_parent, "root");
            let hook_parent = churn_parent.clone();
            let mut churned = false;
            let _guard = install_test_hook(move |boundary| {
                if !churned && boundary == TestBoundary::AfterFirstRootQualification {
                    control_file(&hook_parent, "unrelated-sibling", b"retained");
                    churned = true;
                }
                Ok(())
            });
            QualifiedGenerationRoot::admit(&churn_root)
                .expect("unrelated sibling churn must not poison persisted route identity");
        }

        #[test]
        fn named_anchor_guard_binds_exact_tuple_and_images() {
            let lock_bytes = b"lock-v1!";
            let (root_path, _authority_path, layout) =
                named_root_fixture("named-anchor-happy", lock_bytes, 0xa5);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the exact named anchor tuple should qualify");
            let witnesses = root.anchor_witnesses();
            assert_eq!(witnesses.root(), root.witness());
            assert_ne!(witnesses.root().inode(), witnesses.lock().inode());
            assert_ne!(witnesses.root().inode(), witnesses.authority().inode());
            assert_ne!(witnesses.lock().inode(), witnesses.authority().inode());
            assert_eq!(
                witnesses.lock().byte_len(),
                u64::try_from(lock_bytes.len()).expect("fixture length fits u64")
            );
            assert_eq!(
                witnesses.authority().byte_len(),
                GENERATION_ROOT_AUTHORITY_FILE_BYTES
            );
            let guard = root
                .read_guard()
                .expect("the shared read guard should acquire");
            assert_eq!(guard.lock_bytes(), lock_bytes);
            assert!(guard.authority_bytes().iter().all(|byte| *byte == 0xa5));
            assert_eq!(guard.lock_sha256(), digest(lock_bytes));
            assert_eq!(guard.authority_sha256(), digest(guard.authority_bytes()));
            let first_lock_arc = guard.lock_bytes_arc();
            let second_lock_arc = guard.lock_bytes_arc();
            assert!(Arc::ptr_eq(&first_lock_arc, &second_lock_arc));
            guard
                .release()
                .expect("the unchanged shared guard should release");
        }

        #[test]
        fn named_authority_legitimate_in_place_rewrite_is_visible_to_the_next_guard() {
            let (root_path, authority_path, layout) =
                named_root_fixture("named-anchor-rewrite", b"lock-v1!", 0x11);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the original named anchors should qualify");
            let first = root.read_guard().expect("the first guard should acquire");
            assert!(first.authority_bytes().iter().all(|byte| *byte == 0x11));
            first.release().expect("the first guard should release");

            let replacement = authority_image(0x22);
            rewrite_control_file(&authority_path, &replacement);
            root.revalidate()
                .expect("same-inode fixed-length authority advancement is legitimate");
            let second = root.read_guard().expect("the next guard should acquire");
            assert_eq!(second.authority_bytes(), replacement);
            second.release().expect("the second guard should release");
        }

        #[test]
        fn shared_guards_coexist_and_exclude_the_exclusive_anchor_guard() {
            let (root_path, _authority_path, layout) =
                named_root_fixture("named-anchor-contention", b"lock-v1!", 0x33);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the named anchors should qualify");
            let first = root.read_guard().expect("the first reader should acquire");
            let second = root.read_guard().expect("a second reader should coexist");
            assert_eq!(
                root.try_exclusive_anchor_guard()
                    .expect_err("an exclusive guard must not bypass active readers")
                    .kind(),
                GenerationRootErrorKind::LockContended
            );
            second.release().expect("the second reader should release");
            first.release().expect("the first reader should release");
            root.try_exclusive_anchor_guard()
                .expect("the exclusive guard should acquire after both readers release")
                .release()
                .expect("the exclusive guard should release");
        }

        #[test]
        fn captured_anchor_arc_is_immutable_and_release_detects_ambient_mutation() {
            let (root_path, authority_path, layout) =
                named_root_fixture("named-anchor-ambient-mutation", b"lock-v1!", 0x44);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the named anchors should qualify");
            let guard = root.read_guard().expect("the shared guard should acquire");
            let captured = guard.authority_bytes_arc();
            let replacement = authority_image(0x55);
            rewrite_control_file(&authority_path, &replacement);
            assert!(captured.iter().all(|byte| *byte == 0x44));
            let error = guard
                .release()
                .expect_err("ambient mutation must invalidate explicit guard release");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::ReleaseLock);
            root.try_exclusive_anchor_guard()
                .expect("failed validation must still unlock the kernel flock")
                .release()
                .expect("the post-failure exclusive guard should release");
        }

        #[test]
        fn drift_between_double_anchor_captures_fails_before_returning_a_guard() {
            let (root_path, authority_path, layout) =
                named_root_fixture("named-anchor-double-capture", b"lock-v1!", 0x66);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the named anchors should qualify");
            let replacement = authority_image(0x77);
            let mut exact_reads = 0_u8;
            let mut injected = false;
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::AfterExactRead {
                    exact_reads = exact_reads.saturating_add(1);
                } else if exact_reads >= 4
                    && !injected
                    && matches!(boundary, TestBoundary::BeforeRootComponentOpen { .. })
                {
                    rewrite_control_file(&authority_path, &replacement);
                    injected = true;
                }
                Ok(())
            });
            let error = root
                .read_guard()
                .expect_err("authority drift between the two captures must fail");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                error.stage(),
                GenerationRootStage::AcquireLock,
                "the completed first image and later image must disagree at the guard boundary"
            );
        }

        #[test]
        fn named_anchor_alias_missing_name_and_route_replacement_fail_closed() {
            let alias_root = fixture_root("named-anchor-hardlink-alias");
            let shared = authority_image(0x88);
            let lock_path = control_file(&alias_root, "LOCK", &shared);
            fs::hard_link(&lock_path, alias_root.join("AUTHORITY"))
                .expect("the hostile hard-link alias should be creatable");
            let layout = GenerationRootAnchorLayout::new(GENERATION_ROOT_AUTHORITY_FILE_BYTES)
                .expect("the alias layout is bounded");
            assert_eq!(
                NamedGenerationRoot::admit(&alias_root, layout)
                    .expect_err("LOCK and AUTHORITY must never alias one inode")
                    .kind(),
                GenerationRootErrorKind::HardLinked
            );

            let missing_root = fixture_root("named-anchor-missing");
            control_file(&missing_root, "lock", b"lock-v1!");
            control_file(&missing_root, "AUTHORITY", &authority_image(0x99));
            assert!(
                NamedGenerationRoot::admit(
                    &missing_root,
                    GenerationRootAnchorLayout::new(8).expect("layout is bounded"),
                )
                .is_err(),
                "the lower-case decoy must not satisfy the exact LOCK route"
            );

            let (root_path, authority_path, layout) =
                named_root_fixture("named-anchor-route-swap", b"lock-v1!", 0xaa);
            let root = NamedGenerationRoot::admit(&root_path, layout)
                .expect("the original named tuple should qualify");
            let retained = root_path.join("AUTHORITY-retained");
            let hook_root = root_path.clone();
            let mut exact_reads = 0_u8;
            let mut injected = false;
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::AfterExactRead {
                    exact_reads = exact_reads.saturating_add(1);
                } else if exact_reads >= 4
                    && !injected
                    && matches!(boundary, TestBoundary::BeforeRootComponentOpen { .. })
                {
                    fs::rename(&authority_path, &retained)
                        .expect("the original authority should move to a retained name");
                    control_file(&hook_root, "AUTHORITY", &authority_image(0xaa));
                    injected = true;
                }
                Ok(())
            });
            assert_eq!(
                root.read_guard()
                    .expect_err("route replacement during tuple capture must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn named_root_and_read_guard_are_send_and_sync() {
            fn assert_send_sync<T: Send + Sync>() {}
            assert_send_sync::<NamedGenerationRoot>();
            assert_send_sync::<super::super::GenerationRootReadGuard<'static>>();
        }

        #[test]
        fn private_file_helper_never_opens_read_write_by_default() {
            let root_path = fixture_root("helper-access");
            let path = private_file(&root_path, "artifact", b"readable");
            let mut file = File::open(path).expect("fixture should be readable");
            let position = file
                .stream_position()
                .expect("fixture stream position should be available");
            assert_eq!(position, 0);
        }
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    mod macos_arm64 {
        use super::super::platform::{
            TestBoundary, install_test_hook, set_control_root_creator_process_id_for_test,
            set_root_creator_process_id_for_test, stat_device_as_u64_for_test,
            validate_macos_object_flags_for_test,
        };
        use super::super::{
            ConfinedGenerationPath, GENERATION_ROOT_AUTHORITY_FILE_BYTES,
            GenerationFileExpectation, GenerationRootAnchorLayout, GenerationRootError,
            GenerationRootErrorKind, GenerationRootLockMode, GenerationRootStage,
            PreopenedGenerationRootAnchors, QualifiedFilesystem,
            QualifiedGenerationDirectory as QualifiedGenerationRoot,
            QualifiedGenerationRoot as NamedGenerationRoot,
        };
        use crate::fd_acl::{ExtendedAclPresence, extended_acl_presence};
        use sha2::{Digest, Sha256};
        use std::fs::{self, DirBuilder, File, OpenOptions};
        use std::io::{Read, Seek, SeekFrom, Write};
        use std::os::fd::{AsFd, OwnedFd};
        use std::os::macos::fs::MetadataExt;
        use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt, symlink};
        use std::path::{Path, PathBuf};
        use std::process::Command;
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::sync::{Arc, Mutex, OnceLock};
        use std::time::{Duration, SystemTime, UNIX_EPOCH};

        static FIXTURE_SERIAL: AtomicU64 = AtomicU64::new(0);
        static FIXTURE_SLOT_SERIAL: AtomicU64 = AtomicU64::new(0);
        static FIXTURE_BASE: OnceLock<PathBuf> = OnceLock::new();
        const FIXTURE_SLOT_COUNT: u64 = 512;

        #[test]
        fn apfs_object_flag_profile_accepts_only_zero() {
            validate_macos_object_flags_for_test(0)
                .expect("the narrow APFS object-flag profile accepts zero");
            for flags in [libc::UF_IMMUTABLE, libc::UF_APPEND, libc::UF_NODUMP] {
                let error = validate_macos_object_flags_for_test(flags)
                    .expect_err("every nonzero APFS object flag is outside the profile");
                assert_eq!(
                    error.kind(),
                    GenerationRootErrorKind::UnsupportedObjectFlags
                );
                assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
                assert_eq!(error.expected(), Some(0));
                assert_eq!(error.observed(), Some(u64::from(flags)));
            }
        }

        #[test]
        fn macos_signed_device_ids_are_normalized_by_sign_extension() {
            assert_eq!(stat_device_as_u64_for_test(0), 0);
            assert_eq!(stat_device_as_u64_for_test(1), 1);
            assert_eq!(stat_device_as_u64_for_test(-1), u64::MAX);
            assert_eq!(
                stat_device_as_u64_for_test(i32::MIN),
                u64::from_ne_bytes(i64::from(i32::MIN).to_ne_bytes())
            );
        }

        fn set_empty_acl(path: &Path) {
            let output = Command::new("/bin/chmod")
                .arg("-N")
                .arg(path)
                .output()
                .expect("the physical APFS ACL receipt requires /bin/chmod");
            assert!(
                output.status.success(),
                "chmod -N failed: status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            let retained = File::open(path)
                .expect("the cleared APFS fixture must remain openable for ACL proof");
            assert_eq!(
                extended_acl_presence(retained.as_fd())
                    .expect("the descriptor-bound ACL absence probe must succeed"),
                ExtendedAclPresence::Absent,
                "an admissible APFS fixture must have no extended ACL entries"
            );
        }

        fn set_non_empty_acl(path: &Path, allow: bool) {
            let user = std::env::var("USER").expect("USER must identify an ACL principal");
            let disposition = if allow { "allow" } else { "deny" };
            let entry = format!("user:{user} {disposition} write");
            let output = Command::new("/bin/chmod")
                .args(["+a", &entry])
                .arg(path)
                .output()
                .expect("the physical APFS ACL receipt requires /bin/chmod");
            assert!(
                output.status.success(),
                "chmod +a failed: entry={entry:?}, status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
            let retained = File::open(path)
                .expect("the ACL-bearing APFS fixture must remain openable for ACL proof");
            assert_eq!(
                extended_acl_presence(retained.as_fd())
                    .expect("the descriptor-bound ACL presence probe must succeed"),
                ExtendedAclPresence::Present,
                "the installed {disposition} ACL must be observed through the retained descriptor"
            );
        }

        fn run_chflags(flag: &str, path: &Path) {
            let output = Command::new("/usr/bin/chflags")
                .arg(flag)
                .arg(path)
                .output()
                .expect("the physical APFS object-flag receipt requires chflags");
            assert!(
                output.status.success(),
                "chflags failed: flag={flag}, status={:?}, stdout={}, stderr={}",
                output.status.code(),
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
        }

        fn fixture_root(label: &str) -> PathBuf {
            let slot = FIXTURE_SLOT_SERIAL.fetch_add(1, Ordering::Relaxed);
            assert!(
                slot < FIXTURE_SLOT_COUNT,
                "the retained APFS fixture-slot pool must cover every test root"
            );
            let slot_path = secure_fixture_base().join(format!("slot-{slot:03}"));
            fixture_root_under(&slot_path, label)
        }

        fn secure_fixture_base() -> &'static Path {
            FIXTURE_BASE
                .get_or_init(|| {
                    let private_tmp = std::env::temp_dir()
                        .canonicalize()
                        .expect("the process-private macOS temporary route must canonicalize");
                    assert!(
                        private_tmp.is_absolute(),
                        "the canonical macOS temporary route must be absolute"
                    );
                    let epoch_nanos = SystemTime::now()
                        .duration_since(UNIX_EPOCH)
                        .map_or(0, |duration| duration.as_nanos());
                    for attempt in 0_u64..64 {
                        let candidate = private_tmp.join(format!(
                            "frankensearch-generation-root-tests-{}-{epoch_nanos}-{attempt}",
                            std::process::id()
                        ));
                        match DirBuilder::new().mode(0o700).create(&candidate) {
                            Ok(()) => {
                                fs::set_permissions(&candidate, fs::Permissions::from_mode(0o700))
                                    .expect("persistent APFS fixture base mode should be settable");
                                set_empty_acl(&candidate);
                                for slot in 0..FIXTURE_SLOT_COUNT {
                                    let slot_path = candidate.join(format!("slot-{slot:03}"));
                                    DirBuilder::new().mode(0o700).create(&slot_path).expect(
                                        "each retained APFS fixture slot should be creatable",
                                    );
                                    fs::set_permissions(
                                        &slot_path,
                                        fs::Permissions::from_mode(0o700),
                                    )
                                    .expect(
                                        "each retained APFS fixture slot mode should be private",
                                    );
                                    set_empty_acl(&slot_path);
                                }
                                return candidate;
                            }
                            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                            Err(error) => {
                                panic!("failed to create retained APFS fixture base: {error}");
                            }
                        }
                    }
                    panic!("failed to allocate a retained process APFS fixture base");
                })
                .as_path()
        }

        fn fixture_root_under(base: &Path, label: &str) -> PathBuf {
            fs::create_dir_all(base).expect("persistent APFS fixture base should be creatable");
            let epoch_nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_or(0, |duration| duration.as_nanos());
            for attempt in 0_u64..64 {
                let serial = FIXTURE_SERIAL.fetch_add(1, Ordering::Relaxed);
                let candidate = base.join(format!(
                    "{}-{}-{epoch_nanos}-{serial}-{attempt}",
                    std::process::id(),
                    label
                ));
                match DirBuilder::new().mode(0o700).create(&candidate) {
                    Ok(()) => {
                        fs::set_permissions(&candidate, fs::Permissions::from_mode(0o700))
                            .expect("persistent APFS fixture mode should be settable");
                        set_empty_acl(&candidate);
                        return candidate;
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
                    Err(error) => {
                        panic!("failed to create persistent APFS test fixture: {error}");
                    }
                }
            }
            panic!("failed to allocate a unique persistent APFS test fixture");
        }

        fn private_dir(parent: &Path, name: &str) -> PathBuf {
            let path = parent.join(name);
            DirBuilder::new()
                .mode(0o700)
                .create(&path)
                .expect("private APFS directory should be creatable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
                .expect("private APFS directory mode should be settable");
            set_empty_acl(&path);
            path
        }

        fn observe_case_sensitive(root: &Path) -> bool {
            private_file(root, "case-probe", b"a");
            let upper = root.join("CASE-PROBE");
            match OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&upper)
            {
                Ok(mut file) => {
                    file.write_all(b"b")
                        .expect("case-sensitivity probe byte should be writable");
                    file.sync_all()
                        .expect("case-sensitivity probe byte should be durable");
                    fs::set_permissions(&upper, fs::Permissions::from_mode(0o400))
                        .expect("case-sensitivity probe should be sealed read-only");
                    set_empty_acl(&upper);
                    true
                }
                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,
                Err(error) => panic!("case-sensitivity probe failed unexpectedly: {error}"),
            }
        }

        fn private_file(parent: &Path, name: &str, bytes: &[u8]) -> PathBuf {
            let path = parent.join(name);
            let mut file = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path)
                .expect("private APFS file should be creatable");
            file.write_all(bytes)
                .expect("persistent APFS fixture bytes should be writable");
            file.sync_all()
                .expect("persistent APFS fixture bytes should be durable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o400))
                .expect("immutable APFS fixture should be sealed read-only");
            set_empty_acl(&path);
            path
        }

        fn control_file(parent: &Path, name: &str, bytes: &[u8]) -> PathBuf {
            let path = parent.join(name);
            let mut file = OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&path)
                .expect("private APFS control file should be creatable");
            file.write_all(bytes)
                .expect("persistent APFS control bytes should be writable");
            file.sync_all()
                .expect("persistent APFS control bytes should be durable");
            set_empty_acl(&path);
            path
        }

        fn authority_image(fill: u8) -> Vec<u8> {
            vec![
                fill;
                usize::try_from(GENERATION_ROOT_AUTHORITY_FILE_BYTES)
                    .expect("the frozen authority length fits usize")
            ]
        }

        fn named_root_fixture(
            label: &str,
            lock_bytes: &[u8],
            authority_fill: u8,
        ) -> (PathBuf, PathBuf, PathBuf, GenerationRootAnchorLayout) {
            let root = fixture_root(label);
            let lock_path = control_file(&root, "LOCK", lock_bytes);
            let authority_path = control_file(&root, "AUTHORITY", &authority_image(authority_fill));
            let layout = GenerationRootAnchorLayout::new(
                u64::try_from(lock_bytes.len()).expect("the lock fixture length fits u64"),
            )
            .expect("the named lock fixture length is bounded");
            (root, lock_path, authority_path, layout)
        }

        fn admit_named_root(
            root_path: &Path,
            lock_path: &Path,
            authority_path: &Path,
            layout: GenerationRootAnchorLayout,
        ) -> NamedGenerationRoot {
            NamedGenerationRoot::admit_preopened(
                root_path,
                layout,
                PreopenedGenerationRootAnchors::new(
                    preopened_control(lock_path),
                    preopened_control(authority_path),
                ),
            )
            .expect("the exact provider-labelled anchor tuple should qualify")
        }

        fn rewrite_control_file(path: &Path, bytes: &[u8]) {
            let expected_len = u64::try_from(bytes.len()).expect("fixture length fits u64");
            assert_eq!(
                fs::metadata(path)
                    .expect("control metadata should be readable")
                    .len(),
                expected_len,
                "in-place control rewrites must retain the frozen physical length"
            );
            let mut file = OpenOptions::new()
                .write(true)
                .open(path)
                .expect("the mutable APFS control anchor should be writable");
            file.seek(SeekFrom::Start(0))
                .expect("the APFS control anchor should seek to its first byte");
            file.write_all(bytes)
                .expect("the complete in-place APFS control image should be writable");
            file.sync_all()
                .expect("the in-place APFS control rewrite should be durable");
        }

        fn mapped_control_file(parent: &Path, name: &str) -> (PathBuf, crate::VectorIndex) {
            let path = parent.join(name);
            let mut writer = crate::VectorIndex::create(&path, "generation-root-test", 1)
                .expect("mapped APFS control fixture writer should be creatable");
            writer
                .write_record("control", &[1.0])
                .expect("mapped APFS control fixture record should be valid");
            writer
                .finish()
                .expect("mapped APFS control fixture should be durable");
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
                .expect("mapped APFS control fixture should use the control mode");
            set_empty_acl(&path);
            let mapping = crate::VectorIndex::open(&path)
                .expect("mapped APFS control fixture should retain a shared writable mapping");
            (path, mapping)
        }

        fn mapped_immutable_file(parent: &Path, name: &str) -> (PathBuf, crate::VectorIndex) {
            let (path, mapping) = mapped_control_file(parent, name);
            fs::set_permissions(&path, fs::Permissions::from_mode(0o400))
                .expect("pre-held APFS mapping should seal as an immutable artifact");
            (path, mapping)
        }

        fn mutate_mapping(mapping: &mut crate::VectorIndex) {
            let crate::VectorIndexData::Mutable(bytes) = &mut mapping.data else {
                panic!("legacy VectorIndex::open must retain a writable mapping");
            };
            let byte = bytes
                .last_mut()
                .expect("mapped APFS control fixture must contain at least one byte");
            *byte ^= 0x01;
        }

        fn preopened_immutable(path: &Path) -> OwnedFd {
            File::open(path)
                .expect("trusted test provider should open the known regular artifact read-only")
                .into()
        }

        fn preopened_control(path: &Path) -> OwnedFd {
            OpenOptions::new()
                .read(true)
                .write(true)
                .open(path)
                .expect("trusted test provider should open the known regular control read-write")
                .into()
        }

        fn preopened_with_status_flag(path: &Path, flag: libc::c_int) -> OwnedFd {
            rustix::fs::open(
                path,
                rustix::fs::OFlags::from_bits_retain(flag.unsigned_abs())
                    | rustix::fs::OFlags::CLOEXEC,
                rustix::fs::Mode::empty(),
            )
            .expect("trusted test provider should open the status-flag fixture")
        }

        fn digest(bytes: &[u8]) -> [u8; 32] {
            Sha256::digest(bytes).into()
        }

        fn immutable_expectation(bytes: &[u8]) -> GenerationFileExpectation {
            GenerationFileExpectation::immutable(
                u64::try_from(bytes.len()).expect("fixture length should fit u64"),
                digest(bytes),
            )
            .expect("small fixture expectation should be accepted")
        }

        fn confined(path: &str) -> ConfinedGenerationPath {
            ConfinedGenerationPath::parse(Path::new(path))
                .expect("static relative APFS fixture path should parse")
        }

        fn injected(stage: GenerationRootStage) -> GenerationRootError {
            GenerationRootError::new(GenerationRootErrorKind::Io, stage)
        }

        #[test]
        fn named_anchor_preopened_guard_binds_exact_tuple_and_advances_authority() {
            let lock_bytes = b"lock-v1!";
            let (root_path, lock_path, authority_path, layout) =
                named_root_fixture("named-anchor-preopened", lock_bytes, 0x31);
            let root = admit_named_root(&root_path, &lock_path, &authority_path, layout);
            assert_eq!(
                root.read_guard()
                    .expect_err("Apple Silicon must require a fresh provider-owned LOCK open")
                    .kind(),
                GenerationRootErrorKind::PreopenedDescriptorRequired
            );
            let first = root
                .read_guard_preopened(preopened_control(&lock_path))
                .expect("the first provider-owned shared guard should acquire");
            assert_eq!(first.lock_bytes(), lock_bytes);
            assert!(first.authority_bytes().iter().all(|byte| *byte == 0x31));
            first.release().expect("the unchanged guard should release");

            let replacement = authority_image(0x42);
            rewrite_control_file(&authority_path, &replacement);
            root.revalidate()
                .expect("same-inode fixed-length AUTHORITY advancement should remain admissible");
            let second = root
                .read_guard_preopened(preopened_control(&lock_path))
                .expect("the next provider-owned shared guard should acquire");
            assert_eq!(second.authority_bytes(), replacement);
            second.release().expect("the advanced guard should release");
        }

        #[test]
        fn preopened_shared_guards_coexist_and_exclude_a_fresh_exclusive_open() {
            let (root_path, lock_path, authority_path, layout) =
                named_root_fixture("named-anchor-preopened-contention", b"lock-v1!", 0x53);
            let root = admit_named_root(&root_path, &lock_path, &authority_path, layout);
            let first = root
                .read_guard_preopened(preopened_control(&lock_path))
                .expect("the first provider-owned reader should acquire");
            let second = root
                .read_guard_preopened(preopened_control(&lock_path))
                .expect("the second provider-owned reader should coexist");
            assert_eq!(
                root.try_exclusive_anchor_guard_preopened(preopened_control(&lock_path))
                    .expect_err("a fresh exclusive open must contend with active readers")
                    .kind(),
                GenerationRootErrorKind::LockContended
            );
            second.release().expect("the second reader should release");
            first.release().expect("the first reader should release");
            root.try_exclusive_anchor_guard_preopened(preopened_control(&lock_path))
                .expect("the exclusive guard should acquire after both readers release")
                .release()
                .expect("the exclusive guard should release");
        }

        #[test]
        fn preopened_named_anchor_hardlink_alias_and_ancestor_acls_fail_closed() {
            let alias_root = fixture_root("named-anchor-preopened-alias");
            let shared = authority_image(0x64);
            let lock_path = control_file(&alias_root, "LOCK", &shared);
            let authority_path = alias_root.join("AUTHORITY");
            fs::hard_link(&lock_path, &authority_path)
                .expect("the hostile APFS hard-link alias should be creatable");
            set_empty_acl(&authority_path);
            let error = NamedGenerationRoot::admit_preopened(
                &alias_root,
                GenerationRootAnchorLayout::new(GENERATION_ROOT_AUTHORITY_FILE_BYTES)
                    .expect("the alias layout is bounded"),
                PreopenedGenerationRootAnchors::new(
                    preopened_control(&lock_path),
                    preopened_control(&authority_path),
                ),
            )
            .expect_err("LOCK and AUTHORITY must never alias one inode");
            assert_eq!(error.kind(), GenerationRootErrorKind::HardLinked);

            for (label, allow) in [("allow", true), ("deny", false)] {
                let ancestor = fixture_root(&format!("absolute-ancestor-acl-{label}"));
                let root_path = private_dir(&ancestor, "root");
                set_non_empty_acl(&ancestor, allow);
                assert_eq!(
                    QualifiedGenerationRoot::admit(&root_path)
                        .expect_err("every non-empty APFS ancestor ACL must fail")
                        .kind(),
                    GenerationRootErrorKind::AclRejected
                );
            }
        }

        #[test]
        fn preopened_guard_release_detects_live_authority_mutation_and_unlocks() {
            let (root_path, lock_path, authority_path, layout) =
                named_root_fixture("named-anchor-preopened-live-mutation", b"lock-v1!", 0x71);
            let root = admit_named_root(&root_path, &lock_path, &authority_path, layout);
            let guard = root
                .read_guard_preopened(preopened_control(&lock_path))
                .expect("the provider-owned shared guard should acquire");
            let captured = guard.authority_bytes_arc();
            rewrite_control_file(&authority_path, &authority_image(0x72));
            assert!(
                captured.iter().all(|byte| *byte == 0x71),
                "the live guard must retain its immutable APFS authority image"
            );
            let error = guard
                .release()
                .expect_err("ambient APFS authority mutation must invalidate release");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::ReleaseLock);
            root.try_exclusive_anchor_guard_preopened(preopened_control(&lock_path))
                .expect("failed validation must still release the provider-owned flock")
                .release()
                .expect("the post-failure exclusive guard should release");
        }

        #[test]
        fn preopened_double_capture_rejects_content_drift_and_route_replacement() {
            let (drift_root, drift_lock, drift_authority, drift_layout) =
                named_root_fixture("named-anchor-preopened-double-drift", b"lock-v1!", 0x81);
            let root = admit_named_root(&drift_root, &drift_lock, &drift_authority, drift_layout);
            let replacement = authority_image(0x82);
            let mut exact_reads = 0_u8;
            let mut injected = false;
            let drift_hook = install_test_hook(move |boundary| {
                if boundary == TestBoundary::AfterExactRead {
                    exact_reads = exact_reads.saturating_add(1);
                } else if exact_reads >= 4
                    && !injected
                    && matches!(boundary, TestBoundary::BeforeRootComponentOpen { .. })
                {
                    rewrite_control_file(&drift_authority, &replacement);
                    injected = true;
                }
                Ok(())
            });
            let drift_error = root
                .read_guard_preopened(preopened_control(&drift_lock))
                .expect_err("APFS authority drift between captures must fail");
            assert_eq!(drift_error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                drift_error.stage(),
                GenerationRootStage::AcquireLock,
                "the completed first image and later image must disagree at the guard boundary"
            );
            drop(drift_hook);

            let (route_root, route_lock, route_authority, route_layout) =
                named_root_fixture("named-anchor-preopened-route-swap", b"lock-v1!", 0x91);
            let route = admit_named_root(&route_root, &route_lock, &route_authority, route_layout);
            let retained = route_root.join("AUTHORITY-retained");
            let hook_root = route_root.clone();
            let mut route_reads = 0_u8;
            let mut injected = false;
            let route_hook = install_test_hook(move |boundary| {
                if boundary == TestBoundary::AfterExactRead {
                    route_reads = route_reads.saturating_add(1);
                } else if route_reads >= 4
                    && !injected
                    && matches!(boundary, TestBoundary::BeforeRootComponentOpen { .. })
                {
                    fs::rename(&route_authority, &retained)
                        .expect("the original APFS authority should move aside");
                    control_file(&hook_root, "AUTHORITY", &authority_image(0x92));
                    injected = true;
                }
                Ok(())
            });
            assert_eq!(
                route
                    .read_guard_preopened(preopened_control(&route_lock))
                    .expect_err("APFS authority route replacement between captures must fail")
                    .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            drop(route_hook);
        }

        #[test]
        fn absolute_ancestor_acl_mutation_inside_darwin_ctime_sandwich_is_rejected() {
            let ancestor = fixture_root("absolute-ancestor-acl-sandwich");
            let root_path = private_dir(&ancestor, "root");
            let ancestor_index = ancestor.components().count().saturating_sub(2);
            let hook_ancestor = ancestor.clone();
            let mut mutated = false;
            let hook = install_test_hook(move |boundary| {
                if !mutated
                    && boundary
                        == (TestBoundary::AfterAbsoluteAncestorAclRead {
                            index: Some(ancestor_index),
                        })
                {
                    set_non_empty_acl(&hook_ancestor, true);
                    mutated = true;
                }
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("an ACL inserted after the Darwin probe must trip the ctime fence");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                error.component_index(),
                Some(u16::try_from(ancestor_index).expect("fixture depth fits u16"))
            );
            drop(hook);
        }

        #[test]
        fn physical_apfs_empty_acl_exact_names_locks_and_fullsync_succeed() {
            let root_path = fixture_root("physical-success");
            let generation = private_dir(&root_path, "Generation");
            let contents = b"physical APFS generation";
            let artifact_path = private_file(&generation, "Vector.fsvi", contents);
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            assert_eq!(root.witness().filesystem(), QualifiedFilesystem::AppleApfs);
            let admitted = root
                .admit_preopened_file(
                    &confined("Generation/Vector.fsvi"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(contents),
                )
                .expect("empty-ACL exact-case immutable APFS file should qualify");
            assert_eq!(admitted.as_bytes(), contents);
            admitted
                .sync_durable()
                .expect("retained APFS regular file must support F_FULLFSYNC");

            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("empty-ACL APFS control file should qualify");
            assert_eq!(control.bytes().as_ref(), b"lock-v1!");
            assert_eq!(control.sha256(), digest(b"lock-v1!"));
            let lock = control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("APFS control-file flock should succeed");
            assert_eq!(lock.witness(), control.witness());
            assert_eq!(lock.bytes().as_ref(), b"lock-v1!");
            assert_eq!(lock.sha256(), control.sha256());
            assert_eq!(lock.mode(), GenerationRootLockMode::Exclusive);
            lock.sync_durable()
                .expect("locked APFS control file must support F_FULLFSYNC");
            lock.unlock()
                .expect("APFS control-file unlock should succeed");
            root.sync_directory_durable()
                .expect("retained APFS directory must support F_FULLFSYNC");

            assert_eq!(
                root.admit_preopened_file(
                    &confined("generation/Vector.fsvi"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(contents),
                )
                .expect_err("case-folded ancestor spelling must fail even on insensitive APFS")
                .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
            assert_eq!(
                root.admit_preopened_file(
                    &confined("Generation/vector.fsvi"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(contents),
                )
                .expect_err("case-folded final spelling must fail even on insensitive APFS")
                .kind(),
                GenerationRootErrorKind::ObjectChanged
            );

            let decomposed_name = "e\u{301}.fsvi";
            let decomposed_path = private_file(&generation, decomposed_name, b"unicode");
            assert_eq!(
                root.admit_preopened_file(
                    &confined("Generation/\u{e9}.fsvi"),
                    preopened_immutable(&decomposed_path),
                    immutable_expectation(b"unicode"),
                )
                .expect_err("canonically equivalent but byte-distinct spelling must fail")
                .kind(),
                GenerationRootErrorKind::ObjectChanged
            );
        }

        #[test]
        fn macos_independent_lock_contention_and_creator_release_survive_aliases_and_failures() {
            let root_path = fixture_root("lock-lifecycle");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("empty-ACL APFS control should qualify");

            let shared_one = control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Shared,
                )
                .expect("first independent shared lock should succeed");
            let shared_two = control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Shared,
                )
                .expect("second independent shared lock should succeed");
            let contention_boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&contention_boundaries);
            let contention_hook = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let contention_error = control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect_err("an independent exclusive lock must contend with shared locks");
            assert_eq!(
                contention_error.kind(),
                GenerationRootErrorKind::LockContended
            );
            let observed = contention_boundaries
                .lock()
                .expect("boundary log should lock");
            assert!(observed.contains(&TestBoundary::BeforeLock));
            assert!(
                !observed
                    .iter()
                    .any(|boundary| matches!(boundary, TestBoundary::BeforeRead { .. })),
                "a contended APFS lock must return before descriptor content is inspected"
            );
            drop(observed);
            drop(contention_hook);
            drop(shared_one);
            shared_two
                .unlock()
                .expect("the second independent shared lock should release");

            let drop_candidate = preopened_control(&lock_path);
            let surviving_drop_alias = rustix::io::fcntl_dupfd_cloexec(&drop_candidate, 0)
                .expect("the regression fixture should retain a known duplicate");
            let dropped = control
                .try_lock_preopened(drop_candidate, GenerationRootLockMode::Exclusive)
                .expect("the aliased candidate should acquire under the trusted-provider contract");
            drop(dropped);
            control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("creator Drop must explicitly unlock despite a surviving alias")
                .unlock()
                .expect("fresh contender after Drop should release");
            drop(surviving_drop_alias);

            let explicit_candidate = preopened_control(&lock_path);
            let surviving_explicit_alias = rustix::io::fcntl_dupfd_cloexec(&explicit_candidate, 0)
                .expect("the explicit-unlock fixture should retain a known duplicate");
            control
                .try_lock_preopened(explicit_candidate, GenerationRootLockMode::Exclusive)
                .expect("the explicit-unlock fixture should acquire")
                .unlock()
                .expect("explicit unlock should disarm creator Drop deterministically");
            control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("explicit LOCK_UN must release despite a surviving alias")
                .unlock()
                .expect("fresh contender after explicit unlock should release");
            drop(surviving_explicit_alias);

            let failed_candidate = preopened_control(&lock_path);
            let surviving_failure_alias = rustix::io::fcntl_dupfd_cloexec(&failed_candidate, 0)
                .expect("the post-flock failure fixture should retain a known duplicate");
            let hook = install_test_hook(|boundary| {
                if boundary == TestBoundary::AfterLock {
                    return Err(injected(GenerationRootStage::AcquireLock));
                }
                Ok(())
            });
            assert_eq!(
                control
                    .try_lock_preopened(failed_candidate, GenerationRootLockMode::Exclusive)
                    .expect_err("injected post-flock failure must fail")
                    .kind(),
                GenerationRootErrorKind::Io
            );
            drop(hook);
            control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("provisional RAII must unlock after post-flock failure despite an alias")
                .unlock()
                .expect("fresh contender after injected failure should release");
            drop(surviving_failure_alias);
        }

        #[test]
        fn macos_path_final_admission_requires_preopened_capabilities_before_any_io_boundary() {
            let root_path = fixture_root("path-requires-preopened");
            let artifact_path = private_file(&root_path, "artifact", b"sealed");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("trusted preopened control should qualify");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            for error in [
                root.admit_file(&confined("artifact"), immutable_expectation(b"sealed"))
                    .expect_err("path artifact admission must require external provenance"),
                root.admit_control_file(
                    &confined("LOCK"),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect_err("path control admission must require external provenance"),
            ] {
                assert_eq!(
                    error.kind(),
                    GenerationRootErrorKind::PreopenedDescriptorRequired
                );
                assert_eq!(error.stage(), GenerationRootStage::OpenRegularFile);
            }
            let lock_error = control
                .try_lock(GenerationRootLockMode::Exclusive)
                .expect_err("path lock acquisition must require a fresh provider descriptor");
            assert_eq!(
                lock_error.kind(),
                GenerationRootErrorKind::PreopenedDescriptorRequired
            );
            assert_eq!(lock_error.stage(), GenerationRootStage::AcquireLock);
            assert!(
                boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .is_empty(),
                "typed path rejection must precede revalidation, open, read, flock, ACL, and sync"
            );
            assert!(
                artifact_path.exists(),
                "the known regular fixture remains intact"
            );
        }

        #[test]
        fn macos_forked_capabilities_reject_before_provider_descriptor_inspection() {
            let root_path = fixture_root("forked-preopened");
            let artifact_path = private_file(&root_path, "artifact", b"sealed");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let mut root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            set_root_creator_process_id_for_test(
                &mut root.inner,
                std::process::id().wrapping_add(1),
            );
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let artifact_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    File::open(&root_path)
                        .expect("the precedence fixture directory should open")
                        .into(),
                    immutable_expectation(b"sealed"),
                )
                .expect_err(
                    "ForkedProcess must outrank the supplied directory's NotRegularFile error",
                );
            assert_eq!(
                artifact_error.kind(),
                GenerationRootErrorKind::ForkedProcess
            );
            assert_eq!(artifact_error.stage(), GenerationRootStage::OpenRegularFile);
            let control_error = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_immutable(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect_err(
                    "ForkedProcess must outrank the read-only fd's InvalidDescriptorAccess error",
                );
            assert_eq!(control_error.kind(), GenerationRootErrorKind::ForkedProcess);
            assert_eq!(control_error.stage(), GenerationRootStage::OpenRegularFile);
            assert!(
                boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .is_empty(),
                "creator-process rejection must precede provider-fd inspection and every I/O \
                 boundary"
            );
            drop(guard);

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("fresh APFS root should qualify");
            let mut control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("fresh control should qualify");
            drop(root);
            set_control_root_creator_process_id_for_test(
                &mut control.inner,
                std::process::id().wrapping_add(1),
            );
            let lock_boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_lock_boundaries = Arc::clone(&lock_boundaries);
            let _lock_guard = install_test_hook(move |boundary| {
                hook_lock_boundaries
                    .lock()
                    .expect("lock boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let lock_error = control
                .try_lock_preopened(
                    preopened_immutable(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect_err(
                    "ForkedProcess must outrank the lock fd's InvalidDescriptorAccess error",
                );
            assert_eq!(lock_error.kind(), GenerationRootErrorKind::ForkedProcess);
            assert_eq!(lock_error.stage(), GenerationRootStage::AcquireLock);
            assert!(
                lock_boundaries
                    .lock()
                    .expect("lock boundary log should lock")
                    .is_empty(),
                "creator-process rejection must precede lock-candidate inspection, ACL, content, \
                 and flock"
            );
            assert!(
                artifact_path.exists(),
                "the known regular fixture must remain intact"
            );
        }

        #[test]
        fn macos_preopened_type_access_and_cloexec_gates_precede_content_and_lock_operations() {
            let root_path = fixture_root("preopened-gates");
            let artifact_path = private_file(&root_path, "artifact", b"sealed");
            let execute_path = private_file(&root_path, "execute-artifact", b"sealed");
            fs::set_permissions(&execute_path, fs::Permissions::from_mode(0o500))
                .expect("O_EXEC fixture must be owner-executable");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let fifo_path = root_path.join("fifo");
            let fifo_status = Command::new("/usr/bin/mkfifo")
                .arg("-m")
                .arg("600")
                .arg(&fifo_path)
                .status()
                .expect("macOS mkfifo should start for the special-file fixture");
            assert!(
                fifo_status.success(),
                "macOS mkfifo should create the special-file fixture"
            );
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });

            let fifo: OwnedFd = OpenOptions::new()
                .read(true)
                .custom_flags(libc::O_NONBLOCK)
                .open(&fifo_path)
                .expect("trusted provider should supply the FIFO descriptor for rejection")
                .into();
            let fifo_error = root
                .admit_preopened_control_file(
                    &confined("fifo"),
                    fifo,
                    GenerationFileExpectation::control(0)
                        .expect("zero-length control expectation should be accepted"),
                )
                .expect_err("a supplied FIFO must fail at the first fstat type gate");
            assert_eq!(fifo_error.kind(), GenerationRootErrorKind::NotRegularFile);

            let device: OwnedFd = File::open("/dev/null")
                .expect("trusted provider should supply a real device descriptor for rejection")
                .into();
            let device_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    device,
                    immutable_expectation(b"sealed"),
                )
                .expect_err("a supplied device must fail at the first fstat type gate");
            assert_eq!(device_error.kind(), GenerationRootErrorKind::NotRegularFile);

            fs::set_permissions(&artifact_path, fs::Permissions::from_mode(0o600))
                .expect("fixture should become writable before the provider opens the wrong mode");
            let wrong_artifact_access: OwnedFd = OpenOptions::new()
                .read(true)
                .write(true)
                .open(&artifact_path)
                .expect("trusted provider should supply a deliberately wrong access mode")
                .into();
            fs::set_permissions(&artifact_path, fs::Permissions::from_mode(0o400))
                .expect("fixture should be resealed before library admission");
            let access_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    wrong_artifact_access,
                    immutable_expectation(b"sealed"),
                )
                .expect_err("immutable admission requires an exactly read-only descriptor");
            assert_eq!(
                access_error.kind(),
                GenerationRootErrorKind::InvalidDescriptorAccess
            );

            let wrong_control_access = preopened_immutable(&lock_path);
            let control_access_error = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    wrong_control_access,
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect_err("control admission requires an exactly read-write descriptor");
            assert_eq!(
                control_access_error.kind(),
                GenerationRootErrorKind::InvalidDescriptorAccess
            );

            let missing_cloexec = preopened_immutable(&artifact_path);
            rustix::io::fcntl_setfd(&missing_cloexec, rustix::io::FdFlags::empty())
                .expect("test provider should clear close-on-exec");
            let cloexec_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    missing_cloexec,
                    immutable_expectation(b"sealed"),
                )
                .expect_err("missing FD_CLOEXEC must fail before route or content work");
            assert_eq!(
                cloexec_error.kind(),
                GenerationRootErrorKind::CloseOnExecRequired
            );

            let event_only_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_with_status_flag(&artifact_path, libc::O_EVTONLY),
                    immutable_expectation(b"sealed"),
                )
                .expect_err("O_EVTONLY is not a data-readable descriptor");
            assert_eq!(
                event_only_error.kind(),
                GenerationRootErrorKind::InvalidDescriptorAccess
            );

            let execute_only_error = root
                .admit_preopened_file(
                    &confined("execute-artifact"),
                    preopened_with_status_flag(&execute_path, libc::O_EXEC),
                    immutable_expectation(b"sealed"),
                )
                .expect_err("O_EXEC is not a data-readable descriptor");
            assert_eq!(
                execute_only_error.kind(),
                GenerationRootErrorKind::InvalidDescriptorAccess
            );

            let observed = boundaries.lock().expect("boundary log should lock");
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::BeforeRead { .. }
                        | TestBoundary::BeforeLock
                        | TestBoundary::BeforeFileSync
                        | TestBoundary::BeforeAclRead
                        | TestBoundary::BeforeFinalRouteStat
                )),
                "type/access/status/CLOEXEC rejection must precede ACL, route, content, flock, and sync"
            );
            drop(observed);
            drop(guard);
        }

        #[test]
        fn macos_preopened_lock_candidate_rejects_persistent_fwaslocked_history_before_io() {
            const DARWIN_FWASLOCKED: u32 = 0x0000_4000;

            let root_path = fixture_root("preopened-fwaslocked-history");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("fresh control descriptor should qualify");
            let candidate = preopened_control(&lock_path);
            rustix::fs::flock(
                &candidate,
                rustix::fs::FlockOperation::NonBlockingLockExclusive,
            )
            .expect("the fresh candidate should take an uncontended kernel flock");
            rustix::fs::flock(&candidate, rustix::fs::FlockOperation::Unlock)
                .expect("the fixture should explicitly unlock before admission");
            let observed_status =
                rustix::fs::fcntl_getfl(&candidate).expect("candidate status flags should load");
            assert!(
                observed_status.contains(rustix::fs::OFlags::from_bits_retain(DARWIN_FWASLOCKED)),
                "Darwin must expose the kernel-private FWASLOCKED history bit after successful \
                 flock plus unlock"
            );

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let error = control
                .try_lock_preopened(candidate, GenerationRootLockMode::Exclusive)
                .expect_err("a candidate with prior flock history is not fresh");
            assert_eq!(
                error.kind(),
                GenerationRootErrorKind::InvalidDescriptorAccess
            );
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            assert!(
                boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .is_empty(),
                "exact status validation must reject before preopened qualification, ACL, route, \
                 content, or flock boundaries"
            );
        }

        #[test]
        fn macos_preopened_route_binding_rejects_siblings_and_post_admission_substitution() {
            let root_path = fixture_root("preopened-route-binding");
            let artifact_path = private_file(&root_path, "artifact", b"artifact");
            let sibling_path = private_file(&root_path, "sibling", b"sibling!");
            let lock_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");

            let sibling_error = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_immutable(&sibling_path),
                    immutable_expectation(b"sibling!"),
                )
                .expect_err("a valid sibling descriptor must not satisfy another route");
            assert_eq!(sibling_error.kind(), GenerationRootErrorKind::ObjectChanged);

            let admitted = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(b"artifact"),
                )
                .expect("the exact descriptor and route should qualify");
            fs::rename(&artifact_path, root_path.join("artifact-original"))
                .expect("the admitted artifact should move to a retained route");
            private_file(&root_path, "artifact", b"artifact");
            let file_error = admitted
                .sync_durable()
                .expect_err("route substitution must fence retained-descriptor sync");
            assert_eq!(file_error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(
                file_error.stage(),
                GenerationRootStage::RevalidateRegularFile
            );

            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("the exact control descriptor and route should qualify");
            let fresh_lock_descriptor = preopened_control(&lock_path);
            fs::rename(&lock_path, root_path.join("LOCK-original"))
                .expect("the admitted control should move to a retained route");
            control_file(&root_path, "LOCK", b"lock-v1!");
            let lock_reached = Arc::new(Mutex::new(false));
            let hook_lock_reached = Arc::clone(&lock_reached);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeLock {
                    *hook_lock_reached.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            let error = control
                .try_lock_preopened(fresh_lock_descriptor, GenerationRootLockMode::Exclusive)
                .expect_err("route substitution must fence the fresh lock descriptor");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::RevalidateRegularFile);
            assert!(
                !*lock_reached.lock().expect("hook state should lock"),
                "route revalidation must reject before flock"
            );
        }

        #[test]
        fn macos_absolute_root_route_rejects_ancestor_and_final_symlinks() {
            let container = fixture_root("absolute-symlink-container");
            let target_parent = fixture_root("absolute-symlink-target-parent");
            let target_root = private_dir(&target_parent, "qualified-root");
            let ancestor_link = container.join("ancestor-link");
            let final_link = container.join("final-link");
            symlink(&target_parent, &ancestor_link)
                .expect("absolute-route ancestor symlink should be creatable");
            symlink(&target_root, &final_link)
                .expect("absolute-route final symlink should be creatable");

            assert_eq!(
                QualifiedGenerationRoot::admit(&ancestor_link.join("qualified-root"))
                    .expect_err("an absolute-route ancestor symlink must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
            assert_eq!(
                QualifiedGenerationRoot::admit(&final_link)
                    .expect_err("an absolute-route final symlink must fail")
                    .kind(),
                GenerationRootErrorKind::SymbolicLink
            );
        }

        #[test]
        fn macos_preopened_rejects_ancestor_and_final_symlinks_without_touching_decoys() {
            let root_path = fixture_root("preopened-symlink-routes");
            let decoy_directory = private_dir(&root_path, "decoy-directory");
            let ancestor_target =
                private_file(&decoy_directory, "artifact", b"ancestor decoy stays exact");
            let final_target = private_file(&root_path, "final-target", b"final decoy stays exact");
            symlink(&decoy_directory, root_path.join("ancestor-link"))
                .expect("ancestor symlink should be creatable");
            symlink(&final_target, root_path.join("final-link"))
                .expect("final symlink should be creatable");

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let _hook = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("symlink boundary log should lock")
                    .push(boundary);
                Ok(())
            });
            let ancestor_error = root
                .admit_preopened_file(
                    &confined("ancestor-link/artifact"),
                    preopened_immutable(&ancestor_target),
                    immutable_expectation(b"ancestor decoy stays exact"),
                )
                .expect_err("an ancestor symlink must not bind a trusted descriptor");
            assert_eq!(ancestor_error.kind(), GenerationRootErrorKind::SymbolicLink);
            assert_eq!(ancestor_error.component_index(), Some(0));

            let final_error = root
                .admit_preopened_file(
                    &confined("final-link"),
                    preopened_immutable(&final_target),
                    immutable_expectation(b"final decoy stays exact"),
                )
                .expect_err("a final symlink must not bind a trusted descriptor");
            assert_eq!(final_error.kind(), GenerationRootErrorKind::SymbolicLink);
            assert_eq!(final_error.component_index(), Some(0));

            let observed = boundaries.lock().expect("symlink boundary log should lock");
            assert!(
                !observed.iter().any(|boundary| matches!(
                    boundary,
                    TestBoundary::BeforeRead { .. }
                        | TestBoundary::BeforeTrailingByteProbe
                        | TestBoundary::AfterExactRead
                )),
                "route-bound symlink rejection must precede every content-read boundary"
            );
            drop(observed);

            assert_eq!(
                fs::read(&ancestor_target).expect("ancestor decoy should remain readable"),
                b"ancestor decoy stays exact"
            );
            assert_eq!(
                fs::read(&final_target).expect("final decoy should remain readable"),
                b"final decoy stays exact"
            );
        }

        #[test]
        fn macos_immutable_content_drift_fences_sync_before_durability() {
            let root_path = fixture_root("mapped-immutable-before-sync");
            let (artifact_path, mapping) = mapped_immutable_file(&root_path, "artifact");
            let admitted_bytes =
                fs::read(&artifact_path).expect("mapped APFS immutable fixture must be readable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let admitted = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(&admitted_bytes),
                )
                .expect("mapped APFS immutable fixture should qualify before ambient mutation");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared APFS immutable mapping must remain retained"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = admitted
                .sync_durable()
                .expect_err("pre-durability APFS immutable content drift must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            assert!(
                !boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .contains(&TestBoundary::BeforeFileSync),
                "APFS immutable validation must fail before F_FULLFSYNC"
            );
        }

        #[test]
        fn macos_immutable_content_drift_during_durability_is_detected_after_barrier() {
            let root_path = fixture_root("mapped-immutable-during-sync");
            let (artifact_path, mapping) = mapped_immutable_file(&root_path, "artifact");
            let admitted_bytes =
                fs::read(&artifact_path).expect("mapped APFS immutable fixture must be readable");
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let admitted = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(&admitted_bytes),
                )
                .expect("mapped APFS immutable fixture should qualify before ambient mutation");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == TestBoundary::BeforeFileSync {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared APFS immutable mapping must remain retained"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = admitted
                .sync_durable()
                .expect_err("APFS immutable mutation at durability must fail after the barrier");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            let observed = boundaries.lock().expect("boundary log should lock");
            let after_sync = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::AfterFileSync)
                .expect("F_FULLFSYNC should complete before post-check failure");
            assert!(
                observed.iter().enumerate().any(|(index, boundary)| {
                    index > after_sync && *boundary == (TestBoundary::BeforeRead { offset: 0 })
                }),
                "a second exact APFS immutable read must follow F_FULLFSYNC"
            );
            drop(observed);
        }

        #[test]
        fn macos_control_without_caller_digest_rejects_preheld_mapping_mutation_after_flock() {
            let root_path = fixture_root("mapped-control-after-flock");
            let (lock_path, mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped APFS control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let expectation = GenerationFileExpectation::control(byte_len)
                .expect("mapped APFS control fixture length should be accepted");
            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    expectation,
                )
                .expect("mapped APFS control fixture should qualify before ambient mutation");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut locked = false;
            let mut mutated = false;
            let guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if boundary == TestBoundary::AfterLock {
                    locked = true;
                }
                if locked && !mutated && boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared APFS mapping should remain retained by the hook"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = control
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect_err("post-flock APFS mapped mutation must invalidate the bound image");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::AcquireLock);
            let observed = boundaries.lock().expect("boundary log should lock");
            let before_lock = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::BeforeLock)
                .expect("flock attempt boundary should be observed");
            let after_lock = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::AfterLock)
                .expect("successful flock boundary should be observed");
            let first_locked_read = observed
                .iter()
                .enumerate()
                .find_map(|(index, boundary)| {
                    (index > after_lock && *boundary == (TestBoundary::BeforeRead { offset: 0 }))
                        .then_some(index)
                })
                .expect("post-flock content validation should read the descriptor");
            assert!(before_lock < after_lock && after_lock < first_locked_read);
            drop(observed);
            drop(guard);

            let fresh = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    expectation,
                )
                .expect("the mutated APFS image should support a fresh bound admission");
            fresh
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("failed validation must not leak the APFS kernel flock")
                .unlock()
                .expect("fresh APFS lock should release cleanly");
        }

        #[test]
        fn macos_control_content_drift_fences_sync_before_durability() {
            let root_path = fixture_root("mapped-control-before-sync");
            let (lock_path, mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped APFS control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let lock = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(byte_len)
                        .expect("mapped APFS control fixture length should be accepted"),
                )
                .expect("mapped APFS control fixture should qualify")
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("mapped APFS control fixture should lock");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == (TestBoundary::BeforeRead { offset: 0 }) {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared APFS mapping should remain retained by the hook"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = lock
                .sync_durable()
                .expect_err("pre-durability APFS content drift must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            assert!(
                !boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .contains(&TestBoundary::BeforeFileSync),
                "APFS content validation must fail before the durability syscall"
            );
        }

        #[test]
        fn macos_control_content_drift_during_durability_is_detected_after_barrier() {
            let root_path = fixture_root("mapped-control-during-sync");
            let (lock_path, mapping) = mapped_control_file(&root_path, "LOCK");
            let byte_len = fs::metadata(&lock_path)
                .expect("mapped APFS control fixture metadata should load")
                .len();
            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let lock = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(byte_len)
                        .expect("mapped APFS control fixture length should be accepted"),
                )
                .expect("mapped APFS control fixture should qualify")
                .try_lock_preopened(
                    preopened_control(&lock_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("mapped APFS control fixture should lock");

            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let mut mapping = Some(mapping);
            let mut mutated = false;
            let _guard = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("boundary log should lock")
                    .push(boundary);
                if !mutated && boundary == TestBoundary::BeforeFileSync {
                    mutate_mapping(
                        mapping
                            .as_mut()
                            .expect("shared APFS mapping should remain retained by the hook"),
                    );
                    mutated = true;
                }
                Ok(())
            });
            let error = lock
                .sync_durable()
                .expect_err("APFS mutation at durability must fail after the barrier");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert_eq!(error.stage(), GenerationRootStage::SyncRegularFile);
            let observed = boundaries.lock().expect("boundary log should lock");
            let after_sync = observed
                .iter()
                .position(|boundary| *boundary == TestBoundary::AfterFileSync)
                .expect("the APFS durability barrier should complete before post-check failure");
            assert!(
                observed.iter().enumerate().any(|(index, boundary)| {
                    index > after_sync && *boundary == (TestBoundary::BeforeRead { offset: 0 })
                }),
                "a second exact APFS content read must follow the durability barrier"
            );
            drop(observed);
        }

        #[test]
        fn physical_apfs_rejects_every_non_empty_allow_or_deny_acl() {
            for (label, allow) in [("allow-acl", true), ("deny-acl", false)] {
                let root_path = fixture_root(label);
                set_non_empty_acl(&root_path, allow);

                let error = QualifiedGenerationRoot::admit(&root_path)
                    .expect_err("every non-empty APFS ACL must fail closed");
                assert_eq!(error.kind(), GenerationRootErrorKind::AclRejected);
                assert_eq!(error.stage(), GenerationRootStage::InspectAcl);
                assert!(
                    error.to_string().contains("descriptor-bound absence"),
                    "operator diagnostic must explain the descriptor-bound fail-closed policy"
                );
            }
        }

        #[test]
        fn physical_apfs_acl_add_remove_cycle_rejects_then_admits_same_root() {
            let root_path = fixture_root("acl-add-remove-cycle");
            set_non_empty_acl(&root_path, true);

            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("the ACL-bearing APFS root must fail closed");
            assert_eq!(error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(error.stage(), GenerationRootStage::InspectAcl);

            set_empty_acl(&root_path);
            QualifiedGenerationRoot::admit(&root_path)
                .expect("the same APFS root must qualify after its ACL is removed");
        }

        #[test]
        fn physical_apfs_rejects_acl_bearing_artifact_control_and_lock_targets() {
            let artifact_root = fixture_root("artifact-target-acl");
            let artifact_path = private_file(&artifact_root, "artifact", b"sealed");
            set_non_empty_acl(&artifact_path, true);
            let artifact_generation = QualifiedGenerationRoot::admit(&artifact_root)
                .expect("the empty-ACL APFS root should qualify");
            assert_eq!(
                artifact_generation
                    .admit_preopened_file(
                        &confined("artifact"),
                        preopened_immutable(&artifact_path),
                        immutable_expectation(b"sealed"),
                    )
                    .expect_err("an ACL-bearing artifact descriptor must fail")
                    .kind(),
                GenerationRootErrorKind::AclRejected
            );

            let control_root = fixture_root("control-target-acl");
            let control_path = control_file(&control_root, "LOCK", b"lock-v1!");
            set_non_empty_acl(&control_path, true);
            let control_generation = QualifiedGenerationRoot::admit(&control_root)
                .expect("the empty-ACL APFS root should qualify");
            assert_eq!(
                control_generation
                    .admit_preopened_control_file(
                        &confined("LOCK"),
                        preopened_control(&control_path),
                        GenerationFileExpectation::control(8)
                            .expect("small control expectation should be accepted"),
                    )
                    .expect_err("an ACL-bearing control descriptor must fail")
                    .kind(),
                GenerationRootErrorKind::AclRejected
            );

            let lock_root = fixture_root("lock-target-acl");
            let lock_path = control_file(&lock_root, "LOCK", b"lock-v1!");
            let lock_generation = QualifiedGenerationRoot::admit(&lock_root)
                .expect("the empty-ACL APFS root should qualify");
            let control = lock_generation
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("the empty-ACL control should qualify before target mutation");
            let lock_candidate = preopened_control(&lock_path);
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let hook_lock_path = lock_path.clone();
            let mut mutated = false;
            let _hook = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("hook state should lock")
                    .push(boundary);
                if !mutated && boundary == TestBoundary::BeforePreopenedQualification {
                    set_non_empty_acl(&hook_lock_path, true);
                    mutated = true;
                }
                Ok(())
            });
            assert_eq!(
                control
                    .try_lock_preopened(lock_candidate, GenerationRootLockMode::Exclusive,)
                    .expect_err("the ACL-bearing fresh lock candidate must fail before flock")
                    .kind(),
                GenerationRootErrorKind::AclRejected
            );
            let observed = boundaries.lock().expect("hook state should lock");
            assert!(
                observed.contains(&TestBoundary::BeforePreopenedQualification),
                "the retained control route must revalidate before candidate mutation"
            );
            assert!(
                observed.contains(&TestBoundary::BeforeAclRead),
                "the fresh candidate must reach the descriptor-bound ACL probe"
            );
            assert!(
                !observed.contains(&TestBoundary::BeforeLock),
                "fresh-candidate ACL rejection must precede flock"
            );
            drop(observed);
        }

        #[test]
        fn physical_apfs_rejects_nonzero_flags_on_artifact_control_and_lock_targets() {
            for (label, flag) in [
                ("artifact-immutable-flag", "uchg"),
                ("artifact-nodump-flag", "nodump"),
            ] {
                let root_path = fixture_root(label);
                let artifact_path = private_file(&root_path, "artifact", b"sealed");
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("the zero-flags APFS root should qualify");
                run_chflags(flag, &artifact_path);
                let observed_flags = fs::metadata(&artifact_path)
                    .expect("flagged APFS artifact metadata should load")
                    .st_flags();
                assert_ne!(observed_flags, 0, "chflags must establish the fixture");
                let error = root
                    .admit_preopened_file(
                        &confined("artifact"),
                        preopened_immutable(&artifact_path),
                        immutable_expectation(b"sealed"),
                    )
                    .expect_err("a flagged artifact must be outside the zero-flags profile");
                assert_eq!(
                    error.kind(),
                    GenerationRootErrorKind::UnsupportedObjectFlags
                );
                assert_eq!(error.expected(), Some(0));
                assert_eq!(error.observed(), Some(u64::from(observed_flags)));
            }

            let control_root = fixture_root("control-nodump-flag");
            let control_path = control_file(&control_root, "LOCK", b"lock-v1!");
            let control_generation = QualifiedGenerationRoot::admit(&control_root)
                .expect("the zero-flags APFS root should qualify");
            run_chflags("nodump", &control_path);
            assert_ne!(
                fs::metadata(&control_path)
                    .expect("flagged APFS control metadata should load")
                    .st_flags(),
                0
            );
            assert_eq!(
                control_generation
                    .admit_preopened_control_file(
                        &confined("LOCK"),
                        preopened_control(&control_path),
                        GenerationFileExpectation::control(8)
                            .expect("small control expectation should be accepted"),
                    )
                    .expect_err("a flagged control target must fail")
                    .kind(),
                GenerationRootErrorKind::UnsupportedObjectFlags
            );

            let lock_root = fixture_root("lock-nodump-flag");
            let lock_path = control_file(&lock_root, "LOCK", b"lock-v1!");
            let lock_generation = QualifiedGenerationRoot::admit(&lock_root)
                .expect("the zero-flags APFS root should qualify");
            let control = lock_generation
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&lock_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("the zero-flags control should qualify before target mutation");
            let lock_candidate = preopened_control(&lock_path);
            let boundaries = Arc::new(Mutex::new(Vec::new()));
            let hook_boundaries = Arc::clone(&boundaries);
            let hook_lock_path = lock_path.clone();
            let mut mutated = false;
            let _hook = install_test_hook(move |boundary| {
                hook_boundaries
                    .lock()
                    .expect("hook state should lock")
                    .push(boundary);
                if !mutated && boundary == TestBoundary::BeforePreopenedQualification {
                    run_chflags("nodump", &hook_lock_path);
                    mutated = true;
                }
                Ok(())
            });
            let error = control
                .try_lock_preopened(lock_candidate, GenerationRootLockMode::Exclusive)
                .expect_err("the flagged fresh lock candidate must fail before flock");
            assert_eq!(
                error.kind(),
                GenerationRootErrorKind::UnsupportedObjectFlags
            );
            let observed = boundaries.lock().expect("hook state should lock");
            assert!(
                observed.contains(&TestBoundary::BeforePreopenedQualification),
                "the retained control route must revalidate before candidate mutation"
            );
            assert!(
                !observed.contains(&TestBoundary::BeforeLock),
                "fresh-candidate object-flag rejection must precede flock"
            );
            drop(observed);
        }

        #[test]
        fn physical_apfs_acl_bearing_retained_descriptor_rejects_empty_replacement() {
            let root_path = fixture_root("retained-acl");
            set_non_empty_acl(&root_path, true);
            let displaced = root_path.with_extension("retained-acl-original");
            let canonical = root_path.clone();
            let substituted = Arc::new(Mutex::new(false));
            let hook_substituted = Arc::clone(&substituted);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeAclRead
                    && !*hook_substituted.lock().expect("hook state should lock")
                {
                    fs::rename(&canonical, &displaced)
                        .expect("ACL-bearing root should move to a retained route");
                    DirBuilder::new()
                        .mode(0o700)
                        .create(&canonical)
                        .expect("empty-ACL replacement root should be creatable");
                    fs::set_permissions(&canonical, fs::Permissions::from_mode(0o700))
                        .expect("replacement root mode should be settable");
                    set_empty_acl(&canonical);
                    *hook_substituted.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&root_path).expect_err(
                "the ACL-bearing retained descriptor must reject before route fallback",
            );
            assert_eq!(error.kind(), GenerationRootErrorKind::AclRejected);
            assert_eq!(error.stage(), GenerationRootStage::InspectAcl);
            assert!(*substituted.lock().expect("hook state should lock"));
        }

        #[test]
        fn physical_apfs_empty_retained_descriptor_ignores_acl_bearing_replacement() {
            let root_path = fixture_root("retained-empty-acl");
            let displaced = root_path.with_extension("retained-empty-acl-original");
            let canonical = root_path.clone();
            let substituted = Arc::new(Mutex::new(false));
            let hook_substituted = Arc::clone(&substituted);
            let _guard = install_test_hook(move |boundary| {
                if boundary == TestBoundary::BeforeAclRead
                    && !*hook_substituted.lock().expect("hook state should lock")
                {
                    fs::rename(&canonical, &displaced)
                        .expect("empty-ACL root should move to a retained route");
                    DirBuilder::new()
                        .mode(0o700)
                        .create(&canonical)
                        .expect("replacement root should be creatable");
                    fs::set_permissions(&canonical, fs::Permissions::from_mode(0o700))
                        .expect("replacement root mode should be settable");
                    set_non_empty_acl(&canonical, true);
                    *hook_substituted.lock().expect("hook state should lock") = true;
                }
                Ok(())
            });
            let error = QualifiedGenerationRoot::admit(&root_path)
                .expect_err("canonical route replacement must fail after retained ACL inspection");
            assert_eq!(error.kind(), GenerationRootErrorKind::ObjectChanged);
            assert!(*substituted.lock().expect("hook state should lock"));
        }

        #[test]
        fn physical_apfs_excludes_regular_file_atime_only_drift_and_never_restores_it() {
            let root_path = fixture_root("regular-file-atime-exclusion");
            let artifact_path = private_file(&root_path, "artifact", b"atime");
            let control_path = control_file(&root_path, "LOCK", b"lock-v1!");
            let future_modified = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
            for path in [&artifact_path, &control_path] {
                let timestamp_owner =
                    File::open(path).expect("fixture should open for timestamp setup");
                timestamp_owner
                    .set_times(
                        std::fs::FileTimes::new()
                            .set_accessed(UNIX_EPOCH)
                            .set_modified(future_modified),
                    )
                    .expect(
                        "fixture atime must be old and mtime future-dated before admission so \
                         each physical read remains relatime-eligible",
                    );
            }

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let artifact = root
                .admit_preopened_file(
                    &confined("artifact"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(b"atime"),
                )
                .expect("APFS artifact should qualify");
            let control = root
                .admit_preopened_control_file(
                    &confined("LOCK"),
                    preopened_control(&control_path),
                    GenerationFileExpectation::control(8)
                        .expect("small control expectation should be accepted"),
                )
                .expect("APFS control should qualify");
            let artifact_before = fs::metadata(&artifact_path)
                .expect("artifact metadata should load")
                .accessed()
                .expect("artifact atime should be readable");
            let control_before = fs::metadata(&control_path)
                .expect("control metadata should load")
                .accessed()
                .expect("control atime should be readable");

            std::thread::sleep(Duration::from_millis(20));
            for path in [&artifact_path, &control_path] {
                let mut reader = File::open(path).expect("ambient reader should open");
                let mut byte = [0_u8; 1];
                reader
                    .read_exact(&mut byte)
                    .expect("ambient read should advance atime");
            }
            let artifact_after = fs::metadata(&artifact_path)
                .expect("artifact metadata should reload")
                .accessed()
                .expect("advanced artifact atime should be readable");
            let control_after = fs::metadata(&control_path)
                .expect("control metadata should reload")
                .accessed()
                .expect("advanced control atime should be readable");
            assert!(
                artifact_after > artifact_before,
                "fixture must prove post-admission artifact-atime advancement"
            );
            assert!(
                control_after > control_before,
                "fixture must prove post-admission control-atime advancement"
            );

            artifact
                .sync_durable()
                .expect("APFS artifact atime alone is excluded from the mutation witness");
            control
                .try_lock_preopened(
                    preopened_control(&control_path),
                    GenerationRootLockMode::Exclusive,
                )
                .expect("APFS control atime alone must not fence locking")
                .unlock()
                .expect("atime-only APFS lock should release");
            assert!(
                fs::metadata(&artifact_path)
                    .expect("artifact metadata should remain readable")
                    .accessed()
                    .expect("artifact atime should remain readable")
                    >= artifact_after,
                "validation must never restore the artifact atime"
            );
            assert!(
                fs::metadata(&control_path)
                    .expect("control metadata should remain readable")
                    .accessed()
                    .expect("control atime should remain readable")
                    >= control_after,
                "validation must never restore the control atime"
            );
        }

        #[test]
        fn physical_apfs_excludes_directory_atime_only_drift_and_never_restores_it() {
            let root_path = fixture_root("atime-exclusion");
            private_file(&root_path, "directory-entry", b"atime");
            let timestamp_owner =
                File::open(&root_path).expect("fixture directory should open for timestamp");
            let future_modified = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
            timestamp_owner
                .set_times(
                    std::fs::FileTimes::new()
                        .set_accessed(UNIX_EPOCH)
                        .set_modified(future_modified),
                )
                .expect(
                    "directory atime must be old and mtime future-dated before admission so \
                     each physical readdir remains relatime-eligible",
                );
            drop(timestamp_owner);

            let root =
                QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
            let before = fs::metadata(&root_path)
                .expect("directory metadata should load")
                .accessed()
                .expect("directory atime should be readable");
            let observed_entry = fs::read_dir(&root_path)
                .expect("ambient directory reader should open")
                .next()
                .transpose()
                .expect("ambient directory entry should be readable");
            assert!(
                observed_entry.is_some(),
                "fixture must contain an entry so readdir performs observable work"
            );
            let after = fs::metadata(&root_path)
                .expect("directory metadata should reload")
                .accessed()
                .expect("advanced directory atime should be readable");
            assert!(
                after > before,
                "fixture must prove a post-admission directory-atime advancement"
            );
            root.sync_directory_durable()
                .expect("APFS directory atime alone is excluded from the mutation witness");
            assert_eq!(
                fs::metadata(&root_path)
                    .expect("directory metadata should remain readable")
                    .accessed()
                    .expect("directory atime should remain readable"),
                after,
                "validation must never restore attacker-observed atime"
            );
        }

        #[test]
        fn every_macos_specific_open_acl_and_fullsync_boundary_is_fault_injectable() {
            for target in [
                TestBoundary::BeforeExactNameEnumeration,
                TestBoundary::AfterExactNameEnumeration,
                TestBoundary::BeforeAclRead,
                TestBoundary::AfterAclRead,
            ] {
                let root_path = fixture_root("macos-boundary");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::InspectAcl));
                    }
                    Ok(())
                });
                assert_eq!(
                    QualifiedGenerationRoot::admit(&root_path)
                        .expect_err("injected macOS boundary must fail")
                        .kind(),
                    GenerationRootErrorKind::Io
                );
            }

            for target in [
                TestBoundary::BeforePreopenedQualification,
                TestBoundary::AfterPreopenedQualification,
                TestBoundary::BeforeFinalRouteStat,
                TestBoundary::AfterFinalRouteStat,
            ] {
                let root_path = fixture_root("preopened-boundary");
                let artifact_path = private_file(&root_path, "artifact", b"sealed");
                let root =
                    QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
                let _guard = install_test_hook(move |boundary| {
                    if boundary == target {
                        return Err(injected(GenerationRootStage::OpenRegularFile));
                    }
                    Ok(())
                });
                assert_eq!(
                    root.admit_preopened_file(
                        &confined("artifact"),
                        preopened_immutable(&artifact_path),
                        immutable_expectation(b"sealed"),
                    )
                    .expect_err("injected preopened qualification boundary must fail")
                    .kind(),
                    GenerationRootErrorKind::Io
                );
            }

            for target in [TestBoundary::BeforeFileSync, TestBoundary::AfterFileSync] {
                let root_path = fixture_root("file-fullsync-failure");
                let artifact_path = private_file(&root_path, "artifact", b"barrier");
                let root =
                    QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
                let admitted = root
                    .admit_preopened_file(
                        &confined("artifact"),
                        preopened_immutable(&artifact_path),
                        immutable_expectation(b"barrier"),
                    )
                    .expect("empty-ACL immutable APFS file should qualify");
                let calls = Arc::new(Mutex::new(Vec::new()));
                let hook_calls = Arc::clone(&calls);
                let _guard = install_test_hook(move |boundary| {
                    if matches!(
                        boundary,
                        TestBoundary::BeforeFileSync | TestBoundary::AfterFileSync
                    ) {
                        hook_calls
                            .lock()
                            .expect("hook calls should lock")
                            .push(boundary);
                    }
                    if boundary == target {
                        return Err(GenerationRootError::new(
                            GenerationRootErrorKind::DurabilityUnavailable,
                            GenerationRootStage::SyncRegularFile,
                        ));
                    }
                    Ok(())
                });
                assert_eq!(
                    admitted
                        .sync_durable()
                        .expect_err("required file F_FULLFSYNC boundary failure must propagate")
                        .kind(),
                    GenerationRootErrorKind::DurabilityUnavailable
                );
                let expected = if target == TestBoundary::BeforeFileSync {
                    &[TestBoundary::BeforeFileSync][..]
                } else {
                    &[TestBoundary::BeforeFileSync, TestBoundary::AfterFileSync][..]
                };
                assert_eq!(
                    calls.lock().expect("hook calls should lock").as_slice(),
                    expected,
                    "file F_FULLFSYNC failure must not retry or fall back to a weaker barrier"
                );
            }

            for target in [
                TestBoundary::BeforeDirectorySync,
                TestBoundary::AfterDirectorySync,
            ] {
                let root_path = fixture_root("directory-fullsync-failure");
                let root =
                    QualifiedGenerationRoot::admit(&root_path).expect("local writable APFS root");
                let calls = Arc::new(Mutex::new(Vec::new()));
                let hook_calls = Arc::clone(&calls);
                let _guard = install_test_hook(move |boundary| {
                    if matches!(
                        boundary,
                        TestBoundary::BeforeDirectorySync | TestBoundary::AfterDirectorySync
                    ) {
                        hook_calls
                            .lock()
                            .expect("hook calls should lock")
                            .push(boundary);
                    }
                    if boundary == target {
                        return Err(GenerationRootError::new(
                            GenerationRootErrorKind::DurabilityUnavailable,
                            GenerationRootStage::SyncDirectory,
                        ));
                    }
                    Ok(())
                });
                assert_eq!(
                    root.sync_directory_durable()
                        .expect_err(
                            "required directory F_FULLFSYNC boundary failure must propagate"
                        )
                        .kind(),
                    GenerationRootErrorKind::DurabilityUnavailable
                );
                let expected = if target == TestBoundary::BeforeDirectorySync {
                    &[TestBoundary::BeforeDirectorySync][..]
                } else {
                    &[
                        TestBoundary::BeforeDirectorySync,
                        TestBoundary::AfterDirectorySync,
                    ][..]
                };
                assert_eq!(
                    calls.lock().expect("hook calls should lock").as_slice(),
                    expected,
                    "directory F_FULLFSYNC failure must not retry or fall back to a weaker barrier"
                );
            }
        }

        #[test]
        #[ignore = "physical M4 mount matrix requires explicit host paths"]
        fn physical_m4_external_noowners_and_network_mounts_fail_before_mutation() {
            let external = std::env::var_os("FRANKENSEARCH_M4_EXTERNAL_NOOWNERS_ROOT")
                .expect("set FRANKENSEARCH_M4_EXTERNAL_NOOWNERS_ROOT for the physical receipt");
            let network = std::env::var_os("FRANKENSEARCH_M4_NETWORK_ROOT")
                .expect("set FRANKENSEARCH_M4_NETWORK_ROOT for the physical receipt");

            let external_error = QualifiedGenerationRoot::admit(Path::new(&external))
                .expect_err("APFS with ownership disabled must fail qualification");
            assert!(matches!(
                external_error.kind(),
                GenerationRootErrorKind::ReadOnlyFilesystem
                    | GenerationRootErrorKind::UnsupportedFilesystem
            ));
            assert_eq!(
                QualifiedGenerationRoot::admit(Path::new(&network))
                    .expect_err("network filesystem must fail qualification")
                    .kind(),
                GenerationRootErrorKind::UnsupportedFilesystem
            );
        }

        #[test]
        #[ignore = "physical M4 case-sensitive and case-insensitive APFS bases are explicit"]
        fn physical_m4_case_sensitive_and_insensitive_apfs_both_require_exact_bytes() {
            let insensitive_base = std::env::var_os("FRANKENSEARCH_M4_CASE_INSENSITIVE_APFS_BASE")
                .expect("set the case-insensitive APFS base for the physical receipt");
            let sensitive_base = std::env::var_os("FRANKENSEARCH_M4_CASE_SENSITIVE_APFS_BASE")
                .expect("set the case-sensitive APFS base for the physical receipt");

            for (base, expected_sensitive, label) in [
                (insensitive_base, false, "case-insensitive"),
                (sensitive_base, true, "case-sensitive"),
            ] {
                let root_path = fixture_root_under(Path::new(&base), label);
                assert_eq!(
                    observe_case_sensitive(&root_path),
                    expected_sensitive,
                    "fixture volume sensitivity must match its declared physical lane"
                );
                let artifact_path = private_file(&root_path, "CaseArtifact", b"case");
                let root = QualifiedGenerationRoot::admit(&root_path)
                    .expect("local ownership-aware APFS fixture should qualify");
                root.admit_preopened_file(
                    &confined("CaseArtifact"),
                    preopened_immutable(&artifact_path),
                    immutable_expectation(b"case"),
                )
                .expect("the exact-case route must qualify on each APFS personality");
                assert_eq!(
                    root.admit_preopened_file(
                        &confined("caseartifact"),
                        preopened_immutable(&artifact_path),
                        immutable_expectation(b"case"),
                    )
                    .expect_err("byte-inexact spelling must fail on every APFS personality")
                    .kind(),
                    GenerationRootErrorKind::ObjectChanged
                );
            }
        }
    }
}